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 hide ( self ) : if not HidePrevention ( self . window ) . may_hide ( ) : return self . hidden = True self . get_widget ( 'window-root' ) . unstick ( ) self . window . hide ( )
| 1 |
how to hidden controls of frame in python
|
Hides the main window of the terminal and sets the visible flag to False .
|
cosqa-train-16000
|
def hide(self):
"""Hides the main window of the terminal and sets the visible
flag to False.
"""
if not HidePrevention(self.window).may_hide():
return
self.hidden = True
self.get_widget('window-root').unstick()
self.window.hide()
|
def close ( self ) : if self . db is not None : self . db . commit ( ) self . db . close ( ) self . db = None return
| 0 |
python release memory after function call
|
Close the db and release memory
|
cosqa-train-16001
|
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 strip_comment_marker ( text ) : lines = [ ] for line in text . splitlines ( ) : lines . append ( line . lstrip ( '#' ) ) text = textwrap . dedent ( '\n' . join ( lines ) ) return text
| 0 |
how to hide comment in python
|
Strip # markers at the front of a block of comment text .
|
cosqa-train-16002
|
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
|
def filter_dict_by_key ( d , keys ) : return { k : v for k , v in d . items ( ) if k in keys }
| 0 |
python remove all element in dictionary whose
|
Filter the dict * d * to remove keys not in * keys * .
|
cosqa-train-16003
|
def filter_dict_by_key(d, keys):
"""Filter the dict *d* to remove keys not in *keys*."""
return {k: v for k, v in d.items() if k in keys}
|
def table_nan_locs ( table ) : ans = [ ] for rownum , row in enumerate ( table ) : try : if pd . isnull ( row ) . any ( ) : colnums = pd . isnull ( row ) . nonzero ( ) [ 0 ] ans += [ ( rownum , colnum ) for colnum in colnums ] except AttributeError : # table is really just a sequence of scalars if pd . isnull ( row ) : ans += [ ( rownum , 0 ) ] return ans
| 1 |
how to identify columsn with missing data in python 3
|
from http : // stackoverflow . com / a / 14033137 / 623735 # gets the indices of the rows with nan values in a dataframe pd . isnull ( df ) . any ( 1 ) . nonzero () [ 0 ]
|
cosqa-train-16004
|
def table_nan_locs(table):
"""
from http://stackoverflow.com/a/14033137/623735
# gets the indices of the rows with nan values in a dataframe
pd.isnull(df).any(1).nonzero()[0]
"""
ans = []
for rownum, row in enumerate(table):
try:
if pd.isnull(row).any():
colnums = pd.isnull(row).nonzero()[0]
ans += [(rownum, colnum) for colnum in colnums]
except AttributeError: # table is really just a sequence of scalars
if pd.isnull(row):
ans += [(rownum, 0)]
return ans
|
def strip_sdist_extras ( filelist ) : return [ name for name in filelist if not file_matches ( name , IGNORE ) and not file_matches_regexps ( name , IGNORE_REGEXPS ) ]
| 0 |
python remove all files not in a list
|
Strip generated files that are only present in source distributions .
|
cosqa-train-16005
|
def strip_sdist_extras(filelist):
"""Strip generated files that are only present in source distributions.
We also strip files that are ignored for other reasons, like
command line arguments, setup.cfg rules or MANIFEST.in rules.
"""
return [name for name in filelist
if not file_matches(name, IGNORE)
and not file_matches_regexps(name, IGNORE_REGEXPS)]
|
def coverage ( ctx , opts = "" ) : return test ( ctx , coverage = True , include_slow = True , opts = opts )
| 0 |
how to increase coverage in unit testing python
|
Execute all tests ( normal and slow ) with coverage enabled .
|
cosqa-train-16006
|
def coverage(ctx, opts=""):
"""
Execute all tests (normal and slow) with coverage enabled.
"""
return test(ctx, coverage=True, include_slow=True, opts=opts)
|
def _remove_blank ( l ) : ret = [ ] for i , _ in enumerate ( l ) : if l [ i ] == 0 : break ret . append ( l [ i ] ) return ret
| 0 |
python remove all zeros from a list
|
Removes trailing zeros in the list of integers and returns a new list of integers
|
cosqa-train-16007
|
def _remove_blank(l):
""" Removes trailing zeros in the list of integers and returns a new list of integers"""
ret = []
for i, _ in enumerate(l):
if l[i] == 0:
break
ret.append(l[i])
return ret
|
def init_checks_registry ( ) : mod = inspect . getmodule ( register_check ) for ( name , function ) in inspect . getmembers ( mod , inspect . isfunction ) : register_check ( function )
| 1 |
how to inspect a function python
|
Register all globally visible functions .
|
cosqa-train-16008
|
def init_checks_registry():
"""Register all globally visible functions.
The first argument name is either 'physical_line' or 'logical_line'.
"""
mod = inspect.getmodule(register_check)
for (name, function) in inspect.getmembers(mod, inspect.isfunction):
register_check(function)
|
def unpunctuate ( s , * , char_blacklist = string . punctuation ) : # remove punctuation s = "" . join ( c for c in s if c not in char_blacklist ) # remove consecutive spaces return " " . join ( filter ( None , s . split ( " " ) ) )
| 0 |
python remove any white spaces from string
|
Remove punctuation from string s .
|
cosqa-train-16009
|
def unpunctuate(s, *, char_blacklist=string.punctuation):
""" Remove punctuation from string s. """
# remove punctuation
s = "".join(c for c in s if c not in char_blacklist)
# remove consecutive spaces
return " ".join(filter(None, s.split(" ")))
|
def interpolate_logscale_single ( start , end , coefficient ) : return np . exp ( np . log ( start ) + ( np . log ( end ) - np . log ( start ) ) * coefficient )
| 0 |
how to interpolate logarithmic in python
|
Cosine interpolation
|
cosqa-train-16010
|
def interpolate_logscale_single(start, end, coefficient):
""" Cosine interpolation """
return np.exp(np.log(start) + (np.log(end) - np.log(start)) * coefficient)
|
def __normalize_list ( self , msg ) : if isinstance ( msg , list ) : msg = "" . join ( msg ) return list ( map ( lambda x : x . strip ( ) , msg . split ( "," ) ) )
| 1 |
python remove comma from list
|
Split message to list by commas and trim whitespace .
|
cosqa-train-16011
|
def __normalize_list(self, msg):
"""Split message to list by commas and trim whitespace."""
if isinstance(msg, list):
msg = "".join(msg)
return list(map(lambda x: x.strip(), msg.split(",")))
|
def _normal_prompt ( self ) : sys . stdout . write ( self . __get_ps1 ( ) ) sys . stdout . flush ( ) return safe_input ( )
| 0 |
how to keep prompt in python
|
Flushes the prompt before requesting the input
|
cosqa-train-16012
|
def _normal_prompt(self):
"""
Flushes the prompt before requesting the input
:return: The command line
"""
sys.stdout.write(self.__get_ps1())
sys.stdout.flush()
return safe_input()
|
def _str_to_list ( s ) : _list = s . split ( "," ) return list ( map ( lambda i : i . lstrip ( ) , _list ) )
| 0 |
python remove commas from list string
|
Converts a comma separated string to a list
|
cosqa-train-16013
|
def _str_to_list(s):
"""Converts a comma separated string to a list"""
_list = s.split(",")
return list(map(lambda i: i.lstrip(), _list))
|
def open01 ( x , limit = 1.e-6 ) : try : return np . array ( [ min ( max ( y , limit ) , 1. - limit ) for y in x ] ) except TypeError : return min ( max ( x , limit ) , 1. - limit )
| 0 |
how to limit a float in python
|
Constrain numbers to ( 0 1 ) interval
|
cosqa-train-16014
|
def open01(x, limit=1.e-6):
"""Constrain numbers to (0,1) interval"""
try:
return np.array([min(max(y, limit), 1. - limit) for y in x])
except TypeError:
return min(max(x, limit), 1. - limit)
|
def pop ( self , key ) : if key in self . _keys : self . _keys . remove ( key ) super ( ListDict , self ) . pop ( key )
| 0 |
python remove dictionary element
|
Remove key from dict and return value .
|
cosqa-train-16015
|
def pop (self, key):
"""Remove key from dict and return value."""
if key in self._keys:
self._keys.remove(key)
super(ListDict, self).pop(key)
|
def roundClosestValid ( val , res , decimals = None ) : if decimals is None and "." in str ( res ) : decimals = len ( str ( res ) . split ( '.' ) [ 1 ] ) return round ( round ( val / res ) * res , decimals )
| 1 |
how to limit the decimals in python
|
round to closest resolution
|
cosqa-train-16016
|
def roundClosestValid(val, res, decimals=None):
""" round to closest resolution """
if decimals is None and "." in str(res):
decimals = len(str(res).split('.')[1])
return round(round(val / res) * res, decimals)
|
def _remove_dict_keys_with_value ( dict_ , val ) : return { k : v for k , v in dict_ . items ( ) if v is not val }
| 0 |
python remove dictionary object if has attribute
|
Removes dict keys which have have self as value .
|
cosqa-train-16017
|
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 apply_fit ( xy , coeffs ) : x_new = coeffs [ 0 ] [ 2 ] + coeffs [ 0 ] [ 0 ] * xy [ : , 0 ] + coeffs [ 0 ] [ 1 ] * xy [ : , 1 ] y_new = coeffs [ 1 ] [ 2 ] + coeffs [ 1 ] [ 0 ] * xy [ : , 0 ] + coeffs [ 1 ] [ 1 ] * xy [ : , 1 ] return x_new , y_new
| 0 |
how to linear fit in python for some points
|
Apply the coefficients from a linear fit to an array of x y positions .
|
cosqa-train-16018
|
def apply_fit(xy,coeffs):
""" Apply the coefficients from a linear fit to
an array of x,y positions.
The coeffs come from the 'coeffs' member of the
'fit_arrays()' output.
"""
x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1]
y_new = coeffs[1][2] + coeffs[1][0]*xy[:,0] + coeffs[1][1]*xy[:,1]
return x_new,y_new
|
def clean_py_files ( path ) : for dirname , subdirlist , filelist in os . walk ( path ) : for f in filelist : if f . endswith ( 'py' ) : os . remove ( os . path . join ( dirname , f ) )
| 0 |
python remove files by extension
|
Removes all . py files .
|
cosqa-train-16019
|
def clean_py_files(path):
"""
Removes all .py files.
:param path: the path
:return: None
"""
for dirname, subdirlist, filelist in os.walk(path):
for f in filelist:
if f.endswith('py'):
os.remove(os.path.join(dirname, f))
|
def get_param_names ( cls ) : return [ m [ 0 ] for m in inspect . getmembers ( cls ) if type ( m [ 1 ] ) == property ]
| 0 |
how to list the properties of a variable in python
|
Returns a list of plottable CBC parameter variables
|
cosqa-train-16020
|
def get_param_names(cls):
"""Returns a list of plottable CBC parameter variables"""
return [m[0] for m in inspect.getmembers(cls) \
if type(m[1]) == property]
|
def graph_from_dot_file ( path ) : fd = file ( path , 'rb' ) data = fd . read ( ) fd . close ( ) return graph_from_dot_data ( data )
| 0 |
how to load a dot max file into python
|
Load graph as defined by a DOT file . The file is assumed to be in DOT format . It will be loaded parsed and a Dot class will be returned representing the graph .
|
cosqa-train-16021
|
def graph_from_dot_file(path):
"""Load graph as defined by a DOT file.
The file is assumed to be in DOT format. It will
be loaded, parsed and a Dot class will be returned,
representing the graph.
"""
fd = file(path, 'rb')
data = fd.read()
fd.close()
return graph_from_dot_data(data)
|
def strip_html ( string , keep_tag_content = False ) : r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE return r . sub ( '' , string )
| 1 |
python remove html from string
|
Remove html code contained into the given string .
|
cosqa-train-16022
|
def strip_html(string, keep_tag_content=False):
"""
Remove html code contained into the given string.
:param string: String to manipulate.
:type string: str
:param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default).
:type keep_tag_content: bool
:return: String with html removed.
:rtype: str
"""
r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE
return r.sub('', string)
|
def load_feature ( fname , language ) : fname = os . path . abspath ( fname ) feat = parse_file ( fname , language ) return feat
| 1 |
how to load a string file in python
|
Load and parse a feature file .
|
cosqa-train-16023
|
def load_feature(fname, language):
""" Load and parse a feature file. """
fname = os.path.abspath(fname)
feat = parse_file(fname, language)
return feat
|
def pop ( h ) : n = h . size ( ) - 1 h . swap ( 0 , n ) down ( h , 0 , n ) return h . pop ( )
| 0 |
python remove item from heap
|
Pop the heap value from the heap .
|
cosqa-train-16024
|
def pop(h):
"""Pop the heap value from the heap."""
n = h.size() - 1
h.swap(0, n)
down(h, 0, n)
return h.pop()
|
def get ( url ) : response = urllib . request . urlopen ( url ) data = response . read ( ) data = data . decode ( "utf-8" ) data = json . loads ( data ) return data
| 1 |
how to load data from url with python
|
Recieving the JSON file from uulm
|
cosqa-train-16025
|
def get(url):
"""Recieving the JSON file from uulm"""
response = urllib.request.urlopen(url)
data = response.read()
data = data.decode("utf-8")
data = json.loads(data)
return data
|
def remove_legend ( ax = None ) : from pylab import gca , draw if ax is None : ax = gca ( ) ax . legend_ = None draw ( )
| 0 |
python remove legend from plot
|
Remove legend for axes or gca .
|
cosqa-train-16026
|
def remove_legend(ax=None):
"""Remove legend for axes or gca.
See http://osdir.com/ml/python.matplotlib.general/2005-07/msg00285.html
"""
from pylab import gca, draw
if ax is None:
ax = gca()
ax.legend_ = None
draw()
|
def print_log ( text , * colors ) : sys . stderr . write ( sprint ( "{}: {}" . format ( script_name , text ) , * colors ) + "\n" )
| 1 |
how to log errors in python
|
Print a log message to standard error .
|
cosqa-train-16027
|
def print_log(text, *colors):
"""Print a log message to standard error."""
sys.stderr.write(sprint("{}: {}".format(script_name, text), *colors) + "\n")
|
def replaceNewlines ( string , newlineChar ) : if newlineChar in string : segments = string . split ( newlineChar ) string = "" for segment in segments : string += segment return string
| 0 |
python remove linebreak inside string
|
There s probably a way to do this with string functions but I was lazy . Replace all instances of \ r or \ n in a string with something else .
|
cosqa-train-16028
|
def replaceNewlines(string, newlineChar):
"""There's probably a way to do this with string functions but I was lazy.
Replace all instances of \r or \n in a string with something else."""
if newlineChar in string:
segments = string.split(newlineChar)
string = ""
for segment in segments:
string += segment
return string
|
def next ( self ) : _LOGGER . debug ( "reading next" ) if self . closed : _LOGGER . debug ( "stream is closed" ) raise StopIteration ( ) line = self . readline ( ) if not line : _LOGGER . debug ( "nothing more to read" ) raise StopIteration ( ) return line
| 0 |
how to loop through python iterator without stopiteration error
|
Provides hook for Python2 iterator functionality .
|
cosqa-train-16029
|
def next(self):
"""Provides hook for Python2 iterator functionality."""
_LOGGER.debug("reading next")
if self.closed:
_LOGGER.debug("stream is closed")
raise StopIteration()
line = self.readline()
if not line:
_LOGGER.debug("nothing more to read")
raise StopIteration()
return line
|
def replaceNewlines ( string , newlineChar ) : if newlineChar in string : segments = string . split ( newlineChar ) string = "" for segment in segments : string += segment return string
| 1 |
python remove new line character from string\
|
There s probably a way to do this with string functions but I was lazy . Replace all instances of \ r or \ n in a string with something else .
|
cosqa-train-16030
|
def replaceNewlines(string, newlineChar):
"""There's probably a way to do this with string functions but I was lazy.
Replace all instances of \r or \n in a string with something else."""
if newlineChar in string:
segments = string.split(newlineChar)
string = ""
for segment in segments:
string += segment
return string
|
def _dotify ( cls , data ) : return '' . join ( char if char in cls . PRINTABLE_DATA else '.' for char in data )
| 0 |
how to make a character in dot format python
|
Add dots .
|
cosqa-train-16031
|
def _dotify(cls, data):
"""Add dots."""
return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data)
|
def clean ( self , text ) : return '' . join ( [ c for c in text if c in self . alphabet ] )
| 0 |
python remove non english letter
|
Remove all unwanted characters from text .
|
cosqa-train-16032
|
def clean(self, text):
"""Remove all unwanted characters from text."""
return ''.join([c for c in text if c in self.alphabet])
|
def PyplotHistogram ( ) : import numpy as np import matplotlib . pyplot as plt np . random . seed ( 0 ) n_bins = 10 x = np . random . randn ( 1000 , 3 ) fig , axes = plt . subplots ( nrows = 2 , ncols = 2 ) ax0 , ax1 , ax2 , ax3 = axes . flatten ( ) colors = [ 'red' , 'tan' , 'lime' ] ax0 . hist ( x , n_bins , normed = 1 , histtype = 'bar' , color = colors , label = colors ) ax0 . legend ( prop = { 'size' : 10 } ) ax0 . set_title ( 'bars with legend' ) ax1 . hist ( x , n_bins , normed = 1 , histtype = 'bar' , stacked = True ) ax1 . set_title ( 'stacked bar' ) ax2 . hist ( x , n_bins , histtype = 'step' , stacked = True , fill = False ) ax2 . set_title ( 'stack step (unfilled)' ) # Make a multiple-histogram of data-sets with different length. x_multi = [ np . random . randn ( n ) for n in [ 10000 , 5000 , 2000 ] ] ax3 . hist ( x_multi , n_bins , histtype = 'bar' ) ax3 . set_title ( 'different sample sizes' ) fig . tight_layout ( ) return fig
| 0 |
how to make a histogram in python multiple datasets
|
============================================================= Demo of the histogram ( hist ) function with multiple data sets =============================================================
|
cosqa-train-16033
|
def PyplotHistogram():
"""
=============================================================
Demo of the histogram (hist) function with multiple data sets
=============================================================
Plot histogram with multiple sample sets and demonstrate:
* Use of legend with multiple sample sets
* Stacked bars
* Step curve with no fill
* Data sets of different sample sizes
Selecting different bin counts and sizes can significantly affect the
shape of a histogram. The Astropy docs have a great section on how to
select these parameters:
http://docs.astropy.org/en/stable/visualization/histogram.html
"""
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
n_bins = 10
x = np.random.randn(1000, 3)
fig, axes = plt.subplots(nrows=2, ncols=2)
ax0, ax1, ax2, ax3 = axes.flatten()
colors = ['red', 'tan', 'lime']
ax0.hist(x, n_bins, normed=1, histtype='bar', color=colors, label=colors)
ax0.legend(prop={'size': 10})
ax0.set_title('bars with legend')
ax1.hist(x, n_bins, normed=1, histtype='bar', stacked=True)
ax1.set_title('stacked bar')
ax2.hist(x, n_bins, histtype='step', stacked=True, fill=False)
ax2.set_title('stack step (unfilled)')
# Make a multiple-histogram of data-sets with different length.
x_multi = [np.random.randn(n) for n in [10000, 5000, 2000]]
ax3.hist(x_multi, n_bins, histtype='bar')
ax3.set_title('different sample sizes')
fig.tight_layout()
return fig
|
def normalize_value ( text ) : result = text . replace ( '\n' , ' ' ) result = re . subn ( '[ ]{2,}' , ' ' , result ) [ 0 ] return result
| 1 |
python remove space multiple
|
This removes newlines and multiple spaces from a string .
|
cosqa-train-16034
|
def normalize_value(text):
"""
This removes newlines and multiple spaces from a string.
"""
result = text.replace('\n', ' ')
result = re.subn('[ ]{2,}', ' ', result)[0]
return result
|
def _heappush_max ( heap , item ) : heap . append ( item ) heapq . _siftdown_max ( heap , 0 , len ( heap ) - 1 )
| 0 |
how to make a max heap in python heapq
|
why is this not in heapq
|
cosqa-train-16035
|
def _heappush_max(heap, item):
""" why is this not in heapq """
heap.append(item)
heapq._siftdown_max(heap, 0, len(heap) - 1)
|
def _remove_keywords ( d ) : return { k : v for k , v in iteritems ( d ) if k not in RESERVED }
| 0 |
python remove stopwords from a dictionary
|
copy the dict filter_keywords
|
cosqa-train-16036
|
def _remove_keywords(d):
"""
copy the dict, filter_keywords
Parameters
----------
d : dict
"""
return { k:v for k, v in iteritems(d) if k not in RESERVED }
|
def clean ( s ) : lines = [ l . rstrip ( ) for l in s . split ( '\n' ) ] return '\n' . join ( lines )
| 1 |
python remove whitespace line
|
Removes trailing whitespace on each line .
|
cosqa-train-16037
|
def clean(s):
"""Removes trailing whitespace on each line."""
lines = [l.rstrip() for l in s.split('\n')]
return '\n'.join(lines)
|
def __grid_widgets ( self ) : scrollbar_column = 0 if self . __compound is tk . LEFT else 2 self . _canvas . grid ( row = 0 , column = 1 , sticky = "nswe" ) self . _scrollbar . grid ( row = 0 , column = scrollbar_column , sticky = "ns" )
| 0 |
how to make a scrollbar in python tkinter
|
Places all the child widgets in the appropriate positions .
|
cosqa-train-16038
|
def __grid_widgets(self):
"""Places all the child widgets in the appropriate positions."""
scrollbar_column = 0 if self.__compound is tk.LEFT else 2
self._canvas.grid(row=0, column=1, sticky="nswe")
self._scrollbar.grid(row=0, column=scrollbar_column, sticky="ns")
|
def unescape ( str ) : out = '' prev_backslash = False for char in str : if not prev_backslash and char == '\\' : prev_backslash = True continue out += char prev_backslash = False return out
| 0 |
python repalce all backslash characters
|
Undoes the effects of the escape () function .
|
cosqa-train-16039
|
def unescape(str):
"""Undoes the effects of the escape() function."""
out = ''
prev_backslash = False
for char in str:
if not prev_backslash and char == '\\':
prev_backslash = True
continue
out += char
prev_backslash = False
return out
|
def us2mc ( string ) : return re . sub ( r'_([a-z])' , lambda m : ( m . group ( 1 ) . upper ( ) ) , string )
| 1 |
how to make a sentence into underscores with python
|
Transform an underscore_case string to a mixedCase string
|
cosqa-train-16040
|
def us2mc(string):
"""Transform an underscore_case string to a mixedCase string"""
return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), string)
|
def retry_call ( func , cleanup = lambda : None , retries = 0 , trap = ( ) ) : attempts = count ( ) if retries == float ( 'inf' ) else range ( retries ) for attempt in attempts : try : return func ( ) except trap : cleanup ( ) return func ( )
| 1 |
python repeat try catch block
|
Given a callable func trap the indicated exceptions for up to retries times invoking cleanup on the exception . On the final attempt allow any exceptions to propagate .
|
cosqa-train-16041
|
def retry_call(func, cleanup=lambda: None, retries=0, trap=()):
"""
Given a callable func, trap the indicated exceptions
for up to 'retries' times, invoking cleanup on the
exception. On the final attempt, allow any exceptions
to propagate.
"""
attempts = count() if retries == float('inf') else range(retries)
for attempt in attempts:
try:
return func()
except trap:
cleanup()
return func()
|
def to_camel ( s ) : # r'(?!^)_([a-zA-Z]) original regex wasn't process first groups return re . sub ( r'_([a-zA-Z])' , lambda m : m . group ( 1 ) . upper ( ) , '_' + s )
| 1 |
how to make a str all lowercasein python
|
: param string s : under_scored string to be CamelCased : return : CamelCase version of input : rtype : str
|
cosqa-train-16042
|
def to_camel(s):
"""
:param string s: under_scored string to be CamelCased
:return: CamelCase version of input
:rtype: str
"""
# r'(?!^)_([a-zA-Z]) original regex wasn't process first groups
return re.sub(r'_([a-zA-Z])', lambda m: m.group(1).upper(), '_' + s)
|
def replace_all ( filepath , searchExp , replaceExp ) : for line in fileinput . input ( filepath , inplace = 1 ) : if searchExp in line : line = line . replace ( searchExp , replaceExp ) sys . stdout . write ( line )
| 1 |
python replace keyword in input file
|
Replace all the ocurrences ( in a file ) of a string with another value .
|
cosqa-train-16043
|
def replace_all(filepath, searchExp, replaceExp):
"""
Replace all the ocurrences (in a file) of a string with another value.
"""
for line in fileinput.input(filepath, inplace=1):
if searchExp in line:
line = line.replace(searchExp, replaceExp)
sys.stdout.write(line)
|
def str2int ( num , radix = 10 , alphabet = BASE85 ) : return NumConv ( radix , alphabet ) . str2int ( num )
| 1 |
how to make a str an int python
|
helper function for quick base conversions from strings to integers
|
cosqa-train-16044
|
def str2int(num, radix=10, alphabet=BASE85):
"""helper function for quick base conversions from strings to integers"""
return NumConv(radix, alphabet).str2int(num)
|
def _sub_patterns ( patterns , text ) : for pattern , repl in patterns : text = re . sub ( pattern , repl , text ) return text
| 1 |
python replace multiple occurancew of text
|
Apply re . sub to bunch of ( pattern repl )
|
cosqa-train-16045
|
def _sub_patterns(patterns, text):
"""
Apply re.sub to bunch of (pattern, repl)
"""
for pattern, repl in patterns:
text = re.sub(pattern, repl, text)
return text
|
def string_to_identity ( identity_str ) : m = _identity_regexp . match ( identity_str ) result = m . groupdict ( ) log . debug ( 'parsed identity: %s' , result ) return { k : v for k , v in result . items ( ) if v }
| 1 |
how to make a string into a dictionary in python
|
Parse string into Identity dictionary .
|
cosqa-train-16046
|
def string_to_identity(identity_str):
"""Parse string into Identity dictionary."""
m = _identity_regexp.match(identity_str)
result = m.groupdict()
log.debug('parsed identity: %s', result)
return {k: v for k, v in result.items() if v}
|
def _replace_nan ( a , val ) : mask = isnull ( a ) return where_method ( val , mask , a ) , mask
| 0 |
python replace nan with missing value
|
replace nan in a by val and returns the replaced array and the nan position
|
cosqa-train-16047
|
def _replace_nan(a, val):
"""
replace nan in a by val, and returns the replaced array and the nan
position
"""
mask = isnull(a)
return where_method(val, mask, a), mask
|
def adapter ( data , headers , * * kwargs ) : keys = ( 'sep_title' , 'sep_character' , 'sep_length' ) return vertical_table ( data , headers , * * filter_dict_by_key ( kwargs , keys ) )
| 0 |
how to make a table in python with given columns
|
Wrap vertical table in a function for TabularOutputFormatter .
|
cosqa-train-16048
|
def adapter(data, headers, **kwargs):
"""Wrap vertical table in a function for TabularOutputFormatter."""
keys = ('sep_title', 'sep_character', 'sep_length')
return vertical_table(data, headers, **filter_dict_by_key(kwargs, keys))
|
async def sysinfo ( dev : Device ) : click . echo ( await dev . get_system_info ( ) ) click . echo ( await dev . get_interface_information ( ) )
| 1 |
python request information from usb
|
Print out system information ( version MAC addrs ) .
|
cosqa-train-16049
|
async def sysinfo(dev: Device):
"""Print out system information (version, MAC addrs)."""
click.echo(await dev.get_system_info())
click.echo(await dev.get_interface_information())
|
def _arrayFromBytes ( dataBytes , metadata ) : array = numpy . fromstring ( dataBytes , dtype = numpy . typeDict [ metadata [ 'dtype' ] ] ) if 'shape' in metadata : array = array . reshape ( metadata [ 'shape' ] ) return array
| 0 |
how to make arraybuffer from bytes in python
|
Generates and returns a numpy array from raw data bytes .
|
cosqa-train-16050
|
def _arrayFromBytes(dataBytes, metadata):
"""Generates and returns a numpy array from raw data bytes.
:param bytes: raw data bytes as generated by ``numpy.ndarray.tobytes()``
:param metadata: a dictionary containing the data type and optionally the
shape parameter to reconstruct a ``numpy.array`` from the raw data
bytes. ``{"dtype": "float64", "shape": (2, 3)}``
:returns: ``numpy.array``
"""
array = numpy.fromstring(dataBytes, dtype=numpy.typeDict[metadata['dtype']])
if 'shape' in metadata:
array = array.reshape(metadata['shape'])
return array
|
def dir_exists ( self ) : r = requests . request ( self . method if self . method else 'HEAD' , self . url , * * self . storage_args ) try : r . raise_for_status ( ) except Exception : return False return True
| 1 |
python requests check if url exists
|
Makes a HEAD requests to the URI .
|
cosqa-train-16051
|
def dir_exists(self):
"""
Makes a ``HEAD`` requests to the URI.
:returns: ``True`` if status code is 2xx.
"""
r = requests.request(self.method if self.method else 'HEAD', self.url, **self.storage_args)
try: r.raise_for_status()
except Exception: return False
return True
|
def csv_matrix_print ( classes , table ) : result = "" classes . sort ( ) for i in classes : for j in classes : result += str ( table [ i ] [ j ] ) + "," result = result [ : - 1 ] + "\n" return result [ : - 1 ]
| 0 |
how to make csv as table in python
|
Return matrix as csv data .
|
cosqa-train-16052
|
def csv_matrix_print(classes, table):
"""
Return matrix as csv data.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return:
"""
result = ""
classes.sort()
for i in classes:
for j in classes:
result += str(table[i][j]) + ","
result = result[:-1] + "\n"
return result[:-1]
|
def disable_insecure_request_warning ( ) : import requests from requests . packages . urllib3 . exceptions import InsecureRequestWarning requests . packages . urllib3 . disable_warnings ( InsecureRequestWarning )
| 0 |
python requests disable ssl checks
|
Suppress warning about untrusted SSL certificate .
|
cosqa-train-16053
|
def disable_insecure_request_warning():
"""Suppress warning about untrusted SSL certificate."""
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
|
def getFunction ( self ) : return functionFactory ( self . code , self . name , self . defaults , self . globals , self . imports , )
| 0 |
how to make functions static in python
|
Called by remote workers . Useful to populate main module globals () for interactive shells . Retrieves the serialized function .
|
cosqa-train-16054
|
def getFunction(self):
"""Called by remote workers. Useful to populate main module globals()
for interactive shells. Retrieves the serialized function."""
return functionFactory(
self.code,
self.name,
self.defaults,
self.globals,
self.imports,
)
|
def make_post_request ( self , url , auth , json_payload ) : response = requests . post ( url , auth = auth , json = json_payload ) return response . json ( )
| 1 |
python requests passing json payload
|
This function executes the request with the provided json payload and return the json response
|
cosqa-train-16055
|
def make_post_request(self, url, auth, json_payload):
"""This function executes the request with the provided
json payload and return the json response"""
response = requests.post(url, auth=auth, json=json_payload)
return response.json()
|
def apply ( filter ) : def decorator ( callable ) : return lambda * args , * * kwargs : filter ( callable ( * args , * * kwargs ) ) return decorator
| 1 |
how to make functions that returns a function python
|
Manufacture decorator that filters return value with given function .
|
cosqa-train-16056
|
def apply(filter):
"""Manufacture decorator that filters return value with given function.
``filter``:
Callable that takes a single parameter.
"""
def decorator(callable):
return lambda *args, **kwargs: filter(callable(*args, **kwargs))
return decorator
|
def login ( self , username , password = None , token = None ) : self . session . basic_auth ( username , password )
| 0 |
python requests session auth basic access
|
Login user for protected API calls .
|
cosqa-train-16057
|
def login(self, username, password=None, token=None):
"""Login user for protected API calls."""
self.session.basic_auth(username, password)
|
def scale_image ( image , new_width ) : ( original_width , original_height ) = image . size aspect_ratio = original_height / float ( original_width ) new_height = int ( aspect_ratio * new_width ) # This scales it wider than tall, since characters are biased new_image = image . resize ( ( new_width * 2 , new_height ) ) return new_image
| 1 |
how to make image height and width equal in python
|
Resizes an image preserving the aspect ratio .
|
cosqa-train-16058
|
def scale_image(image, new_width):
"""Resizes an image preserving the aspect ratio.
"""
(original_width, original_height) = image.size
aspect_ratio = original_height/float(original_width)
new_height = int(aspect_ratio * new_width)
# This scales it wider than tall, since characters are biased
new_image = image.resize((new_width*2, new_height))
return new_image
|
def requests_request ( method , url , * * kwargs ) : session = local_sessions . session response = session . request ( method = method , url = url , * * kwargs ) session . close ( ) return response
| 1 |
python requests session mount
|
Requests - mock requests . request wrapper .
|
cosqa-train-16059
|
def requests_request(method, url, **kwargs):
"""Requests-mock requests.request wrapper."""
session = local_sessions.session
response = session.request(method=method, url=url, **kwargs)
session.close()
return response
|
def to_camel ( s ) : # r'(?!^)_([a-zA-Z]) original regex wasn't process first groups return re . sub ( r'_([a-zA-Z])' , lambda m : m . group ( 1 ) . upper ( ) , '_' + s )
| 0 |
how to make parts of word lowercase in python
|
: param string s : under_scored string to be CamelCased : return : CamelCase version of input : rtype : str
|
cosqa-train-16060
|
def to_camel(s):
"""
:param string s: under_scored string to be CamelCased
:return: CamelCase version of input
:rtype: str
"""
# r'(?!^)_([a-zA-Z]) original regex wasn't process first groups
return re.sub(r'_([a-zA-Z])', lambda m: m.group(1).upper(), '_' + s)
|
def reset_params ( self ) : self . __params = dict ( [ p , None ] for p in self . param_names ) self . set_params ( self . param_defaults )
| 0 |
python reset all variables to initial values
|
Reset all parameters to their default values .
|
cosqa-train-16061
|
def reset_params(self):
"""Reset all parameters to their default values."""
self.__params = dict([p, None] for p in self.param_names)
self.set_params(self.param_defaults)
|
def make_post_request ( self , url , auth , json_payload ) : response = requests . post ( url , auth = auth , json = json_payload ) return response . json ( )
| 0 |
how to make post requst in python
|
This function executes the request with the provided json payload and return the json response
|
cosqa-train-16062
|
def make_post_request(self, url, auth, json_payload):
"""This function executes the request with the provided
json payload and return the json response"""
response = requests.post(url, auth=auth, json=json_payload)
return response.json()
|
def arr_to_vector ( arr ) : dim = array_dim ( arr ) tmp_arr = [ ] for n in range ( len ( dim ) - 1 ) : for inner in arr : for i in inner : tmp_arr . append ( i ) arr = tmp_arr tmp_arr = [ ] return arr
| 0 |
python reshape array into single array
|
Reshape a multidimensional array to a vector .
|
cosqa-train-16063
|
def arr_to_vector(arr):
"""Reshape a multidimensional array to a vector.
"""
dim = array_dim(arr)
tmp_arr = []
for n in range(len(dim) - 1):
for inner in arr:
for i in inner:
tmp_arr.append(i)
arr = tmp_arr
tmp_arr = []
return arr
|
def _digits ( minval , maxval ) : if minval == maxval : return 3 else : return min ( 10 , max ( 2 , int ( 1 + abs ( np . log10 ( maxval - minval ) ) ) ) )
| 1 |
how to make python display maximum and minimum number
|
Digits needed to comforatbly display values in [ minval maxval ]
|
cosqa-train-16064
|
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 sf01 ( arr ) : s = arr . shape return arr . swapaxes ( 0 , 1 ) . reshape ( s [ 0 ] * s [ 1 ] , * s [ 2 : ] )
| 0 |
python reshape multiple columns
|
swap and then flatten axes 0 and 1
|
cosqa-train-16065
|
def sf01(arr):
"""
swap and then flatten axes 0 and 1
"""
s = arr.shape
return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])
|
def positive_integer ( anon , obj , field , val ) : return anon . faker . positive_integer ( field = field )
| 1 |
how to make python give out a random integer
|
Returns a random positive integer ( for a Django PositiveIntegerField )
|
cosqa-train-16066
|
def positive_integer(anon, obj, field, val):
"""
Returns a random positive integer (for a Django PositiveIntegerField)
"""
return anon.faker.positive_integer(field=field)
|
def get_func_name ( func ) : func_name = getattr ( func , '__name__' , func . __class__ . __name__ ) module_name = func . __module__ if module_name is not None : module_name = func . __module__ return '{}.{}' . format ( module_name , func_name ) return func_name
| 1 |
python retrieve func name
|
Return a name which includes the module name and function name .
|
cosqa-train-16067
|
def get_func_name(func):
"""Return a name which includes the module name and function name."""
func_name = getattr(func, '__name__', func.__class__.__name__)
module_name = func.__module__
if module_name is not None:
module_name = func.__module__
return '{}.{}'.format(module_name, func_name)
return func_name
|
def fix_call ( callable , * args , * * kw ) : try : val = callable ( * args , * * kw ) except TypeError : exc_info = fix_type_error ( None , callable , args , kw ) reraise ( * exc_info ) return val
| 1 |
how to make raise custom errors in python
|
Call callable ( * args ** kw ) fixing any type errors that come out .
|
cosqa-train-16068
|
def fix_call(callable, *args, **kw):
"""
Call ``callable(*args, **kw)`` fixing any type errors that come out.
"""
try:
val = callable(*args, **kw)
except TypeError:
exc_info = fix_type_error(None, callable, args, kw)
reraise(*exc_info)
return val
|
def distinct ( l ) : seen = set ( ) seen_add = seen . add return ( _ for _ in l if not ( _ in seen or seen_add ( _ ) ) )
| 0 |
python return a list with one item removed
|
Return a list where the duplicates have been removed .
|
cosqa-train-16069
|
def distinct(l):
"""
Return a list where the duplicates have been removed.
Args:
l (list): the list to filter.
Returns:
list: the same list without duplicates.
"""
seen = set()
seen_add = seen.add
return (_ for _ in l if not (_ in seen or seen_add(_)))
|
def print_result_from_timeit ( stmt = 'pass' , setup = 'pass' , number = 1000000 ) : units = [ "s" , "ms" , "us" , "ns" ] duration = timeit ( stmt , setup , number = int ( number ) ) avg_duration = duration / float ( number ) thousands = int ( math . floor ( math . log ( avg_duration , 1000 ) ) ) print ( "Total time: %fs. Average run: %.3f%s." % ( duration , avg_duration * ( 1000 ** - thousands ) , units [ - thousands ] ) )
| 0 |
how to measure the execute time in python
|
Clean function to know how much time took the execution of one statement
|
cosqa-train-16070
|
def print_result_from_timeit(stmt='pass', setup='pass', number=1000000):
"""
Clean function to know how much time took the execution of one statement
"""
units = ["s", "ms", "us", "ns"]
duration = timeit(stmt, setup, number=int(number))
avg_duration = duration / float(number)
thousands = int(math.floor(math.log(avg_duration, 1000)))
print("Total time: %fs. Average run: %.3f%s." % (
duration, avg_duration * (1000 ** -thousands), units[-thousands]))
|
def _find ( string , sub_string , start_index ) : result = string . find ( sub_string , start_index ) if result == - 1 : raise TokenError ( "expected '{0}'" . format ( sub_string ) ) return result
| 1 |
python return location of substring
|
Return index of sub_string in string .
|
cosqa-train-16071
|
def _find(string, sub_string, start_index):
"""Return index of sub_string in string.
Raise TokenError if sub_string is not found.
"""
result = string.find(sub_string, start_index)
if result == -1:
raise TokenError("expected '{0}'".format(sub_string))
return result
|
def _show ( self , message , indent = 0 , enable_verbose = True ) : # pragma: no cover if enable_verbose : print ( " " * indent + message )
| 1 |
how to modify print function in python
|
Message printer .
|
cosqa-train-16072
|
def _show(self, message, indent=0, enable_verbose=True): # pragma: no cover
"""Message printer.
"""
if enable_verbose:
print(" " * indent + message)
|
def return_letters_from_string ( text ) : out = "" for letter in text : if letter . isalpha ( ) : out += letter return out
| 1 |
python return only letters from string
|
Get letters from string only .
|
cosqa-train-16073
|
def return_letters_from_string(text):
"""Get letters from string only."""
out = ""
for letter in text:
if letter.isalpha():
out += letter
return out
|
def move_back ( self , dt ) : self . _position = self . _old_position self . rect . topleft = self . _position self . feet . midbottom = self . rect . midbottom
| 1 |
how to move a sprite in python 3
|
If called after an update the sprite can move back
|
cosqa-train-16074
|
def move_back(self, dt):
""" If called after an update, the sprite can move back
"""
self._position = self._old_position
self.rect.topleft = self._position
self.feet.midbottom = self.rect.midbottom
|
def binSearch ( arr , val ) : i = bisect_left ( arr , val ) if i != len ( arr ) and arr [ i ] == val : return i return - 1
| 0 |
python return the index of an element in a list
|
Function for running binary search on a sorted list .
|
cosqa-train-16075
|
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 list_move_to_front ( l , value = 'other' ) : l = list ( l ) if value in l : l . remove ( value ) l . insert ( 0 , value ) return l
| 0 |
how to move an item in a list to front python
|
if the value is in the list move it to the front and return it .
|
cosqa-train-16076
|
def list_move_to_front(l,value='other'):
"""if the value is in the list, move it to the front and return it."""
l=list(l)
if value in l:
l.remove(value)
l.insert(0,value)
return l
|
def find_nearest_index ( arr , value ) : arr = np . array ( arr ) index = ( abs ( arr - value ) ) . argmin ( ) return index
| 0 |
python return the index of the minimum value in an numpy array
|
For a given value the function finds the nearest value in the array and returns its index .
|
cosqa-train-16077
|
def find_nearest_index(arr, value):
"""For a given value, the function finds the nearest value
in the array and returns its index."""
arr = np.array(arr)
index = (abs(arr-value)).argmin()
return index
|
def closest ( xarr , val ) : idx_closest = np . argmin ( np . abs ( np . array ( xarr ) - val ) ) return idx_closest
| 0 |
python return the two closest numbers to a value in an array
|
Return the index of the closest in xarr to value val
|
cosqa-train-16078
|
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 v_normalize ( v ) : vmag = v_magnitude ( v ) return [ v [ i ] / vmag for i in range ( len ( v ) ) ]
| 0 |
how to normalise a matrix in python'
|
Normalizes the given vector . The vector given may have any number of dimensions .
|
cosqa-train-16079
|
def v_normalize(v):
"""
Normalizes the given vector.
The vector given may have any number of dimensions.
"""
vmag = v_magnitude(v)
return [ v[i]/vmag for i in range(len(v)) ]
|
def invertDictMapping ( d ) : inv_map = { } for k , v in d . items ( ) : inv_map [ v ] = inv_map . get ( v , [ ] ) inv_map [ v ] . append ( k ) return inv_map
| 1 |
python reverse map dict
|
Invert mapping of dictionary ( i . e . map values to list of keys )
|
cosqa-train-16080
|
def invertDictMapping(d):
""" Invert mapping of dictionary (i.e. map values to list of keys) """
inv_map = {}
for k, v in d.items():
inv_map[v] = inv_map.get(v, [])
inv_map[v].append(k)
return inv_map
|
def load ( filename ) : path , name = os . path . split ( filename ) path = path or '.' with util . indir ( path ) : return pickle . load ( open ( name , 'rb' ) )
| 0 |
how to open a pkl file in python
|
Load the state from the given file moving to the file s directory during load ( temporarily moving back after loaded )
|
cosqa-train-16081
|
def load(filename):
"""
Load the state from the given file, moving to the file's directory during
load (temporarily, moving back after loaded)
Parameters
----------
filename : string
name of the file to open, should be a .pkl file
"""
path, name = os.path.split(filename)
path = path or '.'
with util.indir(path):
return pickle.load(open(name, 'rb'))
|
def rotation_matrix ( sigma ) : radians = sigma * np . pi / 180.0 r11 = np . cos ( radians ) r12 = - np . sin ( radians ) r21 = np . sin ( radians ) r22 = np . cos ( radians ) R = np . array ( [ [ r11 , r12 ] , [ r21 , r22 ] ] ) return R
| 0 |
python rotation matrix 2 euler
|
cosqa-train-16082
|
def rotation_matrix(sigma):
"""
https://en.wikipedia.org/wiki/Rotation_matrix
"""
radians = sigma * np.pi / 180.0
r11 = np.cos(radians)
r12 = -np.sin(radians)
r21 = np.sin(radians)
r22 = np.cos(radians)
R = np.array([[r11, r12], [r21, r22]])
return R
|
|
def readme ( filename , encoding = 'utf8' ) : with io . open ( filename , encoding = encoding ) as source : return source . read ( )
| 0 |
how to open file only as ascii in python
|
Read the contents of a file
|
cosqa-train-16083
|
def readme(filename, encoding='utf8'):
"""
Read the contents of a file
"""
with io.open(filename, encoding=encoding) as source:
return source.read()
|
def _saferound ( value , decimal_places ) : try : f = float ( value ) except ValueError : return '' format = '%%.%df' % decimal_places return format % f
| 1 |
python round not showing correct number of decimal places
|
Rounds a float value off to the desired precision
|
cosqa-train-16084
|
def _saferound(value, decimal_places):
"""
Rounds a float value off to the desired precision
"""
try:
f = float(value)
except ValueError:
return ''
format = '%%.%df' % decimal_places
return format % f
|
def bin_open ( fname : str ) : if fname . endswith ( ".gz" ) : return gzip . open ( fname , "rb" ) return open ( fname , "rb" )
| 0 |
how to open gz files in python
|
Returns a file descriptor for a plain text or gzipped file binary read mode for subprocess interaction .
|
cosqa-train-16085
|
def bin_open(fname: str):
"""
Returns a file descriptor for a plain text or gzipped file, binary read mode
for subprocess interaction.
:param fname: The filename to open.
:return: File descriptor in binary read mode.
"""
if fname.endswith(".gz"):
return gzip.open(fname, "rb")
return open(fname, "rb")
|
def round_array ( array_in ) : if isinstance ( array_in , ndarray ) : return np . round ( array_in ) . astype ( int ) else : return int ( np . round ( array_in ) )
| 1 |
python round number ndarray
|
arr_out = round_array ( array_in )
|
cosqa-train-16086
|
def round_array(array_in):
"""
arr_out = round_array(array_in)
Rounds an array and recasts it to int. Also works on scalars.
"""
if isinstance(array_in, ndarray):
return np.round(array_in).astype(int)
else:
return int(np.round(array_in))
|
def jsonify ( symbol ) : try : # all symbols have a toJson method, try it return json . dumps ( symbol . toJson ( ) , indent = ' ' ) except AttributeError : pass return json . dumps ( symbol , indent = ' ' )
| 0 |
how to output symbols in python
|
returns json format for symbol
|
cosqa-train-16087
|
def jsonify(symbol):
""" returns json format for symbol """
try:
# all symbols have a toJson method, try it
return json.dumps(symbol.toJson(), indent=' ')
except AttributeError:
pass
return json.dumps(symbol, indent=' ')
|
def round_array ( array_in ) : if isinstance ( array_in , ndarray ) : return np . round ( array_in ) . astype ( int ) else : return int ( np . round ( array_in ) )
| 1 |
python round to int numpy
|
arr_out = round_array ( array_in )
|
cosqa-train-16088
|
def round_array(array_in):
"""
arr_out = round_array(array_in)
Rounds an array and recasts it to int. Also works on scalars.
"""
if isinstance(array_in, ndarray):
return np.round(array_in).astype(int)
else:
return int(np.round(array_in))
|
def _visual_width ( line ) : return len ( re . sub ( colorama . ansitowin32 . AnsiToWin32 . ANSI_CSI_RE , "" , line ) )
| 1 |
how to output the number of characters in something in python
|
Get the the number of columns required to display a string
|
cosqa-train-16089
|
def _visual_width(line):
"""Get the the number of columns required to display a string"""
return len(re.sub(colorama.ansitowin32.AnsiToWin32.ANSI_CSI_RE, "", line))
|
def price_rounding ( price , decimals = 2 ) : try : exponent = D ( '.' + decimals * '0' ) except InvalidOperation : # Currencies with no decimal places, ex. JPY, HUF exponent = D ( ) return price . quantize ( exponent , rounding = ROUND_UP )
| 1 |
python rounding decimals places
|
Takes a decimal price and rounds to a number of decimal places
|
cosqa-train-16090
|
def price_rounding(price, decimals=2):
"""Takes a decimal price and rounds to a number of decimal places"""
try:
exponent = D('.' + decimals * '0')
except InvalidOperation:
# Currencies with no decimal places, ex. JPY, HUF
exponent = D()
return price.quantize(exponent, rounding=ROUND_UP)
|
def copy_image_on_background ( image , color = WHITE ) : background = Image . new ( "RGB" , image . size , color ) background . paste ( image , mask = image . split ( ) [ 3 ] ) return background
| 0 |
how to overlay an image on a background in python
|
Create a new image by copying the image on a * color * background .
|
cosqa-train-16091
|
def copy_image_on_background(image, color=WHITE):
"""
Create a new image by copying the image on a *color* background.
Args:
image (PIL.Image.Image): Image to copy
color (tuple): Background color usually WHITE or BLACK
Returns:
PIL.Image.Image
"""
background = Image.new("RGB", image.size, color)
background.paste(image, mask=image.split()[3])
return background
|
def sf01 ( arr ) : s = arr . shape return arr . swapaxes ( 0 , 1 ) . reshape ( s [ 0 ] * s [ 1 ] , * s [ 2 : ] )
| 0 |
python rows to columns but not transpose
|
swap and then flatten axes 0 and 1
|
cosqa-train-16092
|
def sf01(arr):
"""
swap and then flatten axes 0 and 1
"""
s = arr.shape
return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])
|
def pstd ( self , * args , * * kwargs ) : kwargs [ 'file' ] = self . out self . print ( * args , * * kwargs ) sys . stdout . flush ( )
| 0 |
how to overwrite print function python
|
Console to STDOUT
|
cosqa-train-16093
|
def pstd(self, *args, **kwargs):
""" Console to STDOUT """
kwargs['file'] = self.out
self.print(*args, **kwargs)
sys.stdout.flush()
|
def remove_file_from_s3 ( awsclient , bucket , key ) : client_s3 = awsclient . get_client ( 's3' ) response = client_s3 . delete_object ( Bucket = bucket , Key = key )
| 0 |
python s3 remove bucket policy
|
Remove a file from an AWS S3 bucket .
|
cosqa-train-16094
|
def remove_file_from_s3(awsclient, bucket, key):
"""Remove a file from an AWS S3 bucket.
:param awsclient:
:param bucket:
:param key:
:return:
"""
client_s3 = awsclient.get_client('s3')
response = client_s3.delete_object(Bucket=bucket, Key=key)
|
def __call__ ( self , img ) : return F . pad ( img , self . padding , self . fill , self . padding_mode )
| 0 |
how to pad an image in python
|
Args : img ( PIL Image ) : Image to be padded .
|
cosqa-train-16095
|
def __call__(self, img):
"""
Args:
img (PIL Image): Image to be padded.
Returns:
PIL Image: Padded image.
"""
return F.pad(img, self.padding, self.fill, self.padding_mode)
|
def get_as_string ( self , s3_path , encoding = 'utf-8' ) : content = self . get_as_bytes ( s3_path ) return content . decode ( encoding )
| 1 |
python s3 save string
|
Get the contents of an object stored in S3 as string .
|
cosqa-train-16096
|
def get_as_string(self, s3_path, encoding='utf-8'):
"""
Get the contents of an object stored in S3 as string.
:param s3_path: URL for target S3 location
:param encoding: Encoding to decode bytes to string
:return: File contents as a string
"""
content = self.get_as_bytes(s3_path)
return content.decode(encoding)
|
def trigger ( self , target : str , trigger : str , parameters : Dict [ str , Any ] = { } ) : pass
| 1 |
how to pass the variables between functions in python with multiple args
|
Calls the specified Trigger of another Area with the optionally given parameters .
|
cosqa-train-16097
|
def trigger(self, target: str, trigger: str, parameters: Dict[str, Any]={}):
"""Calls the specified Trigger of another Area with the optionally given parameters.
Args:
target: The name of the target Area.
trigger: The name of the Trigger.
parameters: The parameters of the function call.
"""
pass
|
def base64ToImage ( imgData , out_path , out_file ) : fh = open ( os . path . join ( out_path , out_file ) , "wb" ) fh . write ( imgData . decode ( 'base64' ) ) fh . close ( ) del fh return os . path . join ( out_path , out_file )
| 0 |
python save base64 string to image
|
converts a base64 string to a file
|
cosqa-train-16098
|
def base64ToImage(imgData, out_path, out_file):
""" converts a base64 string to a file """
fh = open(os.path.join(out_path, out_file), "wb")
fh.write(imgData.decode('base64'))
fh.close()
del fh
return os.path.join(out_path, out_file)
|
def strip_figures ( figure ) : fig = [ ] for trace in figure [ 'data' ] : fig . append ( dict ( data = [ trace ] , layout = figure [ 'layout' ] ) ) return fig
| 0 |
how to plot various charts on a single figure python
|
Strips a figure into multiple figures with a trace on each of them
|
cosqa-train-16099
|
def strip_figures(figure):
"""
Strips a figure into multiple figures with a trace on each of them
Parameters:
-----------
figure : Figure
Plotly Figure
"""
fig=[]
for trace in figure['data']:
fig.append(dict(data=[trace],layout=figure['layout']))
return fig
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.