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 _parse_date ( string : str ) -> datetime . date : return datetime . datetime . strptime ( string , '%Y-%m-%d' ) . date ( )
1
parsing a date string python
Parse an ISO format date ( YYYY - mm - dd ) .
cosqa-train-19500
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 get_codes ( s : Union [ str , 'ChainedBase' ] ) -> List [ str ] : return codegrabpat . findall ( str ( s ) )
1
how to get the character codes for the chars in the string python
Grab all escape codes from a string . Returns a list of all escape codes .
cosqa-train-19501
def get_codes(s: Union[str, 'ChainedBase']) -> List[str]: """ Grab all escape codes from a string. Returns a list of all escape codes. """ return codegrabpat.findall(str(s))
def _parse_tuple_string ( argument ) : if isinstance ( argument , str ) : return tuple ( int ( p . strip ( ) ) for p in argument . split ( ',' ) ) return argument
1
how to turn a string into a tuple pythons
Return a tuple from parsing a b c d - > ( a b c d )
cosqa-train-19502
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 hex_color_to_tuple ( hex ) : hex = hex [ 1 : ] length = len ( hex ) // 2 return tuple ( int ( hex [ i * 2 : i * 2 + 2 ] , 16 ) for i in range ( length ) )
0
color to python tuple
convent hex color to tuple #ffffff - > ( 255 255 255 ) #ffff00ff - > ( 255 255 0 255 )
cosqa-train-19503
def hex_color_to_tuple(hex): """ convent hex color to tuple "#ffffff" -> (255, 255, 255) "#ffff00ff" -> (255, 255, 0, 255) """ hex = hex[1:] length = len(hex) // 2 return tuple(int(hex[i*2:i*2+2], 16) for i in range(length))
def has_key ( cls , * args ) : key = args if len ( args ) > 1 else args [ 0 ] return key in cls . _instances
1
python how to check if key does not exists
Check whether flyweight object with specified key has already been created .
cosqa-train-19504
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 is_valid ( cls , arg ) : return ( isinstance ( arg , ( int , long ) ) and ( arg >= 0 ) ) or isinstance ( arg , basestring )
1
check if enum is valid 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-19505
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 setdefault ( self , name : str , default : Any = None ) -> Any : return self . __dict__ . setdefault ( name , default )
0
python setting a default value for an attribute
Set an attribute with a default value .
cosqa-train-19506
def setdefault(self, name: str, default: Any=None) -> Any: """Set an attribute with a default value.""" return self.__dict__.setdefault(name, default)
def post ( self , endpoint : str , * * kwargs ) -> dict : return self . _request ( 'POST' , endpoint , * * kwargs )
0
sample api post call python
HTTP POST operation to API endpoint .
cosqa-train-19507
def post(self, endpoint: str, **kwargs) -> dict: """HTTP POST operation to API endpoint.""" return self._request('POST', endpoint, **kwargs)
def decode ( string , base ) : base = int ( base ) code_string = get_code_string ( base ) result = 0 if base == 16 : string = string . lower ( ) while len ( string ) > 0 : result *= base result += code_string . find ( string [ 0 ] ) string = string [ 1 : ] return result
1
how to get the base 10value for a string in python
Given a string ( string ) and a numeric base ( base ) decode the string into an integer .
cosqa-train-19508
def decode(string, base): """ Given a string (string) and a numeric base (base), decode the string into an integer. Returns the integer """ base = int(base) code_string = get_code_string(base) result = 0 if base == 16: string = string.lower() while len(string) > 0: result *= base result += code_string.find(string[0]) string = string[1:] 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
1
mulyiple indexing list python
Return dict mapping item - > indices .
cosqa-train-19509
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 enrich_complexes ( graph : BELGraph ) -> None : nodes = list ( get_nodes_by_function ( graph , COMPLEX ) ) for u in nodes : for v in u . members : graph . add_has_component ( u , v )
1
how to graph a complex function in python
Add all of the members of the complex abundances to the graph .
cosqa-train-19510
def enrich_complexes(graph: BELGraph) -> None: """Add all of the members of the complex abundances to the graph.""" nodes = list(get_nodes_by_function(graph, COMPLEX)) for u in nodes: for v in u.members: graph.add_has_component(u, v)
def get_datatype ( self , table : str , column : str ) -> str : return self . flavour . get_datatype ( self , table , column ) . upper ( )
0
how to know the datatype of column+ sql + python
Returns database SQL datatype for a column : e . g . VARCHAR .
cosqa-train-19511
def get_datatype(self, table: str, column: str) -> str: """Returns database SQL datatype for a column: e.g. VARCHAR.""" return self.flavour.get_datatype(self, table, column).upper()
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
skip over blank lines in file python
Helper for iterating only nonempty lines without line breaks
cosqa-train-19512
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 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 )
0
generate graph from dot file python
Print out a neat targets dependency tree based on requested targets .
cosqa-train-19513
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 debugTreePrint ( node , pfx = "->" ) : print pfx , node . item for c in node . children : debugTreePrint ( c , " " + pfx )
0
using recursion in python to print a binary tree
Purely a debugging aid : Ascii - art picture of a tree descended from node
cosqa-train-19514
def debugTreePrint(node,pfx="->"): """Purely a debugging aid: Ascii-art picture of a tree descended from node""" print pfx,node.item for c in node.children: debugTreePrint(c," "+pfx)
def is_orthogonal ( matrix : np . ndarray , * , rtol : float = 1e-5 , atol : float = 1e-8 ) -> bool : return ( matrix . shape [ 0 ] == matrix . shape [ 1 ] and np . all ( np . imag ( matrix ) == 0 ) and np . allclose ( matrix . dot ( matrix . T ) , np . eye ( matrix . shape [ 0 ] ) , rtol = rtol , atol = atol ) )
0
python matrix to orthogonal
Determines if a matrix is approximately orthogonal .
cosqa-train-19515
def is_orthogonal( matrix: np.ndarray, *, rtol: float = 1e-5, atol: float = 1e-8) -> bool: """Determines if a matrix is approximately orthogonal. A matrix is orthogonal if it's square and real and its transpose is its inverse. Args: matrix: The matrix to check. rtol: The per-matrix-entry relative tolerance on equality. atol: The per-matrix-entry absolute tolerance on equality. Returns: Whether the matrix is orthogonal within the given tolerance. """ return (matrix.shape[0] == matrix.shape[1] and np.all(np.imag(matrix) == 0) and np.allclose(matrix.dot(matrix.T), np.eye(matrix.shape[0]), rtol=rtol, atol=atol))
def layer_with ( self , sample : np . ndarray , value : int ) -> np . ndarray : b = np . full ( ( 2 , len ( sample ) ) , value , dtype = float ) b [ 0 ] = sample return b
0
python numpy fill with custom values
Create an identical 2d array where the second row is filled with value
cosqa-train-19516
def layer_with(self, sample: np.ndarray, value: int) -> np.ndarray: """Create an identical 2d array where the second row is filled with value""" b = np.full((2, len(sample)), value, dtype=float) b[0] = sample return b
def inverted_dict ( d ) : return dict ( ( force_hashable ( v ) , k ) for ( k , v ) in viewitems ( dict ( d ) ) )
1
invert a dictionary in python
Return a dict with swapped keys and values
cosqa-train-19517
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 valid_file ( path : str ) -> bool : path = Path ( path ) . expanduser ( ) log . debug ( "checking if %s is a valid file" , path ) return path . exists ( ) and path . is_file ( )
1
how to check path is a file or directory in python
Verifies that a string path actually exists and is a file
cosqa-train-19518
def valid_file(path: str) -> bool: """ Verifies that a string path actually exists and is a file :param path: The path to verify :return: **True** if path exist and is a file """ path = Path(path).expanduser() log.debug("checking if %s is a valid file", path) return path.exists() and path.is_file()
def input_validate_str ( string , name , max_len = None , exact_len = None ) : if type ( string ) is not str : raise pyhsm . exception . YHSM_WrongInputType ( name , str , type ( string ) ) if max_len != None and len ( string ) > max_len : raise pyhsm . exception . YHSM_InputTooLong ( name , max_len , len ( string ) ) if exact_len != None and len ( string ) != exact_len : raise pyhsm . exception . YHSM_WrongInputSize ( name , exact_len , len ( string ) ) return string
0
validate minimum string length of user input in python
Input validation for strings .
cosqa-train-19519
def input_validate_str(string, name, max_len=None, exact_len=None): """ Input validation for strings. """ if type(string) is not str: raise pyhsm.exception.YHSM_WrongInputType(name, str, type(string)) if max_len != None and len(string) > max_len: raise pyhsm.exception.YHSM_InputTooLong(name, max_len, len(string)) if exact_len != None and len(string) != exact_len: raise pyhsm.exception.YHSM_WrongInputSize(name, exact_len, len(string)) return string
def index ( self , item ) : for i , x in enumerate ( self . iter ( ) ) : if x == item : return i return None
1
python get index of element each time it appears in list
Not recommended for use on large lists due to time complexity but it works
cosqa-train-19520
def index(self, item): """ Not recommended for use on large lists due to time complexity, but it works -> #int list index of @item """ for i, x in enumerate(self.iter()): if x == item: return i return None
def is_line_in_file ( filename : str , line : str ) -> bool : assert "\n" not in line with open ( filename , "r" ) as file : for fileline in file : if fileline == line : return True return False
1
python check if string contains a line in file
Detects whether a line is present within a file .
cosqa-train-19521
def is_line_in_file(filename: str, line: str) -> bool: """ Detects whether a line is present within a file. Args: filename: file to check line: line to search for (as an exact match) """ assert "\n" not in line with open(filename, "r") as file: for fileline in file: if fileline == line: return True return False
def inverted_dict ( d ) : return dict ( ( force_hashable ( v ) , k ) for ( k , v ) in viewitems ( dict ( d ) ) )
0
invert a dictionary python
Return a dict with swapped keys and values
cosqa-train-19522
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 strings_to_integers ( strings : Iterable [ str ] ) -> Iterable [ int ] : return strings_to_ ( strings , lambda x : int ( float ( x ) ) )
1
change a string list to int in python
Convert a list of strings to a list of integers .
cosqa-train-19523
def strings_to_integers(strings: Iterable[str]) -> Iterable[int]: """ Convert a list of strings to a list of integers. :param strings: a list of string :return: a list of converted integers .. doctest:: >>> strings_to_integers(['1', '1.0', '-0.2']) [1, 1, 0] """ return strings_to_(strings, lambda x: int(float(x)))
def _check_whitespace ( string ) : if string . count ( ' ' ) + string . count ( '\t' ) + string . count ( '\n' ) > 0 : raise ValueError ( INSTRUCTION_HAS_WHITESPACE )
0
che3ck if string is equal to whitespace python
Make sure thre is no whitespace in the given string . Will raise a ValueError if whitespace is detected
cosqa-train-19524
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 try_cast_int ( s ) : try : temp = re . findall ( '\d' , str ( s ) ) temp = '' . join ( temp ) return int ( temp ) except : return s
0
covert string to int in python
( str ) - > int All the digits in a given string are concatenated and converted into a single number .
cosqa-train-19525
def try_cast_int(s): """(str) -> int All the digits in a given string are concatenated and converted into a single number. """ try: temp = re.findall('\d', str(s)) temp = ''.join(temp) return int(temp) except: return s
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
python check the date a file was altered
Check if filename has changed since the last check . If this is the first check assume the file is changed .
cosqa-train-19526
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 connect_to_database_odbc_access ( self , dsn : str , autocommit : bool = True ) -> None : self . connect ( engine = ENGINE_ACCESS , interface = INTERFACE_ODBC , dsn = dsn , autocommit = autocommit )
0
connecting to an access database with python pyodbc
Connects to an Access database via ODBC with the DSN prespecified .
cosqa-train-19527
def connect_to_database_odbc_access(self, dsn: str, autocommit: bool = True) -> None: """Connects to an Access database via ODBC, with the DSN prespecified.""" self.connect(engine=ENGINE_ACCESS, interface=INTERFACE_ODBC, dsn=dsn, autocommit=autocommit)
def clean_column_names ( df : DataFrame ) -> DataFrame : f = df . copy ( ) f . columns = [ col . strip ( ) for col in f . columns ] return f
1
remove data frame columns python
Strip the whitespace from all column names in the given DataFrame and return the result .
cosqa-train-19528
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 _get_tuple ( self , fields ) : v1 = '' v2 = '' if len ( fields ) > 0 : v1 = fields [ 0 ] if len ( fields ) > 1 : v2 = fields [ 1 ] return v1 , v2
1
python default value return tuple
: param fields : a list which contains either 0 1 or 2 values : return : a tuple with default values of ;
cosqa-train-19529
def _get_tuple(self, fields): """ :param fields: a list which contains either 0,1,or 2 values :return: a tuple with default values of ''; """ v1 = '' v2 = '' if len(fields) > 0: v1 = fields[0] if len(fields) > 1: v2 = fields[1] return v1, v2
def butlast ( iterable ) : iterable = iter ( iterable ) try : first = next ( iterable ) except StopIteration : return for second in iterable : yield first first = second
0
python for loop except first and last elements in list
Yield all items from iterable except the last one .
cosqa-train-19530
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 autoreload ( self , parameter_s = '' ) : if parameter_s == '' : self . _reloader . check ( True ) elif parameter_s == '0' : self . _reloader . enabled = False elif parameter_s == '1' : self . _reloader . check_all = False self . _reloader . enabled = True elif parameter_s == '2' : self . _reloader . check_all = True self . _reloader . enabled = True
1
python reload is not defined
r %autoreload = > Reload modules automatically
cosqa-train-19531
def autoreload(self, parameter_s=''): r"""%autoreload => Reload modules automatically %autoreload Reload all modules (except those excluded by %aimport) automatically now. %autoreload 0 Disable automatic reloading. %autoreload 1 Reload all modules imported with %aimport every time before executing the Python code typed. %autoreload 2 Reload all modules (except those excluded by %aimport) every time before executing the Python code typed. Reloading Python modules in a reliable way is in general difficult, and unexpected things may occur. %autoreload tries to work around common pitfalls by replacing function code objects and parts of classes previously in the module with new versions. This makes the following things to work: - Functions and classes imported via 'from xxx import foo' are upgraded to new versions when 'xxx' is reloaded. - Methods and properties of classes are upgraded on reload, so that calling 'c.foo()' on an object 'c' created before the reload causes the new code for 'foo' to be executed. Some of the known remaining caveats are: - Replacing code objects does not always succeed: changing a @property in a class to an ordinary method or a method to a member variable can cause problems (but in old objects only). - Functions that are removed (eg. via monkey-patching) from a module before it is reloaded are not upgraded. - C extension modules cannot be reloaded, and so cannot be autoreloaded. """ if parameter_s == '': self._reloader.check(True) elif parameter_s == '0': self._reloader.enabled = False elif parameter_s == '1': self._reloader.check_all = False self._reloader.enabled = True elif parameter_s == '2': self._reloader.check_all = True self._reloader.enabled = True
def _centroids ( n_clusters : int , points : List [ List [ float ] ] ) -> List [ List [ float ] ] : k_means = KMeans ( n_clusters = n_clusters ) k_means . fit ( points ) closest , _ = pairwise_distances_argmin_min ( k_means . cluster_centers_ , points ) return list ( map ( list , np . array ( points ) [ closest . tolist ( ) ] ) )
1
python kmeans get the optimal cluster number
Return n_clusters centroids of points
cosqa-train-19532
def _centroids(n_clusters: int, points: List[List[float]]) -> List[List[float]]: """ Return n_clusters centroids of points """ k_means = KMeans(n_clusters=n_clusters) k_means.fit(points) closest, _ = pairwise_distances_argmin_min(k_means.cluster_centers_, points) return list(map(list, np.array(points)[closest.tolist()]))
def product ( * args , * * kwargs ) : p = [ [ ] ] for iterable in map ( tuple , args ) * kwargs . get ( "repeat" , 1 ) : p = [ x + [ y ] for x in p for y in iterable ] for p in p : yield tuple ( p )
1
python generate all permutations
Yields all permutations with replacement : list ( product ( cat repeat = 2 )) = > [ ( c c ) ( c a ) ( c t ) ( a c ) ( a a ) ( a t ) ( t c ) ( t a ) ( t t ) ]
cosqa-train-19533
def product(*args, **kwargs): """ Yields all permutations with replacement: list(product("cat", repeat=2)) => [("c", "c"), ("c", "a"), ("c", "t"), ("a", "c"), ("a", "a"), ("a", "t"), ("t", "c"), ("t", "a"), ("t", "t")] """ p = [[]] for iterable in map(tuple, args) * kwargs.get("repeat", 1): p = [x + [y] for x in p for y in iterable] for p in p: yield tuple(p)
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
1
python check if a valid date
Retrun True if x is a valid YYYYMMDD date ; otherwise return False .
cosqa-train-19534
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 inner ( tensor0 : BKTensor , tensor1 : BKTensor ) -> BKTensor : # Note: Relying on fact that vdot flattens arrays return np . vdot ( tensor0 , tensor1 )
0
python + calculate matrix product of the two tensors
Return the inner product between two tensors
cosqa-train-19535
def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor: """Return the inner product between two tensors""" # Note: Relying on fact that vdot flattens arrays return np.vdot(tensor0, tensor1)
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
python how to turn a string list into a list
Convert a string to a list with sanitization .
cosqa-train-19536
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 _sum_cycles_from_tokens ( self , tokens : List [ str ] ) -> int : return sum ( ( int ( self . _nonnumber_pattern . sub ( '' , t ) ) for t in tokens ) )
0
get document frequency from tokenized lists python
Sum the total number of cycles over a list of tokens .
cosqa-train-19537
def _sum_cycles_from_tokens(self, tokens: List[str]) -> int: """Sum the total number of cycles over a list of tokens.""" return sum((int(self._nonnumber_pattern.sub('', t)) for t in tokens))
def strings_to_integers ( strings : Iterable [ str ] ) -> Iterable [ int ] : return strings_to_ ( strings , lambda x : int ( float ( x ) ) )
1
chaning list entries from string to int in python
Convert a list of strings to a list of integers .
cosqa-train-19538
def strings_to_integers(strings: Iterable[str]) -> Iterable[int]: """ Convert a list of strings to a list of integers. :param strings: a list of string :return: a list of converted integers .. doctest:: >>> strings_to_integers(['1', '1.0', '-0.2']) [1, 1, 0] """ return strings_to_(strings, lambda x: int(float(x)))
def snake_to_camel ( s : str ) -> str : fragments = s . split ( '_' ) return fragments [ 0 ] + '' . join ( x . title ( ) for x in fragments [ 1 : ] )
0
capitalize letters in string python
Convert string from snake case to camel case .
cosqa-train-19539
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 strings_to_integers ( strings : Iterable [ str ] ) -> Iterable [ int ] : return strings_to_ ( strings , lambda x : int ( float ( x ) ) )
0
how to change list of strings to integers python
Convert a list of strings to a list of integers .
cosqa-train-19540
def strings_to_integers(strings: Iterable[str]) -> Iterable[int]: """ Convert a list of strings to a list of integers. :param strings: a list of string :return: a list of converted integers .. doctest:: >>> strings_to_integers(['1', '1.0', '-0.2']) [1, 1, 0] """ return strings_to_(strings, lambda x: int(float(x)))
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 an empty file python
Check if cnr or cns files are empty ( only have a header )
cosqa-train-19541
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 list_to_str ( list , separator = ',' ) : list = [ str ( x ) for x in list ] return separator . join ( list )
1
elements of a list to string in python
>>> list = [ 0 0 7 ] >>> list_to_str ( list ) 0 0 7
cosqa-train-19542
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 read32 ( bytestream ) : dt = np . dtype ( np . uint32 ) . newbyteorder ( '>' ) return np . frombuffer ( bytestream . read ( 4 ) , dtype = dt ) [ 0 ]
0
how to type cast an unsigned long to int in python
Read 4 bytes from bytestream as an unsigned 32 - bit integer .
cosqa-train-19543
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 isarray ( array , test , dim = 2 ) : if dim > 1 : return all ( isarray ( array [ i ] , test , dim - 1 ) for i in range ( len ( array ) ) ) return all ( test ( i ) for i in array )
1
python if array is all 1
Returns True if test is True for all array elements . Otherwise returns False .
cosqa-train-19544
def isarray(array, test, dim=2): """Returns True if test is True for all array elements. Otherwise, returns False. """ if dim > 1: return all(isarray(array[i], test, dim - 1) for i in range(len(array))) return all(test(i) for i in array)
def _check_whitespace ( string ) : if string . count ( ' ' ) + string . count ( '\t' ) + string . count ( '\n' ) > 0 : raise ValueError ( INSTRUCTION_HAS_WHITESPACE )
1
how to check if a string is whitespace in python
Make sure thre is no whitespace in the given string . Will raise a ValueError if whitespace is detected
cosqa-train-19545
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 chars ( string : any ) -> str : return '' . join ( [ c if c . isalpha ( ) else '' for c in str ( string ) ] )
1
how to check if a string contains all letters in python
Return all ( and only ) the chars in the given string .
cosqa-train-19546
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 rms ( x ) : try : return ( np . array ( x ) ** 2 ) . mean ( ) ** 0.5 except : x = np . array ( dropna ( x ) ) invN = 1.0 / len ( x ) return ( sum ( invN * ( x_i ** 2 ) for x_i in x ) ) ** .5
1
rms average equation python
Root Mean Square
cosqa-train-19547
def rms(x): """"Root Mean Square" Arguments: x (seq of float): A sequence of numerical values Returns: The square root of the average of the squares of the values math.sqrt(sum(x_i**2 for x_i in x) / len(x)) or return (np.array(x) ** 2).mean() ** 0.5 >>> rms([0, 2, 4, 4]) 3.0 """ try: return (np.array(x) ** 2).mean() ** 0.5 except: x = np.array(dropna(x)) invN = 1.0 / len(x) return (sum(invN * (x_i ** 2) for x_i in x)) ** .5
def memory_full ( ) : current_process = psutil . Process ( os . getpid ( ) ) return ( current_process . memory_percent ( ) > config . MAXIMUM_CACHE_MEMORY_PERCENTAGE )
1
linux python memcache return none
Check if the memory is too full for further caching .
cosqa-train-19548
def memory_full(): """Check if the memory is too full for further caching.""" current_process = psutil.Process(os.getpid()) return (current_process.memory_percent() > config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)
def get_unique_links ( self ) : page_url = self . get_current_url ( ) soup = self . get_beautiful_soup ( self . get_page_source ( ) ) links = page_utils . _get_unique_links ( page_url , soup ) return links
0
links to html pages with no duplicates code on python
Get all unique links in the html of the page source . Page links include those obtained from : a - > href img - > src link - > href and script - > src .
cosqa-train-19549
def get_unique_links(self): """ Get all unique links in the html of the page source. Page links include those obtained from: "a"->"href", "img"->"src", "link"->"href", and "script"->"src". """ page_url = self.get_current_url() soup = self.get_beautiful_soup(self.get_page_source()) links = page_utils._get_unique_links(page_url, soup) return links
def is_prime ( n ) : if n % 2 == 0 and n > 2 : return False return all ( n % i for i in range ( 3 , int ( math . sqrt ( n ) ) + 1 , 2 ) )
0
python determine if prime and what factors
Check if n is a prime number
cosqa-train-19550
def is_prime(n): """ Check if n is a prime number """ if n % 2 == 0 and n > 2: return False return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
def top ( self , topn = 10 ) : return [ self [ i ] for i in argsort ( list ( zip ( * self ) ) [ 1 ] ) [ : : - 1 ] [ : topn ] ]
1
python choose top 4
Get a list of the top topn features in this : class : . Feature \ .
cosqa-train-19551
def top(self, topn=10): """ Get a list of the top ``topn`` features in this :class:`.Feature`\. Examples -------- .. code-block:: python >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)]) >>> myFeature.top(1) [('trapezoid', 5)] Parameters ---------- topn : int Returns ------- list """ return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]
def post ( self , endpoint : str , * * kwargs ) -> dict : return self . _request ( 'POST' , endpoint , * * kwargs )
0
python requests post parametes dict
HTTP POST operation to API endpoint .
cosqa-train-19552
def post(self, endpoint: str, **kwargs) -> dict: """HTTP POST operation to API endpoint.""" return self._request('POST', endpoint, **kwargs)
def datetime_from_isoformat ( value : str ) : if sys . version_info >= ( 3 , 7 ) : return datetime . fromisoformat ( value ) return datetime . strptime ( value , '%Y-%m-%dT%H:%M:%S.%f' )
1
python datetime from isoformat string
Return a datetime object from an isoformat string .
cosqa-train-19553
def datetime_from_isoformat(value: str): """Return a datetime object from an isoformat string. Args: value (str): Datetime string in isoformat. """ if sys.version_info >= (3, 7): return datetime.fromisoformat(value) return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f')
def samefile ( a : str , b : str ) -> bool : try : return os . path . samefile ( a , b ) except OSError : return os . path . normpath ( a ) == os . path . normpath ( b )
1
python check if two paths are equal
Check if two pathes represent the same file .
cosqa-train-19554
def samefile(a: str, b: str) -> bool: """Check if two pathes represent the same file.""" try: return os.path.samefile(a, b) except OSError: return os.path.normpath(a) == os.path.normpath(b)
def mouse_event ( dwFlags : int , dx : int , dy : int , dwData : int , dwExtraInfo : int ) -> None : ctypes . windll . user32 . mouse_event ( dwFlags , dx , dy , dwData , dwExtraInfo )
0
python win32api mouse event
mouse_event from Win32 .
cosqa-train-19555
def mouse_event(dwFlags: int, dx: int, dy: int, dwData: int, dwExtraInfo: int) -> None: """mouse_event from Win32.""" ctypes.windll.user32.mouse_event(dwFlags, dx, dy, dwData, dwExtraInfo)
def setup_cache ( app : Flask , cache_config ) -> Optional [ Cache ] : if cache_config and cache_config . get ( 'CACHE_TYPE' ) != 'null' : return Cache ( app , config = cache_config ) return None
1
python flask how to access local cache
Setup the flask - cache on a flask app
cosqa-train-19556
def setup_cache(app: Flask, cache_config) -> Optional[Cache]: """Setup the flask-cache on a flask app""" if cache_config and cache_config.get('CACHE_TYPE') != 'null': return Cache(app, config=cache_config) return None
def _find_conda ( ) : if 'CONDA_EXE' in os . environ : conda = os . environ [ 'CONDA_EXE' ] else : conda = util . which ( 'conda' ) return conda
0
conda env python not found
Find the conda executable robustly across conda versions .
cosqa-train-19557
def _find_conda(): """Find the conda executable robustly across conda versions. Returns ------- conda : str Path to the conda executable. Raises ------ IOError If the executable cannot be found in either the CONDA_EXE environment variable or in the PATH. Notes ----- In POSIX platforms in conda >= 4.4, conda can be set up as a bash function rather than an executable. (This is to enable the syntax ``conda activate env-name``.) In this case, the environment variable ``CONDA_EXE`` contains the path to the conda executable. In other cases, we use standard search for the appropriate name in the PATH. See https://github.com/airspeed-velocity/asv/issues/645 for more details. """ if 'CONDA_EXE' in os.environ: conda = os.environ['CONDA_EXE'] else: conda = util.which('conda') return conda
def assert_or_raise ( stmt : bool , exception : Exception , * exception_args , * * exception_kwargs ) -> None : if not stmt : raise exception ( * exception_args , * * exception_kwargs )
1
python raise without parentheses
If the statement is false raise the given exception .
cosqa-train-19558
def assert_or_raise(stmt: bool, exception: Exception, *exception_args, **exception_kwargs) -> None: """ If the statement is false, raise the given exception. """ if not stmt: raise exception(*exception_args, **exception_kwargs)
def multi_split ( s , split ) : # type: (S, Iterable[S]) -> List[S] for r in split : s = s . replace ( r , "|" ) return [ i for i in s . split ( "|" ) if len ( i ) > 0 ]
1
how to use split on a list in python
Splits on multiple given separators .
cosqa-train-19559
def multi_split(s, split): # type: (S, Iterable[S]) -> List[S] """Splits on multiple given separators.""" for r in split: s = s.replace(r, "|") return [i for i in s.split("|") if len(i) > 0]
def read_text_from_file ( path : str ) -> str : with open ( path ) as text_file : content = text_file . read ( ) return content
1
how to get contents of text file in python
Reads text file contents
cosqa-train-19560
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 string ( value ) -> str : return system_json . dumps ( Json ( value ) . safe_object ( ) , ensure_ascii = False )
0
python tostring javascript compatible
string dict / object / value to JSON
cosqa-train-19561
def string(value) -> str: """ string dict/object/value to JSON """ return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)
def bfx ( value , msb , lsb ) : mask = bitmask ( ( msb , lsb ) ) return ( value & mask ) >> lsb
0
how to perform bitwise operation in python
!
cosqa-train-19562
def bfx(value, msb, lsb): """! @brief Extract a value from a bitfield.""" mask = bitmask((msb, lsb)) return (value & mask) >> lsb
def clean_int ( x ) -> int : try : return int ( x ) except ValueError : raise forms . ValidationError ( "Cannot convert to integer: {}" . format ( repr ( x ) ) )
0
python validate value is number
Returns its parameter as an integer or raises django . forms . ValidationError .
cosqa-train-19563
def clean_int(x) -> int: """ Returns its parameter as an integer, or raises ``django.forms.ValidationError``. """ try: return int(x) except ValueError: raise forms.ValidationError( "Cannot convert to integer: {}".format(repr(x)))
def list_depth ( list_ , func = max , _depth = 0 ) : depth_list = [ list_depth ( item , func = func , _depth = _depth + 1 ) for item in list_ if util_type . is_listlike ( item ) ] if len ( depth_list ) > 0 : return func ( depth_list ) else : return _depth
1
python get the depth of list of list
Returns the deepest level of nesting within a list of lists
cosqa-train-19564
def list_depth(list_, func=max, _depth=0): """ Returns the deepest level of nesting within a list of lists Args: list_ : a nested listlike object func : depth aggregation strategy (defaults to max) _depth : internal var Example: >>> # ENABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> list_ = [[[[[1]]], [3]], [[1], [3]], [[1], [3]]] >>> result = (list_depth(list_, _depth=0)) >>> print(result) """ depth_list = [list_depth(item, func=func, _depth=_depth + 1) for item in list_ if util_type.is_listlike(item)] if len(depth_list) > 0: return func(depth_list) else: return _depth
def is_inside_lambda ( node : astroid . node_classes . NodeNG ) -> bool : parent = node . parent while parent is not None : if isinstance ( parent , astroid . Lambda ) : return True parent = parent . parent return False
1
python determine if variable type is lambda function
Return true if given node is inside lambda
cosqa-train-19565
def is_inside_lambda(node: astroid.node_classes.NodeNG) -> bool: """Return true if given node is inside lambda""" parent = node.parent while parent is not None: if isinstance(parent, astroid.Lambda): return True parent = parent.parent return False
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 read file from aws s3 using python s3fs
Pull a file directly from S3 .
cosqa-train-19566
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 get_unique_links ( self ) : page_url = self . get_current_url ( ) soup = self . get_beautiful_soup ( self . get_page_source ( ) ) links = page_utils . _get_unique_links ( page_url , soup ) return links
1
all links to html pages with no duplicates vode in python
Get all unique links in the html of the page source . Page links include those obtained from : a - > href img - > src link - > href and script - > src .
cosqa-train-19567
def get_unique_links(self): """ Get all unique links in the html of the page source. Page links include those obtained from: "a"->"href", "img"->"src", "link"->"href", and "script"->"src". """ page_url = self.get_current_url() soup = self.get_beautiful_soup(self.get_page_source()) links = page_utils._get_unique_links(page_url, soup) return links
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
finding maximum value of column python
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-19568
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 identify_request ( request : RequestType ) -> bool : # noinspection PyBroadException try : data = json . loads ( decode_if_bytes ( request . body ) ) if "@context" in data : return True except Exception : pass return False
1
how to check if a request is valid or not in python
Try to identify whether this is an ActivityPub request .
cosqa-train-19569
def identify_request(request: RequestType) -> bool: """ Try to identify whether this is an ActivityPub request. """ # noinspection PyBroadException try: data = json.loads(decode_if_bytes(request.body)) if "@context" in data: return True except Exception: pass return False
def dtypes ( self ) : return [ ( str ( f . name ) , f . dataType . simpleString ( ) ) for f in self . schema . fields ]
0
python types of all panda columns
Returns all column names and their data types as a list .
cosqa-train-19570
def dtypes(self): """Returns all column names and their data types as a list. >>> df.dtypes [('age', 'int'), ('name', 'string')] """ return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]
def is_sqlatype_integer ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . Integer )
0
how to check type of object in column in python
Is the SQLAlchemy column type an integer type?
cosqa-train-19571
def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool: """ Is the SQLAlchemy column type an integer type? """ coltype = _coltype_to_typeengine(coltype) return isinstance(coltype, sqltypes.Integer)
def url_host ( url : str ) -> str : from urllib . parse import urlparse res = urlparse ( url ) return res . netloc . split ( ':' ) [ 0 ] if res . netloc else ''
1
extract hostname from url python
Parses hostname from URL . : param url : URL : return : hostname
cosqa-train-19572
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 has_key ( cls , * args ) : key = args if len ( args ) > 1 else args [ 0 ] return key in cls . _instances
1
if key exists python do this
Check whether flyweight object with specified key has already been created .
cosqa-train-19573
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 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
python list iterator know this is the last
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-19574
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 _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
1
get the unique index of a list item python
Return dict mapping item - > indices .
cosqa-train-19575
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 get_all_args ( fn ) -> list : sig = inspect . signature ( fn ) return list ( sig . parameters )
0
python print function name and all params
Returns a list of all arguments for the function fn .
cosqa-train-19576
def get_all_args(fn) -> list: """ Returns a list of all arguments for the function fn. >>> def foo(x, y, z=100): return x + y + z >>> get_all_args(foo) ['x', 'y', 'z'] """ sig = inspect.signature(fn) return list(sig.parameters)
def _kbhit_unix ( ) -> bool : dr , dw , de = select . select ( [ sys . stdin ] , [ ] , [ ] , 0 ) return dr != [ ]
0
listen udev python detect keyboard
Under UNIX : is a keystroke available?
cosqa-train-19577
def _kbhit_unix() -> bool: """ Under UNIX: is a keystroke available? """ dr, dw, de = select.select([sys.stdin], [], [], 0) return dr != []
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
python dateutil get current time zone
Discover the current time zone and it s standard string representation ( for source { d } ) .
cosqa-train-19578
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 flatten_list ( x : List [ Any ] ) -> List [ Any ] : # noqa return [ item for sublist in x for item in sublist ]
1
how to flat a list of list python
Converts a list of lists into a flat list . Args : x : list of lists
cosqa-train-19579
def flatten_list(x: List[Any]) -> List[Any]: """ Converts a list of lists into a flat list. Args: x: list of lists Returns: flat list As per http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python """ # noqa return [item for sublist in x for item in sublist]
def copy_session ( session : requests . Session ) -> requests . Session : new = requests . Session ( ) new . cookies = requests . utils . cookiejar_from_dict ( requests . utils . dict_from_cookiejar ( session . cookies ) ) new . headers = session . headers . copy ( ) return new
0
python reusing a single request session
Duplicates a requests . Session .
cosqa-train-19580
def copy_session(session: requests.Session) -> requests.Session: """Duplicates a requests.Session.""" new = requests.Session() new.cookies = requests.utils.cookiejar_from_dict(requests.utils.dict_from_cookiejar(session.cookies)) new.headers = session.headers.copy() return new
def _check_whitespace ( string ) : if string . count ( ' ' ) + string . count ( '\t' ) + string . count ( '\n' ) > 0 : raise ValueError ( INSTRUCTION_HAS_WHITESPACE )
0
python check for whitespace
Make sure thre is no whitespace in the given string . Will raise a ValueError if whitespace is detected
cosqa-train-19581
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 debugTreePrint ( node , pfx = "->" ) : print pfx , node . item for c in node . children : debugTreePrint ( c , " " + pfx )
0
how to draw a simple tree diagram in python without igraph
Purely a debugging aid : Ascii - art picture of a tree descended from node
cosqa-train-19582
def debugTreePrint(node,pfx="->"): """Purely a debugging aid: Ascii-art picture of a tree descended from node""" print pfx,node.item for c in node.children: debugTreePrint(c," "+pfx)
def flatten_list ( l : List [ list ] ) -> list : return [ v for inner_l in l for v in inner_l ]
0
python passing a flattened list
takes a list of lists l and returns a flat list
cosqa-train-19583
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 enumerate_chunks ( phrase , spacy_nlp ) : if ( len ( phrase ) > 1 ) : found = False text = " " . join ( [ rl . text for rl in phrase ] ) doc = spacy_nlp ( text . strip ( ) , parse = True ) for np in doc . noun_chunks : if np . text != text : found = True yield np . text , find_chunk ( phrase , np . text . split ( " " ) ) if not found and all ( [ rl . pos [ 0 ] != "v" for rl in phrase ] ) : yield text , phrase
1
python spacy create noun chunker
iterate through the noun phrases
cosqa-train-19584
def enumerate_chunks (phrase, spacy_nlp): """ iterate through the noun phrases """ if (len(phrase) > 1): found = False text = " ".join([rl.text for rl in phrase]) doc = spacy_nlp(text.strip(), parse=True) for np in doc.noun_chunks: if np.text != text: found = True yield np.text, find_chunk(phrase, np.text.split(" ")) if not found and all([rl.pos[0] != "v" for rl in phrase]): yield text, phrase
def _my_hash ( arg_list ) : # type: (List[Any]) -> int res = 0 for arg in arg_list : res = res * 31 + hash ( arg ) return res
0
python custom hash functions
Simple helper hash function
cosqa-train-19585
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 convert_column ( self , values ) : assert all ( values >= 0 ) , 'Cannot normalize a column with negatives' total = sum ( values ) if total > 0 : return values / total else : return values
0
function that "standardizes" a column python
Normalize values .
cosqa-train-19586
def convert_column(self, values): """Normalize values.""" assert all(values >= 0), 'Cannot normalize a column with negatives' total = sum(values) if total > 0: return values / total else: return values
def __next__ ( self ) : self . current += 1 if self . current > self . total : raise StopIteration else : return self . iterable [ self . current - 1 ]
0
iterator python has next
: return : int
cosqa-train-19587
def __next__(self): """ :return: int """ self.current += 1 if self.current > self.total: raise StopIteration else: return self.iterable[self.current - 1]
def uniqued ( iterable ) : seen = set ( ) add = seen . add return [ i for i in iterable if i not in seen and not add ( i ) ]
0
unique function in python for lists
Return unique list of items preserving order .
cosqa-train-19588
def uniqued(iterable): """Return unique list of items preserving order. >>> uniqued([3, 2, 1, 3, 2, 1, 0]) [3, 2, 1, 0] """ seen = set() add = seen.add return [i for i in iterable if i not in seen and not add(i)]
def run_web ( self , flask , host = '127.0.0.1' , port = 5000 , * * options ) : # type: (Zsl, str, int, **Any)->None return flask . run ( host = flask . config . get ( 'FLASK_HOST' , host ) , port = flask . config . get ( 'FLASK_PORT' , port ) , debug = flask . config . get ( 'DEBUG' , False ) , * * options )
0
python flask auto run
Alias for Flask . run
cosqa-train-19589
def run_web(self, flask, host='127.0.0.1', port=5000, **options): # type: (Zsl, str, int, **Any)->None """Alias for Flask.run""" return flask.run( host=flask.config.get('FLASK_HOST', host), port=flask.config.get('FLASK_PORT', port), debug=flask.config.get('DEBUG', False), **options )
def wipe_table ( self , table : str ) -> int : sql = "DELETE FROM " + self . delimit ( table ) return self . db_exec ( sql )
0
delete table from sql using python using sql server native
Delete all records from a table . Use caution!
cosqa-train-19590
def wipe_table(self, table: str) -> int: """Delete all records from a table. Use caution!""" sql = "DELETE FROM " + self.delimit(table) return self.db_exec(sql)
def write_text ( filename : str , text : str ) -> None : with open ( filename , 'w' ) as f : # type: TextIO print ( text , file = f )
0
how to write text to a file in a python
Writes text to a file .
cosqa-train-19591
def write_text(filename: str, text: str) -> None: """ Writes text to a file. """ with open(filename, 'w') as f: # type: TextIO print(text, file=f)
def 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
0
python dealth last week
Returns the last week as a period string
cosqa-train-19592
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 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
1
python median filter 3d array
Fast median operation for masked array using 50th - percentile
cosqa-train-19593
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 _is_video ( filepath ) -> bool : if os . path . exists ( filepath ) : # Could be broken symlink extension = os . path . splitext ( filepath ) [ 1 ] return extension in ( '.mkv' , '.mp4' , '.avi' ) else : return False
0
python determine if filename is media file
Check filename extension to see if it s a video file .
cosqa-train-19594
def _is_video(filepath) -> bool: """Check filename extension to see if it's a video file.""" if os.path.exists(filepath): # Could be broken symlink extension = os.path.splitext(filepath)[1] return extension in ('.mkv', '.mp4', '.avi') else: return False
def dictlist_wipe_key ( dict_list : Iterable [ Dict ] , key : str ) -> None : for d in dict_list : d . pop ( key , None )
1
remove an entry from a dict python
Process an iterable of dictionaries . For each dictionary d delete d [ key ] if it exists .
cosqa-train-19595
def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, delete ``d[key]`` if it exists. """ for d in dict_list: d.pop(key, None)
def snake_to_camel ( s : str ) -> str : fragments = s . split ( '_' ) return fragments [ 0 ] + '' . join ( x . title ( ) for x in fragments [ 1 : ] )
0
how to capitalize words in python with str
Convert string from snake case to camel case .
cosqa-train-19596
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 check_key ( self , key : str ) -> bool : keys = self . get_keys ( ) return key in keys
1
verify if value exists in hash table python
Checks if key exists in datastore . True if yes False if no .
cosqa-train-19597
def check_key(self, key: str) -> bool: """ Checks if key exists in datastore. True if yes, False if no. :param: SHA512 hash key :return: whether or key not exists in datastore """ keys = self.get_keys() return key in keys
def shape ( self ) -> Tuple [ int , ... ] : return tuple ( bins . bin_count for bins in self . _binnings )
0
how to get the number of value fall in each bins histogram python
Shape of histogram s data .
cosqa-train-19598
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 str_upper ( x ) : sl = _to_string_sequence ( x ) . upper ( ) return column . ColumnStringArrow ( sl . bytes , sl . indices , sl . length , sl . offset , string_sequence = sl )
0
python how to change column to uppercase
Converts all strings in a column to uppercase .
cosqa-train-19599
def str_upper(x): """Converts all strings in a column to uppercase. :returns: an expression containing the converted strings. Example: >>> import vaex >>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.'] >>> df = vaex.from_arrays(text=text) >>> df # text 0 Something 1 very pretty 2 is coming 3 our 4 way. >>> df.text.str.upper() Expression = str_upper(text) Length: 5 dtype: str (expression) --------------------------------- 0 SOMETHING 1 VERY PRETTY 2 IS COMING 3 OUR 4 WAY. """ sl = _to_string_sequence(x).upper() return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl)