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 rmglob ( pattern : str ) -> None : for f in glob . glob ( pattern ) : os . remove ( f )
1
python delete all files with a given extension
Deletes all files whose filename matches the glob pattern ( via : func : glob . glob ) .
cosqa-train-19100
def rmglob(pattern: str) -> None: """ Deletes all files whose filename matches the glob ``pattern`` (via :func:`glob.glob`). """ for f in glob.glob(pattern): os.remove(f)
def get_property_as_float ( self , name : str ) -> float : return float ( self . __instrument . get_property ( name ) )
0
how to define a float in python
Return the value of a float property .
cosqa-train-19101
def get_property_as_float(self, name: str) -> float: """Return the value of a float property. :return: The property value (float). Raises exception if property with name doesn't exist. .. versionadded:: 1.0 Scriptable: Yes """ return float(self.__instrument.get_property(name))
def zfill ( x , width ) : if not isinstance ( x , basestring ) : x = repr ( x ) return x . zfill ( width )
0
zero padding in strings in python
zfill ( x width ) - > string
cosqa-train-19102
def zfill(x, width): """zfill(x, width) -> string Pad a numeric string x with zeros on the left, to fill a field of the specified width. The string x is never truncated. """ if not isinstance(x, basestring): x = repr(x) return x.zfill(width)
def get_column_names ( engine : Engine , tablename : str ) -> List [ str ] : return [ info . name for info in gen_columns_info ( engine , tablename ) ]
0
how to list dynamo db table names using python
Get all the database column names for the specified table .
cosqa-train-19103
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 ( self , status_code ) : # If there are active threads still running infinite loops, sys.exit # won't kill them but os._exit will. os._exit skips calling cleanup # handlers, flushing stdio buffers, etc. exit_func = os . _exit if threading . active_count ( ) > 1 else sys . exit exit_func ( status_code )
0
how to kill threads python
Properly kill Python process including zombie threads .
cosqa-train-19104
def _exit(self, status_code): """Properly kill Python process including zombie threads.""" # If there are active threads still running infinite loops, sys.exit # won't kill them but os._exit will. os._exit skips calling cleanup # handlers, flushing stdio buffers, etc. exit_func = os._exit if threading.active_count() > 1 else sys.exit exit_func(status_code)
def _duplicates ( list_ ) : item_indices = { } for i , item in enumerate ( list_ ) : try : item_indices [ item ] . append ( i ) except KeyError : # First time seen item_indices [ item ] = [ i ] return item_indices
0
python list to dictionary with indexs
Return dict mapping item - > indices .
cosqa-train-19105
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_column_names ( engine : Engine , tablename : str ) -> List [ str ] : return [ info . name for info in gen_columns_info ( engine , tablename ) ]
0
get column names from the database in python pyodbc
Get all the database column names for the specified table .
cosqa-train-19106
def get_column_names(engine: Engine, tablename: str) -> List[str]: """ Get all the database column names for the specified table. """ return [info.name for info in gen_columns_info(engine, tablename)]
def remove_once ( gset , elem ) : remove = getattr ( gset , 'remove' , None ) if remove is not None : remove ( elem ) else : del gset [ elem ] return elem
1
how to delete something 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-19107
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 is_unicode ( string ) : str_type = str ( type ( string ) ) if str_type . find ( 'str' ) > 0 or str_type . find ( 'unicode' ) > 0 : return True return False
1
python check type if string
Validates that the object itself is some kinda string
cosqa-train-19108
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 remove_blank_lines ( string ) : return "\n" . join ( line for line in string . split ( "\n" ) if len ( line . strip ( ) ) )
1
delete blank str python
Removes all blank lines in @string
cosqa-train-19109
def remove_blank_lines(string): """ Removes all blank lines in @string -> #str without blank lines """ return "\n".join(line for line in string.split("\n") if len(line.strip()))
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
get read position python
Returns the offset of the current cursor position in rl_line_buffer
cosqa-train-19110
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 get_pylint_options ( config_dir = '.' ) : # type: (str) -> List[str] if PYLINT_CONFIG_NAME in os . listdir ( config_dir ) : pylint_config_path = PYLINT_CONFIG_NAME else : pylint_config_path = DEFAULT_PYLINT_CONFIG_PATH return [ '--rcfile={}' . format ( pylint_config_path ) ]
1
change python path pylint
Checks for local config overrides for pylint and add them in the correct pylint options format .
cosqa-train-19111
def get_pylint_options(config_dir='.'): # type: (str) -> List[str] """Checks for local config overrides for `pylint` and add them in the correct `pylint` `options` format. :param config_dir: :return: List [str] """ if PYLINT_CONFIG_NAME in os.listdir(config_dir): pylint_config_path = PYLINT_CONFIG_NAME else: pylint_config_path = DEFAULT_PYLINT_CONFIG_PATH return ['--rcfile={}'.format(pylint_config_path)]
def _skip ( self , cnt ) : while cnt > 0 : if cnt > 8192 : buf = self . read ( 8192 ) else : buf = self . read ( cnt ) if not buf : break cnt -= len ( buf )
0
python skip[ byte read file
Read and discard data
cosqa-train-19112
def _skip(self, cnt): """Read and discard data""" while cnt > 0: if cnt > 8192: buf = self.read(8192) else: buf = self.read(cnt) if not buf: break cnt -= len(buf)
def get_domain ( url ) : parse_result = urlparse ( url ) domain = "{schema}://{netloc}" . format ( schema = parse_result . scheme , netloc = parse_result . netloc ) return domain
1
python url extraction from domains
Get domain part of an url .
cosqa-train-19113
def get_domain(url): """ Get domain part of an url. For example: https://www.python.org/doc/ -> https://www.python.org """ parse_result = urlparse(url) domain = "{schema}://{netloc}".format( schema=parse_result.scheme, netloc=parse_result.netloc) return domain
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
empty file condition in python
Check if cnr or cns files are empty ( only have a header )
cosqa-train-19114
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 argmax ( iterable , key = None , both = False ) : if key is not None : it = imap ( key , iterable ) else : it = iter ( iterable ) score , argmax = reduce ( max , izip ( it , count ( ) ) ) if both : return argmax , score return argmax
0
max on a list of ints in python
>>> argmax ( [ 4 2 - 5 ] ) 0 >>> argmax ( [ 4 2 - 5 ] key = abs ) 2 >>> argmax ( [ 4 2 - 5 ] key = abs both = True ) ( 2 5 )
cosqa-train-19115
def argmax(iterable, key=None, both=False): """ >>> argmax([4,2,-5]) 0 >>> argmax([4,2,-5], key=abs) 2 >>> argmax([4,2,-5], key=abs, both=True) (2, 5) """ if key is not None: it = imap(key, iterable) else: it = iter(iterable) score, argmax = reduce(max, izip(it, count())) if both: return argmax, score return argmax
def bfx ( value , msb , lsb ) : mask = bitmask ( ( msb , lsb ) ) return ( value & mask ) >> lsb
0
how to do a bitwise and function in python
!
cosqa-train-19116
def bfx(value, msb, lsb): """! @brief Extract a value from a bitfield.""" mask = bitmask((msb, lsb)) return (value & mask) >> lsb
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 ] ]
0
python max column 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-19117
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 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
python determine if path is relative or absolute
simple method to determine if a url is relative or absolute
cosqa-train-19118
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
python3 np arry to str
Format numpy array as a string .
cosqa-train-19119
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 _get_or_default ( mylist , i , default = None ) : if i >= len ( mylist ) : return default else : return mylist [ i ]
0
get first or default in python
return list item number or default if don t exist
cosqa-train-19120
def _get_or_default(mylist, i, default=None): """return list item number, or default if don't exist""" if i >= len(mylist): return default else : return mylist[i]
def hex_to_int ( value ) : if version_info . major >= 3 : return int . from_bytes ( value , "big" ) return int ( value . encode ( "hex" ) , 16 )
1
python3 hex to int
Convert hex string like \ x0A \ xE3 to 2787 .
cosqa-train-19121
def hex_to_int(value): """ Convert hex string like "\x0A\xE3" to 2787. """ if version_info.major >= 3: return int.from_bytes(value, "big") return int(value.encode("hex"), 16)
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
remove links in python clean text
Helper function to remove the links from the input text
cosqa-train-19122
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 _ ( f , x ) : return { k : v for k , v in x . items ( ) if f ( k , v ) }
1
usinf filter on dictionary python
filter for dict note f should have signature : f :: key - > value - > bool
cosqa-train-19123
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 validate ( request : Union [ Dict , List ] , schema : dict ) -> Union [ Dict , List ] : jsonschema_validate ( request , schema ) return request
1
validations for dict inside array jsonschema python
Wraps jsonschema . validate returning the same object passed in .
cosqa-train-19124
def validate(request: Union[Dict, List], schema: dict) -> Union[Dict, List]: """ Wraps jsonschema.validate, returning the same object passed in. Args: request: The deserialized-from-json request. schema: The jsonschema schema to validate against. Raises: jsonschema.ValidationError """ jsonschema_validate(request, schema) return request
def load_yaml ( file ) : if hasattr ( yaml , "full_load" ) : return yaml . full_load ( file ) else : return yaml . load ( file )
1
python is yaml load fails
If pyyaml > 5 . 1 use full_load to avoid warning
cosqa-train-19125
def load_yaml(file): """If pyyaml > 5.1 use full_load to avoid warning""" if hasattr(yaml, "full_load"): return yaml.full_load(file) else: return yaml.load(file)
def astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( value = array , dtype = CTYPE ) return tensor
0
python list to tensorflow tensor
Covert numpy array to tensorflow tensor
cosqa-train-19126
def astensor(array: TensorLike) -> BKTensor: """Covert numpy array to tensorflow tensor""" tensor = tf.convert_to_tensor(value=array, dtype=CTYPE) return tensor
def hsv2rgb_spectrum ( hsv ) : h , s , v = hsv return hsv2rgb_raw ( ( ( h * 192 ) >> 8 , s , v ) )
0
python hsv rgb transform
Generates RGB values from HSV values in line with a typical light spectrum .
cosqa-train-19127
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 format_exp_floats ( decimals ) : threshold = 10 ** 5 return ( lambda n : "{:.{prec}e}" . format ( n , prec = decimals ) if n > threshold else "{:4.{prec}f}" . format ( n , prec = decimals ) )
0
format decimals as percentages in a column, 2 decimals python
sometimes the exp . column can be too large
cosqa-train-19128
def format_exp_floats(decimals): """ sometimes the exp. column can be too large """ threshold = 10 ** 5 return ( lambda n: "{:.{prec}e}".format(n, prec=decimals) if n > threshold else "{:4.{prec}f}".format(n, prec=decimals) )
def login ( self , user : str , passwd : str ) -> None : self . context . login ( user , passwd )
0
how to log in in instagram using python
Log in to instagram with given username and password and internally store session object .
cosqa-train-19129
def login(self, user: str, passwd: str) -> None: """Log in to instagram with given username and password and internally store session object. :raises InvalidArgumentException: If the provided username does not exist. :raises BadCredentialsException: If the provided password is wrong. :raises ConnectionException: If connection to Instagram failed. :raises TwoFactorAuthRequiredException: First step of 2FA login done, now call :meth:`Instaloader.two_factor_login`.""" self.context.login(user, passwd)
def is_not_null ( df : DataFrame , col_name : str ) -> bool : if ( isinstance ( df , pd . DataFrame ) and col_name in df . columns and df [ col_name ] . notnull ( ) . any ( ) ) : return True else : return False
0
python df check if column has specif nan value
Return True if the given DataFrame has a column of the given name ( string ) and there exists at least one non - NaN value in that column ; return False otherwise .
cosqa-train-19130
def is_not_null(df: DataFrame, col_name: str) -> bool: """ Return ``True`` if the given DataFrame has a column of the given name (string), and there exists at least one non-NaN value in that column; return ``False`` otherwise. """ if ( isinstance(df, pd.DataFrame) and col_name in df.columns and df[col_name].notnull().any() ): return True else: return False
def quaternion_imag ( quaternion ) : return np . array ( quaternion [ 1 : 4 ] , dtype = np . float64 , copy = True )
0
get entire first dimension of 3dimension array python
Return imaginary part of quaternion .
cosqa-train-19131
def quaternion_imag(quaternion): """Return imaginary part of quaternion. >>> quaternion_imag([3, 0, 1, 2]) array([0., 1., 2.]) """ return np.array(quaternion[1:4], dtype=np.float64, copy=True)
def _skip_section ( self ) : self . _last = self . _f . readline ( ) while len ( self . _last ) > 0 and len ( self . _last [ 0 ] . strip ( ) ) == 0 : self . _last = self . _f . readline ( )
0
python how to skip a line
Skip a section
cosqa-train-19132
def _skip_section(self): """Skip a section""" self._last = self._f.readline() while len(self._last) > 0 and len(self._last[0].strip()) == 0: self._last = self._f.readline()
def is_natural ( x ) : try : is_integer = int ( x ) == x except ( TypeError , ValueError ) : return False return is_integer and x >= 0
0
not a number equal python
A non - negative integer .
cosqa-train-19133
def is_natural(x): """A non-negative integer.""" try: is_integer = int(x) == x except (TypeError, ValueError): return False return is_integer and x >= 0
def stretch ( iterable , n = 2 ) : times = range ( n ) for item in iterable : for i in times : yield item
1
python repeat a value n times in a list
r Repeat each item in iterable n times .
cosqa-train-19134
def stretch(iterable, n=2): r"""Repeat each item in `iterable` `n` times. Example: >>> list(stretch(range(3), 2)) [0, 0, 1, 1, 2, 2] """ times = range(n) for item in iterable: for i in times: yield item
def remove_leading_zeros ( num : str ) -> str : if not num : return num if num . startswith ( 'M' ) : ret = 'M' + num [ 1 : ] . lstrip ( '0' ) elif num . startswith ( '-' ) : ret = '-' + num [ 1 : ] . lstrip ( '0' ) else : ret = num . lstrip ( '0' ) return '0' if ret in ( '' , 'M' , '-' ) else ret
1
how to keep leading zero's in an integer in python
Strips zeros while handling - M and empty strings
cosqa-train-19135
def remove_leading_zeros(num: str) -> str: """ Strips zeros while handling -, M, and empty strings """ if not num: return num if num.startswith('M'): ret = 'M' + num[1:].lstrip('0') elif num.startswith('-'): ret = '-' + num[1:].lstrip('0') else: ret = num.lstrip('0') return '0' if ret in ('', 'M', '-') else ret
def _create_empty_array ( self , frames , always_2d , dtype ) : import numpy as np if always_2d or self . channels > 1 : shape = frames , self . channels else : shape = frames , return np . empty ( shape , dtype , order = 'C' )
0
make empty 2d array python
Create an empty array with appropriate shape .
cosqa-train-19136
def _create_empty_array(self, frames, always_2d, dtype): """Create an empty array with appropriate shape.""" import numpy as np if always_2d or self.channels > 1: shape = frames, self.channels else: shape = frames, return np.empty(shape, dtype, order='C')
def dict_to_enum_fn ( d : Dict [ str , Any ] , enum_class : Type [ Enum ] ) -> Enum : return enum_class [ d [ 'name' ] ]
1
python enum not json serializable
Converts an dict to a Enum .
cosqa-train-19137
def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum: """ Converts an ``dict`` to a ``Enum``. """ return enum_class[d['name']]
def increment_frame ( self ) : self . current_frame += 1 if self . current_frame >= self . end_frame : # Wrap back to the beginning of the animation. self . current_frame = 0
1
increase animation speed python
Increment a frame of the animation .
cosqa-train-19138
def increment_frame(self): """Increment a frame of the animation.""" self.current_frame += 1 if self.current_frame >= self.end_frame: # Wrap back to the beginning of the animation. self.current_frame = 0
def is_integer ( value : Any ) -> bool : return ( isinstance ( value , int ) and not isinstance ( value , bool ) ) or ( isinstance ( value , float ) and isfinite ( value ) and int ( value ) == value )
0
check if value is integeer python
Return true if a value is an integer number .
cosqa-train-19139
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 samefile ( a : str , b : str ) -> bool : try : return os . path . samefile ( a , b ) except OSError : return os . path . normpath ( a ) == os . path . normpath ( b )
0
python check if two path are the same
Check if two pathes represent the same file .
cosqa-train-19140
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 __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
how to replace some characters in a string in python
Replaces from a string ** input ** all the occurrences of some symbols according to mapping ** repls ** .
cosqa-train-19141
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 dotproduct ( X , Y ) : return sum ( [ x * y for x , y in zip ( X , Y ) ] )
0
element wise product python
Return the sum of the element - wise product of vectors x and y . >>> dotproduct ( [ 1 2 3 ] [ 1000 100 10 ] ) 1230
cosqa-train-19142
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)])
async def fetchall ( self ) -> Iterable [ sqlite3 . Row ] : return await self . _execute ( self . _cursor . fetchall )
0
python mysql yield all rows
Fetch all remaining rows .
cosqa-train-19143
async def fetchall(self) -> Iterable[sqlite3.Row]: """Fetch all remaining rows.""" return await self._execute(self._cursor.fetchall)
def rate_limited ( max_per_hour : int , * args : Any ) -> Callable [ ... , Any ] : return util . rate_limited ( max_per_hour , * args )
0
python how to define limit of function
Rate limit a function .
cosqa-train-19144
def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]: """Rate limit a function.""" return util.rate_limited(max_per_hour, *args)
def hex_to_int ( value ) : if version_info . major >= 3 : return int . from_bytes ( value , "big" ) return int ( value . encode ( "hex" ) , 16 )
1
python string of hex to int
Convert hex string like \ x0A \ xE3 to 2787 .
cosqa-train-19145
def hex_to_int(value): """ Convert hex string like "\x0A\xE3" to 2787. """ if version_info.major >= 3: return int.from_bytes(value, "big") return int(value.encode("hex"), 16)
def is_integer ( value : Any ) -> bool : return ( isinstance ( value , int ) and not isinstance ( value , bool ) ) or ( isinstance ( value , float ) and isfinite ( value ) and int ( value ) == value )
0
python is integer or float
Return true if a value is an integer number .
cosqa-train-19146
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 de_duplicate ( items ) : result = [ ] for item in items : if item not in result : result . append ( item ) return result
0
python how delete item in a list if partial duplicate
Remove any duplicate item preserving order
cosqa-train-19147
def de_duplicate(items): """Remove any duplicate item, preserving order >>> de_duplicate([1, 2, 1, 2]) [1, 2] """ result = [] for item in items: if item not in result: result.append(item) return result
def uppercase_chars ( string : any ) -> str : return '' . join ( [ c if c . isupper ( ) else '' for c in str ( string ) ] )
0
how to uppercase first letter in each sentence python string upper method
Return all ( and only ) the uppercase chars in the given string .
cosqa-train-19148
def uppercase_chars(string: any) -> str: """Return all (and only) the uppercase chars in the given string.""" return ''.join([c if c.isupper() else '' for c in str(string)])
def cli_run ( ) : parser = argparse . ArgumentParser ( description = 'Stupidly simple code answers from StackOverflow' ) parser . add_argument ( 'query' , help = "What's the problem ?" , type = str , nargs = '+' ) parser . add_argument ( '-t' , '--tags' , help = 'semicolon separated tags -> python;lambda' ) args = parser . parse_args ( ) main ( args )
1
python how to call main that has argparse
docstring for argparse
cosqa-train-19149
def cli_run(): """docstring for argparse""" parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow') parser.add_argument('query', help="What's the problem ?", type=str, nargs='+') parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda') args = parser.parse_args() main(args)
def _duplicates ( list_ ) : item_indices = { } for i , item in enumerate ( list_ ) : try : item_indices [ item ] . append ( i ) except KeyError : # First time seen item_indices [ item ] = [ i ] return item_indices
0
create a list of unique indexes python
Return dict mapping item - > indices .
cosqa-train-19150
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 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
how to check if a line is in a txt file python
Detects whether a line is present within a file .
cosqa-train-19151
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 closest_values ( L ) : assert len ( L ) >= 2 L . sort ( ) valmin , argmin = min ( ( L [ i ] - L [ i - 1 ] , i ) for i in range ( 1 , len ( L ) ) ) return L [ argmin - 1 ] , L [ argmin ]
1
python get two closest numbers in list
Closest values
cosqa-train-19152
def closest_values(L): """Closest values :param L: list of values :returns: two values from L with minimal distance :modifies: the order of L :complexity: O(n log n), for n=len(L) """ assert len(L) >= 2 L.sort() valmin, argmin = min((L[i] - L[i - 1], i) for i in range(1, len(L))) return L[argmin - 1], L[argmin]
def singularize ( word ) : for inflection in UNCOUNTABLES : if re . search ( r'(?i)\b(%s)\Z' % inflection , word ) : return word for rule , replacement in SINGULARS : if re . search ( rule , word ) : return re . sub ( rule , replacement , word ) return word
0
function that returns plural string python
Return the singular form of a word the reverse of : func : pluralize .
cosqa-train-19153
def singularize(word): """ Return the singular form of a word, the reverse of :func:`pluralize`. Examples:: >>> singularize("posts") "post" >>> singularize("octopi") "octopus" >>> singularize("sheep") "sheep" >>> singularize("word") "word" >>> singularize("CamelOctopi") "CamelOctopus" """ for inflection in UNCOUNTABLES: if re.search(r'(?i)\b(%s)\Z' % inflection, word): return word for rule, replacement in SINGULARS: if re.search(rule, word): return re.sub(rule, replacement, word) return word
def to_bytes ( data : Any ) -> bytearray : # noqa if isinstance ( data , int ) : return bytearray ( [ data ] ) return bytearray ( data , encoding = 'latin-1' )
1
cast string to bytearray python
Convert anything to a bytearray . See - http : // stackoverflow . com / questions / 7585435 / best - way - to - convert - string - to - bytes - in - python - 3 - http : // stackoverflow . com / questions / 10459067 / how - to - convert - my - bytearrayb - x9e - x18k - x9a - to - something - like - this - x9e - x1
cosqa-train-19154
def to_bytes(data: Any) -> bytearray: """ Convert anything to a ``bytearray``. See - http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3 - http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1 """ # noqa if isinstance(data, int): return bytearray([data]) return bytearray(data, encoding='latin-1')
def factors ( n ) : return set ( reduce ( list . __add__ , ( [ i , n // i ] for i in range ( 1 , int ( n ** 0.5 ) + 1 ) if n % i == 0 ) ) )
1
python list the factors of an integer
Computes all the integer factors of the number n
cosqa-train-19155
def factors(n): """ Computes all the integer factors of the number `n` Example: >>> # ENABLE_DOCTEST >>> from utool.util_alg import * # NOQA >>> import utool as ut >>> result = sorted(ut.factors(10)) >>> print(result) [1, 2, 5, 10] References: http://stackoverflow.com/questions/6800193/finding-all-the-factors """ return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
def get_environment_info ( ) -> dict : data = _environ . systems . get_system_data ( ) data [ 'cauldron' ] = _environ . package_settings . copy ( ) return data
1
how to get the env variables in python in crontab
Information about Cauldron and its Python interpreter .
cosqa-train-19156
def get_environment_info() -> dict: """ Information about Cauldron and its Python interpreter. :return: A dictionary containing information about the Cauldron and its Python environment. This information is useful when providing feedback and bug reports. """ data = _environ.systems.get_system_data() data['cauldron'] = _environ.package_settings.copy() return data
def _rindex ( mylist : Sequence [ T ] , x : T ) -> int : return len ( mylist ) - mylist [ : : - 1 ] . index ( x ) - 1
0
return last matching index python
Index of the last occurrence of x in the sequence .
cosqa-train-19157
def _rindex(mylist: Sequence[T], x: T) -> int: """Index of the last occurrence of x in the sequence.""" return len(mylist) - mylist[::-1].index(x) - 1
def dotproduct ( X , Y ) : return sum ( [ x * y for x , y in zip ( X , Y ) ] )
1
dot product of 2d matrix 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-19158
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_empty_text ( utterances : List [ Utterance ] ) -> List [ Utterance ] : return [ utter for utter in utterances if utter . text . strip ( ) != "" ]
0
python strip all items in a list
Remove empty utterances from a list of utterances Args : utterances : The list of utterance we are processing
cosqa-train-19159
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 detect_model_num ( string ) : match = re . match ( MODEL_NUM_REGEX , string ) if match : return int ( match . group ( ) ) return None
0
extract model number from a split python
Takes a string related to a model name and extract its model number .
cosqa-train-19160
def detect_model_num(string): """Takes a string related to a model name and extract its model number. For example: '000000-bootstrap.index' => 0 """ match = re.match(MODEL_NUM_REGEX, string) if match: return int(match.group()) return None
def is_sqlatype_integer ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . Integer )
0
change column type from pbject to int python
Is the SQLAlchemy column type an integer type?
cosqa-train-19161
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 uniqued ( iterable ) : seen = set ( ) return [ item for item in iterable if item not in seen and not seen . add ( item ) ]
1
python get unique values from object
Return unique list of iterable items preserving order .
cosqa-train-19162
def uniqued(iterable): """Return unique list of ``iterable`` items preserving order. >>> uniqued('spameggs') ['s', 'p', 'a', 'm', 'e', 'g'] """ seen = set() return [item for item in iterable if item not in seen and not seen.add(item)]
def auto_up ( self , count = 1 , go_to_start_of_line_if_history_changes = False ) : if self . complete_state : self . complete_previous ( count = count ) elif self . document . cursor_position_row > 0 : self . cursor_up ( count = count ) elif not self . selection_state : self . history_backward ( count = count ) # Go to the start of the line? if go_to_start_of_line_if_history_changes : self . cursor_position += self . document . get_start_of_line_position ( )
1
how to loopback to a previous line in python
If we re not on the first line ( of a multiline input ) go a line up otherwise go back in history . ( If nothing is selected . )
cosqa-train-19163
def auto_up(self, count=1, go_to_start_of_line_if_history_changes=False): """ If we're not on the first line (of a multiline input) go a line up, otherwise go back in history. (If nothing is selected.) """ if self.complete_state: self.complete_previous(count=count) elif self.document.cursor_position_row > 0: self.cursor_up(count=count) elif not self.selection_state: self.history_backward(count=count) # Go to the start of the line? if go_to_start_of_line_if_history_changes: self.cursor_position += self.document.get_start_of_line_position()
def pruning ( self , X , y , cost_mat ) : self . tree_ . tree_pruned = copy . deepcopy ( self . tree_ . tree ) if self . tree_ . n_nodes > 0 : self . _pruning ( X , y , cost_mat ) nodes_pruned = self . _nodes ( self . tree_ . tree_pruned ) self . tree_ . n_nodes_pruned = len ( nodes_pruned )
1
how to post prune decision tree python
Function that prune the decision tree .
cosqa-train-19164
def pruning(self, X, y, cost_mat): """ Function that prune the decision tree. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y_true : array indicator matrix Ground truth (correct) labels. cost_mat : array-like of shape = [n_samples, 4] Cost matrix of the classification problem Where the columns represents the costs of: false positives, false negatives, true positives and true negatives, for each example. """ self.tree_.tree_pruned = copy.deepcopy(self.tree_.tree) if self.tree_.n_nodes > 0: self._pruning(X, y, cost_mat) nodes_pruned = self._nodes(self.tree_.tree_pruned) self.tree_.n_nodes_pruned = len(nodes_pruned)
def get_from_gnucash26_date ( date_str : str ) -> date : date_format = "%Y%m%d" result = datetime . strptime ( date_str , date_format ) . date ( ) return result
0
python 3 covert string to date
Creates a datetime from GnuCash 2 . 6 date string
cosqa-train-19165
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 branches ( ) : # type: () -> List[str] out = shell . run ( 'git branch' , capture = True , never_pretend = True ) . stdout . strip ( ) return [ x . strip ( '* \t\n' ) for x in out . splitlines ( ) ]
0
how to get branches from git by python
Return a list of branches in the current repo .
cosqa-train-19166
def branches(): # type: () -> List[str] """ Return a list of branches in the current repo. Returns: list[str]: A list of branches in the current repo. """ out = shell.run( 'git branch', capture=True, never_pretend=True ).stdout.strip() return [x.strip('* \t\n') for x in out.splitlines()]
def content_type ( self ) -> ContentType : return self . _ctype if self . _ctype else self . parent . content_type ( )
1
python get type of self
Return receiver s content type .
cosqa-train-19167
def content_type(self) -> ContentType: """Return receiver's content type.""" return self._ctype if self._ctype else self.parent.content_type()
def butlast ( iterable ) : iterable = iter ( iterable ) try : first = next ( iterable ) except StopIteration : return for second in iterable : yield first first = second
0
python list of lists last element
Yield all items from iterable except the last one .
cosqa-train-19168
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 get_keys_of_max_n ( dict_obj , n ) : return sorted ( [ item [ 0 ] for item in sorted ( dict_obj . items ( ) , key = lambda item : item [ 1 ] , reverse = True ) [ : n ] ] )
0
highest values of a dictionary values in python
Returns the keys that maps to the top n max values in the given dict .
cosqa-train-19169
def get_keys_of_max_n(dict_obj, n): """Returns the keys that maps to the top n max values in the given dict. Example: -------- >>> dict_obj = {'a':2, 'b':1, 'c':5} >>> get_keys_of_max_n(dict_obj, 2) ['a', 'c'] """ return sorted([ item[0] for item in sorted( dict_obj.items(), key=lambda item: item[1], reverse=True )[:n] ])
def _parse_tuple_string ( argument ) : if isinstance ( argument , str ) : return tuple ( int ( p . strip ( ) ) for p in argument . split ( ',' ) ) return argument
1
python string split to list of tuples
Return a tuple from parsing a b c d - > ( a b c d )
cosqa-train-19170
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 clean_column_names ( df : DataFrame ) -> DataFrame : f = df . copy ( ) f . columns = [ col . strip ( ) for col in f . columns ] return f
0
how to drop all column names in python
Strip the whitespace from all column names in the given DataFrame and return the result .
cosqa-train-19171
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 _rindex ( mylist : Sequence [ T ] , x : T ) -> int : return len ( mylist ) - mylist [ : : - 1 ] . index ( x ) - 1
0
index of the last occurrence in python
Index of the last occurrence of x in the sequence .
cosqa-train-19172
def _rindex(mylist: Sequence[T], x: T) -> int: """Index of the last occurrence of x in the sequence.""" return len(mylist) - mylist[::-1].index(x) - 1
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
python determine a url relative or absolute
simple method to determine if a url is relative or absolute
cosqa-train-19173
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 fetchallfirstvalues ( self , sql : str , * args ) -> List [ Any ] : rows = self . fetchall ( sql , * args ) return [ row [ 0 ] for row in rows ]
0
extract first row from a table in python sql
Executes SQL ; returns list of first values of each row .
cosqa-train-19174
def fetchallfirstvalues(self, sql: str, *args) -> List[Any]: """Executes SQL; returns list of first values of each row.""" rows = self.fetchall(sql, *args) return [row[0] for row in rows]
def url_concat ( url , args ) : if not args : return url if url [ - 1 ] not in ( '?' , '&' ) : url += '&' if ( '?' in url ) else '?' return url + urllib . urlencode ( args )
1
python url join query string
Concatenate url and argument dictionary regardless of whether url has existing query parameters .
cosqa-train-19175
def url_concat(url, args): """Concatenate url and argument dictionary regardless of whether url has existing query parameters. >>> url_concat("http://example.com/foo?a=b", dict(c="d")) 'http://example.com/foo?a=b&c=d' """ if not args: return url if url[-1] not in ('?', '&'): url += '&' if ('?' in url) else '?' return url + urllib.urlencode(args)
def proper_round ( n ) : return int ( n ) + ( n / abs ( n ) ) * int ( abs ( n - int ( n ) ) >= 0.5 ) if n != 0 else 0
0
round to nearest even number python
rounds float to closest int : rtype : int : param n : float
cosqa-train-19176
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 uppercase_chars ( string : any ) -> str : return '' . join ( [ c if c . isupper ( ) else '' for c in str ( string ) ] )
0
python code for changing string to uppercase
Return all ( and only ) the uppercase chars in the given string .
cosqa-train-19177
def uppercase_chars(string: any) -> str: """Return all (and only) the uppercase chars in the given string.""" return ''.join([c if c.isupper() else '' for c in str(string)])
def _prm_get_longest_stringsize ( string_list ) : maxlength = 1 for stringar in string_list : if isinstance ( stringar , np . ndarray ) : if stringar . ndim > 0 : for string in stringar . ravel ( ) : maxlength = max ( len ( string ) , maxlength ) else : maxlength = max ( len ( stringar . tolist ( ) ) , maxlength ) else : maxlength = max ( len ( stringar ) , maxlength ) # Make the string Col longer than needed in order to allow later on slightly larger strings return int ( maxlength * 1.5 )
1
max string length for given sting list python
Returns the longest string size for a string entry across data .
cosqa-train-19178
def _prm_get_longest_stringsize(string_list): """ Returns the longest string size for a string entry across data.""" maxlength = 1 for stringar in string_list: if isinstance(stringar, np.ndarray): if stringar.ndim > 0: for string in stringar.ravel(): maxlength = max(len(string), maxlength) else: maxlength = max(len(stringar.tolist()), maxlength) else: maxlength = max(len(stringar), maxlength) # Make the string Col longer than needed in order to allow later on slightly larger strings return int(maxlength * 1.5)
def flatten_list ( x : List [ Any ] ) -> List [ Any ] : # noqa return [ item for sublist in x for item in sublist ]
1
python flat list of list to list
Converts a list of lists into a flat list . Args : x : list of lists
cosqa-train-19179
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 count ( args ) : counts = defaultdict ( int ) for arg in args : for item in arg : counts [ item ] = counts [ item ] + 1 return counts
1
count the occurence in a list python
count occurences in a list of lists >>> count ( [[ a b ] [ a ]] ) defaultdict ( int { a : 2 b : 1 } )
cosqa-train-19180
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 do_quit ( self , _ : argparse . Namespace ) -> bool : self . _should_quit = True return self . _STOP_AND_EXIT
0
python abort script but not exit the gui
Exit this application
cosqa-train-19181
def do_quit(self, _: argparse.Namespace) -> bool: """Exit this application""" self._should_quit = True return self._STOP_AND_EXIT
def replace_in_list ( stringlist : Iterable [ str ] , replacedict : Dict [ str , str ] ) -> List [ str ] : newlist = [ ] for fromstring in stringlist : newlist . append ( multiple_replace ( fromstring , replacedict ) ) return newlist
0
python replace function with for loop
Returns a list produced by applying : func : multiple_replace to every string in stringlist .
cosqa-train-19182
def replace_in_list(stringlist: Iterable[str], replacedict: Dict[str, str]) -> List[str]: """ Returns a list produced by applying :func:`multiple_replace` to every string in ``stringlist``. Args: stringlist: list of source strings replacedict: dictionary mapping "original" to "replacement" strings Returns: list of final strings """ newlist = [] for fromstring in stringlist: newlist.append(multiple_replace(fromstring, replacedict)) return newlist
def is_not_null ( df : DataFrame , col_name : str ) -> bool : if ( isinstance ( df , pd . DataFrame ) and col_name in df . columns and df [ col_name ] . notnull ( ) . any ( ) ) : return True else : return False
1
python determine if data frame has a null
Return True if the given DataFrame has a column of the given name ( string ) and there exists at least one non - NaN value in that column ; return False otherwise .
cosqa-train-19183
def is_not_null(df: DataFrame, col_name: str) -> bool: """ Return ``True`` if the given DataFrame has a column of the given name (string), and there exists at least one non-NaN value in that column; return ``False`` otherwise. """ if ( isinstance(df, pd.DataFrame) and col_name in df.columns and df[col_name].notnull().any() ): return True else: return False
def _hash_the_file ( hasher , filename ) : BUF_SIZE = 65536 with open ( filename , 'rb' ) as f : buf = f . read ( BUF_SIZE ) while len ( buf ) > 0 : hasher . update ( buf ) buf = f . read ( BUF_SIZE ) return hasher
0
hashlib for file python
Helper function for creating hash functions .
cosqa-train-19184
def _hash_the_file(hasher, filename): """Helper function for creating hash functions. See implementation of :func:`dtoolcore.filehasher.shasum` for more usage details. """ BUF_SIZE = 65536 with open(filename, 'rb') as f: buf = f.read(BUF_SIZE) while len(buf) > 0: hasher.update(buf) buf = f.read(BUF_SIZE) return hasher
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 hash function an integer
Simple helper hash function
cosqa-train-19185
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 fix_missing ( df , col , name , na_dict ) : if is_numeric_dtype ( col ) : if pd . isnull ( col ) . sum ( ) or ( name in na_dict ) : df [ name + '_na' ] = pd . isnull ( col ) filler = na_dict [ name ] if name in na_dict else col . median ( ) df [ name ] = col . fillna ( filler ) na_dict [ name ] = filler return na_dict
1
python fill the nan values in the dataset using median values of column
Fill missing data in a column of df with the median and add a { name } _na column which specifies if the data was missing . Parameters : ----------- df : The data frame that will be changed . col : The column of data to fix by filling in missing data . name : The name of the new filled column in df . na_dict : A dictionary of values to create na s of and the value to insert . If name is not a key of na_dict the median will fill any missing data . Also if name is not a key of na_dict and there is no missing data in col then no { name } _na column is not created . Examples : --------- >>> df = pd . DataFrame ( { col1 : [ 1 np . NaN 3 ] col2 : [ 5 2 2 ] } ) >>> df col1 col2 0 1 5 1 nan 2 2 3 2 >>> fix_missing ( df df [ col1 ] col1 {} ) >>> df col1 col2 col1_na 0 1 5 False 1 2 2 True 2 3 2 False >>> df = pd . DataFrame ( { col1 : [ 1 np . NaN 3 ] col2 : [ 5 2 2 ] } ) >>> df col1 col2 0 1 5 1 nan 2 2 3 2 >>> fix_missing ( df df [ col2 ] col2 {} ) >>> df col1 col2 0 1 5 1 nan 2 2 3 2 >>> df = pd . DataFrame ( { col1 : [ 1 np . NaN 3 ] col2 : [ 5 2 2 ] } ) >>> df col1 col2 0 1 5 1 nan 2 2 3 2 >>> fix_missing ( df df [ col1 ] col1 { col1 : 500 } ) >>> df col1 col2 col1_na 0 1 5 False 1 500 2 True 2 3 2 False
cosqa-train-19186
def fix_missing(df, col, name, na_dict): """ Fill missing data in a column of df with the median, and add a {name}_na column which specifies if the data was missing. Parameters: ----------- df: The data frame that will be changed. col: The column of data to fix by filling in missing data. name: The name of the new filled column in df. na_dict: A dictionary of values to create na's of and the value to insert. If name is not a key of na_dict the median will fill any missing data. Also if name is not a key of na_dict and there is no missing data in col, then no {name}_na column is not created. Examples: --------- >>> df = pd.DataFrame({'col1' : [1, np.NaN, 3], 'col2' : [5, 2, 2]}) >>> df col1 col2 0 1 5 1 nan 2 2 3 2 >>> fix_missing(df, df['col1'], 'col1', {}) >>> df col1 col2 col1_na 0 1 5 False 1 2 2 True 2 3 2 False >>> df = pd.DataFrame({'col1' : [1, np.NaN, 3], 'col2' : [5, 2, 2]}) >>> df col1 col2 0 1 5 1 nan 2 2 3 2 >>> fix_missing(df, df['col2'], 'col2', {}) >>> df col1 col2 0 1 5 1 nan 2 2 3 2 >>> df = pd.DataFrame({'col1' : [1, np.NaN, 3], 'col2' : [5, 2, 2]}) >>> df col1 col2 0 1 5 1 nan 2 2 3 2 >>> fix_missing(df, df['col1'], 'col1', {'col1' : 500}) >>> df col1 col2 col1_na 0 1 5 False 1 500 2 True 2 3 2 False """ if is_numeric_dtype(col): if pd.isnull(col).sum() or (name in na_dict): df[name+'_na'] = pd.isnull(col) filler = na_dict[name] if name in na_dict else col.median() df[name] = col.fillna(filler) na_dict[name] = filler return na_dict
def indexes_equal ( a : Index , b : Index ) -> bool : return str ( a ) == str ( b )
1
if two strings are equal python
Are two indexes equal? Checks by comparing str () versions of them . ( AM UNSURE IF THIS IS ENOUGH . )
cosqa-train-19187
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 is_natural ( x ) : try : is_integer = int ( x ) == x except ( TypeError , ValueError ) : return False return is_integer and x >= 0
0
pythong if not an integer
A non - negative integer .
cosqa-train-19188
def is_natural(x): """A non-negative integer.""" try: is_integer = int(x) == x except (TypeError, ValueError): return False return is_integer and x >= 0
def listify ( a ) : if a is None : return [ ] elif not isinstance ( a , ( tuple , list , np . ndarray ) ) : return [ a ] return list ( a )
0
change an array into a list python
Convert a scalar a to a list and all iterables to list as well .
cosqa-train-19189
def listify(a): """ Convert a scalar ``a`` to a list and all iterables to list as well. Examples -------- >>> listify(0) [0] >>> listify([1,2,3]) [1, 2, 3] >>> listify('a') ['a'] >>> listify(np.array([1,2,3])) [1, 2, 3] >>> listify('string') ['string'] """ if a is None: return [] elif not isinstance(a, (tuple, list, np.ndarray)): return [a] return list(a)
def uppercase_chars ( string : any ) -> str : return '' . join ( [ c if c . isupper ( ) else '' for c in str ( string ) ] )
1
how to make letters uppercase in python skipping spaces
Return all ( and only ) the uppercase chars in the given string .
cosqa-train-19190
def uppercase_chars(string: any) -> str: """Return all (and only) the uppercase chars in the given string.""" return ''.join([c if c.isupper() else '' for c in str(string)])
def same ( * values ) : if not values : return True first , rest = values [ 0 ] , values [ 1 : ] return all ( value == first for value in rest )
1
python check equal sequence
Check if all values in a sequence are equal .
cosqa-train-19191
def same(*values): """ Check if all values in a sequence are equal. Returns True on empty sequences. Examples -------- >>> same(1, 1, 1, 1) True >>> same(1, 2, 1) False >>> same() True """ if not values: return True first, rest = values[0], values[1:] return all(value == first for value in rest)
def is_string_dtype ( arr_or_dtype ) : # TODO: gh-15585: consider making the checks stricter. def condition ( dtype ) : return dtype . kind in ( 'O' , 'S' , 'U' ) and not is_period_dtype ( dtype ) return _is_dtype ( arr_or_dtype , condition )
1
function for checking dtype in python
Check whether the provided array or dtype is of the string dtype .
cosqa-train-19192
def is_string_dtype(arr_or_dtype): """ Check whether the provided array or dtype is of the string dtype. Parameters ---------- arr_or_dtype : array-like The array or dtype to check. Returns ------- boolean Whether or not the array or dtype is of the string dtype. Examples -------- >>> is_string_dtype(str) True >>> is_string_dtype(object) True >>> is_string_dtype(int) False >>> >>> is_string_dtype(np.array(['a', 'b'])) True >>> is_string_dtype(pd.Series([1, 2])) False """ # TODO: gh-15585: consider making the checks stricter. def condition(dtype): return dtype.kind in ('O', 'S', 'U') and not is_period_dtype(dtype) return _is_dtype(arr_or_dtype, condition)
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 ) )
1
if isprime(n) is a prime return true else return false python
Check if n is a prime number
cosqa-train-19193
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 trunc ( obj , max , left = 0 ) : s = str ( obj ) s = s . replace ( '\n' , '|' ) if len ( s ) > max : if left : return '...' + s [ len ( s ) - max + 3 : ] else : return s [ : ( max - 3 ) ] + '...' else : return s
0
python, truncating a string by length
Convert obj to string eliminate newlines and truncate the string to max characters . If there are more characters in the string add ... to the string . With left = True the string can be truncated at the beginning .
cosqa-train-19194
def trunc(obj, max, left=0): """ Convert `obj` to string, eliminate newlines and truncate the string to `max` characters. If there are more characters in the string add ``...`` to the string. With `left=True`, the string can be truncated at the beginning. @note: Does not catch exceptions when converting `obj` to string with `str`. >>> trunc('This is a long text.', 8) This ... >>> trunc('This is a long text.', 8, left) ...text. """ s = str(obj) s = s.replace('\n', '|') if len(s) > max: if left: return '...'+s[len(s)-max+3:] else: return s[:(max-3)]+'...' else: return s
def decodebytes ( input ) : py_version = sys . version_info [ 0 ] if py_version >= 3 : return _decodebytes_py3 ( input ) return _decodebytes_py2 ( input )
1
python3 how to get the decode
Decode base64 string to byte array .
cosqa-train-19195
def decodebytes(input): """Decode base64 string to byte array.""" py_version = sys.version_info[0] if py_version >= 3: return _decodebytes_py3(input) return _decodebytes_py2(input)
def snake_to_camel ( s : str ) -> str : fragments = s . split ( '_' ) return fragments [ 0 ] + '' . join ( x . title ( ) for x in fragments [ 1 : ] )
0
capitalize each letter in python
Convert string from snake case to camel case .
cosqa-train-19196
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 uconcatenate ( arrs , axis = 0 ) : v = np . concatenate ( arrs , axis = axis ) v = _validate_numpy_wrapper_units ( v , arrs ) return v
0
python concatenate np array
Concatenate a sequence of arrays .
cosqa-train-19197
def uconcatenate(arrs, axis=0): """Concatenate a sequence of arrays. This wrapper around numpy.concatenate preserves units. All input arrays must have the same units. See the documentation of numpy.concatenate for full details. Examples -------- >>> from unyt import cm >>> A = [1, 2, 3]*cm >>> B = [2, 3, 4]*cm >>> uconcatenate((A, B)) unyt_array([1, 2, 3, 2, 3, 4], 'cm') """ v = np.concatenate(arrs, axis=axis) v = _validate_numpy_wrapper_units(v, arrs) return v
def mmap ( func , iterable ) : if sys . version_info [ 0 ] > 2 : return [ i for i in map ( func , iterable ) ] else : return map ( func , iterable )
0
python 3 replace for loop with map
Wrapper to make map () behave the same on Py2 and Py3 .
cosqa-train-19198
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 getIndex ( predicateFn : Callable [ [ T ] , bool ] , items : List [ T ] ) -> int : try : return next ( i for i , v in enumerate ( items ) if predicateFn ( v ) ) except StopIteration : return - 1
1
python index in list predicate
Finds the index of an item in list which satisfies predicate : param predicateFn : predicate function to run on items of list : param items : list of tuples : return : first index for which predicate function returns True
cosqa-train-19199
def getIndex(predicateFn: Callable[[T], bool], items: List[T]) -> int: """ Finds the index of an item in list, which satisfies predicate :param predicateFn: predicate function to run on items of list :param items: list of tuples :return: first index for which predicate function returns True """ try: return next(i for i, v in enumerate(items) if predicateFn(v)) except StopIteration: return -1