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 _skip_section ( self ) : self . _last = self . _f . readline ( ) while len ( self . _last ) > 0 and len ( self . _last [ 0 ] . strip ( ) ) == 0 : self . _last = self . _f . readline ( )
1
python how to skip subsequent lines
Skip a section
cosqa-train-18400
def _skip_section(self): """Skip a section""" self._last = self._f.readline() while len(self._last) > 0 and len(self._last[0].strip()) == 0: self._last = self._f.readline()
def find_first ( pattern : str , path : str ) -> str : try : return find ( pattern , path ) [ 0 ] except IndexError : log . critical ( '''Couldn't find "{}" in "{}"''' , pattern , path ) raise
1
get first file in a folder python
Finds first file in path whose filename matches pattern ( via : func : fnmatch . fnmatch ) or raises : exc : IndexError .
cosqa-train-18401
def find_first(pattern: str, path: str) -> str: """ Finds first file in ``path`` whose filename matches ``pattern`` (via :func:`fnmatch.fnmatch`), or raises :exc:`IndexError`. """ try: return find(pattern, path)[0] except IndexError: log.critical('''Couldn't find "{}" in "{}"''', pattern, path) raise
def _sum_cycles_from_tokens ( self , tokens : List [ str ] ) -> int : return sum ( ( int ( self . _nonnumber_pattern . sub ( '' , t ) ) for t in tokens ) )
1
how to count a list of tokens in python
Sum the total number of cycles over a list of tokens .
cosqa-train-18402
def _sum_cycles_from_tokens(self, tokens: List[str]) -> int: """Sum the total number of cycles over a list of tokens.""" return sum((int(self._nonnumber_pattern.sub('', t)) for t in tokens))
def cmd_dot ( conf : Config ) : build_context = BuildContext ( conf ) populate_targets_graph ( build_context , conf ) if conf . output_dot_file is None : write_dot ( build_context , conf , sys . stdout ) else : with open ( conf . output_dot_file , 'w' ) as out_file : write_dot ( build_context , conf , out_file )
1
python graphviz create dot file
Print out a neat targets dependency tree based on requested targets .
cosqa-train-18403
def cmd_dot(conf: Config): """Print out a neat targets dependency tree based on requested targets. Use graphviz to render the dot file, e.g.: > ybt dot :foo :bar | dot -Tpng -o graph.png """ build_context = BuildContext(conf) populate_targets_graph(build_context, conf) if conf.output_dot_file is None: write_dot(build_context, conf, sys.stdout) else: with open(conf.output_dot_file, 'w') as out_file: write_dot(build_context, conf, out_file)
def _mid ( pt1 , pt2 ) : ( x0 , y0 ) , ( x1 , y1 ) = pt1 , pt2 return 0.5 * ( x0 + x1 ) , 0.5 * ( y0 + y1 )
0
python midpoint of two numbers
( Point Point ) - > Point Return the point that lies in between the two input points .
cosqa-train-18404
def _mid(pt1, pt2): """ (Point, Point) -> Point Return the point that lies in between the two input points. """ (x0, y0), (x1, y1) = pt1, pt2 return 0.5 * (x0 + x1), 0.5 * (y0 + y1)
def _prm_get_longest_stringsize ( string_list ) : maxlength = 1 for stringar in string_list : if isinstance ( stringar , np . ndarray ) : if stringar . ndim > 0 : for string in stringar . ravel ( ) : maxlength = max ( len ( string ) , maxlength ) else : maxlength = max ( len ( stringar . tolist ( ) ) , maxlength ) else : maxlength = max ( len ( stringar ) , maxlength ) # Make the string Col longer than needed in order to allow later on slightly larger strings return int ( maxlength * 1.5 )
1
how to get longest string in an array of string python
Returns the longest string size for a string entry across data .
cosqa-train-18405
def _prm_get_longest_stringsize(string_list): """ Returns the longest string size for a string entry across data.""" maxlength = 1 for stringar in string_list: if isinstance(stringar, np.ndarray): if stringar.ndim > 0: for string in stringar.ravel(): maxlength = max(len(string), maxlength) else: maxlength = max(len(stringar.tolist()), maxlength) else: maxlength = max(len(stringar), maxlength) # Make the string Col longer than needed in order to allow later on slightly larger strings return int(maxlength * 1.5)
def str_to_time ( time_str : str ) -> datetime . datetime : pieces : Any = [ int ( piece ) for piece in time_str . split ( '-' ) ] return datetime . datetime ( * pieces )
0
python read datetime from text string
Convert human readable string to datetime . datetime .
cosqa-train-18406
def str_to_time(time_str: str) -> datetime.datetime: """ Convert human readable string to datetime.datetime. """ pieces: Any = [int(piece) for piece in time_str.split('-')] return datetime.datetime(*pieces)
def de_duplicate ( items ) : result = [ ] for item in items : if item not in result : result . append ( item ) return result
0
python deleat duplicates in list
Remove any duplicate item preserving order
cosqa-train-18407
def de_duplicate(items): """Remove any duplicate item, preserving order >>> de_duplicate([1, 2, 1, 2]) [1, 2] """ result = [] for item in items: if item not in result: result.append(item) return result
def long_substr ( data ) : substr = '' if len ( data ) > 1 and len ( data [ 0 ] ) > 0 : for i in range ( len ( data [ 0 ] ) ) : for j in range ( len ( data [ 0 ] ) - i + 1 ) : if j > len ( substr ) and all ( data [ 0 ] [ i : i + j ] in x for x in data ) : substr = data [ 0 ] [ i : i + j ] elif len ( data ) == 1 : substr = data [ 0 ] return substr
1
return longest strings substring using python
Return the longest common substring in a list of strings . Credit : http : // stackoverflow . com / questions / 2892931 / longest - common - substring - from - more - than - two - strings - python
cosqa-train-18408
def long_substr(data): """Return the longest common substring in a list of strings. Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python """ substr = '' if len(data) > 1 and len(data[0]) > 0: for i in range(len(data[0])): for j in range(len(data[0])-i+1): if j > len(substr) and all(data[0][i:i+j] in x for x in data): substr = data[0][i:i+j] elif len(data) == 1: substr = data[0] return substr
def get_default_bucket_key ( buckets : List [ Tuple [ int , int ] ] ) -> Tuple [ int , int ] : return max ( buckets )
1
get key with largest value in python
Returns the default bucket from a list of buckets i . e . the largest bucket .
cosqa-train-18409
def get_default_bucket_key(buckets: List[Tuple[int, int]]) -> Tuple[int, int]: """ Returns the default bucket from a list of buckets, i.e. the largest bucket. :param buckets: List of buckets. :return: The largest bucket in the list. """ return max(buckets)
def __next__ ( self ) : self . current += 1 if self . current > self . total : raise StopIteration else : return self . iterable [ self . current - 1 ]
0
python genrator take next
: return : int
cosqa-train-18410
def __next__(self): """ :return: int """ self.current += 1 if self.current > self.total: raise StopIteration else: return self.iterable[self.current - 1]
def recClearTag ( element ) : children = element . getchildren ( ) if len ( children ) > 0 : for child in children : recClearTag ( child ) element . tag = clearTag ( element . tag )
0
python xml delete element elementtree
Applies maspy . xml . clearTag () to the tag attribute of the element and recursively to all child elements .
cosqa-train-18411
def recClearTag(element): """Applies maspy.xml.clearTag() to the tag attribute of the "element" and recursively to all child elements. :param element: an :instance:`xml.etree.Element` """ children = element.getchildren() if len(children) > 0: for child in children: recClearTag(child) element.tag = clearTag(element.tag)
def dictlist_wipe_key ( dict_list : Iterable [ Dict ] , key : str ) -> None : for d in dict_list : d . pop ( key , None )
1
python drop a key in dictionary
Process an iterable of dictionaries . For each dictionary d delete d [ key ] if it exists .
cosqa-train-18412
def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, delete ``d[key]`` if it exists. """ for d in dict_list: d.pop(key, None)
def __remove_trailing_zeros ( self , collection ) : index = len ( collection ) - 1 while index >= 0 and collection [ index ] == 0 : index -= 1 return collection [ : index + 1 ]
1
python remove leading zeroes
Removes trailing zeroes from indexable collection of numbers
cosqa-train-18413
def __remove_trailing_zeros(self, collection): """Removes trailing zeroes from indexable collection of numbers""" index = len(collection) - 1 while index >= 0 and collection[index] == 0: index -= 1 return collection[:index + 1]
def is_sqlatype_integer ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . Integer )
0
how to check type of column in python
Is the SQLAlchemy column type an integer type?
cosqa-train-18414
def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool: """ Is the SQLAlchemy column type an integer type? """ coltype = _coltype_to_typeengine(coltype) return isinstance(coltype, sqltypes.Integer)
def get_from_gnucash26_date ( date_str : str ) -> date : date_format = "%Y%m%d" result = datetime . strptime ( date_str , date_format ) . date ( ) return result
1
python 3 create date from string
Creates a datetime from GnuCash 2 . 6 date string
cosqa-train-18415
def get_from_gnucash26_date(date_str: str) -> date: """ Creates a datetime from GnuCash 2.6 date string """ date_format = "%Y%m%d" result = datetime.strptime(date_str, date_format).date() return result
def dict_to_enum_fn ( d : Dict [ str , Any ] , enum_class : Type [ Enum ] ) -> Enum : return enum_class [ d [ 'name' ] ]
0
python cast as an enum type
Converts an dict to a Enum .
cosqa-train-18416
def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum: """ Converts an ``dict`` to a ``Enum``. """ return enum_class[d['name']]
def is_sqlatype_integer ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . Integer )
0
how to check column type in python
Is the SQLAlchemy column type an integer type?
cosqa-train-18417
def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool: """ Is the SQLAlchemy column type an integer type? """ coltype = _coltype_to_typeengine(coltype) return isinstance(coltype, sqltypes.Integer)
def clean_map ( obj : Mapping [ Any , Any ] ) -> Mapping [ Any , Any ] : return { k : v for k , v in obj . items ( ) if v is not None }
1
remove all values in dictionary python
Return a new copied dictionary without the keys with None values from the given Mapping object .
cosqa-train-18418
def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]: """ Return a new copied dictionary without the keys with ``None`` values from the given Mapping object. """ return {k: v for k, v in obj.items() if v is not None}
def valid_date ( x : str ) -> bool : try : if x != dt . datetime . strptime ( x , DATE_FORMAT ) . strftime ( DATE_FORMAT ) : raise ValueError return True except ValueError : return False
0
python check if valid date
Retrun True if x is a valid YYYYMMDD date ; otherwise return False .
cosqa-train-18419
def valid_date(x: str) -> bool: """ Retrun ``True`` if ``x`` is a valid YYYYMMDD date; otherwise return ``False``. """ try: if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT): raise ValueError return True except ValueError: return False
def branches ( ) : # type: () -> List[str] out = shell . run ( 'git branch' , capture = True , never_pretend = True ) . stdout . strip ( ) return [ x . strip ( '* \t\n' ) for x in out . splitlines ( ) ]
1
python list local branches git
Return a list of branches in the current repo .
cosqa-train-18420
def branches(): # type: () -> List[str] """ Return a list of branches in the current repo. Returns: list[str]: A list of branches in the current repo. """ out = shell.run( 'git branch', capture=True, never_pretend=True ).stdout.strip() return [x.strip('* \t\n') for x in out.splitlines()]
def cache_page ( page_cache , page_hash , cache_size ) : page_cache . append ( page_hash ) if len ( page_cache ) > cache_size : page_cache . pop ( 0 )
1
implementation of cache memory performance in python
Add a page to the page cache .
cosqa-train-18421
def cache_page(page_cache, page_hash, cache_size): """Add a page to the page cache.""" page_cache.append(page_hash) if len(page_cache) > cache_size: page_cache.pop(0)
def butlast ( iterable ) : iterable = iter ( iterable ) try : first = next ( iterable ) except StopIteration : return for second in iterable : yield first first = second
0
iterate till second last element in a list python
Yield all items from iterable except the last one .
cosqa-train-18422
def butlast(iterable): """Yield all items from ``iterable`` except the last one. >>> list(butlast(['spam', 'eggs', 'ham'])) ['spam', 'eggs'] >>> list(butlast(['spam'])) [] >>> list(butlast([])) [] """ iterable = iter(iterable) try: first = next(iterable) except StopIteration: return for second in iterable: yield first first = second
def _log_response ( response ) : message = u'Received HTTP {0} response: {1}' . format ( response . status_code , response . text ) if response . status_code >= 400 : # pragma: no cover logger . warning ( message ) else : logger . debug ( message )
0
python requests detailed log
Log out information about a Request object .
cosqa-train-18423
def _log_response(response): """Log out information about a ``Request`` object. After calling ``requests.request`` or one of its convenience methods, the object returned can be passed to this method. If done, information about the object returned is logged. :return: Nothing is returned. """ message = u'Received HTTP {0} response: {1}'.format( response.status_code, response.text ) if response.status_code >= 400: # pragma: no cover logger.warning(message) else: logger.debug(message)
def empty_wav ( wav_path : Union [ Path , str ] ) -> bool : with wave . open ( str ( wav_path ) , 'rb' ) as wav_f : return wav_f . getnframes ( ) == 0
1
how to test if a wav file says something python
Check if a wav contains data
cosqa-train-18424
def empty_wav(wav_path: Union[Path, str]) -> bool: """Check if a wav contains data""" with wave.open(str(wav_path), 'rb') as wav_f: return wav_f.getnframes() == 0
def _in_qtconsole ( ) -> bool : try : from IPython import get_ipython try : from ipykernel . zmqshell import ZMQInteractiveShell shell_object = ZMQInteractiveShell except ImportError : from IPython . kernel . zmq import zmqshell shell_object = zmqshell . ZMQInteractiveShell return isinstance ( get_ipython ( ) , shell_object ) except Exception : return False
0
python decide if a qapplication instance is active
A small utility function which determines if we re running in QTConsole s context .
cosqa-train-18425
def _in_qtconsole() -> bool: """ A small utility function which determines if we're running in QTConsole's context. """ try: from IPython import get_ipython try: from ipykernel.zmqshell import ZMQInteractiveShell shell_object = ZMQInteractiveShell except ImportError: from IPython.kernel.zmq import zmqshell shell_object = zmqshell.ZMQInteractiveShell return isinstance(get_ipython(), shell_object) except Exception: return False
def get_last_weekday_in_month ( year , month , weekday ) : day = date ( year , month , monthrange ( year , month ) [ 1 ] ) while True : if day . weekday ( ) == weekday : break day = day - timedelta ( days = 1 ) return day
0
get the last day of the month in a list python
Get the last weekday in a given month . e . g :
cosqa-train-18426
def get_last_weekday_in_month(year, month, weekday): """Get the last weekday in a given month. e.g: >>> # the last monday in Jan 2013 >>> Calendar.get_last_weekday_in_month(2013, 1, MON) datetime.date(2013, 1, 28) """ day = date(year, month, monthrange(year, month)[1]) while True: if day.weekday() == weekday: break day = day - timedelta(days=1) return day
def read ( self , start_position : int , size : int ) -> memoryview : return memoryview ( self . _bytes ) [ start_position : start_position + size ]
0
python memview using size
Return a view into the memory
cosqa-train-18427
def read(self, start_position: int, size: int) -> memoryview: """ Return a view into the memory """ return memoryview(self._bytes)[start_position:start_position + size]
def auto_up ( self , count = 1 , go_to_start_of_line_if_history_changes = False ) : if self . complete_state : self . complete_previous ( count = count ) elif self . document . cursor_position_row > 0 : self . cursor_up ( count = count ) elif not self . selection_state : self . history_backward ( count = count ) # Go to the start of the line? if go_to_start_of_line_if_history_changes : self . cursor_position += self . document . get_start_of_line_position ( )
0
how to go to a next line from a current line in line python
If we re not on the first line ( of a multiline input ) go a line up otherwise go back in history . ( If nothing is selected . )
cosqa-train-18428
def auto_up(self, count=1, go_to_start_of_line_if_history_changes=False): """ If we're not on the first line (of a multiline input) go a line up, otherwise go back in history. (If nothing is selected.) """ if self.complete_state: self.complete_previous(count=count) elif self.document.cursor_position_row > 0: self.cursor_up(count=count) elif not self.selection_state: self.history_backward(count=count) # Go to the start of the line? if go_to_start_of_line_if_history_changes: self.cursor_position += self.document.get_start_of_line_position()
def set_cell_value ( cell , value ) : if OPENPYXL_MAJOR_VERSION > 1 : cell . value = value else : cell . internal_value = value
0
python openpyxl set cell color
Convenience method for setting the value of an openpyxl cell
cosqa-train-18429
def set_cell_value(cell, value): """ Convenience method for setting the value of an openpyxl cell This is necessary since the value property changed from internal_value to value between version 1.* and 2.*. """ if OPENPYXL_MAJOR_VERSION > 1: cell.value = value else: cell.internal_value = value
def writable_stream ( handle ) : if isinstance ( handle , io . IOBase ) and sys . version_info >= ( 3 , 5 ) : return handle . writable ( ) try : handle . write ( b'' ) except ( io . UnsupportedOperation , IOError ) : return False else : return True
0
python check if file is writeable
Test whether a stream can be written to .
cosqa-train-18430
def writable_stream(handle): """Test whether a stream can be written to. """ if isinstance(handle, io.IOBase) and sys.version_info >= (3, 5): return handle.writable() try: handle.write(b'') except (io.UnsupportedOperation, IOError): return False else: return True
def sorted ( self ) : for i in range ( 0 , self . tabs . tabBar ( ) . count ( ) - 1 ) : if ( self . tabs . tabBar ( ) . tabText ( i ) > self . tabs . tabBar ( ) . tabText ( i + 1 ) ) : return False return True
1
how do i minimize tabs in python
Utility function for sort_file_tabs_alphabetically () .
cosqa-train-18431
def sorted(self): """Utility function for sort_file_tabs_alphabetically().""" for i in range(0, self.tabs.tabBar().count() - 1): if (self.tabs.tabBar().tabText(i) > self.tabs.tabBar().tabText(i + 1)): return False return True
def ask_bool ( question : str , default : bool = True ) -> bool : default_q = "Y/n" if default else "y/N" answer = input ( "{0} [{1}]: " . format ( question , default_q ) ) lower = answer . lower ( ) if not lower : return default return lower == "y"
0
how to choose between yes or no in python
Asks a question yes no style
cosqa-train-18432
def ask_bool(question: str, default: bool = True) -> bool: """Asks a question yes no style""" default_q = "Y/n" if default else "y/N" answer = input("{0} [{1}]: ".format(question, default_q)) lower = answer.lower() if not lower: return default return lower == "y"
def ensure_list ( iterable : Iterable [ A ] ) -> List [ A ] : if isinstance ( iterable , list ) : return iterable else : return list ( iterable )
0
python expected type 'list', got 'iterator] instead
An Iterable may be a list or a generator . This ensures we get a list without making an unnecessary copy .
cosqa-train-18433
def ensure_list(iterable: Iterable[A]) -> List[A]: """ An Iterable may be a list or a generator. This ensures we get a list without making an unnecessary copy. """ if isinstance(iterable, list): return iterable else: return list(iterable)
def isfile_notempty ( inputfile : str ) -> bool : try : return isfile ( inputfile ) and getsize ( inputfile ) > 0 except TypeError : raise TypeError ( 'inputfile is not a valid type' )
1
python how to check if file is empty
Check if the input filename with path is a file and is not empty .
cosqa-train-18434
def isfile_notempty(inputfile: str) -> bool: """Check if the input filename with path is a file and is not empty.""" try: return isfile(inputfile) and getsize(inputfile) > 0 except TypeError: raise TypeError('inputfile is not a valid type')
def _gauss ( mean : int , sigma : int ) -> int : return int ( random . gauss ( mean , sigma ) )
0
python generate a random number from a normal distribution
Creates a variation from a base value
cosqa-train-18435
def _gauss(mean: int, sigma: int) -> int: """ Creates a variation from a base value Args: mean: base value sigma: gaussian sigma Returns: random value """ return int(random.gauss(mean, sigma))
def stretch ( iterable , n = 2 ) : times = range ( n ) for item in iterable : for i in times : yield item
0
python repeat elements in a list different amount of times
r Repeat each item in iterable n times .
cosqa-train-18436
def stretch(iterable, n=2): r"""Repeat each item in `iterable` `n` times. Example: >>> list(stretch(range(3), 2)) [0, 0, 1, 1, 2, 2] """ times = range(n) for item in iterable: for i in times: yield item
def has_value ( cls , value : int ) -> bool : return any ( value == item . value for item in cls )
0
python checking if a value is in an enumeration
True if specified value exists in int enum ; otherwise False .
cosqa-train-18437
def has_value(cls, value: int) -> bool: """True if specified value exists in int enum; otherwise, False.""" return any(value == item.value for item in cls)
def issubset ( self , other ) : if len ( self ) > len ( other ) : # Fast check for obvious cases return False return all ( item in other for item in self )
1
check if set is subset of another set python
Report whether another set contains this set .
cosqa-train-18438
def issubset(self, other): """ Report whether another set contains this set. Example: >>> OrderedSet([1, 2, 3]).issubset({1, 2}) False >>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4}) True >>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5}) False """ if len(self) > len(other): # Fast check for obvious cases return False return all(item in other for item in self)
def parse_dim ( features , check = True ) : # try: dim = features [ 0 ] . shape [ 1 ] # except IndexError: # dim = 1 if check and not dim > 0 : raise IOError ( 'features dimension must be strictly positive' ) if check and not all ( [ d == dim for d in [ x . shape [ 1 ] for x in features ] ] ) : raise IOError ( 'all files must have the same feature dimension' ) return dim
1
python code to check numbers of rows and columns in a dataset
Return the features dimension raise if error
cosqa-train-18439
def parse_dim(features, check=True): """Return the features dimension, raise if error Raise IOError if features have not all the same positive dimension. Return dim (int), the features dimension. """ # try: dim = features[0].shape[1] # except IndexError: # dim = 1 if check and not dim > 0: raise IOError('features dimension must be strictly positive') if check and not all([d == dim for d in [x.shape[1] for x in features]]): raise IOError('all files must have the same feature dimension') return dim
def is_relative_url ( url ) : if url . startswith ( "#" ) : return None if url . find ( "://" ) > 0 or url . startswith ( "//" ) : # either 'http(s)://...' or '//cdn...' and therefore absolute return False return True
1
python howe to tell if path passed in is absolute or relative
simple method to determine if a url is relative or absolute
cosqa-train-18440
def is_relative_url(url): """ simple method to determine if a url is relative or absolute """ if url.startswith("#"): return None if url.find("://") > 0 or url.startswith("//"): # either 'http(s)://...' or '//cdn...' and therefore absolute return False return True
def _kbhit_unix ( ) -> bool : dr , dw , de = select . select ( [ sys . stdin ] , [ ] , [ ] , 0 ) return dr != [ ]
0
how to check keyboard input with python
Under UNIX : is a keystroke available?
cosqa-train-18441
def _kbhit_unix() -> bool: """ Under UNIX: is a keystroke available? """ dr, dw, de = select.select([sys.stdin], [], [], 0) return dr != []
def camel_to_snake_case ( string ) : s = _1 . sub ( r'\1_\2' , string ) return _2 . sub ( r'\1_\2' , s ) . lower ( )
0
python everything got changed to lowercase
Converts string presented in camel case to snake case .
cosqa-train-18442
def camel_to_snake_case(string): """Converts 'string' presented in camel case to snake case. e.g.: CamelCase => snake_case """ s = _1.sub(r'\1_\2', string) return _2.sub(r'\1_\2', s).lower()
def write_text ( filename : str , text : str ) -> None : with open ( filename , 'w' ) as f : # type: TextIO print ( text , file = f )
1
writing text and a variable to a file in python
Writes text to a file .
cosqa-train-18443
def write_text(filename: str, text: str) -> None: """ Writes text to a file. """ with open(filename, 'w') as f: # type: TextIO print(text, file=f)
def fmt_camel ( name ) : words = split_words ( name ) assert len ( words ) > 0 first = words . pop ( 0 ) . lower ( ) return first + '' . join ( [ word . capitalize ( ) for word in words ] )
0
capitalize first element of the list python
Converts name to lower camel case . Words are identified by capitalization dashes and underscores .
cosqa-train-18444
def fmt_camel(name): """ Converts name to lower camel case. Words are identified by capitalization, dashes, and underscores. """ words = split_words(name) assert len(words) > 0 first = words.pop(0).lower() return first + ''.join([word.capitalize() for word in words])
def _brief_print_list ( lst , limit = 7 ) : lst = list ( lst ) if len ( lst ) > limit : return _brief_print_list ( lst [ : limit // 2 ] , limit ) + ', ..., ' + _brief_print_list ( lst [ - limit // 2 : ] , limit ) return ', ' . join ( [ "'%s'" % str ( i ) for i in lst ] )
1
print only limited element of a list python
Print at most limit elements of list .
cosqa-train-18445
def _brief_print_list(lst, limit=7): """Print at most `limit` elements of list.""" lst = list(lst) if len(lst) > limit: return _brief_print_list(lst[:limit//2], limit) + ', ..., ' + \ _brief_print_list(lst[-limit//2:], limit) return ', '.join(["'%s'"%str(i) for i in lst])
def _isint ( string ) : return type ( string ) is int or ( isinstance ( string , _binary_type ) or isinstance ( string , _text_type ) ) and _isconvertible ( int , string )
1
how to test if str is int python
>>> _isint ( 123 ) True >>> _isint ( 123 . 45 ) False
cosqa-train-18446
def _isint(string): """ >>> _isint("123") True >>> _isint("123.45") False """ return type(string) is int or \ (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \ _isconvertible(int, string)
def position ( self ) -> Position : return Position ( self . _index , self . _lineno , self . _col_offset )
0
python get cursor position
The current position of the cursor .
cosqa-train-18447
def position(self) -> Position: """The current position of the cursor.""" return Position(self._index, self._lineno, self._col_offset)
def get_edge_relations ( graph : BELGraph ) -> Mapping [ Tuple [ BaseEntity , BaseEntity ] , Set [ str ] ] : return group_dict_set ( ( ( u , v ) , d [ RELATION ] ) for u , v , d in graph . edges ( data = True ) )
0
python graph dict of set
Build a dictionary of { node pair : set of edge types } .
cosqa-train-18448
def get_edge_relations(graph: BELGraph) -> Mapping[Tuple[BaseEntity, BaseEntity], Set[str]]: """Build a dictionary of {node pair: set of edge types}.""" return group_dict_set( ((u, v), d[RELATION]) for u, v, d in graph.edges(data=True) )
def flatten_list ( x : List [ Any ] ) -> List [ Any ] : # noqa return [ item for sublist in x for item in sublist ]
0
condense multiple lists to single list python
Converts a list of lists into a flat list . Args : x : list of lists
cosqa-train-18449
def flatten_list(x: List[Any]) -> List[Any]: """ Converts a list of lists into a flat list. Args: x: list of lists Returns: flat list As per http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python """ # noqa return [item for sublist in x for item in sublist]
def arcball_map_to_sphere ( point , center , radius ) : v0 = ( point [ 0 ] - center [ 0 ] ) / radius v1 = ( center [ 1 ] - point [ 1 ] ) / radius n = v0 * v0 + v1 * v1 if n > 1.0 : # position outside of sphere n = math . sqrt ( n ) return numpy . array ( [ v0 / n , v1 / n , 0.0 ] ) else : return numpy . array ( [ v0 , v1 , math . sqrt ( 1.0 - n ) ] )
1
python calculate bounding sphere from points
Return unit sphere coordinates from window coordinates .
cosqa-train-18450
def arcball_map_to_sphere(point, center, radius): """Return unit sphere coordinates from window coordinates.""" v0 = (point[0] - center[0]) / radius v1 = (center[1] - point[1]) / radius n = v0*v0 + v1*v1 if n > 1.0: # position outside of sphere n = math.sqrt(n) return numpy.array([v0/n, v1/n, 0.0]) else: return numpy.array([v0, v1, math.sqrt(1.0 - n)])
def file_exists ( self ) -> bool : cfg_path = self . file_path assert cfg_path return path . isfile ( cfg_path )
0
python configuration file check if it exsists
Check if the settings file exists or not
cosqa-train-18451
def file_exists(self) -> bool: """ Check if the settings file exists or not """ cfg_path = self.file_path assert cfg_path return path.isfile(cfg_path)
def local_machine_uuid ( ) : result = subprocess . check_output ( 'hal-get-property --udi ' '/org/freedesktop/Hal/devices/computer ' '--key system.hardware.uuid' . split ( ) ) . strip ( ) return uuid . UUID ( hex = result )
0
python3 os' has no attribute 'getuid'
Return local machine unique identifier .
cosqa-train-18452
def local_machine_uuid(): """Return local machine unique identifier. >>> uuid = local_machine_uuid() """ result = subprocess.check_output( 'hal-get-property --udi ' '/org/freedesktop/Hal/devices/computer ' '--key system.hardware.uuid'.split() ).strip() return uuid.UUID(hex=result)
def is_prime ( n ) : if n % 2 == 0 and n > 2 : return False return all ( n % i for i in range ( 3 , int ( math . sqrt ( n ) ) + 1 , 2 ) )
0
write a function checking whether a number is prime or not python using def
Check if n is a prime number
cosqa-train-18453
def is_prime(n): """ Check if n is a prime number """ if n % 2 == 0 and n > 2: return False return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
def __setitem__ ( self , * args , * * kwargs ) : super ( History , self ) . __setitem__ ( * args , * * kwargs ) if len ( self ) > self . size : self . popitem ( False )
0
pop will remove popped up items in python
Cut if needed .
cosqa-train-18454
def __setitem__(self, *args, **kwargs): """ Cut if needed. """ super(History, self).__setitem__(*args, **kwargs) if len(self) > self.size: self.popitem(False)
def split ( text : str ) -> List [ str ] : return [ word for word in SEPARATOR . split ( text ) if word . strip ( ' \t' ) ]
0
how to split a word with no whitespaceinto a list in python
Split a text into a list of tokens .
cosqa-train-18455
def split(text: str) -> List[str]: """Split a text into a list of tokens. :param text: the text to split :return: tokens """ return [word for word in SEPARATOR.split(text) if word.strip(' \t')]
def isarray ( array , test , dim = 2 ) : if dim > 1 : return all ( isarray ( array [ i ] , test , dim - 1 ) for i in range ( len ( array ) ) ) return all ( test ( i ) for i in array )
1
if any true in array return true python
Returns True if test is True for all array elements . Otherwise returns False .
cosqa-train-18456
def isarray(array, test, dim=2): """Returns True if test is True for all array elements. Otherwise, returns False. """ if dim > 1: return all(isarray(array[i], test, dim - 1) for i in range(len(array))) return all(test(i) for i in array)
def debugTreePrint ( node , pfx = "->" ) : print pfx , node . item for c in node . children : debugTreePrint ( c , " " + pfx )
0
printing out the leaves of a tree in python
Purely a debugging aid : Ascii - art picture of a tree descended from node
cosqa-train-18457
def debugTreePrint(node,pfx="->"): """Purely a debugging aid: Ascii-art picture of a tree descended from node""" print pfx,node.item for c in node.children: debugTreePrint(c," "+pfx)
def list_adb_devices_by_usb_id ( ) : out = adb . AdbProxy ( ) . devices ( [ '-l' ] ) clean_lines = new_str ( out , 'utf-8' ) . strip ( ) . split ( '\n' ) results = [ ] for line in clean_lines : tokens = line . strip ( ) . split ( ) if len ( tokens ) > 2 and tokens [ 1 ] == 'device' : results . append ( tokens [ 2 ] ) return results
0
python get adb devices id
List the usb id of all android devices connected to the computer that are detected by adb .
cosqa-train-18458
def list_adb_devices_by_usb_id(): """List the usb id of all android devices connected to the computer that are detected by adb. Returns: A list of strings that are android device usb ids. Empty if there's none. """ out = adb.AdbProxy().devices(['-l']) clean_lines = new_str(out, 'utf-8').strip().split('\n') results = [] for line in clean_lines: tokens = line.strip().split() if len(tokens) > 2 and tokens[1] == 'device': results.append(tokens[2]) return results
def snake_case ( a_string ) : partial = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , a_string ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , partial ) . lower ( )
1
lowercase + string object + python
Returns a snake cased version of a string .
cosqa-train-18459
def snake_case(a_string): """Returns a snake cased version of a string. :param a_string: any :class:`str` object. Usage: >>> snake_case('FooBar') "foo_bar" """ partial = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', a_string) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', partial).lower()
def has_key ( cls , * args ) : key = args if len ( args ) > 1 else args [ 0 ] return key in cls . _instances
1
check if file exist in key python
Check whether flyweight object with specified key has already been created .
cosqa-train-18460
def has_key(cls, *args): """ Check whether flyweight object with specified key has already been created. Returns: bool: True if already created, False if not """ key = args if len(args) > 1 else args[0] return key in cls._instances
def decode ( self , bytes , raw = False ) : return struct . unpack ( self . format , buffer ( bytes ) ) [ 0 ]
1
python decode protobuf without proto
decode ( bytearray raw = False ) - > value
cosqa-train-18461
def decode(self, bytes, raw=False): """decode(bytearray, raw=False) -> value Decodes the given bytearray according to this PrimitiveType definition. NOTE: The parameter ``raw`` is present to adhere to the ``decode()`` inteface, but has no effect for PrimitiveType definitions. """ return struct.unpack(self.format, buffer(bytes))[0]
def returns ( self ) -> T . Optional [ DocstringReturns ] : try : return next ( DocstringReturns . from_meta ( meta ) for meta in self . meta if meta . args [ 0 ] in { "return" , "returns" , "yield" , "yields" } ) except StopIteration : return None
1
python docstring specify yield type
Return return information indicated in docstring .
cosqa-train-18462
def returns(self) -> T.Optional[DocstringReturns]: """Return return information indicated in docstring.""" try: return next( DocstringReturns.from_meta(meta) for meta in self.meta if meta.args[0] in {"return", "returns", "yield", "yields"} ) except StopIteration: return None
def dict_of_sets_add ( dictionary , key , value ) : # type: (DictUpperBound, Any, Any) -> None set_objs = dictionary . get ( key , set ( ) ) set_objs . add ( value ) dictionary [ key ] = set_objs
1
python add element for a set
Add value to a set in a dictionary by key
cosqa-train-18463
def dict_of_sets_add(dictionary, key, value): # type: (DictUpperBound, Any, Any) -> None """Add value to a set in a dictionary by key Args: dictionary (DictUpperBound): Dictionary to which to add values key (Any): Key within dictionary value (Any): Value to add to set in dictionary Returns: None """ set_objs = dictionary.get(key, set()) set_objs.add(value) dictionary[key] = set_objs
def getIndex ( predicateFn : Callable [ [ T ] , bool ] , items : List [ T ] ) -> int : try : return next ( i for i , v in enumerate ( items ) if predicateFn ( v ) ) except StopIteration : return - 1
1
python first index of a list that validates a condition
Finds the index of an item in list which satisfies predicate : param predicateFn : predicate function to run on items of list : param items : list of tuples : return : first index for which predicate function returns True
cosqa-train-18464
def getIndex(predicateFn: Callable[[T], bool], items: List[T]) -> int: """ Finds the index of an item in list, which satisfies predicate :param predicateFn: predicate function to run on items of list :param items: list of tuples :return: first index for which predicate function returns True """ try: return next(i for i, v in enumerate(items) if predicateFn(v)) except StopIteration: return -1
def running_containers ( name_filter : str ) -> List [ str ] : return [ container . short_id for container in docker_client . containers . list ( filters = { "name" : name_filter } ) ]
1
list azure containers with specific name type using python
: raises docker . exceptions . APIError
cosqa-train-18465
def running_containers(name_filter: str) -> List[str]: """ :raises docker.exceptions.APIError """ return [container.short_id for container in docker_client.containers.list(filters={"name": name_filter})]
def getIndex ( predicateFn : Callable [ [ T ] , bool ] , items : List [ T ] ) -> int : try : return next ( i for i , v in enumerate ( items ) if predicateFn ( v ) ) except StopIteration : return - 1
1
python return index of item in list satisfying a condition
Finds the index of an item in list which satisfies predicate : param predicateFn : predicate function to run on items of list : param items : list of tuples : return : first index for which predicate function returns True
cosqa-train-18466
def getIndex(predicateFn: Callable[[T], bool], items: List[T]) -> int: """ Finds the index of an item in list, which satisfies predicate :param predicateFn: predicate function to run on items of list :param items: list of tuples :return: first index for which predicate function returns True """ try: return next(i for i, v in enumerate(items) if predicateFn(v)) except StopIteration: return -1
def rank ( tensor : BKTensor ) -> int : if isinstance ( tensor , np . ndarray ) : return len ( tensor . shape ) return len ( tensor [ 0 ] . size ( ) )
1
how to print size of tensor in python in tensorflow
Return the number of dimensions of a tensor
cosqa-train-18467
def rank(tensor: BKTensor) -> int: """Return the number of dimensions of a tensor""" if isinstance(tensor, np.ndarray): return len(tensor.shape) return len(tensor[0].size())
def get_keys_of_max_n ( dict_obj , n ) : return sorted ( [ item [ 0 ] for item in sorted ( dict_obj . items ( ) , key = lambda item : item [ 1 ] , reverse = True ) [ : n ] ] )
1
how to get the top values in a dictionary for python
Returns the keys that maps to the top n max values in the given dict .
cosqa-train-18468
def get_keys_of_max_n(dict_obj, n): """Returns the keys that maps to the top n max values in the given dict. Example: -------- >>> dict_obj = {'a':2, 'b':1, 'c':5} >>> get_keys_of_max_n(dict_obj, 2) ['a', 'c'] """ return sorted([ item[0] for item in sorted( dict_obj.items(), key=lambda item: item[1], reverse=True )[:n] ])
def is_finite ( value : Any ) -> bool : return isinstance ( value , int ) or ( isinstance ( value , float ) and isfinite ( value ) )
0
check if float has some value python
Return true if a value is a finite number .
cosqa-train-18469
def is_finite(value: Any) -> bool: """Return true if a value is a finite number.""" return isinstance(value, int) or (isinstance(value, float) and isfinite(value))
def butlast ( iterable ) : iterable = iter ( iterable ) try : first = next ( iterable ) except StopIteration : return for second in iterable : yield first first = second
1
last elemnts of a list in python
Yield all items from iterable except the last one .
cosqa-train-18470
def butlast(iterable): """Yield all items from ``iterable`` except the last one. >>> list(butlast(['spam', 'eggs', 'ham'])) ['spam', 'eggs'] >>> list(butlast(['spam'])) [] >>> list(butlast([])) [] """ iterable = iter(iterable) try: first = next(iterable) except StopIteration: return for second in iterable: yield first first = second
def constant ( times : np . ndarray , amp : complex ) -> np . ndarray : return np . full ( len ( times ) , amp , dtype = np . complex_ )
1
python numpy fill arraw with sine wave
Continuous constant pulse .
cosqa-train-18471
def constant(times: np.ndarray, amp: complex) -> np.ndarray: """Continuous constant pulse. Args: times: Times to output pulse for. amp: Complex pulse amplitude. """ return np.full(len(times), amp, dtype=np.complex_)
def normcdf ( x , log = False ) : y = np . atleast_1d ( x ) . copy ( ) flib . normcdf ( y ) if log : if ( y > 0 ) . all ( ) : return np . log ( y ) return - np . inf return y
0
how to do normalcdf on python
Normal cumulative density function .
cosqa-train-18472
def normcdf(x, log=False): """Normal cumulative density function.""" y = np.atleast_1d(x).copy() flib.normcdf(y) if log: if (y>0).all(): return np.log(y) return -np.inf return y
def replaceStrs ( s , * args ) : if args == ( ) : return s mapping = dict ( ( frm , to ) for frm , to in args ) return re . sub ( "|" . join ( map ( re . escape , mapping . keys ( ) ) ) , lambda match : mapping [ match . group ( 0 ) ] , s )
1
python multiple string substitutions
r Replace all ( frm to ) tuples in args in string s .
cosqa-train-18473
def replaceStrs(s, *args): r"""Replace all ``(frm, to)`` tuples in `args` in string `s`. >>> replaceStrs("nothing is better than warm beer", ... ('nothing','warm beer'), ('warm beer','nothing')) 'warm beer is better than nothing' """ if args == (): return s mapping = dict((frm, to) for frm, to in args) return re.sub("|".join(map(re.escape, mapping.keys())), lambda match:mapping[match.group(0)], s)
def is_unicode ( string ) : str_type = str ( type ( string ) ) if str_type . find ( 'str' ) > 0 or str_type . find ( 'unicode' ) > 0 : return True return False
1
python if variable type is not str
Validates that the object itself is some kinda string
cosqa-train-18474
def is_unicode(string): """Validates that the object itself is some kinda string""" str_type = str(type(string)) if str_type.find('str') > 0 or str_type.find('unicode') > 0: return True return False
def bfx ( value , msb , lsb ) : mask = bitmask ( ( msb , lsb ) ) return ( value & mask ) >> lsb
0
how to bitmask python
!
cosqa-train-18475
def bfx(value, msb, lsb): """! @brief Extract a value from a bitfield.""" mask = bitmask((msb, lsb)) return (value & mask) >> lsb
def _ ( f , x ) : return { k : v for k , v in x . items ( ) if f ( k , v ) }
1
python filter a dictionary key,valyue
filter for dict note f should have signature : f :: key - > value - > bool
cosqa-train-18476
def _(f, x): """ filter for dict, note `f` should have signature: `f::key->value->bool` """ return {k: v for k, v in x.items() if f(k, v)}
def is_unicode ( string ) : str_type = str ( type ( string ) ) if str_type . find ( 'str' ) > 0 or str_type . find ( 'unicode' ) > 0 : return True return False
1
python if type is a string
Validates that the object itself is some kinda string
cosqa-train-18477
def is_unicode(string): """Validates that the object itself is some kinda string""" str_type = str(type(string)) if str_type.find('str') > 0 or str_type.find('unicode') > 0: return True return False
def _infer_interval_breaks ( coord ) : coord = np . asarray ( coord ) deltas = 0.5 * ( coord [ 1 : ] - coord [ : - 1 ] ) first = coord [ 0 ] - deltas [ 0 ] last = coord [ - 1 ] + deltas [ - 1 ] return np . r_ [ [ first ] , coord [ : - 1 ] + deltas , [ last ] ]
1
how to determine the index interval for given range of array python
>>> _infer_interval_breaks ( np . arange ( 5 )) array ( [ - 0 . 5 0 . 5 1 . 5 2 . 5 3 . 5 4 . 5 ] )
cosqa-train-18478
def _infer_interval_breaks(coord): """ >>> _infer_interval_breaks(np.arange(5)) array([-0.5, 0.5, 1.5, 2.5, 3.5, 4.5]) Taken from xarray.plotting.plot module """ coord = np.asarray(coord) deltas = 0.5 * (coord[1:] - coord[:-1]) first = coord[0] - deltas[0] last = coord[-1] + deltas[-1] return np.r_[[first], coord[:-1] + deltas, [last]]
def _protected_log ( x1 ) : with np . errstate ( divide = 'ignore' , invalid = 'ignore' ) : return np . where ( np . abs ( x1 ) > 0.001 , np . log ( np . abs ( x1 ) ) , 0. )
0
log of zero define in python
Closure of log for zero arguments .
cosqa-train-18479
def _protected_log(x1): """Closure of log for zero arguments.""" with np.errstate(divide='ignore', invalid='ignore'): return np.where(np.abs(x1) > 0.001, np.log(np.abs(x1)), 0.)
def file_exists ( fname ) : try : return fname and os . path . exists ( fname ) and os . path . getsize ( fname ) > 0 except OSError : return False
0
check to see if a value in directory is empty in python
Check if a file exists and is non - empty .
cosqa-train-18480
def file_exists(fname): """Check if a file exists and is non-empty. """ try: return fname and os.path.exists(fname) and os.path.getsize(fname) > 0 except OSError: return False
def check_max_filesize ( chosen_file , max_size ) : if os . path . getsize ( chosen_file ) > max_size : return False else : return True
0
python if file larger than
Checks file sizes for host
cosqa-train-18481
def check_max_filesize(chosen_file, max_size): """ Checks file sizes for host """ if os.path.getsize(chosen_file) > max_size: return False else: return True
def pretty_describe ( object , nestedness = 0 , indent = 2 ) : if not isinstance ( object , dict ) : return str ( object ) sep = f'\n{" " * nestedness * indent}' out = sep . join ( ( f'{k}: {pretty_describe(v, nestedness + 1)}' for k , v in object . items ( ) ) ) if nestedness > 0 and out : return f'{sep}{out}' return out
0
how to display a dictionary with extra indentation python
Maintain dict ordering - but make string version prettier
cosqa-train-18482
def pretty_describe(object, nestedness=0, indent=2): """Maintain dict ordering - but make string version prettier""" if not isinstance(object, dict): return str(object) sep = f'\n{" " * nestedness * indent}' out = sep.join((f'{k}: {pretty_describe(v, nestedness + 1)}' for k, v in object.items())) if nestedness > 0 and out: return f'{sep}{out}' return out
def indent ( text : str , num : int = 2 ) -> str : lines = text . splitlines ( ) return "\n" . join ( indent_iterable ( lines , num = num ) )
1
how to indent a line of text in python
Indent a piece of text .
cosqa-train-18483
def indent(text: str, num: int = 2) -> str: """Indent a piece of text.""" lines = text.splitlines() return "\n".join(indent_iterable(lines, num=num))
def is_any_type_set ( sett : Set [ Type ] ) -> bool : return len ( sett ) == 1 and is_any_type ( min ( sett ) )
1
to check if a set is empty in python
Helper method to check if a set of types is the { AnyObject } singleton
cosqa-train-18484
def is_any_type_set(sett: Set[Type]) -> bool: """ Helper method to check if a set of types is the {AnyObject} singleton :param sett: :return: """ return len(sett) == 1 and is_any_type(min(sett))
def extend ( a : dict , b : dict ) -> dict : res = a . copy ( ) res . update ( b ) return res
0
python dict from another dict
Merge two dicts and return a new dict . Much like subclassing works .
cosqa-train-18485
def extend(a: dict, b: dict) -> dict: """Merge two dicts and return a new dict. Much like subclassing works.""" res = a.copy() res.update(b) return res
def str_to_time ( time_str : str ) -> datetime . datetime : pieces : Any = [ int ( piece ) for piece in time_str . split ( '-' ) ] return datetime . datetime ( * pieces )
0
date time from string python
Convert human readable string to datetime . datetime .
cosqa-train-18486
def str_to_time(time_str: str) -> datetime.datetime: """ Convert human readable string to datetime.datetime. """ pieces: Any = [int(piece) for piece in time_str.split('-')] return datetime.datetime(*pieces)
def contains ( self , token : str ) -> bool : self . _validate_token ( token ) return token in self
1
how to check in python if token is person or not
Return if the token is in the list or not .
cosqa-train-18487
def contains(self, token: str) -> bool: """Return if the token is in the list or not.""" self._validate_token(token) return token in self
def _read_section ( self ) : lines = [ self . _last [ self . _last . find ( ":" ) + 1 : ] ] self . _last = self . _f . readline ( ) while len ( self . _last ) > 0 and len ( self . _last [ 0 ] . strip ( ) ) == 0 : lines . append ( self . _last ) self . _last = self . _f . readline ( ) return lines
0
read the last line/raw of file in python
Read and return an entire section
cosqa-train-18488
def _read_section(self): """Read and return an entire section""" lines = [self._last[self._last.find(":")+1:]] self._last = self._f.readline() while len(self._last) > 0 and len(self._last[0].strip()) == 0: lines.append(self._last) self._last = self._f.readline() return lines
def timeit ( func , * args , * * kwargs ) : start_time = time . time ( ) res = func ( * args , * * kwargs ) timing = time . time ( ) - start_time return res , timing
0
time a function using timeit python
Time execution of function . Returns ( res seconds ) .
cosqa-train-18489
def timeit(func, *args, **kwargs): """ Time execution of function. Returns (res, seconds). >>> res, timing = timeit(time.sleep, 1) """ start_time = time.time() res = func(*args, **kwargs) timing = time.time() - start_time return res, timing
def isarray ( array , test , dim = 2 ) : if dim > 1 : return all ( isarray ( array [ i ] , test , dim - 1 ) for i in range ( len ( array ) ) ) return all ( test ( i ) for i in array )
0
python if any element in array meets conditions
Returns True if test is True for all array elements . Otherwise returns False .
cosqa-train-18490
def isarray(array, test, dim=2): """Returns True if test is True for all array elements. Otherwise, returns False. """ if dim > 1: return all(isarray(array[i], test, dim - 1) for i in range(len(array))) return all(test(i) for i in array)
def dict_to_enum_fn ( d : Dict [ str , Any ] , enum_class : Type [ Enum ] ) -> Enum : return enum_class [ d [ 'name' ] ]
0
how to name enum python
Converts an dict to a Enum .
cosqa-train-18491
def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum: """ Converts an ``dict`` to a ``Enum``. """ return enum_class[d['name']]
def decode ( self , bytes , raw = False ) : return struct . unpack ( self . format , buffer ( bytes ) ) [ 0 ]
1
python protobuf from byte array
decode ( bytearray raw = False ) - > value
cosqa-train-18492
def decode(self, bytes, raw=False): """decode(bytearray, raw=False) -> value Decodes the given bytearray according to this PrimitiveType definition. NOTE: The parameter ``raw`` is present to adhere to the ``decode()`` inteface, but has no effect for PrimitiveType definitions. """ return struct.unpack(self.format, buffer(bytes))[0]
def valid_file ( path : str ) -> bool : path = Path ( path ) . expanduser ( ) log . debug ( "checking if %s is a valid file" , path ) return path . exists ( ) and path . is_file ( )
1
python detect if path is valid
Verifies that a string path actually exists and is a file
cosqa-train-18493
def valid_file(path: str) -> bool: """ Verifies that a string path actually exists and is a file :param path: The path to verify :return: **True** if path exist and is a file """ path = Path(path).expanduser() log.debug("checking if %s is a valid file", path) return path.exists() and path.is_file()
def _my_hash ( arg_list ) : # type: (List[Any]) -> int res = 0 for arg in arg_list : res = res * 31 + hash ( arg ) return res
1
python generate hash of list
Simple helper hash function
cosqa-train-18494
def _my_hash(arg_list): # type: (List[Any]) -> int """Simple helper hash function""" res = 0 for arg in arg_list: res = res * 31 + hash(arg) return res
def decode_base64 ( data : str ) -> bytes : missing_padding = len ( data ) % 4 if missing_padding != 0 : data += "=" * ( 4 - missing_padding ) return base64 . decodebytes ( data . encode ( "utf-8" ) )
0
python base64 encoded missing padding
Decode base64 padding being optional .
cosqa-train-18495
def decode_base64(data: str) -> bytes: """Decode base64, padding being optional. :param data: Base64 data as an ASCII byte string :returns: The decoded byte string. """ missing_padding = len(data) % 4 if missing_padding != 0: data += "=" * (4 - missing_padding) return base64.decodebytes(data.encode("utf-8"))
def lowercase_chars ( string : any ) -> str : return '' . join ( [ c if c . islower ( ) else '' for c in str ( string ) ] )
0
is python string comparison case sensitive
Return all ( and only ) the lowercase chars in the given string .
cosqa-train-18496
def lowercase_chars(string: any) -> str: """Return all (and only) the lowercase chars in the given string.""" return ''.join([c if c.islower() else '' for c in str(string)])
def file_exists ( fname ) : try : return fname and os . path . exists ( fname ) and os . path . getsize ( fname ) > 0 except OSError : return False
1
determine a file exist or not python
Check if a file exists and is non - empty .
cosqa-train-18497
def file_exists(fname): """Check if a file exists and is non-empty. """ try: return fname and os.path.exists(fname) and os.path.getsize(fname) > 0 except OSError: return False
def get_view_selection ( self ) : if not self . MODEL_STORAGE_ID : return None , None # avoid selection requests on empty tree views -> case warnings in gtk3 if len ( self . store ) == 0 : paths = [ ] else : model , paths = self . _tree_selection . get_selected_rows ( ) # get all related models for selection from respective tree store field selected_model_list = [ ] for path in paths : model = self . store [ path ] [ self . MODEL_STORAGE_ID ] selected_model_list . append ( model ) return self . _tree_selection , selected_model_list
1
treeview row selection python
Get actual tree selection object and all respective models of selected rows
cosqa-train-18498
def get_view_selection(self): """Get actual tree selection object and all respective models of selected rows""" if not self.MODEL_STORAGE_ID: return None, None # avoid selection requests on empty tree views -> case warnings in gtk3 if len(self.store) == 0: paths = [] else: model, paths = self._tree_selection.get_selected_rows() # get all related models for selection from respective tree store field selected_model_list = [] for path in paths: model = self.store[path][self.MODEL_STORAGE_ID] selected_model_list.append(model) return self._tree_selection, selected_model_list
def public ( self ) -> 'PrettyDir' : return PrettyDir ( self . obj , [ pattr for pattr in self . pattrs if not pattr . name . startswith ( '_' ) ] )
1
python dir to show public attributes
Returns public attributes of the inspected object .
cosqa-train-18499
def public(self) -> 'PrettyDir': """Returns public attributes of the inspected object.""" return PrettyDir( self.obj, [pattr for pattr in self.pattrs if not pattr.name.startswith('_')] )