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 most_significant_bit ( lst : np . ndarray ) -> int : return np . argwhere ( np . asarray ( lst ) == 1 ) [ 0 ] [ 0 ]
1
index of nonzero value 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-18700
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 string ( value ) -> str : return system_json . dumps ( Json ( value ) . safe_object ( ) , ensure_ascii = False )
1
python json quotes in string
string dict / object / value to JSON
cosqa-train-18701
def string(value) -> str: """ string dict/object/value to JSON """ return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)
def is_up_to_date ( outfile , basedatetime ) : # type: (AnyStr, datetime) -> bool if os . path . exists ( outfile ) : if os . path . getmtime ( outfile ) >= basedatetime : return True return False
1
how to check datatime now older than fixed date python
Return true if outfile exists and is no older than base datetime .
cosqa-train-18702
def is_up_to_date(outfile, basedatetime): # type: (AnyStr, datetime) -> bool """Return true if outfile exists and is no older than base datetime.""" if os.path.exists(outfile): if os.path.getmtime(outfile) >= basedatetime: return True return False
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
get a date from a string pythong
Creates a datetime from GnuCash 2 . 6 date string
cosqa-train-18703
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 _parse_date ( string : str ) -> datetime . date : return datetime . datetime . strptime ( string , '%Y-%m-%d' ) . date ( )
1
python recognize date string as date
Parse an ISO format date ( YYYY - mm - dd ) .
cosqa-train-18704
def _parse_date(string: str) -> datetime.date: """Parse an ISO format date (YYYY-mm-dd). >>> _parse_date('1990-01-02') datetime.date(1990, 1, 2) """ return datetime.datetime.strptime(string, '%Y-%m-%d').date()
def s3_get ( url : str , temp_file : IO ) -> None : s3_resource = boto3 . resource ( "s3" ) bucket_name , s3_path = split_s3_path ( url ) s3_resource . Bucket ( bucket_name ) . download_fileobj ( s3_path , temp_file )
1
how to download file from s3 using python code
Pull a file directly from S3 .
cosqa-train-18705
def s3_get(url: str, temp_file: IO) -> None: """Pull a file directly from S3.""" s3_resource = boto3.resource("s3") bucket_name, s3_path = split_s3_path(url) s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)
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
0
python rate limit requests
Checks if the response has been rate limited by CARTO APIs
cosqa-train-18706
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 __remove_trailing_zeros ( self , collection ) : index = len ( collection ) - 1 while index >= 0 and collection [ index ] == 0 : index -= 1 return collection [ : index + 1 ]
0
get rid of leading zeroes python
Removes trailing zeroes from indexable collection of numbers
cosqa-train-18707
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 has_changed ( filename ) : key = os . path . abspath ( filename ) mtime = get_mtime ( key ) if key not in _mtime_cache : _mtime_cache [ key ] = mtime return True return mtime > _mtime_cache [ key ]
1
how to check if a file has been changed in python 3
Check if filename has changed since the last check . If this is the first check assume the file is changed .
cosqa-train-18708
def has_changed (filename): """Check if filename has changed since the last check. If this is the first check, assume the file is changed.""" key = os.path.abspath(filename) mtime = get_mtime(key) if key not in _mtime_cache: _mtime_cache[key] = mtime return True return mtime > _mtime_cache[key]
def shape ( self ) -> Tuple [ int , ... ] : return tuple ( bins . bin_count for bins in self . _binnings )
1
return the number of items in histogram plot in python
Shape of histogram s data .
cosqa-train-18709
def shape(self) -> Tuple[int, ...]: """Shape of histogram's data. Returns ------- One-element tuple with the number of bins along each axis. """ return tuple(bins.bin_count for bins in self._binnings)
def pack_bits ( longbits ) : byte = longbits & ( 0x0101010101010101 ) byte = ( byte | ( byte >> 7 ) ) & ( 0x0003000300030003 ) byte = ( byte | ( byte >> 14 ) ) & ( 0x0000000f0000000f ) byte = ( byte | ( byte >> 28 ) ) & ( 0x00000000000000ff ) return byte
0
python good bit equivalent
Crunch a 64 - bit int ( 8 bool bytes ) into a bitfield .
cosqa-train-18710
def pack_bits( longbits ): """Crunch a 64-bit int (8 bool bytes) into a bitfield.""" byte = longbits & (0x0101010101010101) byte = (byte | (byte>>7)) & (0x0003000300030003) byte = (byte | (byte>>14)) & (0x0000000f0000000f) byte = (byte | (byte>>28)) & (0x00000000000000ff) return byte
def header_status ( header ) : status_line = header [ : header . find ( '\r' ) ] # 'HTTP/1.1 200 OK' -> (200, 'OK') fields = status_line . split ( None , 2 ) return int ( fields [ 1 ] ) , fields [ 2 ]
1
python read http status from raw
Parse HTTP status line return status ( int ) and reason .
cosqa-train-18711
def header_status(header): """Parse HTTP status line, return status (int) and reason.""" status_line = header[:header.find('\r')] # 'HTTP/1.1 200 OK' -> (200, 'OK') fields = status_line.split(None, 2) return int(fields[1]), fields[2]
def snake_to_camel ( s : str ) -> str : fragments = s . split ( '_' ) return fragments [ 0 ] + '' . join ( x . title ( ) for x in fragments [ 1 : ] )
0
how to capitalize everything in a string python
Convert string from snake case to camel case .
cosqa-train-18712
def snake_to_camel(s: str) -> str: """Convert string from snake case to camel case.""" fragments = s.split('_') return fragments[0] + ''.join(x.title() for x in fragments[1:])
def has_key ( cls , * args ) : key = args if len ( args ) > 1 else args [ 0 ] return key in cls . _instances
0
python create key if don't exist
Check whether flyweight object with specified key has already been created .
cosqa-train-18713
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 find_first_in_list ( txt : str , str_list : [ str ] ) -> int : # type: ignore start = len ( txt ) + 1 for item in str_list : if start > txt . find ( item ) > - 1 : start = txt . find ( item ) return start if len ( txt ) + 1 > start > - 1 else - 1
1
python function to detect first element of list
Returns the index of the earliest occurence of an item from a list in a string
cosqa-train-18714
def find_first_in_list(txt: str, str_list: [str]) -> int: # type: ignore """ Returns the index of the earliest occurence of an item from a list in a string Ex: find_first_in_list('foobar', ['bar', 'fin']) -> 3 """ start = len(txt) + 1 for item in str_list: if start > txt.find(item) > -1: start = txt.find(item) return start if len(txt) + 1 > start > -1 else -1
def array_to_npy ( array_like ) : # type: (np.array or Iterable or int or float) -> object buffer = BytesIO ( ) np . save ( buffer , array_like ) return buffer . getvalue ( )
0
change numyp array to just values python
Convert an array like object to the NPY format .
cosqa-train-18715
def array_to_npy(array_like): # type: (np.array or Iterable or int or float) -> object """Convert an array like object to the NPY format. To understand better what an array like object is see: https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays Args: array_like (np.array or Iterable or int or float): array like object to be converted to NPY. Returns: (obj): NPY array. """ buffer = BytesIO() np.save(buffer, array_like) return buffer.getvalue()
def butlast ( iterable ) : iterable = iter ( iterable ) try : first = next ( iterable ) except StopIteration : return for second in iterable : yield first first = second
0
in python how to output the last item in a list
Yield all items from iterable except the last one .
cosqa-train-18716
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 indent ( text : str , num : int = 2 ) -> str : lines = text . splitlines ( ) return "\n" . join ( indent_iterable ( lines , num = num ) )
0
minmum number of spaces indented space python
Indent a piece of text .
cosqa-train-18717
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 percent_of ( percent , whole ) : percent = float ( percent ) whole = float ( whole ) return ( percent * whole ) / 100
0
how to make a number a percent python
Calculates the value of a percent of a number ie : 5% of 20 is what -- > 1 Args : percent ( float ) : The percent of a number whole ( float ) : The whole of the number Returns : float : The value of a percent Example : >>> percent_of ( 25 100 ) 25 . 0 >>> percent_of ( 5 20 ) 1 . 0
cosqa-train-18718
def percent_of(percent, whole): """Calculates the value of a percent of a number ie: 5% of 20 is what --> 1 Args: percent (float): The percent of a number whole (float): The whole of the number Returns: float: The value of a percent Example: >>> percent_of(25, 100) 25.0 >>> percent_of(5, 20) 1.0 """ percent = float(percent) whole = float(whole) return (percent * whole) / 100
def guess_mimetype ( filename ) : fn = os . path . basename ( filename ) return mimetypes . guess_type ( fn ) [ 0 ] or 'application/octet-stream'
0
python determine mime type of a file
Guesses the mimetype of a file based on the given filename .
cosqa-train-18719
def guess_mimetype(filename): """Guesses the mimetype of a file based on the given ``filename``. .. code-block:: python >>> guess_mimetype('example.txt') 'text/plain' >>> guess_mimetype('/foo/bar/example') 'application/octet-stream' Parameters ---------- filename : str The file name or path for which the mimetype is to be guessed """ fn = os.path.basename(filename) return mimetypes.guess_type(fn)[0] or 'application/octet-stream'
def enum_mark_last ( iterable , start = 0 ) : it = iter ( iterable ) count = start try : last = next ( it ) except StopIteration : return for val in it : yield count , False , last last = val count += 1 yield count , True , last
0
enumerate python last item
Returns a generator over iterable that tells whether the current item is the last one . Usage : >>> iterable = range ( 10 ) >>> for index is_last item in enum_mark_last ( iterable ) : >>> print ( index item end = \ n if is_last else )
cosqa-train-18720
def enum_mark_last(iterable, start=0): """ Returns a generator over iterable that tells whether the current item is the last one. Usage: >>> iterable = range(10) >>> for index, is_last, item in enum_mark_last(iterable): >>> print(index, item, end='\n' if is_last else ', ') """ it = iter(iterable) count = start try: last = next(it) except StopIteration: return for val in it: yield count, False, last last = val count += 1 yield count, True, last
def hsv2rgb_spectrum ( hsv ) : h , s , v = hsv return hsv2rgb_raw ( ( ( h * 192 ) >> 8 , s , v ) )
0
opencv rgb to hsi in python
Generates RGB values from HSV values in line with a typical light spectrum .
cosqa-train-18721
def hsv2rgb_spectrum(hsv): """Generates RGB values from HSV values in line with a typical light spectrum.""" h, s, v = hsv return hsv2rgb_raw(((h * 192) >> 8, s, v))
def inverted_dict ( d ) : return dict ( ( force_hashable ( v ) , k ) for ( k , v ) in viewitems ( dict ( d ) ) )
0
python fastest way to reverse dict
Return a dict with swapped keys and values
cosqa-train-18722
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 get_tokens ( line : str ) -> Iterator [ str ] : for token in line . rstrip ( ) . split ( ) : if len ( token ) > 0 : yield token
1
how to parse a line into tokens in python
Yields tokens from input string .
cosqa-train-18723
def get_tokens(line: str) -> Iterator[str]: """ Yields tokens from input string. :param line: Input string. :return: Iterator over tokens. """ for token in line.rstrip().split(): if len(token) > 0: yield token
def getElementByWdomId ( id : str ) -> Optional [ WebEventTarget ] : if not id : return None elif id == 'document' : return get_document ( ) elif id == 'window' : return get_document ( ) . defaultView elm = WdomElement . _elements_with_wdom_id . get ( id ) return elm
0
wxpython get widget by id
Get element with wdom_id .
cosqa-train-18724
def getElementByWdomId(id: str) -> Optional[WebEventTarget]: """Get element with ``wdom_id``.""" if not id: return None elif id == 'document': return get_document() elif id == 'window': return get_document().defaultView elm = WdomElement._elements_with_wdom_id.get(id) return elm
def returned ( n ) : ## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk for pos in randwalk ( ) >> drop ( 1 ) >> takei ( xrange ( n - 1 ) ) : if pos == Origin : return True return False
0
biased random walk with bound in python
Generate a random walk and return True if the walker has returned to the origin after taking n steps .
cosqa-train-18725
def returned(n): """Generate a random walk and return True if the walker has returned to the origin after taking `n` steps. """ ## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk for pos in randwalk() >> drop(1) >> takei(xrange(n-1)): if pos == Origin: return True return False
def _ ( f , x ) : return { k : v for k , v in x . items ( ) if f ( k , v ) }
0
python using lambda on dictionary
filter for dict note f should have signature : f :: key - > value - > bool
cosqa-train-18726
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 fast_median ( a ) : a = checkma ( a ) #return scoreatpercentile(a.compressed(), 50) if a . count ( ) > 0 : out = np . percentile ( a . compressed ( ) , 50 ) else : out = np . ma . masked return out
0
python plot the median of a column in an array
Fast median operation for masked array using 50th - percentile
cosqa-train-18727
def fast_median(a): """Fast median operation for masked array using 50th-percentile """ a = checkma(a) #return scoreatpercentile(a.compressed(), 50) if a.count() > 0: out = np.percentile(a.compressed(), 50) else: out = np.ma.masked return out
def viewport_to_screen_space ( framebuffer_size : vec2 , point : vec4 ) -> vec2 : return ( framebuffer_size * point . xy ) / point . w
0
python half of screen pixels
Transform point in viewport space to screen space .
cosqa-train-18728
def viewport_to_screen_space(framebuffer_size: vec2, point: vec4) -> vec2: """Transform point in viewport space to screen space.""" return (framebuffer_size * point.xy) / point.w
def indexes_equal ( a : Index , b : Index ) -> bool : return str ( a ) == str ( b )
0
how to check if two strings are the same in python
Are two indexes equal? Checks by comparing str () versions of them . ( AM UNSURE IF THIS IS ENOUGH . )
cosqa-train-18729
def indexes_equal(a: Index, b: Index) -> bool: """ Are two indexes equal? Checks by comparing ``str()`` versions of them. (AM UNSURE IF THIS IS ENOUGH.) """ return str(a) == str(b)
def _cnx_is_empty ( in_file ) : with open ( in_file ) as in_handle : for i , line in enumerate ( in_handle ) : if i > 0 : return False return True
0
how to check for empty file in python
Check if cnr or cns files are empty ( only have a header )
cosqa-train-18730
def _cnx_is_empty(in_file): """Check if cnr or cns files are empty (only have a header) """ with open(in_file) as in_handle: for i, line in enumerate(in_handle): if i > 0: return False return True
def is_running ( process_id : int ) -> bool : pstr = str ( process_id ) encoding = sys . getdefaultencoding ( ) s = subprocess . Popen ( [ "ps" , "-p" , pstr ] , stdout = subprocess . PIPE ) for line in s . stdout : strline = line . decode ( encoding ) if pstr in strline : return True return False
0
python check for a specific process
Uses the Unix ps program to see if a process is running .
cosqa-train-18731
def is_running(process_id: int) -> bool: """ Uses the Unix ``ps`` program to see if a process is running. """ pstr = str(process_id) encoding = sys.getdefaultencoding() s = subprocess.Popen(["ps", "-p", pstr], stdout=subprocess.PIPE) for line in s.stdout: strline = line.decode(encoding) if pstr in strline: return True return False
def datetime_is_iso ( date_str ) : try : if len ( date_str ) > 10 : dt = isodate . parse_datetime ( date_str ) else : dt = isodate . parse_date ( date_str ) return True , [ ] except : # Any error qualifies as not ISO format return False , [ 'Datetime provided is not in a valid ISO 8601 format' ]
1
python check date format in iso
Attempts to parse a date formatted in ISO 8601 format
cosqa-train-18732
def datetime_is_iso(date_str): """Attempts to parse a date formatted in ISO 8601 format""" try: if len(date_str) > 10: dt = isodate.parse_datetime(date_str) else: dt = isodate.parse_date(date_str) return True, [] except: # Any error qualifies as not ISO format return False, ['Datetime provided is not in a valid ISO 8601 format']
def index_exists ( self , table : str , indexname : str ) -> bool : # MySQL: sql = ( "SELECT COUNT(*) FROM information_schema.statistics" " WHERE table_name=? AND index_name=?" ) row = self . fetchone ( sql , table , indexname ) return True if row [ 0 ] >= 1 else False
0
check if column exists by index python
Does an index exist? ( Specific to MySQL . )
cosqa-train-18733
def index_exists(self, table: str, indexname: str) -> bool: """Does an index exist? (Specific to MySQL.)""" # MySQL: sql = ("SELECT COUNT(*) FROM information_schema.statistics" " WHERE table_name=? AND index_name=?") row = self.fetchone(sql, table, indexname) return True if row[0] >= 1 else False
def moving_average ( arr : np . ndarray , n : int = 3 ) -> np . ndarray : ret = np . cumsum ( arr , dtype = float ) ret [ n : ] = ret [ n : ] - ret [ : - n ] return ret [ n - 1 : ] / n
0
python how to calculate moving average in a window
Calculate the moving overage over an array .
cosqa-train-18734
def moving_average(arr: np.ndarray, n: int = 3) -> np.ndarray: """ Calculate the moving overage over an array. Algorithm from: https://stackoverflow.com/a/14314054 Args: arr (np.ndarray): Array over which to calculate the moving average. n (int): Number of elements over which to calculate the moving average. Default: 3 Returns: np.ndarray: Moving average calculated over n. """ ret = np.cumsum(arr, dtype=float) ret[n:] = ret[n:] - ret[:-n] return ret[n - 1:] / n
def argmax ( self , rows : List [ Row ] , column : ComparableColumn ) -> List [ Row ] : if not rows : return [ ] value_row_pairs = [ ( row . values [ column . name ] , row ) for row in rows ] if not value_row_pairs : return [ ] # Returns a list containing the row with the max cell value. return [ sorted ( value_row_pairs , key = lambda x : x [ 0 ] , reverse = True ) [ 0 ] [ 1 ] ]
1
python get row with max value
Takes a list of rows and a column name and returns a list containing a single row ( dict from columns to cells ) that has the maximum numerical value in the given column . We return a list instead of a single dict to be consistent with the return type of select and all_rows .
cosqa-train-18735
def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]: """ Takes a list of rows and a column name and returns a list containing a single row (dict from columns to cells) that has the maximum numerical value in the given column. We return a list instead of a single dict to be consistent with the return type of ``select`` and ``all_rows``. """ if not rows: return [] value_row_pairs = [(row.values[column.name], row) for row in rows] if not value_row_pairs: return [] # Returns a list containing the row with the max cell value. return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]
def truncate ( value : Decimal , n_digits : int ) -> Decimal : return Decimal ( math . trunc ( value * ( 10 ** n_digits ) ) ) / ( 10 ** n_digits )
1
truncate a number after certain amount of decimals in python
Truncates a value to a number of decimals places
cosqa-train-18736
def truncate(value: Decimal, n_digits: int) -> Decimal: """Truncates a value to a number of decimals places""" return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)
def string ( value ) -> str : return system_json . dumps ( Json ( value ) . safe_object ( ) , ensure_ascii = False )
0
python map to json str
string dict / object / value to JSON
cosqa-train-18737
def string(value) -> str: """ string dict/object/value to JSON """ return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)
def dotproduct ( X , Y ) : return sum ( [ x * y for x , y in zip ( X , Y ) ] )
0
computing the product in python
Return the sum of the element - wise product of vectors x and y . >>> dotproduct ( [ 1 2 3 ] [ 1000 100 10 ] ) 1230
cosqa-train-18738
def dotproduct(X, Y): """Return the sum of the element-wise product of vectors x and y. >>> dotproduct([1, 2, 3], [1000, 100, 10]) 1230 """ return sum([x * y for x, y in zip(X, Y)])
def __remove_trailing_zeros ( self , collection ) : index = len ( collection ) - 1 while index >= 0 and collection [ index ] == 0 : index -= 1 return collection [ : index + 1 ]
0
function to remove trailing zeros in python
Removes trailing zeroes from indexable collection of numbers
cosqa-train-18739
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 genfirstvalues ( cursor : Cursor , arraysize : int = 1000 ) -> Generator [ Any , None , None ] : return ( row [ 0 ] for row in genrows ( cursor , arraysize ) )
0
return first 100 rows python
Generate the first value in each row .
cosqa-train-18740
def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \ -> Generator[Any, None, None]: """ Generate the first value in each row. Args: cursor: the cursor arraysize: split fetches into chunks of this many records Yields: the first value of each row """ return (row[0] for row in genrows(cursor, arraysize))
def from_file ( file_path ) -> dict : with io . open ( file_path , 'r' , encoding = 'utf-8' ) as json_stream : return Json . parse ( json_stream , True )
0
load a json python
Load JSON file
cosqa-train-18741
def from_file(file_path) -> dict: """ Load JSON file """ with io.open(file_path, 'r', encoding='utf-8') as json_stream: return Json.parse(json_stream, True)
def right_replace ( string , old , new , count = 1 ) : if not string : return string return new . join ( string . rsplit ( old , count ) )
0
python string replace last occureance
Right replaces count occurrences of old with new in string . For example ::
cosqa-train-18742
def right_replace(string, old, new, count=1): """ Right replaces ``count`` occurrences of ``old`` with ``new`` in ``string``. For example:: right_replace('one_two_two', 'two', 'three') -> 'one_two_three' """ if not string: return string return new.join(string.rsplit(old, count))
def count ( args ) : counts = defaultdict ( int ) for arg in args : for item in arg : counts [ item ] = counts [ item ] + 1 return counts
1
count occurnaces in a list python
count occurences in a list of lists >>> count ( [[ a b ] [ a ]] ) defaultdict ( int { a : 2 b : 1 } )
cosqa-train-18743
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 proper_round ( n ) : return int ( n ) + ( n / abs ( n ) ) * int ( abs ( n - int ( n ) ) >= 0.5 ) if n != 0 else 0
0
rounding to the nearest preset number python
rounds float to closest int : rtype : int : param n : float
cosqa-train-18744
def proper_round(n): """ rounds float to closest int :rtype: int :param n: float """ return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0
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 )
1
how to check the len of every element if it is equal to each other at the same time in python
Returns True if all sequences in the list have the same length .
cosqa-train-18745
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 exclude_from ( l , containing = [ ] , equal_to = [ ] ) : cont = lambda li : any ( c in li for c in containing ) eq = lambda li : any ( e == li for e in equal_to ) return [ li for li in l if not ( cont ( li ) or eq ( li ) ) ]
0
how to exclude certain text as condition for list comprehension in python
Exclude elements in list l containing any elements from list ex . Example : >>> l = [ bob r rob \ r \ r \ nrobert ] >>> containing = [ \ n \ r ] >>> equal_to = [ r ] >>> exclude_from ( l containing equal_to ) [ bob ]
cosqa-train-18746
def exclude_from(l, containing = [], equal_to = []): """Exclude elements in list l containing any elements from list ex. Example: >>> l = ['bob', 'r', 'rob\r', '\r\nrobert'] >>> containing = ['\n', '\r'] >>> equal_to = ['r'] >>> exclude_from(l, containing, equal_to) ['bob'] """ cont = lambda li: any(c in li for c in containing) eq = lambda li: any(e == li for e in equal_to) return [li for li in l if not (cont(li) or eq(li))]
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 whether a date is valid
Retrun True if x is a valid YYYYMMDD date ; otherwise return False .
cosqa-train-18747
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 flatten_list ( l : List [ list ] ) -> list : return [ v for inner_l in l for v in inner_l ]
0
python flatten list comprehension
takes a list of lists l and returns a flat list
cosqa-train-18748
def flatten_list(l: List[list]) -> list: """ takes a list of lists, l and returns a flat list """ return [v for inner_l in l for v in inner_l]
def clean_all_buckets ( self ) : bucket_keys = self . redis_object . keys ( pattern = 'nearpy_*' ) if len ( bucket_keys ) > 0 : self . redis_object . delete ( * bucket_keys )
0
python boto3 dynamodb delete all items
Removes all buckets from all hashes and their content .
cosqa-train-18749
def clean_all_buckets(self): """ Removes all buckets from all hashes and their content. """ bucket_keys = self.redis_object.keys(pattern='nearpy_*') if len(bucket_keys) > 0: self.redis_object.delete(*bucket_keys)
async def cursor ( self ) -> Cursor : return Cursor ( self , await self . _execute ( self . _conn . cursor ) )
0
python return mongodb 'cursor' object is not callable
Create an aiosqlite cursor wrapping a sqlite3 cursor object .
cosqa-train-18750
async def cursor(self) -> Cursor: """Create an aiosqlite cursor wrapping a sqlite3 cursor object.""" return Cursor(self, await self._execute(self._conn.cursor))
def rl_get_point ( ) -> int : # pragma: no cover if rl_type == RlType . GNU : return ctypes . c_int . in_dll ( readline_lib , "rl_point" ) . value elif rl_type == RlType . PYREADLINE : return readline . rl . mode . l_buffer . point else : return 0
1
python ctypes get cursor position
Returns the offset of the current cursor position in rl_line_buffer
cosqa-train-18751
def rl_get_point() -> int: # pragma: no cover """ Returns the offset of the current cursor position in rl_line_buffer """ if rl_type == RlType.GNU: return ctypes.c_int.in_dll(readline_lib, "rl_point").value elif rl_type == RlType.PYREADLINE: return readline.rl.mode.l_buffer.point else: return 0
def to_dict ( cls ) : return dict ( ( item . name , item . number ) for item in iter ( cls ) )
1
enumerate python all instances
Make dictionary version of enumerated class .
cosqa-train-18752
def to_dict(cls): """Make dictionary version of enumerated class. Dictionary created this way can be used with def_num. Returns: A dict (name) -> number """ return dict((item.name, item.number) for item in iter(cls))
def is_valid ( cls , arg ) : return ( isinstance ( arg , ( int , long ) ) and ( arg >= 0 ) ) or isinstance ( arg , basestring )
0
how to check a string for any non integer characters python
Return True if arg is valid value for the class . If the string value is wrong for the enumeration the encoding will fail .
cosqa-train-18753
def is_valid(cls, arg): """Return True if arg is valid value for the class. If the string value is wrong for the enumeration, the encoding will fail. """ return (isinstance(arg, (int, long)) and (arg >= 0)) or \ isinstance(arg, basestring)
def array2string ( arr : numpy . ndarray ) -> str : shape = str ( arr . shape ) [ 1 : - 1 ] if shape . endswith ( "," ) : shape = shape [ : - 1 ] return numpy . array2string ( arr , threshold = 11 ) + "%s[%s]" % ( arr . dtype , shape )
1
python ndarray to string variable with no delimiter
Format numpy array as a string .
cosqa-train-18754
def array2string(arr: numpy.ndarray) -> str: """Format numpy array as a string.""" shape = str(arr.shape)[1:-1] if shape.endswith(","): shape = shape[:-1] return numpy.array2string(arr, threshold=11) + "%s[%s]" % (arr.dtype, shape)
def _str_to_list ( value , separator ) : value_list = [ item . strip ( ) for item in value . split ( separator ) ] value_list_sanitized = builtins . list ( filter ( None , value_list ) ) if len ( value_list_sanitized ) > 0 : return value_list_sanitized else : raise ValueError ( 'Invalid list variable.' )
1
how to split python string to a list
Convert a string to a list with sanitization .
cosqa-train-18755
def _str_to_list(value, separator): """Convert a string to a list with sanitization.""" value_list = [item.strip() for item in value.split(separator)] value_list_sanitized = builtins.list(filter(None, value_list)) if len(value_list_sanitized) > 0: return value_list_sanitized else: raise ValueError('Invalid list variable.')
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 windows dot
Print out a neat targets dependency tree based on requested targets .
cosqa-train-18756
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 from_file ( file_path ) -> dict : with io . open ( file_path , 'r' , encoding = 'utf-8' ) as json_stream : return Json . parse ( json_stream , True )
0
python read json file into dictionary
Load JSON file
cosqa-train-18757
def from_file(file_path) -> dict: """ Load JSON file """ with io.open(file_path, 'r', encoding='utf-8') as json_stream: return Json.parse(json_stream, True)
def read_text_from_file ( path : str ) -> str : with open ( path ) as text_file : content = text_file . read ( ) return content
0
get text of file python
Reads text file contents
cosqa-train-18758
def read_text_from_file(path: str) -> str: """ Reads text file contents """ with open(path) as text_file: content = text_file.read() return content
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 )
0
replace values in python string
r Replace all ( frm to ) tuples in args in string s .
cosqa-train-18759
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_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
python compare if int or not
Return true if a value is an integer number .
cosqa-train-18760
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 __replace_all ( repls : dict , input : str ) -> str : return re . sub ( '|' . join ( re . escape ( key ) for key in repls . keys ( ) ) , lambda k : repls [ k . group ( 0 ) ] , input )
0
python replace several characters in string
Replaces from a string ** input ** all the occurrences of some symbols according to mapping ** repls ** .
cosqa-train-18761
def __replace_all(repls: dict, input: str) -> str: """ Replaces from a string **input** all the occurrences of some symbols according to mapping **repls**. :param dict repls: where #key is the old character and #value is the one to substitute with; :param str input: original string where to apply the replacements; :return: *(str)* the string with the desired characters replaced """ return re.sub('|'.join(re.escape(key) for key in repls.keys()), lambda k: repls[k.group(0)], input)
def get_column_names ( engine : Engine , tablename : str ) -> List [ str ] : return [ info . name for info in gen_columns_info ( engine , tablename ) ]
0
how to get the names of the columns in python
Get all the database column names for the specified table .
cosqa-train-18762
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 __replace_all ( repls : dict , input : str ) -> str : return re . sub ( '|' . join ( re . escape ( key ) for key in repls . keys ( ) ) , lambda k : repls [ k . group ( 0 ) ] , input )
1
how to change character in a string python using replace function
Replaces from a string ** input ** all the occurrences of some symbols according to mapping ** repls ** .
cosqa-train-18763
def __replace_all(repls: dict, input: str) -> str: """ Replaces from a string **input** all the occurrences of some symbols according to mapping **repls**. :param dict repls: where #key is the old character and #value is the one to substitute with; :param str input: original string where to apply the replacements; :return: *(str)* the string with the desired characters replaced """ return re.sub('|'.join(re.escape(key) for key in repls.keys()), lambda k: repls[k.group(0)], input)
def split ( text : str ) -> List [ str ] : return [ word for word in SEPARATOR . split ( text ) if word . strip ( ' \t' ) ]
0
python split string to tokens
Split a text into a list of tokens .
cosqa-train-18764
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 ( ) != "" ]
1
removing all words of a list from a text python
Remove empty utterances from a list of utterances Args : utterances : The list of utterance we are processing
cosqa-train-18765
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 csv_to_numpy ( string_like , dtype = None ) : # type: (str) -> np.array stream = StringIO ( string_like ) return np . genfromtxt ( stream , dtype = dtype , delimiter = ',' )
1
how to read csv file into a numpy array python
Convert a CSV object to a numpy array .
cosqa-train-18766
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_links ( text ) : tco_link_regex = re . compile ( "https?://t.co/[A-z0-9].*" ) generic_link_regex = re . compile ( "(https?://)?(\w*[.]\w+)+([/?=&]+\w+)*" ) remove_tco = re . sub ( tco_link_regex , " " , text ) remove_generic = re . sub ( generic_link_regex , " " , remove_tco ) return remove_generic
0
python remove hyperlinks from text
Helper function to remove the links from the input text
cosqa-train-18767
def remove_links(text): """ Helper function to remove the links from the input text Args: text (str): A string Returns: str: the same text, but with any substring that matches the regex for a link removed and replaced with a space Example: >>> from tweet_parser.getter_methods.tweet_text import remove_links >>> text = "lorem ipsum dolor https://twitter.com/RobotPrincessFi" >>> remove_links(text) 'lorem ipsum dolor ' """ tco_link_regex = re.compile("https?://t.co/[A-z0-9].*") generic_link_regex = re.compile("(https?://)?(\w*[.]\w+)+([/?=&]+\w+)*") remove_tco = re.sub(tco_link_regex, " ", text) remove_generic = re.sub(generic_link_regex, " ", remove_tco) return remove_generic
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
0
how to tell if string is absolute path in python
simple method to determine if a url is relative or absolute
cosqa-train-18768
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 array2string ( arr : numpy . ndarray ) -> str : shape = str ( arr . shape ) [ 1 : - 1 ] if shape . endswith ( "," ) : shape = shape [ : - 1 ] return numpy . array2string ( arr , threshold = 11 ) + "%s[%s]" % ( arr . dtype , shape )
1
python print string numpy array
Format numpy array as a string .
cosqa-train-18769
def array2string(arr: numpy.ndarray) -> str: """Format numpy array as a string.""" shape = str(arr.shape)[1:-1] if shape.endswith(","): shape = shape[:-1] return numpy.array2string(arr, threshold=11) + "%s[%s]" % (arr.dtype, shape)
def mmap ( func , iterable ) : if sys . version_info [ 0 ] > 2 : return [ i for i in map ( func , iterable ) ] else : return map ( func , iterable )
0
iterate a python map fast way
Wrapper to make map () behave the same on Py2 and Py3 .
cosqa-train-18770
def mmap(func, iterable): """Wrapper to make map() behave the same on Py2 and Py3.""" if sys.version_info[0] > 2: return [i for i in map(func, iterable)] else: return map(func, iterable)
def looks_like_url ( url ) : if not isinstance ( url , basestring ) : return False if not isinstance ( url , basestring ) or len ( url ) >= 1024 or not cre_url . match ( url ) : return False return True
1
how to detect a legit url with python
Simplified check to see if the text appears to be a URL .
cosqa-train-18771
def looks_like_url(url): """ Simplified check to see if the text appears to be a URL. Similar to `urlparse` but much more basic. Returns: True if the url str appears to be valid. False otherwise. >>> url = looks_like_url("totalgood.org") >>> bool(url) True """ if not isinstance(url, basestring): return False if not isinstance(url, basestring) or len(url) >= 1024 or not cre_url.match(url): return False return True
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
python check if set is a subset
Report whether another set contains this set .
cosqa-train-18772
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 remove_empty_text ( utterances : List [ Utterance ] ) -> List [ Utterance ] : return [ utter for utter in utterances if utter . text . strip ( ) != "" ]
1
python remove phrase from list of strings
Remove empty utterances from a list of utterances Args : utterances : The list of utterance we are processing
cosqa-train-18773
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 clean_map ( obj : Mapping [ Any , Any ] ) -> Mapping [ Any , Any ] : return { k : v for k , v in obj . items ( ) if v is not None }
1
python clearing a dict of any records with no values
Return a new copied dictionary without the keys with None values from the given Mapping object .
cosqa-train-18774
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 process_literal_param ( self , value : Optional [ List [ int ] ] , dialect : Dialect ) -> str : retval = self . _intlist_to_dbstr ( value ) return retval
1
python list to sql db field
Convert things on the way from Python to the database .
cosqa-train-18775
def process_literal_param(self, value: Optional[List[int]], dialect: Dialect) -> str: """Convert things on the way from Python to the database.""" retval = self._intlist_to_dbstr(value) return retval
def remove_once ( gset , elem ) : remove = getattr ( gset , 'remove' , None ) if remove is not None : remove ( elem ) else : del gset [ elem ] return elem
0
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-18776
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 astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( value = array , dtype = CTYPE ) return tensor
1
python tensorflow shape to array
Covert numpy array to tensorflow tensor
cosqa-train-18777
def astensor(array: TensorLike) -> BKTensor: """Covert numpy array to tensorflow tensor""" tensor = tf.convert_to_tensor(value=array, dtype=CTYPE) return tensor
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 ) )
1
how to set python3 django apache
Verify Django 1 . 11 is present if Python 2 . 7 is active
cosqa-train-18778
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 _parse_tuple_string ( argument ) : if isinstance ( argument , str ) : return tuple ( int ( p . strip ( ) ) for p in argument . split ( ',' ) ) return argument
1
python create a tuple from input split
Return a tuple from parsing a b c d - > ( a b c d )
cosqa-train-18779
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 SwitchToThisWindow ( handle : int ) -> None : ctypes . windll . user32 . SwitchToThisWindow ( ctypes . c_void_p ( handle ) , 1 )
1
how to swithc to an open window in windows 10 using python
SwitchToThisWindow from Win32 . handle : int the handle of a native window .
cosqa-train-18780
def SwitchToThisWindow(handle: int) -> None: """ SwitchToThisWindow from Win32. handle: int, the handle of a native window. """ ctypes.windll.user32.SwitchToThisWindow(ctypes.c_void_p(handle), 1)
def find_first_in_list ( txt : str , str_list : [ str ] ) -> int : # type: ignore start = len ( txt ) + 1 for item in str_list : if start > txt . find ( item ) > - 1 : start = txt . find ( item ) return start if len ( txt ) + 1 > start > - 1 else - 1
0
python index of first match in string
Returns the index of the earliest occurence of an item from a list in a string
cosqa-train-18781
def find_first_in_list(txt: str, str_list: [str]) -> int: # type: ignore """ Returns the index of the earliest occurence of an item from a list in a string Ex: find_first_in_list('foobar', ['bar', 'fin']) -> 3 """ start = len(txt) + 1 for item in str_list: if start > txt.find(item) > -1: start = txt.find(item) return start if len(txt) + 1 > start > -1 else -1
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
0
python type is not str
Validates that the object itself is some kinda string
cosqa-train-18782
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 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
file of words into set python
Extract a de - duped collection ( set ) of text from a file . Expected file format is one item per line .
cosqa-train-18783
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 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
0
python set add dictionnary
Add value to a set in a dictionary by key
cosqa-train-18784
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 attrname_to_colname_dict ( cls ) -> Dict [ str , str ] : attr_col = { } # type: Dict[str, str] for attrname , column in gen_columns ( cls ) : attr_col [ attrname ] = column . name return attr_col
0
python sqlalchemy modle attributes
Asks an SQLAlchemy class how its attribute names correspond to database column names .
cosqa-train-18785
def attrname_to_colname_dict(cls) -> Dict[str, str]: """ Asks an SQLAlchemy class how its attribute names correspond to database column names. Args: cls: SQLAlchemy ORM class Returns: a dictionary mapping attribute names to database column names """ attr_col = {} # type: Dict[str, str] for attrname, column in gen_columns(cls): attr_col[attrname] = column.name return attr_col
def get_column_names ( engine : Engine , tablename : str ) -> List [ str ] : return [ info . name for info in gen_columns_info ( engine , tablename ) ]
1
python list all column names
Get all the database column names for the specified table .
cosqa-train-18786
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 Exit ( msg , code = 1 ) : print >> sys . stderr , msg sys . exit ( code )
1
how to exit a code in python
Exit execution with return code and message : param msg : Message displayed prior to exit : param code : code returned upon exiting
cosqa-train-18787
def Exit(msg, code=1): """Exit execution with return code and message :param msg: Message displayed prior to exit :param code: code returned upon exiting """ print >> sys.stderr, msg sys.exit(code)
def dag_longest_path ( graph , source , target ) : if source == target : return [ source ] allpaths = nx . all_simple_paths ( graph , source , target ) longest_path = [ ] for l in allpaths : if len ( l ) > len ( longest_path ) : longest_path = l return longest_path
0
longest path in a tree python
Finds the longest path in a dag between two nodes
cosqa-train-18788
def dag_longest_path(graph, source, target): """ Finds the longest path in a dag between two nodes """ if source == target: return [source] allpaths = nx.all_simple_paths(graph, source, target) longest_path = [] for l in allpaths: if len(l) > len(longest_path): longest_path = l return longest_path
def hsv2rgb_spectrum ( hsv ) : h , s , v = hsv return hsv2rgb_raw ( ( ( h * 192 ) >> 8 , s , v ) )
1
python hsv to rgb code
Generates RGB values from HSV values in line with a typical light spectrum .
cosqa-train-18789
def hsv2rgb_spectrum(hsv): """Generates RGB values from HSV values in line with a typical light spectrum.""" h, s, v = hsv return hsv2rgb_raw(((h * 192) >> 8, s, v))
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
python create dictionray from a list of keys
Converts a list into a space - separated string and puts it in a dictionary
cosqa-train-18790
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 __as_list ( value : List [ JsonObjTypes ] ) -> List [ JsonTypes ] : return [ e . _as_dict if isinstance ( e , JsonObj ) else e for e in value ]
1
python json dump to list
Return a json array as a list
cosqa-train-18791
def __as_list(value: List[JsonObjTypes]) -> List[JsonTypes]: """ Return a json array as a list :param value: array :return: array with JsonObj instances removed """ return [e._as_dict if isinstance(e, JsonObj) else e for e in value]
def count ( args ) : counts = defaultdict ( int ) for arg in args : for item in arg : counts [ item ] = counts [ item ] + 1 return counts
1
list of arbitrary objects to counts in python
count occurences in a list of lists >>> count ( [[ a b ] [ a ]] ) defaultdict ( int { a : 2 b : 1 } )
cosqa-train-18792
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 strip_codes ( s : Any ) -> str : return codepat . sub ( '' , str ( s ) if ( s or ( s == 0 ) ) else '' )
1
remove characters string python
Strip all color codes from a string . Returns empty string for falsey inputs .
cosqa-train-18793
def strip_codes(s: Any) -> str: """ Strip all color codes from a string. Returns empty string for "falsey" inputs. """ return codepat.sub('', str(s) if (s or (s == 0)) else '')
def get_last_day_of_month ( t : datetime ) -> int : tn = t + timedelta ( days = 32 ) tn = datetime ( year = tn . year , month = tn . month , day = 1 ) tt = tn - timedelta ( hours = 1 ) return tt . day
1
get last day of month python
Returns day number of the last day of the month : param t : datetime : return : int
cosqa-train-18794
def get_last_day_of_month(t: datetime) -> int: """ Returns day number of the last day of the month :param t: datetime :return: int """ tn = t + timedelta(days=32) tn = datetime(year=tn.year, month=tn.month, day=1) tt = tn - timedelta(hours=1) return tt.day
def clean_column_names ( df : DataFrame ) -> DataFrame : f = df . copy ( ) f . columns = [ col . strip ( ) for col in f . columns ] return f
0
how to remove columns from data frame python
Strip the whitespace from all column names in the given DataFrame and return the result .
cosqa-train-18795
def clean_column_names(df: DataFrame) -> DataFrame: """ Strip the whitespace from all column names in the given DataFrame and return the result. """ f = df.copy() f.columns = [col.strip() for col in f.columns] return f
def trade_day ( dt , cal = 'US' ) : from xone import calendar dt = pd . Timestamp ( dt ) . date ( ) return calendar . trading_dates ( start = dt - pd . Timedelta ( '10D' ) , end = dt , calendar = cal ) [ - 1 ]
0
how to get last trading daya as string in python
Latest trading day w . r . t given dt
cosqa-train-18796
def trade_day(dt, cal='US'): """ Latest trading day w.r.t given dt Args: dt: date of reference cal: trading calendar Returns: pd.Timestamp: last trading day Examples: >>> trade_day('2018-12-25').strftime('%Y-%m-%d') '2018-12-24' """ from xone import calendar dt = pd.Timestamp(dt).date() return calendar.trading_dates(start=dt - pd.Timedelta('10D'), end=dt, calendar=cal)[-1]
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
python create dictionary with keys and no values
Return a new copied dictionary without the keys with None values from the given Mapping object .
cosqa-train-18797
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_now_utc_notz_datetime ( ) -> datetime . datetime : now = datetime . datetime . utcnow ( ) return now . replace ( tzinfo = None )
1
python utcnow timezone aware
Get the UTC time now but with no timezone information in : class : datetime . datetime format .
cosqa-train-18798
def get_now_utc_notz_datetime() -> datetime.datetime: """ Get the UTC time now, but with no timezone information, in :class:`datetime.datetime` format. """ now = datetime.datetime.utcnow() return now.replace(tzinfo=None)
def file_exists ( fname ) : try : return fname and os . path . exists ( fname ) and os . path . getsize ( fname ) > 0 except OSError : return False
1
how to check if a file is not empty in python
Check if a file exists and is non - empty .
cosqa-train-18799
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