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 tuple_search ( t , i , v ) : for e in t : if e [ i ] == v : return e return None
| 1 |
python locate tuple in list
|
Search tuple array by index and value : param t : tuple array : param i : index of the value in each tuple : param v : value : return : the first tuple in the array with the specific index / value
|
cosqa-train-13500
|
def tuple_search(t, i, v):
"""
Search tuple array by index and value
:param t: tuple array
:param i: index of the value in each tuple
:param v: value
:return: the first tuple in the array with the specific index / value
"""
for e in t:
if e[i] == v:
return e
return None
|
def col_rename ( df , col_name , new_col_name ) : col_list = list ( df . columns ) for index , value in enumerate ( col_list ) : if value == col_name : col_list [ index ] = new_col_name break df . columns = col_list
| 0 |
how to change a specific column name python
|
Changes a column name in a DataFrame Parameters : df - DataFrame DataFrame to operate on col_name - string Name of column to change new_col_name - string New name of column
|
cosqa-train-13501
|
def col_rename(df,col_name,new_col_name):
""" Changes a column name in a DataFrame
Parameters:
df - DataFrame
DataFrame to operate on
col_name - string
Name of column to change
new_col_name - string
New name of column
"""
col_list = list(df.columns)
for index,value in enumerate(col_list):
if value == col_name:
col_list[index] = new_col_name
break
df.columns = col_list
|
def _find ( string , sub_string , start_index ) : result = string . find ( sub_string , start_index ) if result == - 1 : raise TokenError ( "expected '{0}'" . format ( sub_string ) ) return result
| 1 |
python location of substring in string
|
Return index of sub_string in string .
|
cosqa-train-13502
|
def _find(string, sub_string, start_index):
"""Return index of sub_string in string.
Raise TokenError if sub_string is not found.
"""
result = string.find(sub_string, start_index)
if result == -1:
raise TokenError("expected '{0}'".format(sub_string))
return result
|
def __unixify ( self , s ) : return os . path . normpath ( s ) . replace ( os . sep , "/" )
| 0 |
how to change backslash to forward slash in python os path
|
stupid windows . converts the backslash to forwardslash for consistency
|
cosqa-train-13503
|
def __unixify(self, s):
""" stupid windows. converts the backslash to forwardslash for consistency """
return os.path.normpath(s).replace(os.sep, "/")
|
def assert_lock ( fname ) : if not set_lock ( fname ) : logger . error ( 'File {} is already locked. Terminating.' . format ( fname ) ) sys . exit ( )
| 1 |
python lock file delete
|
If file is locked then terminate program else lock file .
|
cosqa-train-13504
|
def assert_lock(fname):
"""
If file is locked then terminate program else lock file.
"""
if not set_lock(fname):
logger.error('File {} is already locked. Terminating.'.format(fname))
sys.exit()
|
def colorize ( string , color , * args , * * kwargs ) : string = string . format ( * args , * * kwargs ) return color + string + colorama . Fore . RESET
| 1 |
how to change color of string in python
|
Implements string formatting along with color specified in colorama . Fore
|
cosqa-train-13505
|
def colorize(string, color, *args, **kwargs):
"""
Implements string formatting along with color specified in colorama.Fore
"""
string = string.format(*args, **kwargs)
return color + string + colorama.Fore.RESET
|
def lock ( self , block = True ) : self . _locked = True return self . _lock . acquire ( block )
| 0 |
python lock on a variable access
|
Lock connection from being used else where
|
cosqa-train-13506
|
def lock(self, block=True):
"""
Lock connection from being used else where
"""
self._locked = True
return self._lock.acquire(block)
|
def normalise_string ( string ) : string = ( string . strip ( ) ) . lower ( ) return re . sub ( r'\W+' , '_' , string )
| 1 |
how to change spaces to underscores python
|
Strips trailing whitespace from string lowercases it and replaces spaces with underscores
|
cosqa-train-13507
|
def normalise_string(string):
""" Strips trailing whitespace from string, lowercases it and replaces
spaces with underscores
"""
string = (string.strip()).lower()
return re.sub(r'\W+', '_', string)
|
def write ( self , text ) : self . logger . log ( self . loglevel , text , extra = { 'terminator' : None } )
| 0 |
python logging add blank lines
|
Write text . An additional attribute terminator with a value of None is added to the logging record to indicate that StreamHandler should not add a newline .
|
cosqa-train-13508
|
def write(self, text):
"""Write text. An additional attribute terminator with a value of
None is added to the logging record to indicate that StreamHandler
should not add a newline."""
self.logger.log(self.loglevel, text, extra={'terminator': None})
|
def str2int ( num , radix = 10 , alphabet = BASE85 ) : return NumConv ( radix , alphabet ) . str2int ( num )
| 0 |
how to change str to int in python
|
helper function for quick base conversions from strings to integers
|
cosqa-train-13509
|
def str2int(num, radix=10, alphabet=BASE85):
"""helper function for quick base conversions from strings to integers"""
return NumConv(radix, alphabet).str2int(num)
|
def write ( self , text ) : self . logger . log ( self . loglevel , text , extra = { 'terminator' : None } )
| 1 |
python logging create blank line
|
Write text . An additional attribute terminator with a value of None is added to the logging record to indicate that StreamHandler should not add a newline .
|
cosqa-train-13510
|
def write(self, text):
"""Write text. An additional attribute terminator with a value of
None is added to the logging record to indicate that StreamHandler
should not add a newline."""
self.logger.log(self.loglevel, text, extra={'terminator': None})
|
def printc ( cls , txt , color = colors . red ) : print ( cls . color_txt ( txt , color ) )
| 1 |
how to change text print color in python
|
Print in color .
|
cosqa-train-13511
|
def printc(cls, txt, color=colors.red):
"""Print in color."""
print(cls.color_txt(txt, color))
|
def format ( self , record , * args , * * kwargs ) : return logging . Formatter . format ( self , record , * args , * * kwargs ) . replace ( '\n' , '\n' + ' ' * 8 )
| 1 |
python logging format brace bracket
|
Format a message in the log
|
cosqa-train-13512
|
def format(self, record, *args, **kwargs):
"""
Format a message in the log
Act like the normal format, but indent anything that is a
newline within the message.
"""
return logging.Formatter.format(
self, record, *args, **kwargs).replace('\n', '\n' + ' ' * 8)
|
def guess_media_type ( filepath ) : o = subprocess . check_output ( [ 'file' , '--mime-type' , '-Lb' , filepath ] ) o = o . strip ( ) return o
| 1 |
how to change the mime type of a file programmatically in python
|
Returns the media - type of the file at the given filepath
|
cosqa-train-13513
|
def guess_media_type(filepath):
"""Returns the media-type of the file at the given ``filepath``"""
o = subprocess.check_output(['file', '--mime-type', '-Lb', filepath])
o = o.strip()
return o
|
def clog ( color ) : logger = log ( color ) return lambda msg : logger ( centralize ( msg ) . rstrip ( ) )
| 1 |
python logging formatter color
|
Same to log but this one centralizes the message first .
|
cosqa-train-13514
|
def clog(color):
"""Same to ``log``, but this one centralizes the message first."""
logger = log(color)
return lambda msg: logger(centralize(msg).rstrip())
|
def execute_cast_simple_literal_to_timestamp ( op , data , type , * * kwargs ) : return pd . Timestamp ( data , tz = type . timezone )
| 1 |
how to change time zone of a column to ist in python
|
Cast integer and strings to timestamps
|
cosqa-train-13515
|
def execute_cast_simple_literal_to_timestamp(op, data, type, **kwargs):
"""Cast integer and strings to timestamps"""
return pd.Timestamp(data, tz=type.timezone)
|
def find_console_handler ( logger ) : for handler in logger . handlers : if ( isinstance ( handler , logging . StreamHandler ) and handler . stream == sys . stderr ) : return handler
| 1 |
python logging get file handler name
|
Return a stream handler if it exists .
|
cosqa-train-13516
|
def find_console_handler(logger):
"""Return a stream handler, if it exists."""
for handler in logger.handlers:
if (isinstance(handler, logging.StreamHandler) and
handler.stream == sys.stderr):
return handler
|
def title ( msg ) : if sys . platform . startswith ( "win" ) : ctypes . windll . kernel32 . SetConsoleTitleW ( tounicode ( msg ) )
| 1 |
how to change window title python
|
Sets the title of the console window .
|
cosqa-train-13517
|
def title(msg):
"""Sets the title of the console window."""
if sys.platform.startswith("win"):
ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg))
|
def _debug_log ( self , msg ) : if not self . debug : return sys . stderr . write ( '{}\n' . format ( msg ) )
| 1 |
python logging not print immediately
|
Debug log messages if debug = True
|
cosqa-train-13518
|
def _debug_log(self, msg):
"""Debug log messages if debug=True"""
if not self.debug:
return
sys.stderr.write('{}\n'.format(msg))
|
def set_ylim ( self , xlims , dx , xscale , reverse = False ) : self . _set_axis_limits ( 'y' , xlims , dx , xscale , reverse ) return
| 0 |
how to change y axis limits on python
|
Set y limits for plot .
|
cosqa-train-13519
|
def set_ylim(self, xlims, dx, xscale, reverse=False):
"""Set y limits for plot.
This will set the limits for the y axis
for the specific plot.
Args:
ylims (len-2 list of floats): The limits for the axis.
dy (float): Amount to increment by between the limits.
yscale (str): Scale of the axis. Either `log` or `lin`.
reverse (bool, optional): If True, reverse the axis tick marks. Default is False.
"""
self._set_axis_limits('y', xlims, dx, xscale, reverse)
return
|
def close_log ( log , verbose = True ) : if verbose : print ( 'Closing log file:' , log . name ) # Send closing message. log . info ( 'The log file has been closed.' ) # Remove all handlers from log. [ log . removeHandler ( handler ) for handler in log . handlers ]
| 1 |
python logging nothing after delete log file
|
Close log
|
cosqa-train-13520
|
def close_log(log, verbose=True):
"""Close log
This method closes and active logging.Logger instance.
Parameters
----------
log : logging.Logger
Logging instance
"""
if verbose:
print('Closing log file:', log.name)
# Send closing message.
log.info('The log file has been closed.')
# Remove all handlers from log.
[log.removeHandler(handler) for handler in log.handlers]
|
def check_dependencies_remote ( args ) : cmd = [ args . python , '-m' , 'depends' , args . requirement ] env = dict ( PYTHONPATH = os . path . dirname ( __file__ ) ) return subprocess . check_call ( cmd , env = env )
| 0 |
how to check all dependencies of a python script
|
Invoke this command on a remote Python .
|
cosqa-train-13521
|
def check_dependencies_remote(args):
"""
Invoke this command on a remote Python.
"""
cmd = [args.python, '-m', 'depends', args.requirement]
env = dict(PYTHONPATH=os.path.dirname(__file__))
return subprocess.check_call(cmd, env=env)
|
def timed_rotating_file_handler ( name , logname , filename , when = 'h' , interval = 1 , backupCount = 0 , encoding = None , delay = False , utc = False ) : return wrap_log_handler ( logging . handlers . TimedRotatingFileHandler ( filename , when = when , interval = interval , backupCount = backupCount , encoding = encoding , delay = delay , utc = utc ) )
| 0 |
python logging rotatingfilehandler windows
|
A Bark logging handler logging output to a named file . At intervals specified by the when the file will be rotated under control of backupCount .
|
cosqa-train-13522
|
def timed_rotating_file_handler(name, logname, filename, when='h',
interval=1, backupCount=0,
encoding=None, delay=False, utc=False):
"""
A Bark logging handler logging output to a named file. At
intervals specified by the 'when', the file will be rotated, under
control of 'backupCount'.
Similar to logging.handlers.TimedRotatingFileHandler.
"""
return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(
filename, when=when, interval=interval, backupCount=backupCount,
encoding=encoding, delay=delay, utc=utc))
|
def make_kind_check ( python_types , numpy_kind ) : def check ( value ) : if hasattr ( value , 'dtype' ) : return value . dtype . kind == numpy_kind return isinstance ( value , python_types ) return check
| 1 |
how to check column types in python
|
Make a function that checks whether a scalar or array is of a given kind ( e . g . float int datetime timedelta ) .
|
cosqa-train-13523
|
def make_kind_check(python_types, numpy_kind):
"""
Make a function that checks whether a scalar or array is of a given kind
(e.g. float, int, datetime, timedelta).
"""
def check(value):
if hasattr(value, 'dtype'):
return value.dtype.kind == numpy_kind
return isinstance(value, python_types)
return check
|
def set_verbosity ( verbosity ) : Logger . _verbosity = min ( max ( 0 , WARNING - verbosity ) , 2 ) debug ( "Verbosity set to %d" % ( WARNING - Logger . _verbosity ) , 'logging' )
| 1 |
python logging set verbosity
|
Banana banana
|
cosqa-train-13524
|
def set_verbosity(verbosity):
"""Banana banana
"""
Logger._verbosity = min(max(0, WARNING - verbosity), 2)
debug("Verbosity set to %d" % (WARNING - Logger._verbosity), 'logging')
|
def file_empty ( fp ) : # for python 2 we need to use a homemade peek() if six . PY2 : contents = fp . read ( ) fp . seek ( 0 ) return not bool ( contents ) else : return not fp . peek ( )
| 1 |
how to check content of a file is empty or not in python
|
Determine if a file is empty or not .
|
cosqa-train-13525
|
def file_empty(fp):
"""Determine if a file is empty or not."""
# for python 2 we need to use a homemade peek()
if six.PY2:
contents = fp.read()
fp.seek(0)
return not bool(contents)
else:
return not fp.peek()
|
def get_from_human_key ( self , key ) : if key in self . _identifier_map : return self . _identifier_map [ key ] raise KeyError ( key )
| 1 |
python lookup value based on key
|
Return the key ( aka database value ) of a human key ( aka Python identifier ) .
|
cosqa-train-13526
|
def get_from_human_key(self, key):
"""Return the key (aka database value) of a human key (aka Python identifier)."""
if key in self._identifier_map:
return self._identifier_map[key]
raise KeyError(key)
|
def count_nulls ( self , field ) : try : n = self . df [ field ] . isnull ( ) . sum ( ) except KeyError : self . warning ( "Can not find column" , field ) return except Exception as e : self . err ( e , "Can not count nulls" ) return self . ok ( "Found" , n , "nulls in column" , field )
| 0 |
how to check count of null values in python
|
Count the number of null values in a column
|
cosqa-train-13527
|
def count_nulls(self, field):
"""
Count the number of null values in a column
"""
try:
n = self.df[field].isnull().sum()
except KeyError:
self.warning("Can not find column", field)
return
except Exception as e:
self.err(e, "Can not count nulls")
return
self.ok("Found", n, "nulls in column", field)
|
async def restart ( request ) : def wait_and_restart ( ) : log . info ( 'Restarting server' ) sleep ( 1 ) os . system ( 'kill 1' ) Thread ( target = wait_and_restart ) . start ( ) return web . json_response ( { "message" : "restarting" } )
| 1 |
python loop to restart service
|
Returns OK then waits approximately 1 second and restarts container
|
cosqa-train-13528
|
async def restart(request):
"""
Returns OK, then waits approximately 1 second and restarts container
"""
def wait_and_restart():
log.info('Restarting server')
sleep(1)
os.system('kill 1')
Thread(target=wait_and_restart).start()
return web.json_response({"message": "restarting"})
|
def make_kind_check ( python_types , numpy_kind ) : def check ( value ) : if hasattr ( value , 'dtype' ) : return value . dtype . kind == numpy_kind return isinstance ( value , python_types ) return check
| 0 |
how to check datattypes in python
|
Make a function that checks whether a scalar or array is of a given kind ( e . g . float int datetime timedelta ) .
|
cosqa-train-13529
|
def make_kind_check(python_types, numpy_kind):
"""
Make a function that checks whether a scalar or array is of a given kind
(e.g. float, int, datetime, timedelta).
"""
def check(value):
if hasattr(value, 'dtype'):
return value.dtype.kind == numpy_kind
return isinstance(value, python_types)
return check
|
def dict_keys_without_hyphens ( a_dict ) : return dict ( ( key . replace ( '-' , '_' ) , val ) for key , val in a_dict . items ( ) )
| 1 |
python lower each dict key
|
Return the a new dict with underscores instead of hyphens in keys .
|
cosqa-train-13530
|
def dict_keys_without_hyphens(a_dict):
"""Return the a new dict with underscores instead of hyphens in keys."""
return dict(
(key.replace('-', '_'), val) for key, val in a_dict.items())
|
def validate_email ( email ) : from django . core . validators import validate_email from django . core . exceptions import ValidationError try : validate_email ( email ) return True except ValidationError : return False
| 1 |
how to check email is valid or not? in python
|
Validates an email address Source : Himanshu Shankar ( https : // github . com / iamhssingh ) Parameters ---------- email : str
|
cosqa-train-13531
|
def validate_email(email):
"""
Validates an email address
Source: Himanshu Shankar (https://github.com/iamhssingh)
Parameters
----------
email: str
Returns
-------
bool
"""
from django.core.validators import validate_email
from django.core.exceptions import ValidationError
try:
validate_email(email)
return True
except ValidationError:
return False
|
def _guess_extract_method ( fname ) : for method , extensions in _EXTRACTION_METHOD_TO_EXTS : for ext in extensions : if fname . endswith ( ext ) : return method return ExtractMethod . NO_EXTRACT
| 1 |
python magic guess extension
|
Guess extraction method given file name ( or path ) .
|
cosqa-train-13532
|
def _guess_extract_method(fname):
"""Guess extraction method, given file name (or path)."""
for method, extensions in _EXTRACTION_METHOD_TO_EXTS:
for ext in extensions:
if fname.endswith(ext):
return method
return ExtractMethod.NO_EXTRACT
|
def is_empty ( self ) : non_type_attributes = [ attr for attr in self . node . attrib . keys ( ) if attr != 'type' ] return len ( self . node ) == 0 and len ( non_type_attributes ) == 0 and not self . node . text and not self . node . tail
| 1 |
how to check if a element is empty is xml python
|
Returns True if the root node contains no child elements no text and no attributes other than ** type ** . Returns False if any are present .
|
cosqa-train-13533
|
def is_empty(self):
"""Returns True if the root node contains no child elements, no text,
and no attributes other than **type**. Returns False if any are present."""
non_type_attributes = [attr for attr in self.node.attrib.keys() if attr != 'type']
return len(self.node) == 0 and len(non_type_attributes) == 0 \
and not self.node.text and not self.node.tail
|
def copy ( obj ) : def copy ( self ) : """
Copy self to a new object.
""" from copy import deepcopy return deepcopy ( self ) obj . copy = copy return obj
| 1 |
python make a copy not reference
|
cosqa-train-13534
|
def copy(obj):
def copy(self):
"""
Copy self to a new object.
"""
from copy import deepcopy
return deepcopy(self)
obj.copy = copy
return obj
|
|
def has_multiline_items ( maybe_list : Optional [ Sequence [ str ] ] ) : return maybe_list and any ( is_multiline ( item ) for item in maybe_list )
| 1 |
how to check if a line contains any string from a list of strings python and what the string is
|
Check whether one of the items in the list has multiple lines .
|
cosqa-train-13535
|
def has_multiline_items(maybe_list: Optional[Sequence[str]]):
"""Check whether one of the items in the list has multiple lines."""
return maybe_list and any(is_multiline(item) for item in maybe_list)
|
def path_to_list ( pathstr ) : return [ elem for elem in pathstr . split ( os . path . pathsep ) if elem ]
| 0 |
python make a str to a list
|
Conver a path string to a list of path elements .
|
cosqa-train-13536
|
def path_to_list(pathstr):
"""Conver a path string to a list of path elements."""
return [elem for elem in pathstr.split(os.path.pathsep) if elem]
|
def issorted ( list_ , op = operator . le ) : return all ( op ( list_ [ ix ] , list_ [ ix + 1 ] ) for ix in range ( len ( list_ ) - 1 ) )
| 1 |
how to check if a list is in ascending order in python
|
Determines if a list is sorted
|
cosqa-train-13537
|
def issorted(list_, op=operator.le):
"""
Determines if a list is sorted
Args:
list_ (list):
op (func): sorted operation (default=operator.le)
Returns:
bool : True if the list is sorted
"""
return all(op(list_[ix], list_[ix + 1]) for ix in range(len(list_) - 1))
|
def package_in_pypi ( package ) : url = 'http://pypi.python.org/simple/%s' % package try : urllib . request . urlopen ( url ) return True except urllib . error . HTTPError as e : logger . debug ( "Package not found on pypi: %s" , e ) return False
| 1 |
python make pypi trusted site
|
Check whether the package is registered on pypi
|
cosqa-train-13538
|
def package_in_pypi(package):
"""Check whether the package is registered on pypi"""
url = 'http://pypi.python.org/simple/%s' % package
try:
urllib.request.urlopen(url)
return True
except urllib.error.HTTPError as e:
logger.debug("Package not found on pypi: %s", e)
return False
|
def is_alive ( self ) : response = self . get_monitoring_heartbeat ( ) if response . status_code == 200 and response . content == 'alive' : return True return False
| 1 |
how to check if a python service is running
|
Will test whether the ACS service is up and alive .
|
cosqa-train-13539
|
def is_alive(self):
"""
Will test whether the ACS service is up and alive.
"""
response = self.get_monitoring_heartbeat()
if response.status_code == 200 and response.content == 'alive':
return True
return False
|
def sine_wave ( frequency ) : xs = tf . reshape ( tf . range ( _samples ( ) , dtype = tf . float32 ) , [ 1 , _samples ( ) , 1 ] ) ts = xs / FLAGS . sample_rate return tf . sin ( 2 * math . pi * frequency * ts )
| 1 |
python make sine wave
|
Emit a sine wave at the given frequency .
|
cosqa-train-13540
|
def sine_wave(frequency):
"""Emit a sine wave at the given frequency."""
xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1])
ts = xs / FLAGS.sample_rate
return tf.sin(2 * math.pi * frequency * ts)
|
def starts_with_prefix_in_list ( text , prefixes ) : for prefix in prefixes : if text . startswith ( prefix ) : return True return False
| 1 |
how to check if a string is prefix of other string in python
|
Return True if the given string starts with one of the prefixes in the given list otherwise return False .
|
cosqa-train-13541
|
def starts_with_prefix_in_list(text, prefixes):
"""
Return True if the given string starts with one of the prefixes in the given list, otherwise
return False.
Arguments:
text (str): Text to check for prefixes.
prefixes (list): List of prefixes to check for.
Returns:
bool: True if the given text starts with any of the given prefixes, otherwise False.
"""
for prefix in prefixes:
if text.startswith(prefix):
return True
return False
|
def cleanup_storage ( * args ) : ShardedClusters ( ) . cleanup ( ) ReplicaSets ( ) . cleanup ( ) Servers ( ) . cleanup ( ) sys . exit ( 0 )
| 1 |
python manually garbage collect
|
Clean up processes after SIGTERM or SIGINT is received .
|
cosqa-train-13542
|
def cleanup_storage(*args):
"""Clean up processes after SIGTERM or SIGINT is received."""
ShardedClusters().cleanup()
ReplicaSets().cleanup()
Servers().cleanup()
sys.exit(0)
|
def is_string ( val ) : try : basestring except NameError : return isinstance ( val , str ) return isinstance ( val , basestring )
| 1 |
how to check if a value is a string in python
|
Determines whether the passed value is a string safe for 2 / 3 .
|
cosqa-train-13543
|
def is_string(val):
"""Determines whether the passed value is a string, safe for 2/3."""
try:
basestring
except NameError:
return isinstance(val, str)
return isinstance(val, basestring)
|
def colorbar ( height , length , colormap ) : cbar = np . tile ( np . arange ( length ) * 1.0 / ( length - 1 ) , ( height , 1 ) ) cbar = ( cbar * ( colormap . values . max ( ) - colormap . values . min ( ) ) + colormap . values . min ( ) ) return colormap . colorize ( cbar )
| 0 |
python map colorbar to bar plot
|
Return the channels of a colorbar .
|
cosqa-train-13544
|
def colorbar(height, length, colormap):
"""Return the channels of a colorbar.
"""
cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1))
cbar = (cbar * (colormap.values.max() - colormap.values.min())
+ colormap.values.min())
return colormap.colorize(cbar)
|
def isin ( value , values ) : for i , v in enumerate ( value ) : if v not in np . array ( values ) [ : , i ] : return False return True
| 0 |
how to check if a value is in an array python
|
Check that value is in values
|
cosqa-train-13545
|
def isin(value, values):
""" Check that value is in values """
for i, v in enumerate(value):
if v not in np.array(values)[:, i]:
return False
return True
|
def imapchain ( * a , * * kwa ) : imap_results = map ( * a , * * kwa ) return itertools . chain ( * imap_results )
| 1 |
python map function with multiple inputs
|
Like map but also chains the results .
|
cosqa-train-13546
|
def imapchain(*a, **kwa):
""" Like map but also chains the results. """
imap_results = map( *a, **kwa )
return itertools.chain( *imap_results )
|
def instance_name ( string ) : invalid = ':/@' if set ( string ) . intersection ( invalid ) : msg = 'Invalid instance name {}' . format ( string ) raise argparse . ArgumentTypeError ( msg ) return string
| 1 |
how to check if a variable exists in python argparse
|
Check for valid instance name
|
cosqa-train-13547
|
def instance_name(string):
"""Check for valid instance name
"""
invalid = ':/@'
if set(string).intersection(invalid):
msg = 'Invalid instance name {}'.format(string)
raise argparse.ArgumentTypeError(msg)
return string
|
def OnDoubleClick ( self , event ) : node = HotMapNavigator . findNodeAtPosition ( self . hot_map , event . GetPosition ( ) ) if node : wx . PostEvent ( self , SquareActivationEvent ( node = node , point = event . GetPosition ( ) , map = self ) )
| 1 |
python map mouse click lat lon
|
Double click on a given square in the map
|
cosqa-train-13548
|
def OnDoubleClick(self, event):
"""Double click on a given square in the map"""
node = HotMapNavigator.findNodeAtPosition(self.hot_map, event.GetPosition())
if node:
wx.PostEvent( self, SquareActivationEvent( node=node, point=event.GetPosition(), map=self ) )
|
def check_update ( ) : logging . info ( 'Check for app updates.' ) try : update = updater . check_for_app_updates ( ) except Exception : logging . exception ( 'Check for updates failed.' ) return if update : print ( "!!! UPDATE AVAILABLE !!!\n" "" + static_data . PROJECT_URL + "\n\n" ) logging . info ( "Update available: " + static_data . PROJECT_URL ) else : logging . info ( "No update available." )
| 1 |
how to check if a website is updated python
|
Check for app updates and print / log them .
|
cosqa-train-13549
|
def check_update():
"""
Check for app updates and print/log them.
"""
logging.info('Check for app updates.')
try:
update = updater.check_for_app_updates()
except Exception:
logging.exception('Check for updates failed.')
return
if update:
print("!!! UPDATE AVAILABLE !!!\n"
"" + static_data.PROJECT_URL + "\n\n")
logging.info("Update available: " + static_data.PROJECT_URL)
else:
logging.info("No update available.")
|
def validate ( schema , data , owner = None ) : schema . _validate ( data = data , owner = owner )
| 1 |
python marshmallow validation schema from parent
|
Validate input data with input schema .
|
cosqa-train-13550
|
def validate(schema, data, owner=None):
"""Validate input data with input schema.
:param Schema schema: schema able to validate input data.
:param data: data to validate.
:param Schema owner: input schema parent schema.
:raises: Exception if the data is not validated.
"""
schema._validate(data=data, owner=owner)
|
def is_number ( obj ) : return isinstance ( obj , ( int , float , np . int_ , np . float_ ) )
| 1 |
how to check if an element in python is of number datatype
|
Check if obj is number .
|
cosqa-train-13551
|
def is_number(obj):
"""Check if obj is number."""
return isinstance(obj, (int, float, np.int_, np.float_))
|
def mpl_outside_legend ( ax , * * kwargs ) : box = ax . get_position ( ) ax . set_position ( [ box . x0 , box . y0 , box . width * 0.75 , box . height ] ) # Put a legend to the right of the current axis ax . legend ( loc = 'upper left' , bbox_to_anchor = ( 1 , 1 ) , * * kwargs )
| 1 |
python matplotlib reduce text and marker spacing in legend box
|
Places a legend box outside a matplotlib Axes instance .
|
cosqa-train-13552
|
def mpl_outside_legend(ax, **kwargs):
""" Places a legend box outside a matplotlib Axes instance. """
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.75, box.height])
# Put a legend to the right of the current axis
ax.legend(loc='upper left', bbox_to_anchor=(1, 1), **kwargs)
|
def service_available ( service_name ) : try : subprocess . check_output ( [ 'service' , service_name , 'status' ] , stderr = subprocess . STDOUT ) . decode ( 'UTF-8' ) except subprocess . CalledProcessError as e : return b'unrecognized service' not in e . output else : return True
| 1 |
how to check if services are running in linux python
|
Determine whether a system service is available
|
cosqa-train-13553
|
def service_available(service_name):
"""Determine whether a system service is available"""
try:
subprocess.check_output(
['service', service_name, 'status'],
stderr=subprocess.STDOUT).decode('UTF-8')
except subprocess.CalledProcessError as e:
return b'unrecognized service' not in e.output
else:
return True
|
def get_matrix ( self ) : return np . array ( [ self . get_row_list ( i ) for i in range ( self . row_count ( ) ) ] )
| 1 |
python matrix element not callable
|
Use numpy to create a real matrix object from the data
|
cosqa-train-13554
|
def get_matrix(self):
""" Use numpy to create a real matrix object from the data
:return: the matrix representation of the fvm
"""
return np.array([ self.get_row_list(i) for i in range(self.row_count()) ])
|
def numpy_aware_eq ( a , b ) : if isinstance ( a , np . ndarray ) or isinstance ( b , np . ndarray ) : return np . array_equal ( a , b ) if ( ( isinstance ( a , Iterable ) and isinstance ( b , Iterable ) ) and not isinstance ( a , str ) and not isinstance ( b , str ) ) : if len ( a ) != len ( b ) : return False return all ( numpy_aware_eq ( x , y ) for x , y in zip ( a , b ) ) return a == b
| 0 |
how to check if two arrays are equal in python
|
Return whether two objects are equal via recursion using : func : numpy . array_equal for comparing numpy arays .
|
cosqa-train-13555
|
def numpy_aware_eq(a, b):
"""Return whether two objects are equal via recursion, using
:func:`numpy.array_equal` for comparing numpy arays.
"""
if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):
return np.array_equal(a, b)
if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and
not isinstance(a, str) and not isinstance(b, str)):
if len(a) != len(b):
return False
return all(numpy_aware_eq(x, y) for x, y in zip(a, b))
return a == b
|
def fix ( h , i ) : down ( h , i , h . size ( ) ) up ( h , i )
| 1 |
python max heap and doubly linked list
|
Rearrange the heap after the item at position i got updated .
|
cosqa-train-13556
|
def fix(h, i):
"""Rearrange the heap after the item at position i got updated."""
down(h, i, h.size())
up(h, i)
|
def get_url_nofollow ( url ) : try : response = urlopen ( url ) code = response . getcode ( ) return code except HTTPError as e : return e . code except : return 0
| 1 |
how to check if urlopen fails python
|
function to get return code of a url
|
cosqa-train-13557
|
def get_url_nofollow(url):
"""
function to get return code of a url
Credits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-return-code-and-final-return-code-if-redirected/
"""
try:
response = urlopen(url)
code = response.getcode()
return code
except HTTPError as e:
return e.code
except:
return 0
|
def heappop_max ( heap ) : lastelt = heap . pop ( ) # raises appropriate IndexError if heap is empty if heap : returnitem = heap [ 0 ] heap [ 0 ] = lastelt _siftup_max ( heap , 0 ) return returnitem return lastelt
| 1 |
python max heap input spilt
|
Maxheap version of a heappop .
|
cosqa-train-13558
|
def heappop_max(heap):
"""Maxheap version of a heappop."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup_max(heap, 0)
return returnitem
return lastelt
|
def db_exists ( ) : logger . info ( "Checking to see if %s already exists" , repr ( DB [ "NAME" ] ) ) try : # Hide stderr since it is confusing here psql ( "" , stderr = subprocess . STDOUT ) except subprocess . CalledProcessError : return False return True
| 1 |
how to check if variable does not exist python
|
Test if DATABASES [ default ] exists
|
cosqa-train-13559
|
def db_exists():
"""Test if DATABASES['default'] exists"""
logger.info("Checking to see if %s already exists", repr(DB["NAME"]))
try:
# Hide stderr since it is confusing here
psql("", stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
return False
return True
|
def hmean_int ( a , a_min = 5778 , a_max = 1149851 ) : from scipy . stats import hmean return int ( round ( hmean ( np . clip ( a , a_min , a_max ) ) ) )
| 1 |
python max min average value in array
|
Harmonic mean of an array returns the closest int
|
cosqa-train-13560
|
def hmean_int(a, a_min=5778, a_max=1149851):
""" Harmonic mean of an array, returns the closest int
"""
from scipy.stats import hmean
return int(round(hmean(np.clip(a, a_min, a_max))))
|
def is_date ( thing ) : # known date types date_types = ( datetime . datetime , datetime . date , DateTime ) return isinstance ( thing , date_types )
| 1 |
how to check is date in python
|
Checks if the given thing represents a date
|
cosqa-train-13561
|
def is_date(thing):
"""Checks if the given thing represents a date
:param thing: The object to check if it is a date
:type thing: arbitrary object
:returns: True if we have a date object
:rtype: bool
"""
# known date types
date_types = (datetime.datetime,
datetime.date,
DateTime)
return isinstance(thing, date_types)
|
def min_or_none ( val1 , val2 ) : return min ( val1 , val2 , key = lambda x : sys . maxint if x is None else x )
| 1 |
python max with none
|
Returns min ( val1 val2 ) returning None only if both values are None
|
cosqa-train-13562
|
def min_or_none(val1, val2):
"""Returns min(val1, val2) returning None only if both values are None"""
return min(val1, val2, key=lambda x: sys.maxint if x is None else x)
|
def all_strings ( arr ) : if not isinstance ( [ ] , list ) : raise TypeError ( "non-list value found where list is expected" ) return all ( isinstance ( x , str ) for x in arr )
| 0 |
how to check list in astring in python
|
Ensures that the argument is a list that either is empty or contains only strings : param arr : list : return :
|
cosqa-train-13563
|
def all_strings(arr):
"""
Ensures that the argument is a list that either is empty or contains only strings
:param arr: list
:return:
"""
if not isinstance([], list):
raise TypeError("non-list value found where list is expected")
return all(isinstance(x, str) for x in arr)
|
def main_func ( args = None ) : # we have to initialize a gui even if we dont need one right now. # as soon as you call maya.standalone.initialize(), a QApplication # with type Tty is created. This is the type for conosle apps. # Because i have not found a way to replace that, we just init the gui. guimain . init_gui ( ) main . init ( ) launcher = Launcher ( ) parsed , unknown = launcher . parse_args ( args ) parsed . func ( parsed , unknown )
| 1 |
python maya pymel how can i call functions from another script
|
Main funcion when executing this module as script
|
cosqa-train-13564
|
def main_func(args=None):
"""Main funcion when executing this module as script
:param args: commandline arguments
:type args: list
:returns: None
:rtype: None
:raises: None
"""
# we have to initialize a gui even if we dont need one right now.
# as soon as you call maya.standalone.initialize(), a QApplication
# with type Tty is created. This is the type for conosle apps.
# Because i have not found a way to replace that, we just init the gui.
guimain.init_gui()
main.init()
launcher = Launcher()
parsed, unknown = launcher.parse_args(args)
parsed.func(parsed, unknown)
|
def launched ( ) : if not PREFIX : return False return os . path . realpath ( sys . prefix ) == os . path . realpath ( PREFIX )
| 1 |
how to check my python path
|
Test whether the current python environment is the correct lore env .
|
cosqa-train-13565
|
def launched():
"""Test whether the current python environment is the correct lore env.
:return: :any:`True` if the environment is launched
:rtype: bool
"""
if not PREFIX:
return False
return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX)
|
def md5_hash_file ( fh ) : md5 = hashlib . md5 ( ) while True : data = fh . read ( 8192 ) if not data : break md5 . update ( data ) return md5 . hexdigest ( )
| 1 |
python md5 file contents
|
Return the md5 hash of the given file - object
|
cosqa-train-13566
|
def md5_hash_file(fh):
"""Return the md5 hash of the given file-object"""
md5 = hashlib.md5()
while True:
data = fh.read(8192)
if not data:
break
md5.update(data)
return md5.hexdigest()
|
def is_readable_dir ( path ) : return os . path . isdir ( path ) and os . access ( path , os . R_OK ) and os . access ( path , os . X_OK )
| 1 |
how to check paths in python
|
Returns whether a path names an existing directory we can list and read files from .
|
cosqa-train-13567
|
def is_readable_dir(path):
"""Returns whether a path names an existing directory we can list and read files from."""
return os.path.isdir(path) and os.access(path, os.R_OK) and os.access(path, os.X_OK)
|
def timeit ( method ) : def timed ( * args , * * kw ) : time_start = time . time ( ) result = method ( * args , * * kw ) time_end = time . time ( ) print ( 'timeit: %r %2.2f sec (%r, %r) ' % ( method . __name__ , time_end - time_start , str ( args ) [ : 20 ] , kw ) ) return result return timed
| 0 |
python measure time for each function
|
A Python decorator for printing out the execution time for a function .
|
cosqa-train-13568
|
def timeit(method):
"""
A Python decorator for printing out the execution time for a function.
Adapted from:
www.andreas-jung.com/contents/a-python-decorator-for-measuring-the-execution-time-of-methods
"""
def timed(*args, **kw):
time_start = time.time()
result = method(*args, **kw)
time_end = time.time()
print('timeit: %r %2.2f sec (%r, %r) ' % (method.__name__, time_end-time_start, str(args)[:20], kw))
return result
return timed
|
def service_available ( service_name ) : try : subprocess . check_output ( [ 'service' , service_name , 'status' ] , stderr = subprocess . STDOUT ) . decode ( 'UTF-8' ) except subprocess . CalledProcessError as e : return b'unrecognized service' not in e . output else : return True
| 1 |
how to check services in python
|
Determine whether a system service is available
|
cosqa-train-13569
|
def service_available(service_name):
"""Determine whether a system service is available"""
try:
subprocess.check_output(
['service', service_name, 'status'],
stderr=subprocess.STDOUT).decode('UTF-8')
except subprocess.CalledProcessError as e:
return b'unrecognized service' not in e.output
else:
return True
|
def value ( self ) : if self . _prop . fget is None : raise AttributeError ( 'Unable to read attribute' ) return self . _prop . fget ( self . _obj )
| 1 |
python member property getter
|
Value of property .
|
cosqa-train-13570
|
def value(self):
"""Value of property."""
if self._prop.fget is None:
raise AttributeError('Unable to read attribute')
return self._prop.fget(self._obj)
|
def is_numeric_dtype ( dtype ) : dtype = np . dtype ( dtype ) return np . issubsctype ( getattr ( dtype , 'base' , None ) , np . number )
| 1 |
how to check type of object is numeric python
|
Return True if dtype is a numeric type .
|
cosqa-train-13571
|
def is_numeric_dtype(dtype):
"""Return ``True`` if ``dtype`` is a numeric type."""
dtype = np.dtype(dtype)
return np.issubsctype(getattr(dtype, 'base', None), np.number)
|
def contextMenuEvent ( self , event ) : self . update_menu ( ) self . menu . popup ( event . globalPos ( ) )
| 1 |
python menu clicked signal/slot
|
Override Qt method
|
cosqa-train-13572
|
def contextMenuEvent(self, event):
"""Override Qt method"""
self.update_menu()
self.menu.popup(event.globalPos())
|
def is_float ( value ) : return isinstance ( value , float ) or isinstance ( value , int ) or isinstance ( value , np . float64 ) , float ( value )
| 1 |
how to check value is int or float python
|
must be a float
|
cosqa-train-13573
|
def is_float(value):
"""must be a float"""
return isinstance(value, float) or isinstance(value, int) or isinstance(value, np.float64), float(value)
|
def dict_merge ( set1 , set2 ) : return dict ( list ( set1 . items ( ) ) + list ( set2 . items ( ) ) )
| 1 |
python merge 2 dict
|
Joins two dictionaries .
|
cosqa-train-13574
|
def dict_merge(set1, set2):
"""Joins two dictionaries."""
return dict(list(set1.items()) + list(set2.items()))
|
def load_library ( version ) : check_version ( version ) module_name = SUPPORTED_LIBRARIES [ version ] lib = sys . modules . get ( module_name ) if lib is None : lib = importlib . import_module ( module_name ) return lib
| 1 |
how to check what python libraries i have
|
Load the correct module according to the version
|
cosqa-train-13575
|
def load_library(version):
"""
Load the correct module according to the version
:type version: ``str``
:param version: the version of the library to be loaded (e.g. '2.6')
:rtype: module object
"""
check_version(version)
module_name = SUPPORTED_LIBRARIES[version]
lib = sys.modules.get(module_name)
if lib is None:
lib = importlib.import_module(module_name)
return lib
|
def dict_merge ( set1 , set2 ) : return dict ( list ( set1 . items ( ) ) + list ( set2 . items ( ) ) )
| 1 |
python merge two set in single dict
|
Joins two dictionaries .
|
cosqa-train-13576
|
def dict_merge(set1, set2):
"""Joins two dictionaries."""
return dict(list(set1.items()) + list(set2.items()))
|
def string_to_list ( string , sep = "," , filter_empty = False ) : return [ value . strip ( ) for value in string . split ( sep ) if ( not filter_empty or value ) ]
| 1 |
how to civert stings seprated by comma into list in python
|
Transforma una string con elementos separados por sep en una lista .
|
cosqa-train-13577
|
def string_to_list(string, sep=",", filter_empty=False):
"""Transforma una string con elementos separados por `sep` en una lista."""
return [value.strip() for value in string.split(sep)
if (not filter_empty or value)]
|
def is_enum_type ( type_ ) : return isinstance ( type_ , type ) and issubclass ( type_ , tuple ( _get_types ( Types . ENUM ) ) )
| 1 |
python method accept enum type
|
Checks if the given type is an enum type .
|
cosqa-train-13578
|
def is_enum_type(type_):
""" Checks if the given type is an enum type.
:param type_: The type to check
:return: True if the type is a enum type, otherwise False
:rtype: bool
"""
return isinstance(type_, type) and issubclass(type_, tuple(_get_types(Types.ENUM)))
|
def reset ( self ) : self . prevframe = None self . wasmoving = False self . t0 = 0 self . ismoving = False
| 1 |
how to clear a frame in python
|
Reset analyzer state
|
cosqa-train-13579
|
def reset(self):
"""Reset analyzer state
"""
self.prevframe = None
self.wasmoving = False
self.t0 = 0
self.ismoving = False
|
def __ror__ ( self , other ) : return self . callable ( * ( self . args + ( other , ) ) , * * self . kwargs )
| 1 |
python method chaining return self
|
The main machinery of the Pipe calling the chosen callable with the recorded arguments .
|
cosqa-train-13580
|
def __ror__(self, other):
"""The main machinery of the Pipe, calling the chosen callable with the recorded arguments."""
return self.callable(*(self.args + (other, )), **self.kwargs)
|
def remove ( self , key ) : item = self . item_finder . pop ( key ) item [ - 1 ] = None self . removed_count += 1
| 0 |
how to clear the element in deque python
|
remove the value found at key from the queue
|
cosqa-train-13581
|
def remove(self, key):
"""remove the value found at key from the queue"""
item = self.item_finder.pop(key)
item[-1] = None
self.removed_count += 1
|
def pop ( self , key ) : if key in self . _keys : self . _keys . remove ( key ) super ( ListDict , self ) . pop ( key )
| 1 |
python method to remove entry from dictionary
|
Remove key from dict and return value .
|
cosqa-train-13582
|
def pop (self, key):
"""Remove key from dict and return value."""
if key in self._keys:
self._keys.remove(key)
super(ListDict, self).pop(key)
|
def accel_next ( self , * args ) : if self . get_notebook ( ) . get_current_page ( ) + 1 == self . get_notebook ( ) . get_n_pages ( ) : self . get_notebook ( ) . set_current_page ( 0 ) else : self . get_notebook ( ) . next_page ( ) return True
| 1 |
how to click next page using python
|
Callback to go to the next tab . Called by the accel key .
|
cosqa-train-13583
|
def accel_next(self, *args):
"""Callback to go to the next tab. Called by the accel key.
"""
if self.get_notebook().get_current_page() + 1 == self.get_notebook().get_n_pages():
self.get_notebook().set_current_page(0)
else:
self.get_notebook().next_page()
return True
|
def datetime_delta_to_ms ( delta ) : delta_ms = delta . days * 24 * 60 * 60 * 1000 delta_ms += delta . seconds * 1000 delta_ms += delta . microseconds / 1000 delta_ms = int ( delta_ms ) return delta_ms
| 0 |
python millisecond to timedelta
|
Given a datetime . timedelta object return the delta in milliseconds
|
cosqa-train-13584
|
def datetime_delta_to_ms(delta):
"""
Given a datetime.timedelta object, return the delta in milliseconds
"""
delta_ms = delta.days * 24 * 60 * 60 * 1000
delta_ms += delta.seconds * 1000
delta_ms += delta.microseconds / 1000
delta_ms = int(delta_ms)
return delta_ms
|
def pair_strings_sum_formatter ( a , b ) : if b [ : 1 ] == "-" : return "{0} - {1}" . format ( a , b [ 1 : ] ) return "{0} + {1}" . format ( a , b )
| 1 |
how to combine two number strings in python
|
Formats the sum of a and b .
|
cosqa-train-13585
|
def pair_strings_sum_formatter(a, b):
"""
Formats the sum of a and b.
Note
----
Both inputs are numbers already converted to strings.
"""
if b[:1] == "-":
return "{0} - {1}".format(a, b[1:])
return "{0} + {1}".format(a, b)
|
def distance_to_line ( a , b , p ) : return distance ( closest_point ( a , b , p ) , p )
| 1 |
python min distance two line segments
|
Closest distance between a line segment and a point
|
cosqa-train-13586
|
def distance_to_line(a, b, p):
"""Closest distance between a line segment and a point
Args:
a ([float, float]): x and y coordinates. Line start
b ([float, float]): x and y coordinates. Line end
p ([float, float]): x and y coordinates. Point to compute the distance
Returns:
float
"""
return distance(closest_point(a, b, p), p)
|
def compare ( self , first , second ) : if first . lower ( ) == second . lower ( ) : return True else : return False
| 1 |
how to compare without case in python
|
Case in - sensitive comparison of two strings . Required arguments : * first - The first string to compare . * second - The second string to compare .
|
cosqa-train-13587
|
def compare(self, first, second):
"""
Case in-sensitive comparison of two strings.
Required arguments:
* first - The first string to compare.
* second - The second string to compare.
"""
if first.lower() == second.lower():
return True
else:
return False
|
def comments ( self ) : if self . _comments is None : self . _comments = [ c for c in self . grammar . children if c . is_type ( TokenType . comment ) ] return self . _comments
| 1 |
python minidom get comments
|
The AST comments .
|
cosqa-train-13588
|
def comments(self):
"""The AST comments."""
if self._comments is None:
self._comments = [c for c in self.grammar.children if c.is_type(TokenType.comment)]
return self._comments
|
def cpp_prog_builder ( build_context , target ) : yprint ( build_context . conf , 'Build CppProg' , target ) workspace_dir = build_context . get_workspace ( 'CppProg' , target . name ) build_cpp ( build_context , target , target . compiler_config , workspace_dir )
| 1 |
how to compile python program to use in c++
|
Build a C ++ binary executable
|
cosqa-train-13589
|
def cpp_prog_builder(build_context, target):
"""Build a C++ binary executable"""
yprint(build_context.conf, 'Build CppProg', target)
workspace_dir = build_context.get_workspace('CppProg', target.name)
build_cpp(build_context, target, target.compiler_config, workspace_dir)
|
def tag_to_dict ( html ) : element = document_fromstring ( html ) . xpath ( "//html/body/child::*" ) [ 0 ] attributes = dict ( element . attrib ) attributes [ "text" ] = element . text_content ( ) return attributes
| 1 |
python minidom html to dict
|
Extract tag s attributes into a dict .
|
cosqa-train-13590
|
def tag_to_dict(html):
"""Extract tag's attributes into a `dict`."""
element = document_fromstring(html).xpath("//html/body/child::*")[0]
attributes = dict(element.attrib)
attributes["text"] = element.text_content()
return attributes
|
def build_output ( self , fout ) : fout . write ( '\n' . join ( [ s for s in self . out ] ) )
| 1 |
how to concatenate output in same file python
|
Squash self . out into string .
|
cosqa-train-13591
|
def build_output(self, fout):
"""Squash self.out into string.
Join every line in self.out with a new line and write the
result to the output file.
"""
fout.write('\n'.join([s for s in self.out]))
|
def mock_decorator ( * args , * * kwargs ) : def _called_decorator ( dec_func ) : @ wraps ( dec_func ) def _decorator ( * args , * * kwargs ) : return dec_func ( ) return _decorator return _called_decorator
| 1 |
python mock call original function
|
Mocked decorator needed in the case we need to mock a decorator
|
cosqa-train-13592
|
def mock_decorator(*args, **kwargs):
"""Mocked decorator, needed in the case we need to mock a decorator"""
def _called_decorator(dec_func):
@wraps(dec_func)
def _decorator(*args, **kwargs):
return dec_func()
return _decorator
return _called_decorator
|
def cols_str ( columns ) : cols = "" for c in columns : cols = cols + wrap ( c ) + ', ' return cols [ : - 2 ]
| 1 |
how to concatenate strings into a column in python
|
Concatenate list of columns into a string .
|
cosqa-train-13593
|
def cols_str(columns):
"""Concatenate list of columns into a string."""
cols = ""
for c in columns:
cols = cols + wrap(c) + ', '
return cols[:-2]
|
def api_test ( method = 'GET' , * * response_kwargs ) : method = method . lower ( ) def api_test_factory ( fn ) : @ functools . wraps ( fn ) @ mock . patch ( 'requests.{}' . format ( method ) ) def execute_test ( method_func , * args , * * kwargs ) : method_func . return_value = MockResponse ( * * response_kwargs ) expected_url , response = fn ( * args , * * kwargs ) method_func . assert_called_once ( ) assert_valid_api_call ( method_func , expected_url ) assert isinstance ( response , JSONAPIParser ) assert response . json_data is method_func . return_value . data return execute_test return api_test_factory
| 0 |
python mock test rest api example
|
Decorator to ensure API calls are made and return expected data .
|
cosqa-train-13594
|
def api_test(method='GET', **response_kwargs):
""" Decorator to ensure API calls are made and return expected data. """
method = method.lower()
def api_test_factory(fn):
@functools.wraps(fn)
@mock.patch('requests.{}'.format(method))
def execute_test(method_func, *args, **kwargs):
method_func.return_value = MockResponse(**response_kwargs)
expected_url, response = fn(*args, **kwargs)
method_func.assert_called_once()
assert_valid_api_call(method_func, expected_url)
assert isinstance(response, JSONAPIParser)
assert response.json_data is method_func.return_value.data
return execute_test
return api_test_factory
|
def _config_session ( ) : config = tf . ConfigProto ( ) config . gpu_options . allow_growth = True config . gpu_options . visible_device_list = '0' return tf . Session ( config = config )
| 1 |
how to configure python script to tensorflow gpu
|
Configure session for particular device
|
cosqa-train-13595
|
def _config_session():
"""
Configure session for particular device
Returns:
tensorflow.Session
"""
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.gpu_options.visible_device_list = '0'
return tf.Session(config=config)
|
def gaussian_variogram_model ( m , d ) : psill = float ( m [ 0 ] ) range_ = float ( m [ 1 ] ) nugget = float ( m [ 2 ] ) return psill * ( 1. - np . exp ( - d ** 2. / ( range_ * 4. / 7. ) ** 2. ) ) + nugget
| 1 |
python model gaussian curve
|
Gaussian model m is [ psill range nugget ]
|
cosqa-train-13596
|
def gaussian_variogram_model(m, d):
"""Gaussian model, m is [psill, range, nugget]"""
psill = float(m[0])
range_ = float(m[1])
nugget = float(m[2])
return psill * (1. - np.exp(-d**2./(range_*4./7.)**2.)) + nugget
|
def advance_one_line ( self ) : current_line = self . _current_token . line_number while current_line == self . _current_token . line_number : self . _current_token = ConfigParser . Token ( * next ( self . _token_generator ) )
| 1 |
how to continue to the next line in python comment
|
Advances to next line .
|
cosqa-train-13597
|
def advance_one_line(self):
"""Advances to next line."""
current_line = self._current_token.line_number
while current_line == self._current_token.line_number:
self._current_token = ConfigParser.Token(*next(self._token_generator))
|
def get_object_or_none ( model , * args , * * kwargs ) : try : return model . _default_manager . get ( * args , * * kwargs ) except model . DoesNotExist : return None
| 0 |
python model get if exists
|
Like get_object_or_404 but doesn t throw an exception .
|
cosqa-train-13598
|
def get_object_or_none(model, *args, **kwargs):
"""
Like get_object_or_404, but doesn't throw an exception.
Allows querying for an object that might not exist without triggering
an exception.
"""
try:
return model._default_manager.get(*args, **kwargs)
except model.DoesNotExist:
return None
|
def copy ( a ) : shared = anonymousmemmap ( a . shape , dtype = a . dtype ) shared [ : ] = a [ : ] return shared
| 1 |
how to copy the shape of an array in python
|
Copy an array to the shared memory .
|
cosqa-train-13599
|
def copy(a):
""" Copy an array to the shared memory.
Notes
-----
copy is not always necessary because the private memory is always copy-on-write.
Use :code:`a = copy(a)` to immediately dereference the old 'a' on private memory
"""
shared = anonymousmemmap(a.shape, dtype=a.dtype)
shared[:] = a[:]
return shared
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.