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 each_img ( dir_path ) : for fname in os . listdir ( dir_path ) : if fname . endswith ( '.jpg' ) or fname . endswith ( '.png' ) or fname . endswith ( '.bmp' ) : yield fname
1
cycle through a folder of images python
Iterates through each image in the given directory . ( not recursive ) : param dir_path : Directory path where images files are present : return : Iterator to iterate through image files
cosqa-train-15200
def each_img(dir_path): """ Iterates through each image in the given directory. (not recursive) :param dir_path: Directory path where images files are present :return: Iterator to iterate through image files """ for fname in os.listdir(dir_path): if fname.endswith('.jpg') or fname.endswith('.png') or fname.endswith('.bmp'): yield fname
def multidict_to_dict ( d ) : return dict ( ( k , v [ 0 ] if len ( v ) == 1 else v ) for k , v in iterlists ( d ) )
0
python flask parse immutablemultidict
Turns a werkzeug . MultiDict or django . MultiValueDict into a dict with list values : param d : a MultiDict or MultiValueDict instance : return : a dict instance
cosqa-train-15201
def multidict_to_dict(d): """ Turns a werkzeug.MultiDict or django.MultiValueDict into a dict with list values :param d: a MultiDict or MultiValueDict instance :return: a dict instance """ return dict((k, v[0] if len(v) == 1 else v) for k, v in iterlists(d))
def _join ( verb ) : data = pd . merge ( verb . x , verb . y , * * verb . kwargs ) # Preserve x groups if isinstance ( verb . x , GroupedDataFrame ) : data . plydata_groups = list ( verb . x . plydata_groups ) return data
0
data frame merge outer join python
Join helper
cosqa-train-15202
def _join(verb): """ Join helper """ data = pd.merge(verb.x, verb.y, **verb.kwargs) # Preserve x groups if isinstance(verb.x, GroupedDataFrame): data.plydata_groups = list(verb.x.plydata_groups) return data
def pretty_print_post ( req ) : print ( ( '{}\n{}\n{}\n\n{}' . format ( '-----------START-----------' , req . method + ' ' + req . url , '\n' . join ( '{}: {}' . format ( k , v ) for k , v in list ( req . headers . items ( ) ) ) , req . body , ) ) )
0
python flask print all request message
Helper to print a prepared query . Useful to debug a POST query .
cosqa-train-15203
def pretty_print_post(req): """Helper to print a "prepared" query. Useful to debug a POST query. However pay attention at the formatting used in this function because it is programmed to be pretty printed and may differ from the actual request. """ print(('{}\n{}\n{}\n\n{}'.format( '-----------START-----------', req.method + ' ' + req.url, '\n'.join('{}: {}'.format(k, v) for k, v in list(req.headers.items())), req.body, )))
def get_unique_indices ( df , axis = 1 ) : return dict ( zip ( df . columns . names , dif . columns . levels ) )
0
data frame with duplicate index values python
cosqa-train-15204
def get_unique_indices(df, axis=1): """ :param df: :param axis: :return: """ return dict(zip(df.columns.names, dif.columns.levels))
def parse_form ( self , req , name , field ) : return get_value ( req . body_arguments , name , field )
1
python flask request get form name
Pull a form value from the request .
cosqa-train-15205
def parse_form(self, req, name, field): """Pull a form value from the request.""" return get_value(req.body_arguments, name, field)
def make_coord_dict ( coord ) : return dict ( z = int_if_exact ( coord . zoom ) , x = int_if_exact ( coord . column ) , y = int_if_exact ( coord . row ) , )
1
datastructure to hold coordinates in python
helper function to make a dict from a coordinate for logging
cosqa-train-15206
def make_coord_dict(coord): """helper function to make a dict from a coordinate for logging""" return dict( z=int_if_exact(coord.zoom), x=int_if_exact(coord.column), y=int_if_exact(coord.row), )
def do_restart ( self , line ) : self . application . master . Restart ( opendnp3 . RestartType . COLD , restart_callback )
0
python flask restart programmatically
Request that the Outstation perform a cold restart . Command syntax is : restart
cosqa-train-15207
def do_restart(self, line): """Request that the Outstation perform a cold restart. Command syntax is: restart""" self.application.master.Restart(opendnp3.RestartType.COLD, restart_callback)
def convert_time_string ( date_str ) : dt , _ , _ = date_str . partition ( "." ) dt = datetime . strptime ( dt , "%Y-%m-%dT%H:%M:%S" ) return dt
0
date extract from string in python
Change a date string from the format 2018 - 08 - 15T23 : 55 : 17 into a datetime object
cosqa-train-15208
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 mimetype ( self ) : return ( self . environment . mimetypes . get ( self . format_extension ) or self . compiler_mimetype or 'application/octet-stream' )
0
python flask return mimetype
MIME type of the asset .
cosqa-train-15209
def mimetype(self): """MIME type of the asset.""" return (self.environment.mimetypes.get(self.format_extension) or self.compiler_mimetype or 'application/octet-stream')
def parse ( self , s ) : return datetime . datetime . strptime ( s , self . date_format ) . date ( )
1
date parse method python
Parses a date string formatted like YYYY - MM - DD .
cosqa-train-15210
def parse(self, s): """ Parses a date string formatted like ``YYYY-MM-DD``. """ return datetime.datetime.strptime(s, self.date_format).date()
def get_handler ( self , * args , * * options ) : handler = get_internal_wsgi_application ( ) from django . contrib . staticfiles . handlers import StaticFilesHandler return StaticFilesHandler ( handler )
1
python flask serve static files
Returns the default WSGI handler for the runner .
cosqa-train-15211
def get_handler(self, *args, **options): """ Returns the default WSGI handler for the runner. """ handler = get_internal_wsgi_application() from django.contrib.staticfiles.handlers import StaticFilesHandler return StaticFilesHandler(handler)
def AmericanDateToEpoch ( self , date_str ) : try : epoch = time . strptime ( date_str , "%m/%d/%Y" ) return int ( calendar . timegm ( epoch ) ) * 1000000 except ValueError : return 0
0
date string from epoch python
Take a US format date and return epoch .
cosqa-train-15212
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 get_handler ( self , * args , * * options ) : handler = get_internal_wsgi_application ( ) from django . contrib . staticfiles . handlers import StaticFilesHandler return StaticFilesHandler ( handler )
0
python flask static files server
Returns the default WSGI handler for the runner .
cosqa-train-15213
def get_handler(self, *args, **options): """ Returns the default WSGI handler for the runner. """ handler = get_internal_wsgi_application() from django.contrib.staticfiles.handlers import StaticFilesHandler return StaticFilesHandler(handler)
def date_to_datetime ( x ) : if not isinstance ( x , datetime ) and isinstance ( x , date ) : return datetime . combine ( x , time ( ) ) return x
0
datetime obeject to date python
Convert a date into a datetime
cosqa-train-15214
def date_to_datetime(x): """Convert a date into a datetime""" if not isinstance(x, datetime) and isinstance(x, date): return datetime.combine(x, time()) return x
def staticdir ( ) : root = os . path . abspath ( os . path . dirname ( __file__ ) ) return os . path . join ( root , "static" )
1
python flask static sub folder
Return the location of the static data directory .
cosqa-train-15215
def staticdir(): """Return the location of the static data directory.""" root = os.path.abspath(os.path.dirname(__file__)) return os.path.join(root, "static")
def ms_to_datetime ( ms ) : dt = datetime . datetime . utcfromtimestamp ( ms / 1000 ) return dt . replace ( microsecond = ( ms % 1000 ) * 1000 ) . replace ( tzinfo = pytz . utc )
1
datetime to timestamp milisecond python
Converts a millisecond accuracy timestamp to a datetime
cosqa-train-15216
def ms_to_datetime(ms): """ Converts a millisecond accuracy timestamp to a datetime """ dt = datetime.datetime.utcfromtimestamp(ms / 1000) return dt.replace(microsecond=(ms % 1000) * 1000).replace(tzinfo=pytz.utc)
def flatten_array ( grid ) : grid = [ grid [ i ] [ j ] for i in range ( len ( grid ) ) for j in range ( len ( grid [ i ] ) ) ] while type ( grid [ 0 ] ) is list : grid = flatten_array ( grid ) return grid
0
python flatten a list numpy
Takes a multi - dimensional array and returns a 1 dimensional array with the same contents .
cosqa-train-15217
def flatten_array(grid): """ Takes a multi-dimensional array and returns a 1 dimensional array with the same contents. """ grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))] while type(grid[0]) is list: grid = flatten_array(grid) return grid
def this_quarter ( ) : since = TODAY + delta ( day = 1 ) while since . month % 3 != 0 : since -= delta ( months = 1 ) until = since + delta ( months = 3 ) return Date ( since ) , Date ( until )
1
days to end of the quarter python
Return start and end date of this quarter .
cosqa-train-15218
def this_quarter(): """ Return start and end date of this quarter. """ since = TODAY + delta(day=1) while since.month % 3 != 0: since -= delta(months=1) until = since + delta(months=3) return Date(since), Date(until)
def setLib ( self , lib ) : for name , item in lib . items ( ) : self . font . lib [ name ] = item
0
python fonconfig font properties
Copy the lib items into our font .
cosqa-train-15219
def setLib(self, lib): """ Copy the lib items into our font. """ for name, item in lib.items(): self.font.lib[name] = item
def C_dict2array ( C ) : return np . hstack ( [ np . asarray ( C [ k ] ) . ravel ( ) for k in C_keys ] )
0
dct to an array in python
Convert an OrderedDict containing C values to a 1D array .
cosqa-train-15220
def C_dict2array(C): """Convert an OrderedDict containing C values to a 1D array.""" return np.hstack([np.asarray(C[k]).ravel() for k in C_keys])
def _enter_plotting ( self , fontsize = 9 ) : # interactive_status = matplotlib.is_interactive() self . original_fontsize = pyplot . rcParams [ 'font.size' ] pyplot . rcParams [ 'font.size' ] = fontsize pyplot . hold ( False ) # opens a figure window, if non exists pyplot . ioff ( )
1
python font in figure not editable
assumes that a figure is open
cosqa-train-15221
def _enter_plotting(self, fontsize=9): """assumes that a figure is open """ # interactive_status = matplotlib.is_interactive() self.original_fontsize = pyplot.rcParams['font.size'] pyplot.rcParams['font.size'] = fontsize pyplot.hold(False) # opens a figure window, if non exists pyplot.ioff()
def cric__decision_tree ( ) : model = sklearn . tree . DecisionTreeClassifier ( random_state = 0 , max_depth = 4 ) # we want to explain the raw probability outputs of the trees model . predict = lambda X : model . predict_proba ( X ) [ : , 1 ] return model
1
decision tree graph in python
Decision Tree
cosqa-train-15222
def cric__decision_tree(): """ Decision Tree """ model = sklearn.tree.DecisionTreeClassifier(random_state=0, max_depth=4) # we want to explain the raw probability outputs of the trees model.predict = lambda X: model.predict_proba(X)[:,1] return model
def count_levels ( value ) : if not isinstance ( value , dict ) or len ( value ) == 0 : return 0 elif len ( value ) == 0 : return 0 #An emptu dict has 0 else : nextval = list ( value . values ( ) ) [ 0 ] return 1 + count_levels ( nextval )
0
python for dictionary of dictonaries how to know the levels
Count how many levels are in a dict : scalar list etc = 0 {} = 0 { a : 1 } = 1 { a : { b : 1 }} = 2 etc ...
cosqa-train-15223
def count_levels(value): """ Count how many levels are in a dict: scalar, list etc = 0 {} = 0 {'a':1} = 1 {'a' : {'b' : 1}} = 2 etc... """ if not isinstance(value, dict) or len(value) == 0: return 0 elif len(value) == 0: return 0 #An emptu dict has 0 else: nextval = list(value.values())[0] return 1 + count_levels(nextval)
def list_of ( cls ) : return lambda l : isinstance ( l , list ) and all ( isinstance ( x , cls ) for x in l )
0
declaring custom type list in python
Returns a function that checks that each element in a list is of a specific type .
cosqa-train-15224
def list_of(cls): """ Returns a function that checks that each element in a list is of a specific type. """ return lambda l: isinstance(l, list) and all(isinstance(x, cls) for x in l)
def __del__ ( self ) : if hasattr ( self , '_Api' ) : self . _Api . close ( ) self . _Logger . info ( 'object destroyed' )
1
python force destroy object
Frees all resources .
cosqa-train-15225
def __del__(self): """Frees all resources. """ if hasattr(self, '_Api'): self._Api.close() self._Logger.info('object destroyed')
def _decode ( self , obj , context ) : return b'' . join ( map ( int2byte , [ c + 0x60 for c in bytearray ( obj ) ] ) ) . decode ( "utf8" )
1
decode object to bytes python
Get the python representation of the obj
cosqa-train-15226
def _decode(self, obj, context): """ Get the python representation of the obj """ return b''.join(map(int2byte, [c + 0x60 for c in bytearray(obj)])).decode("utf8")
def pprint ( obj , verbose = False , max_width = 79 , newline = '\n' ) : printer = RepresentationPrinter ( sys . stdout , verbose , max_width , newline ) printer . pretty ( obj ) printer . flush ( ) sys . stdout . write ( newline ) sys . stdout . flush ( )
0
python force output to be printer
Like pretty but print to stdout .
cosqa-train-15227
def pprint(obj, verbose=False, max_width=79, newline='\n'): """ Like `pretty` but print to stdout. """ printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline) printer.pretty(obj) printer.flush() sys.stdout.write(newline) sys.stdout.flush()
def lighting ( im , b , c ) : if b == 0 and c == 1 : return im mu = np . average ( im ) return np . clip ( ( im - mu ) * c + mu + b , 0. , 1. ) . astype ( np . float32 )
1
decreasing the contrast of an image using python
Adjust image balance and contrast
cosqa-train-15228
def lighting(im, b, c): """ Adjust image balance and contrast """ if b==0 and c==1: return im mu = np.average(im) return np.clip((im-mu)*c+mu+b,0.,1.).astype(np.float32)
def fixed ( ctx , number , decimals = 2 , no_commas = False ) : value = _round ( ctx , number , decimals ) format_str = '{:f}' if no_commas else '{:,f}' return format_str . format ( value )
1
python format amount commas no decimals
Formats the given number in decimal format using a period and commas
cosqa-train-15229
def fixed(ctx, number, decimals=2, no_commas=False): """ Formats the given number in decimal format using a period and commas """ value = _round(ctx, number, decimals) format_str = '{:f}' if no_commas else '{:,f}' return format_str.format(value)
def b ( s ) : return s if isinstance ( s , bytes ) else s . encode ( locale . getpreferredencoding ( ) )
1
default string encoding python
Encodes Unicode strings to byte strings if necessary .
cosqa-train-15230
def b(s): """ Encodes Unicode strings to byte strings, if necessary. """ return s if isinstance(s, bytes) else s.encode(locale.getpreferredencoding())
def format_float ( value ) : # not used string = "{:g}" . format ( value ) . replace ( "e+" , "e" ) string = re . sub ( "e(-?)0*(\d+)" , r"e\1\2" , string ) return string
0
python format float string negative parenthesis
Modified form of the g format specifier .
cosqa-train-15231
def format_float(value): # not used """Modified form of the 'g' format specifier. """ string = "{:g}".format(value).replace("e+", "e") string = re.sub("e(-?)0*(\d+)", r"e\1\2", string) return string
def strToBool ( val ) : if isinstance ( val , str ) : val = val . lower ( ) return val in [ 'true' , 'on' , 'yes' , True ]
1
define a boolen in python
Helper function to turn a string representation of true into boolean True .
cosqa-train-15232
def strToBool(val): """ Helper function to turn a string representation of "true" into boolean True. """ if isinstance(val, str): val = val.lower() return val in ['true', 'on', 'yes', True]
def pprint ( self , seconds ) : return ( "%d:%02d:%02d.%03d" , reduce ( lambda ll , b : divmod ( ll [ 0 ] , b ) + ll [ 1 : ] , [ ( seconds * 1000 , ) , 1000 , 60 , 60 ] ) )
0
python format minutes seconds print
Pretty Prints seconds as Hours : Minutes : Seconds . MilliSeconds
cosqa-train-15233
def pprint(self, seconds): """ Pretty Prints seconds as Hours:Minutes:Seconds.MilliSeconds :param seconds: The time in seconds. """ return ("%d:%02d:%02d.%03d", reduce(lambda ll, b: divmod(ll[0], b) + ll[1:], [(seconds * 1000,), 1000, 60, 60]))
def delete ( self , name ) : if name in self . _cache : del self . _cache [ name ] self . writeCache ( ) # TODO clean files return True return False
0
delete a cache automatically python
Deletes the named entry in the cache . : param name : the name . : return : true if it is deleted .
cosqa-train-15234
def delete(self, name): """ Deletes the named entry in the cache. :param name: the name. :return: true if it is deleted. """ if name in self._cache: del self._cache[name] self.writeCache() # TODO clean files return True return False
def fmt_sz ( intval ) : try : return fmt . human_size ( intval ) except ( ValueError , TypeError ) : return "N/A" . rjust ( len ( fmt . human_size ( 0 ) ) )
0
python format to width
Format a byte sized value .
cosqa-train-15235
def fmt_sz(intval): """ Format a byte sized value. """ try: return fmt.human_size(intval) except (ValueError, TypeError): return "N/A".rjust(len(fmt.human_size(0)))
def remove_this_tlink ( self , tlink_id ) : for tlink in self . get_tlinks ( ) : if tlink . get_id ( ) == tlink_id : self . node . remove ( tlink . get_node ( ) ) break
0
delete a node in link list in python
Removes the tlink for the given tlink identifier
cosqa-train-15236
def remove_this_tlink(self,tlink_id): """ Removes the tlink for the given tlink identifier @type tlink_id: string @param tlink_id: the tlink identifier to be removed """ for tlink in self.get_tlinks(): if tlink.get_id() == tlink_id: self.node.remove(tlink.get_node()) break
def rotation_from_quaternion ( q_wxyz ) : q_xyzw = np . array ( [ q_wxyz [ 1 ] , q_wxyz [ 2 ] , q_wxyz [ 3 ] , q_wxyz [ 0 ] ] ) R = transformations . quaternion_matrix ( q_xyzw ) [ : 3 , : 3 ] return R
0
python from rotation vector to quatemiond
Convert quaternion array to rotation matrix .
cosqa-train-15237
def rotation_from_quaternion(q_wxyz): """Convert quaternion array to rotation matrix. Parameters ---------- q_wxyz : :obj:`numpy.ndarray` of float A quaternion in wxyz order. Returns ------- :obj:`numpy.ndarray` of float A 3x3 rotation matrix made from the quaternion. """ q_xyzw = np.array([q_wxyz[1], q_wxyz[2], q_wxyz[3], q_wxyz[0]]) R = transformations.quaternion_matrix(q_xyzw)[:3,:3] return R
def rm ( venv_name ) : inenv = InenvManager ( ) venv = inenv . get_venv ( venv_name ) click . confirm ( "Delete dir {}" . format ( venv . path ) ) shutil . rmtree ( venv . path )
0
delete a python virtual environment
Removes the venv by name
cosqa-train-15238
def rm(venv_name): """ Removes the venv by name """ inenv = InenvManager() venv = inenv.get_venv(venv_name) click.confirm("Delete dir {}".format(venv.path)) shutil.rmtree(venv.path)
def convert_tstamp ( response ) : if response is None : # Allow passing None to convert_tstamp() return response # Overrides the set timezone to UTC - I think... tz = timezone . utc if settings . USE_TZ else None return datetime . datetime . fromtimestamp ( response , tz )
0
python fromtimestamp with timezone
Convert a Stripe API timestamp response ( unix epoch ) to a native datetime .
cosqa-train-15239
def convert_tstamp(response): """ Convert a Stripe API timestamp response (unix epoch) to a native datetime. :rtype: datetime """ if response is None: # Allow passing None to convert_tstamp() return response # Overrides the set timezone to UTC - I think... tz = timezone.utc if settings.USE_TZ else None return datetime.datetime.fromtimestamp(response, tz)
def trim ( self ) : for key , value in list ( iteritems ( self . counters ) ) : if value . empty ( ) : del self . counters [ key ]
0
delete all element dictionary in python
Clear not used counters
cosqa-train-15240
def trim(self): """Clear not used counters""" for key, value in list(iteritems(self.counters)): if value.empty(): del self.counters[key]
def connect ( ) : ftp_class = ftplib . FTP if not SSL else ftplib . FTP_TLS ftp = ftp_class ( timeout = TIMEOUT ) ftp . connect ( HOST , PORT ) ftp . login ( USER , PASSWORD ) if SSL : ftp . prot_p ( ) # secure data connection return ftp
0
python ftp can not finish
Connect to FTP server login and return an ftplib . FTP instance .
cosqa-train-15241
def connect(): """Connect to FTP server, login and return an ftplib.FTP instance.""" ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS ftp = ftp_class(timeout=TIMEOUT) ftp.connect(HOST, PORT) ftp.login(USER, PASSWORD) if SSL: ftp.prot_p() # secure data connection return ftp
def safe_delete ( filename ) : try : os . unlink ( filename ) except OSError as e : if e . errno != errno . ENOENT : raise
0
delete an existing file in python
Delete a file safely . If it s not present no - op .
cosqa-train-15242
def safe_delete(filename): """Delete a file safely. If it's not present, no-op.""" try: os.unlink(filename) except OSError as e: if e.errno != errno.ENOENT: raise
def _fullname ( o ) : return o . __module__ + "." + o . __name__ if o . __module__ else o . __name__
1
python full name of object from global
Return the fully - qualified name of a function .
cosqa-train-15243
def _fullname(o): """Return the fully-qualified name of a function.""" return o.__module__ + "." + o.__name__ if o.__module__ else o.__name__
def remove_from_lib ( self , name ) : self . __remove_path ( os . path . join ( self . root_dir , "lib" , name ) )
0
delete an item from directory python
Remove an object from the bin folder .
cosqa-train-15244
def remove_from_lib(self, name): """ Remove an object from the bin folder. """ self.__remove_path(os.path.join(self.root_dir, "lib", name))
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 function for manhattan distance
Return manhattan distance between two lists of numbers .
cosqa-train-15245
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 remove_file_from_s3 ( awsclient , bucket , key ) : client_s3 = awsclient . get_client ( 's3' ) response = client_s3 . delete_object ( Bucket = bucket , Key = key )
0
delete file from s3 bucket python
Remove a file from an AWS S3 bucket .
cosqa-train-15246
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 first_unique_char ( s ) : if ( len ( s ) == 1 ) : return 0 ban = [ ] for i in range ( len ( s ) ) : if all ( s [ i ] != s [ k ] for k in range ( i + 1 , len ( s ) ) ) == True and s [ i ] not in ban : return i else : ban . append ( s [ i ] ) return - 1
0
python function for unique in string
: type s : str : rtype : int
cosqa-train-15247
def first_unique_char(s): """ :type s: str :rtype: int """ if (len(s) == 1): return 0 ban = [] for i in range(len(s)): if all(s[i] != s[k] for k in range(i + 1, len(s))) == True and s[i] not in ban: return i else: ban.append(s[i]) return -1
def safe_delete ( filename ) : try : os . unlink ( filename ) except OSError as e : if e . errno != errno . ENOENT : raise
1
delete file if exist in python
Delete a file safely . If it s not present no - op .
cosqa-train-15248
def safe_delete(filename): """Delete a file safely. If it's not present, no-op.""" try: os.unlink(filename) except OSError as e: if e.errno != errno.ENOENT: raise
def get_object_or_child_by_type ( self , * types ) : objects = self . get_objects_or_children_by_type ( * types ) return objects [ 0 ] if any ( objects ) else None
1
python function get all objects of certain type
Get object if child already been read or get child .
cosqa-train-15249
def get_object_or_child_by_type(self, *types): """ Get object if child already been read or get child. Use this method for fast access to objects in case of static configurations. :param types: requested object types. :return: all children of the specified types. """ objects = self.get_objects_or_children_by_type(*types) return objects[0] if any(objects) else None
def removeFromRegistery ( obj ) : if isRabaObject ( obj ) : _unregisterRabaObjectInstance ( obj ) elif isRabaList ( obj ) : _unregisterRabaListInstance ( obj )
0
delete object python to release memory
Removes an object / rabalist from registery . This is useful if you want to allow the garbage collector to free the memory taken by the objects you ve already loaded . Be careful might cause some discrepenties in your scripts . For objects cascades to free the registeries of related rabalists also
cosqa-train-15250
def removeFromRegistery(obj) : """Removes an object/rabalist from registery. This is useful if you want to allow the garbage collector to free the memory taken by the objects you've already loaded. Be careful might cause some discrepenties in your scripts. For objects, cascades to free the registeries of related rabalists also""" if isRabaObject(obj) : _unregisterRabaObjectInstance(obj) elif isRabaList(obj) : _unregisterRabaListInstance(obj)
def ex ( self , cmd ) : with self . builtin_trap : exec cmd in self . user_global_ns , self . user_ns
0
python function outer scope
Execute a normal python statement in user namespace .
cosqa-train-15251
def ex(self, cmd): """Execute a normal python statement in user namespace.""" with self.builtin_trap: exec cmd in self.user_global_ns, self.user_ns
def normalize_value ( text ) : result = text . replace ( '\n' , ' ' ) result = re . subn ( '[ ]{2,}' , ' ' , result ) [ 0 ] return result
1
delete whitespace from a string python
This removes newlines and multiple spaces from a string .
cosqa-train-15252
def normalize_value(text): """ This removes newlines and multiple spaces from a string. """ result = text.replace('\n', ' ') result = re.subn('[ ]{2,}', ' ', result)[0] return result
def user_exists ( username ) : try : pwd . getpwnam ( username ) user_exists = True except KeyError : user_exists = False return user_exists
0
python function to check if something exists
Check if a user exists
cosqa-train-15253
def user_exists(username): """Check if a user exists""" try: pwd.getpwnam(username) user_exists = True except KeyError: user_exists = False return user_exists
def delete_object_from_file ( file_name , save_key , file_location ) : file = __os . path . join ( file_location , file_name ) shelve_store = __shelve . open ( file ) del shelve_store [ save_key ] shelve_store . close ( )
0
deleting a key from a python shelve file
Function to delete objects from a shelve Args : file_name : Shelve storage file name save_key : The name of the key the item is stored in file_location : The location of the file derive from the os module
cosqa-train-15254
def delete_object_from_file(file_name, save_key, file_location): """ Function to delete objects from a shelve Args: file_name: Shelve storage file name save_key: The name of the key the item is stored in file_location: The location of the file, derive from the os module Returns: """ file = __os.path.join(file_location, file_name) shelve_store = __shelve.open(file) del shelve_store[save_key] shelve_store.close()
def EvalGaussianPdf ( x , mu , sigma ) : return scipy . stats . norm . pdf ( x , mu , sigma )
0
python gaussian probability distribution
Computes the unnormalized PDF of the normal distribution .
cosqa-train-15255
def EvalGaussianPdf(x, mu, sigma): """Computes the unnormalized PDF of the normal distribution. x: value mu: mean sigma: standard deviation returns: float probability density """ return scipy.stats.norm.pdf(x, mu, sigma)
def from_json_list ( cls , api_client , data ) : return [ cls . from_json ( api_client , item ) for item in data ]
1
deserialize object list from json in python
Convert a list of JSON values to a list of models
cosqa-train-15256
def from_json_list(cls, api_client, data): """Convert a list of JSON values to a list of models """ return [cls.from_json(api_client, item) for item in data]
def get_incomplete_path ( filename ) : random_suffix = "" . join ( random . choice ( string . ascii_uppercase + string . digits ) for _ in range ( 6 ) ) return filename + ".incomplete" + random_suffix
1
python generate a random file name
Returns a temporary filename based on filename .
cosqa-train-15257
def get_incomplete_path(filename): """Returns a temporary filename based on filename.""" random_suffix = "".join( random.choice(string.ascii_uppercase + string.digits) for _ in range(6)) return filename + ".incomplete" + random_suffix
def is_int_type ( val ) : try : # Python 2 return isinstance ( val , ( int , long ) ) except NameError : # Python 3 return isinstance ( val , int )
0
determine if a number is an integer python
Return True if val is of integer type .
cosqa-train-15258
def is_int_type(val): """Return True if `val` is of integer type.""" try: # Python 2 return isinstance(val, (int, long)) except NameError: # Python 3 return isinstance(val, int)
def list_get ( l , idx , default = None ) : try : if l [ idx ] : return l [ idx ] else : return default except IndexError : return default
0
python get a list item with default
Get from a list with an optional default value .
cosqa-train-15259
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 estimate_complexity ( self , x , y , z , n ) : num_calculations = x * y * z * n run_time = num_calculations / 100000 # a 2014 PC does about 100k calcs in a second (guess based on prior logs) return self . show_time_as_short_string ( run_time )
1
determine time complexity of my python program
calculates a rough guess of runtime based on product of parameters
cosqa-train-15260
def estimate_complexity(self, x,y,z,n): """ calculates a rough guess of runtime based on product of parameters """ num_calculations = x * y * z * n run_time = num_calculations / 100000 # a 2014 PC does about 100k calcs in a second (guess based on prior logs) return self.show_time_as_short_string(run_time)
def _get_str_columns ( sf ) : return [ name for name in sf . column_names ( ) if sf [ name ] . dtype == str ]
0
python get all column names with a string in it
Returns a list of names of columns that are string type .
cosqa-train-15261
def _get_str_columns(sf): """ Returns a list of names of columns that are string type. """ return [name for name in sf.column_names() if sf[name].dtype == str]
def isSquare ( matrix ) : try : try : dim1 , dim2 = matrix . shape except AttributeError : dim1 , dim2 = _np . array ( matrix ) . shape except ValueError : return False if dim1 == dim2 : return True return False
0
determine whether a shape is square or not python
Check that matrix is square .
cosqa-train-15262
def isSquare(matrix): """Check that ``matrix`` is square. Returns ======= is_square : bool ``True`` if ``matrix`` is square, ``False`` otherwise. """ try: try: dim1, dim2 = matrix.shape except AttributeError: dim1, dim2 = _np.array(matrix).shape except ValueError: return False if dim1 == dim2: return True return False
def search_for_tweets_about ( user_id , params ) : url = "https://api.twitter.com/1.1/search/tweets.json" response = make_twitter_request ( url , user_id , params ) return process_tweets ( response . json ( ) [ "statuses" ] )
0
python get all followers in twitter by twitter api
Search twitter API
cosqa-train-15263
def search_for_tweets_about(user_id, params): """ Search twitter API """ url = "https://api.twitter.com/1.1/search/tweets.json" response = make_twitter_request(url, user_id, params) return process_tweets(response.json()["statuses"])
def is_hex_string ( string ) : pattern = re . compile ( r'[A-Fa-f0-9]+' ) if isinstance ( string , six . binary_type ) : string = str ( string ) return pattern . match ( string ) is not None
1
determine whether or not a string is hex python
Check if the string is only composed of hex characters .
cosqa-train-15264
def is_hex_string(string): """Check if the string is only composed of hex characters.""" pattern = re.compile(r'[A-Fa-f0-9]+') if isinstance(string, six.binary_type): string = str(string) return pattern.match(string) is not None
def getHeaders ( self ) : headers = self . _impl . getHeaders ( ) return tuple ( headers . getIndex ( i ) for i in range ( self . _impl . getNumCols ( ) ) )
0
python get all headers of data frame
Get the headers of this DataFrame .
cosqa-train-15265
def getHeaders(self): """ Get the headers of this DataFrame. Returns: The headers of this DataFrame. """ headers = self._impl.getHeaders() return tuple( headers.getIndex(i) for i in range(self._impl.getNumCols()) )
def C_dict2array ( C ) : return np . hstack ( [ np . asarray ( C [ k ] ) . ravel ( ) for k in C_keys ] )
1
dictionary in python comoared to array
Convert an OrderedDict containing C values to a 1D array .
cosqa-train-15266
def C_dict2array(C): """Convert an OrderedDict containing C values to a 1D array.""" return np.hstack([np.asarray(C[k]).ravel() for k in C_keys])
def caller_locals ( ) : import inspect frame = inspect . currentframe ( ) try : return frame . f_back . f_back . f_locals finally : del frame
0
python get all local variables
Get the local variables in the caller s frame .
cosqa-train-15267
def caller_locals(): """Get the local variables in the caller's frame.""" import inspect frame = inspect.currentframe() try: return frame.f_back.f_back.f_locals finally: del frame
def multi_pop ( d , * args ) : retval = { } for key in args : if key in d : retval [ key ] = d . pop ( key ) return retval
1
dictionary pop python multiple keys
pops multiple keys off a dict like object
cosqa-train-15268
def multi_pop(d, *args): """ pops multiple keys off a dict like object """ retval = {} for key in args: if key in d: retval[key] = d.pop(key) return retval
def __dir__ ( self ) : return sorted ( self . keys ( ) | { m for m in dir ( self . __class__ ) if m . startswith ( 'to_' ) } )
1
python get all staticmethod
u Returns a list of children and available helper methods .
cosqa-train-15269
def __dir__(self): u"""Returns a list of children and available helper methods.""" return sorted(self.keys() | {m for m in dir(self.__class__) if m.startswith('to_')})
def get_flat_size ( self ) : return sum ( np . prod ( v . get_shape ( ) . as_list ( ) ) for v in self . variables . values ( ) )
1
dimensions of a variable in python
Returns the total length of all of the flattened variables .
cosqa-train-15270
def get_flat_size(self): """Returns the total length of all of the flattened variables. Returns: The length of all flattened variables concatenated. """ return sum( np.prod(v.get_shape().as_list()) for v in self.variables.values())
def get_tablenames ( cur ) : cur . execute ( "SELECT name FROM sqlite_master WHERE type='table'" ) tablename_list_ = cur . fetchall ( ) tablename_list = [ str ( tablename [ 0 ] ) for tablename in tablename_list_ ] return tablename_list
1
python get all table sqlite
Conveinience :
cosqa-train-15271
def get_tablenames(cur): """ Conveinience: """ cur.execute("SELECT name FROM sqlite_master WHERE type='table'") tablename_list_ = cur.fetchall() tablename_list = [str(tablename[0]) for tablename in tablename_list_ ] return tablename_list
def me ( self ) : return self . guild . me if self . guild is not None else self . bot . user
0
discord bot python get user
Similar to : attr : . Guild . me except it may return the : class : . ClientUser in private message contexts .
cosqa-train-15272
def me(self): """Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts.""" return self.guild.me if self.guild is not None else self.bot.user
def current_memory_usage ( ) : import psutil proc = psutil . Process ( os . getpid ( ) ) #meminfo = proc.get_memory_info() meminfo = proc . memory_info ( ) rss = meminfo [ 0 ] # Resident Set Size / Mem Usage vms = meminfo [ 1 ] # Virtual Memory Size / VM Size # NOQA return rss
0
python get amount of ram
Returns this programs current memory usage in bytes
cosqa-train-15273
def current_memory_usage(): """ Returns this programs current memory usage in bytes """ import psutil proc = psutil.Process(os.getpid()) #meminfo = proc.get_memory_info() meminfo = proc.memory_info() rss = meminfo[0] # Resident Set Size / Mem Usage vms = meminfo[1] # Virtual Memory Size / VM Size # NOQA return rss
def get_chat_member ( self , user_id ) : return self . bot . api_call ( "getChatMember" , chat_id = str ( self . id ) , user_id = str ( user_id ) )
0
discord python api get userid
Get information about a member of a chat .
cosqa-train-15274
def get_chat_member(self, user_id): """ Get information about a member of a chat. :param int user_id: Unique identifier of the target user """ return self.bot.api_call( "getChatMember", chat_id=str(self.id), user_id=str(user_id) )
def generate_unique_host_id ( ) : host = "." . join ( reversed ( socket . gethostname ( ) . split ( "." ) ) ) pid = os . getpid ( ) return "%s.%d" % ( host , pid )
1
python get an unique id
Generate a unique ID that is somewhat guaranteed to be unique among all instances running at the same time .
cosqa-train-15275
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 debug_src ( src , pm = False , globs = None ) : testsrc = script_from_examples ( src ) debug_script ( testsrc , pm , globs )
0
display doctest results in python
Debug a single doctest docstring in argument src
cosqa-train-15276
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 get_encoding ( binary ) : try : from chardet import detect except ImportError : LOGGER . error ( "Please install the 'chardet' module" ) sys . exit ( 1 ) encoding = detect ( binary ) . get ( 'encoding' ) return 'iso-8859-1' if encoding == 'CP949' else encoding
0
python get barcode encoding type
Return the encoding type .
cosqa-train-15277
def get_encoding(binary): """Return the encoding type.""" try: from chardet import detect except ImportError: LOGGER.error("Please install the 'chardet' module") sys.exit(1) encoding = detect(binary).get('encoding') return 'iso-8859-1' if encoding == 'CP949' else encoding
def get_last_or_frame_exception ( ) : try : if inspect . istraceback ( sys . last_traceback ) : # We do have a traceback so prefer that. return sys . last_type , sys . last_value , sys . last_traceback except AttributeError : pass return sys . exc_info ( )
0
display traceback in try catch python
Intended to be used going into post mortem routines . If sys . last_traceback is set we will return that and assume that this is what post - mortem will want . If sys . last_traceback has not been set then perhaps we * about * to raise an error and are fielding an exception . So assume that sys . exc_info () [ 2 ] is where we want to look .
cosqa-train-15278
def get_last_or_frame_exception(): """Intended to be used going into post mortem routines. If sys.last_traceback is set, we will return that and assume that this is what post-mortem will want. If sys.last_traceback has not been set, then perhaps we *about* to raise an error and are fielding an exception. So assume that sys.exc_info()[2] is where we want to look.""" try: if inspect.istraceback(sys.last_traceback): # We do have a traceback so prefer that. return sys.last_type, sys.last_value, sys.last_traceback except AttributeError: pass return sys.exc_info()
def paste ( cmd = paste_cmd , stdout = PIPE ) : return Popen ( cmd , stdout = stdout ) . communicate ( ) [ 0 ] . decode ( 'utf-8' )
1
python get clipboard contents
Returns system clipboard contents .
cosqa-train-15279
def paste(cmd=paste_cmd, stdout=PIPE): """Returns system clipboard contents. """ return Popen(cmd, stdout=stdout).communicate()[0].decode('utf-8')
def confirm_credential_display ( force = False ) : if force : return True msg = """ [WARNING] Your credential is about to be displayed on screen. If this is really what you want, type 'y' and press enter.""" result = click . confirm ( text = msg ) return result
0
displaying confirm message in python
cosqa-train-15280
def confirm_credential_display(force=False): if force: return True msg = """ [WARNING] Your credential is about to be displayed on screen. If this is really what you want, type 'y' and press enter.""" result = click.confirm(text=msg) return result
def dict_hash ( dct ) : dct_s = json . dumps ( dct , sort_keys = True ) try : m = md5 ( dct_s ) except TypeError : m = md5 ( dct_s . encode ( ) ) return m . hexdigest ( )
1
python get dict hash
Return a hash of the contents of a dictionary
cosqa-train-15281
def dict_hash(dct): """Return a hash of the contents of a dictionary""" dct_s = json.dumps(dct, sort_keys=True) try: m = md5(dct_s) except TypeError: m = md5(dct_s.encode()) return m.hexdigest()
def get_distance_matrix ( x ) : square = nd . sum ( x ** 2.0 , axis = 1 , keepdims = True ) distance_square = square + square . transpose ( ) - ( 2.0 * nd . dot ( x , x . transpose ( ) ) ) return nd . sqrt ( distance_square )
1
distance of values in matrix python function
Get distance matrix given a matrix . Used in testing .
cosqa-train-15282
def get_distance_matrix(x): """Get distance matrix given a matrix. Used in testing.""" square = nd.sum(x ** 2.0, axis=1, keepdims=True) distance_square = square + square.transpose() - (2.0 * nd.dot(x, x.transpose())) return nd.sqrt(distance_square)
def dict_hash ( dct ) : dct_s = json . dumps ( dct , sort_keys = True ) try : m = md5 ( dct_s ) except TypeError : m = md5 ( dct_s . encode ( ) ) return m . hexdigest ( )
1
python get dictionary hash
Return a hash of the contents of a dictionary
cosqa-train-15283
def dict_hash(dct): """Return a hash of the contents of a dictionary""" dct_s = json.dumps(dct, sort_keys=True) try: m = md5(dct_s) except TypeError: m = md5(dct_s.encode()) return m.hexdigest()
def safe_call ( cls , method , * args ) : return cls . call ( method , * args , safe = True )
1
django call python method views
Call a remote api method but don t raise if an error occurred .
cosqa-train-15284
def safe_call(cls, method, *args): """ Call a remote api method but don't raise if an error occurred.""" return cls.call(method, *args, safe=True)
def direct2dDistance ( self , point ) : if not isinstance ( point , MapPoint ) : return 0.0 return ( ( self . x - point . x ) ** 2 + ( self . y - point . y ) ** 2 ) ** ( 0.5 ) # simple distance formula
0
python get distance 2 points
consider the distance between two mapPoints ignoring all terrain pathing issues
cosqa-train-15285
def direct2dDistance(self, point): """consider the distance between two mapPoints, ignoring all terrain, pathing issues""" if not isinstance(point, MapPoint): return 0.0 return ((self.x-point.x)**2 + (self.y-point.y)**2)**(0.5) # simple distance formula
def clone ( src , * * kwargs ) : obj = object . __new__ ( type ( src ) ) obj . __dict__ . update ( src . __dict__ ) obj . __dict__ . update ( kwargs ) return obj
0
django python clone object
Clones object with optionally overridden fields
cosqa-train-15286
def clone(src, **kwargs): """Clones object with optionally overridden fields""" obj = object.__new__(type(src)) obj.__dict__.update(src.__dict__) obj.__dict__.update(kwargs) return obj
def dict_pop_or ( d , key , default = None ) : val = default with suppress ( KeyError ) : val = d . pop ( key ) return val
1
python get element from dict or default
Try popping a key from a dict . Instead of raising KeyError just return the default value .
cosqa-train-15287
def dict_pop_or(d, key, default=None): """ Try popping a key from a dict. Instead of raising KeyError, just return the default value. """ val = default with suppress(KeyError): val = d.pop(key) return val
def load_from_file ( module_path ) : from imp import load_module , PY_SOURCE imported = None if module_path : with open ( module_path , 'r' ) as openfile : imported = load_module ( 'mod' , openfile , module_path , ( 'imported' , 'r' , PY_SOURCE ) ) return imported
1
django python load once
Load a python module from its absolute filesystem path
cosqa-train-15288
def load_from_file(module_path): """ Load a python module from its absolute filesystem path Borrowed from django-cms """ from imp import load_module, PY_SOURCE imported = None if module_path: with open(module_path, 'r') as openfile: imported = load_module('mod', openfile, module_path, ('imported', 'r', PY_SOURCE)) return imported
def get_user_name ( ) : if sys . platform == 'win32' : #user = os.getenv('USERPROFILE') user = os . getenv ( 'USERNAME' ) else : user = os . getenv ( 'LOGNAME' ) return user
1
python get environ user windows
Get user name provide by operating system
cosqa-train-15289
def get_user_name(): """Get user name provide by operating system """ if sys.platform == 'win32': #user = os.getenv('USERPROFILE') user = os.getenv('USERNAME') else: user = os.getenv('LOGNAME') return user
def close ( self ) : if self . db is not None : self . db . commit ( ) self . db . close ( ) self . db = None return
1
do you have to close a database in python
Close the db and release memory
cosqa-train-15290
def close( self ): """ Close the db and release memory """ if self.db is not None: self.db.commit() self.db.close() self.db = None return
def get_parent_folder_name ( file_path ) : return os . path . split ( os . path . split ( os . path . abspath ( file_path ) ) [ 0 ] ) [ - 1 ]
0
python get file parent path nane
Finds parent folder of file
cosqa-train-15291
def get_parent_folder_name(file_path): """Finds parent folder of file :param file_path: path :return: Name of folder container """ return os.path.split(os.path.split(os.path.abspath(file_path))[0])[-1]
def _is_start ( event , node , tagName ) : # pylint: disable=invalid-name return event == pulldom . START_ELEMENT and node . tagName == tagName
0
does an xml element have a beginning property python
Return true if ( event node ) is a start event for tagname .
cosqa-train-15292
def _is_start(event, node, tagName): # pylint: disable=invalid-name """Return true if (event, node) is a start event for tagname.""" return event == pulldom.START_ELEMENT and node.tagName == tagName
def find_geom ( geom , geoms ) : for i , g in enumerate ( geoms ) : if g is geom : return i
0
python get index from set of ranges
Returns the index of a geometry in a list of geometries avoiding expensive equality checks of in operator .
cosqa-train-15293
def find_geom(geom, geoms): """ Returns the index of a geometry in a list of geometries avoiding expensive equality checks of `in` operator. """ for i, g in enumerate(geoms): if g is geom: return i
def _index2n ( self , index ) : n_float = np . sqrt ( index + 1 ) - 1 n_int = int ( n_float ) if n_int == n_float : n = n_int else : n = n_int + 1 return n
0
does indexing return a string or an int python
cosqa-train-15294
def _index2n(self, index): """ :param index: index convention :return: n """ n_float = np.sqrt(index + 1) - 1 n_int = int(n_float) if n_int == n_float: n = n_int else: n = n_int + 1 return n
def bisect_index ( a , x ) : i = bisect . bisect_left ( a , x ) if i != len ( a ) and a [ i ] == x : return i raise ValueError
0
python get index of element from back
Find the leftmost index of an element in a list using binary search .
cosqa-train-15295
def bisect_index(a, x): """ Find the leftmost index of an element in a list using binary search. Parameters ---------- a: list A sorted list. x: arbitrary The element. Returns ------- int The index. """ i = bisect.bisect_left(a, x) if i != len(a) and a[i] == x: return i raise ValueError
def peak_memory_usage ( ) : if sys . platform . startswith ( 'win' ) : p = psutil . Process ( ) return p . memory_info ( ) . peak_wset / 1024 / 1024 mem = resource . getrusage ( resource . RUSAGE_SELF ) . ru_maxrss factor_mb = 1 / 1024 if sys . platform == 'darwin' : factor_mb = 1 / ( 1024 * 1024 ) return mem * factor_mb
0
does python cap the amount of ram it uses
Return peak memory usage in MB
cosqa-train-15296
def peak_memory_usage(): """Return peak memory usage in MB""" if sys.platform.startswith('win'): p = psutil.Process() return p.memory_info().peak_wset / 1024 / 1024 mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss factor_mb = 1 / 1024 if sys.platform == 'darwin': factor_mb = 1 / (1024 * 1024) return mem * factor_mb
def get_substring_idxs ( substr , string ) : return [ match . start ( ) for match in re . finditer ( substr , string ) ]
1
python get indices of char in string
Return a list of indexes of substr . If substr not found list is empty .
cosqa-train-15297
def get_substring_idxs(substr, string): """ Return a list of indexes of substr. If substr not found, list is empty. Arguments: substr (str): Substring to match. string (str): String to match in. Returns: list of int: Start indices of substr. """ return [match.start() for match in re.finditer(substr, string)]
def to_basestring ( value ) : if isinstance ( value , _BASESTRING_TYPES ) : return value assert isinstance ( value , bytes ) return value . decode ( "utf-8" )
0
does python have a char type
Converts a string argument to a subclass of basestring .
cosqa-train-15298
def to_basestring(value): """Converts a string argument to a subclass of basestring. In python2, byte and unicode strings are mostly interchangeable, so functions that deal with a user-supplied argument in combination with ascii string constants can use either and should return the type the user supplied. In python3, the two types are not interchangeable, so this method is needed to convert byte strings to unicode. """ if isinstance(value, _BASESTRING_TYPES): return value assert isinstance(value, bytes) return value.decode("utf-8")
def string_to_int ( s ) : result = 0 for c in s : if not isinstance ( c , int ) : c = ord ( c ) result = 256 * result + c return result
0
python get int from bytes
Convert a string of bytes into an integer as per X9 . 62 .
cosqa-train-15299
def string_to_int( s ): """Convert a string of bytes into an integer, as per X9.62.""" result = 0 for c in s: if not isinstance(c, int): c = ord( c ) result = 256 * result + c return result