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 url ( self ) : with switch_window ( self . _browser , self . name ) : return self . _browser . url
0
python get url in browser
The url of this window
cosqa-train-500
def url(self): """ The url of this window """ with switch_window(self._browser, self.name): return self._browser.url
def euclidean ( c1 , c2 ) : diffs = ( ( i - j ) for i , j in zip ( c1 , c2 ) ) return sum ( x * x for x in diffs )
0
euclidean distance of two lists python
Square of the euclidean distance
cosqa-train-501
def euclidean(c1, c2): """Square of the euclidean distance""" diffs = ((i - j) for i, j in zip(c1, c2)) return sum(x * x for x in diffs)
def get_free_memory_win ( ) : stat = MEMORYSTATUSEX ( ) ctypes . windll . kernel32 . GlobalMemoryStatusEx ( ctypes . byref ( stat ) ) return int ( stat . ullAvailPhys / 1024 / 1024 )
0
python get used memory info
Return current free memory on the machine for windows .
cosqa-train-502
def get_free_memory_win(): """Return current free memory on the machine for windows. Warning : this script is really not robust Return in MB unit """ stat = MEMORYSTATUSEX() ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat)) return int(stat.ullAvailPhys / 1024 / 1024)
def xpathEvalExpression ( self , str ) : ret = libxml2mod . xmlXPathEvalExpression ( str , self . _o ) if ret is None : raise xpathError ( 'xmlXPathEvalExpression() failed' ) return xpathObjectRet ( ret )
0
evaluate expression python xpath
Evaluate the XPath expression in the given context .
cosqa-train-503
def xpathEvalExpression(self, str): """Evaluate the XPath expression in the given context. """ ret = libxml2mod.xmlXPathEvalExpression(str, self._o) if ret is None:raise xpathError('xmlXPathEvalExpression() failed') return xpathObjectRet(ret)
def EnumValueName ( self , enum , value ) : return self . enum_types_by_name [ enum ] . values_by_number [ value ] . name
0
python get value from enum
Returns the string name of an enum value .
cosqa-train-504
def EnumValueName(self, enum, value): """Returns the string name of an enum value. This is just a small helper method to simplify a common operation. Args: enum: string name of the Enum. value: int, value of the enum. Returns: string name of the enum value. Raises: KeyError if either the Enum doesn't exist or the value is not a valid value for the enum. """ return self.enum_types_by_name[enum].values_by_number[value].name
def is_in ( self , point_x , point_y ) : point_array = array ( ( ( point_x , point_y ) , ) ) vertices = array ( self . points ) winding = self . inside_rule == "winding" result = points_in_polygon ( point_array , vertices , winding ) return result [ 0 ]
1
evaluate if a set of points are inside of a polygon python
Test if a point is within this polygonal region
cosqa-train-505
def is_in(self, point_x, point_y): """ Test if a point is within this polygonal region """ point_array = array(((point_x, point_y),)) vertices = array(self.points) winding = self.inside_rule == "winding" result = points_in_polygon(point_array, vertices, winding) return result[0]
def extent_count ( self ) : self . open ( ) count = lvm_vg_get_extent_count ( self . handle ) self . close ( ) return count
0
python get volume size
Returns the volume group extent count .
cosqa-train-506
def extent_count(self): """ Returns the volume group extent count. """ self.open() count = lvm_vg_get_extent_count(self.handle) self.close() return count
def numpy_aware_eq ( a , b ) : if isinstance ( a , np . ndarray ) or isinstance ( b , np . ndarray ) : return np . array_equal ( a , b ) if ( ( isinstance ( a , Iterable ) and isinstance ( b , Iterable ) ) and not isinstance ( a , str ) and not isinstance ( b , str ) ) : if len ( a ) != len ( b ) : return False return all ( numpy_aware_eq ( x , y ) for x , y in zip ( a , b ) ) return a == b
0
evaluate if two ndarrays are equal python
Return whether two objects are equal via recursion using : func : numpy . array_equal for comparing numpy arays .
cosqa-train-507
def numpy_aware_eq(a, b): """Return whether two objects are equal via recursion, using :func:`numpy.array_equal` for comparing numpy arays. """ if isinstance(a, np.ndarray) or isinstance(b, np.ndarray): return np.array_equal(a, b) if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and not isinstance(a, str) and not isinstance(b, str)): if len(a) != len(b): return False return all(numpy_aware_eq(x, y) for x, y in zip(a, b)) return a == b
def title ( self ) : with switch_window ( self . _browser , self . name ) : return self . _browser . title
0
python get window title of selected window
The title of this window
cosqa-train-508
def title(self): """ The title of this window """ with switch_window(self._browser, self.name): return self._browser.title
def visit_BoolOp ( self , node ) : return sum ( ( self . visit ( value ) for value in node . values ) , [ ] )
0
evaluting boolean values in python function
Return type may come from any boolop operand .
cosqa-train-509
def visit_BoolOp(self, node): """ Return type may come from any boolop operand. """ return sum((self.visit(value) for value in node.values), [])
def __get_xml_text ( root ) : txt = "" for e in root . childNodes : if ( e . nodeType == e . TEXT_NODE ) : txt += e . data return txt
0
python get xml text
Return the text for the given root node ( xml . dom . minidom ) .
cosqa-train-510
def __get_xml_text(root): """ Return the text for the given root node (xml.dom.minidom). """ txt = "" for e in root.childNodes: if (e.nodeType == e.TEXT_NODE): txt += e.data return txt
def runcode ( code ) : for line in code : print ( '# ' + line ) exec ( line , globals ( ) ) print ( '# return ans' ) return ans
0
execute code line by line in python
Run the given code line by line with printing as list of lines and return variable ans .
cosqa-train-511
def runcode(code): """Run the given code line by line with printing, as list of lines, and return variable 'ans'.""" for line in code: print('# '+line) exec(line,globals()) print('# return ans') return ans
def fetch_event ( urls ) : rs = ( grequests . get ( u ) for u in urls ) return [ content . json ( ) for content in grequests . map ( rs ) ]
0
python gevent pool paralle
This parallel fetcher uses gevent one uses gevent
cosqa-train-512
def fetch_event(urls): """ This parallel fetcher uses gevent one uses gevent """ rs = (grequests.get(u) for u in urls) return [content.json() for content in grequests.map(rs)]
def get_order ( self , codes ) : return sorted ( codes , key = lambda e : [ self . ev2idx . get ( e ) ] )
0
execute order based on value python
Return evidence codes in order shown in code2name .
cosqa-train-513
def get_order(self, codes): """Return evidence codes in order shown in code2name.""" return sorted(codes, key=lambda e: [self.ev2idx.get(e)])
def equal ( list1 , list2 ) : return [ item1 == item2 for item1 , item2 in broadcast_zip ( list1 , list2 ) ]
0
python given an array of boolean to decide values of another array
takes flags returns indexes of True values
cosqa-train-514
def equal(list1, list2): """ takes flags returns indexes of True values """ return [item1 == item2 for item1, item2 in broadcast_zip(list1, list2)]
def select ( self , cmd , * args , * * kwargs ) : self . cursor . execute ( cmd , * args , * * kwargs ) return self . cursor . fetchall ( )
0
execute(query, arg) cursor python
Execute the SQL command and return the data rows as tuples
cosqa-train-515
def select(self, cmd, *args, **kwargs): """ Execute the SQL command and return the data rows as tuples """ self.cursor.execute(cmd, *args, **kwargs) return self.cursor.fetchall()
def go_to_parent_directory ( self ) : self . chdir ( osp . abspath ( osp . join ( getcwd_or_home ( ) , os . pardir ) ) )
0
python go to parent folder
Go to parent directory
cosqa-train-516
def go_to_parent_directory(self): """Go to parent directory""" self.chdir(osp.abspath(osp.join(getcwd_or_home(), os.pardir)))
def _convert_to_float_if_possible ( s ) : try : ret = float ( s ) except ( ValueError , TypeError ) : ret = s return ret
0
expected string got float instead python
A small helper function to convert a string to a numeric value if appropriate
cosqa-train-517
def _convert_to_float_if_possible(s): """ A small helper function to convert a string to a numeric value if appropriate :param s: the string to be converted :type s: str """ try: ret = float(s) except (ValueError, TypeError): ret = s return ret
def _top ( self ) : # Goto top of the list self . top . body . focus_position = 2 if self . compact is False else 0 self . top . keypress ( self . size , "" )
0
python go to the bottom of a listbox
g
cosqa-train-518
def _top(self): """ g """ # Goto top of the list self.top.body.focus_position = 2 if self.compact is False else 0 self.top.keypress(self.size, "")
def exp_fit_fun ( x , a , tau , c ) : # pylint: disable=invalid-name return a * np . exp ( - x / tau ) + c
0
exponential decay python fit
Function used to fit the exponential decay .
cosqa-train-519
def exp_fit_fun(x, a, tau, c): """Function used to fit the exponential decay.""" # pylint: disable=invalid-name return a * np.exp(-x / tau) + c
def to_gtp ( coord ) : if coord is None : return 'pass' y , x = coord return '{}{}' . format ( _GTP_COLUMNS [ x ] , go . N - y )
0
python gps coordinates to x, y, z
Converts from a Minigo coordinate to a GTP coordinate .
cosqa-train-520
def to_gtp(coord): """Converts from a Minigo coordinate to a GTP coordinate.""" if coord is None: return 'pass' y, x = coord return '{}{}'.format(_GTP_COLUMNS[x], go.N - y)
def nb_to_python ( nb_path ) : exporter = python . PythonExporter ( ) output , resources = exporter . from_filename ( nb_path ) return output
1
export ipynb as python file
convert notebook to python script
cosqa-train-521
def nb_to_python(nb_path): """convert notebook to python script""" exporter = python.PythonExporter() output, resources = exporter.from_filename(nb_path) return output
def searchlast ( self , n = 10 ) : solutions = deque ( [ ] , n ) for solution in self : solutions . append ( solution ) return solutions
0
python grab last n elments
Return the last n results ( or possibly less if not found ) . Note that the last results are not necessarily the best ones! Depending on the search type .
cosqa-train-522
def searchlast(self,n=10): """Return the last n results (or possibly less if not found). Note that the last results are not necessarily the best ones! Depending on the search type.""" solutions = deque([], n) for solution in self: solutions.append(solution) return solutions
def to_json ( df , state_index , color_index , fills ) : records = { } for i , row in df . iterrows ( ) : records [ row [ state_index ] ] = { "fillKey" : row [ color_index ] } return { "data" : records , "fills" : fills }
0
expose data in json format in python using data frame
Transforms dataframe to json response
cosqa-train-523
def to_json(df, state_index, color_index, fills): """Transforms dataframe to json response""" records = {} for i, row in df.iterrows(): records[row[state_index]] = { "fillKey": row[color_index] } return { "data": records, "fills": fills }
def _text_to_graphiz ( self , text ) : dot = Source ( text , format = 'svg' ) return dot . pipe ( ) . decode ( 'utf-8' )
0
python graphviz format png
create a graphviz graph from text
cosqa-train-524
def _text_to_graphiz(self, text): """create a graphviz graph from text""" dot = Source(text, format='svg') return dot.pipe().decode('utf-8')
def get_colors ( img ) : w , h = img . size return [ color [ : 3 ] for count , color in img . convert ( 'RGB' ) . getcolors ( w * h ) ]
0
extract color components of an image in python
Returns a list of all the image s colors .
cosqa-train-525
def get_colors(img): """ Returns a list of all the image's colors. """ w, h = img.size return [color[:3] for count, color in img.convert('RGB').getcolors(w * h)]
def _round_half_hour ( record ) : k = record . datetime + timedelta ( minutes = - ( record . datetime . minute % 30 ) ) return datetime ( k . year , k . month , k . day , k . hour , k . minute , 0 )
0
python group minute data into half hour
Round a time DOWN to half nearest half - hour .
cosqa-train-526
def _round_half_hour(record): """ Round a time DOWN to half nearest half-hour. """ k = record.datetime + timedelta(minutes=-(record.datetime.minute % 30)) return datetime(k.year, k.month, k.day, k.hour, k.minute, 0)
def get_X0 ( X ) : if pandas_available and isinstance ( X , pd . DataFrame ) : assert len ( X ) == 1 x = np . array ( X . iloc [ 0 ] ) else : x , = X return x
0
extract first array in python
Return zero - th element of a one - element data container .
cosqa-train-527
def get_X0(X): """ Return zero-th element of a one-element data container. """ if pandas_available and isinstance(X, pd.DataFrame): assert len(X) == 1 x = np.array(X.iloc[0]) else: x, = X return x
def threads_init ( gtk = True ) : # enable X11 multithreading x11 . XInitThreads ( ) if gtk : from gtk . gdk import threads_init threads_init ( )
0
python gtk starting separate thread but doesn't run
Enables multithreading support in Xlib and PyGTK . See the module docstring for more info . : Parameters : gtk : bool May be set to False to skip the PyGTK module .
cosqa-train-528
def threads_init(gtk=True): """Enables multithreading support in Xlib and PyGTK. See the module docstring for more info. :Parameters: gtk : bool May be set to False to skip the PyGTK module. """ # enable X11 multithreading x11.XInitThreads() if gtk: from gtk.gdk import threads_init threads_init()
def security ( self ) : return { k : v for i in self . pdf . resolvedObjects . items ( ) for k , v in i [ 1 ] . items ( ) }
0
extract pdf fields in python
Print security object information for a pdf document
cosqa-train-529
def security(self): """Print security object information for a pdf document""" return {k: v for i in self.pdf.resolvedObjects.items() for k, v in i[1].items()}
def enable_gtk3 ( self , app = None ) : from pydev_ipython . inputhookgtk3 import create_inputhook_gtk3 self . set_inputhook ( create_inputhook_gtk3 ( self . _stdin_file ) ) self . _current_gui = GUI_GTK
0
python gtk3 not work on window
Enable event loop integration with Gtk3 ( gir bindings ) .
cosqa-train-530
def enable_gtk3(self, app=None): """Enable event loop integration with Gtk3 (gir bindings). Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes ----- This methods sets the PyOS_InputHook for Gtk3, which allows the Gtk3 to integrate with terminal based applications like IPython. """ from pydev_ipython.inputhookgtk3 import create_inputhook_gtk3 self.set_inputhook(create_inputhook_gtk3(self._stdin_file)) self._current_gui = GUI_GTK
def dot ( a , b ) : b = numpy . asarray ( b ) return numpy . dot ( a , b . reshape ( b . shape [ 0 ] , - 1 ) ) . reshape ( a . shape [ : - 1 ] + b . shape [ 1 : ] )
0
fast matrix dot products in python
Take arrays a and b and form the dot product between the last axis of a and the first of b .
cosqa-train-531
def dot(a, b): """Take arrays `a` and `b` and form the dot product between the last axis of `a` and the first of `b`. """ b = numpy.asarray(b) return numpy.dot(a, b.reshape(b.shape[0], -1)).reshape(a.shape[:-1] + b.shape[1:])
def guess_encoding ( text , default = DEFAULT_ENCODING ) : result = chardet . detect ( text ) return normalize_result ( result , default = default )
0
python guess text encoding
Guess string encoding .
cosqa-train-532
def guess_encoding(text, default=DEFAULT_ENCODING): """Guess string encoding. Given a piece of text, apply character encoding detection to guess the appropriate encoding of the text. """ result = chardet.detect(text) return normalize_result(result, default=default)
def check_precomputed_distance_matrix ( X ) : tmp = X . copy ( ) tmp [ np . isinf ( tmp ) ] = 1 check_array ( tmp )
0
fast way of setting certain elements in array to zero python
Perform check_array ( X ) after removing infinite values ( numpy . inf ) from the given distance matrix .
cosqa-train-533
def check_precomputed_distance_matrix(X): """Perform check_array(X) after removing infinite values (numpy.inf) from the given distance matrix. """ tmp = X.copy() tmp[np.isinf(tmp)] = 1 check_array(tmp)
def __gzip ( filename ) : zipname = filename + '.gz' file_pointer = open ( filename , 'rb' ) zip_pointer = gzip . open ( zipname , 'wb' ) zip_pointer . writelines ( file_pointer ) file_pointer . close ( ) zip_pointer . close ( ) return zipname
0
python gzip compress a file
Compress a file returning the new filename ( . gz )
cosqa-train-534
def __gzip(filename): """ Compress a file returning the new filename (.gz) """ zipname = filename + '.gz' file_pointer = open(filename,'rb') zip_pointer = gzip.open(zipname,'wb') zip_pointer.writelines(file_pointer) file_pointer.close() zip_pointer.close() return zipname
def forceupdate ( self , * args , * * kw ) : self . _update ( False , self . _ON_DUP_OVERWRITE , * args , * * kw )
1
faster update bulk in python mysql
Like a bulk : meth : forceput .
cosqa-train-535
def forceupdate(self, *args, **kw): """Like a bulk :meth:`forceput`.""" self._update(False, self._ON_DUP_OVERWRITE, *args, **kw)
def create_h5py_with_large_cache ( filename , cache_size_mb ) : # h5py does not allow to control the cache size from the high level # we employ the workaround # sources: #http://stackoverflow.com/questions/14653259/how-to-set-cache-settings-while-using-h5py-high-level-interface #https://groups.google.com/forum/#!msg/h5py/RVx1ZB6LpE4/KH57vq5yw2AJ propfaid = h5py . h5p . create ( h5py . h5p . FILE_ACCESS ) settings = list ( propfaid . get_cache ( ) ) settings [ 2 ] = 1024 * 1024 * cache_size_mb propfaid . set_cache ( * settings ) fid = h5py . h5f . create ( filename , flags = h5py . h5f . ACC_EXCL , fapl = propfaid ) fin = h5py . File ( fid ) return fin
0
python h5 file how to decrease size
Allows to open the hdf5 file with specified cache size
cosqa-train-536
def create_h5py_with_large_cache(filename, cache_size_mb): """ Allows to open the hdf5 file with specified cache size """ # h5py does not allow to control the cache size from the high level # we employ the workaround # sources: #http://stackoverflow.com/questions/14653259/how-to-set-cache-settings-while-using-h5py-high-level-interface #https://groups.google.com/forum/#!msg/h5py/RVx1ZB6LpE4/KH57vq5yw2AJ propfaid = h5py.h5p.create(h5py.h5p.FILE_ACCESS) settings = list(propfaid.get_cache()) settings[2] = 1024 * 1024 * cache_size_mb propfaid.set_cache(*settings) fid = h5py.h5f.create(filename, flags=h5py.h5f.ACC_EXCL, fapl=propfaid) fin = h5py.File(fid) return fin
def rfft2d_freqs ( h , w ) : fy = np . fft . fftfreq ( h ) [ : , None ] # when we have an odd input dimension we need to keep one additional # frequency and later cut off 1 pixel if w % 2 == 1 : fx = np . fft . fftfreq ( w ) [ : w // 2 + 2 ] else : fx = np . fft . fftfreq ( w ) [ : w // 2 + 1 ] return np . sqrt ( fx * fx + fy * fy )
0
fft 2d spectrum python
Computes 2D spectrum frequencies .
cosqa-train-537
def rfft2d_freqs(h, w): """Computes 2D spectrum frequencies.""" fy = np.fft.fftfreq(h)[:, None] # when we have an odd input dimension we need to keep one additional # frequency and later cut off 1 pixel if w % 2 == 1: fx = np.fft.fftfreq(w)[: w // 2 + 2] else: fx = np.fft.fftfreq(w)[: w // 2 + 1] return np.sqrt(fx * fx + fy * fy)
def md5_hash_file ( fh ) : md5 = hashlib . md5 ( ) while True : data = fh . read ( 8192 ) if not data : break md5 . update ( data ) return md5 . hexdigest ( )
0
python h5file force read into memory
Return the md5 hash of the given file - object
cosqa-train-538
def md5_hash_file(fh): """Return the md5 hash of the given file-object""" md5 = hashlib.md5() while True: data = fh.read(8192) if not data: break md5.update(data) return md5.hexdigest()
def software_fibonacci ( n ) : a , b = 0 , 1 for i in range ( n ) : a , b = b , a + b return a
0
fibonacci with function for in python
a normal old python function to return the Nth fibonacci number .
cosqa-train-539
def software_fibonacci(n): """ a normal old python function to return the Nth fibonacci number. """ a, b = 0, 1 for i in range(n): a, b = b, a + b return a
def h5ToDict ( h5 , readH5pyDataset = True ) : h = h5py . File ( h5 , "r" ) ret = unwrapArray ( h , recursive = True , readH5pyDataset = readH5pyDataset ) if readH5pyDataset : h . close ( ) return ret
0
python h5py read data
Read a hdf5 file into a dictionary
cosqa-train-540
def h5ToDict(h5, readH5pyDataset=True): """ Read a hdf5 file into a dictionary """ h = h5py.File(h5, "r") ret = unwrapArray(h, recursive=True, readH5pyDataset=readH5pyDataset) if readH5pyDataset: h.close() return ret
def current_zipfile ( ) : if zipfile . is_zipfile ( sys . argv [ 0 ] ) : fd = open ( sys . argv [ 0 ] , "rb" ) return zipfile . ZipFile ( fd )
0
file is not a zip file python
A function to vend the current zipfile if any
cosqa-train-541
def current_zipfile(): """A function to vend the current zipfile, if any""" if zipfile.is_zipfile(sys.argv[0]): fd = open(sys.argv[0], "rb") return zipfile.ZipFile(fd)
def __unixify ( self , s ) : return os . path . normpath ( s ) . replace ( os . sep , "/" )
0
python handling windows paths in strings
stupid windows . converts the backslash to forwardslash for consistency
cosqa-train-542
def __unixify(self, s): """ stupid windows. converts the backslash to forwardslash for consistency """ return os.path.normpath(s).replace(os.sep, "/")
def __init__ ( self , encoding = 'utf-8' ) : super ( StdinInputReader , self ) . __init__ ( sys . stdin , encoding = encoding )
0
fileinput python specify encoding
Initializes an stdin input reader .
cosqa-train-543
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 _add_hash ( source ) : source = '\n' . join ( '# ' + line . rstrip ( ) for line in source . splitlines ( ) ) return source
0
python hash bang line
Add a leading hash # at the beginning of every line in the source .
cosqa-train-544
def _add_hash(source): """Add a leading hash '#' at the beginning of every line in the source.""" source = '\n'.join('# ' + line.rstrip() for line in source.splitlines()) return source
def apply ( f , obj , * args , * * kwargs ) : return vectorize ( f ) ( obj , * args , * * kwargs )
0
fille a vector in a parallelize way python
Apply a function in parallel to each element of the input
cosqa-train-545
def apply(f, obj, *args, **kwargs): """Apply a function in parallel to each element of the input""" return vectorize(f)(obj, *args, **kwargs)
def double_sha256 ( data ) : return bytes_as_revhex ( hashlib . sha256 ( hashlib . sha256 ( data ) . digest ( ) ) . digest ( ) )
0
python hashlib return string
A standard compound hash .
cosqa-train-546
def double_sha256(data): """A standard compound hash.""" return bytes_as_revhex(hashlib.sha256(hashlib.sha256(data).digest()).digest())
def drop_empty ( rows ) : return zip ( * [ col for col in zip ( * rows ) if bool ( filter ( bool , col [ 1 : ] ) ) ] )
0
filter empty rows python
Transpose the columns into rows remove all of the rows that are empty after the first cell then transpose back . The result is that columns that have a header but no data in the body are removed assuming the header is the first row .
cosqa-train-547
def drop_empty(rows): """Transpose the columns into rows, remove all of the rows that are empty after the first cell, then transpose back. The result is that columns that have a header but no data in the body are removed, assuming the header is the first row. """ return zip(*[col for col in zip(*rows) if bool(filter(bool, col[1:]))])
def heappush_max ( heap , item ) : heap . append ( item ) _siftdown_max ( heap , 0 , len ( heap ) - 1 )
0
python heap limit length
Push item onto heap maintaining the heap invariant .
cosqa-train-548
def heappush_max(heap, item): """Push item onto heap, maintaining the heap invariant.""" heap.append(item) _siftdown_max(heap, 0, len(heap) - 1)
def split_addresses ( email_string_list ) : return [ f for f in [ s . strip ( ) for s in email_string_list . split ( "," ) ] if f ]
0
filter list using regex email example python
Converts a string containing comma separated email addresses into a list of email addresses .
cosqa-train-549
def split_addresses(email_string_list): """ Converts a string containing comma separated email addresses into a list of email addresses. """ return [f for f in [s.strip() for s in email_string_list.split(",")] if f]
def _heappush_max ( heap , item ) : heap . append ( item ) heapq . _siftdown_max ( heap , 0 , len ( heap ) - 1 )
0
python heap sort stackoverflow
why is this not in heapq
cosqa-train-550
def _heappush_max(heap, item): """ why is this not in heapq """ heap.append(item) heapq._siftdown_max(heap, 0, len(heap) - 1)
def _remove_keywords ( d ) : return { k : v for k , v in iteritems ( d ) if k not in RESERVED }
0
filter stopwords from a dictionary python
copy the dict filter_keywords
cosqa-train-551
def _remove_keywords(d): """ copy the dict, filter_keywords Parameters ---------- d : dict """ return { k:v for k, v in iteritems(d) if k not in RESERVED }
def _heapify_max ( x ) : n = len ( x ) for i in reversed ( range ( n // 2 ) ) : _siftup_max ( x , i )
0
python heapify time complexity
Transform list into a maxheap in - place in O ( len ( x )) time .
cosqa-train-552
def _heapify_max(x): """Transform list into a maxheap, in-place, in O(len(x)) time.""" n = len(x) for i in reversed(range(n//2)): _siftup_max(x, i)
def uniq ( seq ) : seen = set ( ) return [ x for x in seq if str ( x ) not in seen and not seen . add ( str ( x ) ) ]
0
filter uniques from python list
Return a copy of seq without duplicates .
cosqa-train-553
def uniq(seq): """ Return a copy of seq without duplicates. """ seen = set() return [x for x in seq if str(x) not in seen and not seen.add(str(x))]
def pop ( h ) : n = h . size ( ) - 1 h . swap ( 0 , n ) down ( h , 0 , n ) return h . pop ( )
0
python heapq get last element
Pop the heap value from the heap .
cosqa-train-554
def pop(h): """Pop the heap value from the heap.""" n = h.size() - 1 h.swap(0, n) down(h, 0, n) return h.pop()
def replace_all ( filepath , searchExp , replaceExp ) : for line in fileinput . input ( filepath , inplace = 1 ) : if searchExp in line : line = line . replace ( searchExp , replaceExp ) sys . stdout . write ( line )
0
find/replace in a file python
Replace all the ocurrences ( in a file ) of a string with another value .
cosqa-train-555
def replace_all(filepath, searchExp, replaceExp): """ Replace all the ocurrences (in a file) of a string with another value. """ for line in fileinput.input(filepath, inplace=1): if searchExp in line: line = line.replace(searchExp, replaceExp) sys.stdout.write(line)
def __call__ ( self , kind : Optional [ str ] = None , * * kwargs ) : return plot ( self . histogram , kind = kind , * * kwargs )
0
python histogram matplotlib kwargs
Use the plotter as callable .
cosqa-train-556
def __call__(self, kind: Optional[str] = None, **kwargs): """Use the plotter as callable.""" return plot(self.histogram, kind=kind, **kwargs)
def ci ( a , which = 95 , axis = None ) : p = 50 - which / 2 , 50 + which / 2 return percentiles ( a , p , axis )
0
finding 25 percent points in distribution python
Return a percentile range from an array of values .
cosqa-train-557
def ci(a, which=95, axis=None): """Return a percentile range from an array of values.""" p = 50 - which / 2, 50 + which / 2 return percentiles(a, p, axis)
def dtype ( self ) : try : return self . data . dtype except AttributeError : return numpy . dtype ( '%s%d' % ( self . _sample_type , self . _sample_bytes ) )
0
python how do i know what data type
Pixel data type .
cosqa-train-558
def dtype(self): """Pixel data type.""" try: return self.data.dtype except AttributeError: return numpy.dtype('%s%d' % (self._sample_type, self._sample_bytes))
def tuple_search ( t , i , v ) : for e in t : if e [ i ] == v : return e return None
0
finding a string in a python tuple
Search tuple array by index and value : param t : tuple array : param i : index of the value in each tuple : param v : value : return : the first tuple in the array with the specific index / value
cosqa-train-559
def tuple_search(t, i, v): """ Search tuple array by index and value :param t: tuple array :param i: index of the value in each tuple :param v: value :return: the first tuple in the array with the specific index / value """ for e in t: if e[i] == v: return e return None
def from_pairs_to_array_values ( pairs ) : result = { } for pair in pairs : result [ pair [ 0 ] ] = concat ( prop_or ( [ ] , pair [ 0 ] , result ) , [ pair [ 1 ] ] ) return result
0
python how join to lists as pairs
Like from pairs but combines duplicate key values into arrays : param pairs : : return :
cosqa-train-560
def from_pairs_to_array_values(pairs): """ Like from pairs but combines duplicate key values into arrays :param pairs: :return: """ result = {} for pair in pairs: result[pair[0]] = concat(prop_or([], pair[0], result), [pair[1]]) return result
def area ( x , y ) : # http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates return 0.5 * np . abs ( np . dot ( x , np . roll ( y , 1 ) ) - np . dot ( y , np . roll ( x , 1 ) ) )
0
finding area of an irregular polygon python
Calculate the area of a polygon given as x ( ... ) y ( ... ) Implementation of Shoelace formula
cosqa-train-561
def area(x,y): """ Calculate the area of a polygon given as x(...),y(...) Implementation of Shoelace formula """ # http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))
def _getSuperFunc ( self , s , func ) : return getattr ( super ( self . cls ( ) , s ) , func . __name__ )
0
python how to autocomplate to show super method
Return the the super function .
cosqa-train-562
def _getSuperFunc(self, s, func): """Return the the super function.""" return getattr(super(self.cls(), s), func.__name__)
def val_to_bin ( edges , x ) : ibin = np . digitize ( np . array ( x , ndmin = 1 ) , edges ) - 1 return ibin
0
finding center of histogram bins python
Convert axis coordinate to bin index .
cosqa-train-563
def val_to_bin(edges, x): """Convert axis coordinate to bin index.""" ibin = np.digitize(np.array(x, ndmin=1), edges) - 1 return ibin
def val_to_bin ( edges , x ) : ibin = np . digitize ( np . array ( x , ndmin = 1 ) , edges ) - 1 return ibin
0
python how to calculate bins from bin edges
Convert axis coordinate to bin index .
cosqa-train-564
def val_to_bin(edges, x): """Convert axis coordinate to bin index.""" ibin = np.digitize(np.array(x, ndmin=1), edges) - 1 return ibin
def compare ( dicts ) : common_members = { } common_keys = reduce ( lambda x , y : x & y , map ( dict . keys , dicts ) ) for k in common_keys : common_members [ k ] = list ( reduce ( lambda x , y : x & y , [ set ( d [ k ] ) for d in dicts ] ) ) return common_members
0
finding common values in dictionaries python
Compare by iteration
cosqa-train-565
def compare(dicts): """Compare by iteration""" common_members = {} common_keys = reduce(lambda x, y: x & y, map(dict.keys, dicts)) for k in common_keys: common_members[k] = list( reduce(lambda x, y: x & y, [set(d[k]) for d in dicts])) return common_members
def convert_timestamp ( timestamp ) : datetime = dt . datetime . utcfromtimestamp ( timestamp / 1000. ) return np . datetime64 ( datetime . replace ( tzinfo = None ) )
0
python how to cast string to timestamp
Converts bokehJS timestamp to datetime64 .
cosqa-train-566
def convert_timestamp(timestamp): """ Converts bokehJS timestamp to datetime64. """ datetime = dt.datetime.utcfromtimestamp(timestamp/1000.) return np.datetime64(datetime.replace(tzinfo=None))
def _get_compiled_ext ( ) : for ext , mode , typ in imp . get_suffixes ( ) : if typ == imp . PY_COMPILED : return ext
0
finding extensions of files through python
Official way to get the extension of compiled files ( . pyc or . pyo )
cosqa-train-567
def _get_compiled_ext(): """Official way to get the extension of compiled files (.pyc or .pyo)""" for ext, mode, typ in imp.get_suffixes(): if typ == imp.PY_COMPILED: return ext
def list_add_capitalize ( l ) : nl = [ ] for i in l : nl . append ( i ) if hasattr ( i , "capitalize" ) : nl . append ( i . capitalize ( ) ) return list ( set ( nl ) )
0
python how to change list items to capital
cosqa-train-568
def list_add_capitalize(l): """ @type l: list @return: list """ nl = [] for i in l: nl.append(i) if hasattr(i, "capitalize"): nl.append(i.capitalize()) return list(set(nl))
def inh ( table ) : t = [ ] for i in table : t . append ( np . ndarray . tolist ( np . arcsinh ( i ) ) ) return t
0
finding inverse of matrix in python
inverse hyperbolic sine transformation
cosqa-train-569
def inh(table): """ inverse hyperbolic sine transformation """ t = [] for i in table: t.append(np.ndarray.tolist(np.arcsinh(i))) return t
def to_camel_case ( text ) : split = text . split ( '_' ) return split [ 0 ] + "" . join ( x . title ( ) for x in split [ 1 : ] )
0
python how to change text to uppercase
Convert to camel case .
cosqa-train-570
def to_camel_case(text): """Convert to camel case. :param str text: :rtype: str :return: """ split = text.split('_') return split[0] + "".join(x.title() for x in split[1:])
def median ( lst ) : #: http://stackoverflow.com/a/24101534 sortedLst = sorted ( lst ) lstLen = len ( lst ) index = ( lstLen - 1 ) // 2 if ( lstLen % 2 ) : return sortedLst [ index ] else : return ( sortedLst [ index ] + sortedLst [ index + 1 ] ) / 2.0
0
finding median of list python
Calcuates the median value in a
cosqa-train-571
def median(lst): """ Calcuates the median value in a @lst """ #: http://stackoverflow.com/a/24101534 sortedLst = sorted(lst) lstLen = len(lst) index = (lstLen - 1) // 2 if (lstLen % 2): return sortedLst[index] else: return (sortedLst[index] + sortedLst[index + 1])/2.0
def _IsRetryable ( error ) : if not isinstance ( error , MySQLdb . OperationalError ) : return False if not error . args : return False code = error . args [ 0 ] return code in _RETRYABLE_ERRORS
0
python how to check if a database query failed
Returns whether error is likely to be retryable .
cosqa-train-572
def _IsRetryable(error): """Returns whether error is likely to be retryable.""" if not isinstance(error, MySQLdb.OperationalError): return False if not error.args: return False code = error.args[0] return code in _RETRYABLE_ERRORS
def iter_finds ( regex_obj , s ) : if isinstance ( regex_obj , str ) : for m in re . finditer ( regex_obj , s ) : yield m . group ( ) else : for m in regex_obj . finditer ( s ) : yield m . group ( )
0
finding multiple strings using regex in python
Generate all matches found within a string for a regex and yield each match as a string
cosqa-train-573
def iter_finds(regex_obj, s): """Generate all matches found within a string for a regex and yield each match as a string""" if isinstance(regex_obj, str): for m in re.finditer(regex_obj, s): yield m.group() else: for m in regex_obj.finditer(s): yield m.group()
def pid_exists ( pid ) : try : os . kill ( pid , 0 ) except OSError as exc : return exc . errno == errno . EPERM else : return True
0
python how to check if a process exists by pid
Determines if a system process identifer exists in process table .
cosqa-train-574
def pid_exists(pid): """ Determines if a system process identifer exists in process table. """ try: os.kill(pid, 0) except OSError as exc: return exc.errno == errno.EPERM else: return True
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 , ]
0
finding prime and divisors python
Get all the prime factor of given integer
cosqa-train-575
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 _isstring ( dtype ) : return dtype . type == numpy . unicode_ or dtype . type == numpy . string_
0
python how to check if datattype is string
Given a numpy dtype determines whether it is a string . Returns True if the dtype is string or unicode .
cosqa-train-576
def _isstring(dtype): """Given a numpy dtype, determines whether it is a string. Returns True if the dtype is string or unicode. """ return dtype.type == numpy.unicode_ or dtype.type == numpy.string_
def find_lt ( a , x ) : i = bs . bisect_left ( a , x ) if i : return i - 1 raise ValueError
0
finding the two smallest values in a list python
Find rightmost value less than x .
cosqa-train-577
def find_lt(a, x): """Find rightmost value less than x.""" i = bs.bisect_left(a, x) if i: return i - 1 raise ValueError
def _is_override ( meta , method ) : from taipan . objective . modifiers import _OverriddenMethod return isinstance ( method , _OverriddenMethod )
1
python how to check if method is overload
Checks whether given class or instance method has been marked with the
cosqa-train-578
def _is_override(meta, method): """Checks whether given class or instance method has been marked with the ``@override`` decorator. """ from taipan.objective.modifiers import _OverriddenMethod return isinstance(method, _OverriddenMethod)
def is_in ( self , point_x , point_y ) : point_array = array ( ( ( point_x , point_y ) , ) ) vertices = array ( self . points ) winding = self . inside_rule == "winding" result = points_in_polygon ( point_array , vertices , winding ) return result [ 0 ]
0
finding what points are contained in polygon python
Test if a point is within this polygonal region
cosqa-train-579
def is_in(self, point_x, point_y): """ Test if a point is within this polygonal region """ point_array = array(((point_x, point_y),)) vertices = array(self.points) winding = self.inside_rule == "winding" result = points_in_polygon(point_array, vertices, winding) return result[0]
def should_skip_logging ( func ) : disabled = strtobool ( request . headers . get ( "x-request-nolog" , "false" ) ) return disabled or getattr ( func , SKIP_LOGGING , False )
1
python how to check logging is disabled
Should we skip logging for this handler?
cosqa-train-580
def should_skip_logging(func): """ Should we skip logging for this handler? """ disabled = strtobool(request.headers.get("x-request-nolog", "false")) return disabled or getattr(func, SKIP_LOGGING, False)
def calc_cR ( Q2 , sigma ) : return Q2 * np . exp ( np . sum ( np . log ( sigma ** 2 ) ) / sigma . shape [ 0 ] )
0
fit r like formula model in python without intercept
Returns the cR statistic for the variogram fit ( see [ 1 ] ) .
cosqa-train-581
def calc_cR(Q2, sigma): """Returns the cR statistic for the variogram fit (see [1]).""" return Q2 * np.exp(np.sum(np.log(sigma**2))/sigma.shape[0])
def is_builtin_type ( tp ) : return hasattr ( __builtins__ , tp . __name__ ) and tp is getattr ( __builtins__ , tp . __name__ )
0
python how to check methods implemented in a type
Checks if the given type is a builtin one .
cosqa-train-582
def is_builtin_type(tp): """Checks if the given type is a builtin one. """ return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__)
def apply_fit ( xy , coeffs ) : x_new = coeffs [ 0 ] [ 2 ] + coeffs [ 0 ] [ 0 ] * xy [ : , 0 ] + coeffs [ 0 ] [ 1 ] * xy [ : , 1 ] y_new = coeffs [ 1 ] [ 2 ] + coeffs [ 1 ] [ 0 ] * xy [ : , 0 ] + coeffs [ 1 ] [ 1 ] * xy [ : , 1 ] return x_new , y_new
0
fit the variables into a equation python
Apply the coefficients from a linear fit to an array of x y positions .
cosqa-train-583
def apply_fit(xy,coeffs): """ Apply the coefficients from a linear fit to an array of x,y positions. The coeffs come from the 'coeffs' member of the 'fit_arrays()' output. """ x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1] y_new = coeffs[1][2] + coeffs[1][0]*xy[:,0] + coeffs[1][1]*xy[:,1] return x_new,y_new
def forget_coords ( self ) : self . w . ntotal . set_text ( '0' ) self . coords_dict . clear ( ) self . redo ( )
0
python how to clear a variables value
Forget all loaded coordinates .
cosqa-train-584
def forget_coords(self): """Forget all loaded coordinates.""" self.w.ntotal.set_text('0') self.coords_dict.clear() self.redo()
def flat_list ( lst ) : if isinstance ( lst , list ) : for item in lst : for i in flat_list ( item ) : yield i else : yield lst
0
flatten list of list python using yield
This function flatten given nested list . Argument : nested list Returns : flat list
cosqa-train-585
def flat_list(lst): """This function flatten given nested list. Argument: nested list Returns: flat list """ if isinstance(lst, list): for item in lst: for i in flat_list(item): yield i else: yield lst
def safe_exit ( output ) : try : sys . stdout . write ( output ) sys . stdout . flush ( ) except IOError : pass
0
python how to close and if
exit without breaking pipes .
cosqa-train-586
def safe_exit(output): """exit without breaking pipes.""" try: sys.stdout.write(output) sys.stdout.flush() except IOError: pass
def imflip ( img , direction = 'horizontal' ) : assert direction in [ 'horizontal' , 'vertical' ] if direction == 'horizontal' : return np . flip ( img , axis = 1 ) else : return np . flip ( img , axis = 0 )
0
flip a 1d vector python
Flip an image horizontally or vertically .
cosqa-train-587
def imflip(img, direction='horizontal'): """Flip an image horizontally or vertically. Args: img (ndarray): Image to be flipped. direction (str): The flip direction, either "horizontal" or "vertical". Returns: ndarray: The flipped image. """ assert direction in ['horizontal', 'vertical'] if direction == 'horizontal': return np.flip(img, axis=1) else: return np.flip(img, axis=0)
def get_order ( self ) : return [ dict ( reverse = r [ 0 ] , key = r [ 1 ] ) for r in self . get_model ( ) ]
0
python how to create a ordered dict
Return a list of dicionaries . See set_order .
cosqa-train-588
def get_order(self): """ Return a list of dicionaries. See `set_order`. """ return [dict(reverse=r[0], key=r[1]) for r in self.get_model()]
def hflip ( img ) : if not _is_pil_image ( img ) : raise TypeError ( 'img should be PIL Image. Got {}' . format ( type ( img ) ) ) return img . transpose ( Image . FLIP_LEFT_RIGHT )
0
flip image vertical python
Horizontally flip the given PIL Image .
cosqa-train-589
def hflip(img): """Horizontally flip the given PIL Image. Args: img (PIL Image): Image to be flipped. Returns: PIL Image: Horizontall flipped image. """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) return img.transpose(Image.FLIP_LEFT_RIGHT)
def mkdir ( dir , enter ) : if not os . path . exists ( dir ) : os . makedirs ( dir )
0
python how to create dir
Create directory with template for topic of the current environment
cosqa-train-590
def mkdir(dir, enter): """Create directory with template for topic of the current environment """ if not os.path.exists(dir): os.makedirs(dir)
def get_document_frequency ( self , term ) : if term not in self . _terms : raise IndexError ( TERM_DOES_NOT_EXIST ) else : return len ( self . _terms [ term ] )
0
frequency of a word in a document python
Returns the number of documents the specified term appears in .
cosqa-train-591
def get_document_frequency(self, term): """ Returns the number of documents the specified term appears in. """ if term not in self._terms: raise IndexError(TERM_DOES_NOT_EXIST) else: return len(self._terms[term])
def destroy ( self ) : if self . widget : self . set_active ( False ) super ( AndroidBarcodeView , self ) . destroy ( )
0
python how to disconnect signal from a widget
Cleanup the activty lifecycle listener
cosqa-train-592
def destroy(self): """ Cleanup the activty lifecycle listener """ if self.widget: self.set_active(False) super(AndroidBarcodeView, self).destroy()
def connect ( ) : ftp_class = ftplib . FTP if not SSL else ftplib . FTP_TLS ftp = ftp_class ( timeout = TIMEOUT ) ftp . connect ( HOST , PORT ) ftp . login ( USER , PASSWORD ) if SSL : ftp . prot_p ( ) # secure data connection return ftp
1
ftplib python secure connection
Connect to FTP server login and return an ftplib . FTP instance .
cosqa-train-593
def connect(): """Connect to FTP server, login and return an ftplib.FTP instance.""" ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS ftp = ftp_class(timeout=TIMEOUT) ftp.connect(HOST, PORT) ftp.login(USER, PASSWORD) if SSL: ftp.prot_p() # secure data connection return ftp
def one_for_all ( self , deps ) : requires , dependencies = [ ] , [ ] deps . reverse ( ) # Inverting the list brings the # dependencies in order to be installed. requires = Utils ( ) . dimensional_list ( deps ) dependencies = Utils ( ) . remove_dbs ( requires ) return dependencies
0
python how to dowload all dependencies
Because there are dependencies that depend on other dependencies are created lists into other lists . Thus creating this loop create one - dimensional list and remove double packages from dependencies .
cosqa-train-594
def one_for_all(self, deps): """Because there are dependencies that depend on other dependencies are created lists into other lists. Thus creating this loop create one-dimensional list and remove double packages from dependencies. """ requires, dependencies = [], [] deps.reverse() # Inverting the list brings the # dependencies in order to be installed. requires = Utils().dimensional_list(deps) dependencies = Utils().remove_dbs(requires) return dependencies
def trigger_fullscreen_action ( self , fullscreen ) : action = self . action_group . get_action ( 'fullscreen' ) action . set_active ( fullscreen )
1
full screen in python tkinter
Toggle fullscreen from outside the GUI causes the GUI to updated and run all its actions .
cosqa-train-595
def trigger_fullscreen_action(self, fullscreen): """ Toggle fullscreen from outside the GUI, causes the GUI to updated and run all its actions. """ action = self.action_group.get_action('fullscreen') action.set_active(fullscreen)
def download_json ( local_filename , url , clobber = False ) : with open ( local_filename , 'w' ) as json_file : json_file . write ( json . dumps ( requests . get ( url ) . json ( ) , sort_keys = True , indent = 2 , separators = ( ',' , ': ' ) ) )
0
python how to download a json url
Download the given JSON file and pretty - print before we output it .
cosqa-train-596
def download_json(local_filename, url, clobber=False): """Download the given JSON file, and pretty-print before we output it.""" with open(local_filename, 'w') as json_file: json_file.write(json.dumps(requests.get(url).json(), sort_keys=True, indent=2, separators=(',', ': ')))
def is_password_valid ( password ) : pattern = re . compile ( r"^.{4,75}$" ) return bool ( pattern . match ( password ) )
0
function to check strngth of password with regex in python
Check if a password is valid
cosqa-train-597
def is_password_valid(password): """ Check if a password is valid """ pattern = re.compile(r"^.{4,75}$") return bool(pattern.match(password))
def drag_and_drop ( self , droppable ) : self . scroll_to ( ) ActionChains ( self . parent . driver ) . drag_and_drop ( self . _element , droppable . _element ) . perform ( )
1
python how to drag a element to another element and stay at second element
Performs drag a element to another elmenet .
cosqa-train-598
def drag_and_drop(self, droppable): """ Performs drag a element to another elmenet. Currently works only on Chrome driver. """ self.scroll_to() ActionChains(self.parent.driver).drag_and_drop(self._element, droppable._element).perform()
def gauss_pdf ( x , mu , sigma ) : return 1 / np . sqrt ( 2 * np . pi ) / sigma * np . exp ( - ( x - mu ) ** 2 / 2. / sigma ** 2 )
0
gaussian distribution python formula
Normalized Gaussian
cosqa-train-599
def gauss_pdf(x, mu, sigma): """Normalized Gaussian""" return 1 / np.sqrt(2 * np.pi) / sigma * np.exp(-(x - mu) ** 2 / 2. / sigma ** 2)