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 copy_image_on_background ( image , color = WHITE ) : background = Image . new ( "RGB" , image . size , color ) background . paste ( image , mask = image . split ( ) [ 3 ] ) return background
| 0 |
how to change the background to an image in python
|
Create a new image by copying the image on a * color * background .
|
cosqa-train-15700
|
def copy_image_on_background(image, color=WHITE):
"""
Create a new image by copying the image on a *color* background.
Args:
image (PIL.Image.Image): Image to copy
color (tuple): Background color usually WHITE or BLACK
Returns:
PIL.Image.Image
"""
background = Image.new("RGB", image.size, color)
background.paste(image, mask=image.split()[3])
return background
|
def make_symmetric ( dict ) : for key , value in list ( dict . items ( ) ) : dict [ value ] = key return dict
| 0 |
python make dict hashable
|
Makes the given dictionary symmetric . Values are assumed to be unique .
|
cosqa-train-15701
|
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 std_datestr ( self , datestr ) : return date . strftime ( self . str2date ( datestr ) , self . std_dateformat )
| 0 |
how to change to string to date format python
|
Reformat a date string to standard format .
|
cosqa-train-15702
|
def std_datestr(self, datestr):
"""Reformat a date string to standard format.
"""
return date.strftime(
self.str2date(datestr), self.std_dateformat)
|
def list_of_lists_to_dict ( l ) : d = { } for key , val in l : d . setdefault ( key , [ ] ) . append ( val ) return d
| 0 |
python make list into dictionary
|
Convert list of key value lists to dict
|
cosqa-train-15703
|
def list_of_lists_to_dict(l):
""" Convert list of key,value lists to dict
[['id', 1], ['id', 2], ['id', 3], ['foo': 4]]
{'id': [1, 2, 3], 'foo': [4]}
"""
d = {}
for key, val in l:
d.setdefault(key, []).append(val)
return d
|
def file_found ( filename , force ) : if os . path . exists ( filename ) and not force : logger . info ( "Found %s; skipping..." % filename ) return True else : return False
| 0 |
how to chck if exists python
|
Check if a file exists
|
cosqa-train-15704
|
def file_found(filename,force):
"""Check if a file exists"""
if os.path.exists(filename) and not force:
logger.info("Found %s; skipping..."%filename)
return True
else:
return False
|
def filter_none ( list_of_points ) : remove_elementnone = filter ( lambda p : p is not None , list_of_points ) remove_sublistnone = filter ( lambda p : not contains_none ( p ) , remove_elementnone ) return list ( remove_sublistnone )
| 0 |
python make list without element without removing
|
: param list_of_points : : return : list_of_points with None s removed
|
cosqa-train-15705
|
def filter_none(list_of_points):
"""
:param list_of_points:
:return: list_of_points with None's removed
"""
remove_elementnone = filter(lambda p: p is not None, list_of_points)
remove_sublistnone = filter(lambda p: not contains_none(p), remove_elementnone)
return list(remove_sublistnone)
|
def get_naive ( dt ) : if not dt . tzinfo : return dt if hasattr ( dt , "asdatetime" ) : return dt . asdatetime ( ) return dt . replace ( tzinfo = None )
| 1 |
python make naive datetime aware
|
Gets a naive datetime from a datetime .
|
cosqa-train-15706
|
def get_naive(dt):
"""Gets a naive datetime from a datetime.
datetime_tz objects can't just have tzinfo replaced with None, you need to
call asdatetime.
Args:
dt: datetime object.
Returns:
datetime object without any timezone information.
"""
if not dt.tzinfo:
return dt
if hasattr(dt, "asdatetime"):
return dt.asdatetime()
return dt.replace(tzinfo=None)
|
def unicode_is_ascii ( u_string ) : assert isinstance ( u_string , str ) try : u_string . encode ( 'ascii' ) return True except UnicodeEncodeError : return False
| 1 |
how to check character ascii in python
|
Determine if unicode string only contains ASCII characters .
|
cosqa-train-15707
|
def unicode_is_ascii(u_string):
"""Determine if unicode string only contains ASCII characters.
:param str u_string: unicode string to check. Must be unicode
and not Python 2 `str`.
:rtype: bool
"""
assert isinstance(u_string, str)
try:
u_string.encode('ascii')
return True
except UnicodeEncodeError:
return False
|
def makedirs ( path ) : if not os . path . isdir ( path ) : os . makedirs ( path ) return path
| 1 |
python makedir if necessary
|
Create directories if they do not exist otherwise do nothing .
|
cosqa-train-15708
|
def makedirs(path):
"""
Create directories if they do not exist, otherwise do nothing.
Return path for convenience
"""
if not os.path.isdir(path):
os.makedirs(path)
return path
|
def _validate_pos ( df ) : assert isinstance ( df , pd . DataFrame ) assert [ "seqname" , "position" , "strand" ] == df . columns . tolist ( ) assert df . position . dtype == np . dtype ( "int64" ) assert df . strand . dtype == np . dtype ( "O" ) assert df . seqname . dtype == np . dtype ( "O" ) return df
| 0 |
how to check column type in dataset using python
|
Validates the returned positional object
|
cosqa-train-15709
|
def _validate_pos(df):
"""Validates the returned positional object
"""
assert isinstance(df, pd.DataFrame)
assert ["seqname", "position", "strand"] == df.columns.tolist()
assert df.position.dtype == np.dtype("int64")
assert df.strand.dtype == np.dtype("O")
assert df.seqname.dtype == np.dtype("O")
return df
|
def transpose ( table ) : t = [ ] for i in range ( 0 , len ( table [ 0 ] ) ) : t . append ( [ row [ i ] for row in table ] ) return t
| 0 |
python map a 2d list to table
|
transpose matrix
|
cosqa-train-15710
|
def transpose(table):
"""
transpose matrix
"""
t = []
for i in range(0, len(table[0])):
t.append([row[i] for row in table])
return t
|
def _validate_pos ( df ) : assert isinstance ( df , pd . DataFrame ) assert [ "seqname" , "position" , "strand" ] == df . columns . tolist ( ) assert df . position . dtype == np . dtype ( "int64" ) assert df . strand . dtype == np . dtype ( "O" ) assert df . seqname . dtype == np . dtype ( "O" ) return df
| 1 |
how to check datatype in data frame in python
|
Validates the returned positional object
|
cosqa-train-15711
|
def _validate_pos(df):
"""Validates the returned positional object
"""
assert isinstance(df, pd.DataFrame)
assert ["seqname", "position", "strand"] == df.columns.tolist()
assert df.position.dtype == np.dtype("int64")
assert df.strand.dtype == np.dtype("O")
assert df.seqname.dtype == np.dtype("O")
return df
|
def set_as_object ( self , value ) : self . clear ( ) map = MapConverter . to_map ( value ) self . append ( map )
| 0 |
python map append new item
|
Sets a new value to map element
|
cosqa-train-15712
|
def set_as_object(self, value):
"""
Sets a new value to map element
:param value: a new element or map value.
"""
self.clear()
map = MapConverter.to_map(value)
self.append(map)
|
def _check_color_dim ( val ) : val = np . atleast_2d ( val ) if val . shape [ 1 ] not in ( 3 , 4 ) : raise RuntimeError ( 'Value must have second dimension of size 3 or 4' ) return val , val . shape [ 1 ]
| 0 |
how to check dimensions python
|
Ensure val is Nx ( n_col ) usually Nx3
|
cosqa-train-15713
|
def _check_color_dim(val):
"""Ensure val is Nx(n_col), usually Nx3"""
val = np.atleast_2d(val)
if val.shape[1] not in (3, 4):
raise RuntimeError('Value must have second dimension of size 3 or 4')
return val, val.shape[1]
|
def match_paren ( self , tokens , item ) : match , = tokens return self . match ( match , item )
| 0 |
python match parentheses regex
|
Matches a paren .
|
cosqa-train-15714
|
def match_paren(self, tokens, item):
"""Matches a paren."""
match, = tokens
return self.match(match, item)
|
def equal ( obj1 , obj2 ) : Comparable . log ( obj1 , obj2 , '==' ) equality = obj1 . equality ( obj2 ) Comparable . log ( obj1 , obj2 , '==' , result = equality ) return equality
| 1 |
how to check equality python
|
Calculate equality between two ( Comparable ) objects .
|
cosqa-train-15715
|
def equal(obj1, obj2):
"""Calculate equality between two (Comparable) objects."""
Comparable.log(obj1, obj2, '==')
equality = obj1.equality(obj2)
Comparable.log(obj1, obj2, '==', result=equality)
return equality
|
def file_matches ( filename , patterns ) : return any ( fnmatch . fnmatch ( filename , pat ) for pat in patterns )
| 0 |
python match wildcard filenames
|
Does this filename match any of the patterns?
|
cosqa-train-15716
|
def file_matches(filename, patterns):
"""Does this filename match any of the patterns?"""
return any(fnmatch.fnmatch(filename, pat) for pat in patterns)
|
def is_valid_image_extension ( file_path ) : valid_extensions = [ '.jpeg' , '.jpg' , '.gif' , '.png' ] _ , extension = os . path . splitext ( file_path ) return extension . lower ( ) in valid_extensions
| 0 |
how to check file extension in python
|
is_valid_image_extension .
|
cosqa-train-15717
|
def is_valid_image_extension(file_path):
"""is_valid_image_extension."""
valid_extensions = ['.jpeg', '.jpg', '.gif', '.png']
_, extension = os.path.splitext(file_path)
return extension.lower() in valid_extensions
|
def set_title ( self , title , * * kwargs ) : ax = self . get_axes ( ) ax . set_title ( title , * * kwargs )
| 0 |
python matlibplot set axis title
|
Sets the title on the underlying matplotlib AxesSubplot .
|
cosqa-train-15718
|
def set_title(self, title, **kwargs):
"""Sets the title on the underlying matplotlib AxesSubplot."""
ax = self.get_axes()
ax.set_title(title, **kwargs)
|
def is_builtin_css_function ( name ) : name = name . replace ( '_' , '-' ) if name in BUILTIN_FUNCTIONS : return True # Vendor-specific functions (-foo-bar) are always okay if name [ 0 ] == '-' and '-' in name [ 1 : ] : return True return False
| 1 |
how to check for inbuilt string functions + python
|
Returns whether the given name looks like the name of a builtin CSS function .
|
cosqa-train-15719
|
def is_builtin_css_function(name):
"""Returns whether the given `name` looks like the name of a builtin CSS
function.
Unrecognized functions not in this list produce warnings.
"""
name = name.replace('_', '-')
if name in BUILTIN_FUNCTIONS:
return True
# Vendor-specific functions (-foo-bar) are always okay
if name[0] == '-' and '-' in name[1:]:
return True
return False
|
def _linear_seaborn_ ( self , label = None , style = None , opts = None ) : xticks , yticks = self . _get_ticks ( opts ) try : fig = sns . lmplot ( self . x , self . y , data = self . df ) fig = self . _set_with_height ( fig , opts ) return fig except Exception as e : self . err ( e , self . linear_ , "Can not draw linear regression chart" )
| 1 |
python matplotlib add regression line
|
Returns a Seaborn linear regression plot
|
cosqa-train-15720
|
def _linear_seaborn_(self, label=None, style=None, opts=None):
"""
Returns a Seaborn linear regression plot
"""
xticks, yticks = self._get_ticks(opts)
try:
fig = sns.lmplot(self.x, self.y, data=self.df)
fig = self._set_with_height(fig, opts)
return fig
except Exception as e:
self.err(e, self.linear_,
"Can not draw linear regression chart")
|
def clear_matplotlib_ticks ( self , axis = "both" ) : ax = self . get_axes ( ) plotting . clear_matplotlib_ticks ( ax = ax , axis = axis )
| 1 |
python matplotlib clear axes
|
Clears the default matplotlib ticks .
|
cosqa-train-15721
|
def clear_matplotlib_ticks(self, axis="both"):
"""Clears the default matplotlib ticks."""
ax = self.get_axes()
plotting.clear_matplotlib_ticks(ax=ax, axis=axis)
|
def is_iter_non_string ( obj ) : if isinstance ( obj , list ) or isinstance ( obj , tuple ) : return True return False
| 0 |
how to check if a a variable is iterable in python
|
test if object is a list or tuple
|
cosqa-train-15722
|
def is_iter_non_string(obj):
"""test if object is a list or tuple"""
if isinstance(obj, list) or isinstance(obj, tuple):
return True
return False
|
def strip_figures ( figure ) : fig = [ ] for trace in figure [ 'data' ] : fig . append ( dict ( data = [ trace ] , layout = figure [ 'layout' ] ) ) return fig
| 0 |
python matplotlib combining list of figures into a single figure
|
Strips a figure into multiple figures with a trace on each of them
|
cosqa-train-15723
|
def strip_figures(figure):
"""
Strips a figure into multiple figures with a trace on each of them
Parameters:
-----------
figure : Figure
Plotly Figure
"""
fig=[]
for trace in figure['data']:
fig.append(dict(data=[trace],layout=figure['layout']))
return fig
|
def set_value ( self , value ) : if value : self . setChecked ( Qt . Checked ) else : self . setChecked ( Qt . Unchecked )
| 1 |
how to check if a checkbox is checked python
|
Set value of the checkbox .
|
cosqa-train-15724
|
def set_value(self, value):
"""Set value of the checkbox.
Parameters
----------
value : bool
value for the checkbox
"""
if value:
self.setChecked(Qt.Checked)
else:
self.setChecked(Qt.Unchecked)
|
def raise_figure_window ( f = 0 ) : if _fun . is_a_number ( f ) : f = _pylab . figure ( f ) f . canvas . manager . window . raise_ ( )
| 0 |
python matplotlib hide window
|
Raises the supplied figure number or figure window .
|
cosqa-train-15725
|
def raise_figure_window(f=0):
"""
Raises the supplied figure number or figure window.
"""
if _fun.is_a_number(f): f = _pylab.figure(f)
f.canvas.manager.window.raise_()
|
def IPYTHON_MAIN ( ) : import pkg_resources runner_frame = inspect . getouterframes ( inspect . currentframe ( ) ) [ - 2 ] return ( getattr ( runner_frame , "function" , None ) == pkg_resources . load_entry_point ( "ipython" , "console_scripts" , "ipython" ) . __name__ )
| 1 |
how to check if a python script is running idle window
|
Decide if the Ipython command line is running code .
|
cosqa-train-15726
|
def IPYTHON_MAIN():
"""Decide if the Ipython command line is running code."""
import pkg_resources
runner_frame = inspect.getouterframes(inspect.currentframe())[-2]
return (
getattr(runner_frame, "function", None)
== pkg_resources.load_entry_point("ipython", "console_scripts", "ipython").__name__
)
|
def extent ( self ) : return ( self . intervals [ 1 ] . pix1 - 0.5 , self . intervals [ 1 ] . pix2 - 0.5 , self . intervals [ 0 ] . pix1 - 0.5 , self . intervals [ 0 ] . pix2 - 0.5 , )
| 0 |
python matplotlib imshow center to extents
|
Helper for matplotlib imshow
|
cosqa-train-15727
|
def extent(self):
"""Helper for matplotlib imshow"""
return (
self.intervals[1].pix1 - 0.5,
self.intervals[1].pix2 - 0.5,
self.intervals[0].pix1 - 0.5,
self.intervals[0].pix2 - 0.5,
)
|
def exists ( self , filepath ) : if self . is_ssh ( filepath ) : self . _check_ftp ( ) remotepath = self . _get_remote ( filepath ) try : self . ftp . stat ( remotepath ) except IOError as e : if e . errno == errno . ENOENT : return False else : return True else : return os . path . exists ( filepath )
| 1 |
how to check if a remote path exists using sftp in python
|
Determines if the specified file / folder exists even if it is on a remote server .
|
cosqa-train-15728
|
def exists(self, filepath):
"""Determines if the specified file/folder exists, even if it
is on a remote server."""
if self.is_ssh(filepath):
self._check_ftp()
remotepath = self._get_remote(filepath)
try:
self.ftp.stat(remotepath)
except IOError as e:
if e.errno == errno.ENOENT:
return False
else:
return True
else:
return os.path.exists(filepath)
|
def plot ( self ) : plt . plot ( self . bin_edges , self . hist , self . bin_edges , self . best_pdf )
| 1 |
python matplotlib performance plot
|
Plot the empirical histogram versus best - fit distribution s PDF .
|
cosqa-train-15729
|
def plot(self):
"""Plot the empirical histogram versus best-fit distribution's PDF."""
plt.plot(self.bin_edges, self.hist, self.bin_edges, self.best_pdf)
|
def has_attribute ( module_name , attribute_name ) : init_file = '%s/__init__.py' % module_name return any ( [ attribute_name in init_line for init_line in open ( init_file ) . readlines ( ) ] )
| 1 |
how to check if attribute exists python
|
Is this attribute present?
|
cosqa-train-15730
|
def has_attribute(module_name, attribute_name):
"""Is this attribute present?"""
init_file = '%s/__init__.py' % module_name
return any(
[attribute_name in init_line for init_line in open(init_file).readlines()]
)
|
def set_ylimits ( self , row , column , min = None , max = None ) : subplot = self . get_subplot_at ( row , column ) subplot . set_ylimits ( min , max )
| 0 |
python matplotlib set ylim
|
Set y - axis limits of a subplot .
|
cosqa-train-15731
|
def set_ylimits(self, row, column, min=None, max=None):
"""Set y-axis limits of a subplot.
:param row,column: specify the subplot.
:param min: minimal axis value
:param max: maximum axis value
"""
subplot = self.get_subplot_at(row, column)
subplot.set_ylimits(min, max)
|
def is_same_dict ( d1 , d2 ) : for k , v in d1 . items ( ) : if isinstance ( v , dict ) : is_same_dict ( v , d2 [ k ] ) else : assert d1 [ k ] == d2 [ k ] for k , v in d2 . items ( ) : if isinstance ( v , dict ) : is_same_dict ( v , d1 [ k ] ) else : assert d1 [ k ] == d2 [ k ]
| 1 |
how to check if dictionaries are the same python
|
Test two dictionary is equal on values . ( ignore order )
|
cosqa-train-15732
|
def is_same_dict(d1, d2):
"""Test two dictionary is equal on values. (ignore order)
"""
for k, v in d1.items():
if isinstance(v, dict):
is_same_dict(v, d2[k])
else:
assert d1[k] == d2[k]
for k, v in d2.items():
if isinstance(v, dict):
is_same_dict(v, d1[k])
else:
assert d1[k] == d2[k]
|
def roots ( self ) : import numpy as np return np . roots ( list ( self . values ( ) ) [ : : - 1 ] ) . tolist ( )
| 0 |
python matrix of all ones
|
Returns a list with all roots . Needs Numpy .
|
cosqa-train-15733
|
def roots(self):
"""
Returns a list with all roots. Needs Numpy.
"""
import numpy as np
return np.roots(list(self.values())[::-1]).tolist()
|
def boxes_intersect ( box1 , box2 ) : xmin1 , xmax1 , ymin1 , ymax1 = box1 xmin2 , xmax2 , ymin2 , ymax2 = box2 if interval_intersection_width ( xmin1 , xmax1 , xmin2 , xmax2 ) and interval_intersection_width ( ymin1 , ymax1 , ymin2 , ymax2 ) : return True else : return False
| 1 |
how to check if polygons intersect in python
|
Determines if two rectangles each input as a tuple ( xmin xmax ymin ymax ) intersect .
|
cosqa-train-15734
|
def boxes_intersect(box1, box2):
"""Determines if two rectangles, each input as a tuple
(xmin, xmax, ymin, ymax), intersect."""
xmin1, xmax1, ymin1, ymax1 = box1
xmin2, xmax2, ymin2, ymax2 = box2
if interval_intersection_width(xmin1, xmax1, xmin2, xmax2) and \
interval_intersection_width(ymin1, ymax1, ymin2, ymax2):
return True
else:
return False
|
def copy ( a ) : shared = anonymousmemmap ( a . shape , dtype = a . dtype ) shared [ : ] = a [ : ] return shared
| 0 |
python memap numpy everything in memory
|
Copy an array to the shared memory .
|
cosqa-train-15735
|
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
|
def _is_iterable ( item ) : return isinstance ( item , collections . Iterable ) and not isinstance ( item , six . string_types )
| 1 |
how to check if python variable is iterable
|
Checks if an item is iterable ( list tuple generator ) but not string
|
cosqa-train-15736
|
def _is_iterable(item):
""" Checks if an item is iterable (list, tuple, generator), but not string """
return isinstance(item, collections.Iterable) and not isinstance(item, six.string_types)
|
def machine_info ( ) : import psutil BYTES_IN_GIG = 1073741824.0 free_bytes = psutil . virtual_memory ( ) . total return [ { "memory" : float ( "%.1f" % ( free_bytes / BYTES_IN_GIG ) ) , "cores" : multiprocessing . cpu_count ( ) , "name" : socket . gethostname ( ) } ]
| 1 |
python memory cpu inspect
|
Retrieve core and memory information for the current machine .
|
cosqa-train-15737
|
def machine_info():
"""Retrieve core and memory information for the current machine.
"""
import psutil
BYTES_IN_GIG = 1073741824.0
free_bytes = psutil.virtual_memory().total
return [{"memory": float("%.1f" % (free_bytes / BYTES_IN_GIG)), "cores": multiprocessing.cpu_count(),
"name": socket.gethostname()}]
|
def is_string ( val ) : try : basestring except NameError : return isinstance ( val , str ) return isinstance ( val , basestring )
| 0 |
how to check if the data type of a value is a string in python
|
Determines whether the passed value is a string safe for 2 / 3 .
|
cosqa-train-15738
|
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 with_defaults ( method , nparams , defaults = None ) : args = [ None ] * nparams if not defaults else defaults + max ( nparams - len ( defaults ) , 0 ) * [ None ] return method ( * args )
| 0 |
python method definition with default values to params
|
Call method with nparams positional parameters all non - specified defaults are passed None .
|
cosqa-train-15739
|
def with_defaults(method, nparams, defaults=None):
"""Call method with nparams positional parameters, all non-specified defaults are passed None.
:method: the method to call
:nparams: the number of parameters the function expects
:defaults: the default values to pass in for the last len(defaults) params
"""
args = [None] * nparams if not defaults else defaults + max(nparams - len(defaults), 0) * [None]
return method(*args)
|
def is_same_nick ( self , left , right ) : return self . normalize ( left ) == self . normalize ( right )
| 0 |
how to check if two words are the same in python regardless of case
|
Check if given nicknames are equal in the server s case mapping .
|
cosqa-train-15740
|
def is_same_nick(self, left, right):
""" Check if given nicknames are equal in the server's case mapping. """
return self.normalize(left) == self.normalize(right)
|
def _file_type ( self , field ) : type = mimetypes . guess_type ( self . _files [ field ] ) [ 0 ] return type . encode ( "utf-8" ) if isinstance ( type , unicode ) else str ( type )
| 0 |
python mime type from file name
|
Returns file type for given file field . Args : field ( str ) : File field
|
cosqa-train-15741
|
def _file_type(self, field):
""" Returns file type for given file field.
Args:
field (str): File field
Returns:
string. File type
"""
type = mimetypes.guess_type(self._files[field])[0]
return type.encode("utf-8") if isinstance(type, unicode) else str(type)
|
def is_date ( thing ) : # known date types date_types = ( datetime . datetime , datetime . date , DateTime ) return isinstance ( thing , date_types )
| 0 |
how to check if variable is datetime python
|
Checks if the given thing represents a date
|
cosqa-train-15742
|
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 update_one ( self , query , doc ) : if self . table is None : self . build_table ( ) if u"$set" in doc : doc = doc [ u"$set" ] allcond = self . parse_query ( query ) try : result = self . table . update ( doc , allcond ) except : # TODO: check table.update result # check what pymongo does in that case result = None return UpdateResult ( raw_result = result )
| 0 |
python mongo update not working
|
Updates one element of the collection
|
cosqa-train-15743
|
def update_one(self, query, doc):
"""
Updates one element of the collection
:param query: dictionary representing the mongo query
:param doc: dictionary representing the item to be updated
:return: UpdateResult
"""
if self.table is None:
self.build_table()
if u"$set" in doc:
doc = doc[u"$set"]
allcond = self.parse_query(query)
try:
result = self.table.update(doc, allcond)
except:
# TODO: check table.update result
# check what pymongo does in that case
result = None
return UpdateResult(raw_result=result)
|
def eof ( fd ) : b = fd . read ( 1 ) end = len ( b ) == 0 if not end : curpos = fd . tell ( ) fd . seek ( curpos - 1 ) return end
| 1 |
how to check if you have reached the end of a file in python
|
Determine if end - of - file is reached for file fd .
|
cosqa-train-15744
|
def eof(fd):
"""Determine if end-of-file is reached for file fd."""
b = fd.read(1)
end = len(b) == 0
if not end:
curpos = fd.tell()
fd.seek(curpos - 1)
return end
|
def last_month ( ) : since = TODAY + delta ( day = 1 , months = - 1 ) until = since + delta ( months = 1 ) return Date ( since ) , Date ( until )
| 0 |
python month range for from mm/yyyy and to mm/yyyy
|
Return start and end date of this month .
|
cosqa-train-15745
|
def last_month():
""" Return start and end date of this month. """
since = TODAY + delta(day=1, months=-1)
until = since + delta(months=1)
return Date(since), Date(until)
|
def _is_image_sequenced ( image ) : try : image . seek ( 1 ) image . seek ( 0 ) result = True except EOFError : result = False return result
| 0 |
how to check is a image is readable in python
|
Determine if the image is a sequenced image .
|
cosqa-train-15746
|
def _is_image_sequenced(image):
"""Determine if the image is a sequenced image."""
try:
image.seek(1)
image.seek(0)
result = True
except EOFError:
result = False
return result
|
def erase_lines ( n = 1 ) : for _ in range ( n ) : print ( codes . cursor [ "up" ] , end = "" ) print ( codes . cursor [ "eol" ] , end = "" )
| 0 |
python move cursor up n lines
|
Erases n lines from the screen and moves the cursor up to follow
|
cosqa-train-15747
|
def erase_lines(n=1):
""" Erases n lines from the screen and moves the cursor up to follow
"""
for _ in range(n):
print(codes.cursor["up"], end="")
print(codes.cursor["eol"], end="")
|
def is_readable_dir ( path ) : return os . path . isdir ( path ) and os . access ( path , os . R_OK ) and os . access ( path , os . X_OK )
| 0 |
how to check permission of directory using python
|
Returns whether a path names an existing directory we can list and read files from .
|
cosqa-train-15748
|
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 moving_average ( array , n = 3 ) : ret = _np . cumsum ( array , dtype = float ) ret [ n : ] = ret [ n : ] - ret [ : - n ] return ret [ n - 1 : ] / n
| 1 |
python moving average of a series
|
Calculates the moving average of an array .
|
cosqa-train-15749
|
def moving_average(array, n=3):
"""
Calculates the moving average of an array.
Parameters
----------
array : array
The array to have the moving average taken of
n : int
The number of points of moving average to take
Returns
-------
MovingAverageArray : array
The n-point moving average of the input array
"""
ret = _np.cumsum(array, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
|
def memory_used ( self ) : if self . _end_memory : memory_used = self . _end_memory - self . _start_memory return memory_used else : return None
| 1 |
how to check python memory
|
To know the allocated memory at function termination .
|
cosqa-train-15750
|
def memory_used(self):
"""To know the allocated memory at function termination.
..versionadded:: 4.1
This property might return None if the function is still running.
This function should help to show memory leaks or ram greedy code.
"""
if self._end_memory:
memory_used = self._end_memory - self._start_memory
return memory_used
else:
return None
|
def Min ( a , axis , keep_dims ) : return np . amin ( a , axis = axis if not isinstance ( axis , np . ndarray ) else tuple ( axis ) , keepdims = keep_dims ) ,
| 0 |
python multidimensional array argmin
|
Min reduction op .
|
cosqa-train-15751
|
def Min(a, axis, keep_dims):
"""
Min reduction op.
"""
return np.amin(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),
keepdims=keep_dims),
|
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." )
| 0 |
how to check python update
|
Check for app updates and print / log them .
|
cosqa-train-15752
|
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 load ( self ) : self . _list = self . _source . load ( ) self . _list_iter = itertools . cycle ( self . _list )
| 0 |
python multiprocess proxy list
|
Load proxy list from configured proxy source
|
cosqa-train-15753
|
def load(self):
"""Load proxy list from configured proxy source"""
self._list = self._source.load()
self._list_iter = itertools.cycle(self._list)
|
def string_input ( prompt = '' ) : v = sys . version [ 0 ] if v == '3' : return input ( prompt ) else : return raw_input ( prompt )
| 1 |
how to check python verion using prompt
|
Python 3 input () / Python 2 raw_input ()
|
cosqa-train-15754
|
def string_input(prompt=''):
"""Python 3 input()/Python 2 raw_input()"""
v = sys.version[0]
if v == '3':
return input(prompt)
else:
return raw_input(prompt)
|
def compute_capture ( args ) : x , y , w , h , params = args return x , y , mandelbrot_capture ( x , y , w , h , params )
| 1 |
python multiprocessing lock pool
|
Callable function for the multiprocessing pool .
|
cosqa-train-15755
|
def compute_capture(args):
x, y, w, h, params = args
"""Callable function for the multiprocessing pool."""
return x, y, mandelbrot_capture(x, y, w, h, params)
|
def created_today ( self ) : if self . datetime . date ( ) == datetime . today ( ) . date ( ) : return True return False
| 0 |
how to check the current date in python
|
Return True if created today .
|
cosqa-train-15756
|
def created_today(self):
"""Return True if created today."""
if self.datetime.date() == datetime.today().date():
return True
return False
|
def kill_mprocess ( process ) : if process and proc_alive ( process ) : process . terminate ( ) process . communicate ( ) return not proc_alive ( process )
| 0 |
python multiprocessing terminate child process
|
kill process Args : process - Popen object for process
|
cosqa-train-15757
|
def kill_mprocess(process):
"""kill process
Args:
process - Popen object for process
"""
if process and proc_alive(process):
process.terminate()
process.communicate()
return not proc_alive(process)
|
def assert_valid_input ( cls , tag ) : # Fail on unexpected types. if not cls . is_tag ( tag ) : raise TypeError ( "Expected a BeautifulSoup 'Tag', but instead recieved type {}" . format ( type ( tag ) ) )
| 1 |
how to check the type of a users input python
|
Check if valid input tag or document .
|
cosqa-train-15758
|
def assert_valid_input(cls, tag):
"""Check if valid input tag or document."""
# Fail on unexpected types.
if not cls.is_tag(tag):
raise TypeError("Expected a BeautifulSoup 'Tag', but instead recieved type {}".format(type(tag)))
|
def timeout_thread_handler ( timeout , stop_event ) : stop_happened = stop_event . wait ( timeout ) if stop_happened is False : print ( "Killing program due to %f second timeout" % timeout ) os . _exit ( 2 )
| 1 |
python multithreading code to run code then kill it after a certain period of time
|
A background thread to kill the process if it takes too long .
|
cosqa-train-15759
|
def timeout_thread_handler(timeout, stop_event):
"""A background thread to kill the process if it takes too long.
Args:
timeout (float): The number of seconds to wait before killing
the process.
stop_event (Event): An optional event to cleanly stop the background
thread if required during testing.
"""
stop_happened = stop_event.wait(timeout)
if stop_happened is False:
print("Killing program due to %f second timeout" % timeout)
os._exit(2)
|
def has_common ( self , other ) : if not isinstance ( other , WordSet ) : raise ValueError ( 'Can compare only WordSets' ) return self . term_set & other . term_set
| 1 |
how to check two lists for any common terms in python
|
Return set of common words between two word sets .
|
cosqa-train-15760
|
def has_common(self, other):
"""Return set of common words between two word sets."""
if not isinstance(other, WordSet):
raise ValueError('Can compare only WordSets')
return self.term_set & other.term_set
|
def pause ( self ) : mixer . music . pause ( ) self . pause_time = self . get_time ( ) self . paused = True
| 1 |
python musicbox play pause
|
Pause the music
|
cosqa-train-15761
|
def pause(self):
"""Pause the music"""
mixer.music.pause()
self.pause_time = self.get_time()
self.paused = True
|
def autoconvert ( string ) : for fn in ( boolify , int , float ) : try : return fn ( string ) except ValueError : pass return string
| 0 |
how to check varible data type in python
|
Try to convert variables into datatypes .
|
cosqa-train-15762
|
def autoconvert(string):
"""Try to convert variables into datatypes."""
for fn in (boolify, int, float):
try:
return fn(string)
except ValueError:
pass
return string
|
def autoconvert ( string ) : for fn in ( boolify , int , float ) : try : return fn ( string ) except ValueError : pass return string
| 0 |
python must be a mapping, not str
|
Try to convert variables into datatypes .
|
cosqa-train-15763
|
def autoconvert(string):
"""Try to convert variables into datatypes."""
for fn in (boolify, int, float):
try:
return fn(string)
except ValueError:
pass
return string
|
def type ( self ) : if self is FeatureType . TIMESTAMP : return list if self is FeatureType . BBOX : return BBox return dict
| 0 |
how to check what type of data i have in python
|
Returns type of the data for the given FeatureType .
|
cosqa-train-15764
|
def type(self):
"""Returns type of the data for the given FeatureType."""
if self is FeatureType.TIMESTAMP:
return list
if self is FeatureType.BBOX:
return BBox
return dict
|
def isstring ( value ) : classes = ( str , bytes ) if pyutils . PY3 else basestring # noqa: F821 return isinstance ( value , classes )
| 1 |
python must be str, not nonetype
|
Report whether the given value is a byte or unicode string .
|
cosqa-train-15765
|
def isstring(value):
"""Report whether the given value is a byte or unicode string."""
classes = (str, bytes) if pyutils.PY3 else basestring # noqa: F821
return isinstance(value, classes)
|
def chmod_plus_w ( path ) : path_mode = os . stat ( path ) . st_mode path_mode &= int ( '777' , 8 ) path_mode |= stat . S_IWRITE os . chmod ( path , path_mode )
| 0 |
how to chmod in python for entire directory
|
Equivalent of unix chmod + w path
|
cosqa-train-15766
|
def chmod_plus_w(path):
"""Equivalent of unix `chmod +w path`"""
path_mode = os.stat(path).st_mode
path_mode &= int('777', 8)
path_mode |= stat.S_IWRITE
os.chmod(path, path_mode)
|
def object_as_dict ( obj ) : return { c . key : getattr ( obj , c . key ) for c in inspect ( obj ) . mapper . column_attrs }
| 1 |
python mysql get field as dict
|
Turn an SQLAlchemy model into a dict of field names and values .
|
cosqa-train-15767
|
def object_as_dict(obj):
"""Turn an SQLAlchemy model into a dict of field names and values.
Based on https://stackoverflow.com/a/37350445/1579058
"""
return {c.key: getattr(obj, c.key)
for c in inspect(obj).mapper.column_attrs}
|
def random_choice ( sequence ) : return random . choice ( tuple ( sequence ) if isinstance ( sequence , set ) else sequence )
| 0 |
how to choose a random element from a set in python
|
Same as : meth : random . choice but also supports : class : set type to be passed as sequence .
|
cosqa-train-15768
|
def random_choice(sequence):
""" Same as :meth:`random.choice`, but also supports :class:`set` type to be passed as sequence. """
return random.choice(tuple(sequence) if isinstance(sequence, set) else sequence)
|
def object_as_dict ( obj ) : return { c . key : getattr ( obj , c . key ) for c in inspect ( obj ) . mapper . column_attrs }
| 0 |
python mysqldb result as dict
|
Turn an SQLAlchemy model into a dict of field names and values .
|
cosqa-train-15769
|
def object_as_dict(obj):
"""Turn an SQLAlchemy model into a dict of field names and values.
Based on https://stackoverflow.com/a/37350445/1579058
"""
return {c.key: getattr(obj, c.key)
for c in inspect(obj).mapper.column_attrs}
|
def first_unique_char ( s ) : if ( len ( s ) == 1 ) : return 0 ban = [ ] for i in range ( len ( s ) ) : if all ( s [ i ] != s [ k ] for k in range ( i + 1 , len ( s ) ) ) == True and s [ i ] not in ban : return i else : ban . append ( s [ i ] ) return - 1
| 1 |
how to choose unique character from a string in python
|
: type s : str : rtype : int
|
cosqa-train-15770
|
def first_unique_char(s):
"""
:type s: str
:rtype: int
"""
if (len(s) == 1):
return 0
ban = []
for i in range(len(s)):
if all(s[i] != s[k] for k in range(i + 1, len(s))) == True and s[i] not in ban:
return i
else:
ban.append(s[i])
return -1
|
def load_object_by_name ( object_name ) : mod_name , attr = object_name . rsplit ( '.' , 1 ) mod = import_module ( mod_name ) return getattr ( mod , attr )
| 0 |
python name object by input
|
Load an object from a module by name
|
cosqa-train-15771
|
def load_object_by_name(object_name):
"""Load an object from a module by name"""
mod_name, attr = object_name.rsplit('.', 1)
mod = import_module(mod_name)
return getattr(mod, attr)
|
def erase ( self ) : with self . _at_last_line ( ) : self . stream . write ( self . _term . clear_eol ) self . stream . flush ( )
| 0 |
how to clear a printed line in python
|
White out the progress bar .
|
cosqa-train-15772
|
def erase(self):
"""White out the progress bar."""
with self._at_last_line():
self.stream.write(self._term.clear_eol)
self.stream.flush()
|
def dictify ( a_named_tuple ) : return dict ( ( s , getattr ( a_named_tuple , s ) ) for s in a_named_tuple . _fields )
| 0 |
python namedtuple to dict
|
Transform a named tuple into a dictionary
|
cosqa-train-15773
|
def dictify(a_named_tuple):
"""Transform a named tuple into a dictionary"""
return dict((s, getattr(a_named_tuple, s)) for s in a_named_tuple._fields)
|
def __clear_buffers ( self ) : try : self . _port . reset_input_buffer ( ) self . _port . reset_output_buffer ( ) except AttributeError : #pySerial 2.7 self . _port . flushInput ( ) self . _port . flushOutput ( )
| 0 |
how to clear buffer in python3
|
Clears the input and output buffers
|
cosqa-train-15774
|
def __clear_buffers(self):
"""Clears the input and output buffers"""
try:
self._port.reset_input_buffer()
self._port.reset_output_buffer()
except AttributeError:
#pySerial 2.7
self._port.flushInput()
self._port.flushOutput()
|
def index_nearest ( array , value ) : idx = ( np . abs ( array - value ) ) . argmin ( ) return idx
| 1 |
python nearest pixel value image
|
Finds index of nearest value in array . Args : array : numpy array value : Returns : int http : // stackoverflow . com / questions / 2566412 / find - nearest - value - in - numpy - array
|
cosqa-train-15775
|
def index_nearest(array, value):
"""
Finds index of nearest value in array.
Args:
array: numpy array
value:
Returns:
int
http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array
"""
idx = (np.abs(array-value)).argmin()
return idx
|
def raise_figure_window ( f = 0 ) : if _fun . is_a_number ( f ) : f = _pylab . figure ( f ) f . canvas . manager . window . raise_ ( )
| 0 |
how to clear figure from window python
|
Raises the supplied figure number or figure window .
|
cosqa-train-15776
|
def raise_figure_window(f=0):
"""
Raises the supplied figure number or figure window.
"""
if _fun.is_a_number(f): f = _pylab.figure(f)
f.canvas.manager.window.raise_()
|
def from_dict ( cls , d ) : return cls ( * * { k : v for k , v in d . items ( ) if k in cls . ENTRIES } )
| 1 |
python new instance from dict
|
Create an instance from a dictionary .
|
cosqa-train-15777
|
def from_dict(cls, d):
"""Create an instance from a dictionary."""
return cls(**{k: v for k, v in d.items() if k in cls.ENTRIES})
|
def stop_refresh ( self ) : self . logger . debug ( "stopping timed refresh" ) self . rf_flags [ 'done' ] = True self . rf_timer . clear ( )
| 1 |
how to clear python canvas after 5 seconds
|
Stop redrawing the canvas at the previously set timed interval .
|
cosqa-train-15778
|
def stop_refresh(self):
"""Stop redrawing the canvas at the previously set timed interval.
"""
self.logger.debug("stopping timed refresh")
self.rf_flags['done'] = True
self.rf_timer.clear()
|
def make_file_read_only ( file_path ) : old_permissions = os . stat ( file_path ) . st_mode os . chmod ( file_path , old_permissions & ~ WRITE_PERMISSIONS )
| 0 |
python nfs cant open file permissions
|
Removes the write permissions for the given file for owner groups and others .
|
cosqa-train-15779
|
def make_file_read_only(file_path):
"""
Removes the write permissions for the given file for owner, groups and others.
:param file_path: The file whose privileges are revoked.
:raise FileNotFoundError: If the given file does not exist.
"""
old_permissions = os.stat(file_path).st_mode
os.chmod(file_path, old_permissions & ~WRITE_PERMISSIONS)
|
def clear_globals_reload_modules ( self ) : self . code_array . clear_globals ( ) self . code_array . reload_modules ( ) # Clear result cache self . code_array . result_cache . clear ( )
| 1 |
how to clear python variables at begining of code
|
Clears globals and reloads modules
|
cosqa-train-15780
|
def clear_globals_reload_modules(self):
"""Clears globals and reloads modules"""
self.code_array.clear_globals()
self.code_array.reload_modules()
# Clear result cache
self.code_array.result_cache.clear()
|
def norm ( x , mu , sigma = 1.0 ) : return stats . norm ( loc = mu , scale = sigma ) . pdf ( x )
| 0 |
python normal distribution function
|
Scipy norm function
|
cosqa-train-15781
|
def norm(x, mu, sigma=1.0):
""" Scipy norm function """
return stats.norm(loc=mu, scale=sigma).pdf(x)
|
def EvalGaussianPdf ( x , mu , sigma ) : return scipy . stats . norm . pdf ( x , mu , sigma )
| 1 |
python normal distribution p values
|
Computes the unnormalized PDF of the normal distribution .
|
cosqa-train-15782
|
def EvalGaussianPdf(x, mu, sigma):
"""Computes the unnormalized PDF of the normal distribution.
x: value
mu: mean
sigma: standard deviation
returns: float probability density
"""
return scipy.stats.norm.pdf(x, mu, sigma)
|
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
| 0 |
how to click on the next page using python
|
Callback to go to the next tab . Called by the accel key .
|
cosqa-train-15783
|
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 normalize ( im , invert = False , scale = None , dtype = np . float64 ) : if dtype not in { np . float16 , np . float32 , np . float64 } : raise ValueError ( 'dtype must be numpy.float16, float32, or float64.' ) out = im . astype ( 'float' ) . copy ( ) scale = scale or ( 0.0 , 255.0 ) l , u = ( float ( i ) for i in scale ) out = ( out - l ) / ( u - l ) if invert : out = - out + ( out . max ( ) + out . min ( ) ) return out . astype ( dtype )
| 1 |
python normalize an entire image
|
Normalize a field to a ( min max ) exposure range default is ( 0 255 ) . ( min max ) exposure values . Invert the image if requested .
|
cosqa-train-15784
|
def normalize(im, invert=False, scale=None, dtype=np.float64):
"""
Normalize a field to a (min, max) exposure range, default is (0, 255).
(min, max) exposure values. Invert the image if requested.
"""
if dtype not in {np.float16, np.float32, np.float64}:
raise ValueError('dtype must be numpy.float16, float32, or float64.')
out = im.astype('float').copy()
scale = scale or (0.0, 255.0)
l, u = (float(i) for i in scale)
out = (out - l) / (u - l)
if invert:
out = -out + (out.max() + out.min())
return out.astype(dtype)
|
def cleanup ( self , app ) : if hasattr ( self . database . obj , 'close_all' ) : self . database . close_all ( )
| 0 |
how to close all connections python mongo
|
Close all connections .
|
cosqa-train-15785
|
def cleanup(self, app):
"""Close all connections."""
if hasattr(self.database.obj, 'close_all'):
self.database.close_all()
|
def _normalize ( mat : np . ndarray ) : return ( ( mat - mat . min ( ) ) * ( 255 / mat . max ( ) ) ) . astype ( np . uint8 )
| 1 |
python normalize between zero and 255
|
rescales a numpy array so that min is 0 and max is 255
|
cosqa-train-15786
|
def _normalize(mat: np.ndarray):
"""rescales a numpy array, so that min is 0 and max is 255"""
return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8)
|
def _close ( self ) : if self . connection : with self . wrap_database_errors : self . connection . client . close ( )
| 1 |
how to close the connection in createengine in python
|
Closes the client connection to the database .
|
cosqa-train-15787
|
def _close(self):
"""
Closes the client connection to the database.
"""
if self.connection:
with self.wrap_database_errors:
self.connection.client.close()
|
def _normalize ( obj ) : if isinstance ( obj , list ) : return [ _normalize ( item ) for item in obj ] elif isinstance ( obj , dict ) : return { k : _normalize ( v ) for k , v in obj . items ( ) if v is not None } elif hasattr ( obj , 'to_python' ) : return obj . to_python ( ) return obj
| 0 |
python normalize list of dicts
|
Normalize dicts and lists
|
cosqa-train-15788
|
def _normalize(obj):
"""
Normalize dicts and lists
:param obj:
:return: normalized object
"""
if isinstance(obj, list):
return [_normalize(item) for item in obj]
elif isinstance(obj, dict):
return {k: _normalize(v) for k, v in obj.items() if v is not None}
elif hasattr(obj, 'to_python'):
return obj.to_python()
return obj
|
def pascal_row ( n ) : result = [ 1 ] x , numerator = 1 , n for denominator in range ( 1 , n // 2 + 1 ) : x *= numerator x /= denominator result . append ( x ) numerator -= 1 if n & 1 == 0 : result . extend ( reversed ( result [ : - 1 ] ) ) else : result . extend ( reversed ( result ) ) return result
| 0 |
how to code n rows of the pascal triangle in python
|
Returns n - th row of Pascal s triangle
|
cosqa-train-15789
|
def pascal_row(n):
""" Returns n-th row of Pascal's triangle
"""
result = [1]
x, numerator = 1, n
for denominator in range(1, n // 2 + 1):
x *= numerator
x /= denominator
result.append(x)
numerator -= 1
if n & 1 == 0:
result.extend(reversed(result[:-1]))
else:
result.extend(reversed(result))
return result
|
def run ( self ) : try : import nose arguments = [ sys . argv [ 0 ] ] + list ( self . test_args ) return nose . run ( argv = arguments ) except ImportError : print ( ) print ( "*** Nose library missing. Please install it. ***" ) print ( ) raise
| 1 |
python nose fail first test
|
Runs the unit test framework . Can be overridden to run anything . Returns True on passing and False on failure .
|
cosqa-train-15790
|
def run(self):
"""
Runs the unit test framework. Can be overridden to run anything.
Returns True on passing and False on failure.
"""
try:
import nose
arguments = [sys.argv[0]] + list(self.test_args)
return nose.run(argv=arguments)
except ImportError:
print()
print("*** Nose library missing. Please install it. ***")
print()
raise
|
def place ( self ) : self . place_children ( ) self . canvas . append ( self . parent . canvas , float ( self . left ) , float ( self . top ) )
| 0 |
how to combine multiple python canvas objects as one
|
Place this container s canvas onto the parent container s canvas .
|
cosqa-train-15791
|
def place(self):
"""Place this container's canvas onto the parent container's canvas."""
self.place_children()
self.canvas.append(self.parent.canvas,
float(self.left), float(self.top))
|
def test ( nose_argsuments ) : from nose import run params = [ '__main__' , '-c' , 'nose.ini' ] params . extend ( nose_argsuments ) run ( argv = params )
| 0 |
python nose not finding tests
|
Run application tests
|
cosqa-train-15792
|
def test(nose_argsuments):
""" Run application tests """
from nose import run
params = ['__main__', '-c', 'nose.ini']
params.extend(nose_argsuments)
run(argv=params)
|
def merge_dict ( data , * args ) : results = { } for current in ( data , ) + args : results . update ( current ) return results
| 1 |
how to combine several dictory into one in python
|
Merge any number of dictionaries
|
cosqa-train-15793
|
def merge_dict(data, *args):
"""Merge any number of dictionaries
"""
results = {}
for current in (data,) + args:
results.update(current)
return results
|
def wait_until_exit ( self ) : if self . _timeout is None : raise Exception ( "Thread will never exit. Use stop or specify timeout when starting it!" ) self . _thread . join ( ) self . stop ( )
| 1 |
python not exiting after thread ends
|
Wait until thread exit
|
cosqa-train-15794
|
def wait_until_exit(self):
""" Wait until thread exit
Used for testing purpose only
"""
if self._timeout is None:
raise Exception("Thread will never exit. Use stop or specify timeout when starting it!")
self._thread.join()
self.stop()
|
def equal ( obj1 , obj2 ) : Comparable . log ( obj1 , obj2 , '==' ) equality = obj1 . equality ( obj2 ) Comparable . log ( obj1 , obj2 , '==' , result = equality ) return equality
| 1 |
how to compare objects in python
|
Calculate equality between two ( Comparable ) objects .
|
cosqa-train-15795
|
def equal(obj1, obj2):
"""Calculate equality between two (Comparable) objects."""
Comparable.log(obj1, obj2, '==')
equality = obj1.equality(obj2)
Comparable.log(obj1, obj2, '==', result=equality)
return equality
|
def cfloat32_array_to_numpy ( cptr , length ) : if isinstance ( cptr , ctypes . POINTER ( ctypes . c_float ) ) : return np . fromiter ( cptr , dtype = np . float32 , count = length ) else : raise RuntimeError ( 'Expected float pointer' )
| 0 |
python nparray to float pointer
|
Convert a ctypes float pointer array to a numpy array .
|
cosqa-train-15796
|
def cfloat32_array_to_numpy(cptr, length):
"""Convert a ctypes float pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_float)):
return np.fromiter(cptr, dtype=np.float32, count=length)
else:
raise RuntimeError('Expected float pointer')
|
def euclidean ( x , y ) : result = 0.0 for i in range ( x . shape [ 0 ] ) : result += ( x [ i ] - y [ i ] ) ** 2 return np . sqrt ( result )
| 1 |
how to compute euclidean distance in 3 space in python
|
Standard euclidean distance .
|
cosqa-train-15797
|
def euclidean(x, y):
"""Standard euclidean distance.
..math::
D(x, y) = \sqrt{\sum_i (x_i - y_i)^2}
"""
result = 0.0
for i in range(x.shape[0]):
result += (x[i] - y[i]) ** 2
return np.sqrt(result)
|
def compute_number_edges ( function ) : n = 0 for node in function . nodes : n += len ( node . sons ) return n
| 1 |
python number of edges in a set of nodes
|
Compute the number of edges of the CFG Args : function ( core . declarations . function . Function ) Returns : int
|
cosqa-train-15798
|
def compute_number_edges(function):
"""
Compute the number of edges of the CFG
Args:
function (core.declarations.function.Function)
Returns:
int
"""
n = 0
for node in function.nodes:
n += len(node.sons)
return n
|
def bytesize ( arr ) : byte_size = np . prod ( arr . shape ) * np . dtype ( arr . dtype ) . itemsize return byte_size
| 1 |
how to compute memory size used by an array python
|
Returns the memory byte size of a Numpy array as an integer .
|
cosqa-train-15799
|
def bytesize(arr):
"""
Returns the memory byte size of a Numpy array as an integer.
"""
byte_size = np.prod(arr.shape) * np.dtype(arr.dtype).itemsize
return byte_size
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.