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 Output ( self ) : self . Open ( ) self . Header ( ) self . Body ( ) self . Footer ( )
| 0 |
does python have a top of page
|
Output all sections of the page .
|
cosqa-train-15300
|
def Output(self):
"""Output all sections of the page."""
self.Open()
self.Header()
self.Body()
self.Footer()
|
def get_by ( self , name ) : return next ( ( item for item in self if item . name == name ) , None )
| 1 |
python get item in list by name
|
get element by name
|
cosqa-train-15301
|
def get_by(self, name):
"""get element by name"""
return next((item for item in self if item.name == name), None)
|
def graph_from_dot_file ( path ) : fd = file ( path , 'rb' ) data = fd . read ( ) fd . close ( ) return graph_from_dot_data ( data )
| 0 |
dot file parser python
|
Load graph as defined by a DOT file . The file is assumed to be in DOT format . It will be loaded parsed and a Dot class will be returned representing the graph .
|
cosqa-train-15302
|
def graph_from_dot_file(path):
"""Load graph as defined by a DOT file.
The file is assumed to be in DOT format. It will
be loaded, parsed and a Dot class will be returned,
representing the graph.
"""
fd = file(path, 'rb')
data = fd.read()
fd.close()
return graph_from_dot_data(data)
|
def _lookup_enum_in_ns ( namespace , value ) : for attribute in dir ( namespace ) : if getattr ( namespace , attribute ) == value : return attribute
| 0 |
python get item in namespace
|
Return the attribute of namespace corresponding to value .
|
cosqa-train-15303
|
def _lookup_enum_in_ns(namespace, value):
"""Return the attribute of namespace corresponding to value."""
for attribute in dir(namespace):
if getattr(namespace, attribute) == value:
return attribute
|
def dot_v2 ( vec1 , vec2 ) : return vec1 . x * vec2 . x + vec1 . y * vec2 . y
| 0 |
dot product of 3d vector python
|
Return the dot product of two vectors
|
cosqa-train-15304
|
def dot_v2(vec1, vec2):
"""Return the dot product of two vectors"""
return vec1.x * vec2.x + vec1.y * vec2.y
|
def apply_kwargs ( func , * * kwargs ) : new_kwargs = { } params = signature ( func ) . parameters for param_name in params . keys ( ) : if param_name in kwargs : new_kwargs [ param_name ] = kwargs [ param_name ] return func ( * * new_kwargs )
| 1 |
python get kwargs of a function
|
Call * func * with kwargs but only those kwargs that it accepts .
|
cosqa-train-15305
|
def apply_kwargs(func, **kwargs):
"""Call *func* with kwargs, but only those kwargs that it accepts.
"""
new_kwargs = {}
params = signature(func).parameters
for param_name in params.keys():
if param_name in kwargs:
new_kwargs[param_name] = kwargs[param_name]
return func(**new_kwargs)
|
def _intermediary_to_dot ( tables , relationships ) : t = '\n' . join ( t . to_dot ( ) for t in tables ) r = '\n' . join ( r . to_dot ( ) for r in relationships ) return '{}\n{}\n{}\n}}' . format ( GRAPH_BEGINNING , t , r )
| 1 |
dot structure for python
|
Returns the dot source representing the database in a string .
|
cosqa-train-15306
|
def _intermediary_to_dot(tables, relationships):
""" Returns the dot source representing the database in a string. """
t = '\n'.join(t.to_dot() for t in tables)
r = '\n'.join(r.to_dot() for r in relationships)
return '{}\n{}\n{}\n}}'.format(GRAPH_BEGINNING, t, r)
|
def prevmonday ( num ) : today = get_today ( ) lastmonday = today - timedelta ( days = today . weekday ( ) , weeks = num ) return lastmonday
| 0 |
python get last monday date
|
Return unix SECOND timestamp of num mondays ago
|
cosqa-train-15307
|
def prevmonday(num):
"""
Return unix SECOND timestamp of "num" mondays ago
"""
today = get_today()
lastmonday = today - timedelta(days=today.weekday(), weeks=num)
return lastmonday
|
def draw ( self , mode = "triangles" ) : gl . glDepthMask ( 0 ) Collection . draw ( self , mode ) gl . glDepthMask ( 1 )
| 0 |
draw circle in python open gl
|
Draw collection
|
cosqa-train-15308
|
def draw(self, mode="triangles"):
""" Draw collection """
gl.glDepthMask(0)
Collection.draw(self, mode)
gl.glDepthMask(1)
|
def tail ( self , n = 10 ) : with cython_context ( ) : return SArray ( _proxy = self . __proxy__ . tail ( n ) )
| 0 |
python get last n rows
|
Get an SArray that contains the last n elements in the SArray .
|
cosqa-train-15309
|
def tail(self, n=10):
"""
Get an SArray that contains the last n elements in the SArray.
Parameters
----------
n : int
The number of elements to fetch
Returns
-------
out : SArray
A new SArray which contains the last n rows of the current SArray.
"""
with cython_context():
return SArray(_proxy=self.__proxy__.tail(n))
|
def purge_duplicates ( list_in ) : _list = [ ] for item in list_in : if item not in _list : _list . append ( item ) return _list
| 0 |
duplicate a list in python basic
|
Remove duplicates from list while preserving order .
|
cosqa-train-15310
|
def purge_duplicates(list_in):
"""Remove duplicates from list while preserving order.
Parameters
----------
list_in: Iterable
Returns
-------
list
List of first occurences in order
"""
_list = []
for item in list_in:
if item not in _list:
_list.append(item)
return _list
|
def get_table_names ( connection ) : cursor = connection . cursor ( ) cursor . execute ( "SELECT name FROM sqlite_master WHERE type == 'table'" ) return [ name for ( name , ) in cursor ]
| 1 |
python get list of tables in database
|
Return a list of the table names in the database .
|
cosqa-train-15311
|
def get_table_names(connection):
"""
Return a list of the table names in the database.
"""
cursor = connection.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type == 'table'")
return [name for (name,) in cursor]
|
def _histplot_bins ( column , bins = 100 ) : col_min = np . min ( column ) col_max = np . max ( column ) return range ( col_min , col_max + 2 , max ( ( col_max - col_min ) // bins , 1 ) )
| 0 |
dynamic bins histogram python
|
Helper to get bins for histplot .
|
cosqa-train-15312
|
def _histplot_bins(column, bins=100):
"""Helper to get bins for histplot."""
col_min = np.min(column)
col_max = np.max(column)
return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1))
|
def get_language ( self ) : return get_language_parameter ( self . request , self . query_language_key , default = self . get_default_language ( object = object ) )
| 1 |
python get local language
|
Get the language parameter from the current request .
|
cosqa-train-15313
|
def get_language(self):
"""
Get the language parameter from the current request.
"""
return get_language_parameter(self.request, self.query_language_key, default=self.get_default_language(object=object))
|
def are_equal_xml ( a_xml , b_xml ) : a_dom = xml . dom . minidom . parseString ( a_xml ) b_dom = xml . dom . minidom . parseString ( b_xml ) return are_equal_elements ( a_dom . documentElement , b_dom . documentElement )
| 0 |
easy way to compare two xml python
|
Normalize and compare XML documents for equality . The document may or may not be a DataONE type .
|
cosqa-train-15314
|
def are_equal_xml(a_xml, b_xml):
"""Normalize and compare XML documents for equality. The document may or may not be
a DataONE type.
Args:
a_xml: str
b_xml: str
XML documents to compare for equality.
Returns:
bool: ``True`` if the XML documents are semantically equivalent.
"""
a_dom = xml.dom.minidom.parseString(a_xml)
b_dom = xml.dom.minidom.parseString(b_xml)
return are_equal_elements(a_dom.documentElement, b_dom.documentElement)
|
def values ( self ) : lower = float ( self . lowerSpnbx . value ( ) ) upper = float ( self . upperSpnbx . value ( ) ) return ( lower , upper )
| 1 |
python get location of min/max
|
Gets the user enter max and min values of where the raster points should appear on the y - axis
|
cosqa-train-15315
|
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 fetch ( table , cols = "*" , where = ( ) , group = "" , order = ( ) , limit = ( ) , * * kwargs ) : return select ( table , cols , where , group , order , limit , * * kwargs ) . fetchall ( )
| 0 |
efficent way to fetch many records from database in python
|
Convenience wrapper for database SELECT and fetch all .
|
cosqa-train-15316
|
def fetch(table, cols="*", where=(), group="", order=(), limit=(), **kwargs):
"""Convenience wrapper for database SELECT and fetch all."""
return select(table, cols, where, group, order, limit, **kwargs).fetchall()
|
def get_max ( qs , field ) : max_field = '%s__max' % field num = qs . aggregate ( Max ( field ) ) [ max_field ] return num if num else 0
| 1 |
python get max value from table
|
get max for queryset .
|
cosqa-train-15317
|
def get_max(qs, field):
"""
get max for queryset.
qs: queryset
field: The field name to max.
"""
max_field = '%s__max' % field
num = qs.aggregate(Max(field))[max_field]
return num if num else 0
|
def deleteAll ( self ) : for core in self . endpoints : self . _send_solr_command ( self . endpoints [ core ] , "{\"delete\": { \"query\" : \"*:*\"}}" )
| 0 |
elasticsearch dsl python bulk delete
|
Deletes whole Solr index . Use with care .
|
cosqa-train-15318
|
def deleteAll(self):
"""
Deletes whole Solr index. Use with care.
"""
for core in self.endpoints:
self._send_solr_command(self.endpoints[core], "{\"delete\": { \"query\" : \"*:*\"}}")
|
def get_free_memory_win ( ) : stat = MEMORYSTATUSEX ( ) ctypes . windll . kernel32 . GlobalMemoryStatusEx ( ctypes . byref ( stat ) ) return int ( stat . ullAvailPhys / 1024 / 1024 )
| 0 |
python get memory used
|
Return current free memory on the machine for windows .
|
cosqa-train-15319
|
def get_free_memory_win():
"""Return current free memory on the machine for windows.
Warning : this script is really not robust
Return in MB unit
"""
stat = MEMORYSTATUSEX()
ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))
return int(stat.ullAvailPhys / 1024 / 1024)
|
def matrixTimesVector ( MM , aa ) : bb = np . zeros ( 3 , np . float ) for ii in range ( 3 ) : bb [ ii ] = np . sum ( MM [ ii , : ] * aa ) return bb
| 1 |
element wise multiplication matrix and vector python
|
cosqa-train-15320
|
def matrixTimesVector(MM, aa):
"""
:param MM: A matrix of size 3x3
:param aa: A vector of size 3
:return: A vector of size 3 which is the product of the matrix by the vector
"""
bb = np.zeros(3, np.float)
for ii in range(3):
bb[ii] = np.sum(MM[ii, :] * aa)
return bb
|
|
def get_month_start_end_day ( ) : t = date . today ( ) n = mdays [ t . month ] return ( date ( t . year , t . month , 1 ) , date ( t . year , t . month , n ) )
| 1 |
python get month start and end date by month and year
|
Get the month start date a nd end date
|
cosqa-train-15321
|
def get_month_start_end_day():
"""
Get the month start date a nd end date
"""
t = date.today()
n = mdays[t.month]
return (date(t.year, t.month, 1), date(t.year, t.month, n))
|
def remove_bad ( string ) : remove = [ ':' , ',' , '(' , ')' , ' ' , '|' , ';' , '\'' ] for c in remove : string = string . replace ( c , '_' ) return string
| 0 |
eliminate space between strings python
|
remove problem characters from string
|
cosqa-train-15322
|
def remove_bad(string):
"""
remove problem characters from string
"""
remove = [':', ',', '(', ')', ' ', '|', ';', '\'']
for c in remove:
string = string.replace(c, '_')
return string
|
def get_last_modified_timestamp ( self ) : cmd = "find . -print0 | xargs -0 stat -f '%T@ %p' | sort -n | tail -1 | cut -f2- -d' '" ps = subprocess . Popen ( cmd , shell = True , stdout = subprocess . PIPE , stderr = subprocess . STDOUT ) output = ps . communicate ( ) [ 0 ] print output
| 0 |
python get most recently modified file
|
Looks at the files in a git root directory and grabs the last modified timestamp
|
cosqa-train-15323
|
def get_last_modified_timestamp(self):
"""
Looks at the files in a git root directory and grabs the last modified timestamp
"""
cmd = "find . -print0 | xargs -0 stat -f '%T@ %p' | sort -n | tail -1 | cut -f2- -d' '"
ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output = ps.communicate()[0]
print output
|
def validate_email ( email ) : from django . core . validators import validate_email from django . core . exceptions import ValidationError try : validate_email ( email ) return True except ValidationError : return False
| 1 |
email validation in python with sql
|
Validates an email address Source : Himanshu Shankar ( https : // github . com / iamhssingh ) Parameters ---------- email : str
|
cosqa-train-15324
|
def validate_email(email):
"""
Validates an email address
Source: Himanshu Shankar (https://github.com/iamhssingh)
Parameters
----------
email: str
Returns
-------
bool
"""
from django.core.validators import validate_email
from django.core.exceptions import ValidationError
try:
validate_email(email)
return True
except ValidationError:
return False
|
def get_model ( name ) : model = MODELS . get ( name . lower ( ) , None ) assert model , "Could not locate model by name '%s'" % name return model
| 0 |
python get name of model
|
Convert a model s verbose name to the model class . This allows us to use the models verbose name in steps .
|
cosqa-train-15325
|
def get_model(name):
"""
Convert a model's verbose name to the model class. This allows us to
use the models verbose name in steps.
"""
model = MODELS.get(name.lower(), None)
assert model, "Could not locate model by name '%s'" % name
return model
|
def read_string_from_file ( path , encoding = "utf8" ) : with codecs . open ( path , "rb" , encoding = encoding ) as f : value = f . read ( ) return value
| 1 |
encoding of a python file
|
Read entire contents of file into a string .
|
cosqa-train-15326
|
def read_string_from_file(path, encoding="utf8"):
"""
Read entire contents of file into a string.
"""
with codecs.open(path, "rb", encoding=encoding) as f:
value = f.read()
return value
|
def current_timestamp ( ) : now = datetime . utcnow ( ) timestamp = now . isoformat ( ) [ 0 : 19 ] + 'Z' debug ( "generated timestamp: {now}" . format ( now = timestamp ) ) return timestamp
| 1 |
python get now time local isoformat
|
Returns current time as ISO8601 formatted string in the Zulu TZ
|
cosqa-train-15327
|
def current_timestamp():
"""Returns current time as ISO8601 formatted string in the Zulu TZ"""
now = datetime.utcnow()
timestamp = now.isoformat()[0:19] + 'Z'
debug("generated timestamp: {now}".format(now=timestamp))
return timestamp
|
def session_to_epoch ( timestamp ) : utc_timetuple = datetime . strptime ( timestamp , SYNERGY_SESSION_PATTERN ) . replace ( tzinfo = None ) . utctimetuple ( ) return calendar . timegm ( utc_timetuple )
| 1 |
epoch to timezone python
|
converts Synergy Timestamp for session to UTC zone seconds since epoch
|
cosqa-train-15328
|
def session_to_epoch(timestamp):
""" converts Synergy Timestamp for session to UTC zone seconds since epoch """
utc_timetuple = datetime.strptime(timestamp, SYNERGY_SESSION_PATTERN).replace(tzinfo=None).utctimetuple()
return calendar.timegm(utc_timetuple)
|
def dimensions ( self ) : size = self . pdf . getPage ( 0 ) . mediaBox return { 'w' : float ( size [ 2 ] ) , 'h' : float ( size [ 3 ] ) }
| 0 |
python get pdf page size
|
Get width and height of a PDF
|
cosqa-train-15329
|
def dimensions(self):
"""Get width and height of a PDF"""
size = self.pdf.getPage(0).mediaBox
return {'w': float(size[2]), 'h': float(size[3])}
|
def debug_src ( src , pm = False , globs = None ) : testsrc = script_from_examples ( src ) debug_script ( testsrc , pm , globs )
| 0 |
equivalent of python docstrings for js
|
Debug a single doctest docstring in argument src
|
cosqa-train-15330
|
def debug_src(src, pm=False, globs=None):
"""Debug a single doctest docstring, in argument `src`'"""
testsrc = script_from_examples(src)
debug_script(testsrc, pm, globs)
|
def hex_to_rgb ( h ) : h = h . lstrip ( '#' ) return tuple ( int ( h [ i : i + 2 ] , 16 ) / 255. for i in ( 0 , 2 , 4 ) )
| 0 |
python get rgb values from hex value
|
Returns 0 to 1 rgb from a hex list or tuple
|
cosqa-train-15331
|
def hex_to_rgb(h):
""" Returns 0 to 1 rgb from a hex list or tuple """
h = h.lstrip('#')
return tuple(int(h[i:i+2], 16)/255. for i in (0, 2 ,4))
|
def _escape ( s ) : e = s e = e . replace ( '\\' , '\\\\' ) e = e . replace ( '\n' , '\\n' ) e = e . replace ( '\r' , '\\r' ) e = e . replace ( "'" , "\\'" ) e = e . replace ( '"' , '\\"' ) return e
| 1 |
escaping delimiters in python mysql query
|
Helper method that escapes parameters to a SQL query .
|
cosqa-train-15332
|
def _escape(s):
""" Helper method that escapes parameters to a SQL query. """
e = s
e = e.replace('\\', '\\\\')
e = e.replace('\n', '\\n')
e = e.replace('\r', '\\r')
e = e.replace("'", "\\'")
e = e.replace('"', '\\"')
return e
|
def remove_ext ( fname ) : bn = os . path . basename ( fname ) return os . path . splitext ( bn ) [ 0 ]
| 0 |
python get rid off file extend name
|
Removes the extension from a filename
|
cosqa-train-15333
|
def remove_ext(fname):
"""Removes the extension from a filename
"""
bn = os.path.basename(fname)
return os.path.splitext(bn)[0]
|
def _cdf ( self , xloc , dist , base , cache ) : return evaluation . evaluate_forward ( dist , base ** xloc , cache = cache )
| 0 |
evaluate evaluate cdf for uniform distribution in python
|
Cumulative distribution function .
|
cosqa-train-15334
|
def _cdf(self, xloc, dist, base, cache):
"""Cumulative distribution function."""
return evaluation.evaluate_forward(dist, base**xloc, cache=cache)
|
def getdefaultencoding ( ) : enc = get_stream_enc ( sys . stdin ) if not enc or enc == 'ascii' : try : # There are reports of getpreferredencoding raising errors # in some cases, which may well be fixed, but let's be conservative here. enc = locale . getpreferredencoding ( ) except Exception : pass return enc or sys . getdefaultencoding ( )
| 0 |
python get shell encoding
|
Return IPython s guess for the default encoding for bytes as text .
|
cosqa-train-15335
|
def getdefaultencoding():
"""Return IPython's guess for the default encoding for bytes as text.
Asks for stdin.encoding first, to match the calling Terminal, but that
is often None for subprocesses. Fall back on locale.getpreferredencoding()
which should be a sensible platform default (that respects LANG environment),
and finally to sys.getdefaultencoding() which is the most conservative option,
and usually ASCII.
"""
enc = get_stream_enc(sys.stdin)
if not enc or enc=='ascii':
try:
# There are reports of getpreferredencoding raising errors
# in some cases, which may well be fixed, but let's be conservative here.
enc = locale.getpreferredencoding()
except Exception:
pass
return enc or sys.getdefaultencoding()
|
def equal ( obj1 , obj2 ) : Comparable . log ( obj1 , obj2 , '==' ) equality = obj1 . equality ( obj2 ) Comparable . log ( obj1 , obj2 , '==' , result = equality ) return equality
| 1 |
evalulate equivalency of 2 objects python
|
Calculate equality between two ( Comparable ) objects .
|
cosqa-train-15336
|
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 get_size ( objects ) : res = 0 for o in objects : try : res += _getsizeof ( o ) except AttributeError : print ( "IGNORING: type=%s; o=%s" % ( str ( type ( o ) ) , str ( o ) ) ) return res
| 0 |
python get size of all objects
|
Compute the total size of all elements in objects .
|
cosqa-train-15337
|
def get_size(objects):
"""Compute the total size of all elements in objects."""
res = 0
for o in objects:
try:
res += _getsizeof(o)
except AttributeError:
print("IGNORING: type=%s; o=%s" % (str(type(o)), str(o)))
return res
|
def run ( self ) : self . signal_init ( ) self . listen_init ( ) self . logger . info ( 'starting' ) self . loop . start ( )
| 0 |
event loop already running in python
|
Run the event loop .
|
cosqa-train-15338
|
def run(self):
"""Run the event loop."""
self.signal_init()
self.listen_init()
self.logger.info('starting')
self.loop.start()
|
def monthly ( date = datetime . date . today ( ) ) : return datetime . date ( date . year , date . month , 1 )
| 0 |
python get the first and last day of month given year
|
Take a date object and return the first day of the month .
|
cosqa-train-15339
|
def monthly(date=datetime.date.today()):
"""
Take a date object and return the first day of the month.
"""
return datetime.date(date.year, date.month, 1)
|
def previous_quarter ( d ) : from django_toolkit . datetime_util import quarter as datetime_quarter return quarter ( ( datetime_quarter ( datetime ( d . year , d . month , d . day ) ) [ 0 ] + timedelta ( days = - 1 ) ) . date ( ) )
| 0 |
exact quarter from the date column python
|
Retrieve the previous quarter for dt
|
cosqa-train-15340
|
def previous_quarter(d):
"""
Retrieve the previous quarter for dt
"""
from django_toolkit.datetime_util import quarter as datetime_quarter
return quarter( (datetime_quarter(datetime(d.year, d.month, d.day))[0] + timedelta(days=-1)).date() )
|
def findfirst ( f , coll ) : result = list ( dropwhile ( f , coll ) ) return result [ 0 ] if result else None
| 0 |
python get the first object in a list
|
Return first occurrence matching f otherwise None
|
cosqa-train-15341
|
def findfirst(f, coll):
"""Return first occurrence matching f, otherwise None"""
result = list(dropwhile(f, coll))
return result[0] if result else None
|
def isTestCaseDisabled ( test_case_class , method_name ) : test_method = getattr ( test_case_class , method_name ) return getattr ( test_method , "__test__" , 'not nose' ) is False
| 0 |
exclude python test from project
|
I check to see if a method on a TestCase has been disabled via nose s convention for disabling a TestCase . This makes it so that users can mix nose s parameterized tests with green as a runner .
|
cosqa-train-15342
|
def isTestCaseDisabled(test_case_class, method_name):
"""
I check to see if a method on a TestCase has been disabled via nose's
convention for disabling a TestCase. This makes it so that users can
mix nose's parameterized tests with green as a runner.
"""
test_method = getattr(test_case_class, method_name)
return getattr(test_method, "__test__", 'not nose') is False
|
def _get_item_position ( self , idx ) : start = 0 if idx == 0 else self . _index [ idx - 1 ] + 1 end = self . _index [ idx ] return start , end
| 1 |
python get the index at that position
|
Return a tuple of ( start end ) indices of an item from its index .
|
cosqa-train-15343
|
def _get_item_position(self, idx):
"""Return a tuple of (start, end) indices of an item from its index."""
start = 0 if idx == 0 else self._index[idx - 1] + 1
end = self._index[idx]
return start, end
|
def to_dataframe ( products ) : try : import pandas as pd except ImportError : raise ImportError ( "to_dataframe requires the optional dependency Pandas." ) return pd . DataFrame . from_dict ( products , orient = 'index' )
| 1 |
expord a data frame from python
|
Return the products from a query response as a Pandas DataFrame with the values in their appropriate Python types .
|
cosqa-train-15344
|
def to_dataframe(products):
"""Return the products from a query response as a Pandas DataFrame
with the values in their appropriate Python types.
"""
try:
import pandas as pd
except ImportError:
raise ImportError("to_dataframe requires the optional dependency Pandas.")
return pd.DataFrame.from_dict(products, orient='index')
|
def index ( self , elem ) : return _coconut . len ( self . _iter ) - self . _iter . index ( elem ) - 1
| 0 |
python get the index of an iteratable
|
Find the index of elem in the reversed iterator .
|
cosqa-train-15345
|
def index(self, elem):
"""Find the index of elem in the reversed iterator."""
return _coconut.len(self._iter) - self._iter.index(elem) - 1
|
def convert_time_string ( date_str ) : dt , _ , _ = date_str . partition ( "." ) dt = datetime . strptime ( dt , "%Y-%m-%dT%H:%M:%S" ) return dt
| 0 |
extract a date from date and time python
|
Change a date string from the format 2018 - 08 - 15T23 : 55 : 17 into a datetime object
|
cosqa-train-15346
|
def convert_time_string(date_str):
""" Change a date string from the format 2018-08-15T23:55:17 into a datetime object """
dt, _, _ = date_str.partition(".")
dt = datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
return dt
|
def get_key_by_value ( dictionary , search_value ) : for key , value in dictionary . iteritems ( ) : if value == search_value : return ugettext ( key )
| 0 |
python get the key of specific value in dictionary
|
searchs a value in a dicionary and returns the key of the first occurrence
|
cosqa-train-15347
|
def get_key_by_value(dictionary, search_value):
"""
searchs a value in a dicionary and returns the key of the first occurrence
:param dictionary: dictionary to search in
:param search_value: value to search for
"""
for key, value in dictionary.iteritems():
if value == search_value:
return ugettext(key)
|
def AmericanDateToEpoch ( self , date_str ) : try : epoch = time . strptime ( date_str , "%m/%d/%Y" ) return int ( calendar . timegm ( epoch ) ) * 1000000 except ValueError : return 0
| 1 |
extract day from epoch timestamp python
|
Take a US format date and return epoch .
|
cosqa-train-15348
|
def AmericanDateToEpoch(self, date_str):
"""Take a US format date and return epoch."""
try:
epoch = time.strptime(date_str, "%m/%d/%Y")
return int(calendar.timegm(epoch)) * 1000000
except ValueError:
return 0
|
def _dt_to_epoch ( dt ) : try : epoch = dt . timestamp ( ) except AttributeError : # py2 epoch = ( dt - datetime ( 1970 , 1 , 1 ) ) . total_seconds ( ) return epoch
| 1 |
python get timestamp seconds since epoch
|
Convert datetime to epoch seconds .
|
cosqa-train-15349
|
def _dt_to_epoch(dt):
"""Convert datetime to epoch seconds."""
try:
epoch = dt.timestamp()
except AttributeError: # py2
epoch = (dt - datetime(1970, 1, 1)).total_seconds()
return epoch
|
def string_to_genomic_range ( rstring ) : m = re . match ( '([^:]+):(\d+)-(\d+)' , rstring ) if not m : sys . stderr . write ( "ERROR: problem with range string " + rstring + "\n" ) return GenomicRange ( m . group ( 1 ) , int ( m . group ( 2 ) ) , int ( m . group ( 3 ) ) )
| 0 |
extract range from string python
|
Convert a string to a genomic range
|
cosqa-train-15350
|
def string_to_genomic_range(rstring):
""" Convert a string to a genomic range
:param rstring: string representing a genomic range chr1:801-900
:type rstring:
:returns: object representing the string
:rtype: GenomicRange
"""
m = re.match('([^:]+):(\d+)-(\d+)',rstring)
if not m:
sys.stderr.write("ERROR: problem with range string "+rstring+"\n")
return GenomicRange(m.group(1),int(m.group(2)),int(m.group(3)))
|
def convert_2_utc ( self , datetime_ , timezone ) : datetime_ = self . tz_mapper [ timezone ] . localize ( datetime_ ) return datetime_ . astimezone ( pytz . UTC )
| 0 |
python get timezone gmt utc offset
|
convert to datetime to UTC offset .
|
cosqa-train-15351
|
def convert_2_utc(self, datetime_, timezone):
"""convert to datetime to UTC offset."""
datetime_ = self.tz_mapper[timezone].localize(datetime_)
return datetime_.astimezone(pytz.UTC)
|
def listified_tokenizer ( source ) : io_obj = io . StringIO ( source ) return [ list ( a ) for a in tokenize . generate_tokens ( io_obj . readline ) ]
| 1 |
extract tokens from a coulmns text of a file in python
|
Tokenizes * source * and returns the tokens as a list of lists .
|
cosqa-train-15352
|
def listified_tokenizer(source):
"""Tokenizes *source* and returns the tokens as a list of lists."""
io_obj = io.StringIO(source)
return [list(a) for a in tokenize.generate_tokens(io_obj.readline)]
|
def intty ( cls ) : # XXX: temporary hack until we can detect if we are in a pipe or not return True if hasattr ( sys . stdout , 'isatty' ) and sys . stdout . isatty ( ) : return True return False
| 0 |
python get tty echo content
|
Check if we are in a tty .
|
cosqa-train-15353
|
def intty(cls):
""" Check if we are in a tty. """
# XXX: temporary hack until we can detect if we are in a pipe or not
return True
if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():
return True
return False
|
def code_from_ipynb ( nb , markdown = False ) : code = PREAMBLE for cell in nb [ 'cells' ] : if cell [ 'cell_type' ] == 'code' : # transform the input to executable Python code += '' . join ( cell [ 'source' ] ) if cell [ 'cell_type' ] == 'markdown' : code += '\n# ' + '# ' . join ( cell [ 'source' ] ) # We want a blank newline after each cell's output. # And the last line of source doesn't have a newline usually. code += '\n\n' return code
| 0 |
extracting ipynb source using python code
|
Get the code for a given notebook
|
cosqa-train-15354
|
def code_from_ipynb(nb, markdown=False):
"""
Get the code for a given notebook
nb is passed in as a dictionary that's a parsed ipynb file
"""
code = PREAMBLE
for cell in nb['cells']:
if cell['cell_type'] == 'code':
# transform the input to executable Python
code += ''.join(cell['source'])
if cell['cell_type'] == 'markdown':
code += '\n# ' + '# '.join(cell['source'])
# We want a blank newline after each cell's output.
# And the last line of source doesn't have a newline usually.
code += '\n\n'
return code
|
def generate_unique_host_id ( ) : host = "." . join ( reversed ( socket . gethostname ( ) . split ( "." ) ) ) pid = os . getpid ( ) return "%s.%d" % ( host , pid )
| 0 |
python get unique id
|
Generate a unique ID that is somewhat guaranteed to be unique among all instances running at the same time .
|
cosqa-train-15355
|
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 computeFactorial ( n ) : sleep_walk ( 10 ) ret = 1 for i in range ( n ) : ret = ret * ( i + 1 ) return ret
| 1 |
factorial evens function python loop
|
computes factorial of n
|
cosqa-train-15356
|
def computeFactorial(n):
"""
computes factorial of n
"""
sleep_walk(10)
ret = 1
for i in range(n):
ret = ret * (i + 1)
return ret
|
def get_url_nofollow ( url ) : try : response = urlopen ( url ) code = response . getcode ( ) return code except HTTPError as e : return e . code except : return 0
| 0 |
python get url return code
|
function to get return code of a url
|
cosqa-train-15357
|
def get_url_nofollow(url):
"""
function to get return code of a url
Credits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-return-code-and-final-return-code-if-redirected/
"""
try:
response = urlopen(url)
code = response.getcode()
return code
except HTTPError as e:
return e.code
except:
return 0
|
def get_mnist ( data_type = "train" , location = "/tmp/mnist" ) : X , Y = mnist . read_data_sets ( location , data_type ) return X , Y + 1
| 0 |
fetch mnist dataset python
|
Get mnist dataset with features and label as ndarray . Data would be downloaded automatically if it doesn t present at the specific location .
|
cosqa-train-15358
|
def get_mnist(data_type="train", location="/tmp/mnist"):
"""
Get mnist dataset with features and label as ndarray.
Data would be downloaded automatically if it doesn't present at the specific location.
:param data_type: "train" for training data and "test" for testing data.
:param location: Location to store mnist dataset.
:return: (features: ndarray, label: ndarray)
"""
X, Y = mnist.read_data_sets(location, data_type)
return X, Y + 1
|
def get_value ( key , obj , default = missing ) : if isinstance ( key , int ) : return _get_value_for_key ( key , obj , default ) return _get_value_for_keys ( key . split ( '.' ) , obj , default )
| 1 |
python get value by key with default
|
Helper for pulling a keyed value off various types of objects
|
cosqa-train-15359
|
def get_value(key, obj, default=missing):
"""Helper for pulling a keyed value off various types of objects"""
if isinstance(key, int):
return _get_value_for_key(key, obj, default)
return _get_value_for_keys(key.split('.'), obj, default)
|
def c_str ( string ) : if not isinstance ( string , str ) : string = string . decode ( 'ascii' ) return ctypes . c_char_p ( string . encode ( 'utf-8' ) )
| 1 |
ffi python string c string
|
Convert a python string to C string .
|
cosqa-train-15360
|
def c_str(string):
""""Convert a python string to C string."""
if not isinstance(string, str):
string = string.decode('ascii')
return ctypes.c_char_p(string.encode('utf-8'))
|
def get_inputs_from_cm ( index , cm ) : return tuple ( i for i in range ( cm . shape [ 0 ] ) if cm [ i ] [ index ] )
| 0 |
python get x,y indexes of certain elements
|
Return indices of inputs to the node with the given index .
|
cosqa-train-15361
|
def get_inputs_from_cm(index, cm):
"""Return indices of inputs to the node with the given index."""
return tuple(i for i in range(cm.shape[0]) if cm[i][index])
|
def software_fibonacci ( n ) : a , b = 0 , 1 for i in range ( n ) : a , b = b , a + b return a
| 1 |
fibonacci sequence in python for n terms
|
a normal old python function to return the Nth fibonacci number .
|
cosqa-train-15362
|
def software_fibonacci(n):
""" a normal old python function to return the Nth fibonacci number. """
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
|
def _read_stream_for_size ( stream , buf_size = 65536 ) : size = 0 while True : buf = stream . read ( buf_size ) size += len ( buf ) if not buf : break return size
| 1 |
python getsizeof greater than memory size
|
Reads a stream discarding the data read and returns its size .
|
cosqa-train-15363
|
def _read_stream_for_size(stream, buf_size=65536):
"""Reads a stream discarding the data read and returns its size."""
size = 0
while True:
buf = stream.read(buf_size)
size += len(buf)
if not buf:
break
return size
|
def open_file ( file , mode ) : if hasattr ( file , "read" ) : return file if hasattr ( file , "open" ) : return file . open ( mode ) return open ( file , mode )
| 0 |
file opening mode in python
|
Open a file .
|
cosqa-train-15364
|
def open_file(file, mode):
"""Open a file.
:arg file: file-like or path-like object.
:arg str mode: ``mode`` argument for :func:`open`.
"""
if hasattr(file, "read"):
return file
if hasattr(file, "open"):
return file.open(mode)
return open(file, mode)
|
def save_dot ( self , fd ) : from pylon . io import DotWriter DotWriter ( self ) . write ( fd )
| 1 |
python graphviz export pdf
|
Saves a representation of the case in the Graphviz DOT language .
|
cosqa-train-15365
|
def save_dot(self, fd):
""" Saves a representation of the case in the Graphviz DOT language.
"""
from pylon.io import DotWriter
DotWriter(self).write(fd)
|
def read_utf8 ( fh , byteorder , dtype , count , offsetsize ) : return fh . read ( count ) . decode ( 'utf-8' )
| 1 |
file utf8 not read python
|
Read tag data from file and return as unicode string .
|
cosqa-train-15366
|
def read_utf8(fh, byteorder, dtype, count, offsetsize):
"""Read tag data from file and return as unicode string."""
return fh.read(count).decode('utf-8')
|
def _column_resized ( self , col , old_width , new_width ) : self . dataTable . setColumnWidth ( col , new_width ) self . _update_layout ( )
| 1 |
python grid columnconfigure minsize
|
Update the column width .
|
cosqa-train-15367
|
def _column_resized(self, col, old_width, new_width):
"""Update the column width."""
self.dataTable.setColumnWidth(col, new_width)
self._update_layout()
|
def clean_dataframe ( df ) : df = df . fillna ( method = 'ffill' ) df = df . fillna ( 0.0 ) return df
| 0 |
fill null values in df with 0 python
|
Fill NaNs with the previous value the next value or if all are NaN then 1 . 0
|
cosqa-train-15368
|
def clean_dataframe(df):
"""Fill NaNs with the previous value, the next value or if all are NaN then 1.0"""
df = df.fillna(method='ffill')
df = df.fillna(0.0)
return df
|
def gcall ( func , * args , * * kwargs ) : def idle ( ) : with gdk . lock : return bool ( func ( * args , * * kwargs ) ) return gobject . idle_add ( idle )
| 0 |
python gtk not refreshing
|
Calls a function with the given arguments inside Gtk s main loop . Example :: gcall ( lbl . set_text foo )
|
cosqa-train-15369
|
def gcall(func, *args, **kwargs):
"""
Calls a function, with the given arguments inside Gtk's main loop.
Example::
gcall(lbl.set_text, "foo")
If this call would be made in a thread there could be problems, using
it inside Gtk's main loop makes it thread safe.
"""
def idle():
with gdk.lock:
return bool(func(*args, **kwargs))
return gobject.idle_add(idle)
|
def camel_case_from_underscores ( string ) : components = string . split ( '_' ) string = '' for component in components : string += component [ 0 ] . upper ( ) + component [ 1 : ] return string
| 1 |
fill space with underscore in a string in python
|
generate a CamelCase string from an underscore_string .
|
cosqa-train-15370
|
def camel_case_from_underscores(string):
"""generate a CamelCase string from an underscore_string."""
components = string.split('_')
string = ''
for component in components:
string += component[0].upper() + component[1:]
return string
|
def np_hash ( a ) : if a is None : return hash ( None ) # Ensure that hashes are equal whatever the ordering in memory (C or # Fortran) a = np . ascontiguousarray ( a ) # Compute the digest and return a decimal int return int ( hashlib . sha1 ( a . view ( a . dtype ) ) . hexdigest ( ) , 16 )
| 1 |
python hash of numpy array
|
Return a hash of a NumPy array .
|
cosqa-train-15371
|
def np_hash(a):
"""Return a hash of a NumPy array."""
if a is None:
return hash(None)
# Ensure that hashes are equal whatever the ordering in memory (C or
# Fortran)
a = np.ascontiguousarray(a)
# Compute the digest and return a decimal int
return int(hashlib.sha1(a.view(a.dtype)).hexdigest(), 16)
|
def tuple_search ( t , i , v ) : for e in t : if e [ i ] == v : return e return None
| 1 |
finding an element in an tuple list python
|
Search tuple array by index and value : param t : tuple array : param i : index of the value in each tuple : param v : value : return : the first tuple in the array with the specific index / value
|
cosqa-train-15372
|
def tuple_search(t, i, v):
"""
Search tuple array by index and value
:param t: tuple array
:param i: index of the value in each tuple
:param v: value
:return: the first tuple in the array with the specific index / value
"""
for e in t:
if e[i] == v:
return e
return None
|
def top ( n , width = WIDTH , style = STYLE ) : return hrule ( n , width , linestyle = STYLES [ style ] . top )
| 1 |
python head table output
|
Prints the top row of a table
|
cosqa-train-15373
|
def top(n, width=WIDTH, style=STYLE):
"""Prints the top row of a table"""
return hrule(n, width, linestyle=STYLES[style].top)
|
def binSearch ( arr , val ) : i = bisect_left ( arr , val ) if i != len ( arr ) and arr [ i ] == val : return i return - 1
| 0 |
finding an index in a list in python
|
Function for running binary search on a sorted list .
|
cosqa-train-15374
|
def binSearch(arr, val):
"""
Function for running binary search on a sorted list.
:param arr: (list) a sorted list of integers to search
:param val: (int) a integer to search for in the sorted array
:returns: (int) the index of the element if it is found and -1 otherwise.
"""
i = bisect_left(arr, val)
if i != len(arr) and arr[i] == val:
return i
return -1
|
def pop ( h ) : n = h . size ( ) - 1 h . swap ( 0 , n ) down ( h , 0 , n ) return h . pop ( )
| 1 |
python heap top element
|
Pop the heap value from the heap .
|
cosqa-train-15375
|
def pop(h):
"""Pop the heap value from the heap."""
n = h.size() - 1
h.swap(0, n)
down(h, 0, n)
return h.pop()
|
def equal ( list1 , list2 ) : return [ item1 == item2 for item1 , item2 in broadcast_zip ( list1 , list2 ) ]
| 0 |
finding index of boolean passed through array python
|
takes flags returns indexes of True values
|
cosqa-train-15376
|
def equal(list1, list2):
""" takes flags returns indexes of True values """
return [item1 == item2 for item1, item2 in broadcast_zip(list1, list2)]
|
def update_index ( index ) : logger . info ( "Updating search index: '%s'" , index ) client = get_client ( ) responses = [ ] for model in get_index_models ( index ) : logger . info ( "Updating search index model: '%s'" , model . search_doc_type ) objects = model . objects . get_search_queryset ( index ) . iterator ( ) actions = bulk_actions ( objects , index = index , action = "index" ) response = helpers . bulk ( client , actions , chunk_size = get_setting ( "chunk_size" ) ) responses . append ( response ) return responses
| 0 |
python helpers bulk load data elasticsearch
|
Re - index every document in a named index .
|
cosqa-train-15377
|
def update_index(index):
"""Re-index every document in a named index."""
logger.info("Updating search index: '%s'", index)
client = get_client()
responses = []
for model in get_index_models(index):
logger.info("Updating search index model: '%s'", model.search_doc_type)
objects = model.objects.get_search_queryset(index).iterator()
actions = bulk_actions(objects, index=index, action="index")
response = helpers.bulk(client, actions, chunk_size=get_setting("chunk_size"))
responses.append(response)
return responses
|
def is_in ( self , search_list , pair ) : index = - 1 for nr , i in enumerate ( search_list ) : if ( np . all ( i == pair ) ) : return nr return index
| 0 |
finding index of number in list python
|
If pair is in search_list return the index . Otherwise return - 1
|
cosqa-train-15378
|
def is_in(self, search_list, pair):
"""
If pair is in search_list, return the index. Otherwise return -1
"""
index = -1
for nr, i in enumerate(search_list):
if(np.all(i == pair)):
return nr
return index
|
def hide ( self ) : self . tk . withdraw ( ) self . _visible = False if self . _modal : self . tk . grab_release ( )
| 1 |
python hide tkinter window
|
Hide the window .
|
cosqa-train-15379
|
def hide(self):
"""Hide the window."""
self.tk.withdraw()
self._visible = False
if self._modal:
self.tk.grab_release()
|
def local_minima ( img , min_distance = 4 ) : # @TODO: Write a unittest for this. fits = numpy . asarray ( img ) minfits = minimum_filter ( fits , size = min_distance ) # default mode is reflect minima_mask = fits == minfits good_indices = numpy . transpose ( minima_mask . nonzero ( ) ) good_fits = fits [ minima_mask ] order = good_fits . argsort ( ) return good_indices [ order ] , good_fits [ order ]
| 0 |
finding local maxima in image python
|
r Returns all local minima from an image . Parameters ---------- img : array_like The image . min_distance : integer The minimal distance between the minimas in voxels . If it is less only the lower minima is returned . Returns ------- indices : sequence List of all minima indices . values : sequence List of all minima values .
|
cosqa-train-15380
|
def local_minima(img, min_distance = 4):
r"""
Returns all local minima from an image.
Parameters
----------
img : array_like
The image.
min_distance : integer
The minimal distance between the minimas in voxels. If it is less, only the lower minima is returned.
Returns
-------
indices : sequence
List of all minima indices.
values : sequence
List of all minima values.
"""
# @TODO: Write a unittest for this.
fits = numpy.asarray(img)
minfits = minimum_filter(fits, size=min_distance) # default mode is reflect
minima_mask = fits == minfits
good_indices = numpy.transpose(minima_mask.nonzero())
good_fits = fits[minima_mask]
order = good_fits.argsort()
return good_indices[order], good_fits[order]
|
def oplot ( self , x , y , * * kw ) : self . panel . oplot ( x , y , * * kw )
| 0 |
python hold a plot
|
generic plotting method overplotting any existing plot
|
cosqa-train-15381
|
def oplot(self, x, y, **kw):
"""generic plotting method, overplotting any existing plot """
self.panel.oplot(x, y, **kw)
|
def _factor_generator ( n ) : p = prime_factors ( n ) factors = { } for p1 in p : try : factors [ p1 ] += 1 except KeyError : factors [ p1 ] = 1 return factors
| 1 |
finding number of factors of a number in python
|
From a given natural integer returns the prime factors and their multiplicity : param n : Natural integer : return :
|
cosqa-train-15382
|
def _factor_generator(n):
"""
From a given natural integer, returns the prime factors and their multiplicity
:param n: Natural integer
:return:
"""
p = prime_factors(n)
factors = {}
for p1 in p:
try:
factors[p1] += 1
except KeyError:
factors[p1] = 1
return factors
|
def retrieve_by_id ( self , id_ ) : items_with_id = [ item for item in self if item . id == int ( id_ ) ] if len ( items_with_id ) == 1 : return items_with_id [ 0 ] . retrieve ( )
| 1 |
python how do i reference an object by its id number
|
Return a JSSObject for the element with ID id_
|
cosqa-train-15383
|
def retrieve_by_id(self, id_):
"""Return a JSSObject for the element with ID id_"""
items_with_id = [item for item in self if item.id == int(id_)]
if len(items_with_id) == 1:
return items_with_id[0].retrieve()
|
def newest_file ( file_iterable ) : return max ( file_iterable , key = lambda fname : os . path . getmtime ( fname ) )
| 0 |
finding oldest file using python
|
Returns the name of the newest file given an iterable of file names .
|
cosqa-train-15384
|
def newest_file(file_iterable):
"""
Returns the name of the newest file given an iterable of file names.
"""
return max(file_iterable, key=lambda fname: os.path.getmtime(fname))
|
def readline ( self ) : self . lineno += 1 if self . _buffer : return self . _buffer . pop ( ) else : return self . input . readline ( )
| 0 |
python how to access next line text
|
Get the next line including the newline or on EOF .
|
cosqa-train-15385
|
def readline(self):
"""Get the next line including the newline or '' on EOF."""
self.lineno += 1
if self._buffer:
return self._buffer.pop()
else:
return self.input.readline()
|
def union_overlapping ( intervals ) : disjoint_intervals = [ ] for interval in intervals : if disjoint_intervals and disjoint_intervals [ - 1 ] . overlaps ( interval ) : disjoint_intervals [ - 1 ] = disjoint_intervals [ - 1 ] . union ( interval ) else : disjoint_intervals . append ( interval ) return disjoint_intervals
| 0 |
finding overlapping sets in python
|
Union any overlapping intervals in the given set .
|
cosqa-train-15386
|
def union_overlapping(intervals):
"""Union any overlapping intervals in the given set."""
disjoint_intervals = []
for interval in intervals:
if disjoint_intervals and disjoint_intervals[-1].overlaps(interval):
disjoint_intervals[-1] = disjoint_intervals[-1].union(interval)
else:
disjoint_intervals.append(interval)
return disjoint_intervals
|
def init ( ) : print ( yellow ( "# Setting up environment...\n" , True ) ) virtualenv . init ( ) virtualenv . update_requirements ( ) print ( green ( "\n# DONE." , True ) ) print ( green ( "Type " ) + green ( "activate" , True ) + green ( " to enable your virtual environment." ) )
| 0 |
python how to activate virtual environment
|
Execute init tasks for all components ( virtualenv pip ) .
|
cosqa-train-15387
|
def init():
"""
Execute init tasks for all components (virtualenv, pip).
"""
print(yellow("# Setting up environment...\n", True))
virtualenv.init()
virtualenv.update_requirements()
print(green("\n# DONE.", True))
print(green("Type ") + green("activate", True) + green(" to enable your virtual environment."))
|
def binSearch ( arr , val ) : i = bisect_left ( arr , val ) if i != len ( arr ) and arr [ i ] == val : return i return - 1
| 0 |
finding the index in a python list
|
Function for running binary search on a sorted list .
|
cosqa-train-15388
|
def binSearch(arr, val):
"""
Function for running binary search on a sorted list.
:param arr: (list) a sorted list of integers to search
:param val: (int) a integer to search for in the sorted array
:returns: (int) the index of the element if it is found and -1 otherwise.
"""
i = bisect_left(arr, val)
if i != len(arr) and arr[i] == val:
return i
return -1
|
def ratelimit_remaining ( self ) : json = self . _json ( self . _get ( self . _github_url + '/rate_limit' ) , 200 ) core = json . get ( 'resources' , { } ) . get ( 'core' , { } ) self . _remaining = core . get ( 'remaining' , 0 ) return self . _remaining
| 0 |
python how to avoid hitting api limit
|
Number of requests before GitHub imposes a ratelimit .
|
cosqa-train-15389
|
def ratelimit_remaining(self):
"""Number of requests before GitHub imposes a ratelimit.
:returns: int
"""
json = self._json(self._get(self._github_url + '/rate_limit'), 200)
core = json.get('resources', {}).get('core', {})
self._remaining = core.get('remaining', 0)
return self._remaining
|
def _sim_fill ( r1 , r2 , imsize ) : bbsize = ( ( max ( r1 [ "max_x" ] , r2 [ "max_x" ] ) - min ( r1 [ "min_x" ] , r2 [ "min_x" ] ) ) * ( max ( r1 [ "max_y" ] , r2 [ "max_y" ] ) - min ( r1 [ "min_y" ] , r2 [ "min_y" ] ) ) ) return 1.0 - ( bbsize - r1 [ "size" ] - r2 [ "size" ] ) / imsize
| 1 |
finding the similarity between 2 images in python
|
calculate the fill similarity over the image
|
cosqa-train-15390
|
def _sim_fill(r1, r2, imsize):
"""
calculate the fill similarity over the image
"""
bbsize = (
(max(r1["max_x"], r2["max_x"]) - min(r1["min_x"], r2["min_x"]))
* (max(r1["max_y"], r2["max_y"]) - min(r1["min_y"], r2["min_y"]))
)
return 1.0 - (bbsize - r1["size"] - r2["size"]) / imsize
|
def is_sparse_vector ( x ) : return sp . issparse ( x ) and len ( x . shape ) == 2 and x . shape [ 0 ] == 1
| 0 |
python how to avoid sparse matrix
|
x is a 2D sparse matrix with it s first shape equal to 1 .
|
cosqa-train-15391
|
def is_sparse_vector(x):
""" x is a 2D sparse matrix with it's first shape equal to 1.
"""
return sp.issparse(x) and len(x.shape) == 2 and x.shape[0] == 1
|
def head ( filename , n = 10 ) : with freader ( filename ) as fr : for _ in range ( n ) : print ( fr . readline ( ) . strip ( ) )
| 1 |
first few lines of a file python print
|
prints the top n lines of a file
|
cosqa-train-15392
|
def head(filename, n=10):
""" prints the top `n` lines of a file """
with freader(filename) as fr:
for _ in range(n):
print(fr.readline().strip())
|
def _manhattan_distance ( vec_a , vec_b ) : if len ( vec_a ) != len ( vec_b ) : raise ValueError ( 'len(vec_a) must equal len(vec_b)' ) return sum ( map ( lambda a , b : abs ( a - b ) , vec_a , vec_b ) )
| 0 |
python how to calculate manhattan distance
|
Return manhattan distance between two lists of numbers .
|
cosqa-train-15393
|
def _manhattan_distance(vec_a, vec_b):
"""Return manhattan distance between two lists of numbers."""
if len(vec_a) != len(vec_b):
raise ValueError('len(vec_a) must equal len(vec_b)')
return sum(map(lambda a, b: abs(a - b), vec_a, vec_b))
|
def fit_gaussian ( x , y , yerr , p0 ) : try : popt , pcov = curve_fit ( gaussian , x , y , sigma = yerr , p0 = p0 , absolute_sigma = True ) except RuntimeError : return [ 0 ] , [ 0 ] return popt , pcov
| 1 |
fit gaussian curve in python
|
Fit a Gaussian to the data
|
cosqa-train-15394
|
def fit_gaussian(x, y, yerr, p0):
""" Fit a Gaussian to the data """
try:
popt, pcov = curve_fit(gaussian, x, y, sigma=yerr, p0=p0, absolute_sigma=True)
except RuntimeError:
return [0],[0]
return popt, pcov
|
def bytes_to_str ( s , encoding = 'utf-8' ) : if six . PY3 and isinstance ( s , bytes ) : return s . decode ( encoding ) return s
| 1 |
python how to cast bytes into string
|
Returns a str if a bytes object is given .
|
cosqa-train-15395
|
def bytes_to_str(s, encoding='utf-8'):
"""Returns a str if a bytes object is given."""
if six.PY3 and isinstance(s, bytes):
return s.decode(encoding)
return s
|
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 |
fitting data with self defined function python
|
Apply the coefficients from a linear fit to an array of x y positions .
|
cosqa-train-15396
|
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 go_to_parent_directory ( self ) : self . chdir ( osp . abspath ( osp . join ( getcwd_or_home ( ) , os . pardir ) ) )
| 0 |
python how to chang edirectory to parent
|
Go to parent directory
|
cosqa-train-15397
|
def go_to_parent_directory(self):
"""Go to parent directory"""
self.chdir(osp.abspath(osp.join(getcwd_or_home(), os.pardir)))
|
def old_pad ( s ) : if len ( s ) % OLD_BLOCK_SIZE == 0 : return s return Padding . appendPadding ( s , blocksize = OLD_BLOCK_SIZE )
| 0 |
fixed lenth string padding python
|
Pads an input string to a given block size . : param s : string : returns : The padded string .
|
cosqa-train-15398
|
def old_pad(s):
"""
Pads an input string to a given block size.
:param s: string
:returns: The padded string.
"""
if len(s) % OLD_BLOCK_SIZE == 0:
return s
return Padding.appendPadding(s, blocksize=OLD_BLOCK_SIZE)
|
def split_into_words ( s ) : s = re . sub ( r"\W+" , " " , s ) s = re . sub ( r"[_0-9]+" , " " , s ) return s . split ( )
| 0 |
python how to change a string to a list of words
|
Split a sentence into list of words .
|
cosqa-train-15399
|
def split_into_words(s):
"""Split a sentence into list of words."""
s = re.sub(r"\W+", " ", s)
s = re.sub(r"[_0-9]+", " ", s)
return s.split()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.