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 get_time ( filename ) : ts = os . stat ( filename ) . st_mtime return datetime . datetime . utcfromtimestamp ( ts )
1
python get last modification time of a file
Get the modified time for a file as a datetime instance
cosqa-train-13100
def get_time(filename): """ Get the modified time for a file as a datetime instance """ ts = os.stat(filename).st_mtime return datetime.datetime.utcfromtimestamp(ts)
def estimate_complexity ( self , x , y , z , n ) : num_calculations = x * y * z * n run_time = num_calculations / 100000 # a 2014 PC does about 100k calcs in a second (guess based on prior logs) return self . show_time_as_short_string ( run_time )
1
determining time complexity in python
calculates a rough guess of runtime based on product of parameters
cosqa-train-13101
def estimate_complexity(self, x,y,z,n): """ calculates a rough guess of runtime based on product of parameters """ num_calculations = x * y * z * n run_time = num_calculations / 100000 # a 2014 PC does about 100k calcs in a second (guess based on prior logs) return self.show_time_as_short_string(run_time)
def dir_modtime ( dpath ) : return max ( os . path . getmtime ( d ) for d , _ , _ in os . walk ( dpath ) )
1
python get last modified directory
Returns the latest modification time of all files / subdirectories in a directory
cosqa-train-13102
def dir_modtime(dpath): """ Returns the latest modification time of all files/subdirectories in a directory """ return max(os.path.getmtime(d) for d, _, _ in os.walk(dpath))
def splitBy ( data , num ) : return [ data [ i : i + num ] for i in range ( 0 , len ( data ) , num ) ]
1
devide elements in a list by a number python
Turn a list to list of list
cosqa-train-13103
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 last_day ( year = _year , month = _month ) : last_day = calendar . monthrange ( year , month ) [ 1 ] return datetime . date ( year = year , month = month , day = last_day )
1
python get last month datetime
get the current month s last day : param year : default to current year : param month : default to current month : return : month s last day
cosqa-train-13104
def last_day(year=_year, month=_month): """ get the current month's last day :param year: default to current year :param month: default to current month :return: month's last day """ last_day = calendar.monthrange(year, month)[1] return datetime.date(year=year, month=month, day=last_day)
def dict_to_numpy_array ( d ) : return fromarrays ( d . values ( ) , np . dtype ( [ ( str ( k ) , v . dtype ) for k , v in d . items ( ) ] ) )
1
different dtypes in array python
Convert a dict of 1d array to a numpy recarray
cosqa-train-13105
def dict_to_numpy_array(d): """ Convert a dict of 1d array to a numpy recarray """ return fromarrays(d.values(), np.dtype([(str(k), v.dtype) for k, v in d.items()]))
def last_day ( year = _year , month = _month ) : last_day = calendar . monthrange ( year , month ) [ 1 ] return datetime . date ( year = year , month = month , day = last_day )
0
python get last of month current year
get the current month s last day : param year : default to current year : param month : default to current month : return : month s last day
cosqa-train-13106
def last_day(year=_year, month=_month): """ get the current month's last day :param year: default to current year :param month: default to current month :return: month's last day """ last_day = calendar.monthrange(year, month)[1] return datetime.date(year=year, month=month, day=last_day)
def get_entity_kind ( self , model_obj ) : model_obj_ctype = ContentType . objects . get_for_model ( self . queryset . model ) return ( u'{0}.{1}' . format ( model_obj_ctype . app_label , model_obj_ctype . model ) , u'{0}' . format ( model_obj_ctype ) )
1
differentiation between name and entity using python
Returns a tuple for a kind name and kind display name of an entity . By default uses the app_label and model of the model object s content type as the kind .
cosqa-train-13107
def get_entity_kind(self, model_obj): """ Returns a tuple for a kind name and kind display name of an entity. By default, uses the app_label and model of the model object's content type as the kind. """ model_obj_ctype = ContentType.objects.get_for_model(self.queryset.model) return (u'{0}.{1}'.format(model_obj_ctype.app_label, model_obj_ctype.model), u'{0}'.format(model_obj_ctype))
def unique_list_dicts ( dlist , key ) : return list ( dict ( ( val [ key ] , val ) for val in dlist ) . values ( ) )
1
python get list of dictionary keys sorted by value
Return a list of dictionaries which are sorted for only unique entries .
cosqa-train-13108
def unique_list_dicts(dlist, key): """Return a list of dictionaries which are sorted for only unique entries. :param dlist: :param key: :return list: """ return list(dict((val[key], val) for val in dlist).values())
def get_known_read_position ( fp , buffered = True ) : buffer_size = io . DEFAULT_BUFFER_SIZE if buffered else 0 return max ( fp . tell ( ) - buffer_size , 0 )
1
differnce between read, readline, in python
Return a position in a file which is known to be read & handled . It assumes a buffered file and streaming processing .
cosqa-train-13109
def get_known_read_position(fp, buffered=True): """ Return a position in a file which is known to be read & handled. It assumes a buffered file and streaming processing. """ buffer_size = io.DEFAULT_BUFFER_SIZE if buffered else 0 return max(fp.tell() - buffer_size, 0)
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
python get list of prime factors
Get all the prime factor of given integer
cosqa-train-13110
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 unfolding ( tens , i ) : return reshape ( tens . full ( ) , ( np . prod ( tens . n [ 0 : ( i + 1 ) ] ) , - 1 ) )
1
dimension a tensor in python
Compute the i - th unfolding of a tensor .
cosqa-train-13111
def unfolding(tens, i): """Compute the i-th unfolding of a tensor.""" return reshape(tens.full(), (np.prod(tens.n[0:(i+1)]), -1))
def mag ( z ) : if isinstance ( z [ 0 ] , np . ndarray ) : return np . array ( list ( map ( np . linalg . norm , z ) ) ) else : return np . linalg . norm ( z )
0
python get magnitude of multidimensional vector
Get the magnitude of a vector .
cosqa-train-13112
def mag(z): """Get the magnitude of a vector.""" if isinstance(z[0], np.ndarray): return np.array(list(map(np.linalg.norm, z))) else: return np.linalg.norm(z)
def should_skip_logging ( func ) : disabled = strtobool ( request . headers . get ( "x-request-nolog" , "false" ) ) return disabled or getattr ( func , SKIP_LOGGING , False )
1
disable python requests logging
Should we skip logging for this handler?
cosqa-train-13113
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 _longest_val_in_column ( self , col ) : try : # +2 is for implicit separator return max ( [ len ( x [ col ] ) for x in self . table if x [ col ] ] ) + 2 except KeyError : logger . error ( "there is no column %r" , col ) raise
0
python get max column lengh in a csv file column
get size of longest value in specific column
cosqa-train-13114
def _longest_val_in_column(self, col): """ get size of longest value in specific column :param col: str, column name :return int """ try: # +2 is for implicit separator return max([len(x[col]) for x in self.table if x[col]]) + 2 except KeyError: logger.error("there is no column %r", col) raise
def disable_cert_validation ( ) : current_context = ssl . _create_default_https_context ssl . _create_default_https_context = ssl . _create_unverified_context try : yield finally : ssl . _create_default_https_context = current_context
1
disable ssl certificate check python
Context manager to temporarily disable certificate validation in the standard SSL library .
cosqa-train-13115
def disable_cert_validation(): """Context manager to temporarily disable certificate validation in the standard SSL library. Note: This should not be used in production code but is sometimes useful for troubleshooting certificate validation issues. By design, the standard SSL library does not provide a way to disable verification of the server side certificate. However, a patch to disable validation is described by the library developers. This context manager allows applying the patch for specific sections of code. """ current_context = ssl._create_default_https_context ssl._create_default_https_context = ssl._create_unverified_context try: yield finally: ssl._create_default_https_context = current_context
def get_memory_usage ( ) : process = psutil . Process ( os . getpid ( ) ) mem = process . memory_info ( ) . rss return mem / ( 1024 * 1024 )
1
python get memory usage of a process on windows
Gets RAM memory usage
cosqa-train-13116
def get_memory_usage(): """Gets RAM memory usage :return: MB of memory used by this process """ process = psutil.Process(os.getpid()) mem = process.memory_info().rss return mem / (1024 * 1024)
def clear_matplotlib_ticks ( self , axis = "both" ) : ax = self . get_axes ( ) plotting . clear_matplotlib_ticks ( ax = ax , axis = axis )
1
disable xaxis tickmarks python
Clears the default matplotlib ticks .
cosqa-train-13117
def clear_matplotlib_ticks(self, axis="both"): """Clears the default matplotlib ticks.""" ax = self.get_axes() plotting.clear_matplotlib_ticks(ax=ax, axis=axis)
def get_method_name ( method ) : name = get_object_name ( method ) if name . startswith ( "__" ) and not name . endswith ( "__" ) : name = "_{0}{1}" . format ( get_object_name ( method . im_class ) , name ) return name
1
python get method name as string
Returns given method name .
cosqa-train-13118
def get_method_name(method): """ Returns given method name. :param method: Method to retrieve the name. :type method: object :return: Method name. :rtype: unicode """ name = get_object_name(method) if name.startswith("__") and not name.endswith("__"): name = "_{0}{1}".format(get_object_name(method.im_class), name) return name
def _take_ownership ( self ) : if self : ptr = cast ( self . value , GIBaseInfo ) _UnrefFinalizer . track ( self , ptr ) self . __owns = True
1
discarding owned python object not allowed without gil
Make the Python instance take ownership of the GIBaseInfo . i . e . unref if the python instance gets gc ed .
cosqa-train-13119
def _take_ownership(self): """Make the Python instance take ownership of the GIBaseInfo. i.e. unref if the python instance gets gc'ed. """ if self: ptr = cast(self.value, GIBaseInfo) _UnrefFinalizer.track(self, ptr) self.__owns = True
def newest_file ( file_iterable ) : return max ( file_iterable , key = lambda fname : os . path . getmtime ( fname ) )
1
python get most recent file containing string
Returns the name of the newest file given an iterable of file names .
cosqa-train-13120
def newest_file(file_iterable): """ Returns the name of the newest file given an iterable of file names. """ return max(file_iterable, key=lambda fname: os.path.getmtime(fname))
async def delete ( self ) : return await self . bot . delete_message ( self . chat . id , self . message_id )
1
discord bot python delete message
Delete this message
cosqa-train-13121
async def delete(self): """ Delete this message :return: bool """ return await self.bot.delete_message(self.chat.id, self.message_id)
def get_month_namedays ( self , month = None ) : if month is None : month = datetime . now ( ) . month return self . NAMEDAYS [ month - 1 ]
1
python get name for a month
Return names as a tuple based on given month . If no month given use current one
cosqa-train-13122
def get_month_namedays(self, month=None): """Return names as a tuple based on given month. If no month given, use current one""" if month is None: month = datetime.now().month return self.NAMEDAYS[month-1]
def get_system_root_directory ( ) : root = os . path . dirname ( __file__ ) root = os . path . dirname ( root ) root = os . path . abspath ( root ) return root
1
display root folder name in python
Get system root directory ( application installed root directory )
cosqa-train-13123
def get_system_root_directory(): """ Get system root directory (application installed root directory) Returns ------- string A full path """ root = os.path.dirname(__file__) root = os.path.dirname(root) root = os.path.abspath(root) return root
def yank ( event ) : event . current_buffer . paste_clipboard_data ( event . cli . clipboard . get_data ( ) , count = event . arg , paste_mode = PasteMode . EMACS )
1
python get notification of clipboard paste
Paste before cursor .
cosqa-train-13124
def yank(event): """ Paste before cursor. """ event.current_buffer.paste_clipboard_data( event.cli.clipboard.get_data(), count=event.arg, paste_mode=PasteMode.EMACS)
def consecutive ( data , stepsize = 1 ) : return np . split ( data , np . where ( np . diff ( data ) != stepsize ) [ 0 ] + 1 )
1
divide data into equal segments in python
Converts array into chunks with consecutive elements of given step size . http : // stackoverflow . com / questions / 7352684 / how - to - find - the - groups - of - consecutive - elements - from - an - array - in - numpy
cosqa-train-13125
def consecutive(data, stepsize=1): """Converts array into chunks with consecutive elements of given step size. http://stackoverflow.com/questions/7352684/how-to-find-the-groups-of-consecutive-elements-from-an-array-in-numpy """ return np.split(data, np.where(np.diff(data) != stepsize)[0] + 1)
def _nth ( arr , n ) : try : return arr . iloc [ n ] except ( KeyError , IndexError ) : return np . nan
1
python get nth element from array
Return the nth value of array
cosqa-train-13126
def _nth(arr, n): """ Return the nth value of array If it is missing return NaN """ try: return arr.iloc[n] except (KeyError, IndexError): return np.nan
def to_json ( obj ) : i = StringIO . StringIO ( ) w = Writer ( i , encoding = 'UTF-8' ) w . write_value ( obj ) return i . getvalue ( )
0
django python json dump
Return a json string representing the python object obj .
cosqa-train-13127
def to_json(obj): """Return a json string representing the python object obj.""" i = StringIO.StringIO() w = Writer(i, encoding='UTF-8') w.write_value(obj) return i.getvalue()
def _jit_pairwise_distances ( pos1 , pos2 ) : n1 = pos1 . shape [ 0 ] n2 = pos2 . shape [ 0 ] D = np . empty ( ( n1 , n2 ) ) for i in range ( n1 ) : for j in range ( n2 ) : D [ i , j ] = np . sqrt ( ( ( pos1 [ i ] - pos2 [ j ] ) ** 2 ) . sum ( ) ) return D
1
python get pairwise distances
Optimized function for calculating the distance between each pair of points in positions1 and positions2 .
cosqa-train-13128
def _jit_pairwise_distances(pos1, pos2): """Optimized function for calculating the distance between each pair of points in positions1 and positions2. Does use python mode as fallback, if a scalar and not an array is given. """ n1 = pos1.shape[0] n2 = pos2.shape[0] D = np.empty((n1, n2)) for i in range(n1): for j in range(n2): D[i, j] = np.sqrt(((pos1[i] - pos2[j])**2).sum()) return D
def _update_globals ( ) : if not sys . platform . startswith ( 'java' ) and sys . platform != 'cli' : return incompatible = 'extract_constant' , 'get_module_constant' for name in incompatible : del globals ( ) [ name ] __all__ . remove ( name )
1
do global python objects get deleted after program exits
Patch the globals to remove the objects not available on some platforms .
cosqa-train-13129
def _update_globals(): """ Patch the globals to remove the objects not available on some platforms. XXX it'd be better to test assertions about bytecode instead. """ if not sys.platform.startswith('java') and sys.platform != 'cli': return incompatible = 'extract_constant', 'get_module_constant' for name in incompatible: del globals()[name] __all__.remove(name)
def url_to_image ( url ) : r = requests . get ( url ) image = StringIO ( r . content ) return image
1
python get png from url
Fetch an image from url and convert it into a Pillow Image object
cosqa-train-13130
def url_to_image(url): """ Fetch an image from url and convert it into a Pillow Image object """ r = requests.get(url) image = StringIO(r.content) return image
def do_exit ( self , arg ) : if self . current : self . current . close ( ) self . resource_manager . close ( ) del self . resource_manager return True
1
do something on program exit python
Exit the shell session .
cosqa-train-13131
def do_exit(self, arg): """Exit the shell session.""" if self.current: self.current.close() self.resource_manager.close() del self.resource_manager return True
def get_content_type ( headers ) : ptype = headers . get ( 'Content-Type' , 'application/octet-stream' ) if ";" in ptype : # split off not needed extension info ptype = ptype . split ( ';' ) [ 0 ] return ptype . strip ( ) . lower ( )
1
python get post content type
Get the MIME type from the Content - Type header value or application / octet - stream if not found .
cosqa-train-13132
def get_content_type (headers): """ Get the MIME type from the Content-Type header value, or 'application/octet-stream' if not found. @return: MIME type @rtype: string """ ptype = headers.get('Content-Type', 'application/octet-stream') if ";" in ptype: # split off not needed extension info ptype = ptype.split(';')[0] return ptype.strip().lower()
def parse ( text , showToc = True ) : p = Parser ( show_toc = showToc ) return p . parse ( text )
1
doctype html parse python
Returns HTML from MediaWiki markup
cosqa-train-13133
def parse(text, showToc=True): """Returns HTML from MediaWiki markup""" p = Parser(show_toc=showToc) return p.parse(text)
def security ( self ) : return { k : v for i in self . pdf . resolvedObjects . items ( ) for k , v in i [ 1 ] . items ( ) }
1
python get properties of pdf file
Print security object information for a pdf document
cosqa-train-13134
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 _string_hash ( s ) : h = 5381 for c in s : h = h * 33 + ord ( c ) return h
1
does hash in python guarantee that uniqueness for string
String hash ( djb2 ) with consistency between py2 / py3 and persistency between runs ( unlike hash ) .
cosqa-train-13135
def _string_hash(s): """String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`).""" h = 5381 for c in s: h = h * 33 + ord(c) return h
def get_property_by_name ( pif , name ) : return next ( ( x for x in pif . properties if x . name == name ) , None )
1
python get propery by name
Get a property by name
cosqa-train-13136
def get_property_by_name(pif, name): """Get a property by name""" return next((x for x in pif.properties if x.name == name), None)
def call_with_context ( func , context , * args ) : return make_context_aware ( func , len ( args ) ) ( * args + ( context , ) )
1
does python allow for missing function args like r
Check if given function has more arguments than given . Call it with context as last argument or without it .
cosqa-train-13137
def call_with_context(func, context, *args): """ Check if given function has more arguments than given. Call it with context as last argument or without it. """ return make_context_aware(func, len(args))(*args + (context,))
def min_depth ( self , root ) : if root is None : return 0 if root . left is not None or root . right is not None : return max ( self . minDepth ( root . left ) , self . minDepth ( root . right ) ) + 1 return min ( self . minDepth ( root . left ) , self . minDepth ( root . right ) ) + 1
0
python get recursion depth
: type root : TreeNode : rtype : int
cosqa-train-13138
def min_depth(self, root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 if root.left is not None or root.right is not None: return max(self.minDepth(root.left), self.minDepth(root.right))+1 return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
def unit_ball_L2 ( shape ) : x = tf . Variable ( tf . zeros ( shape ) ) return constrain_L2 ( x )
1
does tensorflow work with language other than python
A tensorflow variable tranfomed to be constrained in a L2 unit ball .
cosqa-train-13139
def unit_ball_L2(shape): """A tensorflow variable tranfomed to be constrained in a L2 unit ball. EXPERIMENTAL: Do not use for adverserial examples if you need to be confident they are strong attacks. We are not yet confident in this code. """ x = tf.Variable(tf.zeros(shape)) return constrain_L2(x)
def get_screen_resolution ( self ) : widget = QDesktopWidget ( ) geometry = widget . availableGeometry ( widget . primaryScreen ( ) ) return geometry . width ( ) , geometry . height ( )
1
python get screen dimensions
Return the screen resolution of the primary screen .
cosqa-train-13140
def get_screen_resolution(self): """Return the screen resolution of the primary screen.""" widget = QDesktopWidget() geometry = widget.availableGeometry(widget.primaryScreen()) return geometry.width(), geometry.height()
def dot ( self , w ) : return sum ( [ x * y for x , y in zip ( self , w ) ] )
1
dot product using for loop in python
Return the dotproduct between self and another vector .
cosqa-train-13141
def dot(self, w): """Return the dotproduct between self and another vector.""" return sum([x * y for x, y in zip(self, w)])
def get_list_dimensions ( _list ) : if isinstance ( _list , list ) or isinstance ( _list , tuple ) : return [ len ( _list ) ] + get_list_dimensions ( _list [ 0 ] ) return [ ]
1
python get shape of list of lists
Takes a nested list and returns the size of each dimension followed by the element type in the list
cosqa-train-13142
def get_list_dimensions(_list): """ Takes a nested list and returns the size of each dimension followed by the element type in the list """ if isinstance(_list, list) or isinstance(_list, tuple): return [len(_list)] + get_list_dimensions(_list[0]) return []
def enable_ssl ( self , * args , * * kwargs ) : if self . handshake_sent : raise SSLError ( 'can only enable SSL before handshake' ) self . secure = True self . sock = ssl . wrap_socket ( self . sock , * args , * * kwargs )
1
python get ssl wrapped socket
Transforms the regular socket . socket to an ssl . SSLSocket for secure connections . Any arguments are passed to ssl . wrap_socket : http : // docs . python . org / dev / library / ssl . html#ssl . wrap_socket
cosqa-train-13143
def enable_ssl(self, *args, **kwargs): """ Transforms the regular socket.socket to an ssl.SSLSocket for secure connections. Any arguments are passed to ssl.wrap_socket: http://docs.python.org/dev/library/ssl.html#ssl.wrap_socket """ if self.handshake_sent: raise SSLError('can only enable SSL before handshake') self.secure = True self.sock = ssl.wrap_socket(self.sock, *args, **kwargs)
def hline ( self , x , y , width , color ) : self . rect ( x , y , width , 1 , color , fill = True )
1
draw a line in python
Draw a horizontal line up to a given length .
cosqa-train-13144
def hline(self, x, y, width, color): """Draw a horizontal line up to a given length.""" self.rect(x, y, width, 1, color, fill=True)
def _extract_traceback ( start ) : tb = sys . exc_info ( ) [ 2 ] for i in range ( start ) : tb = tb . tb_next return _parse_traceback ( tb )
1
python get stacktrace from sys
SNAGGED FROM traceback . py
cosqa-train-13145
def _extract_traceback(start): """ SNAGGED FROM traceback.py RETURN list OF dicts DESCRIBING THE STACK TRACE """ tb = sys.exc_info()[2] for i in range(start): tb = tb.tb_next return _parse_traceback(tb)
def print_display_png ( o ) : s = latex ( o , mode = 'plain' ) s = s . strip ( '$' ) # As matplotlib does not support display style, dvipng backend is # used here. png = latex_to_png ( '$$%s$$' % s , backend = 'dvipng' ) return png
1
drawing image with python in latex
A function to display sympy expression using display style LaTeX in PNG .
cosqa-train-13146
def print_display_png(o): """ A function to display sympy expression using display style LaTeX in PNG. """ s = latex(o, mode='plain') s = s.strip('$') # As matplotlib does not support display style, dvipng backend is # used here. png = latex_to_png('$$%s$$' % s, backend='dvipng') return png
async def json_or_text ( response ) : text = await response . text ( ) if response . headers [ 'Content-Type' ] == 'application/json; charset=utf-8' : return json . loads ( text ) return text
1
python get text of response
Turns response into a properly formatted json or text object
cosqa-train-13147
async def json_or_text(response): """Turns response into a properly formatted json or text object""" text = await response.text() if response.headers['Content-Type'] == 'application/json; charset=utf-8': return json.loads(text) return text
def del_Unnamed ( df ) : cols_del = [ c for c in df . columns if 'Unnamed' in c ] return df . drop ( cols_del , axis = 1 )
1
dropping columns with wild card in column name from python data frame
Deletes all the unnamed columns
cosqa-train-13148
def del_Unnamed(df): """ Deletes all the unnamed columns :param df: pandas dataframe """ cols_del=[c for c in df.columns if 'Unnamed' in c] return df.drop(cols_del,axis=1)
def get_month_start ( day = None ) : day = add_timezone ( day or datetime . date . today ( ) ) return day . replace ( day = 1 )
1
python get the first day of current month
Returns the first day of the given month .
cosqa-train-13149
def get_month_start(day=None): """Returns the first day of the given month.""" day = add_timezone(day or datetime.date.today()) return day.replace(day=1)
def __call__ ( self , * args , * * kwargs ) : kwargs [ "mongokat_collection" ] = self return self . document_class ( * args , * * kwargs )
1
dynamically create documents python mongoegine
Instanciates a new * Document * from this collection
cosqa-train-13150
def __call__(self, *args, **kwargs): """ Instanciates a new *Document* from this collection """ kwargs["mongokat_collection"] = self return self.document_class(*args, **kwargs)
def threadid ( self ) : current = self . thread . ident main = get_main_thread ( ) if main is None : return current else : return current if current != main . ident else None
1
python get the id of the current thread
Current thread ident . If current thread is main thread then it returns None .
cosqa-train-13151
def threadid(self): """ Current thread ident. If current thread is main thread then it returns ``None``. :type: int or None """ current = self.thread.ident main = get_main_thread() if main is None: return current else: return current if current != main.ident else None
def encode_batch ( self , inputBatch ) : X = inputBatch encode = self . encode Y = np . array ( [ encode ( x ) for x in X ] ) return Y
0
each input in an array, python
Encodes a whole batch of input arrays without learning .
cosqa-train-13152
def encode_batch(self, inputBatch): """Encodes a whole batch of input arrays, without learning.""" X = inputBatch encode = self.encode Y = np.array([ encode(x) for x in X]) return Y
def tail ( self , n = 10 ) : with cython_context ( ) : return SArray ( _proxy = self . __proxy__ . tail ( n ) )
1
python get the last n from array
Get an SArray that contains the last n elements in the SArray .
cosqa-train-13153
def tail(self, n=10): """ Get an SArray that contains the last n elements in the SArray. Parameters ---------- n : int The number of elements to fetch Returns ------- out : SArray A new SArray which contains the last n rows of the current SArray. """ with cython_context(): return SArray(_proxy=self.__proxy__.tail(n))
def lmx_h1k_f64k ( ) : hparams = lmx_base ( ) hparams . hidden_size = 1024 hparams . filter_size = 65536 hparams . batch_size = 2048 return hparams
1
early stopping use keras lstm in python
HParams for training languagemodel_lm1b32k_packed . 880M Params .
cosqa-train-13154
def lmx_h1k_f64k(): """HParams for training languagemodel_lm1b32k_packed. 880M Params.""" hparams = lmx_base() hparams.hidden_size = 1024 hparams.filter_size = 65536 hparams.batch_size = 2048 return hparams
def check_output ( args , env = None , sp = subprocess ) : log . debug ( 'calling %s with env %s' , args , env ) output = sp . check_output ( args = args , env = env ) log . debug ( 'output: %r' , output ) return output
1
python get the stdout from external command
Call an external binary and return its stdout .
cosqa-train-13155
def check_output(args, env=None, sp=subprocess): """Call an external binary and return its stdout.""" log.debug('calling %s with env %s', args, env) output = sp.check_output(args=args, env=env) log.debug('output: %r', output) return output
def a2s ( a ) : s = np . zeros ( ( 6 , ) , 'f' ) # make the a matrix for i in range ( 3 ) : s [ i ] = a [ i ] [ i ] s [ 3 ] = a [ 0 ] [ 1 ] s [ 4 ] = a [ 1 ] [ 2 ] s [ 5 ] = a [ 0 ] [ 2 ] return s
1
easiest way to create matrix in python
convert 3 3 a matrix to 6 element s list ( see Tauxe 1998 )
cosqa-train-13156
def a2s(a): """ convert 3,3 a matrix to 6 element "s" list (see Tauxe 1998) """ s = np.zeros((6,), 'f') # make the a matrix for i in range(3): s[i] = a[i][i] s[3] = a[0][1] s[4] = a[1][2] s[5] = a[0][2] return s
def convert_2_utc ( self , datetime_ , timezone ) : datetime_ = self . tz_mapper [ timezone ] . localize ( datetime_ ) return datetime_ . astimezone ( pytz . UTC )
1
python get timezone offset for eastern
convert to datetime to UTC offset .
cosqa-train-13157
def convert_2_utc(self, datetime_, timezone): """convert to datetime to UTC offset.""" datetime_ = self.tz_mapper[timezone].localize(datetime_) return datetime_.astimezone(pytz.UTC)
def tokenize_list ( self , text ) : return [ self . get_record_token ( record ) for record in self . analyze ( text ) ]
0
elasticsearch python tokenize results
Split a text into separate words .
cosqa-train-13158
def tokenize_list(self, text): """ Split a text into separate words. """ return [self.get_record_token(record) for record in self.analyze(text)]
def now ( self ) : if self . use_utc : return datetime . datetime . utcnow ( ) else : return datetime . datetime . now ( )
1
python get today's date utc
Return a : py : class : datetime . datetime instance representing the current time .
cosqa-train-13159
def now(self): """ Return a :py:class:`datetime.datetime` instance representing the current time. :rtype: :py:class:`datetime.datetime` """ if self.use_utc: return datetime.datetime.utcnow() else: return datetime.datetime.now()
def unpunctuate ( s , * , char_blacklist = string . punctuation ) : # remove punctuation s = "" . join ( c for c in s if c not in char_blacklist ) # remove consecutive spaces return " " . join ( filter ( None , s . split ( " " ) ) )
1
eliminating spaces in strings python
Remove punctuation from string s .
cosqa-train-13160
def unpunctuate(s, *, char_blacklist=string.punctuation): """ Remove punctuation from string s. """ # remove punctuation s = "".join(c for c in s if c not in char_blacklist) # remove consecutive spaces return " ".join(filter(None, s.split(" ")))
def accuracy ( conf_matrix ) : total , correct = 0.0 , 0.0 for true_response , guess_dict in conf_matrix . items ( ) : for guess , count in guess_dict . items ( ) : if true_response == guess : correct += count total += count return correct / total
1
python get true positives from confusion matrix
Given a confusion matrix returns the accuracy . Accuracy Definition : http : // research . ics . aalto . fi / events / eyechallenge2005 / evaluation . shtml
cosqa-train-13161
def accuracy(conf_matrix): """ Given a confusion matrix, returns the accuracy. Accuracy Definition: http://research.ics.aalto.fi/events/eyechallenge2005/evaluation.shtml """ total, correct = 0.0, 0.0 for true_response, guess_dict in conf_matrix.items(): for guess, count in guess_dict.items(): if true_response == guess: correct += count total += count return correct/total
def to_binary ( s , encoding = 'utf8' ) : if PY3 : # pragma: no cover return s if isinstance ( s , binary_type ) else binary_type ( s , encoding = encoding ) return binary_type ( s )
0
encoding a string to binary in python
Portable cast function .
cosqa-train-13162
def to_binary(s, encoding='utf8'): """Portable cast function. In python 2 the ``str`` function which is used to coerce objects to bytes does not accept an encoding argument, whereas python 3's ``bytes`` function requires one. :param s: object to be converted to binary_type :return: binary_type instance, representing s. """ if PY3: # pragma: no cover return s if isinstance(s, binary_type) else binary_type(s, encoding=encoding) return binary_type(s)
def get_value ( key , obj , default = missing ) : if isinstance ( key , int ) : return _get_value_for_key ( key , obj , default ) return _get_value_for_keys ( key . split ( '.' ) , obj , default )
1
python get value from dictionary by key with default value
Helper for pulling a keyed value off various types of objects
cosqa-train-13163
def get_value(key, obj, default=missing): """Helper for pulling a keyed value off various types of objects""" if isinstance(key, int): return _get_value_for_key(key, obj, default) return _get_value_for_keys(key.split('.'), obj, default)
def getvariable ( name ) : import inspect fr = inspect . currentframe ( ) try : while fr : fr = fr . f_back vars = fr . f_locals if name in vars : return vars [ name ] except : pass return None
1
python get variable by name locals globals
Get the value of a local variable somewhere in the call stack .
cosqa-train-13164
def getvariable(name): """Get the value of a local variable somewhere in the call stack.""" import inspect fr = inspect.currentframe() try: while fr: fr = fr.f_back vars = fr.f_locals if name in vars: return vars[name] except: pass return None
def restore_image_options ( cli , image , options ) : dockerfile = io . StringIO ( ) dockerfile . write ( u'FROM {image}\nCMD {cmd}' . format ( image = image , cmd = json . dumps ( options [ 'cmd' ] ) ) ) if options [ 'entrypoint' ] : dockerfile . write ( '\nENTRYPOINT {}' . format ( json . dumps ( options [ 'entrypoint' ] ) ) ) cli . build ( tag = image , fileobj = dockerfile )
1
environment variables are not recognized in docker entrypoint python file
Restores CMD and ENTRYPOINT values of the image
cosqa-train-13165
def restore_image_options(cli, image, options): """ Restores CMD and ENTRYPOINT values of the image This is needed because we force the overwrite of ENTRYPOINT and CMD in the `run_code_in_container` function, to be able to run the code in the container, through /bin/bash. """ dockerfile = io.StringIO() dockerfile.write(u'FROM {image}\nCMD {cmd}'.format( image=image, cmd=json.dumps(options['cmd']))) if options['entrypoint']: dockerfile.write( '\nENTRYPOINT {}'.format(json.dumps(options['entrypoint']))) cli.build(tag=image, fileobj=dockerfile)
def getSystemVariable ( self , remote , name ) : if self . _server is not None : return self . _server . getSystemVariable ( remote , name )
1
python get variable from another method
Get single system variable from CCU / Homegear
cosqa-train-13166
def getSystemVariable(self, remote, name): """Get single system variable from CCU / Homegear""" if self._server is not None: return self._server.getSystemVariable(remote, name)
def session_to_epoch ( timestamp ) : utc_timetuple = datetime . strptime ( timestamp , SYNERGY_SESSION_PATTERN ) . replace ( tzinfo = None ) . utctimetuple ( ) return calendar . timegm ( utc_timetuple )
1
epoch converter python specific zone
converts Synergy Timestamp for session to UTC zone seconds since epoch
cosqa-train-13167
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 branches ( self ) : result = self . git ( self . default + [ 'branch' , '-a' , '--no-color' ] ) return [ l . strip ( ' *\n' ) for l in result . split ( '\n' ) if l . strip ( ' *\n' ) ]
1
python git all branches
All branches in a list
cosqa-train-13168
def branches(self): """All branches in a list""" result = self.git(self.default + ['branch', '-a', '--no-color']) return [l.strip(' *\n') for l in result.split('\n') if l.strip(' *\n')]
def get_sparse_matrix_keys ( session , key_table ) : return session . query ( key_table ) . order_by ( key_table . name ) . all ( )
0
epython example of sorted key
Return a list of keys for the sparse matrix .
cosqa-train-13169
def get_sparse_matrix_keys(session, key_table): """Return a list of keys for the sparse matrix.""" return session.query(key_table).order_by(key_table.name).all()
def case_us2mc ( x ) : return re . sub ( r'_([a-z])' , lambda m : ( m . group ( 1 ) . upper ( ) ) , x )
1
python githum change string to lower case
underscore to mixed case notation
cosqa-train-13170
def case_us2mc(x): """ underscore to mixed case notation """ return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), x)
def rdist ( x , y ) : result = 0.0 for i in range ( x . shape [ 0 ] ) : result += ( x [ i ] - y [ i ] ) ** 2 return result
1
euclidean distance of nd array algorithm python
Reduced Euclidean distance .
cosqa-train-13171
def rdist(x, y): """Reduced Euclidean distance. Parameters ---------- x: array of shape (embedding_dim,) y: array of shape (embedding_dim,) Returns ------- The squared euclidean distance between x and y """ result = 0.0 for i in range(x.shape[0]): result += (x[i] - y[i]) ** 2 return result
def _to_hours_mins_secs ( time_taken ) : mins , secs = divmod ( time_taken , 60 ) hours , mins = divmod ( mins , 60 ) return hours , mins , secs
1
python given seconds (int) calculate hours minutes and seconds
Convert seconds to hours mins and seconds .
cosqa-train-13172
def _to_hours_mins_secs(time_taken): """Convert seconds to hours, mins, and seconds.""" mins, secs = divmod(time_taken, 60) hours, mins = divmod(mins, 60) return hours, mins, secs
def euclidean ( c1 , c2 ) : diffs = ( ( i - j ) for i , j in zip ( c1 , c2 ) ) return sum ( x * x for x in diffs )
1
euclidean distance python function
Square of the euclidean distance
cosqa-train-13173
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 restore_default_settings ( ) : global __DEFAULTS __DEFAULTS . CACHE_DIR = defaults . CACHE_DIR __DEFAULTS . SET_SEED = defaults . SET_SEED __DEFAULTS . SEED = defaults . SEED logging . info ( 'Settings reverted to their default values.' )
1
python global variable reseting to original value
Restore settings to default values .
cosqa-train-13174
def restore_default_settings(): """ Restore settings to default values. """ global __DEFAULTS __DEFAULTS.CACHE_DIR = defaults.CACHE_DIR __DEFAULTS.SET_SEED = defaults.SET_SEED __DEFAULTS.SEED = defaults.SEED logging.info('Settings reverted to their default values.')
def get_all_attributes ( klass_or_instance ) : pairs = list ( ) for attr , value in inspect . getmembers ( klass_or_instance , lambda x : not inspect . isroutine ( x ) ) : if not ( attr . startswith ( "__" ) or attr . endswith ( "__" ) ) : pairs . append ( ( attr , value ) ) return pairs
1
examble of static methods in python
Get all attribute members ( attribute property style method ) .
cosqa-train-13175
def get_all_attributes(klass_or_instance): """Get all attribute members (attribute, property style method). """ pairs = list() for attr, value in inspect.getmembers( klass_or_instance, lambda x: not inspect.isroutine(x)): if not (attr.startswith("__") or attr.endswith("__")): pairs.append((attr, value)) return pairs
def load_yaml ( filepath ) : with open ( filepath ) as f : txt = f . read ( ) return yaml . load ( txt )
1
python good way to load a yaml file
Convenience function for loading yaml - encoded data from disk .
cosqa-train-13176
def load_yaml(filepath): """Convenience function for loading yaml-encoded data from disk.""" with open(filepath) as f: txt = f.read() return yaml.load(txt)
def query_proc_row ( procname , args = ( ) , factory = None ) : for row in query_proc ( procname , args , factory ) : return row return None
1
execute a stored procedure in python
Execute a stored procedure . Returns the first row of the result set or None .
cosqa-train-13177
def query_proc_row(procname, args=(), factory=None): """ Execute a stored procedure. Returns the first row of the result set, or `None`. """ for row in query_proc(procname, args, factory): return row return None
def _check_graphviz_available ( output_format ) : try : subprocess . call ( [ "dot" , "-V" ] , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) except OSError : print ( "The output format '%s' is currently not available.\n" "Please install 'Graphviz' to have other output formats " "than 'dot' or 'vcg'." % output_format ) sys . exit ( 32 )
1
python graphviz not found
check if we need graphviz for different output format
cosqa-train-13178
def _check_graphviz_available(output_format): """check if we need graphviz for different output format""" try: subprocess.call(["dot", "-V"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError: print( "The output format '%s' is currently not available.\n" "Please install 'Graphviz' to have other output formats " "than 'dot' or 'vcg'." % output_format ) sys.exit(32)
def load_files ( files ) : for py_file in files : LOG . debug ( "exec %s" , py_file ) execfile ( py_file , globals ( ) , locals ( ) )
1
execute python files simultaneously from a single python file
Load and execute a python file .
cosqa-train-13179
def load_files(files): """Load and execute a python file.""" for py_file in files: LOG.debug("exec %s", py_file) execfile(py_file, globals(), locals())
def table_width ( self ) : outer_widths = max_dimensions ( self . table_data , self . padding_left , self . padding_right ) [ 2 ] outer_border = 2 if self . outer_border else 0 inner_border = 1 if self . inner_column_border else 0 return table_width ( outer_widths , outer_border , inner_border )
1
python gridtablebase column width
Return the width of the table including padding and borders .
cosqa-train-13180
def table_width(self): """Return the width of the table including padding and borders.""" outer_widths = max_dimensions(self.table_data, self.padding_left, self.padding_right)[2] outer_border = 2 if self.outer_border else 0 inner_border = 1 if self.inner_column_border else 0 return table_width(outer_widths, outer_border, inner_border)
def to_dotfile ( G : nx . DiGraph , filename : str ) : A = to_agraph ( G ) A . write ( filename )
1
export a graph python to a file
Output a networkx graph to a DOT file .
cosqa-train-13181
def to_dotfile(G: nx.DiGraph, filename: str): """ Output a networkx graph to a DOT file. """ A = to_agraph(G) A.write(filename)
def get_window ( self ) : x = self while not x . _parent == None and not isinstance ( x . _parent , Window ) : x = x . _parent return x . _parent
1
python gtk get parent window of a widget
Returns the object s parent window . Returns None if no window found .
cosqa-train-13182
def get_window(self): """ Returns the object's parent window. Returns None if no window found. """ x = self while not x._parent == None and \ not isinstance(x._parent, Window): x = x._parent return x._parent
def _parse ( self , date_str , format = '%Y-%m-%d' ) : rv = pd . to_datetime ( date_str , format = format ) if hasattr ( rv , 'to_pydatetime' ) : rv = rv . to_pydatetime ( ) return rv
0
extract date from string python with strpfromat
helper function for parsing FRED date string into datetime
cosqa-train-13183
def _parse(self, date_str, format='%Y-%m-%d'): """ helper function for parsing FRED date string into datetime """ rv = pd.to_datetime(date_str, format=format) if hasattr(rv, 'to_pydatetime'): rv = rv.to_pydatetime() return rv
def OnMove ( self , event ) : # Store window position in config position = self . main_window . GetScreenPositionTuple ( ) config [ "window_position" ] = repr ( position )
1
python gui move window location
Main window move event
cosqa-train-13184
def OnMove(self, event): """Main window move event""" # Store window position in config position = self.main_window.GetScreenPositionTuple() config["window_position"] = repr(position)
def correlation_2D ( image ) : # Take the fourier transform of the image. F1 = fftpack . fft2 ( image ) # Now shift the quadrants around so that low spatial frequencies are in # the center of the 2D fourier transformed image. F2 = fftpack . fftshift ( F1 ) # Calculate a 2D power spectrum psd2D = np . abs ( F2 ) # Calculate the azimuthally averaged 1D power spectrum psd1D = analysis_util . azimuthalAverage ( psd2D ) return psd1D , psd2D
1
extract even fourier components from an image python
cosqa-train-13185
def correlation_2D(image): """ :param image: 2d image :return: psd1D, psd2D """ # Take the fourier transform of the image. F1 = fftpack.fft2(image) # Now shift the quadrants around so that low spatial frequencies are in # the center of the 2D fourier transformed image. F2 = fftpack.fftshift(F1) # Calculate a 2D power spectrum psd2D = np.abs(F2) # Calculate the azimuthally averaged 1D power spectrum psd1D = analysis_util.azimuthalAverage(psd2D) return psd1D, psd2D
def is_gzipped_fastq ( file_name ) : _ , ext = os . path . splitext ( file_name ) return file_name . endswith ( ".fastq.gz" ) or file_name . endswith ( ".fq.gz" )
1
python gzip test if a gzip file is valid
Determine whether indicated file appears to be a gzipped FASTQ .
cosqa-train-13186
def is_gzipped_fastq(file_name): """ Determine whether indicated file appears to be a gzipped FASTQ. :param str file_name: Name/path of file to check as gzipped FASTQ. :return bool: Whether indicated file appears to be in gzipped FASTQ format. """ _, ext = os.path.splitext(file_name) return file_name.endswith(".fastq.gz") or file_name.endswith(".fq.gz")
def get_least_distinct_words ( vocab , topic_word_distrib , doc_topic_distrib , doc_lengths , n = None ) : return _words_by_distinctiveness_score ( vocab , topic_word_distrib , doc_topic_distrib , doc_lengths , n , least_to_most = True )
1
extract only words from topics without probability in topic modeling in python
Order the words from vocab by distinctiveness score ( Chuang et al . 2012 ) from least to most distinctive . Optionally only return the n least distinctive words .
cosqa-train-13187
def get_least_distinct_words(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None): """ Order the words from `vocab` by "distinctiveness score" (Chuang et al. 2012) from least to most distinctive. Optionally only return the `n` least distinctive words. J. Chuang, C. Manning, J. Heer 2012: "Termite: Visualization Techniques for Assessing Textual Topic Models" """ return _words_by_distinctiveness_score(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n, least_to_most=True)
def open_hdf5 ( filename , mode = 'r' ) : if isinstance ( filename , ( h5py . Group , h5py . Dataset ) ) : return filename if isinstance ( filename , FILE_LIKE ) : return h5py . File ( filename . name , mode ) return h5py . File ( filename , mode )
0
python h5py check if file is open
Wrapper to open a : class : h5py . File from disk gracefully handling a few corner cases
cosqa-train-13188
def open_hdf5(filename, mode='r'): """Wrapper to open a :class:`h5py.File` from disk, gracefully handling a few corner cases """ if isinstance(filename, (h5py.Group, h5py.Dataset)): return filename if isinstance(filename, FILE_LIKE): return h5py.File(filename.name, mode) return h5py.File(filename, mode)
def load_fasta_file ( filename ) : with open ( filename , "r" ) as handle : records = list ( SeqIO . parse ( handle , "fasta" ) ) return records
1
fasta file parsing biopython to get sequence only
Load a FASTA file and return the sequences as a list of SeqRecords
cosqa-train-13189
def load_fasta_file(filename): """Load a FASTA file and return the sequences as a list of SeqRecords Args: filename (str): Path to the FASTA file to load Returns: list: list of all sequences in the FASTA file as Biopython SeqRecord objects """ with open(filename, "r") as handle: records = list(SeqIO.parse(handle, "fasta")) return records
def open_hdf5 ( filename , mode = 'r' ) : if isinstance ( filename , ( h5py . Group , h5py . Dataset ) ) : return filename if isinstance ( filename , FILE_LIKE ) : return h5py . File ( filename . name , mode ) return h5py . File ( filename , mode )
0
python h5py open not closing
Wrapper to open a : class : h5py . File from disk gracefully handling a few corner cases
cosqa-train-13190
def open_hdf5(filename, mode='r'): """Wrapper to open a :class:`h5py.File` from disk, gracefully handling a few corner cases """ if isinstance(filename, (h5py.Group, h5py.Dataset)): return filename if isinstance(filename, FILE_LIKE): return h5py.File(filename.name, mode) return h5py.File(filename, mode)
def draw_image ( self , ax , image ) : self . renderer . draw_image ( imdata = utils . image_to_base64 ( image ) , extent = image . get_extent ( ) , coordinates = "data" , style = { "alpha" : image . get_alpha ( ) , "zorder" : image . get_zorder ( ) } , mplobj = image )
1
fastest way to render dynamic bitmap graphics python
Process a matplotlib image object and call renderer . draw_image
cosqa-train-13191
def draw_image(self, ax, image): """Process a matplotlib image object and call renderer.draw_image""" self.renderer.draw_image(imdata=utils.image_to_base64(image), extent=image.get_extent(), coordinates="data", style={"alpha": image.get_alpha(), "zorder": image.get_zorder()}, mplobj=image)
def hamming ( s , t ) : if len ( s ) != len ( t ) : raise ValueError ( 'Hamming distance needs strings of equal length.' ) return sum ( s_ != t_ for s_ , t_ in zip ( s , t ) )
1
python hamming distance between columns of strings
Calculate the Hamming distance between two strings . From Wikipedia article : Iterative with two matrix rows .
cosqa-train-13192
def hamming(s, t): """ Calculate the Hamming distance between two strings. From Wikipedia article: Iterative with two matrix rows. :param s: string 1 :type s: str :param t: string 2 :type s: str :return: Hamming distance :rtype: float """ if len(s) != len(t): raise ValueError('Hamming distance needs strings of equal length.') return sum(s_ != t_ for s_, t_ in zip(s, t))
def ffmpeg_version ( ) : cmd = [ 'ffmpeg' , '-version' ] output = sp . check_output ( cmd ) aac_codecs = [ x for x in output . splitlines ( ) if "ffmpeg version " in str ( x ) ] [ 0 ] hay = aac_codecs . decode ( 'ascii' ) match = re . findall ( r'ffmpeg version (\d+\.)?(\d+\.)?(\*|\d+)' , hay ) if match : return "" . join ( match [ 0 ] ) else : return None
1
ffmpeg not working with python
Returns the available ffmpeg version
cosqa-train-13193
def ffmpeg_version(): """Returns the available ffmpeg version Returns ---------- version : str version number as string """ cmd = [ 'ffmpeg', '-version' ] output = sp.check_output(cmd) aac_codecs = [ x for x in output.splitlines() if "ffmpeg version " in str(x) ][0] hay = aac_codecs.decode('ascii') match = re.findall(r'ffmpeg version (\d+\.)?(\d+\.)?(\*|\d+)', hay) if match: return "".join(match[0]) else: return None
def hamming ( s , t ) : if len ( s ) != len ( t ) : raise ValueError ( 'Hamming distance needs strings of equal length.' ) return sum ( s_ != t_ for s_ , t_ in zip ( s , t ) )
1
python hamming distance string
Calculate the Hamming distance between two strings . From Wikipedia article : Iterative with two matrix rows .
cosqa-train-13194
def hamming(s, t): """ Calculate the Hamming distance between two strings. From Wikipedia article: Iterative with two matrix rows. :param s: string 1 :type s: str :param t: string 2 :type s: str :return: Hamming distance :rtype: float """ if len(s) != len(t): raise ValueError('Hamming distance needs strings of equal length.') return sum(s_ != t_ for s_, t_ in zip(s, t))
def scaled_fft ( fft , scale = 1.0 ) : data = np . zeros ( len ( fft ) ) for i , v in enumerate ( fft ) : data [ i ] = scale * ( i * v ) / NUM_SAMPLES return data
0
fft python irregular spaced data
Produces a nicer graph I m not sure if this is correct
cosqa-train-13195
def scaled_fft(fft, scale=1.0): """ Produces a nicer graph, I'm not sure if this is correct """ data = np.zeros(len(fft)) for i, v in enumerate(fft): data[i] = scale * (i * v) / NUM_SAMPLES return data
def _get_file_sha1 ( file ) : bits = file . read ( ) file . seek ( 0 ) h = hashlib . new ( 'sha1' , bits ) . hexdigest ( ) return h
1
python hashlib calc sha1 of file
Return the SHA1 hash of the given a file - like object as file . This will seek the file back to 0 when it s finished .
cosqa-train-13196
def _get_file_sha1(file): """Return the SHA1 hash of the given a file-like object as ``file``. This will seek the file back to 0 when it's finished. """ bits = file.read() file.seek(0) h = hashlib.new('sha1', bits).hexdigest() return h
def normalize_field ( self , value ) : if self . default is not None : if value is None or value == '' : value = self . default return value
1
field default with python
Method that must transform the value from string Ex : if the expected type is int it should return int ( self . _attr )
cosqa-train-13197
def normalize_field(self, value): """ Method that must transform the value from string Ex: if the expected type is int, it should return int(self._attr) """ if self.default is not None: if value is None or value == '': value = self.default return value
def exists ( self , path ) : import hdfs try : self . client . status ( path ) return True except hdfs . util . HdfsError as e : if str ( e ) . startswith ( 'File does not exist: ' ) : return False else : raise e
1
python hdfs detect file exist
Returns true if the path exists and false otherwise .
cosqa-train-13198
def exists(self, path): """ Returns true if the path exists and false otherwise. """ import hdfs try: self.client.status(path) return True except hdfs.util.HdfsError as e: if str(e).startswith('File does not exist: '): return False else: raise e
def is_integer ( obj ) : if PYTHON3 : return isinstance ( obj , int ) return isinstance ( obj , ( int , long ) )
1
figure out data type of an object python
Is this an integer .
cosqa-train-13199
def is_integer(obj): """Is this an integer. :param object obj: :return: """ if PYTHON3: return isinstance(obj, int) return isinstance(obj, (int, long))