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 file_exists ( fname ) : try : return fname and os . path . exists ( fname ) and os . path . getsize ( fname ) > 0 except OSError : return False
1
python check if file is not empty
Check if a file exists and is non - empty .
cosqa-train-17200
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 strtobytes ( input , encoding ) : py_version = sys . version_info [ 0 ] if py_version >= 3 : return _strtobytes_py3 ( input , encoding ) return _strtobytes_py2 ( input , encoding )
0
determine string encoding python 2
Take a str and transform it into a byte array .
cosqa-train-17201
def strtobytes(input, encoding): """Take a str and transform it into a byte array.""" py_version = sys.version_info[0] if py_version >= 3: return _strtobytes_py3(input, encoding) return _strtobytes_py2(input, encoding)
def has_synset ( word : str ) -> list : return wn . synsets ( lemmatize ( word , neverstem = True ) )
0
python parsing wordnet synsets
Returns a list of synsets of a word after lemmatization .
cosqa-train-17202
def has_synset(word: str) -> list: """" Returns a list of synsets of a word after lemmatization. """ return wn.synsets(lemmatize(word, neverstem=True))
def read_set_from_file ( filename : str ) -> Set [ str ] : collection = set ( ) with open ( filename , 'r' ) as file_ : for line in file_ : collection . add ( line . rstrip ( ) ) return collection
0
python read file ofset
Extract a de - duped collection ( set ) of text from a file . Expected file format is one item per line .
cosqa-train-17203
def read_set_from_file(filename: str) -> Set[str]: """ Extract a de-duped collection (set) of text from a file. Expected file format is one item per line. """ collection = set() with open(filename, 'r') as file_: for line in file_: collection.add(line.rstrip()) return collection
def tsv_escape ( x : Any ) -> str : if x is None : return "" x = str ( x ) return x . replace ( "\t" , "\\t" ) . replace ( "\n" , "\\n" )
1
python csv replacing nulls with empty string
Escape data for tab - separated value ( TSV ) format .
cosqa-train-17204
def tsv_escape(x: Any) -> str: """ Escape data for tab-separated value (TSV) format. """ if x is None: return "" x = str(x) return x.replace("\t", "\\t").replace("\n", "\\n")
def _kbhit_unix ( ) -> bool : dr , dw , de = select . select ( [ sys . stdin ] , [ ] , [ ] , 0 ) return dr != [ ]
0
commands to detect if a key is being pressed in python 3
Under UNIX : is a keystroke available?
cosqa-train-17205
def _kbhit_unix() -> bool: """ Under UNIX: is a keystroke available? """ dr, dw, de = select.select([sys.stdin], [], [], 0) return dr != []
def remove_empty_text ( utterances : List [ Utterance ] ) -> List [ Utterance ] : return [ utter for utter in utterances if utter . text . strip ( ) != "" ]
0
filter empty string python
Remove empty utterances from a list of utterances Args : utterances : The list of utterance we are processing
cosqa-train-17206
def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]: """Remove empty utterances from a list of utterances Args: utterances: The list of utterance we are processing """ return [utter for utter in utterances if utter.text.strip() != ""]
def get_system_drives ( ) : drives = [ ] if os . name == 'nt' : import ctypes bitmask = ctypes . windll . kernel32 . GetLogicalDrives ( ) letter = ord ( 'A' ) while bitmask > 0 : if bitmask & 1 : name = chr ( letter ) + ':' + os . sep if os . path . isdir ( name ) : drives . append ( name ) bitmask >>= 1 letter += 1 else : current_drive = get_drive ( os . getcwd ( ) ) if current_drive : drive = current_drive else : drive = os . sep drives . append ( drive ) return drives
0
python 3 get list of windows drives
Get the available drive names on the system . Always returns a list .
cosqa-train-17207
def get_system_drives(): """ Get the available drive names on the system. Always returns a list. """ drives = [] if os.name == 'nt': import ctypes bitmask = ctypes.windll.kernel32.GetLogicalDrives() letter = ord('A') while bitmask > 0: if bitmask & 1: name = chr(letter) + ':' + os.sep if os.path.isdir(name): drives.append(name) bitmask >>= 1 letter += 1 else: current_drive = get_drive(os.getcwd()) if current_drive: drive = current_drive else: drive = os.sep drives.append(drive) return drives
def area ( self ) : area = 0.0 for segment in self . segments ( ) : area += ( ( segment . p . x * segment . q . y ) - ( segment . q . x * segment . p . y ) ) / 2 return area
1
area of a polygon python
area () - > number
cosqa-train-17208
def area (self): """area() -> number Returns the area of this Polygon. """ area = 0.0 for segment in self.segments(): area += ((segment.p.x * segment.q.y) - (segment.q.x * segment.p.y))/2 return area
def is_rate_limited ( response ) : if ( response . status_code == codes . too_many_requests and 'Retry-After' in response . headers and int ( response . headers [ 'Retry-After' ] ) >= 0 ) : return True return False
1
how to implement rate limit python
Checks if the response has been rate limited by CARTO APIs
cosqa-train-17209
def is_rate_limited(response): """ Checks if the response has been rate limited by CARTO APIs :param response: The response rate limited by CARTO APIs :type response: requests.models.Response class :return: Boolean """ if (response.status_code == codes.too_many_requests and 'Retry-After' in response.headers and int(response.headers['Retry-After']) >= 0): return True return False
def convert_bytes_to_ints ( in_bytes , num ) : dt = numpy . dtype ( '>i' + str ( num ) ) return numpy . frombuffer ( in_bytes , dt )
0
bytes to an array of int python
Convert a byte array into an integer array . The number of bytes forming an integer is defined by num
cosqa-train-17210
def convert_bytes_to_ints(in_bytes, num): """Convert a byte array into an integer array. The number of bytes forming an integer is defined by num :param in_bytes: the input bytes :param num: the number of bytes per int :return the integer array""" dt = numpy.dtype('>i' + str(num)) return numpy.frombuffer(in_bytes, dt)
def last_location_of_minimum ( x ) : x = np . asarray ( x ) return 1.0 - np . argmin ( x [ : : - 1 ] ) / len ( x ) if len ( x ) > 0 else np . NaN
1
minimum value location python
Returns the last location of the minimal value of x . The position is calculated relatively to the length of x .
cosqa-train-17211
def last_location_of_minimum(x): """ Returns the last location of the minimal value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ x = np.asarray(x) return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN
def iprotate ( l , steps = 1 ) : if len ( l ) : steps %= len ( l ) if steps : firstPart = l [ : steps ] del l [ : steps ] l . extend ( firstPart ) return l
0
how to rotate list in python
r Like rotate but modifies l in - place .
cosqa-train-17212
def iprotate(l, steps=1): r"""Like rotate, but modifies `l` in-place. >>> l = [1,2,3] >>> iprotate(l) is l True >>> l [2, 3, 1] >>> iprotate(iprotate(l, 2), -3) [1, 2, 3] """ if len(l): steps %= len(l) if steps: firstPart = l[:steps] del l[:steps] l.extend(firstPart) return l
def bytes_hack ( buf ) : ub = None if sys . version_info > ( 3 , ) : ub = buf else : ub = bytes ( buf ) return ub
0
python 3 shortcut if
Hacky workaround for old installs of the library on systems without python - future that were keeping the 2to3 update from working after auto - update .
cosqa-train-17213
def bytes_hack(buf): """ Hacky workaround for old installs of the library on systems without python-future that were keeping the 2to3 update from working after auto-update. """ ub = None if sys.version_info > (3,): ub = buf else: ub = bytes(buf) return ub
def is_integer ( value : Any ) -> bool : return ( isinstance ( value , int ) and not isinstance ( value , bool ) ) or ( isinstance ( value , float ) and isfinite ( value ) and int ( value ) == value )
1
is it a float or an integer python
Return true if a value is an integer number .
cosqa-train-17214
def is_integer(value: Any) -> bool: """Return true if a value is an integer number.""" return (isinstance(value, int) and not isinstance(value, bool)) or ( isinstance(value, float) and isfinite(value) and int(value) == value )
def split ( text : str ) -> List [ str ] : return [ word for word in SEPARATOR . split ( text ) if word . strip ( ' \t' ) ]
0
python how to split sentence by multiple delimiters
Split a text into a list of tokens .
cosqa-train-17215
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 remove_empty_text ( utterances : List [ Utterance ] ) -> List [ Utterance ] : return [ utter for utter in utterances if utter . text . strip ( ) != "" ]
0
python filter non empty from list
Remove empty utterances from a list of utterances Args : utterances : The list of utterance we are processing
cosqa-train-17216
def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]: """Remove empty utterances from a list of utterances Args: utterances: The list of utterance we are processing """ return [utter for utter in utterances if utter.text.strip() != ""]
def to_int64 ( a ) : # build new dtype and replace i4 --> i8 def promote_i4 ( typestr ) : if typestr [ 1 : ] == 'i4' : typestr = typestr [ 0 ] + 'i8' return typestr dtype = [ ( name , promote_i4 ( typestr ) ) for name , typestr in a . dtype . descr ] return a . astype ( dtype )
1
changing dtype in python to int
Return view of the recarray with all int32 cast to int64 .
cosqa-train-17217
def to_int64(a): """Return view of the recarray with all int32 cast to int64.""" # build new dtype and replace i4 --> i8 def promote_i4(typestr): if typestr[1:] == 'i4': typestr = typestr[0]+'i8' return typestr dtype = [(name, promote_i4(typestr)) for name,typestr in a.dtype.descr] return a.astype(dtype)
def _run_sync ( self , method : Callable , * args , * * kwargs ) -> Any : if self . loop . is_running ( ) : raise RuntimeError ( "Event loop is already running." ) if not self . is_connected : self . loop . run_until_complete ( self . connect ( ) ) task = asyncio . Task ( method ( * args , * * kwargs ) , loop = self . loop ) result = self . loop . run_until_complete ( task ) self . loop . run_until_complete ( self . quit ( ) ) return result
0
python asyncio behave different in linux window
Utility method to run commands synchronously for testing .
cosqa-train-17218
def _run_sync(self, method: Callable, *args, **kwargs) -> Any: """ Utility method to run commands synchronously for testing. """ if self.loop.is_running(): raise RuntimeError("Event loop is already running.") if not self.is_connected: self.loop.run_until_complete(self.connect()) task = asyncio.Task(method(*args, **kwargs), loop=self.loop) result = self.loop.run_until_complete(task) self.loop.run_until_complete(self.quit()) return result
def _duplicates ( list_ ) : item_indices = { } for i , item in enumerate ( list_ ) : try : item_indices [ item ] . append ( i ) except KeyError : # First time seen item_indices [ item ] = [ i ] return item_indices
0
how to index with duplicate indexs python
Return dict mapping item - > indices .
cosqa-train-17219
def _duplicates(list_): """Return dict mapping item -> indices.""" item_indices = {} for i, item in enumerate(list_): try: item_indices[item].append(i) except KeyError: # First time seen item_indices[item] = [i] return item_indices
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 input in correct date format
Retrun True if x is a valid YYYYMMDD date ; otherwise return False .
cosqa-train-17220
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 recClearTag ( element ) : children = element . getchildren ( ) if len ( children ) > 0 : for child in children : recClearTag ( child ) element . tag = clearTag ( element . tag )
1
python elementtree delete namespace
Applies maspy . xml . clearTag () to the tag attribute of the element and recursively to all child elements .
cosqa-train-17221
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 browse_dialog_dir ( ) : _go_to_package ( ) logger_directory . info ( "enter browse_dialog" ) _path_bytes = subprocess . check_output ( [ 'python' , 'gui_dir_browse.py' ] , shell = False ) _path = _fix_path_bytes ( _path_bytes , file = False ) if len ( _path ) >= 1 : _path = _path [ 0 ] else : _path = "" logger_directory . info ( "chosen path: {}" . format ( _path ) ) logger_directory . info ( "exit browse_dialog" ) return _path
1
python dialog choose directory
Open up a GUI browse dialog window and let to user pick a target directory . : return str : Target directory path
cosqa-train-17222
def browse_dialog_dir(): """ Open up a GUI browse dialog window and let to user pick a target directory. :return str: Target directory path """ _go_to_package() logger_directory.info("enter browse_dialog") _path_bytes = subprocess.check_output(['python', 'gui_dir_browse.py'], shell=False) _path = _fix_path_bytes(_path_bytes, file=False) if len(_path) >= 1: _path = _path[0] else: _path = "" logger_directory.info("chosen path: {}".format(_path)) logger_directory.info("exit browse_dialog") return _path
def get_timezone ( ) -> Tuple [ datetime . tzinfo , str ] : dt = get_datetime_now ( ) . astimezone ( ) tzstr = dt . strftime ( "%z" ) tzstr = tzstr [ : - 2 ] + ":" + tzstr [ - 2 : ] return dt . tzinfo , tzstr
1
how to print timezone in python3
Discover the current time zone and it s standard string representation ( for source { d } ) .
cosqa-train-17223
def get_timezone() -> Tuple[datetime.tzinfo, str]: """Discover the current time zone and it's standard string representation (for source{d}).""" dt = get_datetime_now().astimezone() tzstr = dt.strftime("%z") tzstr = tzstr[:-2] + ":" + tzstr[-2:] return dt.tzinfo, tzstr
def read32 ( bytestream ) : dt = np . dtype ( np . uint32 ) . newbyteorder ( '>' ) return np . frombuffer ( bytestream . read ( 4 ) , dtype = dt ) [ 0 ]
0
python binary data in 'decimal from signed 2's complement'
Read 4 bytes from bytestream as an unsigned 32 - bit integer .
cosqa-train-17224
def read32(bytestream): """Read 4 bytes from bytestream as an unsigned 32-bit integer.""" dt = np.dtype(np.uint32).newbyteorder('>') return np.frombuffer(bytestream.read(4), dtype=dt)[0]
def interact ( self , container : Container ) -> None : cmd = "/bin/bash -c 'source /.environment && /bin/bash'" cmd = "docker exec -it {} {}" . format ( container . id , cmd ) subprocess . call ( cmd , shell = True )
1
running shell command from a container in python
Connects to the PTY ( pseudo - TTY ) for a given container . Blocks until the user exits the PTY .
cosqa-train-17225
def interact(self, container: Container) -> None: """ Connects to the PTY (pseudo-TTY) for a given container. Blocks until the user exits the PTY. """ cmd = "/bin/bash -c 'source /.environment && /bin/bash'" cmd = "docker exec -it {} {}".format(container.id, cmd) subprocess.call(cmd, shell=True)
def lower_camel_case_from_underscores ( string ) : components = string . split ( '_' ) string = components [ 0 ] for component in components [ 1 : ] : string += component [ 0 ] . upper ( ) + component [ 1 : ] return string
0
python using underscore as variable
generate a lower - cased camelCase string from an underscore_string . For example : my_variable_name - > myVariableName
cosqa-train-17226
def lower_camel_case_from_underscores(string): """generate a lower-cased camelCase string from an underscore_string. For example: my_variable_name -> myVariableName""" components = string.split('_') string = components[0] for component in components[1:]: string += component[0].upper() + component[1:] return string
def psutil_phymem_usage ( ) : import psutil # This is needed to avoid a deprecation warning error with # newer psutil versions try : percent = psutil . virtual_memory ( ) . percent except : percent = psutil . phymem_usage ( ) . percent return percent
0
python detect memory usage in subprocess
Return physical memory usage ( float ) Requires the cross - platform psutil ( > = v0 . 3 ) library ( https : // github . com / giampaolo / psutil )
cosqa-train-17227
def psutil_phymem_usage(): """ Return physical memory usage (float) Requires the cross-platform psutil (>=v0.3) library (https://github.com/giampaolo/psutil) """ import psutil # This is needed to avoid a deprecation warning error with # newer psutil versions try: percent = psutil.virtual_memory().percent except: percent = psutil.phymem_usage().percent return percent
def butlast ( iterable ) : iterable = iter ( iterable ) try : first = next ( iterable ) except StopIteration : return for second in iterable : yield first first = second
1
list of list in python access last eleemnt of each list
Yield all items from iterable except the last one .
cosqa-train-17228
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 is_natural ( x ) : try : is_integer = int ( x ) == x except ( TypeError , ValueError ) : return False return is_integer and x >= 0
0
how to check if input is a natural number in python
A non - negative integer .
cosqa-train-17229
def is_natural(x): """A non-negative integer.""" try: is_integer = int(x) == x except (TypeError, ValueError): return False return is_integer and x >= 0
def file_exists ( self ) -> bool : cfg_path = self . file_path assert cfg_path return path . isfile ( cfg_path )
0
python check if config file exists
Check if the settings file exists or not
cosqa-train-17230
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 _short_repr ( obj ) : stringified = pprint . saferepr ( obj ) if len ( stringified ) > 200 : return '%s... (%d bytes)' % ( stringified [ : 200 ] , len ( stringified ) ) return stringified
0
python how large can an object be
Helper function returns a truncated repr () of an object .
cosqa-train-17231
def _short_repr(obj): """Helper function returns a truncated repr() of an object.""" stringified = pprint.saferepr(obj) if len(stringified) > 200: return '%s... (%d bytes)' % (stringified[:200], len(stringified)) return stringified
def release_lock ( ) : get_lock . n_lock -= 1 assert get_lock . n_lock >= 0 # Only really release lock once all lock requests have ended. if get_lock . lock_is_enabled and get_lock . n_lock == 0 : get_lock . start_time = None get_lock . unlocker . unlock ( )
0
python lock requests hang
Release lock on compilation directory .
cosqa-train-17232
def release_lock(): """Release lock on compilation directory.""" get_lock.n_lock -= 1 assert get_lock.n_lock >= 0 # Only really release lock once all lock requests have ended. if get_lock.lock_is_enabled and get_lock.n_lock == 0: get_lock.start_time = None get_lock.unlocker.unlock()
def remove_once ( gset , elem ) : remove = getattr ( gset , 'remove' , None ) if remove is not None : remove ( elem ) else : del gset [ elem ] return elem
1
delete an element from a set python
Remove the element from a set lists or dict . >>> L = [ Lucy ] ; S = set ( [ Sky ] ) ; D = { Diamonds : True } ; >>> remove_once ( L Lucy ) ; remove_once ( S Sky ) ; remove_once ( D Diamonds ) ; >>> print L S D [] set ( [] ) {}
cosqa-train-17233
def remove_once(gset, elem): """Remove the element from a set, lists or dict. >>> L = ["Lucy"]; S = set(["Sky"]); D = { "Diamonds": True }; >>> remove_once(L, "Lucy"); remove_once(S, "Sky"); remove_once(D, "Diamonds"); >>> print L, S, D [] set([]) {} Returns the element if it was removed. Raises one of the exceptions in :obj:`RemoveError` otherwise. """ remove = getattr(gset, 'remove', None) if remove is not None: remove(elem) else: del gset[elem] return elem
def prevPlot ( self ) : if self . stacker . currentIndex ( ) > 0 : self . stacker . setCurrentIndex ( self . stacker . currentIndex ( ) - 1 )
1
how to move grid to back of plot python
Moves the displayed plot to the previous one
cosqa-train-17234
def prevPlot(self): """Moves the displayed plot to the previous one""" if self.stacker.currentIndex() > 0: self.stacker.setCurrentIndex(self.stacker.currentIndex()-1)
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
1
python last day of a month
Get the last weekday in a given month . e . g :
cosqa-train-17235
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 find_duplicates ( l : list ) -> set : return set ( [ x for x in l if l . count ( x ) > 1 ] )
0
python code to check duplicates in a list
Return the duplicates in a list .
cosqa-train-17236
def find_duplicates(l: list) -> set: """ Return the duplicates in a list. The function relies on https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list . Parameters ---------- l : list Name Returns ------- set Duplicated values >>> find_duplicates([1,2,3]) set() >>> find_duplicates([1,2,1]) {1} """ return set([x for x in l if l.count(x) > 1])
def change_bgcolor_enable ( self , state ) : self . dataModel . bgcolor ( state ) self . bgcolor_global . setEnabled ( not self . is_series and state > 0 )
0
python kivy set conditions on button background color
This is implementet so column min / max is only active when bgcolor is
cosqa-train-17237
def change_bgcolor_enable(self, state): """ This is implementet so column min/max is only active when bgcolor is """ self.dataModel.bgcolor(state) self.bgcolor_global.setEnabled(not self.is_series and state > 0)
def sorted_chain ( * ranges : Iterable [ Tuple [ int , int ] ] ) -> List [ Tuple [ int , int ] ] : return sorted ( itertools . chain ( * ranges ) )
1
can you set a range on the sort function in python
Chain & sort ranges .
cosqa-train-17238
def sorted_chain(*ranges: Iterable[Tuple[int, int]]) -> List[Tuple[int, int]]: """Chain & sort ranges.""" return sorted(itertools.chain(*ranges))
def csv_to_numpy ( string_like , dtype = None ) : # type: (str) -> np.array stream = StringIO ( string_like ) return np . genfromtxt ( stream , dtype = dtype , delimiter = ',' )
1
python how to read csv into numpy array
Convert a CSV object to a numpy array .
cosqa-train-17239
def csv_to_numpy(string_like, dtype=None): # type: (str) -> np.array """Convert a CSV object to a numpy array. Args: string_like (str): CSV string. dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the contents of each column, individually. This argument can only be used to 'upcast' the array. For downcasting, use the .astype(t) method. Returns: (np.array): numpy array """ stream = StringIO(string_like) return np.genfromtxt(stream, dtype=dtype, delimiter=',')
def remove_once ( gset , elem ) : remove = getattr ( gset , 'remove' , None ) if remove is not None : remove ( elem ) else : del gset [ elem ] return elem
1
how to delete an item from a set python
Remove the element from a set lists or dict . >>> L = [ Lucy ] ; S = set ( [ Sky ] ) ; D = { Diamonds : True } ; >>> remove_once ( L Lucy ) ; remove_once ( S Sky ) ; remove_once ( D Diamonds ) ; >>> print L S D [] set ( [] ) {}
cosqa-train-17240
def remove_once(gset, elem): """Remove the element from a set, lists or dict. >>> L = ["Lucy"]; S = set(["Sky"]); D = { "Diamonds": True }; >>> remove_once(L, "Lucy"); remove_once(S, "Sky"); remove_once(D, "Diamonds"); >>> print L, S, D [] set([]) {} Returns the element if it was removed. Raises one of the exceptions in :obj:`RemoveError` otherwise. """ remove = getattr(gset, 'remove', None) if remove is not None: remove(elem) else: del gset[elem] return elem
def _my_hash ( arg_list ) : # type: (List[Any]) -> int res = 0 for arg in arg_list : res = res * 31 + hash ( arg ) return res
1
invertable hash function python
Simple helper hash function
cosqa-train-17241
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 most_significant_bit ( lst : np . ndarray ) -> int : return np . argwhere ( np . asarray ( lst ) == 1 ) [ 0 ] [ 0 ]
0
get the index of no zero entry in array python
A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s i . e . the first position where a 1 appears reading left to right .
cosqa-train-17242
def most_significant_bit(lst: np.ndarray) -> int: """ A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s, i.e. the first position where a 1 appears, reading left to right. :param lst: a 1d array of 0s and 1s with at least one 1 :return: the first position in lst that a 1 appears """ return np.argwhere(np.asarray(lst) == 1)[0][0]
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 ( )
0
python open file and skip to next line
Skip a section
cosqa-train-17243
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 get_column_names ( engine : Engine , tablename : str ) -> List [ str ] : return [ info . name for info in gen_columns_info ( engine , tablename ) ]
1
python return all column names
Get all the database column names for the specified table .
cosqa-train-17244
def get_column_names(engine: Engine, tablename: str) -> List[str]: """ Get all the database column names for the specified table. """ return [info.name for info in gen_columns_info(engine, tablename)]
def remove_empty_text ( utterances : List [ Utterance ] ) -> List [ Utterance ] : return [ utter for utter in utterances if utter . text . strip ( ) != "" ]
1
python filter empty strings
Remove empty utterances from a list of utterances Args : utterances : The list of utterance we are processing
cosqa-train-17245
def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]: """Remove empty utterances from a list of utterances Args: utterances: The list of utterance we are processing """ return [utter for utter in utterances if utter.text.strip() != ""]
def is_integer ( value : Any ) -> bool : return ( isinstance ( value , int ) and not isinstance ( value , bool ) ) or ( isinstance ( value , float ) and isfinite ( value ) and int ( value ) == value )
0
check if value is number or string with number python
Return true if a value is an integer number .
cosqa-train-17246
def is_integer(value: Any) -> bool: """Return true if a value is an integer number.""" return (isinstance(value, int) and not isinstance(value, bool)) or ( isinstance(value, float) and isfinite(value) and int(value) == value )
def _check_whitespace ( string ) : if string . count ( ' ' ) + string . count ( '\t' ) + string . count ( '\n' ) > 0 : raise ValueError ( INSTRUCTION_HAS_WHITESPACE )
0
if string contains whitespace python
Make sure thre is no whitespace in the given string . Will raise a ValueError if whitespace is detected
cosqa-train-17247
def _check_whitespace(string): """ Make sure thre is no whitespace in the given string. Will raise a ValueError if whitespace is detected """ if string.count(' ') + string.count('\t') + string.count('\n') > 0: raise ValueError(INSTRUCTION_HAS_WHITESPACE)
def remove_nans_1D ( * args ) -> tuple : vals = np . isnan ( args [ 0 ] ) for a in args : vals |= np . isnan ( a ) return tuple ( np . array ( a ) [ ~ vals ] for a in args )
0
python filter nan from array
Remove nans in a set of 1D arrays .
cosqa-train-17248
def remove_nans_1D(*args) -> tuple: """Remove nans in a set of 1D arrays. Removes indicies in all arrays if any array is nan at that index. All input arrays must have the same size. Parameters ---------- args : 1D arrays Returns ------- tuple Tuple of 1D arrays in same order as given, with nan indicies removed. """ vals = np.isnan(args[0]) for a in args: vals |= np.isnan(a) return tuple(np.array(a)[~vals] for a in args)
def rate_limited ( max_per_hour : int , * args : Any ) -> Callable [ ... , Any ] : return util . rate_limited ( max_per_hour , * args )
0
limit function python as close as 100
Rate limit a function .
cosqa-train-17249
def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]: """Rate limit a function.""" return util.rate_limited(max_per_hour, *args)
def clean_map ( obj : Mapping [ Any , Any ] ) -> Mapping [ Any , Any ] : return { k : v for k , v in obj . items ( ) if v is not None }
0
python dic minus value all
Return a new copied dictionary without the keys with None values from the given Mapping object .
cosqa-train-17250
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 get_pylint_options ( config_dir = '.' ) : # type: (str) -> List[str] if PYLINT_CONFIG_NAME in os . listdir ( config_dir ) : pylint_config_path = PYLINT_CONFIG_NAME else : pylint_config_path = DEFAULT_PYLINT_CONFIG_PATH return [ '--rcfile={}' . format ( pylint_config_path ) ]
1
python3 pylint pylintrc path
Checks for local config overrides for pylint and add them in the correct pylint options format .
cosqa-train-17251
def get_pylint_options(config_dir='.'): # type: (str) -> List[str] """Checks for local config overrides for `pylint` and add them in the correct `pylint` `options` format. :param config_dir: :return: List [str] """ if PYLINT_CONFIG_NAME in os.listdir(config_dir): pylint_config_path = PYLINT_CONFIG_NAME else: pylint_config_path = DEFAULT_PYLINT_CONFIG_PATH return ['--rcfile={}'.format(pylint_config_path)]
def prin ( * args , * * kwargs ) : print >> kwargs . get ( 'out' , None ) , " " . join ( [ str ( arg ) for arg in args ] )
1
passing variables to a print function in python
r Like print but a function . I . e . prints out all arguments as print would do . Specify output stream like this ::
cosqa-train-17252
def prin(*args, **kwargs): r"""Like ``print``, but a function. I.e. prints out all arguments as ``print`` would do. Specify output stream like this:: print('ERROR', `out="sys.stderr"``). """ print >> kwargs.get('out',None), " ".join([str(arg) for arg in args])
def iter_lines ( file_like : Iterable [ str ] ) -> Generator [ str , None , None ] : for line in file_like : line = line . rstrip ( '\r\n' ) if line : yield line
0
python readline skip blank lines
Helper for iterating only nonempty lines without line breaks
cosqa-train-17253
def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]: """ Helper for iterating only nonempty lines without line breaks""" for line in file_like: line = line.rstrip('\r\n') if line: yield line
def url_host ( url : str ) -> str : from urllib . parse import urlparse res = urlparse ( url ) return res . netloc . split ( ':' ) [ 0 ] if res . netloc else ''
0
python to get hostname
Parses hostname from URL . : param url : URL : return : hostname
cosqa-train-17254
def url_host(url: str) -> str: """ Parses hostname from URL. :param url: URL :return: hostname """ from urllib.parse import urlparse res = urlparse(url) return res.netloc.split(':')[0] if res.netloc else ''
def validate_django_compatible_with_python ( ) : python_version = sys . version [ : 5 ] django_version = django . get_version ( ) if sys . version_info == ( 2 , 7 ) and django_version >= "2" : click . BadArgumentUsage ( "Please install Django v1.11 for Python {}, or switch to Python >= v3.4" . format ( python_version ) )
0
how to check python versio
Verify Django 1 . 11 is present if Python 2 . 7 is active
cosqa-train-17255
def validate_django_compatible_with_python(): """ Verify Django 1.11 is present if Python 2.7 is active Installation of pinax-cli requires the correct version of Django for the active Python version. If the developer subsequently changes the Python version the installed Django may no longer be compatible. """ python_version = sys.version[:5] django_version = django.get_version() if sys.version_info == (2, 7) and django_version >= "2": click.BadArgumentUsage("Please install Django v1.11 for Python {}, or switch to Python >= v3.4".format(python_version))
def memory_usage ( ) : try : import psutil import os except ImportError : return _memory_usage_ps ( ) process = psutil . Process ( os . getpid ( ) ) mem = process . memory_info ( ) [ 0 ] / float ( 2 ** 20 ) return mem
0
how to get memory used or time to run code in python
return memory usage of python process in MB
cosqa-train-17256
def memory_usage(): """return memory usage of python process in MB from http://fa.bianp.net/blog/2013/different-ways-to-get-memory-consumption-or-lessons-learned-from-memory_profiler/ psutil is quicker >>> isinstance(memory_usage(),float) True """ try: import psutil import os except ImportError: return _memory_usage_ps() process = psutil.Process(os.getpid()) mem = process.memory_info()[0] / float(2 ** 20) return mem
def _check_whitespace ( string ) : if string . count ( ' ' ) + string . count ( '\t' ) + string . count ( '\n' ) > 0 : raise ValueError ( INSTRUCTION_HAS_WHITESPACE )
0
how to check for whitespace string in python
Make sure thre is no whitespace in the given string . Will raise a ValueError if whitespace is detected
cosqa-train-17257
def _check_whitespace(string): """ Make sure thre is no whitespace in the given string. Will raise a ValueError if whitespace is detected """ if string.count(' ') + string.count('\t') + string.count('\n') > 0: raise ValueError(INSTRUCTION_HAS_WHITESPACE)
def recClearTag ( element ) : children = element . getchildren ( ) if len ( children ) > 0 : for child in children : recClearTag ( child ) element . tag = clearTag ( element . tag )
0
remove xml element tree python
Applies maspy . xml . clearTag () to the tag attribute of the element and recursively to all child elements .
cosqa-train-17258
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 position ( self ) -> Position : return Position ( self . _index , self . _lineno , self . _col_offset )
0
how to get cursor position in python on mac os x
The current position of the cursor .
cosqa-train-17259
def position(self) -> Position: """The current position of the cursor.""" return Position(self._index, self._lineno, self._col_offset)
def grep ( pattern , filename ) : try : # for line in file # if line matches pattern: # return line return next ( ( L for L in open ( filename ) if L . find ( pattern ) >= 0 ) ) except StopIteration : return ''
0
hoe to get a matching pattern in a file in python
Very simple grep that returns the first matching line in a file . String matching only does not do REs as currently implemented .
cosqa-train-17260
def grep(pattern, filename): """Very simple grep that returns the first matching line in a file. String matching only, does not do REs as currently implemented. """ try: # for line in file # if line matches pattern: # return line return next((L for L in open(filename) if L.find(pattern) >= 0)) except StopIteration: return ''
def _run_sync ( self , method : Callable , * args , * * kwargs ) -> Any : if self . loop . is_running ( ) : raise RuntimeError ( "Event loop is already running." ) if not self . is_connected : self . loop . run_until_complete ( self . connect ( ) ) task = asyncio . Task ( method ( * args , * * kwargs ) , loop = self . loop ) result = self . loop . run_until_complete ( task ) self . loop . run_until_complete ( self . quit ( ) ) return result
1
how to execute async in python
Utility method to run commands synchronously for testing .
cosqa-train-17261
def _run_sync(self, method: Callable, *args, **kwargs) -> Any: """ Utility method to run commands synchronously for testing. """ if self.loop.is_running(): raise RuntimeError("Event loop is already running.") if not self.is_connected: self.loop.run_until_complete(self.connect()) task = asyncio.Task(method(*args, **kwargs), loop=self.loop) result = self.loop.run_until_complete(task) self.loop.run_until_complete(self.quit()) return result
def find_column ( token ) : i = token . lexpos input = token . lexer . lexdata while i > 0 : if input [ i - 1 ] == '\n' : break i -= 1 column = token . lexpos - i + 1 return column
0
tokenizing a column python
Compute column : input is the input text string token is a token instance
cosqa-train-17262
def find_column(token): """ Compute column: input is the input text string token is a token instance """ i = token.lexpos input = token.lexer.lexdata while i > 0: if input[i - 1] == '\n': break i -= 1 column = token.lexpos - i + 1 return column
def file_uptodate ( fname , cmp_fname ) : try : return ( file_exists ( fname ) and file_exists ( cmp_fname ) and getmtime ( fname ) >= getmtime ( cmp_fname ) ) except OSError : return False
0
python check if file modified in last minute
Check if a file exists is non - empty and is more recent than cmp_fname .
cosqa-train-17263
def file_uptodate(fname, cmp_fname): """Check if a file exists, is non-empty and is more recent than cmp_fname. """ try: return (file_exists(fname) and file_exists(cmp_fname) and getmtime(fname) >= getmtime(cmp_fname)) except OSError: return False
def numeric_part ( s ) : m = re_numeric_part . match ( s ) if m : return int ( m . group ( 1 ) ) return None
0
how to return half of a string in python
Returns the leading numeric part of a string .
cosqa-train-17264
def numeric_part(s): """Returns the leading numeric part of a string. >>> numeric_part("20-alpha") 20 >>> numeric_part("foo") >>> numeric_part("16b") 16 """ m = re_numeric_part.match(s) if m: return int(m.group(1)) return None
def numchannels ( samples : np . ndarray ) -> int : if len ( samples . shape ) == 1 : return 1 else : return samples . shape [ 1 ]
0
python opencv check number of channels in mat
return the number of channels present in samples
cosqa-train-17265
def numchannels(samples:np.ndarray) -> int: """ return the number of channels present in samples samples: a numpy array as returned by sndread for multichannel audio, samples is always interleaved, meaning that samples[n] returns always a frame, which is either a single scalar for mono audio, or an array for multichannel audio. """ if len(samples.shape) == 1: return 1 else: return samples.shape[1]
def exponential_backoff ( attempt : int , cap : int = 1200 ) -> timedelta : base = 3 temp = min ( base * 2 ** attempt , cap ) return timedelta ( seconds = temp / 2 + random . randint ( 0 , temp / 2 ) )
1
implement exponential backoff in python 3
Calculate a delay to retry using an exponential backoff algorithm .
cosqa-train-17266
def exponential_backoff(attempt: int, cap: int=1200) -> timedelta: """Calculate a delay to retry using an exponential backoff algorithm. It is an exponential backoff with random jitter to prevent failures from being retried at the same time. It is a good fit for most applications. :arg attempt: the number of attempts made :arg cap: maximum delay, defaults to 20 minutes """ base = 3 temp = min(base * 2 ** attempt, cap) return timedelta(seconds=temp / 2 + random.randint(0, temp / 2))
def strtobytes ( input , encoding ) : py_version = sys . version_info [ 0 ] if py_version >= 3 : return _strtobytes_py3 ( input , encoding ) return _strtobytes_py2 ( input , encoding )
0
how can i determine the encoding of bytes python3
Take a str and transform it into a byte array .
cosqa-train-17267
def strtobytes(input, encoding): """Take a str and transform it into a byte array.""" py_version = sys.version_info[0] if py_version >= 3: return _strtobytes_py3(input, encoding) return _strtobytes_py2(input, encoding)
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 check if path is absolute path or relative path
simple method to determine if a url is relative or absolute
cosqa-train-17268
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
async def parallel_results ( future_map : Sequence [ Tuple ] ) -> Dict : ctx_methods = OrderedDict ( future_map ) fs = list ( ctx_methods . values ( ) ) results = await asyncio . gather ( * fs ) results = { key : results [ idx ] for idx , key in enumerate ( ctx_methods . keys ( ) ) } return results
0
how to combine asyncio python synchronize
Run parallel execution of futures and return mapping of their results to the provided keys . Just a neat shortcut around asyncio . gather ()
cosqa-train-17269
async def parallel_results(future_map: Sequence[Tuple]) -> Dict: """ Run parallel execution of futures and return mapping of their results to the provided keys. Just a neat shortcut around ``asyncio.gather()`` :param future_map: Keys to futures mapping, e.g.: ( ('nav', get_nav()), ('content, get_content()) ) :return: Dict with futures results mapped to keys {'nav': {1:2}, 'content': 'xyz'} """ ctx_methods = OrderedDict(future_map) fs = list(ctx_methods.values()) results = await asyncio.gather(*fs) results = { key: results[idx] for idx, key in enumerate(ctx_methods.keys()) } return results
def chars ( string : any ) -> str : return '' . join ( [ c if c . isalpha ( ) else '' for c in str ( string ) ] )
0
python how to tell if there is at least one alpha character in a string
Return all ( and only ) the chars in the given string .
cosqa-train-17270
def chars(string: any) -> str: """Return all (and only) the chars in the given string.""" return ''.join([c if c.isalpha() else '' for c in str(string)])
def inverted_dict ( d ) : return dict ( ( force_hashable ( v ) , k ) for ( k , v ) in viewitems ( dict ( d ) ) )
1
reversing key value into new dict python
Return a dict with swapped keys and values
cosqa-train-17271
def inverted_dict(d): """Return a dict with swapped keys and values >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0} True """ return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))
def check_consistent_length ( * arrays ) : uniques = np . unique ( [ _num_samples ( X ) for X in arrays if X is not None ] ) if len ( uniques ) > 1 : raise ValueError ( "Found arrays with inconsistent numbers of samples: %s" % str ( uniques ) )
0
python check if lists has same length
Check that all arrays have consistent first dimensions .
cosqa-train-17272
def check_consistent_length(*arrays): """Check that all arrays have consistent first dimensions. Checks whether all objects in arrays have the same shape or length. Parameters ---------- arrays : list or tuple of input objects. Objects that will be checked for consistent length. """ uniques = np.unique([_num_samples(X) for X in arrays if X is not None]) if len(uniques) > 1: raise ValueError("Found arrays with inconsistent numbers of samples: %s" % str(uniques))
def is_integer ( value : Any ) -> bool : return ( isinstance ( value , int ) and not isinstance ( value , bool ) ) or ( isinstance ( value , float ) and isfinite ( value ) and int ( value ) == value )
0
is python integer or float
Return true if a value is an integer number .
cosqa-train-17273
def is_integer(value: Any) -> bool: """Return true if a value is an integer number.""" return (isinstance(value, int) and not isinstance(value, bool)) or ( isinstance(value, float) and isfinite(value) and int(value) == value )
def bfx ( value , msb , lsb ) : mask = bitmask ( ( msb , lsb ) ) return ( value & mask ) >> lsb
0
bitwise operations not working in python
!
cosqa-train-17274
def bfx(value, msb, lsb): """! @brief Extract a value from a bitfield.""" mask = bitmask((msb, lsb)) return (value & mask) >> lsb
def zfill ( x , width ) : if not isinstance ( x , basestring ) : x = repr ( x ) return x . zfill ( width )
0
python fill zeroes in front of string
zfill ( x width ) - > string
cosqa-train-17275
def zfill(x, width): """zfill(x, width) -> string Pad a numeric string x with zeros on the left, to fill a field of the specified width. The string x is never truncated. """ if not isinstance(x, basestring): x = repr(x) return x.zfill(width)
def maybe_infer_dtype_type ( element ) : tipo = None if hasattr ( element , 'dtype' ) : tipo = element . dtype elif is_list_like ( element ) : element = np . asarray ( element ) tipo = element . dtype return tipo
0
python determine dtype of object
Try to infer an object s dtype for use in arithmetic ops
cosqa-train-17276
def maybe_infer_dtype_type(element): """Try to infer an object's dtype, for use in arithmetic ops Uses `element.dtype` if that's available. Objects implementing the iterator protocol are cast to a NumPy array, and from there the array's type is used. Parameters ---------- element : object Possibly has a `.dtype` attribute, and possibly the iterator protocol. Returns ------- tipo : type Examples -------- >>> from collections import namedtuple >>> Foo = namedtuple("Foo", "dtype") >>> maybe_infer_dtype_type(Foo(np.dtype("i8"))) numpy.int64 """ tipo = None if hasattr(element, 'dtype'): tipo = element.dtype elif is_list_like(element): element = np.asarray(element) tipo = element.dtype return tipo
def _check_whitespace ( string ) : if string . count ( ' ' ) + string . count ( '\t' ) + string . count ( '\n' ) > 0 : raise ValueError ( INSTRUCTION_HAS_WHITESPACE )
0
method to check for any whitespace in python
Make sure thre is no whitespace in the given string . Will raise a ValueError if whitespace is detected
cosqa-train-17277
def _check_whitespace(string): """ Make sure thre is no whitespace in the given string. Will raise a ValueError if whitespace is detected """ if string.count(' ') + string.count('\t') + string.count('\n') > 0: raise ValueError(INSTRUCTION_HAS_WHITESPACE)
def iprotate ( l , steps = 1 ) : if len ( l ) : steps %= len ( l ) if steps : firstPart = l [ : steps ] del l [ : steps ] l . extend ( firstPart ) return l
1
list rotate function in python
r Like rotate but modifies l in - place .
cosqa-train-17278
def iprotate(l, steps=1): r"""Like rotate, but modifies `l` in-place. >>> l = [1,2,3] >>> iprotate(l) is l True >>> l [2, 3, 1] >>> iprotate(iprotate(l, 2), -3) [1, 2, 3] """ if len(l): steps %= len(l) if steps: firstPart = l[:steps] del l[:steps] l.extend(firstPart) return l
def segment_str ( text : str , phoneme_inventory : Set [ str ] = PHONEMES ) -> str : text = text . lower ( ) text = segment_into_tokens ( text , phoneme_inventory ) return text
0
recongnizing words in a sentence in python
Takes as input a string in Kunwinjku and segments it into phoneme - like units based on the standard orthographic rules specified at http : // bininjgunwok . org . au /
cosqa-train-17279
def segment_str(text: str, phoneme_inventory: Set[str] = PHONEMES) -> str: """ Takes as input a string in Kunwinjku and segments it into phoneme-like units based on the standard orthographic rules specified at http://bininjgunwok.org.au/ """ text = text.lower() text = segment_into_tokens(text, phoneme_inventory) return text
def last_modified ( self ) -> Optional [ datetime . datetime ] : httpdate = self . _headers . get ( hdrs . LAST_MODIFIED ) if httpdate is not None : timetuple = parsedate ( httpdate ) if timetuple is not None : return datetime . datetime ( * timetuple [ : 6 ] , tzinfo = datetime . timezone . utc ) return None
1
python get last modified date of file http header lines
The value of Last - Modified HTTP header or None .
cosqa-train-17280
def last_modified(self) -> Optional[datetime.datetime]: """The value of Last-Modified HTTP header, or None. This header is represented as a `datetime` object. """ httpdate = self._headers.get(hdrs.LAST_MODIFIED) if httpdate is not None: timetuple = parsedate(httpdate) if timetuple is not None: return datetime.datetime(*timetuple[:6], tzinfo=datetime.timezone.utc) return None
def tofile ( self , fileobj ) : for entry in self : print >> fileobj , str ( entry ) fileobj . close ( )
1
how to print out cache in python
write a cache object to the fileobj as a lal cache file
cosqa-train-17281
def tofile(self, fileobj): """ write a cache object to the fileobj as a lal cache file """ for entry in self: print >>fileobj, str(entry) fileobj.close()
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 ] )
0
python print list %s only certain length
Print at most limit elements of list .
cosqa-train-17282
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 _tree_line ( self , no_type : bool = False ) -> str : return self . _tree_line_prefix ( ) + " " + self . iname ( )
1
creating a tree diagram in python
Return the receiver s contribution to tree diagram .
cosqa-train-17283
def _tree_line(self, no_type: bool = False) -> str: """Return the receiver's contribution to tree diagram.""" return self._tree_line_prefix() + " " + self.iname()
def uconcatenate ( arrs , axis = 0 ) : v = np . concatenate ( arrs , axis = axis ) v = _validate_numpy_wrapper_units ( v , arrs ) return v
0
python concatenate np arrays
Concatenate a sequence of arrays .
cosqa-train-17284
def uconcatenate(arrs, axis=0): """Concatenate a sequence of arrays. This wrapper around numpy.concatenate preserves units. All input arrays must have the same units. See the documentation of numpy.concatenate for full details. Examples -------- >>> from unyt import cm >>> A = [1, 2, 3]*cm >>> B = [2, 3, 4]*cm >>> uconcatenate((A, B)) unyt_array([1, 2, 3, 2, 3, 4], 'cm') """ v = np.concatenate(arrs, axis=axis) v = _validate_numpy_wrapper_units(v, arrs) return v
def _parse_tuple_string ( argument ) : if isinstance ( argument , str ) : return tuple ( int ( p . strip ( ) ) for p in argument . split ( ',' ) ) return argument
0
get 3 separate values froma tuple python
Return a tuple from parsing a b c d - > ( a b c d )
cosqa-train-17285
def _parse_tuple_string(argument): """ Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) """ if isinstance(argument, str): return tuple(int(p.strip()) for p in argument.split(',')) return argument
def get_from_gnucash26_date ( date_str : str ) -> date : date_format = "%Y%m%d" result = datetime . strptime ( date_str , date_format ) . date ( ) return result
0
python 3 cast string to date
Creates a datetime from GnuCash 2 . 6 date string
cosqa-train-17286
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 camel_to_snake_case ( string ) : s = _1 . sub ( r'\1_\2' , string ) return _2 . sub ( r'\1_\2' , s ) . lower ( )
0
change a python value to uppercase
Converts string presented in camel case to snake case .
cosqa-train-17287
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 count ( args ) : counts = defaultdict ( int ) for arg in args : for item in arg : counts [ item ] = counts [ item ] + 1 return counts
0
count function in python for list
count occurences in a list of lists >>> count ( [[ a b ] [ a ]] ) defaultdict ( int { a : 2 b : 1 } )
cosqa-train-17288
def count(args): """ count occurences in a list of lists >>> count([['a','b'],['a']]) defaultdict(int, {'a' : 2, 'b' : 1}) """ counts = defaultdict(int) for arg in args: for item in arg: counts[item] = counts[item] + 1 return counts
def encode_list ( key , list_ ) : # type: (str, Iterable) -> Dict[str, str] if not list_ : return { } return { key : " " . join ( str ( i ) for i in list_ ) }
1
strings inside lists inside a dictionary python
Converts a list into a space - separated string and puts it in a dictionary
cosqa-train-17289
def encode_list(key, list_): # type: (str, Iterable) -> Dict[str, str] """ Converts a list into a space-separated string and puts it in a dictionary :param key: Dictionary key to store the list :param list_: A list of objects :return: A dictionary key->string or an empty dictionary """ if not list_: return {} return {key: " ".join(str(i) for i in list_)}
def natural_sort ( list_to_sort : Iterable [ str ] ) -> List [ str ] : return sorted ( list_to_sort , key = natural_keys )
1
sort the given list without using sort function in python
Sorts a list of strings case insensitively as well as numerically .
cosqa-train-17290
def natural_sort(list_to_sort: Iterable[str]) -> List[str]: """ Sorts a list of strings case insensitively as well as numerically. For example: ['a1', 'A2', 'a3', 'A11', 'a22'] To sort a list in place, don't call this method, which makes a copy. Instead, do this: my_list.sort(key=natural_keys) :param list_to_sort: the list being sorted :return: the list sorted naturally """ return sorted(list_to_sort, key=natural_keys)
def last_location_of_minimum ( x ) : x = np . asarray ( x ) return 1.0 - np . argmin ( x [ : : - 1 ] ) / len ( x ) if len ( x ) > 0 else np . NaN
0
python return the index of the minimum
Returns the last location of the minimal value of x . The position is calculated relatively to the length of x .
cosqa-train-17291
def last_location_of_minimum(x): """ Returns the last location of the minimal value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ x = np.asarray(x) return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN
def has_synset ( word : str ) -> list : return wn . synsets ( lemmatize ( word , neverstem = True ) )
0
how to create acronyms with removed words using python
Returns a list of synsets of a word after lemmatization .
cosqa-train-17292
def has_synset(word: str) -> list: """" Returns a list of synsets of a word after lemmatization. """ return wn.synsets(lemmatize(word, neverstem=True))
def are_token_parallel ( sequences : Sequence [ Sized ] ) -> bool : if not sequences or len ( sequences ) == 1 : return True return all ( len ( s ) == len ( sequences [ 0 ] ) for s in sequences )
0
python check list is sequential
Returns True if all sequences in the list have the same length .
cosqa-train-17293
def are_token_parallel(sequences: Sequence[Sized]) -> bool: """ Returns True if all sequences in the list have the same length. """ if not sequences or len(sequences) == 1: return True return all(len(s) == len(sequences[0]) for s in sequences)
def release_lock ( ) : get_lock . n_lock -= 1 assert get_lock . n_lock >= 0 # Only really release lock once all lock requests have ended. if get_lock . lock_is_enabled and get_lock . n_lock == 0 : get_lock . start_time = None get_lock . unlocker . unlock ( )
1
nodejs equivalent of lock python
Release lock on compilation directory .
cosqa-train-17294
def release_lock(): """Release lock on compilation directory.""" get_lock.n_lock -= 1 assert get_lock.n_lock >= 0 # Only really release lock once all lock requests have ended. if get_lock.lock_is_enabled and get_lock.n_lock == 0: get_lock.start_time = None get_lock.unlocker.unlock()
def _ ( f , x ) : return { k : v for k , v in x . items ( ) if f ( k , v ) }
0
python filter value dict
filter for dict note f should have signature : f :: key - > value - > bool
cosqa-train-17295
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 list_to_str ( list , separator = ',' ) : list = [ str ( x ) for x in list ] return separator . join ( list )
1
numbers in a list to string python
>>> list = [ 0 0 7 ] >>> list_to_str ( list ) 0 0 7
cosqa-train-17296
def list_to_str(list, separator=','): """ >>> list = [0, 0, 7] >>> list_to_str(list) '0,0,7' """ list = [str(x) for x in list] return separator.join(list)
def margin ( text ) : lines = str ( text ) . split ( '\n' ) return '\n' . join ( ' {} ' . format ( l ) for l in lines )
0
is there a equivalent of a margin command in python
r Add a margin to both ends of each line in the string .
cosqa-train-17297
def margin(text): r"""Add a margin to both ends of each line in the string. Example: >>> margin('line1\nline2') ' line1 \n line2 ' """ lines = str(text).split('\n') return '\n'.join(' {} '.format(l) for l in lines)
def get_period_last_3_months ( ) -> str : today = Datum ( ) today . today ( ) # start_date = today - timedelta(weeks=13) start_date = today . clone ( ) start_date . subtract_months ( 3 ) period = get_period ( start_date . date , today . date ) return period
1
python get last of previous month
Returns the last week as a period string
cosqa-train-17298
def get_period_last_3_months() -> str: """ Returns the last week as a period string """ today = Datum() today.today() # start_date = today - timedelta(weeks=13) start_date = today.clone() start_date.subtract_months(3) period = get_period(start_date.date, today.date) return period
def split ( text : str ) -> List [ str ] : return [ word for word in SEPARATOR . split ( text ) if word . strip ( ' \t' ) ]
1
split a particular sentence in a list with a delimiter in python
Split a text into a list of tokens .
cosqa-train-17299
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')]