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 inc_date ( date_obj , num , date_fmt ) : return ( date_obj + timedelta ( days = num ) ) . strftime ( date_fmt )
0
change the format of a date python
Increment the date by a certain number and return date object . as the specific string format .
cosqa-train-15000
def inc_date(date_obj, num, date_fmt): """Increment the date by a certain number and return date object. as the specific string format. """ return (date_obj + timedelta(days=num)).strftime(date_fmt)
def last_month ( ) : since = TODAY + delta ( day = 1 , months = - 1 ) until = since + delta ( months = 1 ) return Date ( since ) , Date ( until )
1
python datetime start date and end date of that month
Return start and end date of this month .
cosqa-train-15001
def last_month(): """ Return start and end date of this month. """ since = TODAY + delta(day=1, months=-1) until = since + delta(months=1) return Date(since), Date(until)
def select_down ( self ) : r , c = self . _index self . _select_index ( r + 1 , c )
0
change the index after selection python
move cursor down
cosqa-train-15002
def select_down(self): """move cursor down""" r, c = self._index self._select_index(r+1, c)
def QA_util_datetime_to_strdate ( dt ) : strdate = "%04d-%02d-%02d" % ( dt . year , dt . month , dt . day ) return strdate
0
python datetime strp date
: param dt : pythone datetime . datetime : return : 1999 - 02 - 01 string type
cosqa-train-15003
def QA_util_datetime_to_strdate(dt): """ :param dt: pythone datetime.datetime :return: 1999-02-01 string type """ strdate = "%04d-%02d-%02d" % (dt.year, dt.month, dt.day) return strdate
def round_sig ( x , sig ) : return round ( x , sig - int ( floor ( log10 ( abs ( x ) ) ) ) - 1 )
0
change to signed number python
Round the number to the specified number of significant figures
cosqa-train-15004
def round_sig(x, sig): """Round the number to the specified number of significant figures""" return round(x, sig - int(floor(log10(abs(x)))) - 1)
def _DateToEpoch ( date ) : tz_zero = datetime . datetime . utcfromtimestamp ( 0 ) diff_sec = int ( ( date - tz_zero ) . total_seconds ( ) ) return diff_sec * 1000000
1
python datetime to microseconds since epoch
Converts python datetime to epoch microseconds .
cosqa-train-15005
def _DateToEpoch(date): """Converts python datetime to epoch microseconds.""" tz_zero = datetime.datetime.utcfromtimestamp(0) diff_sec = int((date - tz_zero).total_seconds()) return diff_sec * 1000000
def robust_int ( v ) : if isinstance ( v , int ) : return v if isinstance ( v , float ) : return int ( v ) v = str ( v ) . replace ( ',' , '' ) if not v : return None return int ( v )
0
change type from float to integer python
Parse an int robustly ignoring commas and other cruft .
cosqa-train-15006
def robust_int(v): """Parse an int robustly, ignoring commas and other cruft. """ if isinstance(v, int): return v if isinstance(v, float): return int(v) v = str(v).replace(',', '') if not v: return None return int(v)
def fromtimestamp ( cls , timestamp ) : d = cls . utcfromtimestamp ( timestamp ) return d . astimezone ( localtz ( ) )
0
python datetime utcfromtimestamp time zone
Returns a datetime object of a given timestamp ( in local tz ) .
cosqa-train-15007
def fromtimestamp(cls, timestamp): """Returns a datetime object of a given timestamp (in local tz).""" d = cls.utcfromtimestamp(timestamp) return d.astimezone(localtz())
def to_str ( s ) : if isinstance ( s , bytes ) : s = s . decode ( 'utf-8' ) elif not isinstance ( s , str ) : s = str ( s ) return s
0
change type of string in python
Convert bytes and non - string into Python 3 str
cosqa-train-15008
def to_str(s): """ Convert bytes and non-string into Python 3 str """ if isinstance(s, bytes): s = s.decode('utf-8') elif not isinstance(s, str): s = str(s) return s
def today ( year = None ) : return datetime . date ( int ( year ) , _date . month , _date . day ) if year else _date
0
python datetime with only year and month
this day last year
cosqa-train-15009
def today(year=None): """this day, last year""" return datetime.date(int(year), _date.month, _date.day) if year else _date
def log_y_cb ( self , w , val ) : self . tab_plot . logy = val self . plot_two_columns ( )
1
change y axis to log scale python
Toggle linear / log scale for Y - axis .
cosqa-train-15010
def log_y_cb(self, w, val): """Toggle linear/log scale for Y-axis.""" self.tab_plot.logy = val self.plot_two_columns()
def toBase64 ( s ) : if isinstance ( s , str ) : s = s . encode ( "utf-8" ) return binascii . b2a_base64 ( s ) [ : - 1 ]
1
python decode and print base64 string
Represent string / bytes s as base64 omitting newlines
cosqa-train-15011
def toBase64(s): """Represent string / bytes s as base64, omitting newlines""" if isinstance(s, str): s = s.encode("utf-8") return binascii.b2a_base64(s)[:-1]
def energy_string_to_float ( string ) : energy_re = re . compile ( "(-?\d+\.\d+)" ) return float ( energy_re . match ( string ) . group ( 0 ) )
1
changing a string to a float python
Convert a string of a calculation energy e . g . - 1 . 2345 eV to a float .
cosqa-train-15012
def energy_string_to_float( string ): """ Convert a string of a calculation energy, e.g. '-1.2345 eV' to a float. Args: string (str): The string to convert. Return (float) """ energy_re = re.compile( "(-?\d+\.\d+)" ) return float( energy_re.match( string ).group(0) )
def append_pdf ( input_pdf : bytes , output_writer : PdfFileWriter ) : append_memory_pdf_to_writer ( input_pdf = input_pdf , writer = output_writer )
0
python decrease pdf file size
Appends a PDF to a pyPDF writer . Legacy interface .
cosqa-train-15013
def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter): """ Appends a PDF to a pyPDF writer. Legacy interface. """ append_memory_pdf_to_writer(input_pdf=input_pdf, writer=output_writer)
def add_exec_permission_to ( target_file ) : mode = os . stat ( target_file ) . st_mode os . chmod ( target_file , mode | stat . S_IXUSR )
0
changing file permissions in python
Add executable permissions to the file
cosqa-train-15014
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 _iterable_to_varargs_method ( func ) : def wrapped ( self , * args , * * kwargs ) : return func ( self , args , * * kwargs ) return wrapped
1
python def wrapper(*args, **kwargs)
decorator to convert a method taking a iterable to a * args one
cosqa-train-15015
def _iterable_to_varargs_method(func): """decorator to convert a method taking a iterable to a *args one""" def wrapped(self, *args, **kwargs): return func(self, args, **kwargs) return wrapped
def auto ( ) : try : Style . enabled = False Style . enabled = sys . stdout . isatty ( ) except ( AttributeError , TypeError ) : pass
1
changing stdout color in python
set colouring on if STDOUT is a terminal device off otherwise
cosqa-train-15016
def auto(): """set colouring on if STDOUT is a terminal device, off otherwise""" try: Style.enabled = False Style.enabled = sys.stdout.isatty() except (AttributeError, TypeError): pass
def set_default ( self , key , value ) : k = self . _real_key ( key . lower ( ) ) self . _defaults [ k ] = value
0
python default dict set default value
Set the default value for this key . Default only used when no value is provided by the user via arg config or env .
cosqa-train-15017
def set_default(self, key, value): """Set the default value for this key. Default only used when no value is provided by the user via arg, config or env. """ k = self._real_key(key.lower()) self._defaults[k] = value
def is_int_type ( val ) : try : # Python 2 return isinstance ( val , ( int , long ) ) except NameError : # Python 3 return isinstance ( val , int )
1
check a num is int python
Return True if val is of integer type .
cosqa-train-15018
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 empty ( self , start = None , stop = None ) : self . set ( NOT_SET , start = start , stop = stop )
1
python defeine set range
Empty the range from start to stop .
cosqa-train-15019
def empty(self, start=None, stop=None): """Empty the range from start to stop. Like delete, but no Error is raised if the entire range isn't mapped. """ self.set(NOT_SET, start=start, stop=stop)
def matrix_at_check ( self , original , loc , tokens ) : return self . check_py ( "35" , "matrix multiplication" , original , loc , tokens )
1
check context free grammar for python
Check for Python 3 . 5 matrix multiplication .
cosqa-train-15020
def matrix_at_check(self, original, loc, tokens): """Check for Python 3.5 matrix multiplication.""" return self.check_py("35", "matrix multiplication", original, loc, tokens)
def show_xticklabels ( self , row , column ) : subplot = self . get_subplot_at ( row , column ) subplot . show_xticklabels ( )
1
python define x axis from colum of subplot
Show the x - axis tick labels for a subplot .
cosqa-train-15021
def show_xticklabels(self, row, column): """Show the x-axis tick labels for a subplot. :param row,column: specify the subplot. """ subplot = self.get_subplot_at(row, column) subplot.show_xticklabels()
def is_timestamp ( obj ) : return isinstance ( obj , datetime . datetime ) or is_string ( obj ) or is_int ( obj ) or is_float ( obj )
0
check datatype of column python
Yaml either have automatically converted it to a datetime object or it is a string that will be validated later .
cosqa-train-15022
def is_timestamp(obj): """ Yaml either have automatically converted it to a datetime object or it is a string that will be validated later. """ return isinstance(obj, datetime.datetime) or is_string(obj) or is_int(obj) or is_float(obj)
def is_date ( thing ) : # known date types date_types = ( datetime . datetime , datetime . date , DateTime ) return isinstance ( thing , date_types )
1
check date type in python
Checks if the given thing represents a date
cosqa-train-15023
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 seconds ( num ) : now = pytime . time ( ) end = now + num until ( end )
1
python delay between loop
Pause for this many seconds
cosqa-train-15024
def seconds(num): """ Pause for this many seconds """ now = pytime.time() end = now + num until(end)
def _get_mtime ( ) : return os . path . exists ( RPM_PATH ) and int ( os . path . getmtime ( RPM_PATH ) ) or 0
1
check disk active time python
Get the modified time of the RPM Database .
cosqa-train-15025
def _get_mtime(): """ Get the modified time of the RPM Database. Returns: Unix ticks """ return os.path.exists(RPM_PATH) and int(os.path.getmtime(RPM_PATH)) or 0
def del_object_from_parent ( self ) : if self . parent : self . parent . objects . pop ( self . ref )
1
python delete an object if it exists
Delete object from parent object .
cosqa-train-15026
def del_object_from_parent(self): """ Delete object from parent object. """ if self.parent: self.parent.objects.pop(self.ref)
def get_file_size ( filename ) : if os . path . isfile ( filename ) : return convert_size ( os . path . getsize ( filename ) ) return None
1
check file size in python
Get the file size of a given file
cosqa-train-15027
def get_file_size(filename): """ Get the file size of a given file :param filename: string: pathname of a file :return: human readable filesize """ if os.path.isfile(filename): return convert_size(os.path.getsize(filename)) return None
def close ( * args , * * kwargs ) : _ , plt , _ = _import_plt ( ) plt . close ( * args , * * kwargs )
0
python delete matplotlib frame
r Close last created figure alias to plt . close () .
cosqa-train-15028
def close(*args, **kwargs): r"""Close last created figure, alias to ``plt.close()``.""" _, plt, _ = _import_plt() plt.close(*args, **kwargs)
def up ( self ) : if self . frame : self . frame = self . frame . f_back return self . frame is None
0
check for empty frame python
Go up in stack and return True if top frame
cosqa-train-15029
def up(self): """Go up in stack and return True if top frame""" if self.frame: self.frame = self.frame.f_back return self.frame is None
def safe_rmtree ( directory ) : if os . path . exists ( directory ) : shutil . rmtree ( directory , True )
1
python delete not empty directory
Delete a directory if it s present . If it s not present no - op .
cosqa-train-15030
def safe_rmtree(directory): """Delete a directory if it's present. If it's not present, no-op.""" if os.path.exists(directory): shutil.rmtree(directory, True)
def is_square_matrix ( mat ) : mat = np . array ( mat ) if mat . ndim != 2 : return False shape = mat . shape return shape [ 0 ] == shape [ 1 ]
0
check if a matrix in singular python
Test if an array is a square matrix .
cosqa-train-15031
def is_square_matrix(mat): """Test if an array is a square matrix.""" mat = np.array(mat) if mat.ndim != 2: return False shape = mat.shape return shape[0] == shape[1]
def invalidate_cache ( cpu , address , size ) : cache = cpu . instruction_cache for offset in range ( size ) : if address + offset in cache : del cache [ address + offset ]
1
python delete variable remove from memory
remove decoded instruction from instruction cache
cosqa-train-15032
def invalidate_cache(cpu, address, size): """ remove decoded instruction from instruction cache """ cache = cpu.instruction_cache for offset in range(size): if address + offset in cache: del cache[address + offset]
def _is_one_arg_pos_call ( call ) : return isinstance ( call , astroid . Call ) and len ( call . args ) == 1 and not call . keywords
0
check if argumnets are blank python
Is this a call with exactly 1 argument where that argument is positional?
cosqa-train-15033
def _is_one_arg_pos_call(call): """Is this a call with exactly 1 argument, where that argument is positional? """ return isinstance(call, astroid.Call) and len(call.args) == 1 and not call.keywords
def __exit__ ( self , * args ) : sys . stdout = self . _orig self . _devnull . close ( )
1
python deleting printout from the command window
Redirect stdout back to the original stdout .
cosqa-train-15034
def __exit__(self, *args): """Redirect stdout back to the original stdout.""" sys.stdout = self._orig self._devnull.close()
def is_int_type ( val ) : try : # Python 2 return isinstance ( val , ( int , long ) ) except NameError : # Python 3 return isinstance ( val , int )
1
check if input is int python
Return True if val is of integer type .
cosqa-train-15035
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 _sanitize ( text ) : d = { '-LRB-' : '(' , '-RRB-' : ')' } return re . sub ( '|' . join ( d . keys ( ) ) , lambda m : d [ m . group ( 0 ) ] , text )
0
python deleting spaces in string
Return sanitized Eidos text field for human readability .
cosqa-train-15036
def _sanitize(text): """Return sanitized Eidos text field for human readability.""" d = {'-LRB-': '(', '-RRB-': ')'} return re.sub('|'.join(d.keys()), lambda m: d[m.group(0)], text)
def _IsDirectory ( parent , item ) : return tf . io . gfile . isdir ( os . path . join ( parent , item ) )
1
check if item is folder or file in python
Helper that returns if parent / item is a directory .
cosqa-train-15037
def _IsDirectory(parent, item): """Helper that returns if parent/item is a directory.""" return tf.io.gfile.isdir(os.path.join(parent, item))
def from_json ( cls , json_str ) : d = json . loads ( json_str ) return cls . from_dict ( d )
0
python deserialize json to object
Deserialize the object from a JSON string .
cosqa-train-15038
def from_json(cls, json_str): """Deserialize the object from a JSON string.""" d = json.loads(json_str) return cls.from_dict(d)
def __contains__ ( self , key ) : assert isinstance ( key , basestring ) return dict . __contains__ ( self , key . lower ( ) )
0
check if key in dictionary either case python
Check lowercase key item .
cosqa-train-15039
def __contains__ (self, key): """Check lowercase key item.""" assert isinstance(key, basestring) return dict.__contains__(self, key.lower())
def dispose_orm ( ) : log . debug ( "Disposing DB connection pool (PID %s)" , os . getpid ( ) ) global engine global Session if Session : Session . remove ( ) Session = None if engine : engine . dispose ( ) engine = None
0
python destructor database connections
Properly close pooled database connections
cosqa-train-15040
def dispose_orm(): """ Properly close pooled database connections """ log.debug("Disposing DB connection pool (PID %s)", os.getpid()) global engine global Session if Session: Session.remove() Session = None if engine: engine.dispose() engine = None
def is_iter_non_string ( obj ) : if isinstance ( obj , list ) or isinstance ( obj , tuple ) : return True return False
0
check if python object isiterable
test if object is a list or tuple
cosqa-train-15041
def is_iter_non_string(obj): """test if object is a list or tuple""" if isinstance(obj, list) or isinstance(obj, tuple): return True return False
def lock_file ( f , block = False ) : try : flags = fcntl . LOCK_EX if not block : flags |= fcntl . LOCK_NB fcntl . flock ( f . fileno ( ) , flags ) except IOError as e : if e . errno in ( errno . EACCES , errno . EAGAIN ) : raise SystemExit ( "ERROR: %s is locked by another process." % f . name ) raise
0
python detect file is locked
If block = False ( the default ) die hard and fast if another process has already grabbed the lock for this file .
cosqa-train-15042
def lock_file(f, block=False): """ If block=False (the default), die hard and fast if another process has already grabbed the lock for this file. If block=True, wait for the lock to be released, then continue. """ try: flags = fcntl.LOCK_EX if not block: flags |= fcntl.LOCK_NB fcntl.flock(f.fileno(), flags) except IOError as e: if e.errno in (errno.EACCES, errno.EAGAIN): raise SystemExit("ERROR: %s is locked by another process." % f.name) raise
def is_valid_row ( cls , row ) : for k in row . keys ( ) : if row [ k ] is None : return False return True
0
check if row is none python
Indicates whether or not the given row contains valid data .
cosqa-train-15043
def is_valid_row(cls, row): """Indicates whether or not the given row contains valid data.""" for k in row.keys(): if row[k] is None: return False return True
def is_symlink ( self ) : try : return S_ISLNK ( self . lstat ( ) . st_mode ) except OSError as e : if e . errno != ENOENT : raise # Path doesn't exist return False
1
python detect if a file is a symbolic link
Whether this path is a symbolic link .
cosqa-train-15044
def is_symlink(self): """ Whether this path is a symbolic link. """ try: return S_ISLNK(self.lstat().st_mode) except OSError as e: if e.errno != ENOENT: raise # Path doesn't exist return False
def stdin_readable ( ) : if not WINDOWS : try : return bool ( select ( [ sys . stdin ] , [ ] , [ ] , 0 ) [ 0 ] ) except Exception : logger . log_exc ( ) try : return not sys . stdin . isatty ( ) except Exception : logger . log_exc ( ) return False
1
check if stdin is provided python
Determine whether stdin has any data to read .
cosqa-train-15045
def stdin_readable(): """Determine whether stdin has any data to read.""" if not WINDOWS: try: return bool(select([sys.stdin], [], [], 0)[0]) except Exception: logger.log_exc() try: return not sys.stdin.isatty() except Exception: logger.log_exc() return False
def is_image ( filename ) : # note: isfile() also accepts symlinks return os . path . isfile ( filename ) and filename . lower ( ) . endswith ( ImageExts )
1
python determine if a file is image
Determine if given filename is an image .
cosqa-train-15046
def is_image(filename): """Determine if given filename is an image.""" # note: isfile() also accepts symlinks return os.path.isfile(filename) and filename.lower().endswith(ImageExts)
def is_valid_url ( url ) : pieces = urlparse ( url ) return all ( [ pieces . scheme , pieces . netloc ] )
0
check if string is a valid url python
Checks if a given string is an url
cosqa-train-15047
def is_valid_url(url): """Checks if a given string is an url""" pieces = urlparse(url) return all([pieces.scheme, pieces.netloc])
def empty_tree ( input_list ) : for item in input_list : if not isinstance ( item , list ) or not empty_tree ( item ) : return False return True
0
python determine if list is nested
Recursively iterate through values in nested lists .
cosqa-train-15048
def empty_tree(input_list): """Recursively iterate through values in nested lists.""" for item in input_list: if not isinstance(item, list) or not empty_tree(item): return False return True
def _valid_table_name ( name ) : if name [ 0 ] not in "_" + string . ascii_letters or not set ( name ) . issubset ( "_" + string . ascii_letters + string . digits ) : return False else : return True
0
check if the row name has some kind of string in python
Verify if a given table name is valid for rows
cosqa-train-15049
def _valid_table_name(name): """Verify if a given table name is valid for `rows` Rules: - Should start with a letter or '_' - Letters can be capitalized or not - Accepts letters, numbers and _ """ if name[0] not in "_" + string.ascii_letters or not set(name).issubset( "_" + string.ascii_letters + string.digits ): return False else: return True
def _is_proper_sequence ( seq ) : return ( isinstance ( seq , collections . abc . Sequence ) and not isinstance ( seq , str ) )
1
python determine if list numbers are sequence
Returns is seq is sequence and not string .
cosqa-train-15050
def _is_proper_sequence(seq): """Returns is seq is sequence and not string.""" return (isinstance(seq, collections.abc.Sequence) and not isinstance(seq, str))
def numpy_aware_eq ( a , b ) : if isinstance ( a , np . ndarray ) or isinstance ( b , np . ndarray ) : return np . array_equal ( a , b ) if ( ( isinstance ( a , Iterable ) and isinstance ( b , Iterable ) ) and not isinstance ( a , str ) and not isinstance ( b , str ) ) : if len ( a ) != len ( b ) : return False return all ( numpy_aware_eq ( x , y ) for x , y in zip ( a , b ) ) return a == b
1
check if two arrays are equal python
Return whether two objects are equal via recursion using : func : numpy . array_equal for comparing numpy arays .
cosqa-train-15051
def numpy_aware_eq(a, b): """Return whether two objects are equal via recursion, using :func:`numpy.array_equal` for comparing numpy arays. """ if isinstance(a, np.ndarray) or isinstance(b, np.ndarray): return np.array_equal(a, b) if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and not isinstance(a, str) and not isinstance(b, str)): if len(a) != len(b): return False return all(numpy_aware_eq(x, y) for x, y in zip(a, b)) return a == b
def fft_bandpassfilter ( data , fs , lowcut , highcut ) : fft = np . fft . fft ( data ) # n = len(data) # timestep = 1.0 / fs # freq = np.fft.fftfreq(n, d=timestep) bp = fft . copy ( ) # Zero out fft coefficients # bp[10:-10] = 0 # Normalise # bp *= real(fft.dot(fft))/real(bp.dot(bp)) bp *= fft . dot ( fft ) / bp . dot ( bp ) # must multipy by 2 to get the correct amplitude ibp = 12 * np . fft . ifft ( bp ) return ibp
0
python determining lowpass filter cutoff
http : // www . swharden . com / blog / 2009 - 01 - 21 - signal - filtering - with - python / #comment - 16801
cosqa-train-15052
def fft_bandpassfilter(data, fs, lowcut, highcut): """ http://www.swharden.com/blog/2009-01-21-signal-filtering-with-python/#comment-16801 """ fft = np.fft.fft(data) # n = len(data) # timestep = 1.0 / fs # freq = np.fft.fftfreq(n, d=timestep) bp = fft.copy() # Zero out fft coefficients # bp[10:-10] = 0 # Normalise # bp *= real(fft.dot(fft))/real(bp.dot(bp)) bp *= fft.dot(fft) / bp.dot(bp) # must multipy by 2 to get the correct amplitude ibp = 12 * np.fft.ifft(bp) return ibp
def has_common ( self , other ) : if not isinstance ( other , WordSet ) : raise ValueError ( 'Can compare only WordSets' ) return self . term_set & other . term_set
0
check if two strings have any words in common python
Return set of common words between two word sets .
cosqa-train-15053
def has_common(self, other): """Return set of common words between two word sets.""" if not isinstance(other, WordSet): raise ValueError('Can compare only WordSets') return self.term_set & other.term_set
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 df change type
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-15054
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 test_value ( self , value ) : if not isinstance ( value , float ) : raise ValueError ( 'expected float value: ' + str ( type ( value ) ) )
1
check if value is an instance of float python
Test if value is an instance of float .
cosqa-train-15055
def test_value(self, value): """Test if value is an instance of float.""" if not isinstance(value, float): raise ValueError('expected float value: ' + str(type(value)))
def dictapply ( d , fn ) : for k , v in d . items ( ) : if isinstance ( v , dict ) : v = dictapply ( v , fn ) else : d [ k ] = fn ( v ) return d
1
python dict change values with dict comprehension
apply a function to all non - dict values in a dictionary
cosqa-train-15056
def dictapply(d, fn): """ apply a function to all non-dict values in a dictionary """ for k, v in d.items(): if isinstance(v, dict): v = dictapply(v, fn) else: d[k] = fn(v) return d
def count_ ( self ) : try : num = len ( self . df . index ) except Exception as e : self . err ( e , "Can not count data" ) return return num
1
check number of rows in data frame python
Returns the number of rows of the main dataframe
cosqa-train-15057
def count_(self): """ Returns the number of rows of the main dataframe """ try: num = len(self.df.index) except Exception as e: self.err(e, "Can not count data") return return num
def _remove_dict_keys_with_value ( dict_ , val ) : return { k : v for k , v in dict_ . items ( ) if v is not val }
0
python dict exclude values
Removes dict keys which have have self as value .
cosqa-train-15058
def _remove_dict_keys_with_value(dict_, val): """Removes `dict` keys which have have `self` as value.""" return {k: v for k, v in dict_.items() if v is not val}
def is_client ( self ) : return ( self . args . client or self . args . browser ) and not self . args . server
1
check python server is working or not
Return True if Glances is running in client mode .
cosqa-train-15059
def is_client(self): """Return True if Glances is running in client mode.""" return (self.args.client or self.args.browser) and not self.args.server
def pretty_dict_str ( d , indent = 2 ) : b = StringIO ( ) write_pretty_dict_str ( b , d , indent = indent ) return b . getvalue ( )
0
python dict output pretty without quote
shows JSON indented representation of d
cosqa-train-15060
def pretty_dict_str(d, indent=2): """shows JSON indented representation of d""" b = StringIO() write_pretty_dict_str(b, d, indent=indent) return b.getvalue()
def get_file_size ( filename ) : if os . path . isfile ( filename ) : return convert_size ( os . path . getsize ( filename ) ) return None
0
check size of a file python
Get the file size of a given file
cosqa-train-15061
def get_file_size(filename): """ Get the file size of a given file :param filename: string: pathname of a file :return: human readable filesize """ if os.path.isfile(filename): return convert_size(os.path.getsize(filename)) return None
def multi_pop ( d , * args ) : retval = { } for key in args : if key in d : retval [ key ] = d . pop ( key ) return retval
0
python dict pop key item
pops multiple keys off a dict like object
cosqa-train-15062
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 safe_delete ( filename ) : try : os . unlink ( filename ) except OSError as e : if e . errno != errno . ENOENT : raise
1
check the file existing and delete in python
Delete a file safely . If it s not present no - op .
cosqa-train-15063
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 purge_dict ( idict ) : odict = { } for key , val in idict . items ( ) : if is_null ( val ) : continue odict [ key ] = val return odict
0
python dict remove null
Remove null items from a dictionary
cosqa-train-15064
def purge_dict(idict): """Remove null items from a dictionary """ odict = {} for key, val in idict.items(): if is_null(val): continue odict[key] = val return odict
def timeit ( self , metric , func , * args , * * kwargs ) : return metrics . timeit ( metric , func , * args , * * kwargs )
0
check time elapsed in function python
Time execution of callable and emit metric then return result .
cosqa-train-15065
def timeit(self, metric, func, *args, **kwargs): """Time execution of callable and emit metric then return result.""" return metrics.timeit(metric, func, *args, **kwargs)
def purge_dict ( idict ) : odict = { } for key , val in idict . items ( ) : if is_null ( val ) : continue odict [ key ] = val return odict
1
python dict remove null values
Remove null items from a dictionary
cosqa-train-15066
def purge_dict(idict): """Remove null items from a dictionary """ odict = {} for key, val in idict.items(): if is_null(val): continue odict[key] = val return odict
def _call_retry ( self , force_retry ) : last_exception = None for i in range ( self . max_attempts ) : try : log . info ( "Calling %s %s" % ( self . method , self . url ) ) response = self . requests_method ( self . url , data = self . data , params = self . params , headers = self . headers , timeout = ( self . connect_timeout , self . read_timeout ) , verify = self . verify_ssl , ) if response is None : log . warn ( "Got response None" ) if self . _method_is_safe_to_retry ( ) : delay = 0.5 + i * 0.5 log . info ( "Waiting %s sec and Retrying since call is a %s" % ( delay , self . method ) ) time . sleep ( delay ) continue else : raise PyMacaronCoreException ( "Call %s %s returned empty response" % ( self . method , self . url ) ) return response except Exception as e : last_exception = e retry = force_retry if isinstance ( e , ReadTimeout ) : # Log enough to help debugging... log . warn ( "Got a ReadTimeout calling %s %s" % ( self . method , self . url ) ) log . warn ( "Exception was: %s" % str ( e ) ) resp = e . response if not resp : log . info ( "Requests error has no response." ) # TODO: retry=True? Is it really safe? else : b = resp . content log . info ( "Requests has a response with content: " + pprint . pformat ( b ) ) if self . _method_is_safe_to_retry ( ) : # It is safe to retry log . info ( "Retrying since call is a %s" % self . method ) retry = True elif isinstance ( e , ConnectTimeout ) : log . warn ( "Got a ConnectTimeout calling %s %s" % ( self . method , self . url ) ) log . warn ( "Exception was: %s" % str ( e ) ) # ConnectTimeouts are safe to retry whatever the call... retry = True if retry : continue else : raise e # max_attempts has been reached: propagate the last received Exception if not last_exception : last_exception = Exception ( "Reached max-attempts (%s). Giving up calling %s %s" % ( self . max_attempts , self . method , self . url ) ) raise last_exception
0
check time gap between retries python
Call request and retry up to max_attempts times ( or none if self . max_attempts = 1 )
cosqa-train-15067
def _call_retry(self, force_retry): """Call request and retry up to max_attempts times (or none if self.max_attempts=1)""" last_exception = None for i in range(self.max_attempts): try: log.info("Calling %s %s" % (self.method, self.url)) response = self.requests_method( self.url, data=self.data, params=self.params, headers=self.headers, timeout=(self.connect_timeout, self.read_timeout), verify=self.verify_ssl, ) if response is None: log.warn("Got response None") if self._method_is_safe_to_retry(): delay = 0.5 + i * 0.5 log.info("Waiting %s sec and Retrying since call is a %s" % (delay, self.method)) time.sleep(delay) continue else: raise PyMacaronCoreException("Call %s %s returned empty response" % (self.method, self.url)) return response except Exception as e: last_exception = e retry = force_retry if isinstance(e, ReadTimeout): # Log enough to help debugging... log.warn("Got a ReadTimeout calling %s %s" % (self.method, self.url)) log.warn("Exception was: %s" % str(e)) resp = e.response if not resp: log.info("Requests error has no response.") # TODO: retry=True? Is it really safe? else: b = resp.content log.info("Requests has a response with content: " + pprint.pformat(b)) if self._method_is_safe_to_retry(): # It is safe to retry log.info("Retrying since call is a %s" % self.method) retry = True elif isinstance(e, ConnectTimeout): log.warn("Got a ConnectTimeout calling %s %s" % (self.method, self.url)) log.warn("Exception was: %s" % str(e)) # ConnectTimeouts are safe to retry whatever the call... retry = True if retry: continue else: raise e # max_attempts has been reached: propagate the last received Exception if not last_exception: last_exception = Exception("Reached max-attempts (%s). Giving up calling %s %s" % (self.max_attempts, self.method, self.url)) raise last_exception
def nonull_dict ( self ) : return { k : v for k , v in six . iteritems ( self . dict ) if v and k != '_codes' }
1
python dict with keys no value
Like dict but does not hold any null values .
cosqa-train-15068
def nonull_dict(self): """Like dict, but does not hold any null values. :return: """ return {k: v for k, v in six.iteritems(self.dict) if v and k != '_codes'}
def _file_exists ( path , filename ) : return os . path . isfile ( os . path . join ( path , filename ) )
1
check to see if a file exists in python
Checks if the filename exists under the path .
cosqa-train-15069
def _file_exists(path, filename): """Checks if the filename exists under the path.""" return os.path.isfile(os.path.join(path, filename))
def multidict_to_dict ( d ) : return dict ( ( k , v [ 0 ] if len ( v ) == 1 else v ) for k , v in iterlists ( d ) )
1
python dictionary example with multiple objects
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-15070
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 _check_valid_key ( self , key ) : if not isinstance ( key , key_type ) : raise ValueError ( '%r is not a valid key type' % key ) if not VALID_KEY_RE . match ( key ) : raise ValueError ( '%r contains illegal characters' % key )
1
check valid dictionary key python
Checks if a key is valid and raises a ValueError if its not .
cosqa-train-15071
def _check_valid_key(self, key): """Checks if a key is valid and raises a ValueError if its not. When in need of checking a key for validity, always use this method if possible. :param key: The key to be checked """ if not isinstance(key, key_type): raise ValueError('%r is not a valid key type' % key) if not VALID_KEY_RE.match(key): raise ValueError('%r contains illegal characters' % key)
def nonull_dict ( self ) : return { k : v for k , v in six . iteritems ( self . dict ) if v and k != '_codes' }
1
python dictionary key with no value
Like dict but does not hold any null values .
cosqa-train-15072
def nonull_dict(self): """Like dict, but does not hold any null values. :return: """ return {k: v for k, v in six.iteritems(self.dict) if v and k != '_codes'}
def _ws_on_close ( self , ws : websocket . WebSocketApp ) : self . connected = False self . logger . error ( 'Websocket closed' ) self . _reconnect_websocket ( )
0
check websocket is closed python
Callback for closing the websocket connection
cosqa-train-15073
def _ws_on_close(self, ws: websocket.WebSocketApp): """Callback for closing the websocket connection Args: ws: websocket connection (now closed) """ self.connected = False self.logger.error('Websocket closed') self._reconnect_websocket()
def to_bipartite_matrix ( A ) : m , n = A . shape return four_blocks ( zeros ( m , m ) , A , A . T , zeros ( n , n ) )
0
python dijkstra using adjacency matrix
Returns the adjacency matrix of a bipartite graph whose biadjacency matrix is A .
cosqa-train-15074
def to_bipartite_matrix(A): """Returns the adjacency matrix of a bipartite graph whose biadjacency matrix is `A`. `A` must be a NumPy array. If `A` has **m** rows and **n** columns, then the returned matrix has **m + n** rows and columns. """ m, n = A.shape return four_blocks(zeros(m, m), A, A.T, zeros(n, n))
def is_identifier ( string ) : matched = PYTHON_IDENTIFIER_RE . match ( string ) return bool ( matched ) and not keyword . iskeyword ( string )
0
check whether a string contains something python
Check if string could be a valid python identifier
cosqa-train-15075
def is_identifier(string): """Check if string could be a valid python identifier :param string: string to be tested :returns: True if string can be a python identifier, False otherwise :rtype: bool """ matched = PYTHON_IDENTIFIER_RE.match(string) return bool(matched) and not keyword.iskeyword(string)
def convert_string ( string ) : if is_int ( string ) : return int ( string ) elif is_float ( string ) : return float ( string ) elif convert_bool ( string ) [ 0 ] : return convert_bool ( string ) [ 1 ] elif string == 'None' : return None else : return string
0
python distinguish string float and string string
Convert string to int float or bool .
cosqa-train-15076
def convert_string(string): """Convert string to int, float or bool. """ if is_int(string): return int(string) elif is_float(string): return float(string) elif convert_bool(string)[0]: return convert_bool(string)[1] elif string == 'None': return None else: return string
def is_non_empty_string ( input_string ) : try : if not input_string . strip ( ) : raise ValueError ( ) except AttributeError as error : raise TypeError ( error ) return True
1
check whether the string is empty in python
Validate if non empty string
cosqa-train-15077
def is_non_empty_string(input_string): """ Validate if non empty string :param input_string: Input is a *str*. :return: True if input is string and non empty. Raise :exc:`Exception` otherwise. """ try: if not input_string.strip(): raise ValueError() except AttributeError as error: raise TypeError(error) return True
def get_serialize_format ( self , mimetype ) : format = self . formats . get ( mimetype , None ) if format is None : format = formats . get ( mimetype , None ) return format
0
python django contenttype serializer
Get the serialization format for the given mimetype
cosqa-train-15078
def get_serialize_format(self, mimetype): """ Get the serialization format for the given mimetype """ format = self.formats.get(mimetype, None) if format is None: format = formats.get(mimetype, None) return format
def equal ( obj1 , obj2 ) : Comparable . log ( obj1 , obj2 , '==' ) equality = obj1 . equality ( obj2 ) Comparable . log ( obj1 , obj2 , '==' , result = equality ) return equality
0
checking for equality python
Calculate equality between two ( Comparable ) objects .
cosqa-train-15079
def equal(obj1, obj2): """Calculate equality between two (Comparable) objects.""" Comparable.log(obj1, obj2, '==') equality = obj1.equality(obj2) Comparable.log(obj1, obj2, '==', result=equality) return equality
def fast_distinct ( self ) : return self . model . objects . filter ( pk__in = self . values_list ( 'pk' , flat = True ) )
0
python django get unique values
Because standard distinct used on the all fields are very slow and works only with PostgreSQL database this method provides alternative to the standard distinct method . : return : qs with unique objects
cosqa-train-15080
def fast_distinct(self): """ Because standard distinct used on the all fields are very slow and works only with PostgreSQL database this method provides alternative to the standard distinct method. :return: qs with unique objects """ return self.model.objects.filter(pk__in=self.values_list('pk', flat=True))
def contained_in ( filename , directory ) : filename = os . path . normcase ( os . path . abspath ( filename ) ) directory = os . path . normcase ( os . path . abspath ( directory ) ) return os . path . commonprefix ( [ filename , directory ] ) == directory
0
checking if a file is in a folder python
Test if a file is located within the given directory .
cosqa-train-15081
def contained_in(filename, directory): """Test if a file is located within the given directory.""" filename = os.path.normcase(os.path.abspath(filename)) directory = os.path.normcase(os.path.abspath(directory)) return os.path.commonprefix([filename, directory]) == directory
def run ( self , value ) : if self . pass_ and not value . strip ( ) : return True if not value : return False return True
1
checking if field is empty python
Determines if value value is empty . Keyword arguments : value str -- the value of the associated field to compare
cosqa-train-15082
def run(self, value): """ Determines if value value is empty. Keyword arguments: value str -- the value of the associated field to compare """ if self.pass_ and not value.strip(): return True if not value: return False return True
def tree_render ( request , upy_context , vars_dictionary ) : page = upy_context [ 'PAGE' ] return render_to_response ( page . template . file_name , vars_dictionary , context_instance = RequestContext ( request ) )
0
python django render page with param
It renders template defined in upy_context s page passed in arguments
cosqa-train-15083
def tree_render(request, upy_context, vars_dictionary): """ It renders template defined in upy_context's page passed in arguments """ page = upy_context['PAGE'] return render_to_response(page.template.file_name, vars_dictionary, context_instance=RequestContext(request))
def is_punctuation ( text ) : return not ( text . lower ( ) in config . AVRO_VOWELS or text . lower ( ) in config . AVRO_CONSONANTS )
1
checking if punctuation is in python string
Check if given string is a punctuation
cosqa-train-15084
def is_punctuation(text): """Check if given string is a punctuation""" return not (text.lower() in config.AVRO_VOWELS or text.lower() in config.AVRO_CONSONANTS)
def static_urls_js ( ) : if apps . is_installed ( 'django.contrib.staticfiles' ) : from django . contrib . staticfiles . storage import staticfiles_storage static_base_url = staticfiles_storage . base_url else : static_base_url = PrefixNode . handle_simple ( "STATIC_URL" ) transpile_base_url = urljoin ( static_base_url , 'js/transpile/' ) return { 'static_base_url' : static_base_url , 'transpile_base_url' : transpile_base_url , 'version' : LAST_RUN [ 'version' ] }
1
python django {% load static%}
Add global variables to JavaScript about the location and latest version of transpiled files . Usage :: { % static_urls_js % }
cosqa-train-15085
def static_urls_js(): """ Add global variables to JavaScript about the location and latest version of transpiled files. Usage:: {% static_urls_js %} """ if apps.is_installed('django.contrib.staticfiles'): from django.contrib.staticfiles.storage import staticfiles_storage static_base_url = staticfiles_storage.base_url else: static_base_url = PrefixNode.handle_simple("STATIC_URL") transpile_base_url = urljoin(static_base_url, 'js/transpile/') return { 'static_base_url': static_base_url, 'transpile_base_url': transpile_base_url, 'version': LAST_RUN['version'] }
def set_executable ( filename ) : st = os . stat ( filename ) os . chmod ( filename , st . st_mode | stat . S_IEXEC )
0
chmod for windows pythong
Set the exectuable bit on the given filename
cosqa-train-15086
def set_executable(filename): """Set the exectuable bit on the given filename""" st = os.stat(filename) os.chmod(filename, st.st_mode | stat.S_IEXEC)
def see_doc ( obj_with_doc ) : def decorator ( fn ) : fn . __doc__ = obj_with_doc . __doc__ return fn return decorator
0
python docs tag for methods
Copy docstring from existing object to the decorated callable .
cosqa-train-15087
def see_doc(obj_with_doc): """Copy docstring from existing object to the decorated callable.""" def decorator(fn): fn.__doc__ = obj_with_doc.__doc__ return fn return decorator
def check_clang_apply_replacements_binary ( args ) : try : subprocess . check_call ( [ args . clang_apply_replacements_binary , '--version' ] ) except : print ( 'Unable to run clang-apply-replacements. Is clang-apply-replacements ' 'binary correctly specified?' , file = sys . stderr ) traceback . print_exc ( ) sys . exit ( 1 )
1
clang python function boundary
Checks if invoking supplied clang - apply - replacements binary works .
cosqa-train-15088
def check_clang_apply_replacements_binary(args): """Checks if invoking supplied clang-apply-replacements binary works.""" try: subprocess.check_call([args.clang_apply_replacements_binary, '--version']) except: print('Unable to run clang-apply-replacements. Is clang-apply-replacements ' 'binary correctly specified?', file=sys.stderr) traceback.print_exc() sys.exit(1)
def fill_document ( doc ) : with doc . create ( Section ( 'A section' ) ) : doc . append ( 'Some regular text and some ' ) doc . append ( italic ( 'italic text. ' ) ) with doc . create ( Subsection ( 'A subsection' ) ) : doc . append ( 'Also some crazy characters: $&#{}' )
1
python docx document section different page
Add a section a subsection and some text to the document .
cosqa-train-15089
def fill_document(doc): """Add a section, a subsection and some text to the document. :param doc: the document :type doc: :class:`pylatex.document.Document` instance """ with doc.create(Section('A section')): doc.append('Some regular text and some ') doc.append(italic('italic text. ')) with doc.create(Subsection('A subsection')): doc.append('Also some crazy characters: $&#{}')
def close_all_but_this ( self ) : self . close_all_right ( ) for i in range ( 0 , self . get_stack_count ( ) - 1 ) : self . close_file ( 0 )
0
close all figures in python matplotlib
Close all files but the current one
cosqa-train-15090
def close_all_but_this(self): """Close all files but the current one""" self.close_all_right() for i in range(0, self.get_stack_count()-1 ): self.close_file(0)
def smartSum ( x , key , value ) : if key not in list ( x . keys ( ) ) : x [ key ] = value else : x [ key ] += value
1
python does add and remove element to dictionary increase the cost
create a new page in x if key is not a page of x otherwise add value to x [ key ]
cosqa-train-15091
def smartSum(x,key,value): """ create a new page in x if key is not a page of x otherwise add value to x[key] """ if key not in list(x.keys()): x[key] = value else: x[key]+=value
def close ( self ) : if self . db is not None : self . db . commit ( ) self . db . close ( ) self . db = None return
1
close database connecting python
Close the db and release memory
cosqa-train-15092
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 next ( self ) : # File-like object. result = self . readline ( ) if result == self . _empty_buffer : raise StopIteration return result
0
python does readline flush the buffer
This is to support iterators over a file - like object .
cosqa-train-15093
def next (self): # File-like object. """This is to support iterators over a file-like object. """ result = self.readline() if result == self._empty_buffer: raise StopIteration return result
def close ( self ) : if self . pyb and self . pyb . serial : self . pyb . serial . close ( ) self . pyb = None
1
close serial port python after time
Closes the serial port .
cosqa-train-15094
def close(self): """Closes the serial port.""" if self.pyb and self.pyb.serial: self.pyb.serial.close() self.pyb = None
def _dotify ( cls , data ) : return '' . join ( char if char in cls . PRINTABLE_DATA else '.' for char in data )
1
python dot derivative string
Add dots .
cosqa-train-15095
def _dotify(cls, data): """Add dots.""" return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data)
def get_closest_index ( myList , myNumber ) : closest_values_index = _np . where ( self . time == take_closest ( myList , myNumber ) ) [ 0 ] [ 0 ] return closest_values_index
1
closest time value before an index python
Assumes myList is sorted . Returns closest value to myNumber . If two numbers are equally close return the smallest number .
cosqa-train-15096
def get_closest_index(myList, myNumber): """ Assumes myList is sorted. Returns closest value to myNumber. If two numbers are equally close, return the smallest number. Parameters ---------- myList : array The list in which to find the closest value to myNumber myNumber : float The number to find the closest to in MyList Returns ------- closest_values_index : int The index in the array of the number closest to myNumber in myList """ closest_values_index = _np.where(self.time == take_closest(myList, myNumber))[0][0] return closest_values_index
def dot_v2 ( vec1 , vec2 ) : return vec1 . x * vec2 . x + vec1 . y * vec2 . y
1
python dot on two array of vectors
Return the dot product of two vectors
cosqa-train-15097
def dot_v2(vec1, vec2): """Return the dot product of two vectors""" return vec1.x * vec2.x + vec1.y * vec2.y
def clear ( ) : if sys . platform . startswith ( "win" ) : call ( "cls" , shell = True ) else : call ( "clear" , shell = True )
1
cls clear screen python windows
Clears the console .
cosqa-train-15098
def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True)
def downsample_with_striding ( array , factor ) : return array [ tuple ( np . s_ [ : : f ] for f in factor ) ]
0
python downsample based on each group
Downsample x by factor using striding .
cosqa-train-15099
def downsample_with_striding(array, factor): """Downsample x by factor using striding. @return: The downsampled array, of the same type as x. """ return array[tuple(np.s_[::f] for f in factor)]