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 fill_form ( form , data ) : for ( key , value ) in data . items ( ) : if hasattr ( form , key ) : if isinstance ( value , dict ) : fill_form ( getattr ( form , key ) , value ) else : getattr ( form , key ) . data = value return form
| 0 |
python fill a form
|
Prefill form with data .
|
cosqa-train-300
|
def fill_form(form, data):
"""Prefill form with data.
:param form: The form to fill.
:param data: The data to insert in the form.
:returns: A pre-filled form.
"""
for (key, value) in data.items():
if hasattr(form, key):
if isinstance(value, dict):
fill_form(getattr(form, key), value)
else:
getattr(form, key).data = value
return form
|
def check_clang_apply_replacements_binary ( args ) : try : subprocess . check_call ( [ args . clang_apply_replacements_binary , '--version' ] ) except : print ( 'Unable to run clang-apply-replacements. Is clang-apply-replacements ' 'binary correctly specified?' , file = sys . stderr ) traceback . print_exc ( ) sys . exit ( 1 )
| 0 |
compile python with clang
|
Checks if invoking supplied clang - apply - replacements binary works .
|
cosqa-train-301
|
def check_clang_apply_replacements_binary(args):
"""Checks if invoking supplied clang-apply-replacements binary works."""
try:
subprocess.check_call([args.clang_apply_replacements_binary, '--version'])
except:
print('Unable to run clang-apply-replacements. Is clang-apply-replacements '
'binary correctly specified?', file=sys.stderr)
traceback.print_exc()
sys.exit(1)
|
def _maybe_fill ( arr , fill_value = np . nan ) : if _isna_compat ( arr , fill_value ) : arr . fill ( fill_value ) return arr
| 0 |
python fillna if false
|
if we have a compatible fill_value and arr dtype then fill
|
cosqa-train-302
|
def _maybe_fill(arr, fill_value=np.nan):
"""
if we have a compatible fill_value and arr dtype, then fill
"""
if _isna_compat(arr, fill_value):
arr.fill(fill_value)
return arr
|
def extract_alzip ( archive , compression , cmd , verbosity , interactive , outdir ) : return [ cmd , '-d' , outdir , archive ]
| 0 |
compression in python without using zlib
|
Extract a ALZIP archive .
|
cosqa-train-303
|
def extract_alzip (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a ALZIP archive."""
return [cmd, '-d', outdir, archive]
|
def _maybe_fill ( arr , fill_value = np . nan ) : if _isna_compat ( arr , fill_value ) : arr . fill ( fill_value ) return arr
| 1 |
python fillna inplace not working
|
if we have a compatible fill_value and arr dtype then fill
|
cosqa-train-304
|
def _maybe_fill(arr, fill_value=np.nan):
"""
if we have a compatible fill_value and arr dtype, then fill
"""
if _isna_compat(arr, fill_value):
arr.fill(fill_value)
return arr
|
def get_lons_from_cartesian ( x__ , y__ ) : return rad2deg ( arccos ( x__ / sqrt ( x__ ** 2 + y__ ** 2 ) ) ) * sign ( y__ )
| 0 |
compute degrees from survey bearing python function
|
Get longitudes from cartesian coordinates .
|
cosqa-train-305
|
def get_lons_from_cartesian(x__, y__):
"""Get longitudes from cartesian coordinates.
"""
return rad2deg(arccos(x__ / sqrt(x__ ** 2 + y__ ** 2))) * sign(y__)
|
def filter_ ( stream_spec , filter_name , * args , * * kwargs ) : return filter ( stream_spec , filter_name , * args , * * kwargs )
| 0 |
python filter str object is not callable
|
Alternate name for filter so as to not collide with the built - in python filter operator .
|
cosqa-train-306
|
def filter_(stream_spec, filter_name, *args, **kwargs):
"""Alternate name for ``filter``, so as to not collide with the
built-in python ``filter`` operator.
"""
return filter(stream_spec, filter_name, *args, **kwargs)
|
def _calculate_distance ( latlon1 , latlon2 ) : lat1 , lon1 = latlon1 lat2 , lon2 = latlon2 dlon = lon2 - lon1 dlat = lat2 - lat1 R = 6371 # radius of the earth in kilometers a = np . sin ( dlat / 2 ) ** 2 + np . cos ( lat1 ) * np . cos ( lat2 ) * ( np . sin ( dlon / 2 ) ) ** 2 c = 2 * np . pi * R * np . arctan2 ( np . sqrt ( a ) , np . sqrt ( 1 - a ) ) / 180 return c
| 1 |
compute distance from longitude and latitude python
|
Calculates the distance between two points on earth .
|
cosqa-train-307
|
def _calculate_distance(latlon1, latlon2):
"""Calculates the distance between two points on earth.
"""
lat1, lon1 = latlon1
lat2, lon2 = latlon2
dlon = lon2 - lon1
dlat = lat2 - lat1
R = 6371 # radius of the earth in kilometers
a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2
c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180
return c
|
def find_lt ( a , x ) : i = bs . bisect_left ( a , x ) if i : return i - 1 raise ValueError
| 1 |
python finding the smallest and largetst valuse in a list
|
Find rightmost value less than x .
|
cosqa-train-308
|
def find_lt(a, x):
"""Find rightmost value less than x."""
i = bs.bisect_left(a, x)
if i: return i - 1
raise ValueError
|
def get_stationary_distribution ( self ) : # The stationary distribution is proportional to the left-eigenvector # associated with the largest eigenvalue (i.e., 1) of the transition # matrix. check_is_fitted ( self , "transmat_" ) eigvals , eigvecs = np . linalg . eig ( self . transmat_ . T ) eigvec = np . real_if_close ( eigvecs [ : , np . argmax ( eigvals ) ] ) return eigvec / eigvec . sum ( )
| 0 |
compute eigenvalues of transition matrix in python
|
Compute the stationary distribution of states .
|
cosqa-train-309
|
def get_stationary_distribution(self):
"""Compute the stationary distribution of states.
"""
# The stationary distribution is proportional to the left-eigenvector
# associated with the largest eigenvalue (i.e., 1) of the transition
# matrix.
check_is_fitted(self, "transmat_")
eigvals, eigvecs = np.linalg.eig(self.transmat_.T)
eigvec = np.real_if_close(eigvecs[:, np.argmax(eigvals)])
return eigvec / eigvec.sum()
|
def apply_fit ( xy , coeffs ) : x_new = coeffs [ 0 ] [ 2 ] + coeffs [ 0 ] [ 0 ] * xy [ : , 0 ] + coeffs [ 0 ] [ 1 ] * xy [ : , 1 ] y_new = coeffs [ 1 ] [ 2 ] + coeffs [ 1 ] [ 0 ] * xy [ : , 0 ] + coeffs [ 1 ] [ 1 ] * xy [ : , 1 ] return x_new , y_new
| 0 |
python fit in 2 dimensions
|
Apply the coefficients from a linear fit to an array of x y positions .
|
cosqa-train-310
|
def apply_fit(xy,coeffs):
""" Apply the coefficients from a linear fit to
an array of x,y positions.
The coeffs come from the 'coeffs' member of the
'fit_arrays()' output.
"""
x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1]
y_new = coeffs[1][2] + coeffs[1][0]*xy[:,0] + coeffs[1][1]*xy[:,1]
return x_new,y_new
|
def _tf_squared_euclidean ( X , Y ) : return tf . reduce_sum ( tf . pow ( tf . subtract ( X , Y ) , 2 ) , axis = 1 )
| 0 |
compute euclidean distance between test set and training setin python
|
Squared Euclidean distance between the rows of X and Y .
|
cosqa-train-311
|
def _tf_squared_euclidean(X, Y):
"""Squared Euclidean distance between the rows of `X` and `Y`.
"""
return tf.reduce_sum(tf.pow(tf.subtract(X, Y), 2), axis=1)
|
def exp_fit_fun ( x , a , tau , c ) : # pylint: disable=invalid-name return a * np . exp ( - x / tau ) + c
| 1 |
python fit to exponential function
|
Function used to fit the exponential decay .
|
cosqa-train-312
|
def exp_fit_fun(x, a, tau, c):
"""Function used to fit the exponential decay."""
# pylint: disable=invalid-name
return a * np.exp(-x / tau) + c
|
def euclidean ( x , y ) : result = 0.0 for i in range ( x . shape [ 0 ] ) : result += ( x [ i ] - y [ i ] ) ** 2 return np . sqrt ( result )
| 0 |
compute euclidean distance python 2d
|
Standard euclidean distance .
|
cosqa-train-313
|
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 create_table_from_fits ( fitsfile , hduname , colnames = None ) : if colnames is None : return Table . read ( fitsfile , hduname ) cols = [ ] with fits . open ( fitsfile , memmap = True ) as h : for k in colnames : data = h [ hduname ] . data . field ( k ) cols += [ Column ( name = k , data = data ) ] return Table ( cols )
| 0 |
python fits table add a column
|
Memory efficient function for loading a table from a FITS file .
|
cosqa-train-314
|
def create_table_from_fits(fitsfile, hduname, colnames=None):
"""Memory efficient function for loading a table from a FITS
file."""
if colnames is None:
return Table.read(fitsfile, hduname)
cols = []
with fits.open(fitsfile, memmap=True) as h:
for k in colnames:
data = h[hduname].data.field(k)
cols += [Column(name=k, data=data)]
return Table(cols)
|
def _gcd_array ( X ) : greatest_common_divisor = 0.0 for x in X : greatest_common_divisor = _gcd ( greatest_common_divisor , x ) return greatest_common_divisor
| 0 |
compute gcd of a list of element in python
|
Return the largest real value h such that all elements in x are integer multiples of h .
|
cosqa-train-315
|
def _gcd_array(X):
"""
Return the largest real value h such that all elements in x are integer
multiples of h.
"""
greatest_common_divisor = 0.0
for x in X:
greatest_common_divisor = _gcd(greatest_common_divisor, x)
return greatest_common_divisor
|
def lint ( args ) : application = get_current_application ( ) if not args : args = [ application . name , 'tests' ] args = [ 'flake8' ] + list ( args ) run . main ( args , standalone_mode = False )
| 0 |
python flake8 line too long
|
Run lint checks using flake8 .
|
cosqa-train-316
|
def lint(args):
"""Run lint checks using flake8."""
application = get_current_application()
if not args:
args = [application.name, 'tests']
args = ['flake8'] + list(args)
run.main(args, standalone_mode=False)
|
def torecarray ( * args , * * kwargs ) : import numpy as np return toarray ( * args , * * kwargs ) . view ( np . recarray )
| 0 |
conactecate array python without numpy
|
Convenient shorthand for toarray ( * args ** kwargs ) . view ( np . recarray ) .
|
cosqa-train-317
|
def torecarray(*args, **kwargs):
"""
Convenient shorthand for ``toarray(*args, **kwargs).view(np.recarray)``.
"""
import numpy as np
return toarray(*args, **kwargs).view(np.recarray)
|
def _type_bool ( label , default = False ) : return label , abstractSearch . nothing , abstractRender . boolen , default
| 0 |
python flask booleanfield center
|
Shortcut fot boolean like fields
|
cosqa-train-318
|
def _type_bool(label,default=False):
"""Shortcut fot boolean like fields"""
return label, abstractSearch.nothing, abstractRender.boolen, default
|
def join_cols ( cols ) : return ", " . join ( [ i for i in cols ] ) if isinstance ( cols , ( list , tuple , set ) ) else cols
| 0 |
concate column names in python
|
Join list of columns into a string for a SQL query
|
cosqa-train-319
|
def join_cols(cols):
"""Join list of columns into a string for a SQL query"""
return ", ".join([i for i in cols]) if isinstance(cols, (list, tuple, set)) else cols
|
def parse_form ( self , req , name , field ) : return core . get_value ( req . POST , name , field )
| 0 |
python flask get text from form post
|
Pull a form value from the request .
|
cosqa-train-320
|
def parse_form(self, req, name, field):
"""Pull a form value from the request."""
return core.get_value(req.POST, name, field)
|
def cors_header ( func ) : @ wraps ( func ) def wrapper ( self , request , * args , * * kwargs ) : res = func ( self , request , * args , * * kwargs ) request . setHeader ( 'Access-Control-Allow-Origin' , '*' ) request . setHeader ( 'Access-Control-Allow-Headers' , 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With' ) return res return wrapper
| 0 |
python flask header cors allow
|
cosqa-train-321
|
def cors_header(func):
""" @cors_header decorator adds CORS headers """
@wraps(func)
def wrapper(self, request, *args, **kwargs):
res = func(self, request, *args, **kwargs)
request.setHeader('Access-Control-Allow-Origin', '*')
request.setHeader('Access-Control-Allow-Headers', 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With')
return res
return wrapper
|
|
def pdf ( x , mu , std ) : return ( 1.0 / ( std * sqrt ( 2 * pi ) ) ) * np . exp ( - ( x - mu ) ** 2 / ( 2 * std ** 2 ) )
| 0 |
conditional probability function in python
|
Probability density function ( normal distribution )
|
cosqa-train-322
|
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 handleFlaskPostRequest ( flaskRequest , endpoint ) : if flaskRequest . method == "POST" : return handleHttpPost ( flaskRequest , endpoint ) elif flaskRequest . method == "OPTIONS" : return handleHttpOptions ( ) else : raise exceptions . MethodNotAllowedException ( )
| 0 |
python flask method for common request
|
Handles the specified flask request for one of the POST URLS Invokes the specified endpoint to generate a response .
|
cosqa-train-323
|
def handleFlaskPostRequest(flaskRequest, endpoint):
"""
Handles the specified flask request for one of the POST URLS
Invokes the specified endpoint to generate a response.
"""
if flaskRequest.method == "POST":
return handleHttpPost(flaskRequest, endpoint)
elif flaskRequest.method == "OPTIONS":
return handleHttpOptions()
else:
raise exceptions.MethodNotAllowedException()
|
def pdf ( x , mu , std ) : return ( 1.0 / ( std * sqrt ( 2 * pi ) ) ) * np . exp ( - ( x - mu ) ** 2 / ( 2 * std ** 2 ) )
| 0 |
conditional probability functions in python
|
Probability density function ( normal distribution )
|
cosqa-train-324
|
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 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
| 0 |
python flask mime types
|
Decorator which adds correct MIME type for python source to the decorated bottle API function .
|
cosqa-train-325
|
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 _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 ( )
| 0 |
confluent kafka consume poll python
|
Spawns a kafka continuous consumer thread
|
cosqa-train-326
|
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 flatpages_link_list ( request ) : from django . contrib . flatpages . models import FlatPage link_list = [ ( page . title , page . url ) for page in FlatPage . objects . all ( ) ] return render_to_link_list ( link_list )
| 0 |
python flask render list of files as links
|
Returns a HttpResponse whose content is a Javascript file representing a list of links to flatpages .
|
cosqa-train-327
|
def flatpages_link_list(request):
"""
Returns a HttpResponse whose content is a Javascript file representing a
list of links to flatpages.
"""
from django.contrib.flatpages.models import FlatPage
link_list = [(page.title, page.url) for page in FlatPage.objects.all()]
return render_to_link_list(link_list)
|
def values ( self ) : lower = float ( self . lowerSpnbx . value ( ) ) upper = float ( self . upperSpnbx . value ( ) ) return ( lower , upper )
| 0 |
contolling the x and y limits of plot in python
|
Gets the user enter max and min values of where the raster points should appear on the y - axis
|
cosqa-train-328
|
def values(self):
"""Gets the user enter max and min values of where the
raster points should appear on the y-axis
:returns: (float, float) -- (min, max) y-values to bound the raster plot by
"""
lower = float(self.lowerSpnbx.value())
upper = float(self.upperSpnbx.value())
return (lower, upper)
|
def sqlmany ( self , stringname , * args ) : if hasattr ( self , 'alchemist' ) : return getattr ( self . alchemist . many , stringname ) ( * args ) s = self . strings [ stringname ] return self . connection . cursor ( ) . executemany ( s , args )
| 0 |
python flask sqlalchemy query on a query
|
Wrapper for executing many SQL calls on my connection .
|
cosqa-train-329
|
def sqlmany(self, stringname, *args):
"""Wrapper for executing many SQL calls on my connection.
First arg is the name of a query, either a key in the
precompiled JSON or a method name in
``allegedb.alchemy.Alchemist``. Remaining arguments should be
tuples of argument sequences to be passed to the query.
"""
if hasattr(self, 'alchemist'):
return getattr(self.alchemist.many, stringname)(*args)
s = self.strings[stringname]
return self.connection.cursor().executemany(s, args)
|
def convolve_gaussian_2d ( image , gaussian_kernel_1d ) : result = scipy . ndimage . filters . correlate1d ( image , gaussian_kernel_1d , axis = 0 ) result = scipy . ndimage . filters . correlate1d ( result , gaussian_kernel_1d , axis = 1 ) return result
| 0 |
convolve image with kernel python stack overflow
|
Convolve 2d gaussian .
|
cosqa-train-330
|
def convolve_gaussian_2d(image, gaussian_kernel_1d):
"""Convolve 2d gaussian."""
result = scipy.ndimage.filters.correlate1d(
image, gaussian_kernel_1d, axis=0)
result = scipy.ndimage.filters.correlate1d(
result, gaussian_kernel_1d, axis=1)
return result
|
def render_template_string ( source , * * context ) : ctx = _app_ctx_stack . top ctx . app . update_template_context ( context ) return _render ( ctx . app . jinja_env . from_string ( source ) , context , ctx . app )
| 1 |
python flask template extend with context
|
Renders a template from the given template source string with the given context .
|
cosqa-train-331
|
def render_template_string(source, **context):
"""Renders a template from the given template source string
with the given context.
:param source: the sourcecode of the template to be
rendered
:param context: the variables that should be available in the
context of the template.
"""
ctx = _app_ctx_stack.top
ctx.app.update_template_context(context)
return _render(ctx.app.jinja_env.from_string(source),
context, ctx.app)
|
def asynchronous ( function , event ) : thread = Thread ( target = synchronous , args = ( function , event ) ) thread . daemon = True thread . start ( )
| 0 |
coroutine blocking functions python
|
Runs the function asynchronously taking care of exceptions .
|
cosqa-train-332
|
def asynchronous(function, event):
"""
Runs the function asynchronously taking care of exceptions.
"""
thread = Thread(target=synchronous, args=(function, event))
thread.daemon = True
thread.start()
|
def HttpResponse403 ( request , template = KEY_AUTH_403_TEMPLATE , content = KEY_AUTH_403_CONTENT , content_type = KEY_AUTH_403_CONTENT_TYPE ) : return AccessFailedResponse ( request , template , content , content_type , status = 403 )
| 0 |
python flask template request status 403
|
HTTP response for forbidden access ( status code 403 )
|
cosqa-train-333
|
def HttpResponse403(request, template=KEY_AUTH_403_TEMPLATE,
content=KEY_AUTH_403_CONTENT, content_type=KEY_AUTH_403_CONTENT_TYPE):
"""
HTTP response for forbidden access (status code 403)
"""
return AccessFailedResponse(request, template, content, content_type, status=403)
|
def similarity ( self , other ) : if self . magnitude == 0 or other . magnitude == 0 : return 0 return self . dot ( other ) / self . magnitude
| 0 |
cosine similarity python query
|
Calculates the cosine similarity between this vector and another vector .
|
cosqa-train-334
|
def similarity(self, other):
"""Calculates the cosine similarity between this vector and another
vector."""
if self.magnitude == 0 or other.magnitude == 0:
return 0
return self.dot(other) / self.magnitude
|
def default_static_path ( ) : fdir = os . path . dirname ( __file__ ) return os . path . abspath ( os . path . join ( fdir , '../assets/' ) )
| 0 |
python flask template static file
|
Return the path to the javascript bundle
|
cosqa-train-335
|
def default_static_path():
"""
Return the path to the javascript bundle
"""
fdir = os.path.dirname(__file__)
return os.path.abspath(os.path.join(fdir, '../assets/'))
|
def count_list ( the_list ) : count = the_list . count result = [ ( item , count ( item ) ) for item in set ( the_list ) ] result . sort ( ) return result
| 0 |
count frequency of unique values in list python
|
Generates a count of the number of times each unique item appears in a list
|
cosqa-train-336
|
def count_list(the_list):
"""
Generates a count of the number of times each unique item appears in a list
"""
count = the_list.count
result = [(item, count(item)) for item in set(the_list)]
result.sort()
return result
|
def round_to_float ( number , precision ) : rounded = Decimal ( str ( floor ( ( number + precision / 2 ) // precision ) ) ) * Decimal ( str ( precision ) ) return float ( rounded )
| 1 |
python float precision rounding
|
Round a float to a precision
|
cosqa-train-337
|
def round_to_float(number, precision):
"""Round a float to a precision"""
rounded = Decimal(str(floor((number + precision / 2) // precision))
) * Decimal(str(precision))
return float(rounded)
|
def _calc_overlap_count ( markers1 : dict , markers2 : dict , ) : overlaps = np . zeros ( ( len ( markers1 ) , len ( markers2 ) ) ) j = 0 for marker_group in markers1 : tmp = [ len ( markers2 [ i ] . intersection ( markers1 [ marker_group ] ) ) for i in markers2 . keys ( ) ] overlaps [ j , : ] = tmp j += 1 return overlaps
| 1 |
count number of overlaps in two python lists
|
Calculate overlap count between the values of two dictionaries
|
cosqa-train-338
|
def _calc_overlap_count(
markers1: dict,
markers2: dict,
):
"""Calculate overlap count between the values of two dictionaries
Note: dict values must be sets
"""
overlaps=np.zeros((len(markers1), len(markers2)))
j=0
for marker_group in markers1:
tmp = [len(markers2[i].intersection(markers1[marker_group])) for i in markers2.keys()]
overlaps[j,:] = tmp
j += 1
return overlaps
|
def intround ( value ) : return int ( decimal . Decimal . from_float ( value ) . to_integral_value ( decimal . ROUND_HALF_EVEN ) )
| 0 |
python float to int cast round
|
Given a float returns a rounded int . Should give the same result on both Py2 / 3
|
cosqa-train-339
|
def intround(value):
"""Given a float returns a rounded int. Should give the same result on
both Py2/3
"""
return int(decimal.Decimal.from_float(
value).to_integral_value(decimal.ROUND_HALF_EVEN))
|
def _datetime_to_date ( arg ) : _arg = parse ( arg ) if isinstance ( _arg , datetime . datetime ) : _arg = _arg . date ( ) return _arg
| 0 |
covert datetime date to datetime python
|
convert datetime / str to date : param arg : : return :
|
cosqa-train-340
|
def _datetime_to_date(arg):
"""
convert datetime/str to date
:param arg:
:return:
"""
_arg = parse(arg)
if isinstance(_arg, datetime.datetime):
_arg = _arg.date()
return _arg
|
def focusInEvent ( self , event ) : self . focus_changed . emit ( ) return super ( PageControlWidget , self ) . focusInEvent ( event )
| 0 |
python focusout comes before button
|
Reimplement Qt method to send focus change notification
|
cosqa-train-341
|
def focusInEvent(self, event):
"""Reimplement Qt method to send focus change notification"""
self.focus_changed.emit()
return super(PageControlWidget, self).focusInEvent(event)
|
def mkdir ( dir , enter ) : if not os . path . exists ( dir ) : os . makedirs ( dir )
| 0 |
creat new folder in python
|
Create directory with template for topic of the current environment
|
cosqa-train-342
|
def mkdir(dir, enter):
"""Create directory with template for topic of the current environment
"""
if not os.path.exists(dir):
os.makedirs(dir)
|
def _accumulate ( sequence , func ) : iterator = iter ( sequence ) total = next ( iterator ) yield total for element in iterator : total = func ( total , element ) yield total
| 1 |
python for comprehension sum
|
Python2 accumulate implementation taken from https : // docs . python . org / 3 / library / itertools . html#itertools . accumulate
|
cosqa-train-343
|
def _accumulate(sequence, func):
"""
Python2 accumulate implementation taken from
https://docs.python.org/3/library/itertools.html#itertools.accumulate
"""
iterator = iter(sequence)
total = next(iterator)
yield total
for element in iterator:
total = func(total, element)
yield total
|
def one_hot ( x , size , dtype = np . float32 ) : return np . array ( x [ ... , np . newaxis ] == np . arange ( size ) , dtype )
| 0 |
create 2d array python numpy one hot encoding
|
Make a n + 1 dim one - hot array from n dim int - categorical array .
|
cosqa-train-344
|
def one_hot(x, size, dtype=np.float32):
"""Make a n+1 dim one-hot array from n dim int-categorical array."""
return np.array(x[..., np.newaxis] == np.arange(size), dtype)
|
def iter_finds ( regex_obj , s ) : if isinstance ( regex_obj , str ) : for m in re . finditer ( regex_obj , s ) : yield m . group ( ) else : for m in regex_obj . finditer ( s ) : yield m . group ( )
| 0 |
python for each regex match in a string
|
Generate all matches found within a string for a regex and yield each match as a string
|
cosqa-train-345
|
def iter_finds(regex_obj, s):
"""Generate all matches found within a string for a regex and yield each match as a string"""
if isinstance(regex_obj, str):
for m in re.finditer(regex_obj, s):
yield m.group()
else:
for m in regex_obj.finditer(s):
yield m.group()
|
def a2s ( a ) : s = np . zeros ( ( 6 , ) , 'f' ) # make the a matrix for i in range ( 3 ) : s [ i ] = a [ i ] [ i ] s [ 3 ] = a [ 0 ] [ 1 ] s [ 4 ] = a [ 1 ] [ 2 ] s [ 5 ] = a [ 0 ] [ 2 ] return s
| 0 |
create 5 by 5 matrix in python
|
convert 3 3 a matrix to 6 element s list ( see Tauxe 1998 )
|
cosqa-train-346
|
def a2s(a):
"""
convert 3,3 a matrix to 6 element "s" list (see Tauxe 1998)
"""
s = np.zeros((6,), 'f') # make the a matrix
for i in range(3):
s[i] = a[i][i]
s[3] = a[0][1]
s[4] = a[1][2]
s[5] = a[0][2]
return s
|
def concat ( cls , iterables ) : def generator ( ) : for it in iterables : for element in it : yield element return cls ( generator ( ) )
| 0 |
python for multiple iterables
|
Similar to #itertools . chain . from_iterable () .
|
cosqa-train-347
|
def concat(cls, iterables):
"""
Similar to #itertools.chain.from_iterable().
"""
def generator():
for it in iterables:
for element in it:
yield element
return cls(generator())
|
def format_result ( input ) : items = list ( iteritems ( input ) ) return OrderedDict ( sorted ( items , key = lambda x : x [ 0 ] ) )
| 0 |
create a dict as ordered dict in python
|
From : http : // stackoverflow . com / questions / 13062300 / convert - a - dict - to - sorted - dict - in - python
|
cosqa-train-348
|
def format_result(input):
"""From: http://stackoverflow.com/questions/13062300/convert-a-dict-to-sorted-dict-in-python
"""
items = list(iteritems(input))
return OrderedDict(sorted(items, key=lambda x: x[0]))
|
def bulk_query ( self , query , * multiparams ) : with self . get_connection ( ) as conn : conn . bulk_query ( query , * multiparams )
| 0 |
python for sql server bulk load
|
Bulk insert or update .
|
cosqa-train-349
|
def bulk_query(self, query, *multiparams):
"""Bulk insert or update."""
with self.get_connection() as conn:
conn.bulk_query(query, *multiparams)
|
def Trie ( S ) : T = None for w in S : T = add ( T , w ) return T
| 0 |
create a trie with a words python
|
: param S : set of words : returns : trie containing all words from S : complexity : linear in total word sizes from S
|
cosqa-train-350
|
def Trie(S):
"""
:param S: set of words
:returns: trie containing all words from S
:complexity: linear in total word sizes from S
"""
T = None
for w in S:
T = add(T, w)
return T
|
def __set__ ( self , instance , value ) : self . map [ id ( instance ) ] = ( weakref . ref ( instance ) , value )
| 1 |
python foreign key to a foreign key
|
Set a related object for an instance .
|
cosqa-train-351
|
def __set__(self, instance, value):
""" Set a related object for an instance. """
self.map[id(instance)] = (weakref.ref(instance), value)
|
def recarray ( self ) : return numpy . rec . fromrecords ( self . records , names = self . names )
| 1 |
create an array in python without numpy
|
Returns data as : class : numpy . recarray .
|
cosqa-train-352
|
def recarray(self):
"""Returns data as :class:`numpy.recarray`."""
return numpy.rec.fromrecords(self.records, names=self.names)
|
def go_to_background ( ) : try : if os . fork ( ) : sys . exit ( ) except OSError as errmsg : LOGGER . error ( 'Fork failed: {0}' . format ( errmsg ) ) sys . exit ( 'Fork failed' )
| 0 |
python fork output incomplete
|
Daemonize the running process .
|
cosqa-train-353
|
def go_to_background():
""" Daemonize the running process. """
try:
if os.fork():
sys.exit()
except OSError as errmsg:
LOGGER.error('Fork failed: {0}'.format(errmsg))
sys.exit('Fork failed')
|
def generate_unique_host_id ( ) : host = "." . join ( reversed ( socket . gethostname ( ) . split ( "." ) ) ) pid = os . getpid ( ) return "%s.%d" % ( host , pid )
| 0 |
create automatic unique id in python
|
Generate a unique ID that is somewhat guaranteed to be unique among all instances running at the same time .
|
cosqa-train-354
|
def generate_unique_host_id():
"""Generate a unique ID, that is somewhat guaranteed to be unique among all
instances running at the same time."""
host = ".".join(reversed(socket.gethostname().split(".")))
pid = os.getpid()
return "%s.%d" % (host, pid)
|
def compress ( self , data_list ) : data = { } if data_list : return dict ( ( f . name , data_list [ i ] ) for i , f in enumerate ( self . form ) ) return data
| 0 |
python form data to dict
|
Return the cleaned_data of the form everything should already be valid
|
cosqa-train-355
|
def compress(self, data_list):
"""
Return the cleaned_data of the form, everything should already be valid
"""
data = {}
if data_list:
return dict(
(f.name, data_list[i]) for i, f in enumerate(self.form))
return data
|
def init_db ( ) : db . drop_all ( ) db . configure_mappers ( ) db . create_all ( ) db . session . commit ( )
| 0 |
create database postgres python sqlalchemy
|
Drops and re - creates the SQL schema
|
cosqa-train-356
|
def init_db():
"""
Drops and re-creates the SQL schema
"""
db.drop_all()
db.configure_mappers()
db.create_all()
db.session.commit()
|
def safe_format ( s , * * kwargs ) : return string . Formatter ( ) . vformat ( s , ( ) , defaultdict ( str , * * kwargs ) )
| 0 |
python format string pass varialbes
|
: type s str
|
cosqa-train-357
|
def safe_format(s, **kwargs):
"""
:type s str
"""
return string.Formatter().vformat(s, (), defaultdict(str, **kwargs))
|
def _init_unique_sets ( self ) : ks = dict ( ) for t in self . _unique_checks : key = t [ 0 ] ks [ key ] = set ( ) # empty set return ks
| 0 |
create dictionary python unique key
|
Initialise sets used for uniqueness checking .
|
cosqa-train-358
|
def _init_unique_sets(self):
"""Initialise sets used for uniqueness checking."""
ks = dict()
for t in self._unique_checks:
key = t[0]
ks[key] = set() # empty set
return ks
|
def straight_line_show ( title , length = 100 , linestyle = "=" , pad = 0 ) : print ( StrTemplate . straight_line ( title = title , length = length , linestyle = linestyle , pad = pad ) )
| 0 |
python formatting a long line
|
Print a formatted straight line .
|
cosqa-train-359
|
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 make_executable ( script_path ) : status = os . stat ( script_path ) os . chmod ( script_path , status . st_mode | stat . S_IEXEC )
| 0 |
create executable python script directly instead of chmod
|
Make script_path executable .
|
cosqa-train-360
|
def make_executable(script_path):
"""Make `script_path` executable.
:param script_path: The file to change
"""
status = os.stat(script_path)
os.chmod(script_path, status.st_mode | stat.S_IEXEC)
|
def make_html_code ( self , lines ) : line = code_header + '\n' for l in lines : line = line + html_quote ( l ) + '\n' return line + code_footer
| 0 |
python formatting code into 2 lines
|
convert a code sequence to HTML
|
cosqa-train-361
|
def make_html_code( self, lines ):
""" convert a code sequence to HTML """
line = code_header + '\n'
for l in lines:
line = line + html_quote( l ) + '\n'
return line + code_footer
|
def cross_product_matrix ( vec ) : return np . array ( [ [ 0 , - vec [ 2 ] , vec [ 1 ] ] , [ vec [ 2 ] , 0 , - vec [ 0 ] ] , [ - vec [ 1 ] , vec [ 0 ] , 0 ] ] )
| 0 |
create matrix from vectors python3
|
Returns a 3x3 cross - product matrix from a 3 - element vector .
|
cosqa-train-362
|
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 index_nearest ( value , array ) : a = ( array - value ) ** 2 return index ( a . min ( ) , a )
| 0 |
python found to nearest integer
|
expects a _n . array returns the global minimum of ( value - array ) ^2
|
cosqa-train-363
|
def index_nearest(value, array):
"""
expects a _n.array
returns the global minimum of (value-array)^2
"""
a = (array-value)**2
return index(a.min(), a)
|
def main ( args = sys . argv ) : parser = create_optparser ( args [ 0 ] ) return cli ( parser . parse_args ( args [ 1 : ] ) )
| 0 |
create parse args python script
|
main entry point for the jardiff CLI
|
cosqa-train-364
|
def main(args=sys.argv):
"""
main entry point for the jardiff CLI
"""
parser = create_optparser(args[0])
return cli(parser.parse_args(args[1:]))
|
def free ( self ) : if self . _ptr is None : return Gauged . array_free ( self . ptr ) FloatArray . ALLOCATIONS -= 1 self . _ptr = None
| 0 |
python free unused numpy array memory
|
Free the underlying C array
|
cosqa-train-365
|
def free(self):
"""Free the underlying C array"""
if self._ptr is None:
return
Gauged.array_free(self.ptr)
FloatArray.ALLOCATIONS -= 1
self._ptr = None
|
def from_points ( cls , list_of_lists ) : result = [ ] for l in list_of_lists : curve = [ ] for point in l : curve . append ( ( point . lon , point . lat ) ) result . append ( curve ) return Polygon ( result )
| 1 |
create polygon from lists of points python
|
Creates a * Polygon * instance out of a list of lists each sublist being populated with pyowm . utils . geo . Point instances : param list_of_lists : list : type : list_of_lists : iterable_of_polygons : returns : a * Polygon * instance
|
cosqa-train-366
|
def from_points(cls, list_of_lists):
"""
Creates a *Polygon* instance out of a list of lists, each sublist being populated with
`pyowm.utils.geo.Point` instances
:param list_of_lists: list
:type: list_of_lists: iterable_of_polygons
:returns: a *Polygon* instance
"""
result = []
for l in list_of_lists:
curve = []
for point in l:
curve.append((point.lon, point.lat))
result.append(curve)
return Polygon(result)
|
def connect ( ) : ftp_class = ftplib . FTP if not SSL else ftplib . FTP_TLS ftp = ftp_class ( timeout = TIMEOUT ) ftp . connect ( HOST , PORT ) ftp . login ( USER , PASSWORD ) if SSL : ftp . prot_p ( ) # secure data connection return ftp
| 0 |
python ftp login and get file
|
Connect to FTP server login and return an ftplib . FTP instance .
|
cosqa-train-367
|
def connect():
"""Connect to FTP server, login and return an ftplib.FTP instance."""
ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS
ftp = ftp_class(timeout=TIMEOUT)
ftp.connect(HOST, PORT)
ftp.login(USER, PASSWORD)
if SSL:
ftp.prot_p() # secure data connection
return ftp
|
def tmpfile ( prefix , direc ) : return tempfile . mktemp ( prefix = prefix , suffix = '.pdb' , dir = direc )
| 0 |
create temporary directory in python with a specific name
|
Returns the path to a newly created temporary file .
|
cosqa-train-368
|
def tmpfile(prefix, direc):
"""Returns the path to a newly created temporary file."""
return tempfile.mktemp(prefix=prefix, suffix='.pdb', dir=direc)
|
def connect ( host , port , username , password ) : # Instantiate ftplib client session = ftplib . FTP ( ) # Connect to host without auth session . connect ( host , port ) # Authenticate connection session . login ( username , password ) return session
| 0 |
python ftp server user name and password
|
Connect and login to an FTP server and return ftplib . FTP object .
|
cosqa-train-369
|
def connect(host, port, username, password):
"""Connect and login to an FTP server and return ftplib.FTP object."""
# Instantiate ftplib client
session = ftplib.FTP()
# Connect to host without auth
session.connect(host, port)
# Authenticate connection
session.login(username, password)
return session
|
def unique_list ( lst ) : uniq = [ ] for item in lst : if item not in uniq : uniq . append ( item ) return uniq
| 0 |
create unique list from a list in python
|
Make a list unique retaining order of initial appearance .
|
cosqa-train-370
|
def unique_list(lst):
"""Make a list unique, retaining order of initial appearance."""
uniq = []
for item in lst:
if item not in uniq:
uniq.append(item)
return uniq
|
def connect ( ) : ftp_class = ftplib . FTP if not SSL else ftplib . FTP_TLS ftp = ftp_class ( timeout = TIMEOUT ) ftp . connect ( HOST , PORT ) ftp . login ( USER , PASSWORD ) if SSL : ftp . prot_p ( ) # secure data connection return ftp
| 0 |
python ftps implicit ssl
|
Connect to FTP server login and return an ftplib . FTP instance .
|
cosqa-train-371
|
def connect():
"""Connect to FTP server, login and return an ftplib.FTP instance."""
ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS
ftp = ftp_class(timeout=TIMEOUT)
ftp.connect(HOST, PORT)
ftp.login(USER, PASSWORD)
if SSL:
ftp.prot_p() # secure data connection
return ftp
|
def exp_fit_fun ( x , a , tau , c ) : # pylint: disable=invalid-name return a * np . exp ( - x / tau ) + c
| 0 |
creating a function to fit exponential curve python
|
Function used to fit the exponential decay .
|
cosqa-train-372
|
def exp_fit_fun(x, a, tau, c):
"""Function used to fit the exponential decay."""
# pylint: disable=invalid-name
return a * np.exp(-x / tau) + c
|
def All ( sequence ) : return bool ( reduce ( lambda x , y : x and y , sequence , True ) )
| 0 |
python fucntion if every element is true
|
: param sequence : Any sequence whose elements can be evaluated as booleans . : returns : true if all elements of the sequence satisfy True and x .
|
cosqa-train-373
|
def All(sequence):
"""
:param sequence: Any sequence whose elements can be evaluated as booleans.
:returns: true if all elements of the sequence satisfy True and x.
"""
return bool(reduce(lambda x, y: x and y, sequence, True))
|
def zero_state ( self , batch_size ) : return torch . zeros ( batch_size , self . state_dim , dtype = torch . float32 )
| 0 |
creating a matrix in python tensorflow
|
Initial state of the network
|
cosqa-train-374
|
def zero_state(self, batch_size):
""" Initial state of the network """
return torch.zeros(batch_size, self.state_dim, dtype=torch.float32)
|
def _fullname ( o ) : return o . __module__ + "." + o . __name__ if o . __module__ else o . __name__
| 0 |
python fully qualified filename
|
Return the fully - qualified name of a function .
|
cosqa-train-375
|
def _fullname(o):
"""Return the fully-qualified name of a function."""
return o.__module__ + "." + o.__name__ if o.__module__ else o.__name__
|
def create_index ( config ) : filename = pathlib . Path ( config . cache_path ) / "index.json" index = { "version" : __version__ } with open ( filename , "w" ) as out : out . write ( json . dumps ( index , indent = 2 ) )
| 0 |
creating an index file in python
|
Create the root index .
|
cosqa-train-376
|
def create_index(config):
"""Create the root index."""
filename = pathlib.Path(config.cache_path) / "index.json"
index = {"version": __version__}
with open(filename, "w") as out:
out.write(json.dumps(index, indent=2))
|
def issorted ( list_ , op = operator . le ) : return all ( op ( list_ [ ix ] , list_ [ ix + 1 ] ) for ix in range ( len ( list_ ) - 1 ) )
| 0 |
python function states whether a list is sorted
|
Determines if a list is sorted
|
cosqa-train-377
|
def issorted(list_, op=operator.le):
"""
Determines if a list is sorted
Args:
list_ (list):
op (func): sorted operation (default=operator.le)
Returns:
bool : True if the list is sorted
"""
return all(op(list_[ix], list_[ix + 1]) for ix in range(len(list_) - 1))
|
def is_valid ( number ) : n = str ( number ) if not n . isdigit ( ) : return False return int ( n [ - 1 ] ) == get_check_digit ( n [ : - 1 ] )
| 0 |
credit card number check digit python
|
determines whether the card number is valid .
|
cosqa-train-378
|
def is_valid(number):
"""determines whether the card number is valid."""
n = str(number)
if not n.isdigit():
return False
return int(n[-1]) == get_check_digit(n[:-1])
|
def us2mc ( string ) : return re . sub ( r'_([a-z])' , lambda m : ( m . group ( 1 ) . upper ( ) ) , string )
| 0 |
python function stating with underscore
|
Transform an underscore_case string to a mixedCase string
|
cosqa-train-379
|
def us2mc(string):
"""Transform an underscore_case string to a mixedCase string"""
return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), string)
|
def csv2yaml ( in_file , out_file = None ) : if out_file is None : out_file = "%s.yaml" % os . path . splitext ( in_file ) [ 0 ] barcode_ids = _generate_barcode_ids ( _read_input_csv ( in_file ) ) lanes = _organize_lanes ( _read_input_csv ( in_file ) , barcode_ids ) with open ( out_file , "w" ) as out_handle : out_handle . write ( yaml . safe_dump ( lanes , default_flow_style = False ) ) return out_file
| 0 |
csv to yaml python
|
Convert a CSV SampleSheet to YAML run_info format .
|
cosqa-train-380
|
def csv2yaml(in_file, out_file=None):
"""Convert a CSV SampleSheet to YAML run_info format.
"""
if out_file is None:
out_file = "%s.yaml" % os.path.splitext(in_file)[0]
barcode_ids = _generate_barcode_ids(_read_input_csv(in_file))
lanes = _organize_lanes(_read_input_csv(in_file), barcode_ids)
with open(out_file, "w") as out_handle:
out_handle.write(yaml.safe_dump(lanes, default_flow_style=False))
return out_file
|
def get_average_length_of_string ( strings ) : if not strings : return 0 return sum ( len ( word ) for word in strings ) / len ( strings )
| 0 |
python function that returns the average of each length of words in a string
|
Computes average length of words
|
cosqa-train-381
|
def get_average_length_of_string(strings):
"""Computes average length of words
:param strings: list of words
:return: Average length of word on list
"""
if not strings:
return 0
return sum(len(word) for word in strings) / len(strings)
|
def cumsum ( inlist ) : newlist = copy . deepcopy ( inlist ) for i in range ( 1 , len ( newlist ) ) : newlist [ i ] = newlist [ i ] + newlist [ i - 1 ] return newlist
| 1 |
cumulative sum of list python
|
Returns a list consisting of the cumulative sum of the items in the passed list .
|
cosqa-train-382
|
def cumsum(inlist):
"""
Returns a list consisting of the cumulative sum of the items in the
passed list.
Usage: lcumsum(inlist)
"""
newlist = copy.deepcopy(inlist)
for i in range(1, len(newlist)):
newlist[i] = newlist[i] + newlist[i - 1]
return newlist
|
def good ( txt ) : print ( "%s# %s%s%s" % ( PR_GOOD_CC , get_time_stamp ( ) , txt , PR_NC ) ) sys . stdout . flush ( )
| 0 |
python function to bold the print statemetn
|
Print emphasized good the given txt message
|
cosqa-train-383
|
def good(txt):
"""Print, emphasized 'good', the given 'txt' message"""
print("%s# %s%s%s" % (PR_GOOD_CC, get_time_stamp(), txt, PR_NC))
sys.stdout.flush()
|
def move_to ( self , ypos , xpos ) : # the screen's co-ordinates are 1 based, but the command is 0 based xpos -= 1 ypos -= 1 self . exec_command ( "MoveCursor({0}, {1})" . format ( ypos , xpos ) . encode ( "ascii" ) )
| 0 |
cursor movement in game using python
|
move the cursor to the given co - ordinates . Co - ordinates are 1 based as listed in the status area of the terminal .
|
cosqa-train-384
|
def move_to(self, ypos, xpos):
"""
move the cursor to the given co-ordinates. Co-ordinates are 1
based, as listed in the status area of the terminal.
"""
# the screen's co-ordinates are 1 based, but the command is 0 based
xpos -= 1
ypos -= 1
self.exec_command("MoveCursor({0}, {1})".format(ypos, xpos).encode("ascii"))
|
def dict_from_object ( obj : object ) : # If object is a dict instance, no need to convert. return ( obj if isinstance ( obj , dict ) else { attr : getattr ( obj , attr ) for attr in dir ( obj ) if not attr . startswith ( '_' ) } )
| 0 |
python function to get object attributes
|
Convert a object into dictionary with all of its readable attributes .
|
cosqa-train-385
|
def dict_from_object(obj: object):
"""Convert a object into dictionary with all of its readable attributes."""
# If object is a dict instance, no need to convert.
return (obj if isinstance(obj, dict)
else {attr: getattr(obj, attr)
for attr in dir(obj) if not attr.startswith('_')})
|
def ensure_hbounds ( self ) : self . cursor . x = min ( max ( 0 , self . cursor . x ) , self . columns - 1 )
| 1 |
cursor position graphics python
|
Ensure the cursor is within horizontal screen bounds .
|
cosqa-train-386
|
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 strip_spaces ( s ) : return u" " . join ( [ c for c in s . split ( u' ' ) if c ] )
| 0 |
python function to remove spaces in a string
|
Strip excess spaces from a string
|
cosqa-train-387
|
def strip_spaces(s):
""" Strip excess spaces from a string """
return u" ".join([c for c in s.split(u' ') if c])
|
def scatter ( self , * args , * * kwargs ) : cls = _make_class ( ScatterVisual , _default_marker = kwargs . pop ( 'marker' , None ) , ) return self . _add_item ( cls , * args , * * kwargs )
| 0 |
custom scatter plot marker with png python
|
Add a scatter plot .
|
cosqa-train-388
|
def scatter(self, *args, **kwargs):
"""Add a scatter plot."""
cls = _make_class(ScatterVisual,
_default_marker=kwargs.pop('marker', None),
)
return self._add_item(cls, *args, **kwargs)
|
def download_file_from_bucket ( self , bucket , file_path , key ) : with open ( file_path , 'wb' ) as data : self . __s3 . download_fileobj ( bucket , key , data ) return file_path
| 0 |
python function to upload file to s3
|
Download file from S3 Bucket
|
cosqa-train-389
|
def download_file_from_bucket(self, bucket, file_path, key):
""" Download file from S3 Bucket """
with open(file_path, 'wb') as data:
self.__s3.download_fileobj(bucket, key, data)
return file_path
|
def imdecode ( image_path ) : import os assert os . path . exists ( image_path ) , image_path + ' not found' im = cv2 . imread ( image_path ) return im
| 0 |
cv2 python load image
|
Return BGR image read by opencv
|
cosqa-train-390
|
def imdecode(image_path):
"""Return BGR image read by opencv"""
import os
assert os.path.exists(image_path), image_path + ' not found'
im = cv2.imread(image_path)
return im
|
def ex ( self , cmd ) : with self . builtin_trap : exec cmd in self . user_global_ns , self . user_ns
| 0 |
python function use variable defined in outer scope
|
Execute a normal python statement in user namespace .
|
cosqa-train-391
|
def ex(self, cmd):
"""Execute a normal python statement in user namespace."""
with self.builtin_trap:
exec cmd in self.user_global_ns, self.user_ns
|
def isbinary ( * args ) : return all ( map ( lambda c : isnumber ( c ) or isbool ( c ) , args ) )
| 1 |
cython python2 bool function
|
Checks if value can be part of binary / bitwise operations .
|
cosqa-train-392
|
def isbinary(*args):
"""Checks if value can be part of binary/bitwise operations."""
return all(map(lambda c: isnumber(c) or isbool(c), args))
|
def split ( s ) : l = [ _split ( x ) for x in _SPLIT_RE . split ( s ) ] return [ item for sublist in l for item in sublist ]
| 0 |
python function used to explode a string into a list of strings
|
Uses dynamic programming to infer the location of spaces in a string without spaces .
|
cosqa-train-393
|
def split(s):
"""Uses dynamic programming to infer the location of spaces in a string without spaces."""
l = [_split(x) for x in _SPLIT_RE.split(s)]
return [item for sublist in l for item in sublist]
|
def dt2jd ( dt ) : a = ( 14 - dt . month ) // 12 y = dt . year + 4800 - a m = dt . month + 12 * a - 3 return dt . day + ( ( 153 * m + 2 ) // 5 ) + 365 * y + y // 4 - y // 100 + y // 400 - 32045
| 0 |
date to jday python
|
Convert datetime to julian date
|
cosqa-train-394
|
def dt2jd(dt):
"""Convert datetime to julian date
"""
a = (14 - dt.month)//12
y = dt.year + 4800 - a
m = dt.month + 12*a - 3
return dt.day + ((153*m + 2)//5) + 365*y + y//4 - y//100 + y//400 - 32045
|
def smooth_gaussian ( image , sigma = 1 ) : return scipy . ndimage . filters . gaussian_filter ( image , sigma = sigma , mode = "nearest" )
| 0 |
python gaussian filter blur image
|
Returns Gaussian smoothed image .
|
cosqa-train-395
|
def smooth_gaussian(image, sigma=1):
"""Returns Gaussian smoothed image.
:param image: numpy array or :class:`jicimagelib.image.Image`
:param sigma: standard deviation
:returns: :class:`jicimagelib.image.Image`
"""
return scipy.ndimage.filters.gaussian_filter(image, sigma=sigma, mode="nearest")
|
def _time_to_json ( value ) : if isinstance ( value , datetime . time ) : value = value . isoformat ( ) return value
| 0 |
datetime to json in python
|
Coerce value to an JSON - compatible representation .
|
cosqa-train-396
|
def _time_to_json(value):
"""Coerce 'value' to an JSON-compatible representation."""
if isinstance(value, datetime.time):
value = value.isoformat()
return value
|
def EvalGaussianPdf ( x , mu , sigma ) : return scipy . stats . norm . pdf ( x , mu , sigma )
| 0 |
python gaussian pdf plot
|
Computes the unnormalized PDF of the normal distribution .
|
cosqa-train-397
|
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 convert_timestamp ( timestamp ) : datetime = dt . datetime . utcfromtimestamp ( timestamp / 1000. ) return np . datetime64 ( datetime . replace ( tzinfo = None ) )
| 0 |
datetime to timestamp ironpython
|
Converts bokehJS timestamp to datetime64 .
|
cosqa-train-398
|
def convert_timestamp(timestamp):
"""
Converts bokehJS timestamp to datetime64.
"""
datetime = dt.datetime.utcfromtimestamp(timestamp/1000.)
return np.datetime64(datetime.replace(tzinfo=None))
|
def _make_cmd_list ( cmd_list ) : cmd = '' for i in cmd_list : cmd = cmd + '"' + i + '",' cmd = cmd [ : - 1 ] return cmd
| 0 |
python generate a string based on a list
|
Helper function to easily create the proper json formated string from a list of strs : param cmd_list : list of strings : return : str json formatted
|
cosqa-train-399
|
def _make_cmd_list(cmd_list):
"""
Helper function to easily create the proper json formated string from a list of strs
:param cmd_list: list of strings
:return: str json formatted
"""
cmd = ''
for i in cmd_list:
cmd = cmd + '"' + i + '",'
cmd = cmd[:-1]
return cmd
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.