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 get_timezone ( ) -> Tuple [ datetime . tzinfo , str ] : dt = get_datetime_now ( ) . astimezone ( ) tzstr = dt . strftime ( "%z" ) tzstr = tzstr [ : - 2 ] + ":" + tzstr [ - 2 : ] return dt . tzinfo , tzstr
| 1 |
how to get time zone python
|
Discover the current time zone and it s standard string representation ( for source { d } ) .
|
cosqa-train-18200
|
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 __replace_all ( repls : dict , input : str ) -> str : return re . sub ( '|' . join ( re . escape ( key ) for key in repls . keys ( ) ) , lambda k : repls [ k . group ( 0 ) ] , input )
| 1 |
python string replace all
|
Replaces from a string ** input ** all the occurrences of some symbols according to mapping ** repls ** .
|
cosqa-train-18201
|
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 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
| 0 |
how to check if a line in a file has something in it python
|
Detects whether a line is present within a file .
|
cosqa-train-18202
|
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 strings_to_integers ( strings : Iterable [ str ] ) -> Iterable [ int ] : return strings_to_ ( strings , lambda x : int ( float ( x ) ) )
| 1 |
cast list of strings to int python
|
Convert a list of strings to a list of integers .
|
cosqa-train-18203
|
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 most_significant_bit ( lst : np . ndarray ) -> int : return np . argwhere ( np . asarray ( lst ) == 1 ) [ 0 ] [ 0 ]
| 1 |
python return largest even number in the arrary
|
A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s i . e . the first position where a 1 appears reading left to right .
|
cosqa-train-18204
|
def most_significant_bit(lst: np.ndarray) -> int:
"""
A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,
i.e. the first position where a 1 appears, reading left to right.
:param lst: a 1d array of 0s and 1s with at least one 1
:return: the first position in lst that a 1 appears
"""
return np.argwhere(np.asarray(lst) == 1)[0][0]
|
def to_dict ( self ) : if self . childCount ( ) > 0 : value = { } for index in range ( self . childCount ( ) ) : value . update ( self . child ( index ) . to_dict ( ) ) else : value = self . value return { self . name : value }
| 1 |
python tree default dict
|
cosqa-train-18205
|
def to_dict(self):
"""
Returns: the tree item as a dictionary
"""
if self.childCount() > 0:
value = {}
for index in range(self.childCount()):
value.update(self.child(index).to_dict())
else:
value = self.value
return {self.name: value}
|
|
def find_first_in_list ( txt : str , str_list : [ str ] ) -> int : # type: ignore start = len ( txt ) + 1 for item in str_list : if start > txt . find ( item ) > - 1 : start = txt . find ( item ) return start if len ( txt ) + 1 > start > - 1 else - 1
| 0 |
found the first occurrence of target string from strings python
|
Returns the index of the earliest occurence of an item from a list in a string
|
cosqa-train-18206
|
def find_first_in_list(txt: str, str_list: [str]) -> int: # type: ignore
"""
Returns the index of the earliest occurence of an item from a list in a string
Ex: find_first_in_list('foobar', ['bar', 'fin']) -> 3
"""
start = len(txt) + 1
for item in str_list:
if start > txt.find(item) > -1:
start = txt.find(item)
return start if len(txt) + 1 > start > -1 else -1
|
def same_network ( atree , btree ) -> bool : return same_hierarchy ( atree , btree ) and same_topology ( atree , btree )
| 0 |
python check a binary tree
|
True if given trees share the same structure of powernodes independently of ( power ) node names and same edge topology between ( power ) nodes .
|
cosqa-train-18207
|
def same_network(atree, btree) -> bool:
"""True if given trees share the same structure of powernodes,
independently of (power)node names,
and same edge topology between (power)nodes.
"""
return same_hierarchy(atree, btree) and same_topology(atree, btree)
|
def iterate_items ( dictish ) : if hasattr ( dictish , 'iteritems' ) : return dictish . iteritems ( ) if hasattr ( dictish , 'items' ) : return dictish . items ( ) return dictish
| 0 |
python iterator for dict
|
Return a consistent ( key value ) iterable on dict - like objects including lists of tuple pairs .
|
cosqa-train-18208
|
def iterate_items(dictish):
""" Return a consistent (key, value) iterable on dict-like objects,
including lists of tuple pairs.
Example:
>>> list(iterate_items({'a': 1}))
[('a', 1)]
>>> list(iterate_items([('a', 1), ('b', 2)]))
[('a', 1), ('b', 2)]
"""
if hasattr(dictish, 'iteritems'):
return dictish.iteritems()
if hasattr(dictish, 'items'):
return dictish.items()
return dictish
|
def most_frequent ( lst ) : lst = lst [ : ] highest_freq = 0 most_freq = None for val in unique ( lst ) : if lst . count ( val ) > highest_freq : most_freq = val highest_freq = lst . count ( val ) return most_freq
| 1 |
python most frequent in a list
|
Returns the item that appears most frequently in the given list .
|
cosqa-train-18209
|
def most_frequent(lst):
"""
Returns the item that appears most frequently in the given list.
"""
lst = lst[:]
highest_freq = 0
most_freq = None
for val in unique(lst):
if lst.count(val) > highest_freq:
most_freq = val
highest_freq = lst.count(val)
return most_freq
|
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' )
| 1 |
python numpy make empty array
|
Create an empty array with appropriate shape .
|
cosqa-train-18210
|
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 python_utc_datetime_to_sqlite_strftime_string ( value : datetime . datetime ) -> str : millisec_str = str ( round ( value . microsecond / 1000 ) ) . zfill ( 3 ) return value . strftime ( "%Y-%m-%d %H:%M:%S" ) + "." + millisec_str
| 0 |
python datetime format string with millisecond
|
Converts a Python datetime to a string literal compatible with SQLite including the millisecond field .
|
cosqa-train-18211
|
def python_utc_datetime_to_sqlite_strftime_string(
value: datetime.datetime) -> str:
"""
Converts a Python datetime to a string literal compatible with SQLite,
including the millisecond field.
"""
millisec_str = str(round(value.microsecond / 1000)).zfill(3)
return value.strftime("%Y-%m-%d %H:%M:%S") + "." + millisec_str
|
def debugTreePrint ( node , pfx = "->" ) : print pfx , node . item for c in node . children : debugTreePrint ( c , " " + pfx )
| 0 |
how to only print the leaf nodes in a tree python
|
Purely a debugging aid : Ascii - art picture of a tree descended from node
|
cosqa-train-18212
|
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 strtobytes ( input , encoding ) : py_version = sys . version_info [ 0 ] if py_version >= 3 : return _strtobytes_py3 ( input , encoding ) return _strtobytes_py2 ( input , encoding )
| 1 |
python 3 change string to a binary string
|
Take a str and transform it into a byte array .
|
cosqa-train-18213
|
def strtobytes(input, encoding):
"""Take a str and transform it into a byte array."""
py_version = sys.version_info[0]
if py_version >= 3:
return _strtobytes_py3(input, encoding)
return _strtobytes_py2(input, encoding)
|
def year ( date ) : try : fmt = '%m/%d/%Y' return datetime . strptime ( date , fmt ) . timetuple ( ) . tm_year except ValueError : return 0
| 1 |
return year from date python
|
Returns the year .
|
cosqa-train-18214
|
def year(date):
""" Returns the year.
:param date:
The string date with this format %m/%d/%Y
:type date:
String
:returns:
int
:example:
>>> year('05/1/2015')
2015
"""
try:
fmt = '%m/%d/%Y'
return datetime.strptime(date, fmt).timetuple().tm_year
except ValueError:
return 0
|
def drop_post ( self ) : post_index = self . version . find ( '.post' ) if post_index >= 0 : self . version = self . version [ : post_index ]
| 1 |
python remove postfix string
|
Remove . postXXXX postfix from version
|
cosqa-train-18215
|
def drop_post(self):
"""Remove .postXXXX postfix from version"""
post_index = self.version.find('.post')
if post_index >= 0:
self.version = self.version[:post_index]
|
def safe_pow ( base , exp ) : if exp > MAX_EXPONENT : raise RuntimeError ( "Invalid exponent, max exponent is {}" . format ( MAX_EXPONENT ) ) return base ** exp
| 0 |
raise a umber to a power function python
|
safe version of pow
|
cosqa-train-18216
|
def safe_pow(base, exp):
"""safe version of pow"""
if exp > MAX_EXPONENT:
raise RuntimeError("Invalid exponent, max exponent is {}".format(MAX_EXPONENT))
return base ** exp
|
def __remove_trailing_zeros ( self , collection ) : index = len ( collection ) - 1 while index >= 0 and collection [ index ] == 0 : index -= 1 return collection [ : index + 1 ]
| 0 |
python how to keep leading zeroes
|
Removes trailing zeroes from indexable collection of numbers
|
cosqa-train-18217
|
def __remove_trailing_zeros(self, collection):
"""Removes trailing zeroes from indexable collection of numbers"""
index = len(collection) - 1
while index >= 0 and collection[index] == 0:
index -= 1
return collection[:index + 1]
|
def callable_validator ( v : Any ) -> AnyCallable : if callable ( v ) : return v raise errors . CallableError ( value = v )
| 1 |
python how to ensure function return type
|
Perform a simple check if the value is callable .
|
cosqa-train-18218
|
def callable_validator(v: Any) -> AnyCallable:
"""
Perform a simple check if the value is callable.
Note: complete matching of argument type hints and return types is not performed
"""
if callable(v):
return v
raise errors.CallableError(value=v)
|
def astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( value = array , dtype = CTYPE ) return tensor
| 0 |
python structured array to tensorflow tensor
|
Covert numpy array to tensorflow tensor
|
cosqa-train-18219
|
def astensor(array: TensorLike) -> BKTensor:
"""Covert numpy array to tensorflow tensor"""
tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)
return tensor
|
def is_finite ( value : Any ) -> bool : return isinstance ( value , int ) or ( isinstance ( value , float ) and isfinite ( value ) )
| 1 |
python isfinite for all columns
|
Return true if a value is a finite number .
|
cosqa-train-18220
|
def is_finite(value: Any) -> bool:
"""Return true if a value is a finite number."""
return isinstance(value, int) or (isinstance(value, float) and isfinite(value))
|
def dotproduct ( X , Y ) : return sum ( [ x * y for x , y in zip ( X , Y ) ] )
| 0 |
python element wise product
|
Return the sum of the element - wise product of vectors x and y . >>> dotproduct ( [ 1 2 3 ] [ 1000 100 10 ] ) 1230
|
cosqa-train-18221
|
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 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 |
check if date is valid python
|
Retrun True if x is a valid YYYYMMDD date ; otherwise return False .
|
cosqa-train-18222
|
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 mkdir ( self , target_folder ) : self . printv ( "Making directory: %s" % target_folder ) self . k . key = re . sub ( r"^/|/$" , "" , target_folder ) + "/" self . k . set_contents_from_string ( '' ) self . k . close ( )
| 0 |
create folder in s3 bucket python
|
Create a folder on S3 .
|
cosqa-train-18223
|
def mkdir(self, target_folder):
"""
Create a folder on S3.
Examples
--------
>>> s3utils.mkdir("path/to/my_folder")
Making directory: path/to/my_folder
"""
self.printv("Making directory: %s" % target_folder)
self.k.key = re.sub(r"^/|/$", "", target_folder) + "/"
self.k.set_contents_from_string('')
self.k.close()
|
def fast_median ( a ) : a = checkma ( a ) #return scoreatpercentile(a.compressed(), 50) if a . count ( ) > 0 : out = np . percentile ( a . compressed ( ) , 50 ) else : out = np . ma . masked return out
| 0 |
median of array in python
|
Fast median operation for masked array using 50th - percentile
|
cosqa-train-18224
|
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 check_key ( self , key : str ) -> bool : keys = self . get_keys ( ) return key in keys
| 1 |
python how to verify if a key exist
|
Checks if key exists in datastore . True if yes False if no .
|
cosqa-train-18225
|
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 remove_prefix ( text , prefix ) : null , prefix , rest = text . rpartition ( prefix ) return rest
| 0 |
python how to remove from a certain word onward with prefix
|
Remove the prefix from the text if it exists .
|
cosqa-train-18226
|
def remove_prefix(text, prefix):
"""
Remove the prefix from the text if it exists.
>>> remove_prefix('underwhelming performance', 'underwhelming ')
'performance'
>>> remove_prefix('something special', 'sample')
'something special'
"""
null, prefix, rest = text.rpartition(prefix)
return rest
|
def local_machine_uuid ( ) : result = subprocess . check_output ( 'hal-get-property --udi ' '/org/freedesktop/Hal/devices/computer ' '--key system.hardware.uuid' . split ( ) ) . strip ( ) return uuid . UUID ( hex = result )
| 0 |
python get computer uuid
|
Return local machine unique identifier .
|
cosqa-train-18227
|
def local_machine_uuid():
"""Return local machine unique identifier.
>>> uuid = local_machine_uuid()
"""
result = subprocess.check_output(
'hal-get-property --udi '
'/org/freedesktop/Hal/devices/computer '
'--key system.hardware.uuid'.split()
).strip()
return uuid.UUID(hex=result)
|
def 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 |
in python how to check if my path given is that of a file or is a directory
|
Verifies that a string path actually exists and is a file
|
cosqa-train-18228
|
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 process_literal_param ( self , value : Optional [ List [ int ] ] , dialect : Dialect ) -> str : retval = self . _intlist_to_dbstr ( value ) return retval
| 0 |
sqlite change int to string python
|
Convert things on the way from Python to the database .
|
cosqa-train-18229
|
def process_literal_param(self, value: Optional[List[int]],
dialect: Dialect) -> str:
"""Convert things on the way from Python to the database."""
retval = self._intlist_to_dbstr(value)
return retval
|
def find_first ( pattern : str , path : str ) -> str : try : return find ( pattern , path ) [ 0 ] except IndexError : log . critical ( '''Couldn't find "{}" in "{}"''' , pattern , path ) raise
| 0 |
python get the first file in a folder
|
Finds first file in path whose filename matches pattern ( via : func : fnmatch . fnmatch ) or raises : exc : IndexError .
|
cosqa-train-18230
|
def find_first(pattern: str, path: str) -> str:
"""
Finds first file in ``path`` whose filename matches ``pattern`` (via
:func:`fnmatch.fnmatch`), or raises :exc:`IndexError`.
"""
try:
return find(pattern, path)[0]
except IndexError:
log.critical('''Couldn't find "{}" in "{}"''', pattern, path)
raise
|
def issuperset ( self , items ) : return all ( _compat . map ( self . _seen . __contains__ , items ) )
| 1 |
python set contains multiple items
|
Return whether this collection contains all items .
|
cosqa-train-18231
|
def issuperset(self, items):
"""Return whether this collection contains all items.
>>> Unique(['spam', 'eggs']).issuperset(['spam', 'spam', 'spam'])
True
"""
return all(_compat.map(self._seen.__contains__, items))
|
def is_any_type_set ( sett : Set [ Type ] ) -> bool : return len ( sett ) == 1 and is_any_type ( min ( sett ) )
| 0 |
check if a set contains one value python
|
Helper method to check if a set of types is the { AnyObject } singleton
|
cosqa-train-18232
|
def is_any_type_set(sett: Set[Type]) -> bool:
"""
Helper method to check if a set of types is the {AnyObject} singleton
:param sett:
:return:
"""
return len(sett) == 1 and is_any_type(min(sett))
|
def _short_repr ( obj ) : stringified = pprint . saferepr ( obj ) if len ( stringified ) > 200 : return '%s... (%d bytes)' % ( stringified [ : 200 ] , len ( stringified ) ) return stringified
| 1 |
python pprint string according to length
|
Helper function returns a truncated repr () of an object .
|
cosqa-train-18233
|
def _short_repr(obj):
"""Helper function returns a truncated repr() of an object."""
stringified = pprint.saferepr(obj)
if len(stringified) > 200:
return '%s... (%d bytes)' % (stringified[:200], len(stringified))
return stringified
|
def rmglob ( pattern : str ) -> None : for f in glob . glob ( pattern ) : os . remove ( f )
| 1 |
delete files in python using glob
|
Deletes all files whose filename matches the glob pattern ( via : func : glob . glob ) .
|
cosqa-train-18234
|
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 convert_bytes_to_ints ( in_bytes , num ) : dt = numpy . dtype ( '>i' + str ( num ) ) return numpy . frombuffer ( in_bytes , dt )
| 0 |
python array of bytes from integers
|
Convert a byte array into an integer array . The number of bytes forming an integer is defined by num
|
cosqa-train-18235
|
def convert_bytes_to_ints(in_bytes, num):
"""Convert a byte array into an integer array. The number of bytes forming an integer
is defined by num
:param in_bytes: the input bytes
:param num: the number of bytes per int
:return the integer array"""
dt = numpy.dtype('>i' + str(num))
return numpy.frombuffer(in_bytes, dt)
|
def _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' )
| 1 |
python create empty array without numpy
|
Create an empty array with appropriate shape .
|
cosqa-train-18236
|
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 union ( cls , * sets ) : import utool as ut lists_ = ut . flatten ( [ list ( s ) for s in sets ] ) return cls ( lists_ )
| 0 |
how to combine sets in python
|
>>> from utool . util_set import * # NOQA
|
cosqa-train-18237
|
def union(cls, *sets):
"""
>>> from utool.util_set import * # NOQA
"""
import utool as ut
lists_ = ut.flatten([list(s) for s in sets])
return cls(lists_)
|
def _cleanup ( path : str ) -> None : if os . path . isdir ( path ) : shutil . rmtree ( path )
| 0 |
python clean up temporary files
|
Cleanup temporary directory .
|
cosqa-train-18238
|
def _cleanup(path: str) -> None:
"""Cleanup temporary directory."""
if os.path.isdir(path):
shutil.rmtree(path)
|
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 |
check if column has null value python
|
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-18239
|
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 __rmatmul__ ( self , other ) : return self . T . dot ( np . transpose ( other ) ) . T
| 1 |
python matrix dot multiplication
|
Matrix multiplication using binary
|
cosqa-train-18240
|
def __rmatmul__(self, other):
"""
Matrix multiplication using binary `@` operator in Python>=3.5.
"""
return self.T.dot(np.transpose(other)).T
|
def running_containers ( name_filter : str ) -> List [ str ] : return [ container . short_id for container in docker_client . containers . list ( filters = { "name" : name_filter } ) ]
| 0 |
python get docker container name
|
: raises docker . exceptions . APIError
|
cosqa-train-18241
|
def running_containers(name_filter: str) -> List[str]:
"""
:raises docker.exceptions.APIError
"""
return [container.short_id for container in
docker_client.containers.list(filters={"name": name_filter})]
|
def file_lines ( bblfile : str ) -> iter : with open ( bblfile ) as fd : yield from ( line . rstrip ( ) for line in fd if line . rstrip ( ) )
| 0 |
python iterator file lines
|
Yield lines found in given file
|
cosqa-train-18242
|
def file_lines(bblfile:str) -> iter:
"""Yield lines found in given file"""
with open(bblfile) as fd:
yield from (line.rstrip() for line in fd if line.rstrip())
|
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 |
how to check column value is null python
|
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-18243
|
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 uppercase_chars ( string : any ) -> str : return '' . join ( [ c if c . isupper ( ) else '' for c in str ( string ) ] )
| 0 |
python finding uppercase strings
|
Return all ( and only ) the uppercase chars in the given string .
|
cosqa-train-18244
|
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 zfill ( x , width ) : if not isinstance ( x , basestring ) : x = repr ( x ) return x . zfill ( width )
| 1 |
pad zeros python string
|
zfill ( x width ) - > string
|
cosqa-train-18245
|
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 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 argparse example call function
|
docstring for argparse
|
cosqa-train-18246
|
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 snake_to_camel ( s : str ) -> str : fragments = s . split ( '_' ) return fragments [ 0 ] + '' . join ( x . title ( ) for x in fragments [ 1 : ] )
| 1 |
how to capitalize the all letter in python
|
Convert string from snake case to camel case .
|
cosqa-train-18247
|
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 valid_substitution ( strlen , index ) : values = index [ 0 ] return all ( [ strlen > i for i in values ] )
| 0 |
check exact substring python
|
skip performing substitutions that are outside the bounds of the string
|
cosqa-train-18248
|
def valid_substitution(strlen, index):
"""
skip performing substitutions that are outside the bounds of the string
"""
values = index[0]
return all([strlen > i for i in values])
|
def recall_score ( y_true , y_pred , average = 'micro' , suffix = False ) : true_entities = set ( get_entities ( y_true , suffix ) ) pred_entities = set ( get_entities ( y_pred , suffix ) ) nb_correct = len ( true_entities & pred_entities ) nb_true = len ( true_entities ) score = nb_correct / nb_true if nb_true > 0 else 0 return score
| 0 |
python accuracy recall f1
|
Compute the recall .
|
cosqa-train-18249
|
def recall_score(y_true, y_pred, average='micro', suffix=False):
"""Compute the recall.
The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of
true positives and ``fn`` the number of false negatives. The recall is
intuitively the ability of the classifier to find all the positive samples.
The best value is 1 and the worst value is 0.
Args:
y_true : 2d array. Ground truth (correct) target values.
y_pred : 2d array. Estimated targets as returned by a tagger.
Returns:
score : float.
Example:
>>> from seqeval.metrics import recall_score
>>> y_true = [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> y_pred = [['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> recall_score(y_true, y_pred)
0.50
"""
true_entities = set(get_entities(y_true, suffix))
pred_entities = set(get_entities(y_pred, suffix))
nb_correct = len(true_entities & pred_entities)
nb_true = len(true_entities)
score = nb_correct / nb_true if nb_true > 0 else 0
return score
|
def default_parser ( ) -> argparse . ArgumentParser : parser = argparse . ArgumentParser ( prog = CONSOLE_SCRIPT , formatter_class = argparse . ArgumentDefaultsHelpFormatter , ) build_parser ( parser ) return parser
| 1 |
argparse python namespace object has no attribute 'help'
|
Create a parser for CLI arguments and options .
|
cosqa-train-18250
|
def default_parser() -> argparse.ArgumentParser:
"""Create a parser for CLI arguments and options."""
parser = argparse.ArgumentParser(
prog=CONSOLE_SCRIPT,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
build_parser(parser)
return parser
|
def pack_bits ( longbits ) : byte = longbits & ( 0x0101010101010101 ) byte = ( byte | ( byte >> 7 ) ) & ( 0x0003000300030003 ) byte = ( byte | ( byte >> 14 ) ) & ( 0x0000000f0000000f ) byte = ( byte | ( byte >> 28 ) ) & ( 0x00000000000000ff ) return byte
| 1 |
extract bits of large numbers python
|
Crunch a 64 - bit int ( 8 bool bytes ) into a bitfield .
|
cosqa-train-18251
|
def pack_bits( longbits ):
"""Crunch a 64-bit int (8 bool bytes) into a bitfield."""
byte = longbits & (0x0101010101010101)
byte = (byte | (byte>>7)) & (0x0003000300030003)
byte = (byte | (byte>>14)) & (0x0000000f0000000f)
byte = (byte | (byte>>28)) & (0x00000000000000ff)
return byte
|
def try_cast_int ( s ) : try : temp = re . findall ( '\d' , str ( s ) ) temp = '' . join ( temp ) return int ( temp ) except : return s
| 0 |
cast str to integer python
|
( str ) - > int All the digits in a given string are concatenated and converted into a single number .
|
cosqa-train-18252
|
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 bfx ( value , msb , lsb ) : mask = bitmask ( ( msb , lsb ) ) return ( value & mask ) >> lsb
| 0 |
bit wise & in python
|
!
|
cosqa-train-18253
|
def bfx(value, msb, lsb):
"""! @brief Extract a value from a bitfield."""
mask = bitmask((msb, lsb))
return (value & mask) >> lsb
|
def callable_validator ( v : Any ) -> AnyCallable : if callable ( v ) : return v raise errors . CallableError ( value = v )
| 1 |
python callable arg must be a list
|
Perform a simple check if the value is callable .
|
cosqa-train-18254
|
def callable_validator(v: Any) -> AnyCallable:
"""
Perform a simple check if the value is callable.
Note: complete matching of argument type hints and return types is not performed
"""
if callable(v):
return v
raise errors.CallableError(value=v)
|
def _find_conda ( ) : if 'CONDA_EXE' in os . environ : conda = os . environ [ 'CONDA_EXE' ] else : conda = util . which ( 'conda' ) return conda
| 1 |
vs code python conda not found
|
Find the conda executable robustly across conda versions .
|
cosqa-train-18255
|
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 inverted_dict ( d ) : return dict ( ( force_hashable ( v ) , k ) for ( k , v ) in viewitems ( dict ( d ) ) )
| 1 |
inverse key and value in dictionary in python
|
Return a dict with swapped keys and values
|
cosqa-train-18256
|
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 is_sqlatype_integer ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . Integer )
| 0 |
identify type of python column
|
Is the SQLAlchemy column type an integer type?
|
cosqa-train-18257
|
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 flatten_list ( l : List [ list ] ) -> list : return [ v for inner_l in l for v in inner_l ]
| 0 |
to flatten a list consisting of individual values as well as list of lists in python
|
takes a list of lists l and returns a flat list
|
cosqa-train-18258
|
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 truncate ( value : Decimal , n_digits : int ) -> Decimal : return Decimal ( math . trunc ( value * ( 10 ** n_digits ) ) ) / ( 10 ** n_digits )
| 0 |
how to truncate decimals python's
|
Truncates a value to a number of decimals places
|
cosqa-train-18259
|
def truncate(value: Decimal, n_digits: int) -> Decimal:
"""Truncates a value to a number of decimals places"""
return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)
|
def Exit ( msg , code = 1 ) : print >> sys . stderr , msg sys . exit ( code )
| 1 |
call function with exit in python
|
Exit execution with return code and message : param msg : Message displayed prior to exit : param code : code returned upon exiting
|
cosqa-train-18260
|
def Exit(msg, code=1):
"""Exit execution with return code and message
:param msg: Message displayed prior to exit
:param code: code returned upon exiting
"""
print >> sys.stderr, msg
sys.exit(code)
|
def cpu_count ( ) -> int : if multiprocessing is None : return 1 try : return multiprocessing . cpu_count ( ) except NotImplementedError : pass try : return os . sysconf ( "SC_NPROCESSORS_CONF" ) except ( AttributeError , ValueError ) : pass gen_log . error ( "Could not detect number of processors; assuming 1" ) return 1
| 1 |
python get cpu cores in a cluster
|
Returns the number of processors on this machine .
|
cosqa-train-18261
|
def cpu_count() -> int:
"""Returns the number of processors on this machine."""
if multiprocessing is None:
return 1
try:
return multiprocessing.cpu_count()
except NotImplementedError:
pass
try:
return os.sysconf("SC_NPROCESSORS_CONF")
except (AttributeError, ValueError):
pass
gen_log.error("Could not detect number of processors; assuming 1")
return 1
|
def flatten_list ( x : List [ Any ] ) -> List [ Any ] : # noqa return [ item for sublist in x for item in sublist ]
| 0 |
flatten list of lists python into list
|
Converts a list of lists into a flat list . Args : x : list of lists
|
cosqa-train-18262
|
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 _gauss ( mean : int , sigma : int ) -> int : return int ( random . gauss ( mean , sigma ) )
| 0 |
function in python to generate random numbers for a given average
|
Creates a variation from a base value
|
cosqa-train-18263
|
def _gauss(mean: int, sigma: int) -> int:
"""
Creates a variation from a base value
Args:
mean: base value
sigma: gaussian sigma
Returns: random value
"""
return int(random.gauss(mean, sigma))
|
def add_mark_at ( string , index , mark ) : if index == - 1 : return string # Python can handle the case which index is out of range of given string return string [ : index ] + add_mark_char ( string [ index ] , mark ) + string [ index + 1 : ]
| 0 |
add marks to string in python
|
Add mark to the index - th character of the given string . Return the new string after applying change . Notice : index > 0
|
cosqa-train-18264
|
def add_mark_at(string, index, mark):
"""
Add mark to the index-th character of the given string. Return the new string after applying change.
Notice: index > 0
"""
if index == -1:
return string
# Python can handle the case which index is out of range of given string
return string[:index] + add_mark_char(string[index], mark) + string[index+1:]
|
def stretch ( iterable , n = 2 ) : times = range ( n ) for item in iterable : for i in times : yield item
| 1 |
python take n elements from iterator
|
r Repeat each item in iterable n times .
|
cosqa-train-18265
|
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 is_up_to_date ( outfile , basedatetime ) : # type: (AnyStr, datetime) -> bool if os . path . exists ( outfile ) : if os . path . getmtime ( outfile ) >= basedatetime : return True return False
| 1 |
python how to check if file older than
|
Return true if outfile exists and is no older than base datetime .
|
cosqa-train-18266
|
def is_up_to_date(outfile, basedatetime):
# type: (AnyStr, datetime) -> bool
"""Return true if outfile exists and is no older than base datetime."""
if os.path.exists(outfile):
if os.path.getmtime(outfile) >= basedatetime:
return True
return False
|
def _check_whitespace ( string ) : if string . count ( ' ' ) + string . count ( '\t' ) + string . count ( '\n' ) > 0 : raise ValueError ( INSTRUCTION_HAS_WHITESPACE )
| 0 |
python check if whitespace
|
Make sure thre is no whitespace in the given string . Will raise a ValueError if whitespace is detected
|
cosqa-train-18267
|
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 first_location_of_maximum ( x ) : if not isinstance ( x , ( np . ndarray , pd . Series ) ) : x = np . asarray ( x ) return np . argmax ( x ) / len ( x ) if len ( x ) > 0 else np . NaN
| 0 |
python data frame show index number of the max value of the vector
|
Returns the first location of the maximum value of x . The position is calculated relatively to the length of x .
|
cosqa-train-18268
|
def first_location_of_maximum(x):
"""
Returns the first location of the maximum value of x.
The position is calculated relatively to the length of x.
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
if not isinstance(x, (np.ndarray, pd.Series)):
x = np.asarray(x)
return np.argmax(x) / len(x) if len(x) > 0 else np.NaN
|
def _kbhit_unix ( ) -> bool : dr , dw , de = select . select ( [ sys . stdin ] , [ ] , [ ] , 0 ) return dr != [ ]
| 1 |
python detect key press do not block
|
Under UNIX : is a keystroke available?
|
cosqa-train-18269
|
def _kbhit_unix() -> bool:
"""
Under UNIX: is a keystroke available?
"""
dr, dw, de = select.select([sys.stdin], [], [], 0)
return dr != []
|
def get_last_weekday_in_month ( year , month , weekday ) : day = date ( year , month , monthrange ( year , month ) [ 1 ] ) while True : if day . weekday ( ) == weekday : break day = day - timedelta ( days = 1 ) return day
| 1 |
python get month last day
|
Get the last weekday in a given month . e . g :
|
cosqa-train-18270
|
def get_last_weekday_in_month(year, month, weekday):
"""Get the last weekday in a given month. e.g:
>>> # the last monday in Jan 2013
>>> Calendar.get_last_weekday_in_month(2013, 1, MON)
datetime.date(2013, 1, 28)
"""
day = date(year, month, monthrange(year, month)[1])
while True:
if day.weekday() == weekday:
break
day = day - timedelta(days=1)
return day
|
def camel_to_snake_case ( string ) : s = _1 . sub ( r'\1_\2' , string ) return _2 . sub ( r'\1_\2' , s ) . lower ( )
| 1 |
how to permanently change a string from upper to lower case in python
|
Converts string presented in camel case to snake case .
|
cosqa-train-18271
|
def camel_to_snake_case(string):
"""Converts 'string' presented in camel case to snake case.
e.g.: CamelCase => snake_case
"""
s = _1.sub(r'\1_\2', string)
return _2.sub(r'\1_\2', s).lower()
|
def get_timezone ( ) -> Tuple [ datetime . tzinfo , str ] : dt = get_datetime_now ( ) . astimezone ( ) tzstr = dt . strftime ( "%z" ) tzstr = tzstr [ : - 2 ] + ":" + tzstr [ - 2 : ] return dt . tzinfo , tzstr
| 1 |
how to get from datetime object about current time zone in python
|
Discover the current time zone and it s standard string representation ( for source { d } ) .
|
cosqa-train-18272
|
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 bulk_load_docs ( es , docs ) : chunk_size = 200 try : results = elasticsearch . helpers . bulk ( es , docs , chunk_size = chunk_size ) log . debug ( f"Elasticsearch documents loaded: {results[0]}" ) # elasticsearch.helpers.parallel_bulk(es, terms, chunk_size=chunk_size, thread_count=4) if len ( results [ 1 ] ) > 0 : log . error ( "Bulk load errors {}" . format ( results ) ) except elasticsearch . ElasticsearchException as e : log . error ( "Indexing error: {}\n" . format ( e ) )
| 0 |
elasticsearch bulk python faster
|
Bulk load docs
|
cosqa-train-18273
|
def bulk_load_docs(es, docs):
"""Bulk load docs
Args:
es: elasticsearch handle
docs: Iterator of doc objects - includes index_name
"""
chunk_size = 200
try:
results = elasticsearch.helpers.bulk(es, docs, chunk_size=chunk_size)
log.debug(f"Elasticsearch documents loaded: {results[0]}")
# elasticsearch.helpers.parallel_bulk(es, terms, chunk_size=chunk_size, thread_count=4)
if len(results[1]) > 0:
log.error("Bulk load errors {}".format(results))
except elasticsearch.ElasticsearchException as e:
log.error("Indexing error: {}\n".format(e))
|
def inject_nulls ( data : Mapping , field_names ) -> dict : record = dict ( ) for field in field_names : record [ field ] = data . get ( field , None ) return record
| 1 |
replace none with blank python dict
|
Insert None as value for missing fields .
|
cosqa-train-18274
|
def inject_nulls(data: Mapping, field_names) -> dict:
"""Insert None as value for missing fields."""
record = dict()
for field in field_names:
record[field] = data.get(field, None)
return record
|
def _check_whitespace ( string ) : if string . count ( ' ' ) + string . count ( '\t' ) + string . count ( '\n' ) > 0 : raise ValueError ( INSTRUCTION_HAS_WHITESPACE )
| 1 |
python checking string for whitespace
|
Make sure thre is no whitespace in the given string . Will raise a ValueError if whitespace is detected
|
cosqa-train-18275
|
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 string ( value ) -> str : return system_json . dumps ( Json ( value ) . safe_object ( ) , ensure_ascii = False )
| 0 |
python string to javascript string
|
string dict / object / value to JSON
|
cosqa-train-18276
|
def string(value) -> str:
""" string dict/object/value to JSON """
return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)
|
def do_quit ( self , _ : argparse . Namespace ) -> bool : self . _should_quit = True return self . _STOP_AND_EXIT
| 0 |
python dont imeditalte terminate
|
Exit this application
|
cosqa-train-18277
|
def do_quit(self, _: argparse.Namespace) -> bool:
"""Exit this application"""
self._should_quit = True
return self._STOP_AND_EXIT
|
def get_column_names ( engine : Engine , tablename : str ) -> List [ str ] : return [ info . name for info in gen_columns_info ( engine , tablename ) ]
| 1 |
how to get all columns names in python
|
Get all the database column names for the specified table .
|
cosqa-train-18278
|
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 SGT ( self , a , b ) : # http://gavwood.com/paper.pdf s0 , s1 = to_signed ( a ) , to_signed ( b ) return Operators . ITEBV ( 256 , s0 > s1 , 1 , 0 )
| 0 |
greater than or equal sign python
|
Signed greater - than comparison
|
cosqa-train-18279
|
def SGT(self, a, b):
"""Signed greater-than comparison"""
# http://gavwood.com/paper.pdf
s0, s1 = to_signed(a), to_signed(b)
return Operators.ITEBV(256, s0 > s1, 1, 0)
|
def get_keys_of_max_n ( dict_obj , n ) : return sorted ( [ item [ 0 ] for item in sorted ( dict_obj . items ( ) , key = lambda item : item [ 1 ] , reverse = True ) [ : n ] ] )
| 1 |
how to get top 5 values from dictionaty in python
|
Returns the keys that maps to the top n max values in the given dict .
|
cosqa-train-18280
|
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 rank ( tensor : BKTensor ) -> int : if isinstance ( tensor , np . ndarray ) : return len ( tensor . shape ) return len ( tensor [ 0 ] . size ( ) )
| 1 |
python get size of the matrix
|
Return the number of dimensions of a tensor
|
cosqa-train-18281
|
def rank(tensor: BKTensor) -> int:
"""Return the number of dimensions of a tensor"""
if isinstance(tensor, np.ndarray):
return len(tensor.shape)
return len(tensor[0].size())
|
def 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 |
determine if a number is a prime factor python
|
Check if n is a prime number
|
cosqa-train-18282
|
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 has_key ( cls , * args ) : key = args if len ( args ) > 1 else args [ 0 ] return key in cls . _instances
| 0 |
python check not existing key
|
Check whether flyweight object with specified key has already been created .
|
cosqa-train-18283
|
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 issubset ( self , other ) : if len ( self ) > len ( other ) : # Fast check for obvious cases return False return all ( item in other for item in self )
| 0 |
how to test if a set is a subset of another set python
|
Report whether another set contains this set .
|
cosqa-train-18284
|
def issubset(self, other):
"""
Report whether another set contains this set.
Example:
>>> OrderedSet([1, 2, 3]).issubset({1, 2})
False
>>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4})
True
>>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5})
False
"""
if len(self) > len(other): # Fast check for obvious cases
return False
return all(item in other for item in self)
|
def after_third_friday ( day = None ) : day = day if day is not None else datetime . datetime . now ( ) now = day . replace ( day = 1 , hour = 16 , minute = 0 , second = 0 , microsecond = 0 ) now += relativedelta . relativedelta ( weeks = 2 , weekday = relativedelta . FR ) return day > now
| 1 |
python third friday date
|
check if day is after month s 3rd friday
|
cosqa-train-18285
|
def after_third_friday(day=None):
""" check if day is after month's 3rd friday """
day = day if day is not None else datetime.datetime.now()
now = day.replace(day=1, hour=16, minute=0, second=0, microsecond=0)
now += relativedelta.relativedelta(weeks=2, weekday=relativedelta.FR)
return day > now
|
def _request ( self , method : str , endpoint : str , params : dict = None , data : dict = None , headers : dict = None ) -> dict :
| 0 |
python api call header and body
|
HTTP request method of interface implementation .
|
cosqa-train-18286
|
def _request(self, method: str, endpoint: str, params: dict = None, data: dict = None, headers: dict = None) -> dict:
"""HTTP request method of interface implementation."""
|
def _write_json ( obj , path ) : # type: (object, str) -> None with open ( path , 'w' ) as f : json . dump ( obj , f )
| 0 |
save an object to file python
|
Writes a serializeable object as a JSON file
|
cosqa-train-18287
|
def _write_json(obj, path): # type: (object, str) -> None
"""Writes a serializeable object as a JSON file"""
with open(path, 'w') as f:
json.dump(obj, f)
|
def flatten_list ( x : List [ Any ] ) -> List [ Any ] : # noqa return [ item for sublist in x for item in sublist ]
| 0 |
flatten python list of lists
|
Converts a list of lists into a flat list . Args : x : list of lists
|
cosqa-train-18288
|
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 get_last_weekday_in_month ( year , month , weekday ) : day = date ( year , month , monthrange ( year , month ) [ 1 ] ) while True : if day . weekday ( ) == weekday : break day = day - timedelta ( days = 1 ) return day
| 0 |
python calendar month how to get last day of month
|
Get the last weekday in a given month . e . g :
|
cosqa-train-18289
|
def get_last_weekday_in_month(year, month, weekday):
"""Get the last weekday in a given month. e.g:
>>> # the last monday in Jan 2013
>>> Calendar.get_last_weekday_in_month(2013, 1, MON)
datetime.date(2013, 1, 28)
"""
day = date(year, month, monthrange(year, month)[1])
while True:
if day.weekday() == weekday:
break
day = day - timedelta(days=1)
return day
|
def 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
| 1 |
python max argmax key lambda
|
>>> argmax ( [ 4 2 - 5 ] ) 0 >>> argmax ( [ 4 2 - 5 ] key = abs ) 2 >>> argmax ( [ 4 2 - 5 ] key = abs both = True ) ( 2 5 )
|
cosqa-train-18290
|
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 get_system_flags ( ) -> FrozenSet [ Flag ] : return frozenset ( { Seen , Recent , Deleted , Flagged , Answered , Draft } )
| 0 |
python return a set
|
Return the set of implemented system flags .
|
cosqa-train-18291
|
def get_system_flags() -> FrozenSet[Flag]:
"""Return the set of implemented system flags."""
return frozenset({Seen, Recent, Deleted, Flagged, Answered, Draft})
|
def list_to_str ( list , separator = ',' ) : list = [ str ( x ) for x in list ] return separator . join ( list )
| 1 |
how go from list to string python
|
>>> list = [ 0 0 7 ] >>> list_to_str ( list ) 0 0 7
|
cosqa-train-18292
|
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 to_bytes ( data : Any ) -> bytearray : # noqa if isinstance ( data , int ) : return bytearray ( [ data ] ) return bytearray ( data , encoding = 'latin-1' )
| 1 |
string to bytes ascii 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-18293
|
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 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 get index for element in list with condition
|
Finds the index of an item in list which satisfies predicate : param predicateFn : predicate function to run on items of list : param items : list of tuples : return : first index for which predicate function returns True
|
cosqa-train-18294
|
def getIndex(predicateFn: Callable[[T], bool], items: List[T]) -> int:
"""
Finds the index of an item in list, which satisfies predicate
:param predicateFn: predicate function to run on items of list
:param items: list of tuples
:return: first index for which predicate function returns True
"""
try:
return next(i for i, v in enumerate(items) if predicateFn(v))
except StopIteration:
return -1
|
def mmap ( func , iterable ) : if sys . version_info [ 0 ] > 2 : return [ i for i in map ( func , iterable ) ] else : return map ( func , iterable )
| 0 |
python map instead of for loop
|
Wrapper to make map () behave the same on Py2 and Py3 .
|
cosqa-train-18295
|
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 Exit ( msg , code = 1 ) : print >> sys . stderr , msg sys . exit ( code )
| 0 |
python how to exit a code
|
Exit execution with return code and message : param msg : Message displayed prior to exit : param code : code returned upon exiting
|
cosqa-train-18296
|
def Exit(msg, code=1):
"""Exit execution with return code and message
:param msg: Message displayed prior to exit
:param code: code returned upon exiting
"""
print >> sys.stderr, msg
sys.exit(code)
|
def hex_to_int ( value ) : if version_info . major >= 3 : return int . from_bytes ( value , "big" ) return int ( value . encode ( "hex" ) , 16 )
| 1 |
python 4 bytes to int32
|
Convert hex string like \ x0A \ xE3 to 2787 .
|
cosqa-train-18297
|
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 timestamp_with_tzinfo ( dt ) : utc = tzutc ( ) if dt . tzinfo : dt = dt . astimezone ( utc ) . replace ( tzinfo = None ) return dt . isoformat ( ) + 'Z'
| 1 |
isoformat python datetitme timezone
|
Serialize a date / time value into an ISO8601 text representation adjusted ( if needed ) to UTC timezone .
|
cosqa-train-18298
|
def timestamp_with_tzinfo(dt):
"""
Serialize a date/time value into an ISO8601 text representation
adjusted (if needed) to UTC timezone.
For instance:
>>> serialize_date(datetime(2012, 4, 10, 22, 38, 20, 604391))
'2012-04-10T22:38:20.604391Z'
"""
utc = tzutc()
if dt.tzinfo:
dt = dt.astimezone(utc).replace(tzinfo=None)
return dt.isoformat() + 'Z'
|
def is_unicode ( string ) : str_type = str ( type ( string ) ) if str_type . find ( 'str' ) > 0 or str_type . find ( 'unicode' ) > 0 : return True return False
| 0 |
python check char type
|
Validates that the object itself is some kinda string
|
cosqa-train-18299
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.