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 _index_ordering ( redshift_list ) : redshift_list = np . array ( redshift_list ) sort_index = np . argsort ( redshift_list ) return sort_index
1
sort return index in python
cosqa-train-14600
def _index_ordering(redshift_list): """ :param redshift_list: list of redshifts :return: indexes in acending order to be evaluated (from z=0 to z=z_source) """ redshift_list = np.array(redshift_list) sort_index = np.argsort(redshift_list) return sort_index
def schedule_task ( self ) : from . tasks import publish_task publish_task . apply_async ( kwargs = { 'pk' : self . pk } , eta = self . scheduled_time )
1
python celery chain tasksk
Schedules this publish action as a Celery task .
cosqa-train-14601
def schedule_task(self): """ Schedules this publish action as a Celery task. """ from .tasks import publish_task publish_task.apply_async(kwargs={'pk': self.pk}, eta=self.scheduled_time)
def get_order ( self , codes ) : return sorted ( codes , key = lambda e : [ self . ev2idx . get ( e ) ] )
1
sorting code in python based on name
Return evidence codes in order shown in code2name .
cosqa-train-14602
def get_order(self, codes): """Return evidence codes in order shown in code2name.""" return sorted(codes, key=lambda e: [self.ev2idx.get(e)])
def sort_data ( x , y ) : xy = sorted ( zip ( x , y ) ) x , y = zip ( * xy ) return x , y
1
sorting the data in python
Sort the data .
cosqa-train-14603
def sort_data(x, y): """Sort the data.""" xy = sorted(zip(x, y)) x, y = zip(*xy) return x, y
def force_stop ( self ) : r = self . local_renderer with self . settings ( warn_only = True ) : r . sudo ( 'pkill -9 -f celery' ) r . sudo ( 'rm -f /tmp/celery*.pid' )
1
python celery worker stop
Forcibly terminates all Celery processes .
cosqa-train-14604
def force_stop(self): """ Forcibly terminates all Celery processes. """ r = self.local_renderer with self.settings(warn_only=True): r.sudo('pkill -9 -f celery') r.sudo('rm -f /tmp/celery*.pid')
def has_add_permission ( self , request ) : return request . user . is_authenticated and request . user . is_active and request . user . is_staff
1
spacy permission denied python 3
Can add this object
cosqa-train-14605
def has_add_permission(self, request): """ Can add this object """ return request.user.is_authenticated and request.user.is_active and request.user.is_staff
def pointer ( self ) : return ctypes . cast ( ctypes . pointer ( ctypes . c_uint8 . from_buffer ( self . mapping , 0 ) ) , ctypes . c_void_p )
1
python cfunctype memory address
Get a ctypes void pointer to the memory mapped region .
cosqa-train-14606
def pointer(self): """Get a ctypes void pointer to the memory mapped region. :type: ctypes.c_void_p """ return ctypes.cast(ctypes.pointer(ctypes.c_uint8.from_buffer(self.mapping, 0)), ctypes.c_void_p)
def do_forceescape ( value ) : if hasattr ( value , '__html__' ) : value = value . __html__ ( ) return escape ( unicode ( value ) )
1
special character change to html encode after save python
Enforce HTML escaping . This will probably double escape variables .
cosqa-train-14607
def do_forceescape(value): """Enforce HTML escaping. This will probably double escape variables.""" if hasattr(value, '__html__'): value = value.__html__() return escape(unicode(value))
def fieldstorage ( self ) : if self . _fieldstorage is None : if self . _body is not None : raise ReadBodyTwiceError ( ) self . _fieldstorage = cgi . FieldStorage ( environ = self . _environ , fp = self . _environ [ 'wsgi.input' ] ) return self . _fieldstorage
1
python cgi fieldstorage none none ajax windows flask
cgi . FieldStorage from wsgi . input .
cosqa-train-14608
def fieldstorage(self): """ `cgi.FieldStorage` from `wsgi.input`. """ if self._fieldstorage is None: if self._body is not None: raise ReadBodyTwiceError() self._fieldstorage = cgi.FieldStorage( environ=self._environ, fp=self._environ['wsgi.input'] ) return self._fieldstorage
def _histplot_op ( ax , data , * * kwargs ) : bins = get_bins ( data ) ax . hist ( data , bins = bins , align = "left" , density = True , * * kwargs ) return ax
0
specify bins in histogram python
Add a histogram for the data to the axes .
cosqa-train-14609
def _histplot_op(ax, data, **kwargs): """Add a histogram for the data to the axes.""" bins = get_bins(data) ax.hist(data, bins=bins, align="left", density=True, **kwargs) return ax
def stringc ( text , color ) : if has_colors : text = str ( text ) return "\033[" + codeCodes [ color ] + "m" + text + "\033[0m" else : return text
1
python chage string color
Return a string with terminal colors .
cosqa-train-14610
def stringc(text, color): """ Return a string with terminal colors. """ if has_colors: text = str(text) return "\033["+codeCodes[color]+"m"+text+"\033[0m" else: return text
def napoleon_to_sphinx ( docstring , * * config_params ) : if "napoleon_use_param" not in config_params : config_params [ "napoleon_use_param" ] = False if "napoleon_use_rtype" not in config_params : config_params [ "napoleon_use_rtype" ] = False config = Config ( * * config_params ) return str ( GoogleDocstring ( docstring , config ) )
1
sphinx proper way to document python function
Convert napoleon docstring to plain sphinx string .
cosqa-train-14611
def napoleon_to_sphinx(docstring, **config_params): """ Convert napoleon docstring to plain sphinx string. Args: docstring (str): Docstring in napoleon format. **config_params (dict): Whatever napoleon doc configuration you want. Returns: str: Sphinx string. """ if "napoleon_use_param" not in config_params: config_params["napoleon_use_param"] = False if "napoleon_use_rtype" not in config_params: config_params["napoleon_use_rtype"] = False config = Config(**config_params) return str(GoogleDocstring(docstring, config))
def _possibly_convert_objects ( values ) : return np . asarray ( pd . Series ( values . ravel ( ) ) ) . reshape ( values . shape )
1
python change array of datetime to integers
Convert arrays of datetime . datetime and datetime . timedelta objects into datetime64 and timedelta64 according to the pandas convention .
cosqa-train-14612
def _possibly_convert_objects(values): """Convert arrays of datetime.datetime and datetime.timedelta objects into datetime64 and timedelta64, according to the pandas convention. """ return np.asarray(pd.Series(values.ravel())).reshape(values.shape)
def _split ( string , splitters ) : part = '' for character in string : if character in splitters : yield part part = '' else : part += character yield part
1
split python on many char
Splits a string into parts at multiple characters
cosqa-train-14613
def _split(string, splitters): """Splits a string into parts at multiple characters""" part = '' for character in string: if character in splitters: yield part part = '' else: part += character yield part
def _to_corrected_pandas_type ( dt ) : import numpy as np if type ( dt ) == ByteType : return np . int8 elif type ( dt ) == ShortType : return np . int16 elif type ( dt ) == IntegerType : return np . int32 elif type ( dt ) == FloatType : return np . float32 else : return None
1
python change df column datatype
When converting Spark SQL records to Pandas DataFrame the inferred data type may be wrong . This method gets the corrected data type for Pandas if that type may be inferred uncorrectly .
cosqa-train-14614
def _to_corrected_pandas_type(dt): """ When converting Spark SQL records to Pandas DataFrame, the inferred data type may be wrong. This method gets the corrected data type for Pandas if that type may be inferred uncorrectly. """ import numpy as np if type(dt) == ByteType: return np.int8 elif type(dt) == ShortType: return np.int16 elif type(dt) == IntegerType: return np.int32 elif type(dt) == FloatType: return np.float32 else: return None
def set_time ( filename , mod_time ) : log . debug ( 'Setting modified time to %s' , mod_time ) mtime = calendar . timegm ( mod_time . utctimetuple ( ) ) # utctimetuple discards microseconds, so restore it (for consistency) mtime += mod_time . microsecond / 1000000 atime = os . stat ( filename ) . st_atime os . utime ( filename , ( atime , mtime ) )
1
python change modified time file
Set the modified time of a file
cosqa-train-14615
def set_time(filename, mod_time): """ Set the modified time of a file """ log.debug('Setting modified time to %s', mod_time) mtime = calendar.timegm(mod_time.utctimetuple()) # utctimetuple discards microseconds, so restore it (for consistency) mtime += mod_time.microsecond / 1000000 atime = os.stat(filename).st_atime os.utime(filename, (atime, mtime))
def split_into_words ( s ) : s = re . sub ( r"\W+" , " " , s ) s = re . sub ( r"[_0-9]+" , " " , s ) return s . split ( )
1
splitting word in to letter in python
Split a sentence into list of words .
cosqa-train-14616
def split_into_words(s): """Split a sentence into list of words.""" s = re.sub(r"\W+", " ", s) s = re.sub(r"[_0-9]+", " ", s) return s.split()
def gauss_pdf ( x , mu , sigma ) : return 1 / np . sqrt ( 2 * np . pi ) / sigma * np . exp ( - ( x - mu ) ** 2 / 2. / sigma ** 2 )
1
python change norm distribution to gauss
Normalized Gaussian
cosqa-train-14617
def gauss_pdf(x, mu, sigma): """Normalized Gaussian""" return 1 / np.sqrt(2 * np.pi) / sigma * np.exp(-(x - mu) ** 2 / 2. / sigma ** 2)
def bulk_query ( self , query , * multiparams ) : with self . get_connection ( ) as conn : conn . bulk_query ( query , * multiparams )
1
sql server bulk merge in python
Bulk insert or update .
cosqa-train-14618
def bulk_query(self, query, *multiparams): """Bulk insert or update.""" with self.get_connection() as conn: conn.bulk_query(query, *multiparams)
def add_exec_permission_to ( target_file ) : mode = os . stat ( target_file ) . st_mode os . chmod ( target_file , mode | stat . S_IXUSR )
1
python change permission of file
Add executable permissions to the file
cosqa-train-14619
def add_exec_permission_to(target_file): """Add executable permissions to the file :param target_file: the target file whose permission to be changed """ mode = os.stat(target_file).st_mode os.chmod(target_file, mode | stat.S_IXUSR)
def createdb ( ) : manager . db . engine . echo = True manager . db . create_all ( ) set_alembic_revision ( )
1
sqlalchemy python create database
Create database tables from sqlalchemy models
cosqa-train-14620
def createdb(): """Create database tables from sqlalchemy models""" manager.db.engine.echo = True manager.db.create_all() set_alembic_revision()
def col_rename ( df , col_name , new_col_name ) : col_list = list ( df . columns ) for index , value in enumerate ( col_list ) : if value == col_name : col_list [ index ] = new_col_name break df . columns = col_list
1
python change specific column name
Changes a column name in a DataFrame Parameters : df - DataFrame DataFrame to operate on col_name - string Name of column to change new_col_name - string New name of column
cosqa-train-14621
def col_rename(df,col_name,new_col_name): """ Changes a column name in a DataFrame Parameters: df - DataFrame DataFrame to operate on col_name - string Name of column to change new_col_name - string New name of column """ col_list = list(df.columns) for index,value in enumerate(col_list): if value == col_name: col_list[index] = new_col_name break df.columns = col_list
def get_db_version ( session ) : value = session . query ( ProgramInformation . value ) . filter ( ProgramInformation . name == "db_version" ) . scalar ( ) return int ( value )
1
sqlalchemy python get integer from query result
: param session : actually it is a sqlalchemy session : return : version number
cosqa-train-14622
def get_db_version(session): """ :param session: actually it is a sqlalchemy session :return: version number """ value = session.query(ProgramInformation.value).filter(ProgramInformation.name == "db_version").scalar() return int(value)
def _fill ( self ) : try : self . _head = self . _iterable . next ( ) except StopIteration : self . _head = None
1
python change the iterator
Advance the iterator without returning the old head .
cosqa-train-14623
def _fill(self): """Advance the iterator without returning the old head.""" try: self._head = self._iterable.next() except StopIteration: self._head = None
def get_checkerboard_matrix ( kernel_width ) : return np . vstack ( ( np . hstack ( ( - 1 * np . ones ( ( kernel_width , kernel_width ) ) , np . ones ( ( kernel_width , kernel_width ) ) ) ) , np . hstack ( ( np . ones ( ( kernel_width , kernel_width ) ) , - 1 * np . ones ( ( kernel_width , kernel_width ) ) ) ) ) )
1
square matrix with a checkerboard pattern of 0's and 1's of any given size python
example matrix for width = 2
cosqa-train-14624
def get_checkerboard_matrix(kernel_width): """ example matrix for width = 2 -1 -1 1 1 -1 -1 1 1 1 1 -1 -1 1 1 -1 -1 :param kernel_width: :return: """ return np.vstack(( np.hstack(( -1 * np.ones((kernel_width, kernel_width)), np.ones((kernel_width, kernel_width)) )), np.hstack(( np.ones((kernel_width, kernel_width)), -1 * np.ones((kernel_width, kernel_width)) )) ))
def unit_key_from_name ( name ) : result = name for old , new in six . iteritems ( UNIT_KEY_REPLACEMENTS ) : result = result . replace ( old , new ) # Collapse redundant underscores and convert to uppercase. result = re . sub ( r'_+' , '_' , result . upper ( ) ) return result
1
python change the name of a key
Return a legal python name for the given name for use as a unit key .
cosqa-train-14625
def unit_key_from_name(name): """Return a legal python name for the given name for use as a unit key.""" result = name for old, new in six.iteritems(UNIT_KEY_REPLACEMENTS): result = result.replace(old, new) # Collapse redundant underscores and convert to uppercase. result = re.sub(r'_+', '_', result.upper()) return result
def cric__lasso ( ) : model = sklearn . linear_model . LogisticRegression ( penalty = "l1" , C = 0.002 ) # we want to explain the raw probability outputs of the trees model . predict = lambda X : model . predict_proba ( X ) [ : , 1 ] return model
1
stackoverflow python logistic regression lasso
Lasso Regression
cosqa-train-14626
def cric__lasso(): """ Lasso Regression """ model = sklearn.linear_model.LogisticRegression(penalty="l1", C=0.002) # we want to explain the raw probability outputs of the trees model.predict = lambda X: model.predict_proba(X)[:,1] return model
def norm_slash ( name ) : if isinstance ( name , str ) : return name . replace ( '/' , "\\" ) if not is_case_sensitive ( ) else name else : return name . replace ( b'/' , b"\\" ) if not is_case_sensitive ( ) else name
1
python change to forward slash
Normalize path slashes .
cosqa-train-14627
def norm_slash(name): """Normalize path slashes.""" if isinstance(name, str): return name.replace('/', "\\") if not is_case_sensitive() else name else: return name.replace(b'/', b"\\") if not is_case_sensitive() else name
def hex_escape ( bin_str ) : printable = string . ascii_letters + string . digits + string . punctuation + ' ' return '' . join ( ch if ch in printable else r'0x{0:02x}' . format ( ord ( ch ) ) for ch in bin_str )
1
stackoverflow python print binary character as ascii equivalent
Hex encode a binary string
cosqa-train-14628
def hex_escape(bin_str): """ Hex encode a binary string """ printable = string.ascii_letters + string.digits + string.punctuation + ' ' return ''.join(ch if ch in printable else r'0x{0:02x}'.format(ord(ch)) for ch in bin_str)
def from_file_url ( url ) : if url . startswith ( 'file://' ) : url = url [ len ( 'file://' ) : ] . replace ( '/' , os . path . sep ) return url
0
python change url path using urlparse/unparse
Convert from file : // url to file path
cosqa-train-14629
def from_file_url(url): """ Convert from file:// url to file path """ if url.startswith('file://'): url = url[len('file://'):].replace('/', os.path.sep) return url
def static_method ( cls , f ) : setattr ( cls , f . __name__ , staticmethod ( f ) ) return f
1
static method in python exmaple
Decorator which dynamically binds static methods to the model for later use .
cosqa-train-14630
def static_method(cls, f): """Decorator which dynamically binds static methods to the model for later use.""" setattr(cls, f.__name__, staticmethod(f)) return f
def _uniquify ( _list ) : seen = set ( ) result = [ ] for x in _list : if x not in seen : result . append ( x ) seen . add ( x ) return result
1
python changing a list into a set
Remove duplicates in a list .
cosqa-train-14631
def _uniquify(_list): """Remove duplicates in a list.""" seen = set() result = [] for x in _list: if x not in seen: result.append(x) seen.add(x) return result
def _StopStatusUpdateThread ( self ) : self . _status_update_active = False if self . _status_update_thread . isAlive ( ) : self . _status_update_thread . join ( ) self . _status_update_thread = None
1
stop already running thread python
Stops the status update thread .
cosqa-train-14632
def _StopStatusUpdateThread(self): """Stops the status update thread.""" self._status_update_active = False if self._status_update_thread.isAlive(): self._status_update_thread.join() self._status_update_thread = None
def _check_key ( self , key ) : if not len ( key ) == 2 : raise TypeError ( 'invalid key: %r' % key ) elif key [ 1 ] not in TYPES : raise TypeError ( 'invalid datatype: %s' % key [ 1 ] )
1
python check all dictionary keys for type
Ensures well - formedness of a key .
cosqa-train-14633
def _check_key(self, key): """ Ensures well-formedness of a key. """ if not len(key) == 2: raise TypeError('invalid key: %r' % key) elif key[1] not in TYPES: raise TypeError('invalid datatype: %s' % key[1])
def _StopStatusUpdateThread ( self ) : self . _status_update_active = False if self . _status_update_thread . isAlive ( ) : self . _status_update_thread . join ( ) self . _status_update_thread = None
0
stop python running thread
Stops the status update thread .
cosqa-train-14634
def _StopStatusUpdateThread(self): """Stops the status update thread.""" self._status_update_active = False if self._status_update_thread.isAlive(): self._status_update_thread.join() self._status_update_thread = None
def is_iterable_of_int ( l ) : if not is_iterable ( l ) : return False return all ( is_int ( value ) for value in l )
1
python check all items in list are ints
r Checks if l is iterable and contains only integral types
cosqa-train-14635
def is_iterable_of_int(l): r""" Checks if l is iterable and contains only integral types """ if not is_iterable(l): return False return all(is_int(value) for value in l)
def kill ( self ) : if self . process : self . process . kill ( ) self . process . wait ( )
1
stop python window from closing
Kill the browser .
cosqa-train-14636
def kill(self): """Kill the browser. This is useful when the browser is stuck. """ if self.process: self.process.kill() self.process.wait()
def memory_used ( self ) : if self . _end_memory : memory_used = self . _end_memory - self . _start_memory return memory_used else : return None
1
python check current memory usage
To know the allocated memory at function termination .
cosqa-train-14637
def memory_used(self): """To know the allocated memory at function termination. ..versionadded:: 4.1 This property might return None if the function is still running. This function should help to show memory leaks or ram greedy code. """ if self._end_memory: memory_used = self._end_memory - self._start_memory return memory_used else: return None
def stop_button_click_handler ( self ) : self . stop_button . setDisabled ( True ) # Interrupt computations or stop debugging if not self . shellwidget . _reading : self . interrupt_kernel ( ) else : self . shellwidget . write_to_stdin ( 'exit' )
1
stop the python shell from execution
Method to handle what to do when the stop button is pressed
cosqa-train-14638
def stop_button_click_handler(self): """Method to handle what to do when the stop button is pressed""" self.stop_button.setDisabled(True) # Interrupt computations or stop debugging if not self.shellwidget._reading: self.interrupt_kernel() else: self.shellwidget.write_to_stdin('exit')
def has_field ( mc , field_name ) : try : mc . _meta . get_field ( field_name ) except FieldDoesNotExist : return False return True
1
python check exists of field
detect if a model has a given field has
cosqa-train-14639
def has_field(mc, field_name): """ detect if a model has a given field has :param field_name: :param mc: :return: """ try: mc._meta.get_field(field_name) except FieldDoesNotExist: return False return True
def _write_json ( file , contents ) : with open ( file , 'w' ) as f : return json . dump ( contents , f , indent = 2 , sort_keys = True )
1
store dictionary as json file in python
Write a dict to a JSON file .
cosqa-train-14640
def _write_json(file, contents): """Write a dict to a JSON file.""" with open(file, 'w') as f: return json.dump(contents, f, indent=2, sort_keys=True)
def is_readable ( filename ) : return os . path . isfile ( filename ) and os . access ( filename , os . R_OK )
1
python check file is readonly
Check if file is a regular file and is readable .
cosqa-train-14641
def is_readable(filename): """Check if file is a regular file and is readable.""" return os.path.isfile(filename) and os.access(filename, os.R_OK)
def to_array ( self ) : dt = np . dtype ( list ( zip ( self . labels , ( c . dtype for c in self . columns ) ) ) ) arr = np . empty_like ( self . columns [ 0 ] , dt ) for label in self . labels : arr [ label ] = self [ label ] return arr
1
storing columns as array python
Convert the table to a structured NumPy array .
cosqa-train-14642
def to_array(self): """Convert the table to a structured NumPy array.""" dt = np.dtype(list(zip(self.labels, (c.dtype for c in self.columns)))) arr = np.empty_like(self.columns[0], dt) for label in self.labels: arr[label] = self[label] return arr
def is_date ( thing ) : # known date types date_types = ( datetime . datetime , datetime . date , DateTime ) return isinstance ( thing , date_types )
1
python check for datetime object
Checks if the given thing represents a date
cosqa-train-14643
def is_date(thing): """Checks if the given thing represents a date :param thing: The object to check if it is a date :type thing: arbitrary object :returns: True if we have a date object :rtype: bool """ # known date types date_types = (datetime.datetime, datetime.date, DateTime) return isinstance(thing, date_types)
def __str__ ( self ) : if not hasattr ( self , '_str' ) : self . _str = self . function ( * self . args , * * self . kwargs ) return self . _str
0
str object is not callable in python
Executes self . function to convert LazyString instance to a real str .
cosqa-train-14644
def __str__(self): """Executes self.function to convert LazyString instance to a real str.""" if not hasattr(self, '_str'): self._str=self.function(*self.args, **self.kwargs) return self._str
def is_datetime_like ( dtype ) : return ( np . issubdtype ( dtype , np . datetime64 ) or np . issubdtype ( dtype , np . timedelta64 ) )
1
python check for datetime type
Check if a dtype is a subclass of the numpy datetime types
cosqa-train-14645
def is_datetime_like(dtype): """Check if a dtype is a subclass of the numpy datetime types """ return (np.issubdtype(dtype, np.datetime64) or np.issubdtype(dtype, np.timedelta64))
def boolean ( value ) : if isinstance ( value , bool ) : return value if value == "" : return False return strtobool ( value )
1
string format boolean python
Configuration - friendly boolean type converter .
cosqa-train-14646
def boolean(value): """ Configuration-friendly boolean type converter. Supports both boolean-valued and string-valued inputs (e.g. from env vars). """ if isinstance(value, bool): return value if value == "": return False return strtobool(value)
def all_strings ( arr ) : if not isinstance ( [ ] , list ) : raise TypeError ( "non-list value found where list is expected" ) return all ( isinstance ( x , str ) for x in arr )
1
python check for list of strings
Ensures that the argument is a list that either is empty or contains only strings : param arr : list : return :
cosqa-train-14647
def all_strings(arr): """ Ensures that the argument is a list that either is empty or contains only strings :param arr: list :return: """ if not isinstance([], list): raise TypeError("non-list value found where list is expected") return all(isinstance(x, str) for x in arr)
def underscore ( text ) : return UNDERSCORE [ 1 ] . sub ( r'\1_\2' , UNDERSCORE [ 0 ] . sub ( r'\1_\2' , text ) ) . lower ( )
1
string template substitute escape underscore in python
Converts text that may be camelcased into an underscored format
cosqa-train-14648
def underscore(text): """Converts text that may be camelcased into an underscored format""" return UNDERSCORE[1].sub(r'\1_\2', UNDERSCORE[0].sub(r'\1_\2', text)).lower()
def _string_hash ( s ) : h = 5381 for c in s : h = h * 33 + ord ( c ) return h
1
string to single letter hash table python
String hash ( djb2 ) with consistency between py2 / py3 and persistency between runs ( unlike hash ) .
cosqa-train-14649
def _string_hash(s): """String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`).""" h = 5381 for c in s: h = h * 33 + ord(c) return h
def _check_valid ( key , val , valid ) : if val not in valid : raise ValueError ( '%s must be one of %s, not "%s"' % ( key , valid , val ) )
1
python check for valid value
Helper to check valid options
cosqa-train-14650
def _check_valid(key, val, valid): """Helper to check valid options""" if val not in valid: raise ValueError('%s must be one of %s, not "%s"' % (key, valid, val))
def camel_to_ ( s ) : s1 = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , s ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , s1 ) . lower ( )
1
string to upper case python3
Convert CamelCase to camel_case
cosqa-train-14651
def camel_to_(s): """ Convert CamelCase to camel_case """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', s) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
def has_field ( mc , field_name ) : try : mc . _meta . get_field ( field_name ) except FieldDoesNotExist : return False return True
0
python check has field
detect if a model has a given field has
cosqa-train-14652
def has_field(mc, field_name): """ detect if a model has a given field has :param field_name: :param mc: :return: """ try: mc._meta.get_field(field_name) except FieldDoesNotExist: return False return True
def blueprint_name_to_url ( name ) : if name [ - 1 : ] == "." : name = name [ : - 1 ] name = str ( name ) . replace ( "." , "/" ) return name
1
strip fqdn from url python flask
remove the last . in the string it it ends with a . for the url structure must follow the flask routing format it should be / model / method instead of / model / method /
cosqa-train-14653
def blueprint_name_to_url(name): """ remove the last . in the string it it ends with a . for the url structure must follow the flask routing format it should be /model/method instead of /model/method/ """ if name[-1:] == ".": name = name[:-1] name = str(name).replace(".", "/") return name
def pid_exists ( pid ) : try : os . kill ( pid , 0 ) except OSError as exc : return exc . errno == errno . EPERM else : return True
0
python check if a pid is running
Determines if a system process identifer exists in process table .
cosqa-train-14654
def pid_exists(pid): """ Determines if a system process identifer exists in process table. """ try: os.kill(pid, 0) except OSError as exc: return exc.errno == errno.EPERM else: return True
def call_and_exit ( self , cmd , shell = True ) : sys . exit ( subprocess . call ( cmd , shell = shell ) )
1
subprocess python exitcode without communicate
Run the * cmd * and exit with the proper exit code .
cosqa-train-14655
def call_and_exit(self, cmd, shell=True): """Run the *cmd* and exit with the proper exit code.""" sys.exit(subprocess.call(cmd, shell=shell))
def contains_geometric_info ( var ) : return isinstance ( var , tuple ) and len ( var ) == 2 and all ( isinstance ( val , ( int , float ) ) for val in var )
1
python check if all items in a list are strings or floats
Check whether the passed variable is a tuple with two floats or integers
cosqa-train-14656
def contains_geometric_info(var): """ Check whether the passed variable is a tuple with two floats or integers """ return isinstance(var, tuple) and len(var) == 2 and all(isinstance(val, (int, float)) for val in var)
def weekly ( date = datetime . date . today ( ) ) : return date - datetime . timedelta ( days = date . weekday ( ) )
0
substracting weeks to date in python
Weeks start are fixes at Monday for now .
cosqa-train-14657
def weekly(date=datetime.date.today()): """ Weeks start are fixes at Monday for now. """ return date - datetime.timedelta(days=date.weekday())
def is_bytes ( string ) : if six . PY3 and isinstance ( string , ( bytes , memoryview , bytearray ) ) : # noqa return True elif six . PY2 and isinstance ( string , ( buffer , bytearray ) ) : # noqa return True return False
1
python check if bytes
Check if a string is a bytes instance
cosqa-train-14658
def is_bytes(string): """Check if a string is a bytes instance :param Union[str, bytes] string: A string that may be string or bytes like :return: Whether the provided string is a bytes type or not :rtype: bool """ if six.PY3 and isinstance(string, (bytes, memoryview, bytearray)): # noqa return True elif six.PY2 and isinstance(string, (buffer, bytearray)): # noqa return True return False
def Sum ( a , axis , keep_dims ) : return np . sum ( a , axis = axis if not isinstance ( axis , np . ndarray ) else tuple ( axis ) , keepdims = keep_dims ) ,
1
sum over a single axis python numpy
Sum reduction op .
cosqa-train-14659
def Sum(a, axis, keep_dims): """ Sum reduction op. """ return np.sum(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis), keepdims=keep_dims),
def closeEvent ( self , e ) : if self . _closed : return res = self . emit ( 'close' ) # Discard the close event if False is returned by one of the callback # functions. if False in res : # pragma: no cover e . ignore ( ) return super ( GUI , self ) . closeEvent ( e ) self . _closed = True
0
python check if close button has been pressed
Qt slot when the window is closed .
cosqa-train-14660
def closeEvent(self, e): """Qt slot when the window is closed.""" if self._closed: return res = self.emit('close') # Discard the close event if False is returned by one of the callback # functions. if False in res: # pragma: no cover e.ignore() return super(GUI, self).closeEvent(e) self._closed = True
def print_err ( * args , end = '\n' ) : print ( * args , end = end , file = sys . stderr ) sys . stderr . flush ( )
0
suppress python print modulr
Similar to print but prints to stderr .
cosqa-train-14661
def print_err(*args, end='\n'): """Similar to print, but prints to stderr. """ print(*args, end=end, file=sys.stderr) sys.stderr.flush()
def _isstring ( dtype ) : return dtype . type == numpy . unicode_ or dtype . type == numpy . string_
1
python check if column is a string
Given a numpy dtype determines whether it is a string . Returns True if the dtype is string or unicode .
cosqa-train-14662
def _isstring(dtype): """Given a numpy dtype, determines whether it is a string. Returns True if the dtype is string or unicode. """ return dtype.type == numpy.unicode_ or dtype.type == numpy.string_
def byteswap ( data , word_size = 4 ) : return reduce ( lambda x , y : x + '' . join ( reversed ( y ) ) , chunks ( data , word_size ) , '' )
1
swapping bytes of data python
Swap the byte - ordering in a packet with N = 4 bytes per word
cosqa-train-14663
def byteswap(data, word_size=4): """ Swap the byte-ordering in a packet with N=4 bytes per word """ return reduce(lambda x,y: x+''.join(reversed(y)), chunks(data, word_size), '')
def is_executable ( path ) : return os . path . isfile ( path ) and os . access ( path , os . X_OK )
1
python check if executable exists in path
Returns whether a path names an existing executable file .
cosqa-train-14664
def is_executable(path): """Returns whether a path names an existing executable file.""" return os.path.isfile(path) and os.access(path, os.X_OK)
def instance_contains ( container , item ) : return item in ( member for _ , member in inspect . getmembers ( container ) )
0
syntax for contains in python
Search into instance attributes properties and return values of no - args methods .
cosqa-train-14665
def instance_contains(container, item): """Search into instance attributes, properties and return values of no-args methods.""" return item in (member for _, member in inspect.getmembers(container))
def column_exists ( cr , table , column ) : cr . execute ( 'SELECT count(attname) FROM pg_attribute ' 'WHERE attrelid = ' '( SELECT oid FROM pg_class WHERE relname = %s ) ' 'AND attname = %s' , ( table , column ) ) return cr . fetchone ( ) [ 0 ] == 1
1
python check if field exists in sql table
Check whether a certain column exists
cosqa-train-14666
def column_exists(cr, table, column): """ Check whether a certain column exists """ cr.execute( 'SELECT count(attname) FROM pg_attribute ' 'WHERE attrelid = ' '( SELECT oid FROM pg_class WHERE relname = %s ) ' 'AND attname = %s', (table, column)) return cr.fetchone()[0] == 1
def get_dimension_array ( array ) : if all ( isinstance ( el , list ) for el in array ) : result = [ len ( array ) , len ( max ( [ x for x in array ] , key = len , ) ) ] # elif array and isinstance(array, list): else : result = [ len ( array ) , 1 ] return result
1
t dimensions of alist in python
Get dimension of an array getting the number of rows and the max num of columns .
cosqa-train-14667
def get_dimension_array(array): """ Get dimension of an array getting the number of rows and the max num of columns. """ if all(isinstance(el, list) for el in array): result = [len(array), len(max([x for x in array], key=len,))] # elif array and isinstance(array, list): else: result = [len(array), 1] return result
def is_valid_file ( parser , arg ) : arg = os . path . abspath ( arg ) if not os . path . exists ( arg ) : parser . error ( "The file %s does not exist!" % arg ) else : return arg
1
python check if file exists in path variable
Check if arg is a valid file that already exists on the file system .
cosqa-train-14668
def is_valid_file(parser, arg): """Check if arg is a valid file that already exists on the file system.""" arg = os.path.abspath(arg) if not os.path.exists(arg): parser.error("The file %s does not exist!" % arg) else: return arg
def ci ( a , which = 95 , axis = None ) : p = 50 - which / 2 , 50 + which / 2 return percentiles ( a , p , axis )
1
take 25 and 75 percentile python
Return a percentile range from an array of values .
cosqa-train-14669
def ci(a, which=95, axis=None): """Return a percentile range from an array of values.""" p = 50 - which / 2, 50 + which / 2 return percentiles(a, p, axis)
def is_readable ( fp , size = 1 ) : read_size = len ( fp . read ( size ) ) fp . seek ( - read_size , 1 ) return read_size == size
1
python check if file size is zero
Check if the file - like object is readable .
cosqa-train-14670
def is_readable(fp, size=1): """ Check if the file-like object is readable. :param fp: file-like object :param size: byte size :return: bool """ read_size = len(fp.read(size)) fp.seek(-read_size, 1) return read_size == size
def point8_to_box ( points ) : p = points . reshape ( ( - 1 , 4 , 2 ) ) minxy = p . min ( axis = 1 ) # nx2 maxxy = p . max ( axis = 1 ) # nx2 return np . concatenate ( ( minxy , maxxy ) , axis = 1 )
1
take all points in box python
Args : points : ( nx4 ) x2 Returns : nx4 boxes ( x1y1x2y2 )
cosqa-train-14671
def point8_to_box(points): """ Args: points: (nx4)x2 Returns: nx4 boxes (x1y1x2y2) """ p = points.reshape((-1, 4, 2)) minxy = p.min(axis=1) # nx2 maxxy = p.max(axis=1) # nx2 return np.concatenate((minxy, maxxy), axis=1)
def determine_interactive ( self ) : try : if not sys . stdout . isatty ( ) or os . getpgrp ( ) != os . tcgetpgrp ( sys . stdout . fileno ( ) ) : self . interactive = 0 return False except Exception : self . interactive = 0 return False if self . interactive == 0 : return False return True
1
python check if in interactive mode
Determine whether we re in an interactive shell . Sets interactivity off if appropriate . cf http : // stackoverflow . com / questions / 24861351 / how - to - detect - if - python - script - is - being - run - as - a - background - process
cosqa-train-14672
def determine_interactive(self): """Determine whether we're in an interactive shell. Sets interactivity off if appropriate. cf http://stackoverflow.com/questions/24861351/how-to-detect-if-python-script-is-being-run-as-a-background-process """ try: if not sys.stdout.isatty() or os.getpgrp() != os.tcgetpgrp(sys.stdout.fileno()): self.interactive = 0 return False except Exception: self.interactive = 0 return False if self.interactive == 0: return False return True
def _first_and_last_element ( arr ) : if isinstance ( arr , np . ndarray ) or hasattr ( arr , 'data' ) : # numpy array or sparse matrix with .data attribute data = arr . data if sparse . issparse ( arr ) else arr return data . flat [ 0 ] , data . flat [ - 1 ] else : # Sparse matrices without .data attribute. Only dok_matrix at # the time of writing, in this case indexing is fast return arr [ 0 , 0 ] , arr [ - 1 , - 1 ]
0
take first element of multi dimensional array in python
Returns first and last element of numpy array or sparse matrix .
cosqa-train-14673
def _first_and_last_element(arr): """Returns first and last element of numpy array or sparse matrix.""" if isinstance(arr, np.ndarray) or hasattr(arr, 'data'): # numpy array or sparse matrix with .data attribute data = arr.data if sparse.issparse(arr) else arr return data.flat[0], data.flat[-1] else: # Sparse matrices without .data attribute. Only dok_matrix at # the time of writing, in this case indexing is fast return arr[0, 0], arr[-1, -1]
def __contains__ ( self , key ) : k = self . _real_key ( key ) return k in self . _data
1
python check if key in dect
Invoked when determining whether a specific key is in the dictionary using key in d .
cosqa-train-14674
def __contains__(self, key): """ Invoked when determining whether a specific key is in the dictionary using `key in d`. The key is looked up case-insensitively. """ k = self._real_key(key) return k in self._data
def _clean_dict ( target_dict , whitelist = None ) : assert isinstance ( target_dict , dict ) return { ustr ( k ) . strip ( ) : ustr ( v ) . strip ( ) for k , v in target_dict . items ( ) if v not in ( None , Ellipsis , [ ] , ( ) , "" ) and ( not whitelist or k in whitelist ) }
1
test for empty python dictionary
Convenience function that removes a dicts keys that have falsy values
cosqa-train-14675
def _clean_dict(target_dict, whitelist=None): """ Convenience function that removes a dicts keys that have falsy values """ assert isinstance(target_dict, dict) return { ustr(k).strip(): ustr(v).strip() for k, v in target_dict.items() if v not in (None, Ellipsis, [], (), "") and (not whitelist or k in whitelist) }
def hasattrs ( object , * names ) : for name in names : if not hasattr ( object , name ) : return False return True
1
python check if object has attribute and if it is not none
Takes in an object and a variable length amount of named attributes and checks to see if the object has each property . If any of the attributes are missing this returns false .
cosqa-train-14676
def hasattrs(object, *names): """ Takes in an object and a variable length amount of named attributes, and checks to see if the object has each property. If any of the attributes are missing, this returns false. :param object: an object that may or may not contain the listed attributes :param names: a variable amount of attribute names to check for :return: True if the object contains each named attribute, false otherwise """ for name in names: if not hasattr(object, name): return False return True
def is_iterable_but_not_string ( obj ) : return hasattr ( obj , '__iter__' ) and not isinstance ( obj , str ) and not isinstance ( obj , bytes )
1
test for iterable is string in python
Determine whether or not obj is iterable but not a string ( eg a list set tuple etc ) .
cosqa-train-14677
def is_iterable_but_not_string(obj): """ Determine whether or not obj is iterable but not a string (eg, a list, set, tuple etc). """ return hasattr(obj, '__iter__') and not isinstance(obj, str) and not isinstance(obj, bytes)
def has_field ( mc , field_name ) : try : mc . _meta . get_field ( field_name ) except FieldDoesNotExist : return False return True
1
python check if object has field
detect if a model has a given field has
cosqa-train-14678
def has_field(mc, field_name): """ detect if a model has a given field has :param field_name: :param mc: :return: """ try: mc._meta.get_field(field_name) except FieldDoesNotExist: return False return True
def is_valid_regex ( string ) : try : re . compile ( string ) is_valid = True except re . error : is_valid = False return is_valid
1
test if a regexp match fails in python
Checks whether the re module can compile the given regular expression .
cosqa-train-14679
def is_valid_regex(string): """ Checks whether the re module can compile the given regular expression. Parameters ---------- string: str Returns ------- boolean """ try: re.compile(string) is_valid = True except re.error: is_valid = False return is_valid
def pid_exists ( pid ) : try : os . kill ( pid , 0 ) except OSError as exc : return exc . errno == errno . EPERM else : return True
1
python check if pid exists
Determines if a system process identifer exists in process table .
cosqa-train-14680
def pid_exists(pid): """ Determines if a system process identifer exists in process table. """ try: os.kill(pid, 0) except OSError as exc: return exc.errno == errno.EPERM else: return True
def is_listish ( obj ) : if isinstance ( obj , ( list , tuple , set ) ) : return True return is_sequence ( obj )
1
test if instance is list python
Check if something quacks like a list .
cosqa-train-14681
def is_listish(obj): """Check if something quacks like a list.""" if isinstance(obj, (list, tuple, set)): return True return is_sequence(obj)
def _using_stdout ( self ) : if WINDOWS and colorama : # Then self.stream is an AnsiToWin32 object. return self . stream . wrapped is sys . stdout return self . stream is sys . stdout
1
python check if stdout is readable
Return whether the handler is using sys . stdout .
cosqa-train-14682
def _using_stdout(self): """ Return whether the handler is using sys.stdout. """ if WINDOWS and colorama: # Then self.stream is an AnsiToWin32 object. return self.stream.wrapped is sys.stdout return self.stream is sys.stdout
def unicode_is_ascii ( u_string ) : assert isinstance ( u_string , str ) try : u_string . encode ( 'ascii' ) return True except UnicodeEncodeError : return False
1
test to see if a character is non ascii in python
Determine if unicode string only contains ASCII characters .
cosqa-train-14683
def unicode_is_ascii(u_string): """Determine if unicode string only contains ASCII characters. :param str u_string: unicode string to check. Must be unicode and not Python 2 `str`. :rtype: bool """ assert isinstance(u_string, str) try: u_string.encode('ascii') return True except UnicodeEncodeError: return False
def 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
0
python check if string is hex value
Check if the string is only composed of hex characters .
cosqa-train-14684
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 is_lazy_iterable ( obj ) : return isinstance ( obj , ( types . GeneratorType , collections . MappingView , six . moves . range , enumerate ) )
1
test whether python object is iterable
Returns whether * obj * is iterable lazily such as generators range objects etc .
cosqa-train-14685
def is_lazy_iterable(obj): """ Returns whether *obj* is iterable lazily, such as generators, range objects, etc. """ return isinstance(obj, (types.GeneratorType, collections.MappingView, six.moves.range, enumerate))
def user_in_all_groups ( user , groups ) : return user_is_superuser ( user ) or all ( user_in_group ( user , group ) for group in groups )
1
python check if user in group
Returns True if the given user is in all given groups
cosqa-train-14686
def user_in_all_groups(user, groups): """Returns True if the given user is in all given groups""" return user_is_superuser(user) or all(user_in_group(user, group) for group in groups)
def unicode_is_ascii ( u_string ) : assert isinstance ( u_string , str ) try : u_string . encode ( 'ascii' ) return True except UnicodeEncodeError : return False
1
testing whether a string is ascii in python
Determine if unicode string only contains ASCII characters .
cosqa-train-14687
def unicode_is_ascii(u_string): """Determine if unicode string only contains ASCII characters. :param str u_string: unicode string to check. Must be unicode and not Python 2 `str`. :rtype: bool """ assert isinstance(u_string, str) try: u_string.encode('ascii') return True except UnicodeEncodeError: return False
def is_float ( value ) : return isinstance ( value , float ) or isinstance ( value , int ) or isinstance ( value , np . float64 ) , float ( value )
1
python check if variable is float, int, boolean
must be a float
cosqa-train-14688
def is_float(value): """must be a float""" return isinstance(value, float) or isinstance(value, int) or isinstance(value, np.float64), float(value)
def wrap ( s , width = 80 ) : return '\n' . join ( textwrap . wrap ( str ( s ) , width = width ) )
1
text wrap on python with raw input
Formats the text input with newlines given the user specified width for each line .
cosqa-train-14689
def wrap(s, width=80): """ Formats the text input with newlines given the user specified width for each line. Parameters ---------- s : str width : int Returns ------- text : str Notes ----- .. versionadded:: 1.1 """ return '\n'.join(textwrap.wrap(str(s), width=width))
def has_virtualenv ( self ) : with self . settings ( warn_only = True ) : ret = self . run_or_local ( 'which virtualenv' ) . strip ( ) return bool ( ret )
1
python check if virtualenv is activated
Returns true if the virtualenv tool is installed .
cosqa-train-14690
def has_virtualenv(self): """ Returns true if the virtualenv tool is installed. """ with self.settings(warn_only=True): ret = self.run_or_local('which virtualenv').strip() return bool(ret)
def normalize_text ( text , line_len = 80 , indent = "" ) : return "\n" . join ( textwrap . wrap ( text , width = line_len , initial_indent = indent , subsequent_indent = indent ) )
0
textwrapping examples using python
Wrap the text on the given line length .
cosqa-train-14691
def normalize_text(text, line_len=80, indent=""): """Wrap the text on the given line length.""" return "\n".join( textwrap.wrap( text, width=line_len, initial_indent=indent, subsequent_indent=indent ) )
def get_substring_idxs ( substr , string ) : return [ match . start ( ) for match in re . finditer ( substr , string ) ]
1
python check index of a substring
Return a list of indexes of substr . If substr not found list is empty .
cosqa-train-14692
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 mul ( a , b ) : def multiply ( a , b ) : """Multiplication""" return a * b return op_with_scalar_cast ( a , b , multiply )
1
tf have no attribute python
A wrapper around tf multiplication that does more automatic casting of the input .
cosqa-train-14693
def mul(a, b): """ A wrapper around tf multiplication that does more automatic casting of the input. """ def multiply(a, b): """Multiplication""" return a * b return op_with_scalar_cast(a, b, multiply)
def percent_d ( data , period ) : p_k = percent_k ( data , period ) percent_d = sma ( p_k , 3 ) return percent_d
0
the function of the percent symbol in python
%D .
cosqa-train-14694
def percent_d(data, period): """ %D. Formula: %D = SMA(%K, 3) """ p_k = percent_k(data, period) percent_d = sma(p_k, 3) return percent_d
def service_available ( service_name ) : try : subprocess . check_output ( [ 'service' , service_name , 'status' ] , stderr = subprocess . STDOUT ) . decode ( 'UTF-8' ) except subprocess . CalledProcessError as e : return b'unrecognized service' not in e . output else : return True
1
python check status of linux service
Determine whether a system service is available
cosqa-train-14695
def service_available(service_name): """Determine whether a system service is available""" try: subprocess.check_output( ['service', service_name, 'status'], stderr=subprocess.STDOUT).decode('UTF-8') except subprocess.CalledProcessError as e: return b'unrecognized service' not in e.output else: return True
def _dt_to_epoch ( dt ) : try : epoch = dt . timestamp ( ) except AttributeError : # py2 epoch = ( dt - datetime ( 1970 , 1 , 1 ) ) . total_seconds ( ) return epoch
1
time since epoch in seconds python
Convert datetime to epoch seconds .
cosqa-train-14696
def _dt_to_epoch(dt): """Convert datetime to epoch seconds.""" try: epoch = dt.timestamp() except AttributeError: # py2 epoch = (dt - datetime(1970, 1, 1)).total_seconds() return epoch
def 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
python check string is hex
Check if the string is only composed of hex characters .
cosqa-train-14697
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 now ( timezone = None ) : d = datetime . datetime . utcnow ( ) if not timezone : return d return to_timezone ( d , timezone ) . replace ( tzinfo = None )
1
timezone python central time zone
Return a naive datetime object for the given timezone . A timezone is any pytz - like or datetime . tzinfo - like timezone object . If no timezone is given then UTC is assumed .
cosqa-train-14698
def now(timezone=None): """ Return a naive datetime object for the given ``timezone``. A ``timezone`` is any pytz- like or datetime.tzinfo-like timezone object. If no timezone is given, then UTC is assumed. This method is best used with pytz installed:: pip install pytz """ d = datetime.datetime.utcnow() if not timezone: return d return to_timezone(d, timezone).replace(tzinfo=None)
def _is_path ( s ) : if isinstance ( s , string_types ) : try : return op . exists ( s ) except ( OSError , ValueError ) : return False else : return False
1
python check string is path
Return whether an object is a path .
cosqa-train-14699
def _is_path(s): """Return whether an object is a path.""" if isinstance(s, string_types): try: return op.exists(s) except (OSError, ValueError): return False else: return False