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 drop_column ( self , tablename : str , fieldname : str ) -> int : sql = "ALTER TABLE {} DROP COLUMN {}" . format ( tablename , fieldname ) log . info ( sql ) return self . db_exec_literal ( sql )
| 1 |
delete a column in python db
|
Drops ( deletes ) a column from an existing table .
|
cosqa-train-18500
|
def drop_column(self, tablename: str, fieldname: str) -> int:
"""Drops (deletes) a column from an existing table."""
sql = "ALTER TABLE {} DROP COLUMN {}".format(tablename, fieldname)
log.info(sql)
return self.db_exec_literal(sql)
|
async def executemany ( self , sql : str , parameters : Iterable [ Iterable [ Any ] ] ) -> None : await self . _execute ( self . _cursor . executemany , sql , parameters )
| 1 |
python mssql send query that uses in tuple
|
Execute the given multiquery .
|
cosqa-train-18501
|
async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None:
"""Execute the given multiquery."""
await self._execute(self._cursor.executemany, sql, parameters)
|
def iter_lines ( file_like : Iterable [ str ] ) -> Generator [ str , None , None ] : for line in file_like : line = line . rstrip ( '\r\n' ) if line : yield line
| 1 |
how to have python skip empty lines
|
Helper for iterating only nonempty lines without line breaks
|
cosqa-train-18502
|
def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:
""" Helper for iterating only nonempty lines without line breaks"""
for line in file_like:
line = line.rstrip('\r\n')
if line:
yield line
|
def output_dir ( self , * args ) -> str : return os . path . join ( self . project_dir , 'output' , * args )
| 1 |
how to define output path in python
|
Directory where to store output
|
cosqa-train-18503
|
def output_dir(self, *args) -> str:
""" Directory where to store output """
return os.path.join(self.project_dir, 'output', *args)
|
def astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( value = array , dtype = CTYPE ) return tensor
| 0 |
python array to tensor
|
Covert numpy array to tensorflow tensor
|
cosqa-train-18504
|
def astensor(array: TensorLike) -> BKTensor:
"""Covert numpy array to tensorflow tensor"""
tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)
return tensor
|
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 |
set python path for pylint
|
Checks for local config overrides for pylint and add them in the correct pylint options format .
|
cosqa-train-18505
|
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 string ( value ) -> str : return system_json . dumps ( Json ( value ) . safe_object ( ) , ensure_ascii = False )
| 0 |
passing python object as a string
|
string dict / object / value to JSON
|
cosqa-train-18506
|
def string(value) -> str:
""" string dict/object/value to JSON """
return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)
|
def _check_limit ( self ) : # First compress self . _compress ( ) # Then check the max size if len ( self . _store ) >= self . _max_size : self . _store . popitem ( last = False )
| 0 |
python spider memery usage not stop growing
|
Intenal method : check if current cache size exceeds maximum cache size and pop the oldest item in this case
|
cosqa-train-18507
|
def _check_limit(self):
"""Intenal method: check if current cache size exceeds maximum cache
size and pop the oldest item in this case"""
# First compress
self._compress()
# Then check the max size
if len(self._store) >= self._max_size:
self._store.popitem(last=False)
|
def get_default_bucket_key ( buckets : List [ Tuple [ int , int ] ] ) -> Tuple [ int , int ] : return max ( buckets )
| 1 |
how to reurn the key for a largest value in python
|
Returns the default bucket from a list of buckets i . e . the largest bucket .
|
cosqa-train-18508
|
def get_default_bucket_key(buckets: List[Tuple[int, int]]) -> Tuple[int, int]:
"""
Returns the default bucket from a list of buckets, i.e. the largest bucket.
:param buckets: List of buckets.
:return: The largest bucket in the list.
"""
return max(buckets)
|
def codes_get_size ( handle , key ) : # type: (cffi.FFI.CData, str) -> int size = ffi . new ( 'size_t *' ) _codes_get_size ( handle , key . encode ( ENC ) , size ) return size [ 0 ]
| 1 |
max size of a key in python
|
Get the number of coded value from a key . If several keys of the same name are present the total sum is returned .
|
cosqa-train-18509
|
def codes_get_size(handle, key):
# type: (cffi.FFI.CData, str) -> int
"""
Get the number of coded value from a key.
If several keys of the same name are present, the total sum is returned.
:param bytes key: the keyword to get the size of
:rtype: int
"""
size = ffi.new('size_t *')
_codes_get_size(handle, key.encode(ENC), size)
return size[0]
|
def try_cast_int ( s ) : try : temp = re . findall ( '\d' , str ( s ) ) temp = '' . join ( temp ) return int ( temp ) except : return s
| 0 |
pythong 3 covert str to int
|
( str ) - > int All the digits in a given string are concatenated and converted into a single number .
|
cosqa-train-18510
|
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 remove_namespaces ( root ) : for elem in root . getiterator ( ) : if not hasattr ( elem . tag , 'find' ) : continue i = elem . tag . find ( '}' ) if i >= 0 : elem . tag = elem . tag [ i + 1 : ] objectify . deannotate ( root , cleanup_namespaces = True )
| 1 |
python remove all xml namespaces
|
Call this on an lxml . etree document to remove all namespaces
|
cosqa-train-18511
|
def remove_namespaces(root):
"""Call this on an lxml.etree document to remove all namespaces"""
for elem in root.getiterator():
if not hasattr(elem.tag, 'find'):
continue
i = elem.tag.find('}')
if i >= 0:
elem.tag = elem.tag[i + 1:]
objectify.deannotate(root, cleanup_namespaces=True)
|
def remove_blank_lines ( string ) : return "\n" . join ( line for line in string . split ( "\n" ) if len ( line . strip ( ) ) )
| 0 |
clear whitespace python string
|
Removes all blank lines in @string
|
cosqa-train-18512
|
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 _brief_print_list ( lst , limit = 7 ) : lst = list ( lst ) if len ( lst ) > limit : return _brief_print_list ( lst [ : limit // 2 ] , limit ) + ', ..., ' + _brief_print_list ( lst [ - limit // 2 : ] , limit ) return ', ' . join ( [ "'%s'" % str ( i ) for i in lst ] )
| 0 |
how to print few element of a list in python
|
Print at most limit elements of list .
|
cosqa-train-18513
|
def _brief_print_list(lst, limit=7):
"""Print at most `limit` elements of list."""
lst = list(lst)
if len(lst) > limit:
return _brief_print_list(lst[:limit//2], limit) + ', ..., ' + \
_brief_print_list(lst[-limit//2:], limit)
return ', '.join(["'%s'"%str(i) for i in lst])
|
def 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 |
python check if file has a specific line
|
Detects whether a line is present within a file .
|
cosqa-train-18514
|
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 convert_bytes_to_ints ( in_bytes , num ) : dt = numpy . dtype ( '>i' + str ( num ) ) return numpy . frombuffer ( in_bytes , dt )
| 1 |
values in bytearray should be integers between python
|
Convert a byte array into an integer array . The number of bytes forming an integer is defined by num
|
cosqa-train-18515
|
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 zfill ( x , width ) : if not isinstance ( x , basestring ) : x = repr ( x ) return x . zfill ( width )
| 0 |
python string zero fill
|
zfill ( x width ) - > string
|
cosqa-train-18516
|
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 list_to_str ( lst ) : if len ( lst ) == 1 : str_ = lst [ 0 ] elif len ( lst ) == 2 : str_ = ' and ' . join ( lst ) elif len ( lst ) > 2 : str_ = ', ' . join ( lst [ : - 1 ] ) str_ += ', and {0}' . format ( lst [ - 1 ] ) else : raise ValueError ( 'List of length 0 provided.' ) return str_
| 0 |
how to return a string formed by concatenating all the elements in a list in python
|
Turn a list into a comma - and / or and - separated string .
|
cosqa-train-18517
|
def list_to_str(lst):
"""
Turn a list into a comma- and/or and-separated string.
Parameters
----------
lst : :obj:`list`
A list of strings to join into a single string.
Returns
-------
str_ : :obj:`str`
A string with commas and/or ands separating th elements from ``lst``.
"""
if len(lst) == 1:
str_ = lst[0]
elif len(lst) == 2:
str_ = ' and '.join(lst)
elif len(lst) > 2:
str_ = ', '.join(lst[:-1])
str_ += ', and {0}'.format(lst[-1])
else:
raise ValueError('List of length 0 provided.')
return str_
|
def csv_to_numpy ( string_like , dtype = None ) : # type: (str) -> np.array stream = StringIO ( string_like ) return np . genfromtxt ( stream , dtype = dtype , delimiter = ',' )
| 1 |
reading csv as numpy array in python
|
Convert a CSV object to a numpy array .
|
cosqa-train-18518
|
def csv_to_numpy(string_like, dtype=None): # type: (str) -> np.array
"""Convert a CSV object to a numpy array.
Args:
string_like (str): CSV string.
dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the
contents of each column, individually. This argument can only be used to
'upcast' the array. For downcasting, use the .astype(t) method.
Returns:
(np.array): numpy array
"""
stream = StringIO(string_like)
return np.genfromtxt(stream, dtype=dtype, delimiter=',')
|
def genfirstvalues ( cursor : Cursor , arraysize : int = 1000 ) -> Generator [ Any , None , None ] : return ( row [ 0 ] for row in genrows ( cursor , arraysize ) )
| 1 |
how to get first few rows in python
|
Generate the first value in each row .
|
cosqa-train-18519
|
def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \
-> Generator[Any, None, None]:
"""
Generate the first value in each row.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
the first value of each row
"""
return (row[0] for row in genrows(cursor, arraysize))
|
def first_digits ( s , default = 0 ) : s = re . split ( r'[^0-9]+' , str ( s ) . strip ( ) . lstrip ( '+-' + charlist . whitespace ) ) if len ( s ) and len ( s [ 0 ] ) : return int ( s [ 0 ] ) return default
| 1 |
python return based on first digit of string
|
Return the fist ( left - hand ) digits in a string as a single integer ignoring sign ( + / - ) . >>> first_digits ( + 123 . 456 ) 123
|
cosqa-train-18520
|
def first_digits(s, default=0):
"""Return the fist (left-hand) digits in a string as a single integer, ignoring sign (+/-).
>>> first_digits('+123.456')
123
"""
s = re.split(r'[^0-9]+', str(s).strip().lstrip('+-' + charlist.whitespace))
if len(s) and len(s[0]):
return int(s[0])
return default
|
def uppercase_chars ( string : any ) -> str : return '' . join ( [ c if c . isupper ( ) else '' for c in str ( string ) ] )
| 0 |
turn string into uppercase python
|
Return all ( and only ) the uppercase chars in the given string .
|
cosqa-train-18521
|
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 _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 |
python exit thread in advance
|
Properly kill Python process including zombie threads .
|
cosqa-train-18522
|
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 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 |
how to check character type in python
|
Validates that the object itself is some kinda string
|
cosqa-train-18523
|
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 dict_to_enum_fn ( d : Dict [ str , Any ] , enum_class : Type [ Enum ] ) -> Enum : return enum_class [ d [ 'name' ] ]
| 0 |
python from string to enum
|
Converts an dict to a Enum .
|
cosqa-train-18524
|
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 _relative_frequency ( self , word ) : count = self . type_counts . get ( word , 0 ) return math . log ( count / len ( self . type_counts ) ) if count > 0 else 0
| 1 |
how to get % frequencies python
|
Computes the log relative frequency for a word form
|
cosqa-train-18525
|
def _relative_frequency(self, word):
"""Computes the log relative frequency for a word form"""
count = self.type_counts.get(word, 0)
return math.log(count/len(self.type_counts)) if count > 0 else 0
|
def replace_variables ( self , source : str , variables : dict ) -> str : try : replaced = re . sub ( "{{(.*?)}}" , lambda m : variables . get ( m . group ( 1 ) , "" ) , source ) except TypeError : replaced = source return replaced
| 1 |
python variable replacement in string
|
Replace {{ variable - name }} with stored value .
|
cosqa-train-18526
|
def replace_variables(self, source: str, variables: dict) -> str:
"""Replace {{variable-name}} with stored value."""
try:
replaced = re.sub(
"{{(.*?)}}", lambda m: variables.get(m.group(1), ""), source
)
except TypeError:
replaced = source
return replaced
|
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 create dict of index and item of list
|
Return dict mapping item - > indices .
|
cosqa-train-18527
|
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 update_kwargs ( kwargs , * * keyvalues ) : for key , value in keyvalues . items ( ) : if key not in kwargs : kwargs [ key ] = value
| 0 |
python how to add to kwargs if not present
|
Update dict with keys and values if keys do not already exist .
|
cosqa-train-18528
|
def update_kwargs(kwargs, **keyvalues):
"""Update dict with keys and values if keys do not already exist.
>>> kwargs = {'one': 1, }
>>> update_kwargs(kwargs, one=None, two=2)
>>> kwargs == {'one': 1, 'two': 2}
True
"""
for key, value in keyvalues.items():
if key not in kwargs:
kwargs[key] = value
|
async def executemany ( self , sql : str , parameters : Iterable [ Iterable [ Any ] ] ) -> None : await self . _execute ( self . _cursor . executemany , sql , parameters )
| 0 |
python mysqldb executemany thread
|
Execute the given multiquery .
|
cosqa-train-18529
|
async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None:
"""Execute the given multiquery."""
await self._execute(self._cursor.executemany, sql, parameters)
|
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 reader skip header line
|
Skip a section
|
cosqa-train-18530
|
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 flatten_multidict ( multidict ) : return dict ( [ ( key , value if len ( value ) > 1 else value [ 0 ] ) for ( key , value ) in multidict . iterlists ( ) ] )
| 1 |
python flatten a nested dictionaary
|
Return flattened dictionary from MultiDict .
|
cosqa-train-18531
|
def flatten_multidict(multidict):
"""Return flattened dictionary from ``MultiDict``."""
return dict([(key, value if len(value) > 1 else value[0])
for (key, value) in multidict.iterlists()])
|
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 2 paths are the same
|
Check if two pathes represent the same file .
|
cosqa-train-18532
|
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 file_exists ( fname ) : try : return fname and os . path . exists ( fname ) and os . path . getsize ( fname ) > 0 except OSError : return False
| 0 |
python check if doesn't exist
|
Check if a file exists and is non - empty .
|
cosqa-train-18533
|
def file_exists(fname):
"""Check if a file exists and is non-empty.
"""
try:
return fname and os.path.exists(fname) and os.path.getsize(fname) > 0
except OSError:
return False
|
async def parallel_results ( future_map : Sequence [ Tuple ] ) -> Dict : ctx_methods = OrderedDict ( future_map ) fs = list ( ctx_methods . values ( ) ) results = await asyncio . gather ( * fs ) results = { key : results [ idx ] for idx , key in enumerate ( ctx_methods . keys ( ) ) } return results
| 0 |
crawl async data with python asyncio
|
Run parallel execution of futures and return mapping of their results to the provided keys . Just a neat shortcut around asyncio . gather ()
|
cosqa-train-18534
|
async def parallel_results(future_map: Sequence[Tuple]) -> Dict:
"""
Run parallel execution of futures and return mapping of their results to the provided keys.
Just a neat shortcut around ``asyncio.gather()``
:param future_map: Keys to futures mapping, e.g.: ( ('nav', get_nav()), ('content, get_content()) )
:return: Dict with futures results mapped to keys {'nav': {1:2}, 'content': 'xyz'}
"""
ctx_methods = OrderedDict(future_map)
fs = list(ctx_methods.values())
results = await asyncio.gather(*fs)
results = {
key: results[idx] for idx, key in enumerate(ctx_methods.keys())
}
return results
|
def split ( text : str ) -> List [ str ] : return [ word for word in SEPARATOR . split ( text ) if word . strip ( ' \t' ) ]
| 1 |
python text to list tokenizer split
|
Split a text into a list of tokens .
|
cosqa-train-18535
|
def split(text: str) -> List[str]:
"""Split a text into a list of tokens.
:param text: the text to split
:return: tokens
"""
return [word for word in SEPARATOR.split(text) if word.strip(' \t')]
|
def strtobytes ( input , encoding ) : py_version = sys . version_info [ 0 ] if py_version >= 3 : return _strtobytes_py3 ( input , encoding ) return _strtobytes_py2 ( input , encoding )
| 0 |
python 3 string to bytecode
|
Take a str and transform it into a byte array .
|
cosqa-train-18536
|
def strtobytes(input, encoding):
"""Take a str and transform it into a byte array."""
py_version = sys.version_info[0]
if py_version >= 3:
return _strtobytes_py3(input, encoding)
return _strtobytes_py2(input, encoding)
|
def has_synset ( word : str ) -> list : return wn . synsets ( lemmatize ( word , neverstem = True ) )
| 1 |
python get set word synonyms
|
Returns a list of synsets of a word after lemmatization .
|
cosqa-train-18537
|
def has_synset(word: str) -> list:
"""" Returns a list of synsets of a word after lemmatization. """
return wn.synsets(lemmatize(word, neverstem=True))
|
def read_text_from_file ( path : str ) -> str : with open ( path ) as text_file : content = text_file . read ( ) return content
| 1 |
read and display a text file in python
|
Reads text file contents
|
cosqa-train-18538
|
def read_text_from_file(path: str) -> str:
""" Reads text file contents """
with open(path) as text_file:
content = text_file.read()
return content
|
def timeit ( func , * args , * * kwargs ) : start_time = time . time ( ) res = func ( * args , * * kwargs ) timing = time . time ( ) - start_time return res , timing
| 0 |
how to time a python function
|
Time execution of function . Returns ( res seconds ) .
|
cosqa-train-18539
|
def timeit(func, *args, **kwargs):
"""
Time execution of function. Returns (res, seconds).
>>> res, timing = timeit(time.sleep, 1)
"""
start_time = time.time()
res = func(*args, **kwargs)
timing = time.time() - start_time
return res, timing
|
def head ( self ) -> Any : lambda_list = self . _get_value ( ) return lambda_list ( lambda head , _ : head )
| 0 |
python lambda get self
|
Retrive first element in List .
|
cosqa-train-18540
|
def head(self) -> Any:
"""Retrive first element in List."""
lambda_list = self._get_value()
return lambda_list(lambda head, _: head)
|
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 change a str to a date
|
Creates a datetime from GnuCash 2 . 6 date string
|
cosqa-train-18541
|
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 has_value ( cls , value : int ) -> bool : return any ( value == item . value for item in cls )
| 0 |
compare against enum values in python
|
True if specified value exists in int enum ; otherwise False .
|
cosqa-train-18542
|
def has_value(cls, value: int) -> bool:
"""True if specified value exists in int enum; otherwise, False."""
return any(value == item.value for item in cls)
|
def _str_to_list ( value , separator ) : value_list = [ item . strip ( ) for item in value . split ( separator ) ] value_list_sanitized = builtins . list ( filter ( None , value_list ) ) if len ( value_list_sanitized ) > 0 : return value_list_sanitized else : raise ValueError ( 'Invalid list variable.' )
| 1 |
turning a string into a list in python
|
Convert a string to a list with sanitization .
|
cosqa-train-18543
|
def _str_to_list(value, separator):
"""Convert a string to a list with sanitization."""
value_list = [item.strip() for item in value.split(separator)]
value_list_sanitized = builtins.list(filter(None, value_list))
if len(value_list_sanitized) > 0:
return value_list_sanitized
else:
raise ValueError('Invalid list variable.')
|
def truncate ( value : Decimal , n_digits : int ) -> Decimal : return Decimal ( math . trunc ( value * ( 10 ** n_digits ) ) ) / ( 10 ** n_digits )
| 1 |
truncate floats to 4 decimals in python
|
Truncates a value to a number of decimals places
|
cosqa-train-18544
|
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 stop ( self ) -> None : if self . _stop and not self . _posted_kork : self . _stop ( ) self . _stop = None
| 1 |
stop a function from continuing python
|
Stops the analysis as soon as possible .
|
cosqa-train-18545
|
def stop(self) -> None:
"""Stops the analysis as soon as possible."""
if self._stop and not self._posted_kork:
self._stop()
self._stop = None
|
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 get back to previous line in python while printing
|
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-18546
|
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 _reshuffle ( mat , shape ) : return np . reshape ( np . transpose ( np . reshape ( mat , shape ) , ( 3 , 1 , 2 , 0 ) ) , ( shape [ 3 ] * shape [ 1 ] , shape [ 0 ] * shape [ 2 ] ) )
| 0 |
how to shuffe columns python
|
Reshuffle the indicies of a bipartite matrix A [ ij kl ] - > A [ lj ki ] .
|
cosqa-train-18547
|
def _reshuffle(mat, shape):
"""Reshuffle the indicies of a bipartite matrix A[ij,kl] -> A[lj,ki]."""
return np.reshape(
np.transpose(np.reshape(mat, shape), (3, 1, 2, 0)),
(shape[3] * shape[1], shape[0] * shape[2]))
|
def integer_partition ( size : int , nparts : int ) -> Iterator [ List [ List [ int ] ] ] : for part in algorithm_u ( range ( size ) , nparts ) : yield part
| 0 |
count partitions python permute
|
Partition a list of integers into a list of partitions
|
cosqa-train-18548
|
def integer_partition(size: int, nparts: int) -> Iterator[List[List[int]]]:
""" Partition a list of integers into a list of partitions """
for part in algorithm_u(range(size), nparts):
yield part
|
def Exit ( msg , code = 1 ) : print >> sys . stderr , msg sys . exit ( code )
| 0 |
how do you input the exit function in python
|
Exit execution with return code and message : param msg : Message displayed prior to exit : param code : code returned upon exiting
|
cosqa-train-18549
|
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 filter_float ( n : Node , query : str ) -> float : return _scalariter2item ( n , query , float )
| 0 |
wrapper for int or float python
|
Filter and ensure that the returned value is of type int .
|
cosqa-train-18550
|
def filter_float(n: Node, query: str) -> float:
"""
Filter and ensure that the returned value is of type int.
"""
return _scalariter2item(n, query, float)
|
def lcm ( num1 , num2 ) : if num1 > num2 : bigger = num1 else : bigger = num2 while True : if bigger % num1 == 0 and bigger % num2 == 0 : return bigger bigger += 1
| 1 |
python code for least common multiple of a list of numbers
|
Find the lowest common multiple of 2 numbers
|
cosqa-train-18551
|
def lcm(num1, num2):
"""
Find the lowest common multiple of 2 numbers
:type num1: number
:param num1: The first number to find the lcm for
:type num2: number
:param num2: The second number to find the lcm for
"""
if num1 > num2:
bigger = num1
else:
bigger = num2
while True:
if bigger % num1 == 0 and bigger % num2 == 0:
return bigger
bigger += 1
|
def _rindex ( mylist : Sequence [ T ] , x : T ) -> int : return len ( mylist ) - mylist [ : : - 1 ] . index ( x ) - 1
| 1 |
index of last occurence of an element in a list in python
|
Index of the last occurrence of x in the sequence .
|
cosqa-train-18552
|
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_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 then
|
Return true if outfile exists and is no older than base datetime .
|
cosqa-train-18553
|
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 from_file ( file_path ) -> dict : with io . open ( file_path , 'r' , encoding = 'utf-8' ) as json_stream : return Json . parse ( json_stream , True )
| 1 |
python reading text file as json
|
Load JSON file
|
cosqa-train-18554
|
def from_file(file_path) -> dict:
""" Load JSON file """
with io.open(file_path, 'r', encoding='utf-8') as json_stream:
return Json.parse(json_stream, True)
|
def run_time ( ) -> timedelta : delta = start_time if start_time else datetime . utcnow ( ) return datetime . utcnow ( ) - delta
| 1 |
starttime minus current time delta in python
|
cosqa-train-18555
|
def run_time() -> timedelta:
"""
:return:
"""
delta = start_time if start_time else datetime.utcnow()
return datetime.utcnow() - delta
|
|
def get_from_gnucash26_date ( date_str : str ) -> date : date_format = "%Y%m%d" result = datetime . strptime ( date_str , date_format ) . date ( ) return result
| 1 |
how to create a datetime object with a string date in python
|
Creates a datetime from GnuCash 2 . 6 date string
|
cosqa-train-18556
|
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 negate_mask ( mask ) : res = np . ones ( mask . shape , dtype = np . int8 ) res [ mask > 0 ] = 0 return res
| 0 |
python bitwise mask not turning white pixels
|
Returns the negated mask . If elements of input mask have 0 and non - zero values then the returned matrix will have all elements 0 ( 1 ) where the original one has non - zero ( 0 ) . : param mask : Input mask : type mask : np . array : return : array of same shape and dtype = int8 as input array : rtype : np . array
|
cosqa-train-18557
|
def negate_mask(mask):
"""Returns the negated mask.
If elements of input mask have 0 and non-zero values, then the returned matrix will have all elements 0 (1) where
the original one has non-zero (0).
:param mask: Input mask
:type mask: np.array
:return: array of same shape and dtype=int8 as input array
:rtype: np.array
"""
res = np.ones(mask.shape, dtype=np.int8)
res[mask > 0] = 0
return res
|
def _ ( f , x ) : return { k : v for k , v in x . items ( ) if f ( k , v ) }
| 0 |
filter dictionary values in python
|
filter for dict note f should have signature : f :: key - > value - > bool
|
cosqa-train-18558
|
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 csv_to_numpy ( string_like , dtype = None ) : # type: (str) -> np.array stream = StringIO ( string_like ) return np . genfromtxt ( stream , dtype = dtype , delimiter = ',' )
| 1 |
python load csv to numpy array
|
Convert a CSV object to a numpy array .
|
cosqa-train-18559
|
def csv_to_numpy(string_like, dtype=None): # type: (str) -> np.array
"""Convert a CSV object to a numpy array.
Args:
string_like (str): CSV string.
dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the
contents of each column, individually. This argument can only be used to
'upcast' the array. For downcasting, use the .astype(t) method.
Returns:
(np.array): numpy array
"""
stream = StringIO(string_like)
return np.genfromtxt(stream, dtype=dtype, delimiter=',')
|
def _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
| 1 |
testing for empty file in python
|
Check if cnr or cns files are empty ( only have a header )
|
cosqa-train-18560
|
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 get_domain ( url ) : parse_result = urlparse ( url ) domain = "{schema}://{netloc}" . format ( schema = parse_result . scheme , netloc = parse_result . netloc ) return domain
| 1 |
python 3 domain url parse
|
Get domain part of an url .
|
cosqa-train-18561
|
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 maybe_infer_dtype_type ( element ) : tipo = None if hasattr ( element , 'dtype' ) : tipo = element . dtype elif is_list_like ( element ) : element = np . asarray ( element ) tipo = element . dtype return tipo
| 1 |
how to determine data type of variable in python
|
Try to infer an object s dtype for use in arithmetic ops
|
cosqa-train-18562
|
def maybe_infer_dtype_type(element):
"""Try to infer an object's dtype, for use in arithmetic ops
Uses `element.dtype` if that's available.
Objects implementing the iterator protocol are cast to a NumPy array,
and from there the array's type is used.
Parameters
----------
element : object
Possibly has a `.dtype` attribute, and possibly the iterator
protocol.
Returns
-------
tipo : type
Examples
--------
>>> from collections import namedtuple
>>> Foo = namedtuple("Foo", "dtype")
>>> maybe_infer_dtype_type(Foo(np.dtype("i8")))
numpy.int64
"""
tipo = None
if hasattr(element, 'dtype'):
tipo = element.dtype
elif is_list_like(element):
element = np.asarray(element)
tipo = element.dtype
return tipo
|
def memory_usage ( ) : try : import psutil import os except ImportError : return _memory_usage_ps ( ) process = psutil . Process ( os . getpid ( ) ) mem = process . memory_info ( ) [ 0 ] / float ( 2 ** 20 ) return mem
| 0 |
python measuring memory usage dynamically
|
return memory usage of python process in MB
|
cosqa-train-18563
|
def memory_usage():
"""return memory usage of python process in MB
from
http://fa.bianp.net/blog/2013/different-ways-to-get-memory-consumption-or-lessons-learned-from-memory_profiler/
psutil is quicker
>>> isinstance(memory_usage(),float)
True
"""
try:
import psutil
import os
except ImportError:
return _memory_usage_ps()
process = psutil.Process(os.getpid())
mem = process.memory_info()[0] / float(2 ** 20)
return mem
|
def snake_to_camel ( s : str ) -> str : fragments = s . split ( '_' ) return fragments [ 0 ] + '' . join ( x . title ( ) for x in fragments [ 1 : ] )
| 0 |
python comvert string to title case
|
Convert string from snake case to camel case .
|
cosqa-train-18564
|
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 was_into_check ( self ) -> bool : king = self . king ( not self . turn ) return king is not None and self . is_attacked_by ( self . turn , king )
| 1 |
a check funtion in python for turned based game
|
Checks if the king of the other side is attacked . Such a position is not valid and could only be reached by an illegal move .
|
cosqa-train-18565
|
def was_into_check(self) -> bool:
"""
Checks if the king of the other side is attacked. Such a position is not
valid and could only be reached by an illegal move.
"""
king = self.king(not self.turn)
return king is not None and self.is_attacked_by(self.turn, king)
|
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 |
check if column values are blank in 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-18566
|
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 url_host ( url : str ) -> str : from urllib . parse import urlparse res = urlparse ( url ) return res . netloc . split ( ':' ) [ 0 ] if res . netloc else ''
| 0 |
python extract hostname from url
|
Parses hostname from URL . : param url : URL : return : hostname
|
cosqa-train-18567
|
def url_host(url: str) -> str:
"""
Parses hostname from URL.
:param url: URL
:return: hostname
"""
from urllib.parse import urlparse
res = urlparse(url)
return res.netloc.split(':')[0] if res.netloc else ''
|
def load_preprocess_images ( image_paths : List [ str ] , image_size : tuple ) -> List [ np . ndarray ] : image_size = image_size [ 1 : ] # we do not need the number of channels images = [ ] for image_path in image_paths : images . append ( load_preprocess_image ( image_path , image_size ) ) return images
| 1 |
how to prepreocess multiple images in python
|
Load and pre - process the images specified with absolute paths .
|
cosqa-train-18568
|
def load_preprocess_images(image_paths: List[str], image_size: tuple) -> List[np.ndarray]:
"""
Load and pre-process the images specified with absolute paths.
:param image_paths: List of images specified with paths.
:param image_size: Tuple to resize the image to (Channels, Height, Width)
:return: A list of loaded images (numpy arrays).
"""
image_size = image_size[1:] # we do not need the number of channels
images = []
for image_path in image_paths:
images.append(load_preprocess_image(image_path, image_size))
return images
|
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 |
check is a link is relative python
|
simple method to determine if a url is relative or absolute
|
cosqa-train-18569
|
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 _short_repr ( obj ) : stringified = pprint . saferepr ( obj ) if len ( stringified ) > 200 : return '%s... (%d bytes)' % ( stringified [ : 200 ] , len ( stringified ) ) return stringified
| 1 |
python pprint a long string
|
Helper function returns a truncated repr () of an object .
|
cosqa-train-18570
|
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 to_0d_array ( value : Any ) -> np . ndarray : if np . isscalar ( value ) or ( isinstance ( value , np . ndarray ) and value . ndim == 0 ) : return np . array ( value ) else : return to_0d_object_array ( value )
| 1 |
selecting a range of 2d elements from a numpy array gives empty array in python 3
|
Given a value wrap it in a 0 - D numpy . ndarray .
|
cosqa-train-18571
|
def to_0d_array(value: Any) -> np.ndarray:
"""Given a value, wrap it in a 0-D numpy.ndarray.
"""
if np.isscalar(value) or (isinstance(value, np.ndarray) and
value.ndim == 0):
return np.array(value)
else:
return to_0d_object_array(value)
|
def is_natural ( x ) : try : is_integer = int ( x ) == x except ( TypeError , ValueError ) : return False return is_integer and x >= 0
| 0 |
python check for real number
|
A non - negative integer .
|
cosqa-train-18572
|
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 find_unit_clause ( clauses , model ) : for clause in clauses : P , value = unit_clause_assign ( clause , model ) if P : return P , value return None , None
| 0 |
if clause checking tow statemetents in python
|
Find a forced assignment if possible from a clause with only 1 variable not bound in the model . >>> find_unit_clause ( [ A|B|C B|~C ~A|~B ] { A : True } ) ( B False )
|
cosqa-train-18573
|
def find_unit_clause(clauses, model):
"""Find a forced assignment if possible from a clause with only 1
variable not bound in the model.
>>> find_unit_clause([A|B|C, B|~C, ~A|~B], {A:True})
(B, False)
"""
for clause in clauses:
P, value = unit_clause_assign(clause, model)
if P: return P, value
return None, None
|
def valid_date ( x : str ) -> bool : try : if x != dt . datetime . strptime ( x , DATE_FORMAT ) . strftime ( DATE_FORMAT ) : raise ValueError return True except ValueError : return False
| 0 |
check if a string match date type format python
|
Retrun True if x is a valid YYYYMMDD date ; otherwise return False .
|
cosqa-train-18574
|
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 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 if it is not a string
|
Validates that the object itself is some kinda string
|
cosqa-train-18575
|
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 dotproduct ( X , Y ) : return sum ( [ x * y for x , y in zip ( X , Y ) ] )
| 1 |
product of all elements python
|
Return the sum of the element - wise product of vectors x and y . >>> dotproduct ( [ 1 2 3 ] [ 1000 100 10 ] ) 1230
|
cosqa-train-18576
|
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 chars ( string : any ) -> str : return '' . join ( [ c if c . isalpha ( ) else '' for c in str ( string ) ] )
| 1 |
how to check if any char in a string is alpha python
|
Return all ( and only ) the chars in the given string .
|
cosqa-train-18577
|
def chars(string: any) -> str:
"""Return all (and only) the chars in the given string."""
return ''.join([c if c.isalpha() else '' for c in str(string)])
|
def listify ( a ) : if a is None : return [ ] elif not isinstance ( a , ( tuple , list , np . ndarray ) ) : return [ a ] return list ( a )
| 0 |
covert an array to a list in python
|
Convert a scalar a to a list and all iterables to list as well .
|
cosqa-train-18578
|
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 year ( date ) : try : fmt = '%m/%d/%Y' return datetime . strptime ( date , fmt ) . timetuple ( ) . tm_year except ValueError : return 0
| 0 |
python how to get the year from a timestamp
|
Returns the year .
|
cosqa-train-18579
|
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 clean_column_names ( df : DataFrame ) -> DataFrame : f = df . copy ( ) f . columns = [ col . strip ( ) for col in f . columns ] return f
| 0 |
remove columns a data frame python
|
Strip the whitespace from all column names in the given DataFrame and return the result .
|
cosqa-train-18580
|
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 valid_date ( x : str ) -> bool : try : if x != dt . datetime . strptime ( x , DATE_FORMAT ) . strftime ( DATE_FORMAT ) : raise ValueError return True except ValueError : return False
| 1 |
python check if date is valid
|
Retrun True if x is a valid YYYYMMDD date ; otherwise return False .
|
cosqa-train-18581
|
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 __remove_trailing_zeros ( self , collection ) : index = len ( collection ) - 1 while index >= 0 and collection [ index ] == 0 : index -= 1 return collection [ : index + 1 ]
| 1 |
trimming off leading zeros python
|
Removes trailing zeroes from indexable collection of numbers
|
cosqa-train-18582
|
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 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 |
finding the last occurance of a character in a string in python
|
Returns the index of the earliest occurence of an item from a list in a string
|
cosqa-train-18583
|
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 get_now_utc_notz_datetime ( ) -> datetime . datetime : now = datetime . datetime . utcnow ( ) return now . replace ( tzinfo = None )
| 0 |
python datetime today astimezone
|
Get the UTC time now but with no timezone information in : class : datetime . datetime format .
|
cosqa-train-18584
|
def get_now_utc_notz_datetime() -> datetime.datetime:
"""
Get the UTC time now, but with no timezone information,
in :class:`datetime.datetime` format.
"""
now = datetime.datetime.utcnow()
return now.replace(tzinfo=None)
|
def __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 |
is there a way to replace multiple characters in python
|
Replaces from a string ** input ** all the occurrences of some symbols according to mapping ** repls ** .
|
cosqa-train-18585
|
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 indexes_equal ( a : Index , b : Index ) -> bool : return str ( a ) == str ( b )
| 1 |
how to check 2 strings are the same in python
|
Are two indexes equal? Checks by comparing str () versions of them . ( AM UNSURE IF THIS IS ENOUGH . )
|
cosqa-train-18586
|
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 make_dep_graph ( depender ) : shutit_global . shutit_global_object . yield_to_draw ( ) digraph = '' for dependee_id in depender . depends_on : digraph = ( digraph + '"' + depender . module_id + '"->"' + dependee_id + '";\n' ) return digraph
| 0 |
python draw dependency graph
|
Returns a digraph string fragment based on the passed - in module
|
cosqa-train-18587
|
def make_dep_graph(depender):
"""Returns a digraph string fragment based on the passed-in module
"""
shutit_global.shutit_global_object.yield_to_draw()
digraph = ''
for dependee_id in depender.depends_on:
digraph = (digraph + '"' + depender.module_id + '"->"' + dependee_id + '";\n')
return digraph
|
def isarray ( array , test , dim = 2 ) : if dim > 1 : return all ( isarray ( array [ i ] , test , dim - 1 ) for i in range ( len ( array ) ) ) return all ( test ( i ) for i in array )
| 1 |
python test elements of an array
|
Returns True if test is True for all array elements . Otherwise returns False .
|
cosqa-train-18588
|
def isarray(array, test, dim=2):
"""Returns True if test is True for all array elements.
Otherwise, returns False.
"""
if dim > 1:
return all(isarray(array[i], test, dim - 1)
for i in range(len(array)))
return all(test(i) for i in array)
|
def clean ( ctx , text ) : text = conversions . to_string ( text , ctx ) return '' . join ( [ c for c in text if ord ( c ) >= 32 ] )
| 1 |
python remove non english charachters from a text
|
Removes all non - printable characters from a text string
|
cosqa-train-18589
|
def clean(ctx, text):
"""
Removes all non-printable characters from a text string
"""
text = conversions.to_string(text, ctx)
return ''.join([c for c in text if ord(c) >= 32])
|
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 get a numerical date from a string date
|
Creates a datetime from GnuCash 2 . 6 date string
|
cosqa-train-18590
|
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 read_text_from_file ( path : str ) -> str : with open ( path ) as text_file : content = text_file . read ( ) return content
| 1 |
vs code python read text file
|
Reads text file contents
|
cosqa-train-18591
|
def read_text_from_file(path: str) -> str:
""" Reads text file contents """
with open(path) as text_file:
content = text_file.read()
return content
|
def _find_conda ( ) : if 'CONDA_EXE' in os . environ : conda = os . environ [ 'CONDA_EXE' ] else : conda = util . which ( 'conda' ) return conda
| 0 |
how to open a python conda environment
|
Find the conda executable robustly across conda versions .
|
cosqa-train-18592
|
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 connect_to_database_odbc_access ( self , dsn : str , autocommit : bool = True ) -> None : self . connect ( engine = ENGINE_ACCESS , interface = INTERFACE_ODBC , dsn = dsn , autocommit = autocommit )
| 0 |
pyodbc python oracle connect
|
Connects to an Access database via ODBC with the DSN prespecified .
|
cosqa-train-18593
|
def connect_to_database_odbc_access(self,
dsn: str,
autocommit: bool = True) -> None:
"""Connects to an Access database via ODBC, with the DSN
prespecified."""
self.connect(engine=ENGINE_ACCESS, interface=INTERFACE_ODBC,
dsn=dsn, autocommit=autocommit)
|
def _find_conda ( ) : if 'CONDA_EXE' in os . environ : conda = os . environ [ 'CONDA_EXE' ] else : conda = util . which ( 'conda' ) return conda
| 1 |
conda python env not activated windows
|
Find the conda executable robustly across conda versions .
|
cosqa-train-18594
|
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 clean ( ctx , text ) : text = conversions . to_string ( text , ctx ) return '' . join ( [ c for c in text if ord ( c ) >= 32 ] )
| 1 |
python delete all characters from text
|
Removes all non - printable characters from a text string
|
cosqa-train-18595
|
def clean(ctx, text):
"""
Removes all non-printable characters from a text string
"""
text = conversions.to_string(text, ctx)
return ''.join([c for c in text if ord(c) >= 32])
|
def _parse_tuple_string ( argument ) : if isinstance ( argument , str ) : return tuple ( int ( p . strip ( ) ) for p in argument . split ( ',' ) ) return argument
| 0 |
python how to return separate tuples
|
Return a tuple from parsing a b c d - > ( a b c d )
|
cosqa-train-18596
|
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 remove_blank_lines ( string ) : return "\n" . join ( line for line in string . split ( "\n" ) if len ( line . strip ( ) ) )
| 1 |
how to remove a empty string in python
|
Removes all blank lines in @string
|
cosqa-train-18597
|
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 returned ( n ) : ## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk for pos in randwalk ( ) >> drop ( 1 ) >> takei ( xrange ( n - 1 ) ) : if pos == Origin : return True return False
| 0 |
how to get randomwalk to work python
|
Generate a random walk and return True if the walker has returned to the origin after taking n steps .
|
cosqa-train-18598
|
def returned(n):
"""Generate a random walk and return True if the walker has returned to
the origin after taking `n` steps.
"""
## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk
for pos in randwalk() >> drop(1) >> takei(xrange(n-1)):
if pos == Origin:
return True
return False
|
def get_now_utc_notz_datetime ( ) -> datetime . datetime : now = datetime . datetime . utcnow ( ) return now . replace ( tzinfo = None )
| 0 |
python datetime utcnow no tzinfo
|
Get the UTC time now but with no timezone information in : class : datetime . datetime format .
|
cosqa-train-18599
|
def get_now_utc_notz_datetime() -> datetime.datetime:
"""
Get the UTC time now, but with no timezone information,
in :class:`datetime.datetime` format.
"""
now = datetime.datetime.utcnow()
return now.replace(tzinfo=None)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.