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 uniform_noise ( points ) : return np . random . rand ( 1 ) * np . random . uniform ( points , 1 ) + random . sample ( [ 2 , - 2 ] , 1 )
1
python add random noise on image
Init a uniform noise variable .
cosqa-train-14500
def uniform_noise(points): """Init a uniform noise variable.""" return np.random.rand(1) * np.random.uniform(points, 1) \ + random.sample([2, -2], 1)
def replaceNewlines ( string , newlineChar ) : if newlineChar in string : segments = string . split ( newlineChar ) string = "" for segment in segments : string += segment return string
1
replacing new line from string in python
There s probably a way to do this with string functions but I was lazy . Replace all instances of \ r or \ n in a string with something else .
cosqa-train-14501
def replaceNewlines(string, newlineChar): """There's probably a way to do this with string functions but I was lazy. Replace all instances of \r or \n in a string with something else.""" if newlineChar in string: segments = string.split(newlineChar) string = "" for segment in segments: string += segment return string
def add_suffix ( fullname , suffix ) : name , ext = os . path . splitext ( fullname ) return name + '_' + suffix + ext
1
python add suffix to filename
Add suffix to a full file name
cosqa-train-14502
def add_suffix(fullname, suffix): """ Add suffix to a full file name""" name, ext = os.path.splitext(fullname) return name + '_' + suffix + ext
def alter_change_column ( self , table , column , field ) : return self . _update_column ( table , column , lambda a , b : b )
1
replacing values in a colmn in python
Support change columns .
cosqa-train-14503
def alter_change_column(self, table, column, field): """Support change columns.""" return self._update_column(table, column, lambda a, b: b)
def create_symlink ( source , link_name ) : os_symlink = getattr ( os , "symlink" , None ) if isinstance ( os_symlink , collections . Callable ) : os_symlink ( source , link_name ) else : import ctypes csl = ctypes . windll . kernel32 . CreateSymbolicLinkW csl . argtypes = ( ctypes . c_wchar_p , ctypes . c_wchar_p , ctypes . c_uint32 ) csl . restype = ctypes . c_ubyte flags = 1 if os . path . isdir ( source ) else 0 if csl ( link_name , source , flags ) == 0 : raise ctypes . WinError ( )
1
python add symbolic link in windows
Creates symbolic link for either operating system . http : // stackoverflow . com / questions / 6260149 / os - symlink - support - in - windows
cosqa-train-14504
def create_symlink(source, link_name): """ Creates symbolic link for either operating system. http://stackoverflow.com/questions/6260149/os-symlink-support-in-windows """ os_symlink = getattr(os, "symlink", None) if isinstance(os_symlink, collections.Callable): os_symlink(source, link_name) else: import ctypes csl = ctypes.windll.kernel32.CreateSymbolicLinkW csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32) csl.restype = ctypes.c_ubyte flags = 1 if os.path.isdir(source) else 0 if csl(link_name, source, flags) == 0: raise ctypes.WinError()
def __repr__ ( self ) : return str ( { 'name' : self . _name , 'watts' : self . _watts , 'type' : self . _output_type , 'id' : self . _integration_id } )
1
representing an object as a string python
Returns a stringified representation of this object .
cosqa-train-14505
def __repr__(self): """Returns a stringified representation of this object.""" return str({'name': self._name, 'watts': self._watts, 'type': self._output_type, 'id': self._integration_id})
def make_aware ( value , timezone ) : if hasattr ( timezone , 'localize' ) and value not in ( datetime . datetime . min , datetime . datetime . max ) : # available for pytz time zones return timezone . localize ( value , is_dst = None ) else : # may be wrong around DST changes return value . replace ( tzinfo = timezone )
1
python add timezone aware
Makes a naive datetime . datetime in a given time zone aware .
cosqa-train-14506
def make_aware(value, timezone): """ Makes a naive datetime.datetime in a given time zone aware. """ if hasattr(timezone, 'localize') and value not in (datetime.datetime.min, datetime.datetime.max): # available for pytz time zones return timezone.localize(value, is_dst=None) else: # may be wrong around DST changes return value.replace(tzinfo=timezone)
def _is_root ( ) : import os import ctypes try : return os . geteuid ( ) == 0 except AttributeError : return ctypes . windll . shell32 . IsUserAnAdmin ( ) != 0 return False
0
requesting root permissions python programming
Checks if the user is rooted .
cosqa-train-14507
def _is_root(): """Checks if the user is rooted.""" import os import ctypes try: return os.geteuid() == 0 except AttributeError: return ctypes.windll.shell32.IsUserAnAdmin() != 0 return False
def reset_password ( app , appbuilder , username , password ) : _appbuilder = import_application ( app , appbuilder ) user = _appbuilder . sm . find_user ( username = username ) if not user : click . echo ( "User {0} not found." . format ( username ) ) else : _appbuilder . sm . reset_password ( user . id , password ) click . echo ( click . style ( "User {0} reseted." . format ( username ) , fg = "green" ) )
0
reset password using flask python
Resets a user s password
cosqa-train-14508
def reset_password(app, appbuilder, username, password): """ Resets a user's password """ _appbuilder = import_application(app, appbuilder) user = _appbuilder.sm.find_user(username=username) if not user: click.echo("User {0} not found.".format(username)) else: _appbuilder.sm.reset_password(user.id, password) click.echo(click.style("User {0} reseted.".format(username), fg="green"))
def check ( text ) : err = "malapropisms.misc" msg = u"'{}' is a malapropism." illogics = [ "the infinitesimal universe" , "a serial experience" , "attack my voracity" , ] return existence_check ( text , illogics , err , msg , offset = 1 )
1
python algorihtym to determine if text is question
Check the text .
cosqa-train-14509
def check(text): """Check the text.""" err = "malapropisms.misc" msg = u"'{}' is a malapropism." illogics = [ "the infinitesimal universe", "a serial experience", "attack my voracity", ] return existence_check(text, illogics, err, msg, offset=1)
def format_doc_text ( text ) : return '\n' . join ( textwrap . fill ( line , width = 99 , initial_indent = ' ' , subsequent_indent = ' ' ) for line in inspect . cleandoc ( text ) . splitlines ( ) )
0
restructured text docstrings python multiple return
A very thin wrapper around textwrap . fill to consistently wrap documentation text for display in a command line environment . The text is wrapped to 99 characters with an indentation depth of 4 spaces . Each line is wrapped independently in order to preserve manually added line breaks .
cosqa-train-14510
def format_doc_text(text): """ A very thin wrapper around textwrap.fill to consistently wrap documentation text for display in a command line environment. The text is wrapped to 99 characters with an indentation depth of 4 spaces. Each line is wrapped independently in order to preserve manually added line breaks. :param text: The text to format, it is cleaned by inspect.cleandoc. :return: The formatted doc text. """ return '\n'.join( textwrap.fill(line, width=99, initial_indent=' ', subsequent_indent=' ') for line in inspect.cleandoc(text).splitlines())
def extract_all ( zipfile , dest_folder ) : z = ZipFile ( zipfile ) print ( z ) z . extract ( dest_folder )
0
python all files unzip except the first
reads the zip file determines compression and unzips recursively until source files are extracted
cosqa-train-14511
def extract_all(zipfile, dest_folder): """ reads the zip file, determines compression and unzips recursively until source files are extracted """ z = ZipFile(zipfile) print(z) z.extract(dest_folder)
def get_decimal_quantum ( precision ) : assert isinstance ( precision , ( int , decimal . Decimal ) ) return decimal . Decimal ( 10 ) ** ( - precision )
1
retaining precision in decimal types python
Return minimal quantum of a number as defined by precision .
cosqa-train-14512
def get_decimal_quantum(precision): """Return minimal quantum of a number, as defined by precision.""" assert isinstance(precision, (int, decimal.Decimal)) return decimal.Decimal(10) ** (-precision)
def angle ( x0 , y0 , x1 , y1 ) : return degrees ( atan2 ( y1 - y0 , x1 - x0 ) )
1
python angle betwen two points
Returns the angle between two points .
cosqa-train-14513
def angle(x0, y0, x1, y1): """ Returns the angle between two points. """ return degrees(atan2(y1-y0, x1-x0))
def getvariable ( name ) : import inspect fr = inspect . currentframe ( ) try : while fr : fr = fr . f_back vars = fr . f_locals if name in vars : return vars [ name ] except : pass return None
1
return global variable in python
Get the value of a local variable somewhere in the call stack .
cosqa-train-14514
def getvariable(name): """Get the value of a local variable somewhere in the call stack.""" import inspect fr = inspect.currentframe() try: while fr: fr = fr.f_back vars = fr.f_locals if name in vars: return vars[name] except: pass return None
def apply ( filter ) : def decorator ( callable ) : return lambda * args , * * kwargs : filter ( callable ( * args , * * kwargs ) ) return decorator
1
python any functionm pass comparator
Manufacture decorator that filters return value with given function .
cosqa-train-14515
def apply(filter): """Manufacture decorator that filters return value with given function. ``filter``: Callable that takes a single parameter. """ def decorator(callable): return lambda *args, **kwargs: filter(callable(*args, **kwargs)) return decorator
def create_response ( self , request , content , content_type ) : return HttpResponse ( content = content , content_type = content_type )
0
return httpresponse python django
Returns a response object for the request . Can be overridden to return different responses .
cosqa-train-14516
def create_response(self, request, content, content_type): """Returns a response object for the request. Can be overridden to return different responses.""" return HttpResponse(content=content, content_type=content_type)
def mostCommonItem ( lst ) : # This elegant solution from: http://stackoverflow.com/a/1518632/1760218 lst = [ l for l in lst if l ] if lst : return max ( set ( lst ) , key = lst . count ) else : return None
0
return second most common item in list python
Choose the most common item from the list or the first item if all items are unique .
cosqa-train-14517
def mostCommonItem(lst): """Choose the most common item from the list, or the first item if all items are unique.""" # This elegant solution from: http://stackoverflow.com/a/1518632/1760218 lst = [l for l in lst if l] if lst: return max(set(lst), key=lst.count) else: return None
def extend ( self , iterable ) : return super ( Collection , self ) . extend ( self . _ensure_iterable_is_valid ( iterable ) )
1
python append to iterable
Extend the list by appending all the items in the given list .
cosqa-train-14518
def extend(self, iterable): """Extend the list by appending all the items in the given list.""" return super(Collection, self).extend( self._ensure_iterable_is_valid(iterable))
def path_to_list ( pathstr ) : return [ elem for elem in pathstr . split ( os . path . pathsep ) if elem ]
1
returning a string as list python
Conver a path string to a list of path elements .
cosqa-train-14519
def path_to_list(pathstr): """Conver a path string to a list of path elements.""" return [elem for elem in pathstr.split(os.path.pathsep) if elem]
def allclose ( a , b ) : from numpy import allclose return ( a . shape == b . shape ) and allclose ( a , b )
0
python are two ndarrays equal
Test that a and b are close and match in shape .
cosqa-train-14520
def allclose(a, b): """ Test that a and b are close and match in shape. Parameters ---------- a : ndarray First array to check b : ndarray First array to check """ from numpy import allclose return (a.shape == b.shape) and allclose(a, b)
def counter ( items ) : results = { } for item in items : results [ item ] = results . get ( item , 0 ) + 1 return results
1
returning counter results in python
Simplest required implementation of collections . Counter . Required as 2 . 6 does not have Counter in collections .
cosqa-train-14521
def counter(items): """ Simplest required implementation of collections.Counter. Required as 2.6 does not have Counter in collections. """ results = {} for item in items: results[item] = results.get(item, 0) + 1 return results
def set_subparsers_args ( self , * args , * * kwargs ) : self . subparsers_args = args self . subparsers_kwargs = kwargs
1
python argparse add subparser to subparser
Sets args and kwargs that are passed when creating a subparsers group in an argparse . ArgumentParser i . e . when calling argparser . ArgumentParser . add_subparsers
cosqa-train-14522
def set_subparsers_args(self, *args, **kwargs): """ Sets args and kwargs that are passed when creating a subparsers group in an argparse.ArgumentParser i.e. when calling argparser.ArgumentParser.add_subparsers """ self.subparsers_args = args self.subparsers_kwargs = kwargs
def __reversed__ ( self ) : _dict = self . _dict return iter ( ( key , _dict [ key ] ) for key in reversed ( self . _list ) )
0
reverse iterate python ordereddict
Return a reversed iterable over the items in the dictionary . Items are iterated over in their reverse sort order .
cosqa-train-14523
def __reversed__(self): """ Return a reversed iterable over the items in the dictionary. Items are iterated over in their reverse sort order. Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries. """ _dict = self._dict return iter((key, _dict[key]) for key in reversed(self._list))
def add_option ( self , * args , * * kwargs ) : if self . parseTool == 'argparse' : if args and args [ 0 ] == '' : # no short option args = args [ 1 : ] return self . parser . add_argument ( * args , * * kwargs ) else : return self . parser . add_option ( * args , * * kwargs )
0
python argparse custom action
Add optparse or argparse option depending on CmdHelper initialization .
cosqa-train-14524
def add_option(self, *args, **kwargs): """Add optparse or argparse option depending on CmdHelper initialization.""" if self.parseTool == 'argparse': if args and args[0] == '': # no short option args = args[1:] return self.parser.add_argument(*args, **kwargs) else: return self.parser.add_option(*args, **kwargs)
def delete ( filething ) : t = MP4 ( filething ) filething . fileobj . seek ( 0 ) t . delete ( filething )
1
rip and tear mp3 file for python
delete ( filething )
cosqa-train-14525
def delete(filething): """ delete(filething) Arguments: filething (filething) Raises: mutagen.MutagenError Remove tags from a file. """ t = MP4(filething) filething.fileobj.seek(0) t.delete(filething)
def __init__ ( self , name , flag , * * kwargs ) : self . name = name self . flag = flag self . options = kwargs
1
python argparse customize action
Argument class constructor should be used inside a class that inherits the BaseAction class .
cosqa-train-14526
def __init__(self, name, flag, **kwargs): """ Argument class constructor, should be used inside a class that inherits the BaseAction class. :param name(str): the optional argument name to be used with two slahes (--cmd) :param flag(str): a short flag for the argument (-c) :param \*\*kwargs: all keywords arguments supported for argparse actions. """ self.name = name self.flag = flag self.options = kwargs
def get_system_root_directory ( ) : root = os . path . dirname ( __file__ ) root = os . path . dirname ( root ) root = os . path . abspath ( root ) return root
1
root of the current python file
Get system root directory ( application installed root directory )
cosqa-train-14527
def get_system_root_directory(): """ Get system root directory (application installed root directory) Returns ------- string A full path """ root = os.path.dirname(__file__) root = os.path.dirname(root) root = os.path.abspath(root) return root
def list_get ( l , idx , default = None ) : try : if l [ idx ] : return l [ idx ] else : return default except IndexError : return default
1
python array get element by index with default
Get from a list with an optional default value .
cosqa-train-14528
def list_get(l, idx, default=None): """ Get from a list with an optional default value. """ try: if l[idx]: return l[idx] else: return default except IndexError: return default
def intround ( value ) : return int ( decimal . Decimal . from_float ( value ) . to_integral_value ( decimal . ROUND_HALF_EVEN ) )
1
round down float to int python
Given a float returns a rounded int . Should give the same result on both Py2 / 3
cosqa-train-14529
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 be_array_from_bytes ( fmt , data ) : arr = array . array ( str ( fmt ) , data ) return fix_byteorder ( arr )
1
python array to bigendian
Reads an array from bytestring with big - endian data .
cosqa-train-14530
def be_array_from_bytes(fmt, data): """ Reads an array from bytestring with big-endian data. """ arr = array.array(str(fmt), data) return fix_byteorder(arr)
def round_array ( array_in ) : if isinstance ( array_in , ndarray ) : return np . round ( array_in ) . astype ( int ) else : return int ( np . round ( array_in ) )
1
round numbers in array to nearest whole python
arr_out = round_array ( array_in )
cosqa-train-14531
def round_array(array_in): """ arr_out = round_array(array_in) Rounds an array and recasts it to int. Also works on scalars. """ if isinstance(array_in, ndarray): return np.round(array_in).astype(int) else: return int(np.round(array_in))
def c_array ( ctype , values ) : if isinstance ( values , np . ndarray ) and values . dtype . itemsize == ctypes . sizeof ( ctype ) : return ( ctype * len ( values ) ) . from_buffer_copy ( values ) return ( ctype * len ( values ) ) ( * values )
0
python array wrap ctype array
Convert a python string to c array .
cosqa-train-14532
def c_array(ctype, values): """Convert a python string to c array.""" if isinstance(values, np.ndarray) and values.dtype.itemsize == ctypes.sizeof(ctype): return (ctype * len(values)).from_buffer_copy(values) return (ctype * len(values))(*values)
def round_to_float ( number , precision ) : rounded = Decimal ( str ( floor ( ( number + precision / 2 ) // precision ) ) ) * Decimal ( str ( precision ) ) return float ( rounded )
1
round to precision python
Round a float to a precision
cosqa-train-14533
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 access_ok ( self , access ) : for c in access : if c not in self . perms : return False return True
1
python asking forgiveness, not permission
Check if there is enough permissions for access
cosqa-train-14534
def access_ok(self, access): """ Check if there is enough permissions for access """ for c in access: if c not in self.perms: return False return True
def rstjinja ( app , docname , source ) : # Make sure we're outputting HTML if app . builder . format != 'html' : return src = source [ 0 ] rendered = app . builder . templates . render_string ( src , app . config . html_context ) source [ 0 ] = rendered
1
run functions parrale flask python jinja2
Render our pages as a jinja template for fancy templating goodness .
cosqa-train-14535
def rstjinja(app, docname, source): """ Render our pages as a jinja template for fancy templating goodness. """ # Make sure we're outputting HTML if app.builder.format != 'html': return src = source[0] rendered = app.builder.templates.render_string( src, app.config.html_context ) source[0] = rendered
def _assert_is_type ( name , value , value_type ) : if not isinstance ( value , value_type ) : if type ( value_type ) is tuple : types = ', ' . join ( t . __name__ for t in value_type ) raise ValueError ( '{0} must be one of ({1})' . format ( name , types ) ) else : raise ValueError ( '{0} must be {1}' . format ( name , value_type . __name__ ) )
1
python assert value is of type
Assert that a value must be a given type .
cosqa-train-14536
def _assert_is_type(name, value, value_type): """Assert that a value must be a given type.""" if not isinstance(value, value_type): if type(value_type) is tuple: types = ', '.join(t.__name__ for t in value_type) raise ValueError('{0} must be one of ({1})'.format(name, types)) else: raise ValueError('{0} must be {1}' .format(name, value_type.__name__))
def install_postgres ( user = None , dbname = None , password = None ) : execute ( pydiploy . django . install_postgres_server , user = user , dbname = dbname , password = password )
1
run postgres and python on same docker image
Install Postgres on remote
cosqa-train-14537
def install_postgres(user=None, dbname=None, password=None): """Install Postgres on remote""" execute(pydiploy.django.install_postgres_server, user=user, dbname=dbname, password=password)
def web ( host , port ) : from . webserver . web import get_app get_app ( ) . run ( host = host , port = port )
1
running python on your webserver
Start web application
cosqa-train-14538
def web(host, port): """Start web application""" from .webserver.web import get_app get_app().run(host=host, port=port)
async def list ( source ) : result = [ ] async with streamcontext ( source ) as streamer : async for item in streamer : result . append ( item ) yield result
1
python asyncio task multipe
Generate a single list from an asynchronous sequence .
cosqa-train-14539
async def list(source): """Generate a single list from an asynchronous sequence.""" result = [] async with streamcontext(source) as streamer: async for item in streamer: result.append(item) yield result
def s3 ( ctx , bucket_name , data_file , region ) : if not ctx . data_file : ctx . data_file = data_file if not ctx . bucket_name : ctx . bucket_name = bucket_name if not ctx . region : ctx . region = region ctx . type = 's3'
1
s3 sync between bucket python
Use the S3 SWAG backend .
cosqa-train-14540
def s3(ctx, bucket_name, data_file, region): """Use the S3 SWAG backend.""" if not ctx.data_file: ctx.data_file = data_file if not ctx.bucket_name: ctx.bucket_name = bucket_name if not ctx.region: ctx.region = region ctx.type = 's3'
def StringIO ( * args , * * kwargs ) : raw = sync_io . StringIO ( * args , * * kwargs ) return AsyncStringIOWrapper ( raw )
1
python asyncore to asyncio
StringIO constructor shim for the async wrapper .
cosqa-train-14541
def StringIO(*args, **kwargs): """StringIO constructor shim for the async wrapper.""" raw = sync_io.StringIO(*args, **kwargs) return AsyncStringIOWrapper(raw)
def save_pdf ( path ) : pp = PdfPages ( path ) pp . savefig ( pyplot . gcf ( ) ) pp . close ( )
1
save figure to pdf python
Saves a pdf of the current matplotlib figure .
cosqa-train-14542
def save_pdf(path): """ Saves a pdf of the current matplotlib figure. :param path: str, filepath to save to """ pp = PdfPages(path) pp.savefig(pyplot.gcf()) pp.close()
def creation_time ( self ) : timestamp = self . _fsntfs_attribute . get_creation_time_as_integer ( ) return dfdatetime_filetime . Filetime ( timestamp = timestamp )
1
python attribute for file date created
dfdatetime . Filetime : creation time or None if not set .
cosqa-train-14543
def creation_time(self): """dfdatetime.Filetime: creation time or None if not set.""" timestamp = self._fsntfs_attribute.get_creation_time_as_integer() return dfdatetime_filetime.Filetime(timestamp=timestamp)
def download_file ( save_path , file_url ) : r = requests . get ( file_url ) # create HTTP response object with open ( save_path , 'wb' ) as f : f . write ( r . content ) return save_path
1
savehttp response to a file python
Download file from http url link
cosqa-train-14544
def download_file(save_path, file_url): """ Download file from http url link """ r = requests.get(file_url) # create HTTP response object with open(save_path, 'wb') as f: f.write(r.content) return save_path
def nmse ( a , b ) : return np . square ( a - b ) . mean ( ) / ( a . mean ( ) * b . mean ( ) )
1
python average of 2 function
Returns the normalized mean square error of a and b
cosqa-train-14545
def nmse(a, b): """Returns the normalized mean square error of a and b """ return np.square(a - b).mean() / (a.mean() * b.mean())
def save_pdf ( path ) : pp = PdfPages ( path ) pp . savefig ( pyplot . gcf ( ) ) pp . close ( )
1
saving figure as pdf python
Saves a pdf of the current matplotlib figure .
cosqa-train-14546
def save_pdf(path): """ Saves a pdf of the current matplotlib figure. :param path: str, filepath to save to """ pp = PdfPages(path) pp.savefig(pyplot.gcf()) pp.close()
def safe_rmtree ( directory ) : if os . path . exists ( directory ) : shutil . rmtree ( directory , True )
1
python best way to delete directory
Delete a directory if it s present . If it s not present no - op .
cosqa-train-14547
def safe_rmtree(directory): """Delete a directory if it's present. If it's not present, no-op.""" if os.path.exists(directory): shutil.rmtree(directory, True)
def _rescale_array ( self , array , scale , zero ) : if scale != 1.0 : sval = numpy . array ( scale , dtype = array . dtype ) array *= sval if zero != 0.0 : zval = numpy . array ( zero , dtype = array . dtype ) array += zval
1
scale 1d array python to between 0 and 1
Scale the input array
cosqa-train-14548
def _rescale_array(self, array, scale, zero): """ Scale the input array """ if scale != 1.0: sval = numpy.array(scale, dtype=array.dtype) array *= sval if zero != 0.0: zval = numpy.array(zero, dtype=array.dtype) array += zval
def set_scrollregion ( self , event = None ) : self . canvas . configure ( scrollregion = self . canvas . bbox ( 'all' ) )
1
python bind scrollbar to canvas
Set the scroll region on the canvas
cosqa-train-14549
def set_scrollregion(self, event=None): """ Set the scroll region on the canvas""" self.canvas.configure(scrollregion=self.canvas.bbox('all'))
def extract_vars_above ( * names ) : callerNS = sys . _getframe ( 2 ) . f_locals return dict ( ( k , callerNS [ k ] ) for k in names )
1
scope of variables in same function in python
Extract a set of variables by name from another frame .
cosqa-train-14550
def extract_vars_above(*names): """Extract a set of variables by name from another frame. Similar to extractVars(), but with a specified depth of 1, so that names are exctracted exactly from above the caller. This is simply a convenience function so that the very common case (for us) of skipping exactly 1 frame doesn't have to construct a special dict for keyword passing.""" callerNS = sys._getframe(2).f_locals return dict((k,callerNS[k]) for k in names)
def __init__ ( self , name , contained_key ) : self . name = name self . contained_key = contained_key
1
python boto3 create containor
Instantiate an anonymous file - based Bucket around a single key .
cosqa-train-14551
def __init__(self, name, contained_key): """Instantiate an anonymous file-based Bucket around a single key. """ self.name = name self.contained_key = contained_key
def is_nullable_list ( val , vtype ) : return ( isinstance ( val , list ) and any ( isinstance ( v , vtype ) for v in val ) and all ( ( isinstance ( v , vtype ) or v is None ) for v in val ) )
1
see if a list is null in python
Return True if list contains either values of type vtype or None .
cosqa-train-14552
def is_nullable_list(val, vtype): """Return True if list contains either values of type `vtype` or None.""" return (isinstance(val, list) and any(isinstance(v, vtype) for v in val) and all((isinstance(v, vtype) or v is None) for v in val))
def remove_file_from_s3 ( awsclient , bucket , key ) : client_s3 = awsclient . get_client ( 's3' ) response = client_s3 . delete_object ( Bucket = bucket , Key = key )
1
python boto3 delete key from s3
Remove a file from an AWS S3 bucket .
cosqa-train-14553
def remove_file_from_s3(awsclient, bucket, key): """Remove a file from an AWS S3 bucket. :param awsclient: :param bucket: :param key: :return: """ client_s3 = awsclient.get_client('s3') response = client_s3.delete_object(Bucket=bucket, Key=key)
def get_public_members ( obj ) : return { attr : getattr ( obj , attr ) for attr in dir ( obj ) if not attr . startswith ( "_" ) and not hasattr ( getattr ( obj , attr ) , '__call__' ) }
1
see properties of an object python
Retrieves a list of member - like objects ( members or properties ) that are publically exposed .
cosqa-train-14554
def get_public_members(obj): """ Retrieves a list of member-like objects (members or properties) that are publically exposed. :param obj: The object to probe. :return: A list of strings. """ return {attr: getattr(obj, attr) for attr in dir(obj) if not attr.startswith("_") and not hasattr(getattr(obj, attr), '__call__')}
def compute_boxplot ( self , series ) : from matplotlib . cbook import boxplot_stats series = series [ series . notnull ( ) ] if len ( series . values ) == 0 : return { } elif not is_numeric_dtype ( series ) : return self . non_numeric_stats ( series ) stats = boxplot_stats ( list ( series . values ) ) [ 0 ] stats [ 'count' ] = len ( series . values ) stats [ 'fliers' ] = "|" . join ( map ( str , stats [ 'fliers' ] ) ) return stats
1
python box plot value
Compute boxplot for given pandas Series .
cosqa-train-14555
def compute_boxplot(self, series): """ Compute boxplot for given pandas Series. """ from matplotlib.cbook import boxplot_stats series = series[series.notnull()] if len(series.values) == 0: return {} elif not is_numeric_dtype(series): return self.non_numeric_stats(series) stats = boxplot_stats(list(series.values))[0] stats['count'] = len(series.values) stats['fliers'] = "|".join(map(str, stats['fliers'])) return stats
def Any ( a , axis , keep_dims ) : return np . any ( a , axis = axis if not isinstance ( axis , np . ndarray ) else tuple ( axis ) , keepdims = keep_dims ) ,
1
select all components in array python numpy
Any reduction op .
cosqa-train-14556
def Any(a, axis, keep_dims): """ Any reduction op. """ return np.any(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis), keepdims=keep_dims),
def compute_boxplot ( self , series ) : from matplotlib . cbook import boxplot_stats series = series [ series . notnull ( ) ] if len ( series . values ) == 0 : return { } elif not is_numeric_dtype ( series ) : return self . non_numeric_stats ( series ) stats = boxplot_stats ( list ( series . values ) ) [ 0 ] stats [ 'count' ] = len ( series . values ) stats [ 'fliers' ] = "|" . join ( map ( str , stats [ 'fliers' ] ) ) return stats
1
python boxplot min max q1 median to number summary
Compute boxplot for given pandas Series .
cosqa-train-14557
def compute_boxplot(self, series): """ Compute boxplot for given pandas Series. """ from matplotlib.cbook import boxplot_stats series = series[series.notnull()] if len(series.values) == 0: return {} elif not is_numeric_dtype(series): return self.non_numeric_stats(series) stats = boxplot_stats(list(series.values))[0] stats['count'] = len(series.values) stats['fliers'] = "|".join(map(str, stats['fliers'])) return stats
def selectin ( table , field , value , complement = False ) : return select ( table , field , lambda v : v in value , complement = complement )
1
select rows isin python notin
Select rows where the given field is a member of the given value .
cosqa-train-14558
def selectin(table, field, value, complement=False): """Select rows where the given field is a member of the given value.""" return select(table, field, lambda v: v in value, complement=complement)
def compute_boxplot ( self , series ) : from matplotlib . cbook import boxplot_stats series = series [ series . notnull ( ) ] if len ( series . values ) == 0 : return { } elif not is_numeric_dtype ( series ) : return self . non_numeric_stats ( series ) stats = boxplot_stats ( list ( series . values ) ) [ 0 ] stats [ 'count' ] = len ( series . values ) stats [ 'fliers' ] = "|" . join ( map ( str , stats [ 'fliers' ] ) ) return stats
1
python boxplot not working
Compute boxplot for given pandas Series .
cosqa-train-14559
def compute_boxplot(self, series): """ Compute boxplot for given pandas Series. """ from matplotlib.cbook import boxplot_stats series = series[series.notnull()] if len(series.values) == 0: return {} elif not is_numeric_dtype(series): return self.non_numeric_stats(series) stats = boxplot_stats(list(series.values))[0] stats['count'] = len(series.values) stats['fliers'] = "|".join(map(str, stats['fliers'])) return stats
def uncheck ( self , locator = None , allow_label_click = None , * * kwargs ) : self . _check_with_label ( "checkbox" , False , locator = locator , allow_label_click = allow_label_click , * * kwargs )
1
selenim uncheck box python
Find a check box and uncheck it . The check box can be found via name id or label text . ::
cosqa-train-14560
def uncheck(self, locator=None, allow_label_click=None, **kwargs): """ Find a check box and uncheck it. The check box can be found via name, id, or label text. :: page.uncheck("German") Args: locator (str, optional): Which check box to uncheck. allow_label_click (bool, optional): Attempt to click the label to toggle state if element is non-visible. Defaults to :data:`capybara.automatic_label_click`. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. """ self._check_with_label( "checkbox", False, locator=locator, allow_label_click=allow_label_click, **kwargs)
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 buffer is smaller than requested size
Reads a stream discarding the data read and returns its size .
cosqa-train-14561
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 upload_as_json ( name , mylist ) : location = list ( IPList . objects . filter ( name ) ) if location : iplist = location [ 0 ] return iplist . upload ( json = mylist , as_type = 'json' )
1
send python list as json django
Upload the IPList as json payload .
cosqa-train-14562
def upload_as_json(name, mylist): """ Upload the IPList as json payload. :param str name: name of IPList :param list: list of IPList entries :return: None """ location = list(IPList.objects.filter(name)) if location: iplist = location[0] return iplist.upload(json=mylist, as_type='json')
def comma_delimited_to_list ( list_param ) : if isinstance ( list_param , list ) : return list_param if isinstance ( list_param , str ) : return list_param . split ( ',' ) else : return [ ]
1
python build comma separated list
Convert comma - delimited list / string into a list of strings
cosqa-train-14563
def comma_delimited_to_list(list_param): """Convert comma-delimited list / string into a list of strings :param list_param: Comma-delimited string :type list_param: str | unicode :return: A list of strings :rtype: list """ if isinstance(list_param, list): return list_param if isinstance(list_param, str): return list_param.split(',') else: return []
def __getattr__ ( self , * args , * * kwargs ) : return xmlrpc . client . _Method ( self . __request , * args , * * kwargs )
1
send xmlrpc over python requests
Magic method dispatcher
cosqa-train-14564
def __getattr__(self, *args, **kwargs): """ Magic method dispatcher """ return xmlrpc.client._Method(self.__request, *args, **kwargs)
def getbyteslice ( self , start , end ) : c = self . _rawarray [ start : end ] return c
1
python byte array slicing
Direct access to byte data .
cosqa-train-14565
def getbyteslice(self, start, end): """Direct access to byte data.""" c = self._rawarray[start:end] return c
def get_serializable_data_for_fields ( model ) : pk_field = model . _meta . pk # If model is a child via multitable inheritance, use parent's pk while pk_field . remote_field and pk_field . remote_field . parent_link : pk_field = pk_field . remote_field . model . _meta . pk obj = { 'pk' : get_field_value ( pk_field , model ) } for field in model . _meta . fields : if field . serialize : obj [ field . name ] = get_field_value ( field , model ) return obj
1
serializer database model python model relation
Return a serialised version of the model s fields which exist as local database columns ( i . e . excluding m2m and incoming foreign key relations )
cosqa-train-14566
def get_serializable_data_for_fields(model): """ Return a serialised version of the model's fields which exist as local database columns (i.e. excluding m2m and incoming foreign key relations) """ pk_field = model._meta.pk # If model is a child via multitable inheritance, use parent's pk while pk_field.remote_field and pk_field.remote_field.parent_link: pk_field = pk_field.remote_field.model._meta.pk obj = {'pk': get_field_value(pk_field, model)} for field in model._meta.fields: if field.serialize: obj[field.name] = get_field_value(field, model) return obj
def __init__ ( self , ba = None ) : self . bytearray = ba or ( bytearray ( b'\0' ) * self . SIZEOF )
1
python bytearray no init
Constructor .
cosqa-train-14567
def __init__(self, ba=None): """Constructor.""" self.bytearray = ba or (bytearray(b'\0') * self.SIZEOF)
def setRect ( self , rect ) : self . x , self . y , self . w , self . h = rect
1
set a rect to a variable python
Sets the window bounds from a tuple of ( x y w h )
cosqa-train-14568
def setRect(self, rect): """ Sets the window bounds from a tuple of (x,y,w,h) """ self.x, self.y, self.w, self.h = rect
def calc_base64 ( s ) : s = compat . to_bytes ( s ) s = compat . base64_encodebytes ( s ) . strip ( ) # return bytestring return compat . to_native ( s )
1
python bytes to base64 \n
Return base64 encoded binarystring .
cosqa-train-14569
def calc_base64(s): """Return base64 encoded binarystring.""" s = compat.to_bytes(s) s = compat.base64_encodebytes(s).strip() # return bytestring return compat.to_native(s)
def plot_target ( target , ax ) : ax . scatter ( target [ 0 ] , target [ 1 ] , target [ 2 ] , c = "red" , s = 80 )
1
set color for scatter plot in python
Ajoute la target au plot
cosqa-train-14570
def plot_target(target, ax): """Ajoute la target au plot""" ax.scatter(target[0], target[1], target[2], c="red", s=80)
def prsint ( string ) : string = stypes . stringToCharP ( string ) intval = ctypes . c_int ( ) libspice . prsint_c ( string , ctypes . byref ( intval ) ) return intval . value
1
python c api parse string to number
Parse a string as an integer encapsulating error handling .
cosqa-train-14571
def prsint(string): """ Parse a string as an integer, encapsulating error handling. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/prsint_c.html :param string: String representing an integer. :type string: str :return: Integer value obtained by parsing string. :rtype: int """ string = stypes.stringToCharP(string) intval = ctypes.c_int() libspice.prsint_c(string, ctypes.byref(intval)) return intval.value
def set_default ( self , key , value ) : k = self . _real_key ( key . lower ( ) ) self . _defaults [ k ] = value
1
set default for all key in dict python
Set the default value for this key . Default only used when no value is provided by the user via arg config or env .
cosqa-train-14572
def set_default(self, key, value): """Set the default value for this key. Default only used when no value is provided by the user via arg, config or env. """ k = self._real_key(key.lower()) self._defaults[k] = value
def struct2dict ( struct ) : return { x : getattr ( struct , x ) for x in dict ( struct . _fields_ ) . keys ( ) }
1
python c structure to dict
convert a ctypes structure to a dictionary
cosqa-train-14573
def struct2dict(struct): """convert a ctypes structure to a dictionary""" return {x: getattr(struct, x) for x in dict(struct._fields_).keys()}
def set_logxticks_for_all ( self , row_column_list = None , logticks = None ) : if row_column_list is None : self . ticks [ 'x' ] = [ '1e%d' % u for u in logticks ] else : for row , column in row_column_list : self . set_logxticks ( row , column , logticks )
1
set log scale axis labels ticks, python
Manually specify the x - axis log tick values .
cosqa-train-14574
def set_logxticks_for_all(self, row_column_list=None, logticks=None): """Manually specify the x-axis log tick values. :param row_column_list: a list containing (row, column) tuples to specify the subplots, or None to indicate *all* subplots. :type row_column_list: list or None :param logticks: logarithm of the locations for the ticks along the axis. For example, if you specify [1, 2, 3], ticks will be placed at 10, 100 and 1000. """ if row_column_list is None: self.ticks['x'] = ['1e%d' % u for u in logticks] else: for row, column in row_column_list: self.set_logxticks(row, column, logticks)
def testable_memoized_property ( func = None , key_factory = per_instance , * * kwargs ) : getter = memoized_method ( func = func , key_factory = key_factory , * * kwargs ) def setter ( self , val ) : with getter . put ( self ) as putter : putter ( val ) return property ( fget = getter , fset = setter , fdel = lambda self : getter . forget ( self ) )
1
python cache properties for an immutable object
A variant of memoized_property that allows for setting of properties ( for tests etc ) .
cosqa-train-14575
def testable_memoized_property(func=None, key_factory=per_instance, **kwargs): """A variant of `memoized_property` that allows for setting of properties (for tests, etc).""" getter = memoized_method(func=func, key_factory=key_factory, **kwargs) def setter(self, val): with getter.put(self) as putter: putter(val) return property(fget=getter, fset=setter, fdel=lambda self: getter.forget(self))
def table_width ( self ) : outer_widths = max_dimensions ( self . table_data , self . padding_left , self . padding_right ) [ 2 ] outer_border = 2 if self . outer_border else 0 inner_border = 1 if self . inner_column_border else 0 return table_width ( outer_widths , outer_border , inner_border )
1
set table widget cell width python
Return the width of the table including padding and borders .
cosqa-train-14576
def table_width(self): """Return the width of the table including padding and borders.""" outer_widths = max_dimensions(self.table_data, self.padding_left, self.padding_right)[2] outer_border = 2 if self.outer_border else 0 inner_border = 1 if self.inner_column_border else 0 return table_width(outer_widths, outer_border, inner_border)
def is_cached ( self , url ) : try : return True if url in self . cache else False except TypeError : return False
0
python cache url calls
Checks if specified URL is cached .
cosqa-train-14577
def is_cached(self, url): """Checks if specified URL is cached.""" try: return True if url in self.cache else False except TypeError: return False
def set_xlimits_widgets ( self , set_min = True , set_max = True ) : xmin , xmax = self . tab_plot . ax . get_xlim ( ) if set_min : self . w . x_lo . set_text ( '{0}' . format ( xmin ) ) if set_max : self . w . x_hi . set_text ( '{0}' . format ( xmax ) )
0
set x axis limits in python
Populate axis limits GUI with current plot values .
cosqa-train-14578
def set_xlimits_widgets(self, set_min=True, set_max=True): """Populate axis limits GUI with current plot values.""" xmin, xmax = self.tab_plot.ax.get_xlim() if set_min: self.w.x_lo.set_text('{0}'.format(xmin)) if set_max: self.w.x_hi.set_text('{0}'.format(xmax))
def ttl ( self ) : ret = 3600 cn = self . get_process ( ) if "ttl" in cn : ret = cn [ "ttl" ] return ret
0
python caching intermediate results
how long you should cache results for cacheable queries
cosqa-train-14579
def ttl(self): """how long you should cache results for cacheable queries""" ret = 3600 cn = self.get_process() if "ttl" in cn: ret = cn["ttl"] return ret
def set_xlimits ( self , min = None , max = None ) : self . limits [ 'xmin' ] = min self . limits [ 'xmax' ] = max
1
set xaxis limibts python
Set limits for the x - axis .
cosqa-train-14580
def set_xlimits(self, min=None, max=None): """Set limits for the x-axis. :param min: minimum value to be displayed. If None, it will be calculated. :param max: maximum value to be displayed. If None, it will be calculated. """ self.limits['xmin'] = min self.limits['xmax'] = max
def manhattan_distance_numpy ( object1 , object2 ) : return numpy . sum ( numpy . absolute ( object1 - object2 ) , axis = 1 ) . T
1
python calculate manhattan distance between two arrays
!
cosqa-train-14581
def manhattan_distance_numpy(object1, object2): """! @brief Calculate Manhattan distance between two objects using numpy. @param[in] object1 (array_like): The first array_like object. @param[in] object2 (array_like): The second array_like object. @return (double) Manhattan distance between two objects. """ return numpy.sum(numpy.absolute(object1 - object2), axis=1).T
def add_xlabel ( self , text = None ) : x = self . fit . meta [ 'independent' ] if not text : text = '$' + x [ 'tex_symbol' ] + r'$ $(\si{' + x [ 'siunitx' ] + r'})$' self . plt . set_xlabel ( text )
1
set xtick label incline python
Add a label to the x - axis .
cosqa-train-14582
def add_xlabel(self, text=None): """ Add a label to the x-axis. """ x = self.fit.meta['independent'] if not text: text = '$' + x['tex_symbol'] + r'$ $(\si{' + x['siunitx'] + r'})$' self.plt.set_xlabel(text)
def get_model ( name ) : model = MODELS . get ( name . lower ( ) , None ) assert model , "Could not locate model by name '%s'" % name return model
1
python call model name
Convert a model s verbose name to the model class . This allows us to use the models verbose name in steps .
cosqa-train-14583
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 test ( ) : # pragma: no cover import pytest import os pytest . main ( [ os . path . dirname ( os . path . abspath ( __file__ ) ) ] )
1
python calling pytest from a python script
Execute the unit tests on an installed copy of unyt .
cosqa-train-14584
def test(): # pragma: no cover """Execute the unit tests on an installed copy of unyt. Note that this function requires pytest to run. If pytest is not installed this function will raise ImportError. """ import pytest import os pytest.main([os.path.dirname(os.path.abspath(__file__))])
def stft ( func = None , * * kwparams ) : from numpy . fft import fft , ifft return stft . base ( transform = fft , inverse_transform = ifft ) ( func , * * kwparams )
1
short time fourier transform python
Short Time Fourier Transform for complex data .
cosqa-train-14585
def stft(func=None, **kwparams): """ Short Time Fourier Transform for complex data. Same to the default STFT strategy, but with new defaults. This is the same to: .. code-block:: python stft.base(transform=numpy.fft.fft, inverse_transform=numpy.fft.ifft) See ``stft.base`` docs for more. """ from numpy.fft import fft, ifft return stft.base(transform=fft, inverse_transform=ifft)(func, **kwparams)
def _fill ( self ) : try : self . _head = self . _iterable . next ( ) except StopIteration : self . _head = None
0
python can i modify an iterator
Advance the iterator without returning the old head .
cosqa-train-14586
def _fill(self): """Advance the iterator without returning the old head.""" try: self._head = self._iterable.next() except StopIteration: self._head = None
def prettyprint ( d ) : print ( json . dumps ( d , sort_keys = True , indent = 4 , separators = ( "," , ": " ) ) )
1
show json tree python
Print dicttree in Json - like format . keys are sorted
cosqa-train-14587
def prettyprint(d): """Print dicttree in Json-like format. keys are sorted """ print(json.dumps(d, sort_keys=True, indent=4, separators=("," , ": ")))
def sdmethod ( meth ) : sd = singledispatch ( meth ) def wrapper ( obj , * args , * * kwargs ) : return sd . dispatch ( args [ 0 ] . __class__ ) ( obj , * args , * * kwargs ) wrapper . register = sd . register wrapper . dispatch = sd . dispatch wrapper . registry = sd . registry wrapper . _clear_cache = sd . _clear_cache functools . update_wrapper ( wrapper , meth ) return wrapper
1
python can you monkey patch methods on an object
This is a hack to monkey patch sdproperty to work as expected with instance methods .
cosqa-train-14588
def sdmethod(meth): """ This is a hack to monkey patch sdproperty to work as expected with instance methods. """ sd = singledispatch(meth) def wrapper(obj, *args, **kwargs): return sd.dispatch(args[0].__class__)(obj, *args, **kwargs) wrapper.register = sd.register wrapper.dispatch = sd.dispatch wrapper.registry = sd.registry wrapper._clear_cache = sd._clear_cache functools.update_wrapper(wrapper, meth) return wrapper
def _match_literal ( self , a , b = None ) : return a . lower ( ) == b if not self . case_sensitive else a == b
1
similar match function in python
Match two names .
cosqa-train-14589
def _match_literal(self, a, b=None): """Match two names.""" return a.lower() == b if not self.case_sensitive else a == b
def to_capitalized_camel_case ( snake_case_string ) : parts = snake_case_string . split ( '_' ) return '' . join ( [ i . title ( ) for i in parts ] )
0
python capitalize function to capitalize the first letter
Convert a string from snake case to camel case with the first letter capitalized . For example some_var would become SomeVar .
cosqa-train-14590
def to_capitalized_camel_case(snake_case_string): """ Convert a string from snake case to camel case with the first letter capitalized. For example, "some_var" would become "SomeVar". :param snake_case_string: Snake-cased string to convert to camel case. :returns: Camel-cased version of snake_case_string. """ parts = snake_case_string.split('_') return ''.join([i.title() for i in parts])
def query ( self , base , filterstr , attrlist = None ) : return self . conn . search_s ( base , ldap . SCOPE_SUBTREE , filterstr , attrlist )
1
simple ldap query in python
wrapper to search_s
cosqa-train-14591
def query(self, base, filterstr, attrlist=None): """ wrapper to search_s """ return self.conn.search_s(base, ldap.SCOPE_SUBTREE, filterstr, attrlist)
def angle_to_cartesian ( lon , lat ) : theta = np . array ( np . pi / 2. - lat ) return np . vstack ( ( np . sin ( theta ) * np . cos ( lon ) , np . sin ( theta ) * np . sin ( lon ) , np . cos ( theta ) ) ) . T
1
python cartesian to spherical coordinate
Convert spherical coordinates to cartesian unit vectors .
cosqa-train-14592
def angle_to_cartesian(lon, lat): """Convert spherical coordinates to cartesian unit vectors.""" theta = np.array(np.pi / 2. - lat) return np.vstack((np.sin(theta) * np.cos(lon), np.sin(theta) * np.sin(lon), np.cos(theta))).T
def shutdown ( self ) : if self . sock : self . sock . close ( ) self . sock = None self . connected = False
1
simulate cutting a socket connection python
close socket immediately .
cosqa-train-14593
def shutdown(self): """close socket, immediately.""" if self.sock: self.sock.close() self.sock = None self.connected = False
def bin_to_int ( string ) : if isinstance ( string , str ) : return struct . unpack ( "b" , string ) [ 0 ] else : return struct . unpack ( "b" , bytes ( [ string ] ) ) [ 0 ]
1
python cast signed int
Convert a one element byte string to signed int for python 2 support .
cosqa-train-14594
def bin_to_int(string): """Convert a one element byte string to signed int for python 2 support.""" if isinstance(string, str): return struct.unpack("b", string)[0] else: return struct.unpack("b", bytes([string]))[0]
def advance_one_line ( self ) : current_line = self . _current_token . line_number while current_line == self . _current_token . line_number : self . _current_token = ConfigParser . Token ( * next ( self . _token_generator ) )
1
skip to next line python
Advances to next line .
cosqa-train-14595
def advance_one_line(self): """Advances to next line.""" current_line = self._current_token.line_number while current_line == self._current_token.line_number: self._current_token = ConfigParser.Token(*next(self._token_generator))
def solve ( A , x ) : # https://stackoverflow.com/a/48387507/353337 x = numpy . asarray ( x ) return numpy . linalg . solve ( A , x . reshape ( x . shape [ 0 ] , - 1 ) ) . reshape ( x . shape )
0
solving lwast squares of matrix in python
Solves a linear equation system with a matrix of shape ( n n ) and an array of shape ( n ... ) . The output has the same shape as the second argument .
cosqa-train-14596
def solve(A, x): """Solves a linear equation system with a matrix of shape (n, n) and an array of shape (n, ...). The output has the same shape as the second argument. """ # https://stackoverflow.com/a/48387507/353337 x = numpy.asarray(x) return numpy.linalg.solve(A, x.reshape(x.shape[0], -1)).reshape(x.shape)
def _to_numeric ( val ) : if isinstance ( val , ( int , float , datetime . datetime , datetime . timedelta ) ) : return val return float ( val )
1
python cast true or false as numbers
Helper function for conversion of various data types into numeric representation .
cosqa-train-14597
def _to_numeric(val): """ Helper function for conversion of various data types into numeric representation. """ if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)): return val return float(val)
def sort_data ( x , y ) : xy = sorted ( zip ( x , y ) ) x , y = zip ( * xy ) return x , y
1
sort on x then y python
Sort the data .
cosqa-train-14598
def sort_data(x, y): """Sort the data.""" xy = sorted(zip(x, y)) x, y = zip(*xy) return x, y
def str_to_boolean ( input_str ) : if not isinstance ( input_str , six . string_types ) : raise ValueError ( input_str ) input_str = str_quote_stripper ( input_str ) return input_str . lower ( ) in ( "true" , "t" , "1" , "y" , "yes" )
1
python casting a bool as a string
a conversion function for boolean
cosqa-train-14599
def str_to_boolean(input_str): """ a conversion function for boolean """ if not isinstance(input_str, six.string_types): raise ValueError(input_str) input_str = str_quote_stripper(input_str) return input_str.lower() in ("true", "t", "1", "y", "yes")