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 get_bin_indices ( self , values ) : return tuple ( [ self . get_axis_bin_index ( values [ ax_i ] , ax_i ) for ax_i in range ( self . dimensions ) ] )
1
python histogram get data with in bin
Returns index tuple in histogram of bin which contains value
cosqa-train-13200
def get_bin_indices(self, values): """Returns index tuple in histogram of bin which contains value""" return tuple([self.get_axis_bin_index(values[ax_i], ax_i) for ax_i in range(self.dimensions)])
def normalize_path ( path ) : return os . path . normcase ( os . path . realpath ( os . path . expanduser ( path ) ) )
1
file path username case sensitivity python
Convert a path to its canonical case - normalized absolute version .
cosqa-train-13201
def normalize_path(path): """ Convert a path to its canonical, case-normalized, absolute version. """ return os.path.normcase(os.path.realpath(os.path.expanduser(path)))
def getSize ( self ) : return self . widget . size [ 0 ] - self . border [ 0 ] * 2 , self . widget . size [ 1 ] - self . border [ 1 ] * 2
1
python how do i get a stacked widget height
Returns the size of the layer with the border size already subtracted .
cosqa-train-13202
def getSize(self): """ Returns the size of the layer, with the border size already subtracted. """ return self.widget.size[0]-self.border[0]*2,self.widget.size[1]-self.border[1]*2
def make_writeable ( filename ) : if not os . access ( filename , os . W_OK ) : st = os . stat ( filename ) new_permissions = stat . S_IMODE ( st . st_mode ) | stat . S_IWUSR os . chmod ( filename , new_permissions )
1
file permissions python write
Make sure that the file is writeable . Useful if our source is read - only .
cosqa-train-13203
def make_writeable(filename): """ Make sure that the file is writeable. Useful if our source is read-only. """ if not os.access(filename, os.W_OK): st = os.stat(filename) new_permissions = stat.S_IMODE(st.st_mode) | stat.S_IWUSR os.chmod(filename, new_permissions)
def get_image_dimension ( self , url ) : w_h = ( None , None ) try : if url . startswith ( '//' ) : url = 'http:' + url data = requests . get ( url ) . content im = Image . open ( BytesIO ( data ) ) w_h = im . size except Exception : logger . warning ( "Error getting image size {}" . format ( url ) , exc_info = True ) return w_h
1
python how do i get the image size
Return a tuple that contains ( width height ) Pass in a url to an image and find out its size without loading the whole file If the image wxh could not be found the tuple will contain None values
cosqa-train-13204
def get_image_dimension(self, url): """ Return a tuple that contains (width, height) Pass in a url to an image and find out its size without loading the whole file If the image wxh could not be found, the tuple will contain `None` values """ w_h = (None, None) try: if url.startswith('//'): url = 'http:' + url data = requests.get(url).content im = Image.open(BytesIO(data)) w_h = im.size except Exception: logger.warning("Error getting image size {}".format(url), exc_info=True) return w_h
def filter_bolts ( table , header ) : bolts_info = [ ] for row in table : if row [ 0 ] == 'bolt' : bolts_info . append ( row ) return bolts_info , header
1
filer the values of a table in python based upon variable
filter to keep bolts
cosqa-train-13205
def filter_bolts(table, header): """ filter to keep bolts """ bolts_info = [] for row in table: if row[0] == 'bolt': bolts_info.append(row) return bolts_info, header
def is_array ( self , key ) : data = self . model . get_data ( ) return isinstance ( data [ key ] , ( ndarray , MaskedArray ) )
1
python how do you check the array attribute
Return True if variable is a numpy array
cosqa-train-13206
def is_array(self, key): """Return True if variable is a numpy array""" data = self.model.get_data() return isinstance(data[key], (ndarray, MaskedArray))
def clean_dataframe ( df ) : df = df . fillna ( method = 'ffill' ) df = df . fillna ( 0.0 ) return df
1
fill is null with other columns python
Fill NaNs with the previous value the next value or if all are NaN then 1 . 0
cosqa-train-13207
def clean_dataframe(df): """Fill NaNs with the previous value, the next value or if all are NaN then 1.0""" df = df.fillna(method='ffill') df = df.fillna(0.0) return df
def chunks ( dictionary , chunk_size ) : iterable = iter ( dictionary ) for __ in range ( 0 , len ( dictionary ) , chunk_size ) : yield { key : dictionary [ key ] for key in islice ( iterable , chunk_size ) }
1
python how do you split a dictionary into evenly sized chunks
Yield successive n - sized chunks from dictionary .
cosqa-train-13208
def chunks(dictionary, chunk_size): """ Yield successive n-sized chunks from dictionary. """ iterable = iter(dictionary) for __ in range(0, len(dictionary), chunk_size): yield {key: dictionary[key] for key in islice(iterable, chunk_size)}
def inpaint ( self ) : import inpaint filled = inpaint . replace_nans ( np . ma . filled ( self . raster_data , np . NAN ) . astype ( np . float32 ) , 3 , 0.01 , 2 ) self . raster_data = np . ma . masked_invalid ( filled )
1
filling around an image with white python
Replace masked - out elements in an array using an iterative image inpainting algorithm .
cosqa-train-13209
def inpaint(self): """ Replace masked-out elements in an array using an iterative image inpainting algorithm. """ import inpaint filled = inpaint.replace_nans(np.ma.filled(self.raster_data, np.NAN).astype(np.float32), 3, 0.01, 2) self.raster_data = np.ma.masked_invalid(filled)
def quit ( self ) : logger . debug ( "ArgosApplication.quit called" ) assert len ( self . mainWindows ) == 0 , "Bug: still {} windows present at application quit!" . format ( len ( self . mainWindows ) ) self . qApplication . quit ( )
1
python how not to close the window after running
Quits the application ( called when the last window is closed )
cosqa-train-13210
def quit(self): """ Quits the application (called when the last window is closed) """ logger.debug("ArgosApplication.quit called") assert len(self.mainWindows) == 0, \ "Bug: still {} windows present at application quit!".format(len(self.mainWindows)) self.qApplication.quit()
def stringify_col ( df , col_name ) : df = df . copy ( ) df [ col_name ] = df [ col_name ] . fillna ( "" ) df [ col_name ] = df [ col_name ] . astype ( str ) return df
1
fillna with string for specific columnin python
Take a dataframe and string - i - fy a column of values . Turn nan / None into and all other values into strings .
cosqa-train-13211
def stringify_col(df, col_name): """ Take a dataframe and string-i-fy a column of values. Turn nan/None into "" and all other values into strings. Parameters ---------- df : dataframe col_name : string """ df = df.copy() df[col_name] = df[col_name].fillna("") df[col_name] = df[col_name].astype(str) return df
def extend_with ( func ) : if not func . __name__ in ArgParseInator . _plugins : ArgParseInator . _plugins [ func . __name__ ] = func
0
python how to add builtin
Extends with class or function
cosqa-train-13212
def extend_with(func): """Extends with class or function""" if not func.__name__ in ArgParseInator._plugins: ArgParseInator._plugins[func.__name__] = func
def filter_dict ( d , keys ) : return { k : v for k , v in d . items ( ) if k in keys }
1
filter dictionary python with certain keys
Creates a new dict from an existing dict that only has the given keys
cosqa-train-13213
def filter_dict(d, keys): """ Creates a new dict from an existing dict that only has the given keys """ return {k: v for k, v in d.items() if k in keys}
def _transform_col ( self , x , i ) : return x . fillna ( NAN_INT ) . map ( self . label_encoders [ i ] ) . fillna ( 0 )
1
python how to apply label encoder all all columns
Encode one categorical column into labels .
cosqa-train-13214
def _transform_col(self, x, i): """Encode one categorical column into labels. Args: x (pandas.Series): a categorical column to encode i (int): column index Returns: x (pandas.Series): a column with labels. """ return x.fillna(NAN_INT).map(self.label_encoders[i]).fillna(0)
def twitter_timeline ( screen_name , since_id = None ) : consumer_key = twitter_credential ( 'consumer_key' ) consumer_secret = twitter_credential ( 'consumer_secret' ) access_token = twitter_credential ( 'access_token' ) access_token_secret = twitter_credential ( 'access_secret' ) auth = tweepy . OAuthHandler ( consumer_key , consumer_secret ) auth . set_access_token ( access_token , access_token_secret ) api = tweepy . API ( auth ) return get_all_tweets ( screen_name , api , since_id )
1
filter twitter user tweepy python
Return relevant twitter timeline
cosqa-train-13215
def twitter_timeline(screen_name, since_id=None): """ Return relevant twitter timeline """ consumer_key = twitter_credential('consumer_key') consumer_secret = twitter_credential('consumer_secret') access_token = twitter_credential('access_token') access_token_secret = twitter_credential('access_secret') auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) return get_all_tweets(screen_name, api, since_id)
def round_data ( filter_data ) : for index , _ in enumerate ( filter_data ) : filter_data [ index ] [ 0 ] = round ( filter_data [ index ] [ 0 ] / 100.0 ) * 100.0 return filter_data
0
python how to apply round in list value
round the data
cosqa-train-13216
def round_data(filter_data): """ round the data""" for index, _ in enumerate(filter_data): filter_data[index][0] = round(filter_data[index][0] / 100.0) * 100.0 return filter_data
def binSearch ( arr , val ) : i = bisect_left ( arr , val ) if i != len ( arr ) and arr [ i ] == val : return i return - 1
1
finding index of a specific element in a list python
Function for running binary search on a sorted list .
cosqa-train-13217
def binSearch(arr, val): """ Function for running binary search on a sorted list. :param arr: (list) a sorted list of integers to search :param val: (int) a integer to search for in the sorted array :returns: (int) the index of the element if it is found and -1 otherwise. """ i = bisect_left(arr, val) if i != len(arr) and arr[i] == val: return i return -1
def _bind_parameter ( self , parameter , value ) : for ( instr , param_index ) in self . _parameter_table [ parameter ] : instr . params [ param_index ] = value
1
python how to bind paramters to function
Assigns a parameter value to matching instructions in - place .
cosqa-train-13218
def _bind_parameter(self, parameter, value): """Assigns a parameter value to matching instructions in-place.""" for (instr, param_index) in self._parameter_table[parameter]: instr.params[param_index] = value
def index_nearest ( value , array ) : a = ( array - value ) ** 2 return index ( a . min ( ) , a )
1
finding nearest numbers in python
expects a _n . array returns the global minimum of ( value - array ) ^2
cosqa-train-13219
def index_nearest(value, array): """ expects a _n.array returns the global minimum of (value-array)^2 """ a = (array-value)**2 return index(a.min(), a)
def lower_ext ( abspath ) : fname , ext = os . path . splitext ( abspath ) return fname + ext . lower ( )
1
python how to change file extension
Convert file extension to lowercase .
cosqa-train-13220
def lower_ext(abspath): """Convert file extension to lowercase. """ fname, ext = os.path.splitext(abspath) return fname + ext.lower()
def iter_finds ( regex_obj , s ) : if isinstance ( regex_obj , str ) : for m in re . finditer ( regex_obj , s ) : yield m . group ( ) else : for m in regex_obj . finditer ( s ) : yield m . group ( )
1
finding patterns in python string
Generate all matches found within a string for a regex and yield each match as a string
cosqa-train-13221
def iter_finds(regex_obj, s): """Generate all matches found within a string for a regex and yield each match as a string""" if isinstance(regex_obj, str): for m in re.finditer(regex_obj, s): yield m.group() else: for m in regex_obj.finditer(s): yield m.group()
def _pip_exists ( self ) : return os . path . isfile ( os . path . join ( self . path , 'bin' , 'pip' ) )
1
python how to check if environment defined
Returns True if pip exists inside the virtual environment . Can be used as a naive way to verify that the environment is installed .
cosqa-train-13222
def _pip_exists(self): """Returns True if pip exists inside the virtual environment. Can be used as a naive way to verify that the environment is installed.""" return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))
def check_if_numbers_are_consecutive ( list_ ) : return all ( ( True if second - first == 1 else False for first , second in zip ( list_ [ : - 1 ] , list_ [ 1 : ] ) ) )
1
finding sets of consecutive numbers in a list python
Returns True if numbers in the list are consecutive
cosqa-train-13223
def check_if_numbers_are_consecutive(list_): """ Returns True if numbers in the list are consecutive :param list_: list of integers :return: Boolean """ return all((True if second - first == 1 else False for first, second in zip(list_[:-1], list_[1:])))
def class_check ( vector ) : for i in vector : if not isinstance ( i , type ( vector [ 0 ] ) ) : return False return True
1
python how to check list or array
Check different items in matrix classes .
cosqa-train-13224
def class_check(vector): """ Check different items in matrix classes. :param vector: input vector :type vector : list :return: bool """ for i in vector: if not isinstance(i, type(vector[0])): return False return True
def get_previous ( self ) : return BillingCycle . objects . filter ( date_range__lt = self . date_range ) . order_by ( 'date_range' ) . last ( )
0
finding the most recent date before a given date python
Get the billing cycle prior to this one . May return None
cosqa-train-13225
def get_previous(self): """Get the billing cycle prior to this one. May return None""" return BillingCycle.objects.filter(date_range__lt=self.date_range).order_by('date_range').last()
def pid_exists ( pid ) : try : os . kill ( pid , 0 ) except OSError as exc : return exc . errno == errno . EPERM else : return True
1
python how to check whether the process with pid exist
Determines if a system process identifer exists in process table .
cosqa-train-13226
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 closest ( xarr , val ) : idx_closest = np . argmin ( np . abs ( np . array ( xarr ) - val ) ) return idx_closest
0
finding the two closest values in an array python
Return the index of the closest in xarr to value val
cosqa-train-13227
def closest(xarr, val): """ Return the index of the closest in xarr to value val """ idx_closest = np.argmin(np.abs(np.array(xarr) - val)) return idx_closest
def Flush ( self ) : while self . _age : node = self . _age . PopLeft ( ) self . KillObject ( node . data ) self . _hash = dict ( )
1
python how to clear memory
Flush all items from cache .
cosqa-train-13228
def Flush(self): """Flush all items from cache.""" while self._age: node = self._age.PopLeft() self.KillObject(node.data) self._hash = dict()
def findMax ( arr ) : out = np . zeros ( shape = arr . shape , dtype = bool ) _calcMax ( arr , out ) return out
1
fins max in array python
in comparison to argrelmax () more simple and reliable peak finder
cosqa-train-13229
def findMax(arr): """ in comparison to argrelmax() more simple and reliable peak finder """ out = np.zeros(shape=arr.shape, dtype=bool) _calcMax(arr, out) return out
def is_equal_strings_ignore_case ( first , second ) : if first and second : return first . upper ( ) == second . upper ( ) else : return not ( first or second )
0
python how to compare strings without case
The function compares strings ignoring case
cosqa-train-13230
def is_equal_strings_ignore_case(first, second): """The function compares strings ignoring case""" if first and second: return first.upper() == second.upper() else: return not (first or second)
def fit_gaussian ( x , y , yerr , p0 ) : try : popt , pcov = curve_fit ( gaussian , x , y , sigma = yerr , p0 = p0 , absolute_sigma = True ) except RuntimeError : return [ 0 ] , [ 0 ] return popt , pcov
1
fitting a gaussian in python direct method
Fit a Gaussian to the data
cosqa-train-13231
def fit_gaussian(x, y, yerr, p0): """ Fit a Gaussian to the data """ try: popt, pcov = curve_fit(gaussian, x, y, sigma=yerr, p0=p0, absolute_sigma=True) except RuntimeError: return [0],[0] return popt, pcov
def chi_square_calc ( classes , table , TOP , P , POP ) : try : result = 0 for i in classes : for index , j in enumerate ( classes ) : expected = ( TOP [ j ] * P [ i ] ) / ( POP [ i ] ) result += ( ( table [ i ] [ j ] - expected ) ** 2 ) / expected return result except Exception : return "None"
1
python how to compute chi square
Calculate chi - squared .
cosqa-train-13232
def chi_square_calc(classes, table, TOP, P, POP): """ Calculate chi-squared. :param classes: confusion matrix classes :type classes : list :param table: confusion matrix table :type table : dict :param TOP: test outcome positive :type TOP : dict :param P: condition positive :type P : dict :param POP: population :type POP : dict :return: chi-squared as float """ try: result = 0 for i in classes: for index, j in enumerate(classes): expected = (TOP[j] * P[i]) / (POP[i]) result += ((table[i][j] - expected)**2) / expected return result except Exception: return "None"
def sbatch_template ( self ) : template = self . sbatch_template_str if template . startswith ( '#!' ) : # script is embedded in YAML return jinja_environment . from_string ( template ) return jinja_environment . get_template ( template )
1
flask jinja if get python
: return Jinja sbatch template for the current tag
cosqa-train-13233
def sbatch_template(self): """:return Jinja sbatch template for the current tag""" template = self.sbatch_template_str if template.startswith('#!'): # script is embedded in YAML return jinja_environment.from_string(template) return jinja_environment.get_template(template)
def be_array_from_bytes ( fmt , data ) : arr = array . array ( str ( fmt ) , data ) return fix_byteorder ( arr )
1
python how to covert binary to byte arry
Reads an array from bytestring with big - endian data .
cosqa-train-13234
def be_array_from_bytes(fmt, data): """ Reads an array from bytestring with big-endian data. """ arr = array.array(str(fmt), data) return fix_byteorder(arr)
def _change_height ( self , ax , new_value ) : for patch in ax . patches : current_height = patch . get_height ( ) diff = current_height - new_value # we change the bar height patch . set_height ( new_value ) # we recenter the bar patch . set_y ( patch . get_y ( ) + diff * .5 )
1
flexibility for barwidth in python matplotlib barplot
Make bars in horizontal bar chart thinner
cosqa-train-13235
def _change_height(self, ax, new_value): """Make bars in horizontal bar chart thinner""" for patch in ax.patches: current_height = patch.get_height() diff = current_height - new_value # we change the bar height patch.set_height(new_value) # we recenter the bar patch.set_y(patch.get_y() + diff * .5)
def auto_update ( cls , function ) : def wrapper ( self , * args , * * kwargs ) : f = function ( self , * args , * * kwargs ) self . update ( ) return f return wrapper
1
python how to decorate for both instance methods
This class method could be used as decorator on subclasses it ensures update method is called after function execution .
cosqa-train-13236
def auto_update(cls, function): """ This class method could be used as decorator on subclasses, it ensures update method is called after function execution. """ def wrapper(self, *args, **kwargs): f = function(self, *args, **kwargs) self.update() return f return wrapper
def hflip ( img ) : if not _is_pil_image ( img ) : raise TypeError ( 'img should be PIL Image. Got {}' . format ( type ( img ) ) ) return img . transpose ( Image . FLIP_LEFT_RIGHT )
1
flip image using python
Horizontally flip the given PIL Image .
cosqa-train-13237
def hflip(img): """Horizontally flip the given PIL Image. Args: img (PIL Image): Image to be flipped. Returns: PIL Image: Horizontall flipped image. """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) return img.transpose(Image.FLIP_LEFT_RIGHT)
def _delete_local ( self , filename ) : if os . path . exists ( filename ) : os . remove ( filename )
1
python how to delete files on local disk
Deletes the specified file from the local filesystem .
cosqa-train-13238
def _delete_local(self, filename): """Deletes the specified file from the local filesystem.""" if os.path.exists(filename): os.remove(filename)
def safe_exit ( output ) : try : sys . stdout . write ( output ) sys . stdout . flush ( ) except IOError : pass
1
flush standard output python
exit without breaking pipes .
cosqa-train-13239
def safe_exit(output): """exit without breaking pipes.""" try: sys.stdout.write(output) sys.stdout.flush() except IOError: pass
def _platform_is_windows ( platform = sys . platform ) : matched = platform in ( 'cygwin' , 'win32' , 'win64' ) if matched : error_msg = "Windows isn't supported yet" raise OSError ( error_msg ) return matched
0
python how to determine if linux or windows
Is the current OS a Windows?
cosqa-train-13240
def _platform_is_windows(platform=sys.platform): """Is the current OS a Windows?""" matched = platform in ('cygwin', 'win32', 'win64') if matched: error_msg = "Windows isn't supported yet" raise OSError(error_msg) return matched
def get_page_and_url ( session , url ) : reply = get_reply ( session , url ) return reply . text , reply . url
1
follow redirection to get actual link in python
Download an HTML page using the requests session and return the final URL after following redirects .
cosqa-train-13241
def get_page_and_url(session, url): """ Download an HTML page using the requests session and return the final URL after following redirects. """ reply = get_reply(session, url) return reply.text, reply.url
def compute_boxplot ( self , series ) : from matplotlib . cbook import boxplot_stats series = series [ series . notnull ( ) ] if len ( series . values ) == 0 : return { } elif not is_numeric_dtype ( series ) : return self . non_numeric_stats ( series ) stats = boxplot_stats ( list ( series . values ) ) [ 0 ] stats [ 'count' ] = len ( series . values ) stats [ 'fliers' ] = "|" . join ( map ( str , stats [ 'fliers' ] ) ) return stats
1
python how to do a boxplot
Compute boxplot for given pandas Series .
cosqa-train-13242
def compute_boxplot(self, series): """ Compute boxplot for given pandas Series. """ from matplotlib.cbook import boxplot_stats series = series[series.notnull()] if len(series.values) == 0: return {} elif not is_numeric_dtype(series): return self.non_numeric_stats(series) stats = boxplot_stats(list(series.values))[0] stats['count'] = len(series.values) stats['fliers'] = "|".join(map(str, stats['fliers'])) return stats
def serialize ( self , value , * * kwargs ) : return [ self . item_type . serialize ( val , * * kwargs ) for val in value ]
1
for in python unhashable type list
Serialize every item of the list .
cosqa-train-13243
def serialize(self, value, **kwargs): """Serialize every item of the list.""" return [self.item_type.serialize(val, **kwargs) for val in value]
def unit_tangent ( self , t ) : dseg = self . derivative ( t ) return dseg / abs ( dseg )
0
python how to do tangent
returns the unit tangent vector of the segment at t ( centered at the origin and expressed as a complex number ) .
cosqa-train-13244
def unit_tangent(self, t): """returns the unit tangent vector of the segment at t (centered at the origin and expressed as a complex number).""" dseg = self.derivative(t) return dseg/abs(dseg)
def find_frequencies ( data , freq = 44100 , bits = 16 ) : # Fast fourier transform n = len ( data ) p = _fft ( data ) uniquePts = numpy . ceil ( ( n + 1 ) / 2.0 ) # Scale by the length (n) and square the value to get the amplitude p = [ ( abs ( x ) / float ( n ) ) ** 2 * 2 for x in p [ 0 : uniquePts ] ] p [ 0 ] = p [ 0 ] / 2 if n % 2 == 0 : p [ - 1 ] = p [ - 1 ] / 2 # Generate the frequencies and zip with the amplitudes s = freq / float ( n ) freqArray = numpy . arange ( 0 , uniquePts * s , s ) return zip ( freqArray , p )
1
fourier transform audio file python
Convert audio data into a frequency - amplitude table using fast fourier transformation .
cosqa-train-13245
def find_frequencies(data, freq=44100, bits=16): """Convert audio data into a frequency-amplitude table using fast fourier transformation. Return a list of tuples (frequency, amplitude). Data should only contain one channel of audio. """ # Fast fourier transform n = len(data) p = _fft(data) uniquePts = numpy.ceil((n + 1) / 2.0) # Scale by the length (n) and square the value to get the amplitude p = [(abs(x) / float(n)) ** 2 * 2 for x in p[0:uniquePts]] p[0] = p[0] / 2 if n % 2 == 0: p[-1] = p[-1] / 2 # Generate the frequencies and zip with the amplitudes s = freq / float(n) freqArray = numpy.arange(0, uniquePts * s, s) return zip(freqArray, p)
def autoscan ( ) : for port in serial . tools . list_ports . comports ( ) : if is_micropython_usb_device ( port ) : connect_serial ( port [ 0 ] )
1
python how to enumerate serial ports in linux usb hub
autoscan will check all of the serial ports to see if they have a matching VID : PID for a MicroPython board .
cosqa-train-13246
def autoscan(): """autoscan will check all of the serial ports to see if they have a matching VID:PID for a MicroPython board. """ for port in serial.tools.list_ports.comports(): if is_micropython_usb_device(port): connect_serial(port[0])
def parse_float ( float_str ) : factor = __get_factor ( float_str ) if factor != 1 : float_str = float_str [ : - 1 ] try : return float ( float_str . replace ( ',' , '' ) ) * factor except ValueError : return None
1
fraction and whole number string to float python
Parse a string of the form 305 . 48b into a Python float . The terminal letter if present indicates e . g . billions .
cosqa-train-13247
def parse_float(float_str): """Parse a string of the form 305.48b into a Python float. The terminal letter, if present, indicates e.g. billions.""" factor = __get_factor(float_str) if factor != 1: float_str = float_str[:-1] try: return float(float_str.replace(',', '')) * factor except ValueError: return None
def cli ( ctx , project_dir ) : exit_code = SCons ( project_dir ) . clean ( ) ctx . exit ( exit_code )
1
python how to exit a project
Clean the previous generated files .
cosqa-train-13248
def cli(ctx, project_dir): """Clean the previous generated files.""" exit_code = SCons(project_dir).clean() ctx.exit(exit_code)
def connect ( ) : ftp_class = ftplib . FTP if not SSL else ftplib . FTP_TLS ftp = ftp_class ( timeout = TIMEOUT ) ftp . connect ( HOST , PORT ) ftp . login ( USER , PASSWORD ) if SSL : ftp . prot_p ( ) # secure data connection return ftp
1
free servers for testing ftp in python
Connect to FTP server login and return an ftplib . FTP instance .
cosqa-train-13249
def connect(): """Connect to FTP server, login and return an ftplib.FTP instance.""" ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS ftp = ftp_class(timeout=TIMEOUT) ftp.connect(HOST, PORT) ftp.login(USER, PASSWORD) if SSL: ftp.prot_p() # secure data connection return ftp
def fmt_duration ( secs ) : return ' ' . join ( fmt . human_duration ( secs , 0 , precision = 2 , short = True ) . strip ( ) . split ( ) )
1
python how to format a duration in seconds
Format a duration in seconds .
cosqa-train-13250
def fmt_duration(secs): """Format a duration in seconds.""" return ' '.join(fmt.human_duration(secs, 0, precision=2, short=True).strip().split())
def get_lons_from_cartesian ( x__ , y__ ) : return rad2deg ( arccos ( x__ / sqrt ( x__ ** 2 + y__ ** 2 ) ) ) * sign ( y__ )
0
from polar to lat lon python
Get longitudes from cartesian coordinates .
cosqa-train-13251
def get_lons_from_cartesian(x__, y__): """Get longitudes from cartesian coordinates. """ return rad2deg(arccos(x__ / sqrt(x__ ** 2 + y__ ** 2))) * sign(y__)
def _digits ( minval , maxval ) : if minval == maxval : return 3 else : return min ( 10 , max ( 2 , int ( 1 + abs ( np . log10 ( maxval - minval ) ) ) ) )
1
python how to get a decimal range
Digits needed to comforatbly display values in [ minval maxval ]
cosqa-train-13252
def _digits(minval, maxval): """Digits needed to comforatbly display values in [minval, maxval]""" if minval == maxval: return 3 else: return min(10, max(2, int(1 + abs(np.log10(maxval - minval)))))
def _bytes_to_json ( value ) : if isinstance ( value , bytes ) : value = base64 . standard_b64encode ( value ) . decode ( "ascii" ) return value
1
from python json to bytes
Coerce value to an JSON - compatible representation .
cosqa-train-13253
def _bytes_to_json(value): """Coerce 'value' to an JSON-compatible representation.""" if isinstance(value, bytes): value = base64.standard_b64encode(value).decode("ascii") return value
def _num_cpus_darwin ( ) : p = subprocess . Popen ( [ 'sysctl' , '-n' , 'hw.ncpu' ] , stdout = subprocess . PIPE ) return p . stdout . read ( )
1
python how to get number of cores on computer
Return the number of active CPUs on a Darwin system .
cosqa-train-13254
def _num_cpus_darwin(): """Return the number of active CPUs on a Darwin system.""" p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE) return p.stdout.read()
def get_table_width ( table ) : columns = transpose_table ( prepare_rows ( table ) ) widths = [ max ( len ( cell ) for cell in column ) for column in columns ] return len ( '+' + '|' . join ( '-' * ( w + 2 ) for w in widths ) + '+' )
1
function for width of table in python
Gets the width of the table that would be printed . : rtype : int
cosqa-train-13255
def get_table_width(table): """ Gets the width of the table that would be printed. :rtype: ``int`` """ columns = transpose_table(prepare_rows(table)) widths = [max(len(cell) for cell in column) for column in columns] return len('+' + '|'.join('-' * (w + 2) for w in widths) + '+')
def find_root ( self ) : cmd = self while cmd . parent : cmd = cmd . parent return cmd
1
python how to get parent of self
Traverse parent refs to top .
cosqa-train-13256
def find_root(self): """ Traverse parent refs to top. """ cmd = self while cmd.parent: cmd = cmd.parent return cmd
def _fullname ( o ) : return o . __module__ + "." + o . __name__ if o . __module__ else o . __name__
1
function name to string python
Return the fully - qualified name of a function .
cosqa-train-13257
def _fullname(o): """Return the fully-qualified name of a function.""" return o.__module__ + "." + o.__name__ if o.__module__ else o.__name__
def get_obj_cols ( df ) : obj_cols = [ ] for idx , dt in enumerate ( df . dtypes ) : if dt == 'object' or is_category ( dt ) : obj_cols . append ( df . columns . values [ idx ] ) return obj_cols
1
python how to get the names of columns in data frame
Returns names of object columns in the DataFrame .
cosqa-train-13258
def get_obj_cols(df): """ Returns names of 'object' columns in the DataFrame. """ obj_cols = [] for idx, dt in enumerate(df.dtypes): if dt == 'object' or is_category(dt): obj_cols.append(df.columns.values[idx]) return obj_cols
def flatten_list ( l ) : return list ( chain . from_iterable ( repeat ( x , 1 ) if isinstance ( x , str ) else x for x in l ) )
1
function python several lists to one list
Nested lists to single - level list does not split strings
cosqa-train-13259
def flatten_list(l): """ Nested lists to single-level list, does not split strings""" return list(chain.from_iterable(repeat(x,1) if isinstance(x,str) else x for x in l))
def count_ ( self ) : try : num = len ( self . df . index ) except Exception as e : self . err ( e , "Can not count data" ) return return num
1
python how to get the number of rows of a data frame
Returns the number of rows of the main dataframe
cosqa-train-13260
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 apply ( self , func , args = ( ) , kwds = dict ( ) ) : return self . apply_async ( func , args , kwds ) . get ( )
1
function return apply async python
Equivalent of the apply () builtin function . It blocks till the result is ready .
cosqa-train-13261
def apply(self, func, args=(), kwds=dict()): """Equivalent of the apply() builtin function. It blocks till the result is ready.""" return self.apply_async(func, args, kwds).get()
def _check_task_id ( self , context ) : ti = context [ 'ti' ] celery_result = ti . xcom_pull ( task_ids = self . target_task_id ) return celery_result . ready ( )
1
python how to get the progress of celery task
Gets the returned Celery result from the Airflow task ID provided to the sensor and returns True if the celery result has been finished execution .
cosqa-train-13262
def _check_task_id(self, context): """ Gets the returned Celery result from the Airflow task ID provided to the sensor, and returns True if the celery result has been finished execution. :param context: Airflow's execution context :type context: dict :return: True if task has been executed, otherwise False :rtype: bool """ ti = context['ti'] celery_result = ti.xcom_pull(task_ids=self.target_task_id) return celery_result.ready()
def _file_exists ( path , filename ) : return os . path . isfile ( os . path . join ( path , filename ) )
1
function to check file existence in python
Checks if the filename exists under the path .
cosqa-train-13263
def _file_exists(path, filename): """Checks if the filename exists under the path.""" return os.path.isfile(os.path.join(path, filename))
def to_tree ( self ) : tree = TreeLibTree ( ) for node in self : tree . create_node ( node , node . node_id , parent = node . parent ) return tree
1
python how to get tree object
returns a TreeLib tree
cosqa-train-13264
def to_tree(self): """ returns a TreeLib tree """ tree = TreeLibTree() for node in self: tree.create_node(node, node.node_id, parent=node.parent) return tree
def test3 ( ) : import time p = MVisionProcess ( ) p . start ( ) time . sleep ( 5 ) p . stop ( )
1
function to repeat process in python 3
Test the multiprocess
cosqa-train-13265
def test3(): """Test the multiprocess """ import time p = MVisionProcess() p.start() time.sleep(5) p.stop()
def hash_iterable ( it ) : hash_value = hash ( type ( it ) ) for value in it : hash_value = hash ( ( hash_value , value ) ) return hash_value
0
python how to hash tuple
Perform a O ( 1 ) memory hash of an iterable of arbitrary length .
cosqa-train-13266
def hash_iterable(it): """Perform a O(1) memory hash of an iterable of arbitrary length. hash(tuple(it)) creates a temporary tuple containing all values from it which could be a problem if it is large. See discussion at: https://groups.google.com/forum/#!msg/python-ideas/XcuC01a8SYs/e-doB9TbDwAJ """ hash_value = hash(type(it)) for value in it: hash_value = hash((hash_value, value)) return hash_value
def gauss_pdf ( x , mu , sigma ) : return 1 / np . sqrt ( 2 * np . pi ) / sigma * np . exp ( - ( x - mu ) ** 2 / 2. / sigma ** 2 )
1
gaussian distribution code in python
Normalized Gaussian
cosqa-train-13267
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 handle_m2m ( self , sender , instance , * * kwargs ) : self . handle_save ( instance . __class__ , instance )
0
python how to implement one to many association
Handle many to many relationships
cosqa-train-13268
def handle_m2m(self, sender, instance, **kwargs): """ Handle many to many relationships """ self.handle_save(instance.__class__, instance)
def gaussian_kernel ( sigma , truncate = 4.0 ) : sigma = float ( sigma ) radius = int ( truncate * sigma + 0.5 ) x , y = np . mgrid [ - radius : radius + 1 , - radius : radius + 1 ] sigma = sigma ** 2 k = 2 * np . exp ( - 0.5 * ( x ** 2 + y ** 2 ) / sigma ) k = k / np . sum ( k ) return k
1
gaussian kernel python with sigma and width
Return Gaussian that truncates at the given number of std deviations .
cosqa-train-13269
def gaussian_kernel(sigma, truncate=4.0): """Return Gaussian that truncates at the given number of std deviations. Adapted from https://github.com/nicjhan/gaussian-filter """ sigma = float(sigma) radius = int(truncate * sigma + 0.5) x, y = np.mgrid[-radius:radius + 1, -radius:radius + 1] sigma = sigma ** 2 k = 2 * np.exp(-0.5 * (x ** 2 + y ** 2) / sigma) k = k / np.sum(k) return k
def do_next ( self , args ) : self . _do_print_from_last_cmd = True self . _interp . step_over ( ) return True
1
python how to jump to next loop
Step over the next statement
cosqa-train-13270
def do_next(self, args): """Step over the next statement """ self._do_print_from_last_cmd = True self._interp.step_over() return True
def generate_random_id ( size = 6 , chars = string . ascii_uppercase + string . digits ) : return "" . join ( random . choice ( chars ) for x in range ( size ) )
0
generate arbitrary ascii identifier in python
Generate random id numbers .
cosqa-train-13271
def generate_random_id(size=6, chars=string.ascii_uppercase + string.digits): """Generate random id numbers.""" return "".join(random.choice(chars) for x in range(size))
def _unique_rows_numpy ( a ) : a = np . ascontiguousarray ( a ) unique_a = np . unique ( a . view ( [ ( '' , a . dtype ) ] * a . shape [ 1 ] ) ) return unique_a . view ( a . dtype ) . reshape ( ( unique_a . shape [ 0 ] , a . shape [ 1 ] ) )
1
python how to keep every 3rd element of array
return unique rows
cosqa-train-13272
def _unique_rows_numpy(a): """return unique rows""" a = np.ascontiguousarray(a) unique_a = np.unique(a.view([('', a.dtype)] * a.shape[1])) return unique_a.view(a.dtype).reshape((unique_a.shape[0], a.shape[1]))
def mongoqs_to_json ( qs , fields = None ) : l = list ( qs . as_pymongo ( ) ) for element in l : element . pop ( '_cls' ) # use DjangoJSONEncoder for transform date data type to datetime json_qs = json . dumps ( l , indent = 2 , ensure_ascii = False , cls = DjangoJSONEncoder ) return json_qs
1
generate json to python queryset object
transform mongoengine . QuerySet to json
cosqa-train-13273
def mongoqs_to_json(qs, fields=None): """ transform mongoengine.QuerySet to json """ l = list(qs.as_pymongo()) for element in l: element.pop('_cls') # use DjangoJSONEncoder for transform date data type to datetime json_qs = json.dumps(l, indent=2, ensure_ascii=False, cls=DjangoJSONEncoder) return json_qs
def _uniform_phi ( M ) : return np . random . uniform ( - np . pi , np . pi , M )
1
generate random unitary matrix in python
Generate M random numbers in [ - pi pi ) .
cosqa-train-13274
def _uniform_phi(M): """ Generate M random numbers in [-pi, pi). """ return np.random.uniform(-np.pi, np.pi, M)
def getPrimeFactors ( n ) : lo = [ 1 ] n2 = n // 2 k = 2 for k in range ( 2 , n2 + 1 ) : if ( n // k ) * k == n : lo . append ( k ) return lo + [ n , ]
1
python how to make a list of prime numbers
Get all the prime factor of given integer
cosqa-train-13275
def getPrimeFactors(n): """ Get all the prime factor of given integer @param n integer @return list [1, ..., n] """ lo = [1] n2 = n // 2 k = 2 for k in range(2, n2 + 1): if (n // k)*k == n: lo.append(k) return lo + [n, ]
def generate_unique_host_id ( ) : host = "." . join ( reversed ( socket . gethostname ( ) . split ( "." ) ) ) pid = os . getpid ( ) return "%s.%d" % ( host , pid )
1
generate short unique id python
Generate a unique ID that is somewhat guaranteed to be unique among all instances running at the same time .
cosqa-train-13276
def generate_unique_host_id(): """Generate a unique ID, that is somewhat guaranteed to be unique among all instances running at the same time.""" host = ".".join(reversed(socket.gethostname().split("."))) pid = os.getpid() return "%s.%d" % (host, pid)
def _dotify ( cls , data ) : return '' . join ( char if char in cls . PRINTABLE_DATA else '.' for char in data )
1
python how to make dot charcter
Add dots .
cosqa-train-13277
def _dotify(cls, data): """Add dots.""" return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data)
def daterange ( start_date , end_date ) : for n in range ( int ( ( end_date - start_date ) . days ) ) : yield start_date + timedelta ( n )
1
get a range of dates python
Yield one date per day from starting date to ending date .
cosqa-train-13278
def daterange(start_date, end_date): """ Yield one date per day from starting date to ending date. Args: start_date (date): starting date. end_date (date): ending date. Yields: date: a date for each day within the range. """ for n in range(int((end_date - start_date).days)): yield start_date + timedelta(n)
def _set_scroll_v ( self , * args ) : self . _canvas_categories . yview ( * args ) self . _canvas_scroll . yview ( * args )
0
python how to make kivy scrollview be at the end
Scroll both categories Canvas and scrolling container
cosqa-train-13279
def _set_scroll_v(self, *args): """Scroll both categories Canvas and scrolling container""" self._canvas_categories.yview(*args) self._canvas_scroll.yview(*args)
def title ( self ) : with switch_window ( self . _browser , self . name ) : return self . _browser . title
0
get active window title python
The title of this window
cosqa-train-13280
def title(self): """ The title of this window """ with switch_window(self._browser, self.name): return self._browser.title
def do_restart ( self , line ) : self . application . master . Restart ( opendnp3 . RestartType . COLD , restart_callback )
1
python how to make something restart
Request that the Outstation perform a cold restart . Command syntax is : restart
cosqa-train-13281
def do_restart(self, line): """Request that the Outstation perform a cold restart. Command syntax is: restart""" self.application.master.Restart(opendnp3.RestartType.COLD, restart_callback)
def _get_str_columns ( sf ) : return [ name for name in sf . column_names ( ) if sf [ name ] . dtype == str ]
1
get all column names in a dataset in python
Returns a list of names of columns that are string type .
cosqa-train-13282
def _get_str_columns(sf): """ Returns a list of names of columns that are string type. """ return [name for name in sf.column_names() if sf[name].dtype == str]
def ma ( self ) : a = self . array return numpy . ma . MaskedArray ( a , mask = numpy . logical_not ( numpy . isfinite ( a ) ) )
1
python how to mask a numpy array
Represent data as a masked array .
cosqa-train-13283
def ma(self): """Represent data as a masked array. The array is returned with column-first indexing, i.e. for a data file with columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1] = Y1, ... . inf and nan are filtered via :func:`numpy.isfinite`. """ a = self.array return numpy.ma.MaskedArray(a, mask=numpy.logical_not(numpy.isfinite(a)))
def __get_xml_text ( root ) : txt = "" for e in root . childNodes : if ( e . nodeType == e . TEXT_NODE ) : txt += e . data return txt
1
get all text inside xml python
Return the text for the given root node ( xml . dom . minidom ) .
cosqa-train-13284
def __get_xml_text(root): """ Return the text for the given root node (xml.dom.minidom). """ txt = "" for e in root.childNodes: if (e.nodeType == e.TEXT_NODE): txt += e.data return txt
def set_context ( self , data ) : for key in data : setattr ( self . local_context , key , data [ key ] )
1
python how to merge into locals
Load Context with data
cosqa-train-13285
def set_context(self, data): """Load Context with data""" for key in data: setattr(self.local_context, key, data[key])
def get_attribute_name_id ( attr ) : return attr . value . id if isinstance ( attr . value , ast . Name ) else None
0
get attribute type from python
Return the attribute name identifier
cosqa-train-13286
def get_attribute_name_id(attr): """ Return the attribute name identifier """ return attr.value.id if isinstance(attr.value, ast.Name) else None
def normalize_array ( lst ) : np_arr = np . array ( lst ) x_normalized = np_arr / np_arr . max ( axis = 0 ) return list ( x_normalized )
1
python how to normalize an array
Normalizes list
cosqa-train-13287
def normalize_array(lst): """Normalizes list :param lst: Array of floats :return: Normalized (in [0, 1]) input array """ np_arr = np.array(lst) x_normalized = np_arr / np_arr.max(axis=0) return list(x_normalized)
def shape ( self ) : return tuple ( len ( self . _get_axis ( a ) ) for a in self . _AXIS_ORDERS )
1
get axis size python
Return a tuple of axis dimensions
cosqa-train-13288
def shape(self): """ Return a tuple of axis dimensions """ return tuple(len(self._get_axis(a)) for a in self._AXIS_ORDERS)
def normalize ( self , string ) : return '' . join ( [ self . _normalize . get ( x , x ) for x in nfd ( string ) ] )
1
python how to normalize text values
Normalize the string according to normalization list
cosqa-train-13289
def normalize(self, string): """Normalize the string according to normalization list""" return ''.join([self._normalize.get(x, x) for x in nfd(string)])
def is_bool_matrix ( l ) : if isinstance ( l , np . ndarray ) : if l . ndim == 2 and ( l . dtype == bool ) : return True return False
1
get boolean matrix similar python
r Checks if l is a 2D numpy array of bools
cosqa-train-13290
def is_bool_matrix(l): r"""Checks if l is a 2D numpy array of bools """ if isinstance(l, np.ndarray): if l.ndim == 2 and (l.dtype == bool): return True return False
def fopenat ( base_fd , path ) : return os . fdopen ( openat ( base_fd , path , os . O_RDONLY ) , 'rb' )
1
python how to open a file in relative path
Does openat read - only then does fdopen to get a file object
cosqa-train-13291
def fopenat(base_fd, path): """ Does openat read-only, then does fdopen to get a file object """ return os.fdopen(openat(base_fd, path, os.O_RDONLY), 'rb')
def array_bytes ( array ) : return np . product ( array . shape ) * np . dtype ( array . dtype ) . itemsize
0
get bytes size of array python
Estimates the memory of the supplied array in bytes
cosqa-train-13292
def array_bytes(array): """ Estimates the memory of the supplied array in bytes """ return np.product(array.shape)*np.dtype(array.dtype).itemsize
def reopen ( self ) : try : self . _con . reopen ( ) except Exception : if self . _transcation : self . _transaction = False try : self . _con . query ( 'rollback' ) except Exception : pass else : self . _transaction = False self . _closed = False self . _setsession ( ) self . _usage = 0
0
python how to preserve a connection i
Reopen the tough connection .
cosqa-train-13293
def reopen(self): """Reopen the tough connection. It will not complain if the connection cannot be reopened. """ try: self._con.reopen() except Exception: if self._transcation: self._transaction = False try: self._con.query('rollback') except Exception: pass else: self._transaction = False self._closed = False self._setsession() self._usage = 0
def paste ( cmd = paste_cmd , stdout = PIPE ) : return Popen ( cmd , stdout = stdout ) . communicate ( ) [ 0 ] . decode ( 'utf-8' )
1
get clipboard data with python on linux
Returns system clipboard contents .
cosqa-train-13294
def paste(cmd=paste_cmd, stdout=PIPE): """Returns system clipboard contents. """ return Popen(cmd, stdout=stdout).communicate()[0].decode('utf-8')
def native_conn ( self ) : if self . __native is None : self . __native = self . _get_connection ( ) return self . __native
0
python how to preserve a connection in
Native connection object .
cosqa-train-13295
def native_conn(self): """Native connection object.""" if self.__native is None: self.__native = self._get_connection() return self.__native
def AmericanDateToEpoch ( self , date_str ) : try : epoch = time . strptime ( date_str , "%m/%d/%Y" ) return int ( calendar . timegm ( epoch ) ) * 1000000 except ValueError : return 0
1
get date from epoch timestamp python
Take a US format date and return epoch .
cosqa-train-13296
def AmericanDateToEpoch(self, date_str): """Take a US format date and return epoch.""" try: epoch = time.strptime(date_str, "%m/%d/%Y") return int(calendar.timegm(epoch)) * 1000000 except ValueError: return 0
def runcode ( code ) : for line in code : print ( '# ' + line ) exec ( line , globals ( ) ) print ( '# return ans' ) return ans
0
python how to print code as its executed
Run the given code line by line with printing as list of lines and return variable ans .
cosqa-train-13297
def runcode(code): """Run the given code line by line with printing, as list of lines, and return variable 'ans'.""" for line in code: print('# '+line) exec(line,globals()) print('# return ans') return ans
def datetime64_to_datetime ( dt ) : dt64 = np . datetime64 ( dt ) ts = ( dt64 - np . datetime64 ( '1970-01-01T00:00:00' ) ) / np . timedelta64 ( 1 , 's' ) return datetime . datetime . utcfromtimestamp ( ts )
1
get date from timedelta64 python
convert numpy s datetime64 to datetime
cosqa-train-13298
def datetime64_to_datetime(dt): """ convert numpy's datetime64 to datetime """ dt64 = np.datetime64(dt) ts = (dt64 - np.datetime64('1970-01-01T00:00:00')) / np.timedelta64(1, 's') return datetime.datetime.utcfromtimestamp(ts)
def _dump_enum ( self , e , top = '' ) : self . _print ( ) self . _print ( 'enum {} {{' . format ( e . name ) ) self . defines . append ( '{}.{}' . format ( top , e . name ) ) self . tabs += 1 for v in e . value : self . _print ( '{} = {};' . format ( v . name , v . number ) ) self . tabs -= 1 self . _print ( '}' )
1
python how to print enum key
Dump single enum type . Keyword arguments : top -- top namespace
cosqa-train-13299
def _dump_enum(self, e, top=''): """Dump single enum type. Keyword arguments: top -- top namespace """ self._print() self._print('enum {} {{'.format(e.name)) self.defines.append('{}.{}'.format(top,e.name)) self.tabs+=1 for v in e.value: self._print('{} = {};'.format(v.name, v.number)) self.tabs-=1 self._print('}')