code_tokens
stringlengths
60
3.94k
label
int64
0
1
doc
stringlengths
16
98
docstring_tokens
stringlengths
0
1.41k
idx
stringlengths
13
17
code
stringlengths
87
6.4k
def __init__ ( self , encoding = 'utf-8' ) : super ( StdinInputReader , self ) . __init__ ( sys . stdin , encoding = encoding )
1
python stdin to self
Initializes an stdin input reader .
cosqa-train-14100
def __init__(self, encoding='utf-8'): """Initializes an stdin input reader. Args: encoding (Optional[str]): input encoding. """ super(StdinInputReader, self).__init__(sys.stdin, encoding=encoding)
def fix_line_breaks ( s ) : l = s . splitlines ( ) x = [ i . strip ( ) for i in l ] x = [ i for i in x if i ] # remove blank lines return "\n" . join ( x )
0
how to sstrip \r\n from list in python 3
Convert \ r \ n and \ r to \ n chars . Strip any leading or trailing whitespace on each line . Remove blank lines .
cosqa-train-14101
def fix_line_breaks(s): """ Convert \r\n and \r to \n chars. Strip any leading or trailing whitespace on each line. Remove blank lines. """ l = s.splitlines() x = [i.strip() for i in l] x = [i for i in x if i] # remove blank lines return "\n".join(x)
def printOut ( value , end = '\n' ) : sys . stdout . write ( value ) sys . stdout . write ( end ) sys . stdout . flush ( )
1
python stdout new line
This function prints the given String immediately and flushes the output .
cosqa-train-14102
def printOut(value, end='\n'): """ This function prints the given String immediately and flushes the output. """ sys.stdout.write(value) sys.stdout.write(end) sys.stdout.flush()
def go_to_new_line ( self ) : self . stdkey_end ( False , False ) self . insert_text ( self . get_line_separator ( ) )
1
how to start a new line in python gui
Go to the end of the current line and create a new line
cosqa-train-14103
def go_to_new_line(self): """Go to the end of the current line and create a new line""" self.stdkey_end(False, False) self.insert_text(self.get_line_separator())
def stop ( self , timeout = None ) : self . stopping = True for process in list ( self . processes ) : self . stop_process ( process , timeout = timeout )
1
python stop process multiprocessing
Initiates a graceful stop of the processes
cosqa-train-14104
def stop(self, timeout=None): """ Initiates a graceful stop of the processes """ self.stopping = True for process in list(self.processes): self.stop_process(process, timeout=timeout)
def is_static ( * p ) : return all ( is_CONST ( x ) or is_number ( x ) or is_const ( x ) for x in p )
1
how to static variabl in python
A static value ( does not change at runtime ) which is known at compile time
cosqa-train-14105
def is_static(*p): """ A static value (does not change at runtime) which is known at compile time """ return all(is_CONST(x) or is_number(x) or is_const(x) for x in p)
def to_list ( self ) : return [ [ int ( self . table . cell_values [ 0 ] [ 1 ] ) , int ( self . table . cell_values [ 0 ] [ 2 ] ) ] , [ int ( self . table . cell_values [ 1 ] [ 1 ] ) , int ( self . table . cell_values [ 1 ] [ 2 ] ) ] ]
1
python store array as a list
Convert this confusion matrix into a 2x2 plain list of values .
cosqa-train-14106
def to_list(self): """Convert this confusion matrix into a 2x2 plain list of values.""" return [[int(self.table.cell_values[0][1]), int(self.table.cell_values[0][2])], [int(self.table.cell_values[1][1]), int(self.table.cell_values[1][2])]]
def stop ( self ) : if self . _progressing : self . _progressing = False self . _thread . join ( )
1
how to stop a runaway thread in python
Stop the progress bar .
cosqa-train-14107
def stop(self): """Stop the progress bar.""" if self._progressing: self._progressing = False self._thread.join()
def getFunction ( self ) : return functionFactory ( self . code , self . name , self . defaults , self . globals , self . imports , )
0
python store function in variable
Called by remote workers . Useful to populate main module globals () for interactive shells . Retrieves the serialized function .
cosqa-train-14108
def getFunction(self): """Called by remote workers. Useful to populate main module globals() for interactive shells. Retrieves the serialized function.""" return functionFactory( self.code, self.name, self.defaults, self.globals, self.imports, )
def do_quit ( self , arg ) : for name , fh in self . _backup : setattr ( sys , name , fh ) self . console . writeline ( '*** Aborting program ***\n' ) self . console . flush ( ) self . console . close ( ) WebPdb . active_instance = None return Pdb . do_quit ( self , arg )
1
how to stop pdb python
quit || exit || q Stop and quit the current debugging session
cosqa-train-14109
def do_quit(self, arg): """ quit || exit || q Stop and quit the current debugging session """ for name, fh in self._backup: setattr(sys, name, fh) self.console.writeline('*** Aborting program ***\n') self.console.flush() self.console.close() WebPdb.active_instance = None return Pdb.do_quit(self, arg)
def bytes_to_c_array ( data ) : chars = [ "'{}'" . format ( encode_escape ( i ) ) for i in decode_escape ( data ) ] return ', ' . join ( chars ) + ', 0'
1
python str to c++ char array
Make a C array using the given string .
cosqa-train-14110
def bytes_to_c_array(data): """ Make a C array using the given string. """ chars = [ "'{}'".format(encode_escape(i)) for i in decode_escape(data) ] return ', '.join(chars) + ', 0'
def on_error ( e ) : # pragma: no cover exname = { 'RuntimeError' : 'Runtime error' , 'Value Error' : 'Value error' } sys . stderr . write ( '{}: {}\n' . format ( exname [ e . __class__ . __name__ ] , str ( e ) ) ) sys . stderr . write ( 'See file slam_error.log for additional details.\n' ) sys . exit ( 1 )
1
how to store python error log
Error handler
cosqa-train-14111
def on_error(e): # pragma: no cover """Error handler RuntimeError or ValueError exceptions raised by commands will be handled by this function. """ exname = {'RuntimeError': 'Runtime error', 'Value Error': 'Value error'} sys.stderr.write('{}: {}\n'.format(exname[e.__class__.__name__], str(e))) sys.stderr.write('See file slam_error.log for additional details.\n') sys.exit(1)
def get_gzipped_contents ( input_file ) : zbuf = StringIO ( ) zfile = GzipFile ( mode = "wb" , compresslevel = 6 , fileobj = zbuf ) zfile . write ( input_file . read ( ) ) zfile . close ( ) return ContentFile ( zbuf . getvalue ( ) )
1
python stream gzip file
Returns a gzipped version of a previously opened file s buffer .
cosqa-train-14112
def get_gzipped_contents(input_file): """ Returns a gzipped version of a previously opened file's buffer. """ zbuf = StringIO() zfile = GzipFile(mode="wb", compresslevel=6, fileobj=zbuf) zfile.write(input_file.read()) zfile.close() return ContentFile(zbuf.getvalue())
def __normalize_list ( self , msg ) : if isinstance ( msg , list ) : msg = "" . join ( msg ) return list ( map ( lambda x : x . strip ( ) , msg . split ( "," ) ) )
0
how to strip alist of comma and bracket python
Split message to list by commas and trim whitespace .
cosqa-train-14113
def __normalize_list(self, msg): """Split message to list by commas and trim whitespace.""" if isinstance(msg, list): msg = "".join(msg) return list(map(lambda x: x.strip(), msg.split(",")))
def list_formatter ( handler , item , value ) : return u', ' . join ( str ( v ) for v in value )
1
python string formatting in list
Format list .
cosqa-train-14114
def list_formatter(handler, item, value): """Format list.""" return u', '.join(str(v) for v in value)
def splitBy ( data , num ) : return [ data [ i : i + num ] for i in range ( 0 , len ( data ) , num ) ]
0
how to take certain range of elements in list python
Turn a list to list of list
cosqa-train-14115
def splitBy(data, num): """ Turn a list to list of list """ return [data[i:i + num] for i in range(0, len(data), num)]
def add_suffix ( fullname , suffix ) : name , ext = os . path . splitext ( fullname ) return name + '_' + suffix + ext
0
python string function to add suffix
Add suffix to a full file name
cosqa-train-14116
def add_suffix(fullname, suffix): """ Add suffix to a full file name""" name, ext = os.path.splitext(fullname) return name + '_' + suffix + ext
def itemlist ( item , sep , suppress_trailing = True ) : return condense ( item + ZeroOrMore ( addspace ( sep + item ) ) + Optional ( sep . suppress ( ) if suppress_trailing else sep ) )
1
how to take list as input in python seperated with spaces
Create a list of items seperated by seps .
cosqa-train-14117
def itemlist(item, sep, suppress_trailing=True): """Create a list of items seperated by seps.""" return condense(item + ZeroOrMore(addspace(sep + item)) + Optional(sep.suppress() if suppress_trailing else sep))
def PythonPercentFormat ( format_str ) : if format_str . startswith ( 'printf ' ) : fmt = format_str [ len ( 'printf ' ) : ] return lambda value : fmt % value else : return None
1
python string percent s %s
Use Python % format strings as template format specifiers .
cosqa-train-14118
def PythonPercentFormat(format_str): """Use Python % format strings as template format specifiers.""" if format_str.startswith('printf '): fmt = format_str[len('printf '):] return lambda value: fmt % value else: return None
def transpose ( table ) : t = [ ] for i in range ( 0 , len ( table [ 0 ] ) ) : t . append ( [ row [ i ] for row in table ] ) return t
1
how to take transpose of a matrix in python
transpose matrix
cosqa-train-14119
def transpose(table): """ transpose matrix """ t = [] for i in range(0, len(table[0])): t.append([row[i] for row in table]) return t
def subat ( orig , index , replace ) : return "" . join ( [ ( orig [ x ] if x != index else replace ) for x in range ( len ( orig ) ) ] )
1
python string replace based on position
Substitutes the replacement string / character at the given index in the given string returns the modified string .
cosqa-train-14120
def subat(orig, index, replace): """Substitutes the replacement string/character at the given index in the given string, returns the modified string. **Examples**: :: auxly.stringy.subat("bit", 2, "n") """ return "".join([(orig[x] if x != index else replace) for x in range(len(orig))])
def require_root ( fn ) : @ wraps ( fn ) def xex ( * args , * * kwargs ) : assert os . geteuid ( ) == 0 , "You have to be root to run function '%s'." % fn . __name__ return fn ( * args , * * kwargs ) return xex
1
how to tell if a user is running as root python
Decorator to make sure that user is root .
cosqa-train-14121
def require_root(fn): """ Decorator to make sure, that user is root. """ @wraps(fn) def xex(*args, **kwargs): assert os.geteuid() == 0, \ "You have to be root to run function '%s'." % fn.__name__ return fn(*args, **kwargs) return xex
def fsliceafter ( astr , sub ) : findex = astr . find ( sub ) return astr [ findex + len ( sub ) : ]
1
python string slice special position
Return the slice after at sub in string astr
cosqa-train-14122
def fsliceafter(astr, sub): """Return the slice after at sub in string astr""" findex = astr.find(sub) return astr[findex + len(sub):]
def cat_acc ( y_true , y_pred ) : return np . mean ( y_true . argmax ( axis = 1 ) == y_pred . argmax ( axis = 1 ) )
1
how to test a prediction model accuracy python
Categorical accuracy
cosqa-train-14123
def cat_acc(y_true, y_pred): """Categorical accuracy """ return np.mean(y_true.argmax(axis=1) == y_pred.argmax(axis=1))
def comma_delimited_to_list ( list_param ) : if isinstance ( list_param , list ) : return list_param if isinstance ( list_param , str ) : return list_param . split ( ',' ) else : return [ ]
1
python string to list comma delimited
Convert comma - delimited list / string into a list of strings
cosqa-train-14124
def comma_delimited_to_list(list_param): """Convert comma-delimited list / string into a list of strings :param list_param: Comma-delimited string :type list_param: str | unicode :return: A list of strings :rtype: list """ if isinstance(list_param, list): return list_param if isinstance(list_param, str): return list_param.split(',') else: return []
def string_to_list ( string , sep = "," , filter_empty = False ) : return [ value . strip ( ) for value in string . split ( sep ) if ( not filter_empty or value ) ]
1
python string to list exclude empty
Transforma una string con elementos separados por sep en una lista .
cosqa-train-14125
def string_to_list(string, sep=",", filter_empty=False): """Transforma una string con elementos separados por `sep` en una lista.""" return [value.strip() for value in string.split(sep) if (not filter_empty or value)]
def is_integer ( dtype ) : dtype = tf . as_dtype ( dtype ) if hasattr ( dtype , 'is_integer' ) : return dtype . is_integer return np . issubdtype ( np . dtype ( dtype ) , np . integer )
1
how to test if a symbol is an int python
Returns whether this is a ( non - quantized ) integer type .
cosqa-train-14126
def is_integer(dtype): """Returns whether this is a (non-quantized) integer type.""" dtype = tf.as_dtype(dtype) if hasattr(dtype, 'is_integer'): return dtype.is_integer return np.issubdtype(np.dtype(dtype), np.integer)
def get_line_ending ( line ) : non_whitespace_index = len ( line . rstrip ( ) ) - len ( line ) if not non_whitespace_index : return '' else : return line [ non_whitespace_index : ]
1
python strip , midline
Return line ending .
cosqa-train-14127
def get_line_ending(line): """Return line ending.""" non_whitespace_index = len(line.rstrip()) - len(line) if not non_whitespace_index: return '' else: return line[non_whitespace_index:]
def find_first_number ( ll ) : for nr , entry in enumerate ( ll ) : try : float ( entry ) except ( ValueError , TypeError ) as e : pass else : return nr return None
1
how to test the first digit of a float number in python
Returns nr of first entry parseable to float in ll None otherwise
cosqa-train-14128
def find_first_number(ll): """ Returns nr of first entry parseable to float in ll, None otherwise""" for nr, entry in enumerate(ll): try: float(entry) except (ValueError, TypeError) as e: pass else: return nr return None
def execute_in_background ( self ) : # http://stackoverflow.com/questions/1605520 args = shlex . split ( self . cmd ) p = Popen ( args ) return p . pid
1
python subprocess call in background
Executes a ( shell ) command in the background
cosqa-train-14129
def execute_in_background(self): """Executes a (shell) command in the background :return: the process' pid """ # http://stackoverflow.com/questions/1605520 args = shlex.split(self.cmd) p = Popen(args) return p.pid
def camel_to_underscore ( string ) : string = FIRST_CAP_RE . sub ( r'\1_\2' , string ) return ALL_CAP_RE . sub ( r'\1_\2' , string ) . lower ( )
1
how to transform letters to underscores in python
Convert camelcase to lowercase and underscore .
cosqa-train-14130
def camel_to_underscore(string): """Convert camelcase to lowercase and underscore. Recipe from http://stackoverflow.com/a/1176023 Args: string (str): The string to convert. Returns: str: The converted string. """ string = FIRST_CAP_RE.sub(r'\1_\2', string) return ALL_CAP_RE.sub(r'\1_\2', string).lower()
def _finish ( self ) : if self . _process . returncode is None : self . _process . stdin . flush ( ) self . _process . stdin . close ( ) self . _process . wait ( ) self . closed = True
1
python subprocess close stdin
Closes and waits for subprocess to exit .
cosqa-train-14131
def _finish(self): """ Closes and waits for subprocess to exit. """ if self._process.returncode is None: self._process.stdin.flush() self._process.stdin.close() self._process.wait() self.closed = True
def _trim ( self , somestr ) : tmp = RE_LSPACES . sub ( "" , somestr ) tmp = RE_TSPACES . sub ( "" , tmp ) return str ( tmp )
1
how to trim a string in python
Trim left - right given string
cosqa-train-14132
def _trim(self, somestr): """ Trim left-right given string """ tmp = RE_LSPACES.sub("", somestr) tmp = RE_TSPACES.sub("", tmp) return str(tmp)
def correspond ( text ) : subproc . stdin . write ( text ) subproc . stdin . flush ( ) return drain ( )
1
python subprocess stdin flush
Communicate with the child process without closing stdin .
cosqa-train-14133
def correspond(text): """Communicate with the child process without closing stdin.""" subproc.stdin.write(text) subproc.stdin.flush() return drain()
def bytes_to_bits ( bytes_ ) : res = [ ] for x in bytes_ : if not isinstance ( x , int ) : x = ord ( x ) res += byte_to_bits ( x ) return res
0
how to turn a byte array into bits python
Convert bytes to a list of bits
cosqa-train-14134
def bytes_to_bits(bytes_): """Convert bytes to a list of bits """ res = [] for x in bytes_: if not isinstance(x, int): x = ord(x) res += byte_to_bits(x) return res
def query_sum ( queryset , field ) : return queryset . aggregate ( s = models . functions . Coalesce ( models . Sum ( field ) , 0 ) ) [ 's' ]
1
python sum values from field
Let the DBMS perform a sum on a queryset
cosqa-train-14135
def query_sum(queryset, field): """ Let the DBMS perform a sum on a queryset """ return queryset.aggregate(s=models.functions.Coalesce(models.Sum(field), 0))['s']
def _str_to_list ( s ) : _list = s . split ( "," ) return list ( map ( lambda i : i . lstrip ( ) , _list ) )
0
how to turn a string into a list by blank space python
Converts a comma separated string to a list
cosqa-train-14136
def _str_to_list(s): """Converts a comma separated string to a list""" _list = s.split(",") return list(map(lambda i: i.lstrip(), _list))
def Sum ( a , axis , keep_dims ) : return np . sum ( a , axis = axis if not isinstance ( axis , np . ndarray ) else tuple ( axis ) , keepdims = keep_dims ) ,
0
python suma an array axis
Sum reduction op .
cosqa-train-14137
def Sum(a, axis, keep_dims): """ Sum reduction op. """ return np.sum(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis), keepdims=keep_dims),
def from_series ( cls , series ) : # TODO: add a 'name' parameter name = series . name df = pd . DataFrame ( { name : series } ) ds = Dataset . from_dataframe ( df ) return ds [ name ]
1
how to turn series into 2d array python
Convert a pandas . Series into an xarray . DataArray .
cosqa-train-14138
def from_series(cls, series): """Convert a pandas.Series into an xarray.DataArray. If the series's index is a MultiIndex, it will be expanded into a tensor product of one-dimensional coordinates (filling in missing values with NaN). Thus this operation should be the inverse of the `to_series` method. """ # TODO: add a 'name' parameter name = series.name df = pd.DataFrame({name: series}) ds = Dataset.from_dataframe(df) return ds[name]
def get_last_filled_cell ( self , table = None ) : maxrow = 0 maxcol = 0 for row , col , tab in self . dict_grid : if table is None or tab == table : maxrow = max ( row , maxrow ) maxcol = max ( col , maxcol ) return maxrow , maxcol , table
1
python table highest number in columb
Returns key for the bottommost rightmost cell with content
cosqa-train-14139
def get_last_filled_cell(self, table=None): """Returns key for the bottommost rightmost cell with content Parameters ---------- table: Integer, defaults to None \tLimit search to this table """ maxrow = 0 maxcol = 0 for row, col, tab in self.dict_grid: if table is None or tab == table: maxrow = max(row, maxrow) maxcol = max(col, maxcol) return maxrow, maxcol, table
def to_list ( var ) : if var is None : return [ ] if isinstance ( var , str ) : var = var . split ( '\n' ) elif not isinstance ( var , list ) : try : var = list ( var ) except TypeError : raise ValueError ( "{} cannot be converted to the list." . format ( var ) ) return var
1
how to turn string into a list in python
Checks if given value is a list tries to convert if it is not .
cosqa-train-14140
def to_list(var): """Checks if given value is a list, tries to convert, if it is not.""" if var is None: return [] if isinstance(var, str): var = var.split('\n') elif not isinstance(var, list): try: var = list(var) except TypeError: raise ValueError("{} cannot be converted to the list.".format(var)) return var
def adapter ( data , headers , * * kwargs ) : keys = ( 'sep_title' , 'sep_character' , 'sep_length' ) return vertical_table ( data , headers , * * filter_dict_by_key ( kwargs , keys ) )
1
python tabulate without wrapping
Wrap vertical table in a function for TabularOutputFormatter .
cosqa-train-14141
def adapter(data, headers, **kwargs): """Wrap vertical table in a function for TabularOutputFormatter.""" keys = ('sep_title', 'sep_character', 'sep_length') return vertical_table(data, headers, **filter_dict_by_key(kwargs, keys))
def coerce ( self , value ) : if isinstance ( value , dict ) : value = [ value ] if not isiterable_notstring ( value ) : value = [ value ] return [ coerce_single_instance ( self . lookup_field , v ) for v in value ]
0
how to typecast a list of strings python
Convert from whatever is given to a list of scalars for the lookup_field .
cosqa-train-14142
def coerce(self, value): """Convert from whatever is given to a list of scalars for the lookup_field.""" if isinstance(value, dict): value = [value] if not isiterable_notstring(value): value = [value] return [coerce_single_instance(self.lookup_field, v) for v in value]
def _format_title_string ( self , title_string ) : return self . _title_string_format_text_tag ( title_string . replace ( self . icy_tokkens [ 0 ] , self . icy_title_prefix ) )
1
python take a string after the title
format mpv s title
cosqa-train-14143
def _format_title_string(self, title_string): """ format mpv's title """ return self._title_string_format_text_tag(title_string.replace(self.icy_tokkens[0], self.icy_title_prefix))
def load ( self , filename = 'classifier.dump' ) : ifile = open ( filename , 'r+' ) self . classifier = pickle . load ( ifile ) ifile . close ( )
1
how to un pickle a file python
Unpickles the classifier used
cosqa-train-14144
def load(self, filename='classifier.dump'): """ Unpickles the classifier used """ ifile = open(filename, 'r+') self.classifier = pickle.load(ifile) ifile.close()
def conv1x1 ( in_planes , out_planes , stride = 1 ) : return nn . Conv2d ( in_planes , out_planes , kernel_size = 1 , stride = stride , bias = False )
1
python tensorflow custom convolution pooling
1x1 convolution
cosqa-train-14145
def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution""" return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
def get_shape ( img ) : if hasattr ( img , 'shape' ) : shape = img . shape else : shape = img . get_data ( ) . shape return shape
1
how to uniquely identify shape in an image using python
Return the shape of img .
cosqa-train-14146
def get_shape(img): """Return the shape of img. Paramerers ----------- img: Returns ------- shape: tuple """ if hasattr(img, 'shape'): shape = img.shape else: shape = img.get_data().shape return shape
def run_std_server ( self ) : config = tf . estimator . RunConfig ( ) server = tf . train . Server ( config . cluster_spec , job_name = config . task_type , task_index = config . task_id , protocol = config . protocol ) server . join ( )
0
python tensorflow multithread validate
Starts a TensorFlow server and joins the serving thread .
cosqa-train-14147
def run_std_server(self): """Starts a TensorFlow server and joins the serving thread. Typically used for parameter servers. Raises: ValueError: if not enough information is available in the estimator's config to create a server. """ config = tf.estimator.RunConfig() server = tf.train.Server( config.cluster_spec, job_name=config.task_type, task_index=config.task_id, protocol=config.protocol) server.join()
def convert_array ( array ) : out = io . BytesIO ( array ) out . seek ( 0 ) return np . load ( out )
1
how to unpack python array
Converts an ARRAY string stored in the database back into a Numpy array .
cosqa-train-14148
def convert_array(array): """ Converts an ARRAY string stored in the database back into a Numpy array. Parameters ---------- array: ARRAY The array object to be converted back into a Numpy array. Returns ------- array The converted Numpy array. """ out = io.BytesIO(array) out.seek(0) return np.load(out)
def requests_post ( url , data = None , json = None , * * kwargs ) : return requests_request ( 'post' , url , data = data , json = json , * * kwargs )
1
python tesing mock requests
Requests - mock requests . post wrapper .
cosqa-train-14149
def requests_post(url, data=None, json=None, **kwargs): """Requests-mock requests.post wrapper.""" return requests_request('post', url, data=data, json=json, **kwargs)
def unpickle_file ( picklefile , * * kwargs ) : with open ( picklefile , 'rb' ) as f : return pickle . load ( f , * * kwargs )
1
how to unpickle a file python
Helper function to unpickle data from picklefile .
cosqa-train-14150
def unpickle_file(picklefile, **kwargs): """Helper function to unpickle data from `picklefile`.""" with open(picklefile, 'rb') as f: return pickle.load(f, **kwargs)
def is_timestamp ( instance ) : if not isinstance ( instance , ( int , str ) ) : return True return datetime . fromtimestamp ( int ( instance ) )
1
python test a datetime object
Validates data is a timestamp
cosqa-train-14151
def is_timestamp(instance): """Validates data is a timestamp""" if not isinstance(instance, (int, str)): return True return datetime.fromtimestamp(int(instance))
def filesavebox ( msg = None , title = None , argInitialFile = None ) : return psidialogs . ask_file ( message = msg , title = title , default = argInitialFile , save = True )
1
how to use a dialog box to save a file in python
Original doc : A file to get the name of a file to save . Returns the name of a file or None if user chose to cancel .
cosqa-train-14152
def filesavebox(msg=None, title=None, argInitialFile=None): """Original doc: A file to get the name of a file to save. Returns the name of a file, or None if user chose to cancel. if argInitialFile contains a valid filename, the dialog will be positioned at that file when it appears. """ return psidialogs.ask_file(message=msg, title=title, default=argInitialFile, save=True)
def test ( ) : command = 'nosetests --with-coverage --cover-package=pwnurl' status = subprocess . call ( shlex . split ( command ) ) sys . exit ( status )
1
python test cases to run in jenkins
Run all Tests [ nose ]
cosqa-train-14153
def test(): """ Run all Tests [nose] """ command = 'nosetests --with-coverage --cover-package=pwnurl' status = subprocess.call(shlex.split(command)) sys.exit(status)
def json_iter ( path ) : with open ( path , 'r' ) as f : for line in f . readlines ( ) : yield json . loads ( line )
1
how to use chain with a json file python
iterator for JSON - per - line in a file pattern
cosqa-train-14154
def json_iter (path): """ iterator for JSON-per-line in a file pattern """ with open(path, 'r') as f: for line in f.readlines(): yield json.loads(line)
def is_executable ( path ) : return os . path . isfile ( path ) and os . access ( path , os . X_OK )
1
python test if a file is executable
Returns whether a path names an existing executable file .
cosqa-train-14155
def is_executable(path): """Returns whether a path names an existing executable file.""" return os.path.isfile(path) and os.access(path, os.X_OK)
def help_for_command ( command ) : help_text = pydoc . text . document ( command ) # remove backspaces return re . subn ( '.\\x08' , '' , help_text ) [ 0 ]
1
how to use help in cmd to get docstring in python
Get the help text ( signature + docstring ) for a command ( function ) .
cosqa-train-14156
def help_for_command(command): """Get the help text (signature + docstring) for a command (function).""" help_text = pydoc.text.document(command) # remove backspaces return re.subn('.\\x08', '', help_text)[0]
def column_exists ( cr , table , column ) : cr . execute ( 'SELECT count(attname) FROM pg_attribute ' 'WHERE attrelid = ' '( SELECT oid FROM pg_class WHERE relname = %s ) ' 'AND attname = %s' , ( table , column ) ) return cr . fetchone ( ) [ 0 ] == 1
1
python test if column exists
Check whether a certain column exists
cosqa-train-14157
def column_exists(cr, table, column): """ Check whether a certain column exists """ cr.execute( 'SELECT count(attname) FROM pg_attribute ' 'WHERE attrelid = ' '( SELECT oid FROM pg_class WHERE relname = %s ) ' 'AND attname = %s', (table, column)) return cr.fetchone()[0] == 1
def list_files ( directory ) : return [ f for f in pathlib . Path ( directory ) . iterdir ( ) if f . is_file ( ) and not f . name . startswith ( '.' ) ]
1
how to use python to list the files in a folder
Returns all files in a given directory
cosqa-train-14158
def list_files(directory): """Returns all files in a given directory """ return [f for f in pathlib.Path(directory).iterdir() if f.is_file() and not f.name.startswith('.')]
def is_power_of_2 ( num ) : log = math . log2 ( num ) return int ( log ) == float ( log )
1
python test if power of 2
Return whether num is a power of two
cosqa-train-14159
def is_power_of_2(num): """Return whether `num` is a power of two""" log = math.log2(num) return int(log) == float(log)
def _load_texture ( file_name , resolver ) : file_data = resolver . get ( file_name ) image = PIL . Image . open ( util . wrap_as_stream ( file_data ) ) return image
1
how to use python to load an image
Load a texture from a file into a PIL image .
cosqa-train-14160
def _load_texture(file_name, resolver): """ Load a texture from a file into a PIL image. """ file_data = resolver.get(file_name) image = PIL.Image.open(util.wrap_as_stream(file_data)) return image
def is_connected ( self ) : try : return self . socket is not None and self . socket . getsockname ( ) [ 1 ] != 0 and BaseTransport . is_connected ( self ) except socket . error : return False
1
python test if there's a connection
Return true if the socket managed by this connection is connected
cosqa-train-14161
def is_connected(self): """ Return true if the socket managed by this connection is connected :rtype: bool """ try: return self.socket is not None and self.socket.getsockname()[1] != 0 and BaseTransport.is_connected(self) except socket.error: return False
def fmt_subst ( regex , subst ) : return lambda text : re . sub ( regex , subst , text ) if text else text
1
how to use replace to replace many thing in string python
Replace regex with string .
cosqa-train-14162
def fmt_subst(regex, subst): """Replace regex with string.""" return lambda text: re.sub(regex, subst, text) if text else text
def is_array ( type_ ) : nake_type = remove_alias ( type_ ) nake_type = remove_reference ( nake_type ) nake_type = remove_cv ( nake_type ) return isinstance ( nake_type , cpptypes . array_t )
1
python test if value is ctypes array
returns True if type represents C ++ array type False otherwise
cosqa-train-14163
def is_array(type_): """returns True, if type represents C++ array type, False otherwise""" nake_type = remove_alias(type_) nake_type = remove_reference(nake_type) nake_type = remove_cv(nake_type) return isinstance(nake_type, cpptypes.array_t)
def setDictDefaults ( d , defaults ) : for key , val in defaults . items ( ) : d . setdefault ( key , val ) return d
1
how to use set default dictionary in python
Sets all defaults for the given dictionary to those contained in a second defaults dictionary . This convenience method calls :
cosqa-train-14164
def setDictDefaults (d, defaults): """Sets all defaults for the given dictionary to those contained in a second defaults dictionary. This convenience method calls: d.setdefault(key, value) for each key and value in the given defaults dictionary. """ for key, val in defaults.items(): d.setdefault(key, val) return d
def is_integer_array ( val ) : return is_np_array ( val ) and issubclass ( val . dtype . type , np . integer )
1
python test if var is array
Checks whether a variable is a numpy integer array .
cosqa-train-14165
def is_integer_array(val): """ Checks whether a variable is a numpy integer array. Parameters ---------- val The variable to check. Returns ------- bool True if the variable is a numpy integer array. Otherwise False. """ return is_np_array(val) and issubclass(val.dtype.type, np.integer)
def get_join_cols ( by_entry ) : left_cols = [ ] right_cols = [ ] for col in by_entry : if isinstance ( col , str ) : left_cols . append ( col ) right_cols . append ( col ) else : left_cols . append ( col [ 0 ] ) right_cols . append ( col [ 1 ] ) return left_cols , right_cols
1
how to use the join function python
helper function used for joins builds left and right join list for join function
cosqa-train-14166
def get_join_cols(by_entry): """ helper function used for joins builds left and right join list for join function """ left_cols = [] right_cols = [] for col in by_entry: if isinstance(col, str): left_cols.append(col) right_cols.append(col) else: left_cols.append(col[0]) right_cols.append(col[1]) return left_cols, right_cols
def colorize ( txt , fg = None , bg = None ) : setting = '' setting += _SET_FG . format ( fg ) if fg else '' setting += _SET_BG . format ( bg ) if bg else '' return setting + str ( txt ) + _STYLE_RESET
1
python text color and styling
Print escape codes to set the terminal color .
cosqa-train-14167
def colorize(txt, fg=None, bg=None): """ Print escape codes to set the terminal color. fg and bg are indices into the color palette for the foreground and background colors. """ setting = '' setting += _SET_FG.format(fg) if fg else '' setting += _SET_BG.format(bg) if bg else '' return setting + str(txt) + _STYLE_RESET
def step_impl06 ( context ) : store = context . SingleStore context . st_1 = store ( ) context . st_2 = store ( ) context . st_3 = store ( )
1
how to use variables for seperate unit tests python
Prepare test for singleton property .
cosqa-train-14168
def step_impl06(context): """Prepare test for singleton property. :param context: test context. """ store = context.SingleStore context.st_1 = store() context.st_2 = store() context.st_3 = store()
def to_snake_case ( text ) : s1 = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , text ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , s1 ) . lower ( )
1
python text to lower
Convert to snake case .
cosqa-train-14169
def to_snake_case(text): """Convert to snake case. :param str text: :rtype: str :return: """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
def import_public_rsa_key_from_file ( filename ) : with open ( filename , "rb" ) as key_file : public_key = serialization . load_pem_public_key ( key_file . read ( ) , backend = default_backend ( ) ) return public_key
1
how to view an rsa key in memory python
Read a public RSA key from a PEM file .
cosqa-train-14170
def import_public_rsa_key_from_file(filename): """ Read a public RSA key from a PEM file. :param filename: The name of the file :param passphrase: A pass phrase to use to unpack the PEM file. :return: A cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey instance """ with open(filename, "rb") as key_file: public_key = serialization.load_pem_public_key( key_file.read(), backend=default_backend()) return public_key
def last ( self ) : # End of file self . __file . seek ( 0 , 2 ) # Get the last struct data = self . get ( self . length - 1 ) return data
1
python the last line in a file
Get the last object in file .
cosqa-train-14171
def last(self): """Get the last object in file.""" # End of file self.__file.seek(0, 2) # Get the last struct data = self.get(self.length - 1) return data
def format_exception ( e ) : from . utils . printing import fill return '\n' . join ( fill ( line ) for line in traceback . format_exception_only ( type ( e ) , e ) )
1
how to view the traceback error in python
Returns a string containing the type and text of the exception .
cosqa-train-14172
def format_exception(e): """Returns a string containing the type and text of the exception. """ from .utils.printing import fill return '\n'.join(fill(line) for line in traceback.format_exception_only(type(e), e))
def join ( self ) : self . inputfeeder_thread . join ( ) self . pool . join ( ) self . resulttracker_thread . join ( ) self . failuretracker_thread . join ( )
1
python thread join it self
Note that the Executor must be close () d elsewhere or join () will never return .
cosqa-train-14173
def join(self): """Note that the Executor must be close()'d elsewhere, or join() will never return. """ self.inputfeeder_thread.join() self.pool.join() self.resulttracker_thread.join() self.failuretracker_thread.join()
def post_process ( self ) : self . image . putdata ( self . pixels ) self . image = self . image . transpose ( Image . ROTATE_90 )
1
how to warp one image into another python
Apply last 2D transforms
cosqa-train-14174
def post_process(self): """ Apply last 2D transforms""" self.image.putdata(self.pixels) self.image = self.image.transpose(Image.ROTATE_90)
def join ( self ) : self . inputfeeder_thread . join ( ) self . pool . join ( ) self . resulttracker_thread . join ( ) self . failuretracker_thread . join ( )
1
python threading not running concurrent join
Note that the Executor must be close () d elsewhere or join () will never return .
cosqa-train-14175
def join(self): """Note that the Executor must be close()'d elsewhere, or join() will never return. """ self.inputfeeder_thread.join() self.pool.join() self.resulttracker_thread.join() self.failuretracker_thread.join()
def getPrimeFactors ( n ) : lo = [ 1 ] n2 = n // 2 k = 2 for k in range ( 2 , n2 + 1 ) : if ( n // k ) * k == n : lo . append ( k ) return lo + [ n , ]
1
how to write a function in python that returns a list of prime numbers
Get all the prime factor of given integer
cosqa-train-14176
def getPrimeFactors(n): """ Get all the prime factor of given integer @param n integer @return list [1, ..., n] """ lo = [1] n2 = n // 2 k = 2 for k in range(2, n2 + 1): if (n // k)*k == n: lo.append(k) return lo + [n, ]
def Join ( self ) : for _ in range ( self . JOIN_TIMEOUT_DECISECONDS ) : if self . _queue . empty ( ) and not self . busy_threads : return time . sleep ( 0.1 ) raise ValueError ( "Timeout during Join() for threadpool %s." % self . name )
1
python threadpool dummy join
Waits until all outstanding tasks are completed .
cosqa-train-14177
def Join(self): """Waits until all outstanding tasks are completed.""" for _ in range(self.JOIN_TIMEOUT_DECISECONDS): if self._queue.empty() and not self.busy_threads: return time.sleep(0.1) raise ValueError("Timeout during Join() for threadpool %s." % self.name)
def _letter_map ( word ) : lmap = { } for letter in word : try : lmap [ letter ] += 1 except KeyError : lmap [ letter ] = 1 return lmap
0
how to write a function that counts letters of a string in python
Creates a map of letter use in a word .
cosqa-train-14178
def _letter_map(word): """Creates a map of letter use in a word. Args: word: a string to create a letter map from Returns: a dictionary of {letter: integer count of letter in word} """ lmap = {} for letter in word: try: lmap[letter] += 1 except KeyError: lmap[letter] = 1 return lmap
def utcfromtimestamp ( cls , timestamp ) : obj = datetime . datetime . utcfromtimestamp ( timestamp ) obj = pytz . utc . localize ( obj ) return cls ( obj )
1
python time struct from timestamp
Returns a datetime object of a given timestamp ( in UTC ) .
cosqa-train-14179
def utcfromtimestamp(cls, timestamp): """Returns a datetime object of a given timestamp (in UTC).""" obj = datetime.datetime.utcfromtimestamp(timestamp) obj = pytz.utc.localize(obj) return cls(obj)
def _screen ( self , s , newline = False ) : if self . verbose : if newline : print ( s ) else : print ( s , end = ' ' )
1
how to write a print without a space in python
Print something on screen when self . verbose == True
cosqa-train-14180
def _screen(self, s, newline=False): """Print something on screen when self.verbose == True""" if self.verbose: if newline: print(s) else: print(s, end=' ')
def seconds_to_time ( x ) : t = int ( x * 10 ** 6 ) ms = t % 10 ** 6 t = t // 10 ** 6 s = t % 60 t = t // 60 m = t % 60 t = t // 60 h = t return time ( h , m , s , ms )
1
python time to minutes
Convert a number of second into a time
cosqa-train-14181
def seconds_to_time(x): """Convert a number of second into a time""" t = int(x * 10**6) ms = t % 10**6 t = t // 10**6 s = t % 60 t = t // 60 m = t % 60 t = t // 60 h = t return time(h, m, s, ms)
def ratio_and_percentage ( current , total , time_remaining ) : return "{} / {} ({}% completed)" . format ( current , total , int ( current / total * 100 ) )
1
how to write code to calculate percentage in python
Returns the progress ratio and percentage .
cosqa-train-14182
def ratio_and_percentage(current, total, time_remaining): """Returns the progress ratio and percentage.""" return "{} / {} ({}% completed)".format(current, total, int(current / total * 100))
def fmt_duration ( secs ) : return ' ' . join ( fmt . human_duration ( secs , 0 , precision = 2 , short = True ) . strip ( ) . split ( ) )
0
python timedelta to readable
Format a duration in seconds .
cosqa-train-14183
def fmt_duration(secs): """Format a duration in seconds.""" return ' '.join(fmt.human_duration(secs, 0, precision=2, short=True).strip().split())
def _rotate ( n , x , y , rx , ry ) : if ry == 0 : if rx == 1 : x = n - 1 - x y = n - 1 - y return y , x return x , y
1
how to write code to rot13 in python
Rotate and flip a quadrant appropriately
cosqa-train-14184
def _rotate(n, x, y, rx, ry): """Rotate and flip a quadrant appropriately Based on the implementation here: https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503 """ if ry == 0: if rx == 1: x = n - 1 - x y = n - 1 - y return y, x return x, y
def add_datetime ( dataframe , timestamp_key = 'UNIXTIME' ) : def convert_data ( timestamp ) : return datetime . fromtimestamp ( float ( timestamp ) / 1e3 , UTC_TZ ) try : log . debug ( "Adding DATETIME column to the data" ) converted = dataframe [ timestamp_key ] . apply ( convert_data ) dataframe [ 'DATETIME' ] = converted except KeyError : log . warning ( "Could not add DATETIME column" )
1
python timestamp column change format
Add an additional DATETIME column with standar datetime format .
cosqa-train-14185
def add_datetime(dataframe, timestamp_key='UNIXTIME'): """Add an additional DATETIME column with standar datetime format. This currently manipulates the incoming DataFrame! """ def convert_data(timestamp): return datetime.fromtimestamp(float(timestamp) / 1e3, UTC_TZ) try: log.debug("Adding DATETIME column to the data") converted = dataframe[timestamp_key].apply(convert_data) dataframe['DATETIME'] = converted except KeyError: log.warning("Could not add DATETIME column")
def _make_sql_params ( self , kw ) : return [ '%s=?' % k for k in kw . keys ( ) ] for k , v in kw . iteritems ( ) : vals . append ( '%s=?' % k ) return vals
1
how to write sql queries with variables python
Make a list of strings to pass to an SQL statement from the dictionary kw with Python types
cosqa-train-14186
def _make_sql_params(self,kw): """Make a list of strings to pass to an SQL statement from the dictionary kw with Python types""" return ['%s=?' %k for k in kw.keys() ] for k,v in kw.iteritems(): vals.append('%s=?' %k) return vals
def session_to_epoch ( timestamp ) : utc_timetuple = datetime . strptime ( timestamp , SYNERGY_SESSION_PATTERN ) . replace ( tzinfo = None ) . utctimetuple ( ) return calendar . timegm ( utc_timetuple )
0
python timestamp with timezone to epoc
converts Synergy Timestamp for session to UTC zone seconds since epoch
cosqa-train-14187
def session_to_epoch(timestamp): """ converts Synergy Timestamp for session to UTC zone seconds since epoch """ utc_timetuple = datetime.strptime(timestamp, SYNERGY_SESSION_PATTERN).replace(tzinfo=None).utctimetuple() return calendar.timegm(utc_timetuple)
def extent ( self ) : return ( self . intervals [ 1 ] . pix1 - 0.5 , self . intervals [ 1 ] . pix2 - 0.5 , self . intervals [ 0 ] . pix1 - 0.5 , self . intervals [ 0 ] . pix2 - 0.5 , )
1
how to zoom in on a plot imshow python
Helper for matplotlib imshow
cosqa-train-14188
def extent(self): """Helper for matplotlib imshow""" return ( self.intervals[1].pix1 - 0.5, self.intervals[1].pix2 - 0.5, self.intervals[0].pix1 - 0.5, self.intervals[0].pix2 - 0.5, )
def current_offset ( local_tz = None ) : if local_tz is None : local_tz = DEFAULT_LOCAL_TZ dt = local_tz . localize ( datetime . now ( ) ) return dt . utcoffset ( )
1
python timezone name to offset
Returns current utcoffset for a timezone . Uses DEFAULT_LOCAL_TZ by default . That value can be changed at runtime using the func below .
cosqa-train-14189
def current_offset(local_tz=None): """ Returns current utcoffset for a timezone. Uses DEFAULT_LOCAL_TZ by default. That value can be changed at runtime using the func below. """ if local_tz is None: local_tz = DEFAULT_LOCAL_TZ dt = local_tz.localize(datetime.now()) return dt.utcoffset()
def GetRootKey ( self ) : regf_key = self . _regf_file . get_root_key ( ) if not regf_key : return None return REGFWinRegistryKey ( regf_key , key_path = self . _key_path_prefix )
0
howto open a specific key python winreg
Retrieves the root key .
cosqa-train-14190
def GetRootKey(self): """Retrieves the root key. Returns: WinRegistryKey: Windows Registry root key or None if not available. """ regf_key = self._regf_file.get_root_key() if not regf_key: return None return REGFWinRegistryKey(regf_key, key_path=self._key_path_prefix)
def yview ( self , * args ) : self . after_idle ( self . __updateWnds ) ttk . Treeview . yview ( self , * args )
1
python tk treeview with scrollbar
Update inplace widgets position when doing vertical scroll
cosqa-train-14191
def yview(self, *args): """Update inplace widgets position when doing vertical scroll""" self.after_idle(self.__updateWnds) ttk.Treeview.yview(self, *args)
def html_to_text ( content ) : text = None h2t = html2text . HTML2Text ( ) h2t . ignore_links = False text = h2t . handle ( content ) return text
1
html 2 text python
Converts html content to plain text
cosqa-train-14192
def html_to_text(content): """ Converts html content to plain text """ text = None h2t = html2text.HTML2Text() h2t.ignore_links = False text = h2t.handle(content) return text
def _grid_widgets ( self ) : scrollbar_column = 0 if self . __compound is tk . LEFT else 2 self . listbox . grid ( row = 0 , column = 1 , sticky = "nswe" ) self . scrollbar . grid ( row = 0 , column = scrollbar_column , sticky = "ns" )
0
python tkinter align widgets in a row vertically
Puts the two whole widgets in the correct position depending on compound .
cosqa-train-14193
def _grid_widgets(self): """Puts the two whole widgets in the correct position depending on compound.""" scrollbar_column = 0 if self.__compound is tk.LEFT else 2 self.listbox.grid(row=0, column=1, sticky="nswe") self.scrollbar.grid(row=0, column=scrollbar_column, sticky="ns")
def get_jsonparsed_data ( url ) : response = urlopen ( url ) data = response . read ( ) . decode ( 'utf-8' ) return json . loads ( data )
1
http url json parsing ijn python
Receive the content of url parse it as JSON and return the object .
cosqa-train-14194
def get_jsonparsed_data(url): """Receive the content of ``url``, parse it as JSON and return the object. """ response = urlopen(url) data = response.read().decode('utf-8') return json.loads(data)
def askopenfilename ( * * kwargs ) : try : from Tkinter import Tk import tkFileDialog as filedialog except ImportError : from tkinter import Tk , filedialog root = Tk ( ) root . withdraw ( ) root . update ( ) filenames = filedialog . askopenfilename ( * * kwargs ) root . destroy ( ) return filenames
1
python tkinter askopenfilenames dialog won't close
Return file name ( s ) from Tkinter s file open dialog .
cosqa-train-14195
def askopenfilename(**kwargs): """Return file name(s) from Tkinter's file open dialog.""" try: from Tkinter import Tk import tkFileDialog as filedialog except ImportError: from tkinter import Tk, filedialog root = Tk() root.withdraw() root.update() filenames = filedialog.askopenfilename(**kwargs) root.destroy() return filenames
def arg_default ( * args , * * kwargs ) : parser = argparse . ArgumentParser ( ) parser . add_argument ( * args , * * kwargs ) args = vars ( parser . parse_args ( [ ] ) ) _ , default = args . popitem ( ) return default
1
i have default args defined, how do i tell python to use default args
Return default argument value as given by argparse s add_argument () .
cosqa-train-14196
def arg_default(*args, **kwargs): """Return default argument value as given by argparse's add_argument(). The argument is passed through a mocked-up argument parser. This way, we get default parameters even if the feature is called directly and not through the CLI. """ parser = argparse.ArgumentParser() parser.add_argument(*args, **kwargs) args = vars(parser.parse_args([])) _, default = args.popitem() return default
def on_source_directory_chooser_clicked ( self ) : title = self . tr ( 'Set the source directory for script and scenario' ) self . choose_directory ( self . source_directory , title )
1
python tkinter choose folder
Autoconnect slot activated when tbSourceDir is clicked .
cosqa-train-14197
def on_source_directory_chooser_clicked(self): """Autoconnect slot activated when tbSourceDir is clicked.""" title = self.tr('Set the source directory for script and scenario') self.choose_directory(self.source_directory, title)
def value_left ( self , other ) : return other . value if isinstance ( other , self . __class__ ) else other
1
imitate the left function in python
Returns the value of the other type instance to use in an operator method namely when the method s instance is on the left side of the expression .
cosqa-train-14198
def value_left(self, other): """ Returns the value of the other type instance to use in an operator method, namely when the method's instance is on the left side of the expression. """ return other.value if isinstance(other, self.__class__) else other
def hide ( self ) : self . tk . withdraw ( ) self . _visible = False if self . _modal : self . tk . grab_release ( )
1
python tkinter hide a window
Hide the window .
cosqa-train-14199
def hide(self): """Hide the window.""" self.tk.withdraw() self._visible = False if self._modal: self.tk.grab_release()