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 remove_leading ( needle , haystack ) : if haystack [ : len ( needle ) ] == needle : return haystack [ len ( needle ) : ] return haystack | 0 | how to discard first text of a string in pythong | Remove leading needle string ( if exists ) . | cosqa-train-19700 | def remove_leading(needle, haystack):
"""Remove leading needle string (if exists).
>>> remove_leading('Test', 'TestThisAndThat')
'ThisAndThat'
>>> remove_leading('Test', 'ArbitraryName')
'ArbitraryName'
"""
if haystack[:len(needle)] == needle:
return haystack[len(needle):]
return haystack |
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 read csv to numpy array | Convert a CSV object to a numpy array . | cosqa-train-19701 | 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 inner ( tensor0 : BKTensor , tensor1 : BKTensor ) -> BKTensor : # Note: Relying on fact that vdot flattens arrays return np . vdot ( tensor0 , tensor1 ) | 1 | python tensor dot product | Return the inner product between two tensors | cosqa-train-19702 | def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor:
"""Return the inner product between two tensors"""
# Note: Relying on fact that vdot flattens arrays
return np.vdot(tensor0, tensor1) |
def memory_full ( ) : current_process = psutil . Process ( os . getpid ( ) ) return ( current_process . memory_percent ( ) > config . MAXIMUM_CACHE_MEMORY_PERCENTAGE ) | 0 | python check memory usage stackoverflow | Check if the memory is too full for further caching . | cosqa-train-19703 | def memory_full():
"""Check if the memory is too full for further caching."""
current_process = psutil.Process(os.getpid())
return (current_process.memory_percent() >
config.MAXIMUM_CACHE_MEMORY_PERCENTAGE) |
def _kbhit_unix ( ) -> bool : dr , dw , de = select . select ( [ sys . stdin ] , [ ] , [ ] , 0 ) return dr != [ ] | 1 | python unix detect key press | Under UNIX : is a keystroke available? | cosqa-train-19704 | def _kbhit_unix() -> bool:
"""
Under UNIX: is a keystroke available?
"""
dr, dw, de = select.select([sys.stdin], [], [], 0)
return dr != [] |
def _rindex ( mylist : Sequence [ T ] , x : T ) -> int : return len ( mylist ) - mylist [ : : - 1 ] . index ( x ) - 1 | 0 | python get last index of character | Index of the last occurrence of x in the sequence . | cosqa-train-19705 | 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 debugTreePrint ( node , pfx = "->" ) : print pfx , node . item for c in node . children : debugTreePrint ( c , " " + pfx ) | 0 | printing a tree recursively python | Purely a debugging aid : Ascii - art picture of a tree descended from node | cosqa-train-19706 | def debugTreePrint(node,pfx="->"):
"""Purely a debugging aid: Ascii-art picture of a tree descended from node"""
print pfx,node.item
for c in node.children:
debugTreePrint(c," "+pfx) |
def 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 string to a date | Creates a datetime from GnuCash 2 . 6 date string | cosqa-train-19707 | 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 _check_whitespace ( string ) : if string . count ( ' ' ) + string . count ( '\t' ) + string . count ( '\n' ) > 0 : raise ValueError ( INSTRUCTION_HAS_WHITESPACE ) | 1 | python check for trailing whitespace | Make sure thre is no whitespace in the given string . Will raise a ValueError if whitespace is detected | cosqa-train-19708 | def _check_whitespace(string):
"""
Make sure thre is no whitespace in the given string. Will raise a
ValueError if whitespace is detected
"""
if string.count(' ') + string.count('\t') + string.count('\n') > 0:
raise ValueError(INSTRUCTION_HAS_WHITESPACE) |
def 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 | most frequent substring of strings, python | 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-19709 | 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 |
async def async_run ( self ) -> None : self . main_task = self . loop . create_task ( self . main ( ) ) await self . main_task | 1 | python asyncio start server connection refuse | Asynchronously run the worker does not close connections . Useful when testing . | cosqa-train-19710 | async def async_run(self) -> None:
"""
Asynchronously run the worker, does not close connections. Useful when testing.
"""
self.main_task = self.loop.create_task(self.main())
await self.main_task |
async def async_run ( self ) -> None : self . main_task = self . loop . create_task ( self . main ( ) ) await self . main_task | 0 | python test async coroutine is running | Asynchronously run the worker does not close connections . Useful when testing . | cosqa-train-19711 | async def async_run(self) -> None:
"""
Asynchronously run the worker, does not close connections. Useful when testing.
"""
self.main_task = self.loop.create_task(self.main())
await self.main_task |
def _duplicates ( list_ ) : item_indices = { } for i , item in enumerate ( list_ ) : try : item_indices [ item ] . append ( i ) except KeyError : # First time seen item_indices [ item ] = [ i ] return item_indices | 0 | create dictionary of indices in list in python | Return dict mapping item - > indices . | cosqa-train-19712 | def _duplicates(list_):
"""Return dict mapping item -> indices."""
item_indices = {}
for i, item in enumerate(list_):
try:
item_indices[item].append(i)
except KeyError: # First time seen
item_indices[item] = [i]
return item_indices |
def get_column_names ( engine : Engine , tablename : str ) -> List [ str ] : return [ info . name for info in gen_columns_info ( engine , tablename ) ] | 1 | how to get table names from dynamo in python | Get all the database column names for the specified table . | cosqa-train-19713 | def get_column_names(engine: Engine, tablename: str) -> List[str]:
"""
Get all the database column names for the specified table.
"""
return [info.name for info in gen_columns_info(engine, tablename)] |
def 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 | 0 | largest common substring python | 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-19714 | 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 _kbhit_unix ( ) -> bool : dr , dw , de = select . select ( [ sys . stdin ] , [ ] , [ ] , 0 ) return dr != [ ] | 1 | python 3 detect keyboard press linux | Under UNIX : is a keystroke available? | cosqa-train-19715 | def _kbhit_unix() -> bool:
"""
Under UNIX: is a keystroke available?
"""
dr, dw, de = select.select([sys.stdin], [], [], 0)
return dr != [] |
def bfx ( value , msb , lsb ) : mask = bitmask ( ( msb , lsb ) ) return ( value & mask ) >> lsb | 0 | how to do bitwise or on a string of bits in python | ! | cosqa-train-19716 | def bfx(value, msb, lsb):
"""! @brief Extract a value from a bitfield."""
mask = bitmask((msb, lsb))
return (value & mask) >> lsb |
def remove_empty_text ( utterances : List [ Utterance ] ) -> List [ Utterance ] : return [ utter for utter in utterances if utter . text . strip ( ) != "" ] | 1 | python exclude words from list | Remove empty utterances from a list of utterances Args : utterances : The list of utterance we are processing | cosqa-train-19717 | def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:
"""Remove empty utterances from a list of utterances
Args:
utterances: The list of utterance we are processing
"""
return [utter for utter in utterances if utter.text.strip() != ""] |
def dotproduct ( X , Y ) : return sum ( [ x * y for x , y in zip ( X , Y ) ] ) | 1 | dot product of two vectors python sympy | Return the sum of the element - wise product of vectors x and y . >>> dotproduct ( [ 1 2 3 ] [ 1000 100 10 ] ) 1230 | cosqa-train-19718 | def dotproduct(X, Y):
"""Return the sum of the element-wise product of vectors x and y.
>>> dotproduct([1, 2, 3], [1000, 100, 10])
1230
"""
return sum([x * y for x, y in zip(X, Y)]) |
def __remove_trailing_zeros ( self , collection ) : index = len ( collection ) - 1 while index >= 0 and collection [ index ] == 0 : index -= 1 return collection [ : index + 1 ] | 1 | reduce trailing zeros python | Removes trailing zeroes from indexable collection of numbers | cosqa-train-19719 | 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 indexes_equal ( a : Index , b : Index ) -> bool : return str ( a ) == str ( b ) | 0 | check if two string equal python | Are two indexes equal? Checks by comparing str () versions of them . ( AM UNSURE IF THIS IS ENOUGH . ) | cosqa-train-19720 | 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 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 | 1 | create a set python from a text file | Extract a de - duped collection ( set ) of text from a file . Expected file format is one item per line . | cosqa-train-19721 | 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 most_frequent ( lst ) : lst = lst [ : ] highest_freq = 0 most_freq = None for val in unique ( lst ) : if lst . count ( val ) > highest_freq : most_freq = val highest_freq = lst . count ( val ) return most_freq | 1 | most frequent items in list python | Returns the item that appears most frequently in the given list . | cosqa-train-19722 | def most_frequent(lst):
"""
Returns the item that appears most frequently in the given list.
"""
lst = lst[:]
highest_freq = 0
most_freq = None
for val in unique(lst):
if lst.count(val) > highest_freq:
most_freq = val
highest_freq = lst.count(val)
return most_freq |
def availability_pdf ( ) -> bool : pdftotext = tools [ 'pdftotext' ] if pdftotext : return True elif pdfminer : log . warning ( "PDF conversion: pdftotext missing; " "using pdfminer (less efficient)" ) return True else : return False | 0 | pdf to text converter returning me invalid pdf file python | Is a PDF - to - text tool available? | cosqa-train-19723 | def availability_pdf() -> bool:
"""
Is a PDF-to-text tool available?
"""
pdftotext = tools['pdftotext']
if pdftotext:
return True
elif pdfminer:
log.warning("PDF conversion: pdftotext missing; "
"using pdfminer (less efficient)")
return True
else:
return False |
def snake_to_camel ( s : str ) -> str : fragments = s . split ( '_' ) return fragments [ 0 ] + '' . join ( x . title ( ) for x in fragments [ 1 : ] ) | 1 | how to capitalize all the characters in python | Convert string from snake case to camel case . | cosqa-train-19724 | 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 truncate ( value : Decimal , n_digits : int ) -> Decimal : return Decimal ( math . trunc ( value * ( 10 ** n_digits ) ) ) / ( 10 ** n_digits ) | 1 | truncate variable to three decimals python | Truncates a value to a number of decimals places | cosqa-train-19725 | 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 file_exists ( fname ) : try : return fname and os . path . exists ( fname ) and os . path . getsize ( fname ) > 0 except OSError : return False | 0 | check if a directory is empty python | Check if a file exists and is non - empty . | cosqa-train-19726 | 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 CheckDisjointCalendars ( self ) : # TODO: Do an exact check here. a_service_periods = self . feed_merger . a_schedule . GetServicePeriodList ( ) b_service_periods = self . feed_merger . b_schedule . GetServicePeriodList ( ) for a_service_period in a_service_periods : a_start , a_end = a_service_period . GetDateRange ( ) for b_service_period in b_service_periods : b_start , b_end = b_service_period . GetDateRange ( ) overlap_start = max ( a_start , b_start ) overlap_end = min ( a_end , b_end ) if overlap_end >= overlap_start : return False return True | 0 | python get overlap between two schedules | Check whether any old service periods intersect with any new ones . | cosqa-train-19727 | def CheckDisjointCalendars(self):
"""Check whether any old service periods intersect with any new ones.
This is a rather coarse check based on
transitfeed.SevicePeriod.GetDateRange.
Returns:
True if the calendars are disjoint or False if not.
"""
# TODO: Do an exact check here.
a_service_periods = self.feed_merger.a_schedule.GetServicePeriodList()
b_service_periods = self.feed_merger.b_schedule.GetServicePeriodList()
for a_service_period in a_service_periods:
a_start, a_end = a_service_period.GetDateRange()
for b_service_period in b_service_periods:
b_start, b_end = b_service_period.GetDateRange()
overlap_start = max(a_start, b_start)
overlap_end = min(a_end, b_end)
if overlap_end >= overlap_start:
return False
return True |
def top ( self , topn = 10 ) : return [ self [ i ] for i in argsort ( list ( zip ( * self ) ) [ 1 ] ) [ : : - 1 ] [ : topn ] ] | 0 | take top items in a list python | Get a list of the top topn features in this : class : . Feature \ . | cosqa-train-19728 | def top(self, topn=10):
"""
Get a list of the top ``topn`` features in this :class:`.Feature`\.
Examples
--------
.. code-block:: python
>>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])
>>> myFeature.top(1)
[('trapezoid', 5)]
Parameters
----------
topn : int
Returns
-------
list
"""
return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]] |
def __gt__ ( self , other ) : if isinstance ( other , Address ) : return str ( self ) > str ( other ) raise TypeError | 0 | print "hello world" if a is greater than b in python | Test for greater than . | cosqa-train-19729 | def __gt__(self, other):
"""Test for greater than."""
if isinstance(other, Address):
return str(self) > str(other)
raise TypeError |
def inject_nulls ( data : Mapping , field_names ) -> dict : record = dict ( ) for field in field_names : record [ field ] = data . get ( field , None ) return record | 1 | python fill null value in dictionary | Insert None as value for missing fields . | cosqa-train-19730 | def inject_nulls(data: Mapping, field_names) -> dict:
"""Insert None as value for missing fields."""
record = dict()
for field in field_names:
record[field] = data.get(field, None)
return record |
def 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 | python connect to oracle database without dsn | Connects to an Access database via ODBC with the DSN prespecified . | cosqa-train-19731 | 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 grep ( pattern , filename ) : try : # for line in file # if line matches pattern: # return line return next ( ( L for L in open ( filename ) if L . find ( pattern ) >= 0 ) ) except StopIteration : return '' | 0 | python how to grep a file for a string | Very simple grep that returns the first matching line in a file . String matching only does not do REs as currently implemented . | cosqa-train-19732 | def grep(pattern, filename):
"""Very simple grep that returns the first matching line in a file.
String matching only, does not do REs as currently implemented.
"""
try:
# for line in file
# if line matches pattern:
# return line
return next((L for L in open(filename) if L.find(pattern) >= 0))
except StopIteration:
return '' |
def recClearTag ( element ) : children = element . getchildren ( ) if len ( children ) > 0 : for child in children : recClearTag ( child ) element . tag = clearTag ( element . tag ) | 1 | remove element python xml tree | Applies maspy . xml . clearTag () to the tag attribute of the element and recursively to all child elements . | cosqa-train-19733 | def recClearTag(element):
"""Applies maspy.xml.clearTag() to the tag attribute of the "element" and
recursively to all child elements.
:param element: an :instance:`xml.etree.Element`
"""
children = element.getchildren()
if len(children) > 0:
for child in children:
recClearTag(child)
element.tag = clearTag(element.tag) |
def PrintIndented ( self , file , ident , code ) : for entry in code : print >> file , '%s%s' % ( ident , entry ) | 1 | python write to file indentation | Takes an array add indentation to each entry and prints it . | cosqa-train-19734 | def PrintIndented(self, file, ident, code):
"""Takes an array, add indentation to each entry and prints it."""
for entry in code:
print >>file, '%s%s' % (ident, entry) |
def pack_bits ( longbits ) : byte = longbits & ( 0x0101010101010101 ) byte = ( byte | ( byte >> 7 ) ) & ( 0x0003000300030003 ) byte = ( byte | ( byte >> 14 ) ) & ( 0x0000000f0000000f ) byte = ( byte | ( byte >> 28 ) ) & ( 0x00000000000000ff ) return byte | 0 | how to keep bit values on python | Crunch a 64 - bit int ( 8 bool bytes ) into a bitfield . | cosqa-train-19735 | def pack_bits( longbits ):
"""Crunch a 64-bit int (8 bool bytes) into a bitfield."""
byte = longbits & (0x0101010101010101)
byte = (byte | (byte>>7)) & (0x0003000300030003)
byte = (byte | (byte>>14)) & (0x0000000f0000000f)
byte = (byte | (byte>>28)) & (0x00000000000000ff)
return byte |
def read_text_from_file ( path : str ) -> str : with open ( path ) as text_file : content = text_file . read ( ) return content | 1 | how to get contents fromtext file python | Reads text file contents | cosqa-train-19736 | 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 full ( self ) : return self . maxsize and len ( self . list ) >= self . maxsize or False | 0 | python how to check the queue length | Return True if the queue is full False otherwise ( not reliable! ) . | cosqa-train-19737 | def full(self):
"""Return ``True`` if the queue is full, ``False``
otherwise (not reliable!).
Only applicable if :attr:`maxsize` is set.
"""
return self.maxsize and len(self.list) >= self.maxsize or False |
def kernel ( self , spread = 1 ) : # TODO: use self.kernel_type to choose function def gaussian ( data , pixel ) : return mvn . pdf ( data , mean = pixel , cov = spread ) return gaussian | 0 | python density map gaussian kernel | This will return whatever kind of kernel we want to use . Must have signature ( ndarray size NxM ndarray size 1xM ) - > ndarray size Nx1 | cosqa-train-19738 | def kernel(self, spread=1):
""" This will return whatever kind of kernel we want to use.
Must have signature (ndarray size NxM, ndarray size 1xM) -> ndarray size Nx1
"""
# TODO: use self.kernel_type to choose function
def gaussian(data, pixel):
return mvn.pdf(data, mean=pixel, cov=spread)
return gaussian |
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 | reshape shuffle array python | Reshuffle the indicies of a bipartite matrix A [ ij kl ] - > A [ lj ki ] . | cosqa-train-19739 | 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 _my_hash ( arg_list ) : # type: (List[Any]) -> int res = 0 for arg in arg_list : res = res * 31 + hash ( arg ) return res | 0 | python hashlib function an integer | Simple helper hash function | cosqa-train-19740 | def _my_hash(arg_list):
# type: (List[Any]) -> int
"""Simple helper hash function"""
res = 0
for arg in arg_list:
res = res * 31 + hash(arg)
return res |
def clean_column_names ( df : DataFrame ) -> DataFrame : f = df . copy ( ) f . columns = [ col . strip ( ) for col in f . columns ] return f | 0 | python truncate an existing data frame to keep the column names | Strip the whitespace from all column names in the given DataFrame and return the result . | cosqa-train-19741 | 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 dictlist_wipe_key ( dict_list : Iterable [ Dict ] , key : str ) -> None : for d in dict_list : d . pop ( key , None ) | 1 | del element in dictionary in python | Process an iterable of dictionaries . For each dictionary d delete d [ key ] if it exists . | cosqa-train-19742 | 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 remove_once ( gset , elem ) : remove = getattr ( gset , 'remove' , None ) if remove is not None : remove ( elem ) else : del gset [ elem ] return elem | 0 | python delete a value from a set | Remove the element from a set lists or dict . >>> L = [ Lucy ] ; S = set ( [ Sky ] ) ; D = { Diamonds : True } ; >>> remove_once ( L Lucy ) ; remove_once ( S Sky ) ; remove_once ( D Diamonds ) ; >>> print L S D [] set ( [] ) {} | cosqa-train-19743 | def remove_once(gset, elem):
"""Remove the element from a set, lists or dict.
>>> L = ["Lucy"]; S = set(["Sky"]); D = { "Diamonds": True };
>>> remove_once(L, "Lucy"); remove_once(S, "Sky"); remove_once(D, "Diamonds");
>>> print L, S, D
[] set([]) {}
Returns the element if it was removed. Raises one of the exceptions in
:obj:`RemoveError` otherwise.
"""
remove = getattr(gset, 'remove', None)
if remove is not None: remove(elem)
else: del gset[elem]
return elem |
def is_unicode ( string ) : str_type = str ( type ( string ) ) if str_type . find ( 'str' ) > 0 or str_type . find ( 'unicode' ) > 0 : return True return False | 0 | python how to check type is string | Validates that the object itself is some kinda string | cosqa-train-19744 | 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 ResetConsoleColor ( ) -> bool : if sys . stdout : sys . stdout . flush ( ) bool ( ctypes . windll . kernel32 . SetConsoleTextAttribute ( _ConsoleOutputHandle , _DefaultConsoleColor ) ) | 1 | python reset window color | Reset to the default text color on console window . Return bool True if succeed otherwise False . | cosqa-train-19745 | def ResetConsoleColor() -> bool:
"""
Reset to the default text color on console window.
Return bool, True if succeed otherwise False.
"""
if sys.stdout:
sys.stdout.flush()
bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, _DefaultConsoleColor)) |
def pairwise ( iterable ) : first , second = tee ( iterable ) next ( second , None ) return zip ( first , second ) | 1 | skip first return value in tuple python | From itertools cookbook . [ a b c ... ] - > ( a b ) ( b c ) ... | cosqa-train-19746 | 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 is_not_null ( df : DataFrame , col_name : str ) -> bool : if ( isinstance ( df , pd . DataFrame ) and col_name in df . columns and df [ col_name ] . notnull ( ) . any ( ) ) : return True else : return False | 0 | check whether column contain nulls 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-19747 | 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 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 | 1 | get user cpu usage python | return memory usage of python process in MB | cosqa-train-19748 | 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 de_duplicate ( items ) : result = [ ] for item in items : if item not in result : result . append ( item ) return result | 1 | python how to get rid of repeating items in a list | Remove any duplicate item preserving order | cosqa-train-19749 | 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 rmglob ( pattern : str ) -> None : for f in glob . glob ( pattern ) : os . remove ( f ) | 1 | python 3 remove file with pattern | Deletes all files whose filename matches the glob pattern ( via : func : glob . glob ) . | cosqa-train-19750 | def rmglob(pattern: str) -> None:
"""
Deletes all files whose filename matches the glob ``pattern`` (via
:func:`glob.glob`).
"""
for f in glob.glob(pattern):
os.remove(f) |
def _check_whitespace ( string ) : if string . count ( ' ' ) + string . count ( '\t' ) + string . count ( '\n' ) > 0 : raise ValueError ( INSTRUCTION_HAS_WHITESPACE ) | 1 | python white space check | Make sure thre is no whitespace in the given string . Will raise a ValueError if whitespace is detected | cosqa-train-19751 | def _check_whitespace(string):
"""
Make sure thre is no whitespace in the given string. Will raise a
ValueError if whitespace is detected
"""
if string.count(' ') + string.count('\t') + string.count('\n') > 0:
raise ValueError(INSTRUCTION_HAS_WHITESPACE) |
def inverted_dict ( d ) : return dict ( ( force_hashable ( v ) , k ) for ( k , v ) in viewitems ( dict ( d ) ) ) | 0 | inverse dictionary python with a function | Return a dict with swapped keys and values | cosqa-train-19752 | def inverted_dict(d):
"""Return a dict with swapped keys and values
>>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}
True
"""
return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d))) |
def almost_hermitian ( gate : Gate ) -> bool : return np . allclose ( asarray ( gate . asoperator ( ) ) , asarray ( gate . H . asoperator ( ) ) ) | 0 | python check if hessian is invertible | Return true if gate tensor is ( almost ) Hermitian | cosqa-train-19753 | def almost_hermitian(gate: Gate) -> bool:
"""Return true if gate tensor is (almost) Hermitian"""
return np.allclose(asarray(gate.asoperator()),
asarray(gate.H.asoperator())) |
def strings_to_integers ( strings : Iterable [ str ] ) -> Iterable [ int ] : return strings_to_ ( strings , lambda x : int ( float ( x ) ) ) | 1 | python turn list of string into integers | Convert a list of strings to a list of integers . | cosqa-train-19754 | 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 is_any_type_set ( sett : Set [ Type ] ) -> bool : return len ( sett ) == 1 and is_any_type ( min ( sett ) ) | 0 | test if set is empty python | Helper method to check if a set of types is the { AnyObject } singleton | cosqa-train-19755 | def is_any_type_set(sett: Set[Type]) -> bool:
"""
Helper method to check if a set of types is the {AnyObject} singleton
:param sett:
:return:
"""
return len(sett) == 1 and is_any_type(min(sett)) |
def encode_list ( key , list_ ) : # type: (str, Iterable) -> Dict[str, str] if not list_ : return { } return { key : " " . join ( str ( i ) for i in list_ ) } | 1 | python create dict with list of list | Converts a list into a space - separated string and puts it in a dictionary | cosqa-train-19756 | def encode_list(key, list_):
# type: (str, Iterable) -> Dict[str, str]
"""
Converts a list into a space-separated string and puts it in a dictionary
:param key: Dictionary key to store the list
:param list_: A list of objects
:return: A dictionary key->string or an empty dictionary
"""
if not list_:
return {}
return {key: " ".join(str(i) for i in list_)} |
def issubset ( self , other ) : if len ( self ) > len ( other ) : # Fast check for obvious cases return False return all ( item in other for item in self ) | 1 | check if a set is a subset python | Report whether another set contains this set . | cosqa-train-19757 | def issubset(self, other):
"""
Report whether another set contains this set.
Example:
>>> OrderedSet([1, 2, 3]).issubset({1, 2})
False
>>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4})
True
>>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5})
False
"""
if len(self) > len(other): # Fast check for obvious cases
return False
return all(item in other for item in self) |
def flatten_list ( l : List [ list ] ) -> list : return [ v for inner_l in l for v in inner_l ] | 1 | python turn list of lists into one list | takes a list of lists l and returns a flat list | cosqa-train-19758 | def flatten_list(l: List[list]) -> list:
""" takes a list of lists, l and returns a flat list
"""
return [v for inner_l in l for v in inner_l] |
def cli_run ( ) : parser = argparse . ArgumentParser ( description = 'Stupidly simple code answers from StackOverflow' ) parser . add_argument ( 'query' , help = "What's the problem ?" , type = str , nargs = '+' ) parser . add_argument ( '-t' , '--tags' , help = 'semicolon separated tags -> python;lambda' ) args = parser . parse_args ( ) main ( args ) | 1 | python argparse specify flad | docstring for argparse | cosqa-train-19759 | 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 to_bytes ( data : Any ) -> bytearray : # noqa if isinstance ( data , int ) : return bytearray ( [ data ] ) return bytearray ( data , encoding = 'latin-1' ) | 0 | change data to bytes in python | Convert anything to a bytearray . See - http : // stackoverflow . com / questions / 7585435 / best - way - to - convert - string - to - bytes - in - python - 3 - http : // stackoverflow . com / questions / 10459067 / how - to - convert - my - bytearrayb - x9e - x18k - x9a - to - something - like - this - x9e - x1 | cosqa-train-19760 | def to_bytes(data: Any) -> bytearray:
"""
Convert anything to a ``bytearray``.
See
- http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3
- http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1
""" # noqa
if isinstance(data, int):
return bytearray([data])
return bytearray(data, encoding='latin-1') |
def getIndex ( predicateFn : Callable [ [ T ] , bool ] , items : List [ T ] ) -> int : try : return next ( i for i , v in enumerate ( items ) if predicateFn ( v ) ) except StopIteration : return - 1 | 0 | return indices to python list items meeting a specific condition | Finds the index of an item in list which satisfies predicate : param predicateFn : predicate function to run on items of list : param items : list of tuples : return : first index for which predicate function returns True | cosqa-train-19761 | def getIndex(predicateFn: Callable[[T], bool], items: List[T]) -> int:
"""
Finds the index of an item in list, which satisfies predicate
:param predicateFn: predicate function to run on items of list
:param items: list of tuples
:return: first index for which predicate function returns True
"""
try:
return next(i for i, v in enumerate(items) if predicateFn(v))
except StopIteration:
return -1 |
def full ( self ) : return self . maxsize and len ( self . list ) >= self . maxsize or False | 0 | python queue check size | Return True if the queue is full False otherwise ( not reliable! ) . | cosqa-train-19762 | def full(self):
"""Return ``True`` if the queue is full, ``False``
otherwise (not reliable!).
Only applicable if :attr:`maxsize` is set.
"""
return self.maxsize and len(self.list) >= self.maxsize or False |
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 | check first index of a string python | Returns the index of the earliest occurence of an item from a list in a string | cosqa-train-19763 | 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 default_parser ( ) -> argparse . ArgumentParser : parser = argparse . ArgumentParser ( prog = CONSOLE_SCRIPT , formatter_class = argparse . ArgumentDefaultsHelpFormatter , ) build_parser ( parser ) return parser | 0 | python argparser hidden variable | Create a parser for CLI arguments and options . | cosqa-train-19764 | def default_parser() -> argparse.ArgumentParser:
"""Create a parser for CLI arguments and options."""
parser = argparse.ArgumentParser(
prog=CONSOLE_SCRIPT,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
build_parser(parser)
return parser |
def titleize ( text ) : if len ( text ) == 0 : # if empty string, return it return text else : text = text . lower ( ) # lower all char # delete redundant empty space chunks = [ chunk [ 0 ] . upper ( ) + chunk [ 1 : ] for chunk in text . split ( " " ) if len ( chunk ) >= 1 ] return " " . join ( chunks ) | 1 | how to capaitalize the first letter in each word python | Capitalizes all the words and replaces some characters in the string to create a nicer looking title . | cosqa-train-19765 | def titleize(text):
"""Capitalizes all the words and replaces some characters in the string
to create a nicer looking title.
"""
if len(text) == 0: # if empty string, return it
return text
else:
text = text.lower() # lower all char
# delete redundant empty space
chunks = [chunk[0].upper() + chunk[1:] for chunk in text.split(" ") if len(chunk) >= 1]
return " ".join(chunks) |
def _my_hash ( arg_list ) : # type: (List[Any]) -> int res = 0 for arg in arg_list : res = res * 31 + hash ( arg ) return res | 1 | equivallent function in python for hash array in perl | Simple helper hash function | cosqa-train-19766 | def _my_hash(arg_list):
# type: (List[Any]) -> int
"""Simple helper hash function"""
res = 0
for arg in arg_list:
res = res * 31 + hash(arg)
return res |
def _isint ( string ) : return type ( string ) is int or ( isinstance ( string , _binary_type ) or isinstance ( string , _text_type ) ) and _isconvertible ( int , string ) | 0 | python if string is int | >>> _isint ( 123 ) True >>> _isint ( 123 . 45 ) False | cosqa-train-19767 | def _isint(string):
"""
>>> _isint("123")
True
>>> _isint("123.45")
False
"""
return type(string) is int or \
(isinstance(string, _binary_type) or isinstance(string, _text_type)) and \
_isconvertible(int, string) |
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 string in line of file | Detects whether a line is present within a file . | cosqa-train-19768 | 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 set_int ( bytearray_ , byte_index , _int ) : # make sure were dealing with an int _int = int ( _int ) _bytes = struct . unpack ( '2B' , struct . pack ( '>h' , _int ) ) bytearray_ [ byte_index : byte_index + 2 ] = _bytes return bytearray_ | 1 | messge pack setup int type in python | Set value in bytearray to int | cosqa-train-19769 | def set_int(bytearray_, byte_index, _int):
"""
Set value in bytearray to int
"""
# make sure were dealing with an int
_int = int(_int)
_bytes = struct.unpack('2B', struct.pack('>h', _int))
bytearray_[byte_index:byte_index + 2] = _bytes
return bytearray_ |
def _run_sync ( self , method : Callable , * args , * * kwargs ) -> Any : if self . loop . is_running ( ) : raise RuntimeError ( "Event loop is already running." ) if not self . is_connected : self . loop . run_until_complete ( self . connect ( ) ) task = asyncio . Task ( method ( * args , * * kwargs ) , loop = self . loop ) result = self . loop . run_until_complete ( task ) self . loop . run_until_complete ( self . quit ( ) ) return result | 1 | python concurrent future asyncio future | Utility method to run commands synchronously for testing . | cosqa-train-19770 | def _run_sync(self, method: Callable, *args, **kwargs) -> Any:
"""
Utility method to run commands synchronously for testing.
"""
if self.loop.is_running():
raise RuntimeError("Event loop is already running.")
if not self.is_connected:
self.loop.run_until_complete(self.connect())
task = asyncio.Task(method(*args, **kwargs), loop=self.loop)
result = self.loop.run_until_complete(task)
self.loop.run_until_complete(self.quit())
return result |
def multi_split ( s , split ) : # type: (S, Iterable[S]) -> List[S] for r in split : s = s . replace ( r , "|" ) return [ i for i in s . split ( "|" ) if len ( i ) > 0 ] | 1 | python split according to a list of delimiters | Splits on multiple given separators . | cosqa-train-19771 | def multi_split(s, split):
# type: (S, Iterable[S]) -> List[S]
"""Splits on multiple given separators."""
for r in split:
s = s.replace(r, "|")
return [i for i in s.split("|") if len(i) > 0] |
def get_period_last_3_months ( ) -> str : today = Datum ( ) today . today ( ) # start_date = today - timedelta(weeks=13) start_date = today . clone ( ) start_date . subtract_months ( 3 ) period = get_period ( start_date . date , today . date ) return period | 0 | python from most recent strptime and retrieve last 12 months | Returns the last week as a period string | cosqa-train-19772 | def get_period_last_3_months() -> str:
""" Returns the last week as a period string """
today = Datum()
today.today()
# start_date = today - timedelta(weeks=13)
start_date = today.clone()
start_date.subtract_months(3)
period = get_period(start_date.date, today.date)
return period |
def get_column_names ( engine : Engine , tablename : str ) -> List [ str ] : return [ info . name for info in gen_columns_info ( engine , tablename ) ] | 1 | list the columns in a table in python | Get all the database column names for the specified table . | cosqa-train-19773 | def get_column_names(engine: Engine, tablename: str) -> List[str]:
"""
Get all the database column names for the specified table.
"""
return [info.name for info in gen_columns_info(engine, tablename)] |
def dtypes ( self ) : return [ ( str ( f . name ) , f . dataType . simpleString ( ) ) for f in self . schema . fields ] | 1 | how to print out dtypes for all columns in python | Returns all column names and their data types as a list . | cosqa-train-19774 | def dtypes(self):
"""Returns all column names and their data types as a list.
>>> df.dtypes
[('age', 'int'), ('name', 'string')]
"""
return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields] |
def _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 | python list with duplicate items get index | Return dict mapping item - > indices . | cosqa-train-19775 | 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 infer_format ( filename : str ) -> str : _ , ext = os . path . splitext ( filename ) return ext | 1 | how to get the file extension in python | Return extension identifying format of given filename | cosqa-train-19776 | def infer_format(filename:str) -> str:
"""Return extension identifying format of given filename"""
_, ext = os.path.splitext(filename)
return ext |
def read_text_from_file ( path : str ) -> str : with open ( path ) as text_file : content = text_file . read ( ) return content | 1 | how to get text file python | Reads text file contents | cosqa-train-19777 | 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 remove_blank_lines ( string ) : return "\n" . join ( line for line in string . split ( "\n" ) if len ( line . strip ( ) ) ) | 1 | python string remove blank | Removes all blank lines in @string | cosqa-train-19778 | 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 _ ( f , x ) : return { k : v for k , v in x . items ( ) if f ( k , v ) } | 0 | how to filter a dictionary of values in python | filter for dict note f should have signature : f :: key - > value - > bool | cosqa-train-19779 | 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 _my_hash ( arg_list ) : # type: (List[Any]) -> int res = 0 for arg in arg_list : res = res * 31 + hash ( arg ) return res | 1 | how to hash integers python | Simple helper hash function | cosqa-train-19780 | def _my_hash(arg_list):
# type: (List[Any]) -> int
"""Simple helper hash function"""
res = 0
for arg in arg_list:
res = res * 31 + hash(arg)
return res |
def _ ( f , x ) : return { k : v for k , v in x . items ( ) if f ( k , v ) } | 0 | python dict get value filter by another key | filter for dict note f should have signature : f :: key - > value - > bool | cosqa-train-19781 | 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)} |
async def cursor ( self ) -> Cursor : return Cursor ( self , await self . _execute ( self . _conn . cursor ) ) | 1 | python engine has no cursor attribute | Create an aiosqlite cursor wrapping a sqlite3 cursor object . | cosqa-train-19782 | 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_integer ( value : Any ) -> bool : return ( isinstance ( value , int ) and not isinstance ( value , bool ) ) or ( isinstance ( value , float ) and isfinite ( value ) and int ( value ) == value ) | 1 | python int and float equals string or float | Return true if a value is an integer number . | cosqa-train-19783 | def is_integer(value: Any) -> bool:
"""Return true if a value is an integer number."""
return (isinstance(value, int) and not isinstance(value, bool)) or (
isinstance(value, float) and isfinite(value) and int(value) == value
) |
def infer_format ( filename : str ) -> str : _ , ext = os . path . splitext ( filename ) return ext | 0 | filename and extension of file in python | Return extension identifying format of given filename | cosqa-train-19784 | def infer_format(filename:str) -> str:
"""Return extension identifying format of given filename"""
_, ext = os.path.splitext(filename)
return ext |
def decodebytes ( input ) : py_version = sys . version_info [ 0 ] if py_version >= 3 : return _decodebytes_py3 ( input ) return _decodebytes_py2 ( input ) | 1 | python3 decode byte string | Decode base64 string to byte array . | cosqa-train-19785 | 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 fetchvalue ( self , sql : str , * args ) -> Optional [ Any ] : row = self . fetchone ( sql , * args ) if row is None : return None return row [ 0 ] | 0 | returning single value in sql stored procedure python | Executes SQL ; returns the first value of the first row or None . | cosqa-train-19786 | def fetchvalue(self, sql: str, *args) -> Optional[Any]:
"""Executes SQL; returns the first value of the first row, or None."""
row = self.fetchone(sql, *args)
if row is None:
return None
return row[0] |
def string ( value ) -> str : return system_json . dumps ( Json ( value ) . safe_object ( ) , ensure_ascii = False ) | 0 | jsonstring to string python | string dict / object / value to JSON | cosqa-train-19787 | def string(value) -> str:
""" string dict/object/value to JSON """
return system_json.dumps(Json(value).safe_object(), ensure_ascii=False) |
def is_sqlatype_integer ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . Integer ) | 1 | type of a column python | Is the SQLAlchemy column type an integer type? | cosqa-train-19788 | def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type an integer type?
"""
coltype = _coltype_to_typeengine(coltype)
return isinstance(coltype, sqltypes.Integer) |
def _kbhit_unix ( ) -> bool : dr , dw , de = select . select ( [ sys . stdin ] , [ ] , [ ] , 0 ) return dr != [ ] | 1 | python detect key press linux | Under UNIX : is a keystroke available? | cosqa-train-19789 | def _kbhit_unix() -> bool:
"""
Under UNIX: is a keystroke available?
"""
dr, dw, de = select.select([sys.stdin], [], [], 0)
return dr != [] |
def debugTreePrint ( node , pfx = "->" ) : print pfx , node . item for c in node . children : debugTreePrint ( c , " " + pfx ) | 0 | print all leaf nodes of a binary tree python | Purely a debugging aid : Ascii - art picture of a tree descended from node | cosqa-train-19790 | def debugTreePrint(node,pfx="->"):
"""Purely a debugging aid: Ascii-art picture of a tree descended from node"""
print pfx,node.item
for c in node.children:
debugTreePrint(c," "+pfx) |
def warn_if_nans_exist ( X ) : null_count = count_rows_with_nans ( X ) total = len ( X ) percent = 100 * null_count / total if null_count > 0 : warning_message = 'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' 'complete rows will be plotted.' . format ( null_count , total , percent ) warnings . warn ( warning_message , DataWarning ) | 1 | to check the nan and null values in python | Warn if nans exist in a numpy array . | cosqa-train-19791 | def warn_if_nans_exist(X):
"""Warn if nans exist in a numpy array."""
null_count = count_rows_with_nans(X)
total = len(X)
percent = 100 * null_count / total
if null_count > 0:
warning_message = \
'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' \
'complete rows will be plotted.'.format(null_count, total, percent)
warnings.warn(warning_message, DataWarning) |
def recClearTag ( element ) : children = element . getchildren ( ) if len ( children ) > 0 : for child in children : recClearTag ( child ) element . tag = clearTag ( element . tag ) | 0 | python xml elementtree remove child node | Applies maspy . xml . clearTag () to the tag attribute of the element and recursively to all child elements . | cosqa-train-19792 | def recClearTag(element):
"""Applies maspy.xml.clearTag() to the tag attribute of the "element" and
recursively to all child elements.
:param element: an :instance:`xml.etree.Element`
"""
children = element.getchildren()
if len(children) > 0:
for child in children:
recClearTag(child)
element.tag = clearTag(element.tag) |
def dfromdm ( dm ) : if np . size ( dm ) > 1 : dm = np . atleast_1d ( dm ) return 10 ** ( 1 + dm / 5 ) | 0 | how to make a distance function in python | Returns distance given distance modulus . | cosqa-train-19793 | def dfromdm(dm):
"""Returns distance given distance modulus.
"""
if np.size(dm)>1:
dm = np.atleast_1d(dm)
return 10**(1+dm/5) |
def get_window_dim ( ) : version = sys . version_info if version >= ( 3 , 3 ) : return _size_36 ( ) if platform . system ( ) == 'Windows' : return _size_windows ( ) return _size_27 ( ) | 1 | determine win folder size in python | gets the dimensions depending on python version and os | cosqa-train-19794 | def get_window_dim():
""" gets the dimensions depending on python version and os"""
version = sys.version_info
if version >= (3, 3):
return _size_36()
if platform.system() == 'Windows':
return _size_windows()
return _size_27() |
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 | how to check if the date is last date of the month python | Get the last weekday in a given month . e . g : | cosqa-train-19795 | 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 get_window_dim ( ) : version = sys . version_info if version >= ( 3 , 3 ) : return _size_36 ( ) if platform . system ( ) == 'Windows' : return _size_windows ( ) return _size_27 ( ) | 1 | python get browser size | gets the dimensions depending on python version and os | cosqa-train-19796 | def get_window_dim():
""" gets the dimensions depending on python version and os"""
version = sys.version_info
if version >= (3, 3):
return _size_36()
if platform.system() == 'Windows':
return _size_windows()
return _size_27() |
def str_to_time ( time_str : str ) -> datetime . datetime : pieces : Any = [ int ( piece ) for piece in time_str . split ( '-' ) ] return datetime . datetime ( * pieces ) | 1 | python from string to date time | Convert human readable string to datetime . datetime . | cosqa-train-19797 | def str_to_time(time_str: str) -> datetime.datetime:
"""
Convert human readable string to datetime.datetime.
"""
pieces: Any = [int(piece) for piece in time_str.split('-')]
return datetime.datetime(*pieces) |
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 | read json object from file as dict python | Load JSON file | cosqa-train-19798 | 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 hsv2rgb_spectrum ( hsv ) : h , s , v = hsv return hsv2rgb_raw ( ( ( h * 192 ) >> 8 , s , v ) ) | 1 | rgb to hsv for image python | Generates RGB values from HSV values in line with a typical light spectrum . | cosqa-train-19799 | def hsv2rgb_spectrum(hsv):
"""Generates RGB values from HSV values in line with a typical light
spectrum."""
h, s, v = hsv
return hsv2rgb_raw(((h * 192) >> 8, s, v)) |