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 _manhattan_distance ( vec_a , vec_b ) : if len ( vec_a ) != len ( vec_b ) : raise ValueError ( 'len(vec_a) must equal len(vec_b)' ) return sum ( map ( lambda a , b : abs ( a - b ) , vec_a , vec_b ) )
| 1 |
implement manhattan distance for 8puzzle python
|
Return manhattan distance between two lists of numbers .
|
cosqa-train-14200
|
def _manhattan_distance(vec_a, vec_b):
"""Return manhattan distance between two lists of numbers."""
if len(vec_a) != len(vec_b):
raise ValueError('len(vec_a) must equal len(vec_b)')
return sum(map(lambda a, b: abs(a - b), vec_a, vec_b))
|
def closeEvent ( self , e ) : self . emit ( 'close_widget' ) super ( DockWidget , self ) . closeEvent ( e )
| 1 |
python tkinter on close window
|
Qt slot when the window is closed .
|
cosqa-train-14201
|
def closeEvent(self, e):
"""Qt slot when the window is closed."""
self.emit('close_widget')
super(DockWidget, self).closeEvent(e)
|
def uint8sc ( im ) : im = np . asarray ( im ) immin = im . min ( ) immax = im . max ( ) imrange = immax - immin return cv2 . convertScaleAbs ( im - immin , alpha = 255 / imrange )
| 1 |
imshow scaling cv2 python
|
Scale the image to uint8
|
cosqa-train-14202
|
def uint8sc(im):
"""Scale the image to uint8
Parameters:
-----------
im: 2d array
The image
Returns:
--------
im: 2d array (dtype uint8)
The scaled image to uint8
"""
im = np.asarray(im)
immin = im.min()
immax = im.max()
imrange = immax - immin
return cv2.convertScaleAbs(im - immin, alpha=255 / imrange)
|
def detach ( self , * items ) : self . _visual_drag . detach ( * items ) ttk . Treeview . detach ( self , * items )
| 1 |
python tkinter treeview deleate an item
|
Unlinks all of the specified items from the tree .
|
cosqa-train-14203
|
def detach(self, *items):
"""
Unlinks all of the specified items from the tree.
The items and all of their descendants are still present, and may be
reinserted at another point in the tree, but will not be displayed.
The root item may not be detached.
:param items: list of item identifiers
:type items: sequence[str]
"""
self._visual_drag.detach(*items)
ttk.Treeview.detach(self, *items)
|
def instance_contains ( container , item ) : return item in ( member for _ , member in inspect . getmembers ( container ) )
| 0 |
in or contains method in python
|
Search into instance attributes properties and return values of no - args methods .
|
cosqa-train-14204
|
def instance_contains(container, item):
"""Search into instance attributes, properties and return values of no-args methods."""
return item in (member for _, member in inspect.getmembers(container))
|
def remote_file_exists ( self , url ) : status = requests . head ( url ) . status_code if status != 200 : raise RemoteFileDoesntExist
| 1 |
python to check if file arrives
|
Checks whether the remote file exists .
|
cosqa-train-14205
|
def remote_file_exists(self, url):
""" Checks whether the remote file exists.
:param url:
The url that has to be checked.
:type url:
String
:returns:
**True** if remote file exists and **False** if it doesn't exist.
"""
status = requests.head(url).status_code
if status != 200:
raise RemoteFileDoesntExist
|
def ensure_hbounds ( self ) : self . cursor . x = min ( max ( 0 , self . cursor . x ) , self . columns - 1 )
| 1 |
in python how to use a mouse position for rectangle
|
Ensure the cursor is within horizontal screen bounds .
|
cosqa-train-14206
|
def ensure_hbounds(self):
"""Ensure the cursor is within horizontal screen bounds."""
self.cursor.x = min(max(0, self.cursor.x), self.columns - 1)
|
def s3_connect ( bucket_name , s3_access_key_id , s3_secret_key ) : conn = connect_s3 ( s3_access_key_id , s3_secret_key ) try : return conn . get_bucket ( bucket_name ) except S3ResponseError as e : if e . status == 403 : raise Exception ( "Bad Amazon S3 credentials." ) raise
| 1 |
python to connect to s3
|
Returns a Boto connection to the provided S3 bucket .
|
cosqa-train-14207
|
def s3_connect(bucket_name, s3_access_key_id, s3_secret_key):
""" Returns a Boto connection to the provided S3 bucket. """
conn = connect_s3(s3_access_key_id, s3_secret_key)
try:
return conn.get_bucket(bucket_name)
except S3ResponseError as e:
if e.status == 403:
raise Exception("Bad Amazon S3 credentials.")
raise
|
def Proxy ( f ) : def Wrapped ( self , * args ) : return getattr ( self , f ) ( * args ) return Wrapped
| 1 |
in python static method should be decorated with
|
A helper to create a proxy method in a class .
|
cosqa-train-14208
|
def Proxy(f):
"""A helper to create a proxy method in a class."""
def Wrapped(self, *args):
return getattr(self, f)(*args)
return Wrapped
|
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 |
python to determine if services are running
|
Determine whether a system service is available
|
cosqa-train-14209
|
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 to_str ( s ) : if isinstance ( s , bytes ) : s = s . decode ( 'utf-8' ) elif not isinstance ( s , str ) : s = str ( s ) return s
| 1 |
in python who is responsible to change raw input to string
|
Convert bytes and non - string into Python 3 str
|
cosqa-train-14210
|
def to_str(s):
"""
Convert bytes and non-string into Python 3 str
"""
if isinstance(s, bytes):
s = s.decode('utf-8')
elif not isinstance(s, str):
s = str(s)
return s
|
def table_top_abs ( self ) : table_height = np . array ( [ 0 , 0 , self . table_full_size [ 2 ] ] ) return string_to_array ( self . floor . get ( "pos" ) ) + table_height
| 0 |
python top 5 row
|
Returns the absolute position of table top
|
cosqa-train-14211
|
def table_top_abs(self):
"""Returns the absolute position of table top"""
table_height = np.array([0, 0, self.table_full_size[2]])
return string_to_array(self.floor.get("pos")) + table_height
|
def process_docstring ( app , what , name , obj , options , lines ) : # pylint: disable=unused-argument # pylint: disable=too-many-arguments lines . extend ( _format_contracts ( what = what , obj = obj ) )
| 1 |
include latex in python docstrings
|
React to a docstring event and append contracts to it .
|
cosqa-train-14212
|
def process_docstring(app, what, name, obj, options, lines):
"""React to a docstring event and append contracts to it."""
# pylint: disable=unused-argument
# pylint: disable=too-many-arguments
lines.extend(_format_contracts(what=what, obj=obj))
|
def python_mime ( fn ) : @ wraps ( fn ) def python_mime_decorator ( * args , * * kwargs ) : response . content_type = "text/x-python" return fn ( * args , * * kwargs ) return python_mime_decorator
| 1 |
python tornado rest set mimetype
|
Decorator which adds correct MIME type for python source to the decorated bottle API function .
|
cosqa-train-14213
|
def python_mime(fn):
"""
Decorator, which adds correct MIME type for python source to the decorated
bottle API function.
"""
@wraps(fn)
def python_mime_decorator(*args, **kwargs):
response.content_type = "text/x-python"
return fn(*args, **kwargs)
return python_mime_decorator
|
def rstjinja ( app , docname , source ) : # Make sure we're outputting HTML if app . builder . format != 'html' : return src = source [ 0 ] rendered = app . builder . templates . render_string ( src , app . config . html_context ) source [ 0 ] = rendered
| 1 |
incoporating html jsscript with python project
|
Render our pages as a jinja template for fancy templating goodness .
|
cosqa-train-14214
|
def rstjinja(app, docname, source):
"""
Render our pages as a jinja template for fancy templating goodness.
"""
# Make sure we're outputting HTML
if app.builder.format != 'html':
return
src = source[0]
rendered = app.builder.templates.render_string(
src, app.config.html_context
)
source[0] = rendered
|
def __run ( self ) : sys . settrace ( self . globaltrace ) self . __run_backup ( ) self . run = self . __run_backup
| 1 |
python trace function call
|
Hacked run function which installs the trace .
|
cosqa-train-14215
|
def __run(self):
"""Hacked run function, which installs the trace."""
sys.settrace(self.globaltrace)
self.__run_backup()
self.run = self.__run_backup
|
def required_header ( header ) : if header in IGNORE_HEADERS : return False if header . startswith ( 'HTTP_' ) or header == 'CONTENT_TYPE' : return True return False
| 1 |
incorrect header check python
|
Function that verify if the header parameter is a essential header
|
cosqa-train-14216
|
def required_header(header):
"""Function that verify if the header parameter is a essential header
:param header: A string represented a header
:returns: A boolean value that represent if the header is required
"""
if header in IGNORE_HEADERS:
return False
if header.startswith('HTTP_') or header == 'CONTENT_TYPE':
return True
return False
|
def _read_json_file ( self , json_file ) : self . log . debug ( "Reading '%s' JSON file..." % json_file ) with open ( json_file , 'r' ) as f : return json . load ( f , object_pairs_hook = OrderedDict )
| 1 |
python treat json file as objects
|
Helper function to read JSON file as OrderedDict
|
cosqa-train-14217
|
def _read_json_file(self, json_file):
""" Helper function to read JSON file as OrderedDict """
self.log.debug("Reading '%s' JSON file..." % json_file)
with open(json_file, 'r') as f:
return json.load(f, object_pairs_hook=OrderedDict)
|
def _column_resized ( self , col , old_width , new_width ) : self . dataTable . setColumnWidth ( col , new_width ) self . _update_layout ( )
| 1 |
increase width of columns panda python
|
Update the column width .
|
cosqa-train-14218
|
def _column_resized(self, col, old_width, new_width):
"""Update the column width."""
self.dataTable.setColumnWidth(col, new_width)
self._update_layout()
|
def print_tree ( self , indent = 2 ) : config . LOGGER . info ( "{indent}{data}" . format ( indent = " " * indent , data = str ( self ) ) ) for child in self . children : child . print_tree ( indent + 1 )
| 1 |
python tree structure using indent
|
print_tree : prints out structure of tree Args : indent ( int ) : What level of indentation at which to start printing Returns : None
|
cosqa-train-14219
|
def print_tree(self, indent=2):
""" print_tree: prints out structure of tree
Args: indent (int): What level of indentation at which to start printing
Returns: None
"""
config.LOGGER.info("{indent}{data}".format(indent=" " * indent, data=str(self)))
for child in self.children:
child.print_tree(indent + 1)
|
def sorted_index ( values , x ) : i = bisect_left ( values , x ) j = bisect_right ( values , x ) return values [ i : j ] . index ( x ) + i
| 1 |
index of the val in list python
|
For list values returns the index location of element x . If x does not exist will raise an error .
|
cosqa-train-14220
|
def sorted_index(values, x):
"""
For list, values, returns the index location of element x. If x does not exist will raise an error.
:param values: list
:param x: item
:return: integer index
"""
i = bisect_left(values, x)
j = bisect_right(values, x)
return values[i:j].index(x) + i
|
def register_view ( self , view ) : super ( ListViewController , self ) . register_view ( view ) self . tree_view . connect ( 'button_press_event' , self . mouse_click )
| 1 |
python treeview bind double click
|
Register callbacks for button press events and selection changed
|
cosqa-train-14221
|
def register_view(self, view):
"""Register callbacks for button press events and selection changed"""
super(ListViewController, self).register_view(view)
self.tree_view.connect('button_press_event', self.mouse_click)
|
def make_prefixed_stack_name ( prefix , template_path ) : parts = os . path . basename ( template_path ) . split ( '-' ) parts = parts if len ( parts ) == 1 else parts [ : - 1 ] return ( '%s-%s' % ( prefix , '-' . join ( parts ) ) ) . split ( '.' ) [ 0 ]
| 1 |
infix to prefix in stack coding in python
|
cosqa-train-14222
|
def make_prefixed_stack_name(prefix, template_path):
"""
:param prefix:
:param template_path:
"""
parts = os.path.basename(template_path).split('-')
parts = parts if len(parts) == 1 else parts[:-1]
return ('%s-%s' % (prefix, '-'.join(parts))).split('.')[0]
|
|
def _trim ( self , somestr ) : tmp = RE_LSPACES . sub ( "" , somestr ) tmp = RE_TSPACES . sub ( "" , tmp ) return str ( tmp )
| 1 |
python trim left side of a string
|
Trim left - right given string
|
cosqa-train-14223
|
def _trim(self, somestr):
""" Trim left-right given string """
tmp = RE_LSPACES.sub("", somestr)
tmp = RE_TSPACES.sub("", tmp)
return str(tmp)
|
def __init__ ( self , capacity = 10 ) : super ( ) . __init__ ( ) self . _array = [ None ] * capacity self . _front = 0 self . _rear = 0
| 1 |
initializing a list of a certain size in python
|
Initialize python List with capacity of 10 or user given input . Python List type is a dynamic array so we have to restrict its dynamic nature to make it work like a static array .
|
cosqa-train-14224
|
def __init__(self, capacity=10):
"""
Initialize python List with capacity of 10 or user given input.
Python List type is a dynamic array, so we have to restrict its
dynamic nature to make it work like a static array.
"""
super().__init__()
self._array = [None] * capacity
self._front = 0
self._rear = 0
|
def drop_bad_characters ( text ) : # Strip all non-ascii and non-printable characters text = '' . join ( [ c for c in text if c in ALLOWED_CHARS ] ) return text
| 0 |
python trim non word characters
|
Takes a text and drops all non - printable and non - ascii characters and also any whitespace characters that aren t space .
|
cosqa-train-14225
|
def drop_bad_characters(text):
"""Takes a text and drops all non-printable and non-ascii characters and
also any whitespace characters that aren't space.
:arg str text: the text to fix
:returns: text with all bad characters dropped
"""
# Strip all non-ascii and non-printable characters
text = ''.join([c for c in text if c in ALLOWED_CHARS])
return text
|
def cint8_array_to_numpy ( cptr , length ) : if isinstance ( cptr , ctypes . POINTER ( ctypes . c_int8 ) ) : return np . fromiter ( cptr , dtype = np . int8 , count = length ) else : raise RuntimeError ( 'Expected int pointer' )
| 1 |
inputting a python array in ctypes buffer
|
Convert a ctypes int pointer array to a numpy array .
|
cosqa-train-14226
|
def cint8_array_to_numpy(cptr, length):
"""Convert a ctypes int pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_int8)):
return np.fromiter(cptr, dtype=np.int8, count=length)
else:
raise RuntimeError('Expected int pointer')
|
def round_sig ( x , sig ) : return round ( x , sig - int ( floor ( log10 ( abs ( x ) ) ) ) - 1 )
| 1 |
python truncate to significant digits
|
Round the number to the specified number of significant figures
|
cosqa-train-14227
|
def round_sig(x, sig):
"""Round the number to the specified number of significant figures"""
return round(x, sig - int(floor(log10(abs(x)))) - 1)
|
def append_position_to_token_list ( token_list ) : return [ PositionToken ( value . content , value . gd , index , index + 1 ) for ( index , value ) in enumerate ( token_list ) ]
| 0 |
invalid token python for an array
|
Converts a list of Token into a list of Token asuming size == 1
|
cosqa-train-14228
|
def append_position_to_token_list(token_list):
"""Converts a list of Token into a list of Token, asuming size == 1"""
return [PositionToken(value.content, value.gd, index, index+1) for (index, value) in enumerate(token_list)]
|
def _tuple_repr ( data ) : if len ( data ) == 1 : return "(%s,)" % rpr ( data [ 0 ] ) else : return "(%s)" % ", " . join ( [ rpr ( x ) for x in data ] )
| 1 |
python tuple with lists of objects show string representation
|
Return a repr () for a list / tuple
|
cosqa-train-14229
|
def _tuple_repr(data):
"""Return a repr() for a list/tuple"""
if len(data) == 1:
return "(%s,)" % rpr(data[0])
else:
return "(%s)" % ", ".join([rpr(x) for x in data])
|
def logout ( cache ) : cache . set ( flask . session [ 'auth0_key' ] , None ) flask . session . clear ( ) return True
| 1 |
invalidate old session after authantification python flask
|
Logs out the current session by removing it from the cache . This is expected to only occur when a session has
|
cosqa-train-14230
|
def logout(cache):
"""
Logs out the current session by removing it from the cache. This is
expected to only occur when a session has
"""
cache.set(flask.session['auth0_key'], None)
flask.session.clear()
return True
|
def list_to_csv ( value ) : if isinstance ( value , ( list , tuple , set ) ) : value = "," . join ( value ) return value
| 1 |
python turn an array into comma seperated string
|
Converts list to string with comma separated values . For string is no - op .
|
cosqa-train-14231
|
def list_to_csv(value):
"""
Converts list to string with comma separated values. For string is no-op.
"""
if isinstance(value, (list, tuple, set)):
value = ",".join(value)
return value
|
def MatrixInverse ( a , adj ) : return np . linalg . inv ( a if not adj else _adjoint ( a ) ) ,
| 1 |
inverse matrix in python without numpy
|
Matrix inversion op .
|
cosqa-train-14232
|
def MatrixInverse(a, adj):
"""
Matrix inversion op.
"""
return np.linalg.inv(a if not adj else _adjoint(a)),
|
def on_success ( self , fn , * args , * * kwargs ) : self . _callbacks . append ( ( fn , args , kwargs ) ) result = self . _resulted_in if result is not _NOTHING_YET : self . _succeed ( result = result )
| 0 |
python turn callback to future
|
Call the given callback if or when the connected deferred succeeds .
|
cosqa-train-14233
|
def on_success(self, fn, *args, **kwargs):
"""
Call the given callback if or when the connected deferred succeeds.
"""
self._callbacks.append((fn, args, kwargs))
result = self._resulted_in
if result is not _NOTHING_YET:
self._succeed(result=result)
|
def cross_product_matrix ( vec ) : return np . array ( [ [ 0 , - vec [ 2 ] , vec [ 1 ] ] , [ vec [ 2 ] , 0 , - vec [ 0 ] ] , [ - vec [ 1 ] , vec [ 0 ] , 0 ] ] )
| 1 |
inverse of 3x3 matrix python
|
Returns a 3x3 cross - product matrix from a 3 - element vector .
|
cosqa-train-14234
|
def cross_product_matrix(vec):
"""Returns a 3x3 cross-product matrix from a 3-element vector."""
return np.array([[0, -vec[2], vec[1]],
[vec[2], 0, -vec[0]],
[-vec[1], vec[0], 0]])
|
def _to_array ( value ) : if isinstance ( value , ( tuple , list ) ) : return array ( value ) elif isinstance ( value , ( float , int ) ) : return np . float64 ( value ) else : return value
| 1 |
python turn list of list into a numpy array
|
As a convenience turn Python lists and tuples into NumPy arrays .
|
cosqa-train-14235
|
def _to_array(value):
"""As a convenience, turn Python lists and tuples into NumPy arrays."""
if isinstance(value, (tuple, list)):
return array(value)
elif isinstance(value, (float, int)):
return np.float64(value)
else:
return value
|
def MatrixInverse ( a , adj ) : return np . linalg . inv ( a if not adj else _adjoint ( a ) ) ,
| 0 |
inverse of matrix in python numpy
|
Matrix inversion op .
|
cosqa-train-14236
|
def MatrixInverse(a, adj):
"""
Matrix inversion op.
"""
return np.linalg.inv(a if not adj else _adjoint(a)),
|
def string_to_float_list ( string_var ) : try : return [ float ( s ) for s in string_var . strip ( '[' ) . strip ( ']' ) . split ( ', ' ) ] except : return [ float ( s ) for s in string_var . strip ( '[' ) . strip ( ']' ) . split ( ',' ) ]
| 0 |
python turn list of strings into list of floats
|
Pull comma separated string values out of a text file and converts them to float list
|
cosqa-train-14237
|
def string_to_float_list(string_var):
"""Pull comma separated string values out of a text file and converts them to float list"""
try:
return [float(s) for s in string_var.strip('[').strip(']').split(', ')]
except:
return [float(s) for s in string_var.strip('[').strip(']').split(',')]
|
def _get_local_ip ( ) : return set ( [ x [ 4 ] [ 0 ] for x in socket . getaddrinfo ( socket . gethostname ( ) , 80 , socket . AF_INET ) ] ) . pop ( )
| 1 |
ip adress of current machine in python
|
Get the local ip of this device
|
cosqa-train-14238
|
def _get_local_ip():
"""
Get the local ip of this device
:return: Ip of this computer
:rtype: str
"""
return set([x[4][0] for x in socket.getaddrinfo(
socket.gethostname(),
80,
socket.AF_INET
)]).pop()
|
def _interval_to_bound_points ( array ) : array_boundaries = np . array ( [ x . left for x in array ] ) array_boundaries = np . concatenate ( ( array_boundaries , np . array ( [ array [ - 1 ] . right ] ) ) ) return array_boundaries
| 1 |
python turn range to array
|
Helper function which returns an array with the Intervals boundaries .
|
cosqa-train-14239
|
def _interval_to_bound_points(array):
"""
Helper function which returns an array
with the Intervals' boundaries.
"""
array_boundaries = np.array([x.left for x in array])
array_boundaries = np.concatenate(
(array_boundaries, np.array([array[-1].right])))
return array_boundaries
|
def log ( self , level , msg = None , * args , * * kwargs ) : return self . _log ( level , msg , args , kwargs )
| 1 |
is python logging async
|
Writes log out at any arbitray level .
|
cosqa-train-14240
|
def log(self, level, msg=None, *args, **kwargs):
"""Writes log out at any arbitray level."""
return self._log(level, msg, args, kwargs)
|
def _from_bytes ( bytes , byteorder = "big" , signed = False ) : return int . from_bytes ( bytes , byteorder = byteorder , signed = signed )
| 1 |
python type cast to bigint
|
This is the same functionality as int . from_bytes in python 3
|
cosqa-train-14241
|
def _from_bytes(bytes, byteorder="big", signed=False):
"""This is the same functionality as ``int.from_bytes`` in python 3"""
return int.from_bytes(bytes, byteorder=byteorder, signed=signed)
|
def _unordered_iterator ( self ) : for i , qs in zip ( self . _queryset_idxs , self . _querysets ) : for item in qs : setattr ( item , '#' , i ) yield item
| 1 |
iterating through queryset python
|
Return the value of each QuerySet but also add the # property to each return item .
|
cosqa-train-14242
|
def _unordered_iterator(self):
"""
Return the value of each QuerySet, but also add the '#' property to each
return item.
"""
for i, qs in zip(self._queryset_idxs, self._querysets):
for item in qs:
setattr(item, '#', i)
yield item
|
def boolean ( value ) : if isinstance ( value , bool ) : return value if value == "" : return False return strtobool ( value )
| 1 |
python type true or false
|
Configuration - friendly boolean type converter .
|
cosqa-train-14243
|
def boolean(value):
"""
Configuration-friendly boolean type converter.
Supports both boolean-valued and string-valued inputs (e.g. from env vars).
"""
if isinstance(value, bool):
return value
if value == "":
return False
return strtobool(value)
|
def group_by ( iterable , key_func ) : groups = ( list ( sub ) for key , sub in groupby ( iterable , key_func ) ) return zip ( groups , groups )
| 1 |
itertools python grouby multiple keys
|
Wrap itertools . groupby to make life easier .
|
cosqa-train-14244
|
def group_by(iterable, key_func):
"""Wrap itertools.groupby to make life easier."""
groups = (
list(sub) for key, sub in groupby(iterable, key_func)
)
return zip(groups, groups)
|
def isfunc ( x ) : return any ( [ inspect . isfunction ( x ) and not asyncio . iscoroutinefunction ( x ) , inspect . ismethod ( x ) and not asyncio . iscoroutinefunction ( x ) ] )
| 1 |
python types check if coroutine'
|
Returns True if the given value is a function or method object .
|
cosqa-train-14245
|
def isfunc(x):
"""
Returns `True` if the given value is a function or method object.
Arguments:
x (mixed): value to check.
Returns:
bool
"""
return any([
inspect.isfunction(x) and not asyncio.iscoroutinefunction(x),
inspect.ismethod(x) and not asyncio.iscoroutinefunction(x)
])
|
def jaccard ( c_1 , c_2 ) : nom = np . intersect1d ( c_1 , c_2 ) . size denom = np . union1d ( c_1 , c_2 ) . size return nom / denom
| 0 |
jaccard similarity between two data sets python
|
Calculates the Jaccard similarity between two sets of nodes . Called by mroc .
|
cosqa-train-14246
|
def jaccard(c_1, c_2):
"""
Calculates the Jaccard similarity between two sets of nodes. Called by mroc.
Inputs: - c_1: Community (set of nodes) 1.
- c_2: Community (set of nodes) 2.
Outputs: - jaccard_similarity: The Jaccard similarity of these two communities.
"""
nom = np.intersect1d(c_1, c_2).size
denom = np.union1d(c_1, c_2).size
return nom/denom
|
def reload_localzone ( ) : global _cache_tz _cache_tz = pytz . timezone ( get_localzone_name ( ) ) utils . assert_tz_offset ( _cache_tz ) return _cache_tz
| 1 |
python tzlocal not defined
|
Reload the cached localzone . You need to call this if the timezone has changed .
|
cosqa-train-14247
|
def reload_localzone():
"""Reload the cached localzone. You need to call this if the timezone has changed."""
global _cache_tz
_cache_tz = pytz.timezone(get_localzone_name())
utils.assert_tz_offset(_cache_tz)
return _cache_tz
|
def levenshtein_distance_metric ( a , b ) : return ( levenshtein_distance ( a , b ) / ( 2.0 * max ( len ( a ) , len ( b ) , 1 ) ) )
| 1 |
jaro winkler distance in python
|
1 - farthest apart ( same number of words all diff ) . 0 - same
|
cosqa-train-14248
|
def levenshtein_distance_metric(a, b):
""" 1 - farthest apart (same number of words, all diff). 0 - same"""
return (levenshtein_distance(a, b) / (2.0 * max(len(a), len(b), 1)))
|
def __init__ ( self ) : self . state = self . STATE_INITIALIZING self . state_start = time . time ( )
| 1 |
python udating init variable
|
Initialize the state of the object
|
cosqa-train-14249
|
def __init__(self):
"""Initialize the state of the object"""
self.state = self.STATE_INITIALIZING
self.state_start = time.time()
|
def json_dumps ( self , obj ) : return json . dumps ( obj , sort_keys = True , indent = 4 , separators = ( ',' , ': ' ) )
| 1 |
json dump dictionary minus key python
|
Serializer for consistency
|
cosqa-train-14250
|
def json_dumps(self, obj):
"""Serializer for consistency"""
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
|
def uint32_to_uint8 ( cls , img ) : return np . flipud ( img . view ( dtype = np . uint8 ) . reshape ( img . shape + ( 4 , ) ) )
| 1 |
python uint8 to double image
|
Cast uint32 RGB image to 4 uint8 channels .
|
cosqa-train-14251
|
def uint32_to_uint8(cls, img):
"""
Cast uint32 RGB image to 4 uint8 channels.
"""
return np.flipud(img.view(dtype=np.uint8).reshape(img.shape + (4,)))
|
def json_template ( data , template_name , template_context ) : html = render_to_string ( template_name , template_context ) data = data or { } data [ 'html' ] = html return HttpResponse ( json_encode ( data ) , content_type = 'application/json' )
| 1 |
json dynamic template python
|
Old style use JSONTemplateResponse instead of this .
|
cosqa-train-14252
|
def json_template(data, template_name, template_context):
"""Old style, use JSONTemplateResponse instead of this.
"""
html = render_to_string(template_name, template_context)
data = data or {}
data['html'] = html
return HttpResponse(json_encode(data), content_type='application/json')
|
def endline_semicolon_check ( self , original , loc , tokens ) : return self . check_strict ( "semicolon at end of line" , original , loc , tokens )
| 1 |
python unexpectd character after line continuation character
|
Check for semicolons at the end of lines .
|
cosqa-train-14253
|
def endline_semicolon_check(self, original, loc, tokens):
"""Check for semicolons at the end of lines."""
return self.check_strict("semicolon at end of line", original, loc, tokens)
|
def timestamping_validate ( data , schema ) : jsonschema . validate ( data , schema ) data [ 'timestamp' ] = str ( time . time ( ) )
| 1 |
json supported timstamp in python
|
Custom validation function which inserts a timestamp for when the validation occurred
|
cosqa-train-14254
|
def timestamping_validate(data, schema):
"""
Custom validation function which inserts a timestamp for when the
validation occurred
"""
jsonschema.validate(data, schema)
data['timestamp'] = str(time.time())
|
def get_uniques ( l ) : result = [ ] for i in l : if i not in result : result . append ( i ) return result
| 1 |
python unique lists of boolean values
|
Returns a list with no repeated elements .
|
cosqa-train-14255
|
def get_uniques(l):
""" Returns a list with no repeated elements.
"""
result = []
for i in l:
if i not in result:
result.append(i)
return result
|
def _spawn_kafka_consumer_thread ( self ) : self . logger . debug ( "Spawn kafka consumer thread" "" ) self . _consumer_thread = Thread ( target = self . _consumer_loop ) self . _consumer_thread . setDaemon ( True ) self . _consumer_thread . start ( )
| 1 |
kafka consumer python loop
|
Spawns a kafka continuous consumer thread
|
cosqa-train-14256
|
def _spawn_kafka_consumer_thread(self):
"""Spawns a kafka continuous consumer thread"""
self.logger.debug("Spawn kafka consumer thread""")
self._consumer_thread = Thread(target=self._consumer_loop)
self._consumer_thread.setDaemon(True)
self._consumer_thread.start()
|
def assert_error ( text , check , n = 1 ) : assert_error . description = "No {} error for '{}'" . format ( check , text ) assert ( check in [ error [ 0 ] for error in lint ( text ) ] )
| 0 |
python unittest assert msg
|
Assert that text has n errors of type check .
|
cosqa-train-14257
|
def assert_error(text, check, n=1):
"""Assert that text has n errors of type check."""
assert_error.description = "No {} error for '{}'".format(check, text)
assert(check in [error[0] for error in lint(text)])
|
def send ( self , topic , * args , * * kwargs ) : prefix_topic = self . heroku_kafka . prefix_topic ( topic ) return super ( HerokuKafkaProducer , self ) . send ( prefix_topic , * args , * * kwargs )
| 1 |
kafka python producer specify parittion
|
Appends the prefix to the topic before sendingf
|
cosqa-train-14258
|
def send(self, topic, *args, **kwargs):
"""
Appends the prefix to the topic before sendingf
"""
prefix_topic = self.heroku_kafka.prefix_topic(topic)
return super(HerokuKafkaProducer, self).send(prefix_topic, *args, **kwargs)
|
def assert_error ( text , check , n = 1 ) : assert_error . description = "No {} error for '{}'" . format ( check , text ) assert ( check in [ error [ 0 ] for error in lint ( text ) ] )
| 1 |
python unittest assert with message
|
Assert that text has n errors of type check .
|
cosqa-train-14259
|
def assert_error(text, check, n=1):
"""Assert that text has n errors of type check."""
assert_error.description = "No {} error for '{}'".format(check, text)
assert(check in [error[0] for error in lint(text)])
|
def remove_rows_matching ( df , column , match ) : df = df . copy ( ) mask = df [ column ] . values != match return df . iloc [ mask , : ]
| 1 |
keep only rows in a column matching a value in python
|
Return a DataFrame with rows where column values match match are removed .
|
cosqa-train-14260
|
def remove_rows_matching(df, column, match):
"""
Return a ``DataFrame`` with rows where `column` values match `match` are removed.
The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared
to `match`, and those rows that match are removed from the DataFrame.
:param df: Pandas ``DataFrame``
:param column: Column indexer
:param match: ``str`` match target
:return: Pandas ``DataFrame`` filtered
"""
df = df.copy()
mask = df[column].values != match
return df.iloc[mask, :]
|
def _assert_is_type ( name , value , value_type ) : if not isinstance ( value , value_type ) : if type ( value_type ) is tuple : types = ', ' . join ( t . __name__ for t in value_type ) raise ValueError ( '{0} must be one of ({1})' . format ( name , types ) ) else : raise ValueError ( '{0} must be {1}' . format ( name , value_type . __name__ ) )
| 1 |
python unittests assert type
|
Assert that a value must be a given type .
|
cosqa-train-14261
|
def _assert_is_type(name, value, value_type):
"""Assert that a value must be a given type."""
if not isinstance(value, value_type):
if type(value_type) is tuple:
types = ', '.join(t.__name__ for t in value_type)
raise ValueError('{0} must be one of ({1})'.format(name, types))
else:
raise ValueError('{0} must be {1}'
.format(name, value_type.__name__))
|
def make_symmetric ( dict ) : for key , value in list ( dict . items ( ) ) : dict [ value ] = key return dict
| 1 |
python unmashable dict fix all columns
|
Makes the given dictionary symmetric . Values are assumed to be unique .
|
cosqa-train-14262
|
def make_symmetric(dict):
"""Makes the given dictionary symmetric. Values are assumed to be unique."""
for key, value in list(dict.items()):
dict[value] = key
return dict
|
def kubectl ( * args , input = None , * * flags ) : # Build command line call. line = [ 'kubectl' ] + list ( args ) line = line + get_flag_args ( * * flags ) if input is not None : line = line + [ '-f' , '-' ] # Run subprocess output = subprocess . run ( line , input = input , capture_output = True , text = True ) return output
| 1 |
kubectl api for python
|
Simple wrapper to kubectl .
|
cosqa-train-14263
|
def kubectl(*args, input=None, **flags):
"""Simple wrapper to kubectl."""
# Build command line call.
line = ['kubectl'] + list(args)
line = line + get_flag_args(**flags)
if input is not None:
line = line + ['-f', '-']
# Run subprocess
output = subprocess.run(
line,
input=input,
capture_output=True,
text=True
)
return output
|
def _get_context ( argspec , kwargs ) : if argspec . keywords is not None : return kwargs return dict ( ( arg , kwargs [ arg ] ) for arg in argspec . args if arg in kwargs )
| 1 |
python unpack kwargs into dict
|
Prepare a context for the serialization .
|
cosqa-train-14264
|
def _get_context(argspec, kwargs):
"""Prepare a context for the serialization.
:param argspec: The argspec of the serialization function.
:param kwargs: Dict with context
:return: Keywords arguments that function can accept.
"""
if argspec.keywords is not None:
return kwargs
return dict((arg, kwargs[arg]) for arg in argspec.args if arg in kwargs)
|
def straight_line_show ( title , length = 100 , linestyle = "=" , pad = 0 ) : print ( StrTemplate . straight_line ( title = title , length = length , linestyle = linestyle , pad = pad ) )
| 1 |
latex auto line wrap python display
|
Print a formatted straight line .
|
cosqa-train-14265
|
def straight_line_show(title, length=100, linestyle="=", pad=0):
"""Print a formatted straight line.
"""
print(StrTemplate.straight_line(
title=title, length=length, linestyle=linestyle, pad=pad))
|
def roundClosestValid ( val , res , decimals = None ) : if decimals is None and "." in str ( res ) : decimals = len ( str ( res ) . split ( '.' ) [ 1 ] ) return round ( round ( val / res ) * res , decimals )
| 1 |
limit float decimals in python
|
round to closest resolution
|
cosqa-train-14266
|
def roundClosestValid(val, res, decimals=None):
""" round to closest resolution """
if decimals is None and "." in str(res):
decimals = len(str(res).split('.')[1])
return round(round(val / res) * res, decimals)
|
def extract_all ( zipfile , dest_folder ) : z = ZipFile ( zipfile ) print ( z ) z . extract ( dest_folder )
| 1 |
python unzip all zip files recursively
|
reads the zip file determines compression and unzips recursively until source files are extracted
|
cosqa-train-14267
|
def extract_all(zipfile, dest_folder):
"""
reads the zip file, determines compression
and unzips recursively until source files
are extracted
"""
z = ZipFile(zipfile)
print(z)
z.extract(dest_folder)
|
def retry_until_not_none_or_limit_reached ( method , limit , sleep_s = 1 , catch_exceptions = ( ) ) : return retry_until_valid_or_limit_reached ( method , limit , lambda x : x is not None , sleep_s , catch_exceptions )
| 1 |
limit invalid attempts in python 3
|
Executes a method until the retry limit is hit or not None is returned .
|
cosqa-train-14268
|
def retry_until_not_none_or_limit_reached(method, limit, sleep_s=1,
catch_exceptions=()):
"""Executes a method until the retry limit is hit or not None is returned."""
return retry_until_valid_or_limit_reached(
method, limit, lambda x: x is not None, sleep_s, catch_exceptions)
|
def recursively_update ( d , d2 ) : for k , v in d2 . items ( ) : if k in d : if isinstance ( v , dict ) : recursively_update ( d [ k ] , v ) continue d [ k ] = v
| 1 |
python update dictionary recursively
|
dict . update but which merges child dicts ( dict2 takes precedence where there s conflict ) .
|
cosqa-train-14269
|
def recursively_update(d, d2):
"""dict.update but which merges child dicts (dict2 takes precedence where there's conflict)."""
for k, v in d2.items():
if k in d:
if isinstance(v, dict):
recursively_update(d[k], v)
continue
d[k] = v
|
def _linear_interpolation ( x , X , Y ) : return ( Y [ 1 ] * ( x - X [ 0 ] ) + Y [ 0 ] * ( X [ 1 ] - x ) ) / ( X [ 1 ] - X [ 0 ] )
| 1 |
linearly interpolate between two points in 3d python
|
Given two data points [ X Y ] linearly interpolate those at x .
|
cosqa-train-14270
|
def _linear_interpolation(x, X, Y):
"""Given two data points [X,Y], linearly interpolate those at x.
"""
return (Y[1] * (x - X[0]) + Y[0] * (X[1] - x)) / (X[1] - X[0])
|
def increment ( self , amount = 1 ) : self . _primaryProgressBar . setValue ( self . value ( ) + amount ) QApplication . instance ( ) . processEvents ( )
| 1 |
python update qprogressbar value
|
Increments the main progress bar by amount .
|
cosqa-train-14271
|
def increment(self, amount=1):
"""
Increments the main progress bar by amount.
"""
self._primaryProgressBar.setValue(self.value() + amount)
QApplication.instance().processEvents()
|
def safe_url ( url ) : parsed = urlparse ( url ) if parsed . password is not None : pwd = ':%s@' % parsed . password url = url . replace ( pwd , ':*****@' ) return url
| 1 |
python urllib is there a way to bypass the username and password page
|
Remove password from printed connection URLs .
|
cosqa-train-14272
|
def safe_url(url):
"""Remove password from printed connection URLs."""
parsed = urlparse(url)
if parsed.password is not None:
pwd = ':%s@' % parsed.password
url = url.replace(pwd, ':*****@')
return url
|
def put_pidfile ( pidfile_path , pid ) : with open ( pidfile_path , "w" ) as f : f . write ( "%s" % pid ) os . fsync ( f . fileno ( ) ) return
| 1 |
linux copy pid of python script to a file at time of init
|
Put a PID into a pidfile
|
cosqa-train-14273
|
def put_pidfile( pidfile_path, pid ):
"""
Put a PID into a pidfile
"""
with open( pidfile_path, "w" ) as f:
f.write("%s" % pid)
os.fsync(f.fileno())
return
|
def get ( url ) : response = urllib . request . urlopen ( url ) data = response . read ( ) data = data . decode ( "utf-8" ) data = json . loads ( data ) return data
| 1 |
python urllib2 receive json
|
Recieving the JSON file from uulm
|
cosqa-train-14274
|
def get(url):
"""Recieving the JSON file from uulm"""
response = urllib.request.urlopen(url)
data = response.read()
data = data.decode("utf-8")
data = json.loads(data)
return data
|
def get_services ( ) : with win32 . OpenSCManager ( dwDesiredAccess = win32 . SC_MANAGER_ENUMERATE_SERVICE ) as hSCManager : try : return win32 . EnumServicesStatusEx ( hSCManager ) except AttributeError : return win32 . EnumServicesStatus ( hSCManager )
| 1 |
list all services of windows in python
|
Retrieve a list of all system services .
|
cosqa-train-14275
|
def get_services():
"""
Retrieve a list of all system services.
@see: L{get_active_services},
L{start_service}, L{stop_service},
L{pause_service}, L{resume_service}
@rtype: list( L{win32.ServiceStatusProcessEntry} )
@return: List of service status descriptors.
"""
with win32.OpenSCManager(
dwDesiredAccess = win32.SC_MANAGER_ENUMERATE_SERVICE
) as hSCManager:
try:
return win32.EnumServicesStatusEx(hSCManager)
except AttributeError:
return win32.EnumServicesStatus(hSCManager)
|
def addClassKey ( self , klass , key , obj ) : d = self . _getClass ( klass ) d [ key ] = obj
| 1 |
python use key as object
|
Adds an object to the collection based on klass and key .
|
cosqa-train-14276
|
def addClassKey(self, klass, key, obj):
"""
Adds an object to the collection, based on klass and key.
@param klass: The class of the object.
@param key: The datastore key of the object.
@param obj: The loaded instance from the datastore.
"""
d = self._getClass(klass)
d[key] = obj
|
def has_multiline_items ( maybe_list : Optional [ Sequence [ str ] ] ) : return maybe_list and any ( is_multiline ( item ) for item in maybe_list )
| 1 |
list comprehension if else python multi line
|
Check whether one of the items in the list has multiple lines .
|
cosqa-train-14277
|
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 _split ( value ) : if isinstance ( value , str ) : # iterable, but not meant for splitting return value , value try : invalue , outvalue = value except TypeError : invalue = outvalue = value except ValueError : raise ValueError ( "Only single values and pairs are allowed" ) return invalue , outvalue
| 1 |
python use split not enough values to unpack
|
Split input / output value into two values .
|
cosqa-train-14278
|
def _split(value):
"""Split input/output value into two values."""
if isinstance(value, str):
# iterable, but not meant for splitting
return value, value
try:
invalue, outvalue = value
except TypeError:
invalue = outvalue = value
except ValueError:
raise ValueError("Only single values and pairs are allowed")
return invalue, outvalue
|
def from_file ( filename ) : f = open ( filename , 'r' ) j = json . load ( f ) f . close ( ) return from_dict ( j )
| 1 |
load a json file onto variable python
|
load an nparray object from a json filename
|
cosqa-train-14279
|
def from_file(filename):
"""
load an nparray object from a json filename
@parameter str filename: path to the file
"""
f = open(filename, 'r')
j = json.load(f)
f.close()
return from_dict(j)
|
def __add__ ( self , other ) : return self . _handle_type ( other ) ( self . value + other . value )
| 0 |
python using element in addition
|
Handle the + operator .
|
cosqa-train-14280
|
def __add__(self, other):
"""Handle the `+` operator."""
return self._handle_type(other)(self.value + other.value)
|
def Load ( file ) : with open ( file , 'rb' ) as file : model = dill . load ( file ) return model
| 1 |
loading text file into python using load function
|
Loads a model from specified file
|
cosqa-train-14281
|
def Load(file):
""" Loads a model from specified file """
with open(file, 'rb') as file:
model = dill.load(file)
return model
|
def get_soup ( page = '' ) : content = requests . get ( '%s/%s' % ( BASE_URL , page ) ) . text return BeautifulSoup ( content )
| 1 |
python using requests to get html from page
|
Returns a bs4 object of the page requested
|
cosqa-train-14282
|
def get_soup(page=''):
"""
Returns a bs4 object of the page requested
"""
content = requests.get('%s/%s' % (BASE_URL, page)).text
return BeautifulSoup(content)
|
def log_all ( self , file ) : global rflink_log if file == None : rflink_log = None else : log . debug ( 'logging to: %s' , file ) rflink_log = open ( file , 'a' )
| 1 |
log file not saving python logging
|
Log all data received from RFLink to file .
|
cosqa-train-14283
|
def log_all(self, file):
"""Log all data received from RFLink to file."""
global rflink_log
if file == None:
rflink_log = None
else:
log.debug('logging to: %s', file)
rflink_log = open(file, 'a')
|
def generate_uuid ( ) : r_uuid = base64 . urlsafe_b64encode ( uuid . uuid4 ( ) . bytes ) return r_uuid . decode ( ) . replace ( '=' , '' )
| 1 |
python uuid 50 string
|
Generate a UUID .
|
cosqa-train-14284
|
def generate_uuid():
"""Generate a UUID."""
r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)
return r_uuid.decode().replace('=', '')
|
def keys_to_snake_case ( camel_case_dict ) : return dict ( ( to_snake_case ( key ) , value ) for ( key , value ) in camel_case_dict . items ( ) )
| 1 |
lower case for dictionary in python
|
Make a copy of a dictionary with all keys converted to snake case . This is just calls to_snake_case on each of the keys in the dictionary and returns a new dictionary .
|
cosqa-train-14285
|
def keys_to_snake_case(camel_case_dict):
"""
Make a copy of a dictionary with all keys converted to snake case. This is just calls to_snake_case on
each of the keys in the dictionary and returns a new dictionary.
:param camel_case_dict: Dictionary with the keys to convert.
:type camel_case_dict: Dictionary.
:return: Dictionary with the keys converted to snake case.
"""
return dict((to_snake_case(key), value) for (key, value) in camel_case_dict.items())
|
def generate_uuid ( ) : r_uuid = base64 . urlsafe_b64encode ( uuid . uuid4 ( ) . bytes ) return r_uuid . decode ( ) . replace ( '=' , '' )
| 0 |
python uuid without cash
|
Generate a UUID .
|
cosqa-train-14286
|
def generate_uuid():
"""Generate a UUID."""
r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)
return r_uuid.decode().replace('=', '')
|
def c2u ( name ) : s1 = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , name ) s1 = re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , s1 ) . lower ( ) return s1
| 1 |
lowercase a variable in python
|
Convert camelCase ( used in PHP ) to Python - standard snake_case .
|
cosqa-train-14287
|
def c2u(name):
"""Convert camelCase (used in PHP) to Python-standard snake_case.
Src:
https://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case
Parameters
----------
name: A function or variable name in camelCase
Returns
-------
str: The name in snake_case
"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
s1 = re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
return s1
|
def is_valid_email ( email ) : pattern = re . compile ( r'[\w\.-]+@[\w\.-]+[.]\w+' ) return bool ( pattern . match ( email ) )
| 1 |
python validate email regular expression
|
Check if email is valid
|
cosqa-train-14288
|
def is_valid_email(email):
"""
Check if email is valid
"""
pattern = re.compile(r'[\w\.-]+@[\w\.-]+[.]\w+')
return bool(pattern.match(email))
|
def _interval_to_bound_points ( array ) : array_boundaries = np . array ( [ x . left for x in array ] ) array_boundaries = np . concatenate ( ( array_boundaries , np . array ( [ array [ - 1 ] . right ] ) ) ) return array_boundaries
| 1 |
make a range into an array python
|
Helper function which returns an array with the Intervals boundaries .
|
cosqa-train-14289
|
def _interval_to_bound_points(array):
"""
Helper function which returns an array
with the Intervals' boundaries.
"""
array_boundaries = np.array([x.left for x in array])
array_boundaries = np.concatenate(
(array_boundaries, np.array([array[-1].right])))
return array_boundaries
|
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 |
python validate proper email address
|
Validates an email address Source : Himanshu Shankar ( https : // github . com / iamhssingh ) Parameters ---------- email : str
|
cosqa-train-14290
|
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 force_iterable ( f ) : def wrapper ( * args , * * kwargs ) : r = f ( * args , * * kwargs ) if hasattr ( r , '__iter__' ) : return r else : return [ r ] return wrapper
| 1 |
make an iterable python
|
Will make any functions return an iterable objects by wrapping its result in a list .
|
cosqa-train-14291
|
def force_iterable(f):
"""Will make any functions return an iterable objects by wrapping its result in a list."""
def wrapper(*args, **kwargs):
r = f(*args, **kwargs)
if hasattr(r, '__iter__'):
return r
else:
return [r]
return wrapper
|
def parse ( self , s ) : return datetime . datetime . strptime ( s , self . date_format ) . date ( )
| 1 |
python validate string as date
|
Parses a date string formatted like YYYY - MM - DD .
|
cosqa-train-14292
|
def parse(self, s):
"""
Parses a date string formatted like ``YYYY-MM-DD``.
"""
return datetime.datetime.strptime(s, self.date_format).date()
|
def url_syntax_check ( url ) : # pragma: no cover if url and isinstance ( url , str ) : # The given URL is not empty nor None. # and # * The given URL is a string. # We silently load the configuration. load_config ( True ) return Check ( url ) . is_url_valid ( ) # We return None, there is nothing to check. return None
| 1 |
python validate url invalid characters
|
Check the syntax of the given URL .
|
cosqa-train-14293
|
def url_syntax_check(url): # pragma: no cover
"""
Check the syntax of the given URL.
:param url: The URL to check the syntax for.
:type url: str
:return: The syntax validity.
:rtype: bool
.. warning::
If an empty or a non-string :code:`url` is given, we return :code:`None`.
"""
if url and isinstance(url, str):
# The given URL is not empty nor None.
# and
# * The given URL is a string.
# We silently load the configuration.
load_config(True)
return Check(url).is_url_valid()
# We return None, there is nothing to check.
return None
|
def __init__ ( self , response ) : self . response = response super ( ResponseException , self ) . __init__ ( "received {} HTTP response" . format ( response . status_code ) )
| 1 |
make response python constructor
|
Initialize a ResponseException instance .
|
cosqa-train-14294
|
def __init__(self, response):
"""Initialize a ResponseException instance.
:param response: A requests.response instance.
"""
self.response = response
super(ResponseException, self).__init__(
"received {} HTTP response".format(response.status_code)
)
|
def venv ( ) : try : import virtualenv # NOQA except ImportError : sh ( "%s -m pip install virtualenv" % PYTHON ) if not os . path . isdir ( "venv" ) : sh ( "%s -m virtualenv venv" % PYTHON ) sh ( "venv\\Scripts\\pip install -r %s" % ( REQUIREMENTS_TXT ) )
| 0 |
python venv not found
|
Install venv + deps .
|
cosqa-train-14295
|
def venv():
"""Install venv + deps."""
try:
import virtualenv # NOQA
except ImportError:
sh("%s -m pip install virtualenv" % PYTHON)
if not os.path.isdir("venv"):
sh("%s -m virtualenv venv" % PYTHON)
sh("venv\\Scripts\\pip install -r %s" % (REQUIREMENTS_TXT))
|
def stringify_dict_contents ( dct ) : return { str_if_nested_or_str ( k ) : str_if_nested_or_str ( v ) for k , v in dct . items ( ) }
| 1 |
make the key of a dict a string python
|
Turn dict keys and values into native strings .
|
cosqa-train-14296
|
def stringify_dict_contents(dct):
"""Turn dict keys and values into native strings."""
return {
str_if_nested_or_str(k): str_if_nested_or_str(v)
for k, v in dct.items()
}
|
def check_alert ( self , text ) : try : alert = Alert ( world . browser ) if alert . text != text : raise AssertionError ( "Alert text expected to be {!r}, got {!r}." . format ( text , alert . text ) ) except WebDriverException : # PhantomJS is kinda poor pass
| 1 |
python verify text field in alert window
|
Assert an alert is showing with the given text .
|
cosqa-train-14297
|
def check_alert(self, text):
"""
Assert an alert is showing with the given text.
"""
try:
alert = Alert(world.browser)
if alert.text != text:
raise AssertionError(
"Alert text expected to be {!r}, got {!r}.".format(
text, alert.text))
except WebDriverException:
# PhantomJS is kinda poor
pass
|
def pdf ( x , mu , std ) : return ( 1.0 / ( std * sqrt ( 2 * pi ) ) ) * np . exp ( - ( x - mu ) ** 2 / ( 2 * std ** 2 ) )
| 1 |
making a probability distribution in python
|
Probability density function ( normal distribution )
|
cosqa-train-14298
|
def pdf(x, mu, std):
"""Probability density function (normal distribution)"""
return (1.0 / (std * sqrt(2 * pi))) * np.exp(-(x - mu) ** 2 / (2 * std ** 2))
|
def adapter ( data , headers , * * kwargs ) : keys = ( 'sep_title' , 'sep_character' , 'sep_length' ) return vertical_table ( data , headers , * * filter_dict_by_key ( kwargs , keys ) )
| 1 |
python view table with headers
|
Wrap vertical table in a function for TabularOutputFormatter .
|
cosqa-train-14299
|
def adapter(data, headers, **kwargs):
"""Wrap vertical table in a function for TabularOutputFormatter."""
keys = ('sep_title', 'sep_character', 'sep_length')
return vertical_table(data, headers, **filter_dict_by_key(kwargs, keys))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.