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
|
---|---|---|---|---|---|
async def fetchall ( self ) -> Iterable [ sqlite3 . Row ] : return await self . _execute ( self . _cursor . fetchall )
| 0 |
python cursor iterate fetchall
|
Fetch all remaining rows .
|
cosqa-train-18300
|
async def fetchall(self) -> Iterable[sqlite3.Row]:
"""Fetch all remaining rows."""
return await self._execute(self._cursor.fetchall)
|
def _duplicates ( list_ ) : item_indices = { } for i , item in enumerate ( list_ ) : try : item_indices [ item ] . append ( i ) except KeyError : # First time seen item_indices [ item ] = [ i ] return item_indices
| 1 |
get duplicate index python
|
Return dict mapping item - > indices .
|
cosqa-train-18301
|
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 _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 |
turn string to a list in python
|
Convert a string to a list with sanitization .
|
cosqa-train-18302
|
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 list_to_str ( list , separator = ',' ) : list = [ str ( x ) for x in list ] return separator . join ( list )
| 1 |
elements of list to string python
|
>>> list = [ 0 0 7 ] >>> list_to_str ( list ) 0 0 7
|
cosqa-train-18303
|
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 dictlist_wipe_key ( dict_list : Iterable [ Dict ] , key : str ) -> None : for d in dict_list : d . pop ( key , None )
| 1 |
delete an entry out of a dictionary python
|
Process an iterable of dictionaries . For each dictionary d delete d [ key ] if it exists .
|
cosqa-train-18304
|
def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, delete
``d[key]`` if it exists.
"""
for d in dict_list:
d.pop(key, None)
|
def 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
| 0 |
python subsitute a variable with the variable text
|
Replace {{ variable - name }} with stored value .
|
cosqa-train-18305
|
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 is_empty_shape ( sh : ShExJ . Shape ) -> bool : return sh . closed is None and sh . expression is None and sh . extra is None and sh . semActs is None
| 0 |
check if object is not empty python
|
Determine whether sh has any value
|
cosqa-train-18306
|
def is_empty_shape(sh: ShExJ.Shape) -> bool:
""" Determine whether sh has any value """
return sh.closed is None and sh.expression is None and sh.extra is None and \
sh.semActs is None
|
def stretch ( iterable , n = 2 ) : times = range ( n ) for item in iterable : for i in times : yield item
| 1 |
python for n in arange loop numper of times
|
r Repeat each item in iterable n times .
|
cosqa-train-18307
|
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_unicode ( string ) : str_type = str ( type ( string ) ) if str_type . find ( 'str' ) > 0 or str_type . find ( 'unicode' ) > 0 : return True return False
| 1 |
python verify if type is string
|
Validates that the object itself is some kinda string
|
cosqa-train-18308
|
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 has_key ( cls , * args ) : key = args if len ( args ) > 1 else args [ 0 ] return key in cls . _instances
| 1 |
python if key doesn't exist create
|
Check whether flyweight object with specified key has already been created .
|
cosqa-train-18309
|
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 duplicates ( coll ) : return list ( set ( x for x in coll if coll . count ( x ) > 1 ) )
| 0 |
python remove duplicate in collection
|
Return the duplicated items in the given collection
|
cosqa-train-18310
|
def duplicates(coll):
"""Return the duplicated items in the given collection
:param coll: a collection
:returns: a list of the duplicated items in the collection
>>> duplicates([1, 1, 2, 3, 3, 4, 1, 1])
[1, 3]
"""
return list(set(x for x in coll if coll.count(x) > 1))
|
def proper_round ( n ) : return int ( n ) + ( n / abs ( n ) ) * int ( abs ( n - int ( n ) ) >= 0.5 ) if n != 0 else 0
| 1 |
round to closest defined value python
|
rounds float to closest int : rtype : int : param n : float
|
cosqa-train-18311
|
def proper_round(n):
"""
rounds float to closest int
:rtype: int
:param n: float
"""
return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0
|
def _dfs_cycle_detect ( graph , node , path , visited_nodes ) : visited_nodes . add ( node ) for target in graph [ node ] : if target in path : # cycle found => return current path return path + [ target ] else : return _dfs_cycle_detect ( graph , target , path + [ target ] , visited_nodes ) return None
| 1 |
python cycle detection dfs stack
|
search graph for cycle using DFS continuing from node path contains the list of visited nodes currently on the stack visited_nodes is the set of already visited nodes : param graph : : param node : : param path : : param visited_nodes : : return :
|
cosqa-train-18312
|
def _dfs_cycle_detect(graph, node, path, visited_nodes):
"""
search graph for cycle using DFS continuing from node
path contains the list of visited nodes currently on the stack
visited_nodes is the set of already visited nodes
:param graph:
:param node:
:param path:
:param visited_nodes:
:return:
"""
visited_nodes.add(node)
for target in graph[node]:
if target in path:
# cycle found => return current path
return path + [target]
else:
return _dfs_cycle_detect(graph, target, path + [target], visited_nodes)
return None
|
def read_set_from_file ( filename : str ) -> Set [ str ] : collection = set ( ) with open ( filename , 'r' ) as file_ : for line in file_ : collection . add ( line . rstrip ( ) ) return collection
| 0 |
how to create a set within a file in python
|
Extract a de - duped collection ( set ) of text from a file . Expected file format is one item per line .
|
cosqa-train-18313
|
def read_set_from_file(filename: str) -> Set[str]:
"""
Extract a de-duped collection (set) of text from a file.
Expected file format is one item per line.
"""
collection = set()
with open(filename, 'r') as file_:
for line in file_:
collection.add(line.rstrip())
return collection
|
def __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 |
replace a substring of characters in python
|
Replaces from a string ** input ** all the occurrences of some symbols according to mapping ** repls ** .
|
cosqa-train-18314
|
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 read_set_from_file ( filename : str ) -> Set [ str ] : collection = set ( ) with open ( filename , 'r' ) as file_ : for line in file_ : collection . add ( line . rstrip ( ) ) return collection
| 0 |
how to read a text file in python to a set
|
Extract a de - duped collection ( set ) of text from a file . Expected file format is one item per line .
|
cosqa-train-18315
|
def read_set_from_file(filename: str) -> Set[str]:
"""
Extract a de-duped collection (set) of text from a file.
Expected file format is one item per line.
"""
collection = set()
with open(filename, 'r') as file_:
for line in file_:
collection.add(line.rstrip())
return collection
|
def file_exists ( fname ) : try : return fname and os . path . exists ( fname ) and os . path . getsize ( fname ) > 0 except OSError : return False
| 0 |
how to tell if a directory is empty in python
|
Check if a file exists and is non - empty .
|
cosqa-train-18316
|
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
|
def do_quit ( self , _ : argparse . Namespace ) -> bool : self . _should_quit = True return self . _STOP_AND_EXIT
| 0 |
tell python to quit else rerun main function
|
Exit this application
|
cosqa-train-18317
|
def do_quit(self, _: argparse.Namespace) -> bool:
"""Exit this application"""
self._should_quit = True
return self._STOP_AND_EXIT
|
def collect_static ( ) -> bool : from django . core . management import execute_from_command_line # from django.conf import settings # if not os.listdir(settings.STATIC_ROOT): wf ( 'Collecting static files... ' , False ) execute_from_command_line ( [ './manage.py' , 'collectstatic' , '-c' , '--noinput' , '-v0' ] ) wf ( '[+]\n' ) return True
| 0 |
python django name 'static' is not defined
|
Runs Django collectstatic command in silent mode .
|
cosqa-train-18318
|
def collect_static() -> bool:
"""
Runs Django ``collectstatic`` command in silent mode.
:return: always ``True``
"""
from django.core.management import execute_from_command_line
# from django.conf import settings
# if not os.listdir(settings.STATIC_ROOT):
wf('Collecting static files... ', False)
execute_from_command_line(['./manage.py', 'collectstatic', '-c', '--noinput', '-v0'])
wf('[+]\n')
return True
|
def check_key ( self , key : str ) -> bool : keys = self . get_keys ( ) return key in keys
| 0 |
python checking if key exists in shelve
|
Checks if key exists in datastore . True if yes False if no .
|
cosqa-train-18319
|
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 safe_pow ( base , exp ) : if exp > MAX_EXPONENT : raise RuntimeError ( "Invalid exponent, max exponent is {}" . format ( MAX_EXPONENT ) ) return base ** exp
| 1 |
python 2^3 exponents using pow
|
safe version of pow
|
cosqa-train-18320
|
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 product ( * args , * * kwargs ) : p = [ [ ] ] for iterable in map ( tuple , args ) * kwargs . get ( "repeat" , 1 ) : p = [ x + [ y ] for x in p for y in iterable ] for p in p : yield tuple ( p )
| 0 |
python generate permutions of sequence
|
Yields all permutations with replacement : list ( product ( cat repeat = 2 )) = > [ ( c c ) ( c a ) ( c t ) ( a c ) ( a a ) ( a t ) ( t c ) ( t a ) ( t t ) ]
|
cosqa-train-18321
|
def product(*args, **kwargs):
""" Yields all permutations with replacement:
list(product("cat", repeat=2)) =>
[("c", "c"),
("c", "a"),
("c", "t"),
("a", "c"),
("a", "a"),
("a", "t"),
("t", "c"),
("t", "a"),
("t", "t")]
"""
p = [[]]
for iterable in map(tuple, args) * kwargs.get("repeat", 1):
p = [x + [y] for x in p for y in iterable]
for p in p:
yield tuple(p)
|
def _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 ( )
| 1 |
how do i skip a line without entering it in python
|
Skip a section
|
cosqa-train-18322
|
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 long_substr ( data ) : substr = '' if len ( data ) > 1 and len ( data [ 0 ] ) > 0 : for i in range ( len ( data [ 0 ] ) ) : for j in range ( len ( data [ 0 ] ) - i + 1 ) : if j > len ( substr ) and all ( data [ 0 ] [ i : i + j ] in x for x in data ) : substr = data [ 0 ] [ i : i + j ] elif len ( data ) == 1 : substr = data [ 0 ] return substr
| 1 |
python for longest substring in list
|
Return the longest common substring in a list of strings . Credit : http : // stackoverflow . com / questions / 2892931 / longest - common - substring - from - more - than - two - strings - python
|
cosqa-train-18323
|
def long_substr(data):
"""Return the longest common substring in a list of strings.
Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python
"""
substr = ''
if len(data) > 1 and len(data[0]) > 0:
for i in range(len(data[0])):
for j in range(len(data[0])-i+1):
if j > len(substr) and all(data[0][i:i+j] in x for x in data):
substr = data[0][i:i+j]
elif len(data) == 1:
substr = data[0]
return substr
|
def _parse_date ( string : str ) -> datetime . date : return datetime . datetime . strptime ( string , '%Y-%m-%d' ) . date ( )
| 1 |
python 3 parse iso date
|
Parse an ISO format date ( YYYY - mm - dd ) .
|
cosqa-train-18324
|
def _parse_date(string: str) -> datetime.date:
"""Parse an ISO format date (YYYY-mm-dd).
>>> _parse_date('1990-01-02')
datetime.date(1990, 1, 2)
"""
return datetime.datetime.strptime(string, '%Y-%m-%d').date()
|
def read_flat ( self ) : x , y , pixel , meta = self . read ( ) arraycode = 'BH' [ meta [ 'bitdepth' ] > 8 ] pixel = array ( arraycode , itertools . chain ( * pixel ) ) return x , y , pixel , meta
| 0 |
how to flatten image in python
|
Read a PNG file and decode it into flat row flat pixel format .
|
cosqa-train-18325
|
def read_flat(self):
"""
Read a PNG file and decode it into flat row flat pixel format.
Returns (*width*, *height*, *pixels*, *metadata*).
May use excessive memory.
`pixels` are returned in flat row flat pixel format.
See also the :meth:`read` method which returns pixels in the
more stream-friendly boxed row flat pixel format.
"""
x, y, pixel, meta = self.read()
arraycode = 'BH'[meta['bitdepth'] > 8]
pixel = array(arraycode, itertools.chain(*pixel))
return x, y, pixel, meta
|
def iter_lines ( file_like : Iterable [ str ] ) -> Generator [ str , None , None ] : for line in file_like : line = line . rstrip ( '\r\n' ) if line : yield line
| 0 |
readlines function in python deleting spaces
|
Helper for iterating only nonempty lines without line breaks
|
cosqa-train-18326
|
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 is_sqlatype_string ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . String )
| 0 |
how to check a column type in python
|
Is the SQLAlchemy column type a string type?
|
cosqa-train-18327
|
def is_sqlatype_string(coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type a string type?
"""
coltype = _coltype_to_typeengine(coltype)
return isinstance(coltype, sqltypes.String)
|
def import_by_path ( path : str ) -> Callable : module_path , _ , class_name = path . rpartition ( '.' ) return getattr ( import_module ( module_path ) , class_name )
| 1 |
python get function by full path
|
Import a class or function given it s absolute path .
|
cosqa-train-18328
|
def import_by_path(path: str) -> Callable:
"""Import a class or function given it's absolute path.
Parameters
----------
path:
Path to object to import
"""
module_path, _, class_name = path.rpartition('.')
return getattr(import_module(module_path), class_name)
|
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 occurence 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-18329
|
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 clean_column_names ( df : DataFrame ) -> DataFrame : f = df . copy ( ) f . columns = [ col . strip ( ) for col in f . columns ] return f
| 0 |
python trim white space on column names
|
Strip the whitespace from all column names in the given DataFrame and return the result .
|
cosqa-train-18330
|
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 sample_normal ( mean , var , rng ) : ret = numpy . sqrt ( var ) * rng . randn ( * mean . shape ) + mean return ret
| 0 |
how to random sample part of normal distribution in python
|
Sample from independent normal distributions
|
cosqa-train-18331
|
def sample_normal(mean, var, rng):
"""Sample from independent normal distributions
Each element is an independent normal distribution.
Parameters
----------
mean : numpy.ndarray
Means of the normal distribution. Shape --> (batch_num, sample_dim)
var : numpy.ndarray
Variance of the normal distribution. Shape --> (batch_num, sample_dim)
rng : numpy.random.RandomState
Returns
-------
ret : numpy.ndarray
The sampling result. Shape --> (batch_num, sample_dim)
"""
ret = numpy.sqrt(var) * rng.randn(*mean.shape) + mean
return ret
|
async def cursor ( self ) -> Cursor : return Cursor ( self , await self . _execute ( self . _conn . cursor ) )
| 1 |
python sqlite3 cursor context
|
Create an aiosqlite cursor wrapping a sqlite3 cursor object .
|
cosqa-train-18332
|
async def cursor(self) -> Cursor:
"""Create an aiosqlite cursor wrapping a sqlite3 cursor object."""
return Cursor(self, await self._execute(self._conn.cursor))
|
def is_line_in_file ( filename : str , line : str ) -> bool : assert "\n" not in line with open ( filename , "r" ) as file : for fileline in file : if fileline == line : return True return False
| 1 |
python test if line in file
|
Detects whether a line is present within a file .
|
cosqa-train-18333
|
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 decodebytes ( input ) : py_version = sys . version_info [ 0 ] if py_version >= 3 : return _decodebytes_py3 ( input ) return _decodebytes_py2 ( input )
| 0 |
python3 decode b string
|
Decode base64 string to byte array .
|
cosqa-train-18334
|
def decodebytes(input):
"""Decode base64 string to byte array."""
py_version = sys.version_info[0]
if py_version >= 3:
return _decodebytes_py3(input)
return _decodebytes_py2(input)
|
def most_significant_bit ( lst : np . ndarray ) -> int : return np . argwhere ( np . asarray ( lst ) == 1 ) [ 0 ] [ 0 ]
| 0 |
python index of the second largest value in a 2d array
|
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-18335
|
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 strings_to_integers ( strings : Iterable [ str ] ) -> Iterable [ int ] : return strings_to_ ( strings , lambda x : int ( float ( x ) ) )
| 1 |
turn list of str into int python
|
Convert a list of strings to a list of integers .
|
cosqa-train-18336
|
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 ensure_list ( iterable : Iterable [ A ] ) -> List [ A ] : if isinstance ( iterable , list ) : return iterable else : return list ( iterable )
| 0 |
python expected type 'list', got 'iterator' instead
|
An Iterable may be a list or a generator . This ensures we get a list without making an unnecessary copy .
|
cosqa-train-18337
|
def ensure_list(iterable: Iterable[A]) -> List[A]:
"""
An Iterable may be a list or a generator.
This ensures we get a list without making an unnecessary copy.
"""
if isinstance(iterable, list):
return iterable
else:
return list(iterable)
|
def csv_to_numpy ( string_like , dtype = None ) : # type: (str) -> np.array stream = StringIO ( string_like ) return np . genfromtxt ( stream , dtype = dtype , delimiter = ',' )
| 0 |
python numpy read array from csv
|
Convert a CSV object to a numpy array .
|
cosqa-train-18338
|
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 lint ( fmt = 'colorized' ) : if fmt == 'html' : outfile = 'pylint_report.html' local ( 'pylint -f %s davies > %s || true' % ( fmt , outfile ) ) local ( 'open %s' % outfile ) else : local ( 'pylint -f %s davies || true' % fmt )
| 0 |
how to use pylint for python 3
|
Run verbose PyLint on source . Optionally specify fmt = html for HTML output .
|
cosqa-train-18339
|
def lint(fmt='colorized'):
"""Run verbose PyLint on source. Optionally specify fmt=html for HTML output."""
if fmt == 'html':
outfile = 'pylint_report.html'
local('pylint -f %s davies > %s || true' % (fmt, outfile))
local('open %s' % outfile)
else:
local('pylint -f %s davies || true' % fmt)
|
def _protected_log ( x1 ) : with np . errstate ( divide = 'ignore' , invalid = 'ignore' ) : return np . where ( np . abs ( x1 ) > 0.001 , np . log ( np . abs ( x1 ) ) , 0. )
| 0 |
log distribution in python with a zero value
|
Closure of log for zero arguments .
|
cosqa-train-18340
|
def _protected_log(x1):
"""Closure of log for zero arguments."""
with np.errstate(divide='ignore', invalid='ignore'):
return np.where(np.abs(x1) > 0.001, np.log(np.abs(x1)), 0.)
|
def bfx ( value , msb , lsb ) : mask = bitmask ( ( msb , lsb ) ) return ( value & mask ) >> lsb
| 1 |
python right bitwise overload
|
!
|
cosqa-train-18341
|
def bfx(value, msb, lsb):
"""! @brief Extract a value from a bitfield."""
mask = bitmask((msb, lsb))
return (value & mask) >> lsb
|
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 with conditional function
|
Wrapper to make map () behave the same on Py2 and Py3 .
|
cosqa-train-18342
|
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 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 ( )
| 0 |
python check if path is file or folder
|
Verifies that a string path actually exists and is a file
|
cosqa-train-18343
|
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 _ ( f , x ) : return { k : v for k , v in x . items ( ) if f ( k , v ) }
| 1 |
python filter a dictionary by value
|
filter for dict note f should have signature : f :: key - > value - > bool
|
cosqa-train-18344
|
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 is_not_null ( df : DataFrame , col_name : str ) -> bool : if ( isinstance ( df , pd . DataFrame ) and col_name in df . columns and df [ col_name ] . notnull ( ) . any ( ) ) : return True else : return False
| 1 |
python if column is not null
|
Return True if the given DataFrame has a column of the given name ( string ) and there exists at least one non - NaN value in that column ; return False otherwise .
|
cosqa-train-18345
|
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 _rindex ( mylist : Sequence [ T ] , x : T ) -> int : return len ( mylist ) - mylist [ : : - 1 ] . index ( x ) - 1
| 0 |
determine the mth to last element of a sequence python
|
Index of the last occurrence of x in the sequence .
|
cosqa-train-18346
|
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 s3_get ( url : str , temp_file : IO ) -> None : s3_resource = boto3 . resource ( "s3" ) bucket_name , s3_path = split_s3_path ( url ) s3_resource . Bucket ( bucket_name ) . download_fileobj ( s3_path , temp_file )
| 1 |
how to read file from s3 bucket in python
|
Pull a file directly from S3 .
|
cosqa-train-18347
|
def s3_get(url: str, temp_file: IO) -> None:
"""Pull a file directly from S3."""
s3_resource = boto3.resource("s3")
bucket_name, s3_path = split_s3_path(url)
s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)
|
def find_first ( pattern : str , path : str ) -> str : try : return find ( pattern , path ) [ 0 ] except IndexError : log . critical ( '''Couldn't find "{}" in "{}"''' , pattern , path ) raise
| 1 |
how to get the first file of the path python glob
|
Finds first file in path whose filename matches pattern ( via : func : fnmatch . fnmatch ) or raises : exc : IndexError .
|
cosqa-train-18348
|
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 list_to_str ( list , separator = ',' ) : list = [ str ( x ) for x in list ] return separator . join ( list )
| 1 |
storing elements of a list to string python
|
>>> list = [ 0 0 7 ] >>> list_to_str ( list ) 0 0 7
|
cosqa-train-18349
|
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 get_timezone ( ) -> Tuple [ datetime . tzinfo , str ] : dt = get_datetime_now ( ) . astimezone ( ) tzstr = dt . strftime ( "%z" ) tzstr = tzstr [ : - 2 ] + ":" + tzstr [ - 2 : ] return dt . tzinfo , tzstr
| 1 |
python, get timezone info in python
|
Discover the current time zone and it s standard string representation ( for source { d } ) .
|
cosqa-train-18350
|
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 bytes_hack ( buf ) : ub = None if sys . version_info > ( 3 , ) : ub = buf else : ub = bytes ( buf ) return ub
| 1 |
diffrence bytes bwtween python2 and python3
|
Hacky workaround for old installs of the library on systems without python - future that were keeping the 2to3 update from working after auto - update .
|
cosqa-train-18351
|
def bytes_hack(buf):
"""
Hacky workaround for old installs of the library on systems without python-future that were
keeping the 2to3 update from working after auto-update.
"""
ub = None
if sys.version_info > (3,):
ub = buf
else:
ub = bytes(buf)
return ub
|
def is_line_in_file ( filename : str , line : str ) -> bool : assert "\n" not in line with open ( filename , "r" ) as file : for fileline in file : if fileline == line : return True return False
| 1 |
check if line in file python
|
Detects whether a line is present within a file .
|
cosqa-train-18352
|
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 samefile ( a : str , b : str ) -> bool : try : return os . path . samefile ( a , b ) except OSError : return os . path . normpath ( a ) == os . path . normpath ( b )
| 1 |
python see if 2 paths equal
|
Check if two pathes represent the same file .
|
cosqa-train-18353
|
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 _parse_tuple_string ( argument ) : if isinstance ( argument , str ) : return tuple ( int ( p . strip ( ) ) for p in argument . split ( ',' ) ) return argument
| 1 |
splitting a tuple into variables python
|
Return a tuple from parsing a b c d - > ( a b c d )
|
cosqa-train-18354
|
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 _rindex ( mylist : Sequence [ T ] , x : T ) -> int : return len ( mylist ) - mylist [ : : - 1 ] . index ( x ) - 1
| 0 |
python get the last index of a slice
|
Index of the last occurrence of x in the sequence .
|
cosqa-train-18355
|
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 are_token_parallel ( sequences : Sequence [ Sized ] ) -> bool : if not sequences or len ( sequences ) == 1 : return True return all ( len ( s ) == len ( sequences [ 0 ] ) for s in sequences )
| 0 |
check if a list is sequential python
|
Returns True if all sequences in the list have the same length .
|
cosqa-train-18356
|
def are_token_parallel(sequences: Sequence[Sized]) -> bool:
"""
Returns True if all sequences in the list have the same length.
"""
if not sequences or len(sequences) == 1:
return True
return all(len(s) == len(sequences[0]) for s in sequences)
|
def 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 to get the uid of a process
|
Return local machine unique identifier .
|
cosqa-train-18357
|
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 url_host ( url : str ) -> str : from urllib . parse import urlparse res = urlparse ( url ) return res . netloc . split ( ':' ) [ 0 ] if res . netloc else ''
| 1 |
parse a url in python and get the hostname
|
Parses hostname from URL . : param url : URL : return : hostname
|
cosqa-train-18358
|
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 _check_update_ ( self ) : try : data = requests . get ( "https://pypi.python.org/pypi/jira/json" , timeout = 2.001 ) . json ( ) released_version = data [ 'info' ] [ 'version' ] if parse_version ( released_version ) > parse_version ( __version__ ) : warnings . warn ( "You are running an outdated version of JIRA Python %s. Current version is %s. Do not file any bugs against older versions." % ( __version__ , released_version ) ) except requests . RequestException : pass except Exception as e : logging . warning ( e )
| 0 |
jira python issue fixversion
|
Check if the current version of the library is outdated .
|
cosqa-train-18359
|
def _check_update_(self):
"""Check if the current version of the library is outdated."""
try:
data = requests.get("https://pypi.python.org/pypi/jira/json", timeout=2.001).json()
released_version = data['info']['version']
if parse_version(released_version) > parse_version(__version__):
warnings.warn(
"You are running an outdated version of JIRA Python %s. Current version is %s. Do not file any bugs against older versions." % (
__version__, released_version))
except requests.RequestException:
pass
except Exception as e:
logging.warning(e)
|
def last_location_of_minimum ( x ) : x = np . asarray ( x ) return 1.0 - np . argmin ( x [ : : - 1 ] ) / len ( x ) if len ( x ) > 0 else np . NaN
| 0 |
finding the minimum in a vector in python
|
Returns the last location of the minimal value of x . The position is calculated relatively to the length of x .
|
cosqa-train-18360
|
def last_location_of_minimum(x):
"""
Returns the last location of the minimal 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
"""
x = np.asarray(x)
return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN
|
def __gt__ ( self , other ) : if isinstance ( other , Address ) : return str ( self ) > str ( other ) raise TypeError
| 0 |
greater than comparison python3
|
Test for greater than .
|
cosqa-train-18361
|
def __gt__(self, other):
"""Test for greater than."""
if isinstance(other, Address):
return str(self) > str(other)
raise TypeError
|
def last ( self ) : if self . _last is UNDETERMINED : # not necessarily the last one... self . _last = self . sdat . tseries . index [ - 1 ] return self [ self . _last ]
| 1 |
last item of series in python
|
Last time step available .
|
cosqa-train-18362
|
def last(self):
"""Last time step available.
Example:
>>> sdat = StagyyData('path/to/run')
>>> assert(sdat.steps.last is sdat.steps[-1])
"""
if self._last is UNDETERMINED:
# not necessarily the last one...
self._last = self.sdat.tseries.index[-1]
return self[self._last]
|
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 )
| 0 |
python parser call from script
|
docstring for argparse
|
cosqa-train-18363
|
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 _get_or_default ( mylist , i , default = None ) : if i >= len ( mylist ) : return default else : return mylist [ i ]
| 0 |
get with default value python
|
return list item number or default if don t exist
|
cosqa-train-18364
|
def _get_or_default(mylist, i, default=None):
"""return list item number, or default if don't exist"""
if i >= len(mylist):
return default
else :
return mylist[i]
|
def 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 )
| 0 |
how to use mulde argparse to input parmeters into python program
|
docstring for argparse
|
cosqa-train-18365
|
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 right_replace ( string , old , new , count = 1 ) : if not string : return string return new . join ( string . rsplit ( old , count ) )
| 0 |
python replace string until no further replaces made
|
Right replaces count occurrences of old with new in string . For example ::
|
cosqa-train-18366
|
def right_replace(string, old, new, count=1):
"""
Right replaces ``count`` occurrences of ``old`` with ``new`` in ``string``.
For example::
right_replace('one_two_two', 'two', 'three') -> 'one_two_three'
"""
if not string:
return string
return new.join(string.rsplit(old, count))
|
def gcd_float ( numbers , tol = 1e-8 ) : def pair_gcd_tol ( a , b ) : """Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
""" while b > tol : a , b = b , a % b return a n = numbers [ 0 ] for i in numbers : n = pair_gcd_tol ( n , i ) return n
| 1 |
greatest common divisor of 3 numbers python
|
Returns the greatest common divisor for a sequence of numbers . Uses a numerical tolerance so can be used on floats
|
cosqa-train-18367
|
def gcd_float(numbers, tol=1e-8):
"""
Returns the greatest common divisor for a sequence of numbers.
Uses a numerical tolerance, so can be used on floats
Args:
numbers: Sequence of numbers.
tol: Numerical tolerance
Returns:
(int) Greatest common divisor of numbers.
"""
def pair_gcd_tol(a, b):
"""Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b > tol:
a, b = b, a % b
return a
n = numbers[0]
for i in numbers:
n = pair_gcd_tol(n, i)
return n
|
def de_duplicate ( items ) : result = [ ] for item in items : if item not in result : result . append ( item ) return result
| 0 |
replace duplicare in python list
|
Remove any duplicate item preserving order
|
cosqa-train-18368
|
def de_duplicate(items):
"""Remove any duplicate item, preserving order
>>> de_duplicate([1, 2, 1, 2])
[1, 2]
"""
result = []
for item in items:
if item not in result:
result.append(item)
return result
|
def __replace_all ( repls : dict , input : str ) -> str : return re . sub ( '|' . join ( re . escape ( key ) for key in repls . keys ( ) ) , lambda k : repls [ k . group ( 0 ) ] , input )
| 0 |
python method to replace multiple characters
|
Replaces from a string ** input ** all the occurrences of some symbols according to mapping ** repls ** .
|
cosqa-train-18369
|
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 version ( ) : OPENJPEG . opj_version . restype = ctypes . c_char_p library_version = OPENJPEG . opj_version ( ) if sys . hexversion >= 0x03000000 : return library_version . decode ( 'utf-8' ) else : return library_version
| 0 |
make jpeg default in python
|
Wrapper for opj_version library routine .
|
cosqa-train-18370
|
def version():
"""Wrapper for opj_version library routine."""
OPENJPEG.opj_version.restype = ctypes.c_char_p
library_version = OPENJPEG.opj_version()
if sys.hexversion >= 0x03000000:
return library_version.decode('utf-8')
else:
return library_version
|
def uppercase_chars ( string : any ) -> str : return '' . join ( [ c if c . isupper ( ) else '' for c in str ( string ) ] )
| 1 |
making a string all uppercase python
|
Return all ( and only ) the uppercase chars in the given string .
|
cosqa-train-18371
|
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 get_now_sql_datetime ( ) : ## > IMPORTS ## from datetime import datetime , date , time now = datetime . now ( ) now = now . strftime ( "%Y-%m-%dT%H:%M:%S" ) return now
| 1 |
how to pass the current time as variable in python to sql
|
* A datetime stamp in MySQL format : YYYY - MM - DDTHH : MM : SS *
|
cosqa-train-18372
|
def get_now_sql_datetime():
"""
*A datetime stamp in MySQL format: ``YYYY-MM-DDTHH:MM:SS``*
**Return:**
- ``now`` -- current time and date in MySQL format
**Usage:**
.. code-block:: python
from fundamentals import times
now = times.get_now_sql_datetime()
print now
# OUT: 2016-03-18T11:08:23
"""
## > IMPORTS ##
from datetime import datetime, date, time
now = datetime.now()
now = now.strftime("%Y-%m-%dT%H:%M:%S")
return now
|
def assert_equal ( first , second , msg_fmt = "{msg}" ) : if isinstance ( first , dict ) and isinstance ( second , dict ) : assert_dict_equal ( first , second , msg_fmt ) elif not first == second : msg = "{!r} != {!r}" . format ( first , second ) fail ( msg_fmt . format ( msg = msg , first = first , second = second ) )
| 0 |
python test assert not equal
|
Fail unless first equals second as determined by the == operator .
|
cosqa-train-18373
|
def assert_equal(first, second, msg_fmt="{msg}"):
"""Fail unless first equals second, as determined by the '==' operator.
>>> assert_equal(5, 5.0)
>>> assert_equal("Hello World!", "Goodbye!")
Traceback (most recent call last):
...
AssertionError: 'Hello World!' != 'Goodbye!'
The following msg_fmt arguments are supported:
* msg - the default error message
* first - the first argument
* second - the second argument
"""
if isinstance(first, dict) and isinstance(second, dict):
assert_dict_equal(first, second, msg_fmt)
elif not first == second:
msg = "{!r} != {!r}".format(first, second)
fail(msg_fmt.format(msg=msg, first=first, second=second))
|
def right_replace ( string , old , new , count = 1 ) : if not string : return string return new . join ( string . rsplit ( old , count ) )
| 0 |
replace is not working in python
|
Right replaces count occurrences of old with new in string . For example ::
|
cosqa-train-18374
|
def right_replace(string, old, new, count=1):
"""
Right replaces ``count`` occurrences of ``old`` with ``new`` in ``string``.
For example::
right_replace('one_two_two', 'two', 'three') -> 'one_two_three'
"""
if not string:
return string
return new.join(string.rsplit(old, count))
|
def is_builtin_object ( node : astroid . node_classes . NodeNG ) -> bool : return node and node . root ( ) . name == BUILTINS_NAME
| 0 |
how to check if a node is a leaf in python
|
Returns True if the given node is an object from the __builtin__ module .
|
cosqa-train-18375
|
def is_builtin_object(node: astroid.node_classes.NodeNG) -> bool:
"""Returns True if the given node is an object from the __builtin__ module."""
return node and node.root().name == BUILTINS_NAME
|
def iprotate ( l , steps = 1 ) : if len ( l ) : steps %= len ( l ) if steps : firstPart = l [ : steps ] del l [ : steps ] l . extend ( firstPart ) return l
| 1 |
how to rotate a list of numbers in python
|
r Like rotate but modifies l in - place .
|
cosqa-train-18376
|
def iprotate(l, steps=1):
r"""Like rotate, but modifies `l` in-place.
>>> l = [1,2,3]
>>> iprotate(l) is l
True
>>> l
[2, 3, 1]
>>> iprotate(iprotate(l, 2), -3)
[1, 2, 3]
"""
if len(l):
steps %= len(l)
if steps:
firstPart = l[:steps]
del l[:steps]
l.extend(firstPart)
return l
|
def bfx ( value , msb , lsb ) : mask = bitmask ( ( msb , lsb ) ) return ( value & mask ) >> lsb
| 1 |
python bitwise first bit on
|
!
|
cosqa-train-18377
|
def bfx(value, msb, lsb):
"""! @brief Extract a value from a bitfield."""
mask = bitmask((msb, lsb))
return (value & mask) >> lsb
|
def remove_blank_lines ( string ) : return "\n" . join ( line for line in string . split ( "\n" ) if len ( line . strip ( ) ) )
| 1 |
string remove the last blank python
|
Removes all blank lines in @string
|
cosqa-train-18378
|
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 capitalize ( string ) : if not string : return string if len ( string ) == 1 : return string . upper ( ) return string [ 0 ] . upper ( ) + string [ 1 : ] . lower ( )
| 0 |
what code in python capitalizes the first letter of the word
|
Capitalize a sentence .
|
cosqa-train-18379
|
def capitalize(string):
"""Capitalize a sentence.
Parameters
----------
string : `str`
String to capitalize.
Returns
-------
`str`
Capitalized string.
Examples
--------
>>> capitalize('worD WORD WoRd')
'Word word word'
"""
if not string:
return string
if len(string) == 1:
return string.upper()
return string[0].upper() + string[1:].lower()
|
def min ( self ) : res = self . _qexec ( "min(%s)" % self . _name ) if len ( res ) > 0 : self . _min = res [ 0 ] [ 0 ] return self . _min
| 1 |
python get min value from column
|
: returns the minimum of the column
|
cosqa-train-18380
|
def min(self):
"""
:returns the minimum of the column
"""
res = self._qexec("min(%s)" % self._name)
if len(res) > 0:
self._min = res[0][0]
return self._min
|
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 last day in month
|
Get the last weekday in a given month . e . g :
|
cosqa-train-18381
|
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 checksum ( path ) : hasher = hashlib . sha1 ( ) with open ( path , 'rb' ) as stream : buf = stream . read ( BLOCKSIZE ) while len ( buf ) > 0 : hasher . update ( buf ) buf = stream . read ( BLOCKSIZE ) return hasher . hexdigest ( )
| 1 |
generating a checksum of a file python
|
Calculcate checksum for a file .
|
cosqa-train-18382
|
def checksum(path):
"""Calculcate checksum for a file."""
hasher = hashlib.sha1()
with open(path, 'rb') as stream:
buf = stream.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
buf = stream.read(BLOCKSIZE)
return hasher.hexdigest()
|
def fib ( n ) : assert n > 0 a , b = 1 , 1 for i in range ( n - 1 ) : a , b = b , a + b return a
| 0 |
fibonacci sequence python lambda
|
Fibonacci example function
|
cosqa-train-18383
|
def fib(n):
"""Fibonacci example function
Args:
n (int): integer
Returns:
int: n-th Fibonacci number
"""
assert n > 0
a, b = 1, 1
for i in range(n - 1):
a, b = b, a + b
return a
|
def get_days_in_month ( year : int , month : int ) -> int : month_range = calendar . monthrange ( year , month ) return month_range [ 1 ]
| 1 |
python program to determine days number in a month in a year
|
Returns number of days in the given month . 1 - based numbers as arguments . i . e . November = 11
|
cosqa-train-18384
|
def get_days_in_month(year: int, month: int) -> int:
""" Returns number of days in the given month.
1-based numbers as arguments. i.e. November = 11 """
month_range = calendar.monthrange(year, month)
return month_range[1]
|
def has_key ( cls , * args ) : key = args if len ( args ) > 1 else args [ 0 ] return key in cls . _instances
| 0 |
python get key if it exists
|
Check whether flyweight object with specified key has already been created .
|
cosqa-train-18385
|
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 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 dateutil get last day of this month
|
Get the last weekday in a given month . e . g :
|
cosqa-train-18386
|
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 string ( value ) -> str : return system_json . dumps ( Json ( value ) . safe_object ( ) , ensure_ascii = False )
| 0 |
change json text to string python
|
string dict / object / value to JSON
|
cosqa-train-18387
|
def string(value) -> str:
""" string dict/object/value to JSON """
return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)
|
def pairwise ( iterable ) : first , second = tee ( iterable ) next ( second , None ) return zip ( first , second )
| 0 |
python itertools tuple for every two elements
|
From itertools cookbook . [ a b c ... ] - > ( a b ) ( b c ) ...
|
cosqa-train-18388
|
def pairwise(iterable):
"""From itertools cookbook. [a, b, c, ...] -> (a, b), (b, c), ..."""
first, second = tee(iterable)
next(second, None)
return zip(first, second)
|
def to_graphviz ( graph ) : ret = [ 'digraph g {' ] vertices = [ ] node_ids = dict ( [ ( name , 'node' + idx ) for ( idx , name ) in enumerate ( list ( graph ) ) ] ) for node in list ( graph ) : ret . append ( ' "%s" [label="%s"];' % ( node_ids [ node ] , node ) ) for target in graph [ node ] : vertices . append ( ' "%s" -> "%s";' % ( node_ids [ node ] , node_ids [ target ] ) ) ret += vertices ret . append ( '}' ) return '\n' . join ( ret )
| 0 |
python3 dict to graphviz nodes
|
cosqa-train-18389
|
def to_graphviz(graph):
"""
:param graph:
:return:
"""
ret = ['digraph g {']
vertices = []
node_ids = dict([(name, 'node' + idx) for (idx, name) in enumerate(list(graph))])
for node in list(graph):
ret.append(' "%s" [label="%s"];' % (node_ids[node], node))
for target in graph[node]:
vertices.append(' "%s" -> "%s";' % (node_ids[node], node_ids[target]))
ret += vertices
ret.append('}')
return '\n'.join(ret)
|
|
def file_or_stdin ( ) -> Callable : def parse ( path ) : if path is None or path == "-" : return sys . stdin else : return data_io . smart_open ( path ) return parse
| 1 |
python open file or stdin
|
Returns a file descriptor from stdin or opening a file from a given path .
|
cosqa-train-18390
|
def file_or_stdin() -> Callable:
"""
Returns a file descriptor from stdin or opening a file from a given path.
"""
def parse(path):
if path is None or path == "-":
return sys.stdin
else:
return data_io.smart_open(path)
return parse
|
def get_file_extension ( filename ) : filename_x = filename . split ( '.' ) if len ( filename_x ) > 1 : if filename_x [ - 1 ] . strip ( ) is not '' : return filename_x [ - 1 ] return None
| 1 |
python how to get the file extension
|
Return the extension if the filename has it . None if not .
|
cosqa-train-18391
|
def get_file_extension(filename):
""" Return the extension if the filename has it. None if not.
:param filename: The filename.
:return: Extension or None.
"""
filename_x = filename.split('.')
if len(filename_x) > 1:
if filename_x[-1].strip() is not '':
return filename_x[-1]
return None
|
def truncate ( value : Decimal , n_digits : int ) -> Decimal : return Decimal ( math . trunc ( value * ( 10 ** n_digits ) ) ) / ( 10 ** n_digits )
| 0 |
how to cut decimals in python
|
Truncates a value to a number of decimals places
|
cosqa-train-18392
|
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 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_
| 1 |
python how to combine a list to make a string
|
Turn a list into a comma - and / or and - separated string .
|
cosqa-train-18393
|
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 normalize_column_names ( df ) : columns = df . columns if hasattr ( df , 'columns' ) else df columns = [ c . lower ( ) . replace ( ' ' , '_' ) for c in columns ] return columns
| 1 |
python, remove special characters [spaces,'(', and ')'] from column names
|
r Clean up whitespace in column names . See better version at pugnlp . clean_columns
|
cosqa-train-18394
|
def normalize_column_names(df):
r""" Clean up whitespace in column names. See better version at `pugnlp.clean_columns`
>>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['Hello World', 'not here'])
>>> normalize_column_names(df)
['hello_world', 'not_here']
"""
columns = df.columns if hasattr(df, 'columns') else df
columns = [c.lower().replace(' ', '_') for c in columns]
return columns
|
def _width_is_big_enough ( image , width ) : if width > image . size [ 0 ] : raise ImageSizeError ( image . size [ 0 ] , width )
| 0 |
how to check image pixel size python
|
Check that the image width is superior to width
|
cosqa-train-18395
|
def _width_is_big_enough(image, width):
"""Check that the image width is superior to `width`"""
if width > image.size[0]:
raise ImageSizeError(image.size[0], width)
|
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 python bulk stackoverflow
|
Bulk load docs
|
cosqa-train-18396
|
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 read_text_from_file ( path : str ) -> str : with open ( path ) as text_file : content = text_file . read ( ) return content
| 0 |
how to display contents a text file in python
|
Reads text file contents
|
cosqa-train-18397
|
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 detect_model_num ( string ) : match = re . match ( MODEL_NUM_REGEX , string ) if match : return int ( match . group ( ) ) return None
| 0 |
python get the model number
|
Takes a string related to a model name and extract its model number .
|
cosqa-train-18398
|
def detect_model_num(string):
"""Takes a string related to a model name and extract its model number.
For example:
'000000-bootstrap.index' => 0
"""
match = re.match(MODEL_NUM_REGEX, string)
if match:
return int(match.group())
return None
|
def normcdf ( x , log = False ) : y = np . atleast_1d ( x ) . copy ( ) flib . normcdf ( y ) if log : if ( y > 0 ) . all ( ) : return np . log ( y ) return - np . inf return y
| 1 |
how to do normalcdf in python
|
Normal cumulative density function .
|
cosqa-train-18399
|
def normcdf(x, log=False):
"""Normal cumulative density function."""
y = np.atleast_1d(x).copy()
flib.normcdf(y)
if log:
if (y>0).all():
return np.log(y)
return -np.inf
return y
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.