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 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 |
how to fit a gaussian in python
|
Fit a Gaussian to the data
|
cosqa-train-13700
|
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 truncate ( self , table ) : if isinstance ( table , ( list , set , tuple ) ) : for t in table : self . _truncate ( t ) else : self . _truncate ( table )
| 1 |
python oracle truncate a table
|
Empty a table by deleting all of its rows .
|
cosqa-train-13701
|
def truncate(self, table):
"""Empty a table by deleting all of its rows."""
if isinstance(table, (list, set, tuple)):
for t in table:
self._truncate(t)
else:
self._truncate(table)
|
def sort_dict ( d , key = None , reverse = False ) : kv_items = [ kv for kv in d . items ( ) ] # Sort kv_items according to key. if key is None : kv_items . sort ( key = lambda t : t [ 1 ] , reverse = reverse ) else : kv_items . sort ( key = key , reverse = reverse ) # Build ordered dict. return collections . OrderedDict ( kv_items )
| 1 |
python order a dictionary alphabetically
|
Sorts a dict by value .
|
cosqa-train-13702
|
def sort_dict(d, key=None, reverse=False):
"""
Sorts a dict by value.
Args:
d: Input dictionary
key: Function which takes an tuple (key, object) and returns a value to
compare and sort by. By default, the function compares the values
of the dict i.e. key = lambda t : t[1]
reverse: Allows to reverse sort order.
Returns:
OrderedDict object whose keys are ordered according to their value.
"""
kv_items = [kv for kv in d.items()]
# Sort kv_items according to key.
if key is None:
kv_items.sort(key=lambda t: t[1], reverse=reverse)
else:
kv_items.sort(key=key, reverse=reverse)
# Build ordered dict.
return collections.OrderedDict(kv_items)
|
def generate_unique_host_id ( ) : host = "." . join ( reversed ( socket . gethostname ( ) . split ( "." ) ) ) pid = os . getpid ( ) return "%s.%d" % ( host , pid )
| 1 |
how to generate a unique id each program run python
|
Generate a unique ID that is somewhat guaranteed to be unique among all instances running at the same time .
|
cosqa-train-13703
|
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 _IsDirectory ( parent , item ) : return tf . io . gfile . isdir ( os . path . join ( parent , item ) )
| 1 |
python os check if an item is a directory
|
Helper that returns if parent / item is a directory .
|
cosqa-train-13704
|
def _IsDirectory(parent, item):
"""Helper that returns if parent/item is a directory."""
return tf.io.gfile.isdir(os.path.join(parent, item))
|
def rgamma ( alpha , beta , size = None ) : return np . random . gamma ( shape = alpha , scale = 1. / beta , size = size )
| 1 |
how to generate random gaussian matrix in python
|
Random gamma variates .
|
cosqa-train-13705
|
def rgamma(alpha, beta, size=None):
"""
Random gamma variates.
"""
return np.random.gamma(shape=alpha, scale=1. / beta, size=size)
|
def normalize_text ( text , line_len = 80 , indent = "" ) : return "\n" . join ( textwrap . wrap ( text , width = line_len , initial_indent = indent , subsequent_indent = indent ) )
| 0 |
python output automatic wrap long line
|
Wrap the text on the given line length .
|
cosqa-train-13706
|
def normalize_text(text, line_len=80, indent=""):
"""Wrap the text on the given line length."""
return "\n".join(
textwrap.wrap(
text, width=line_len, initial_indent=indent, subsequent_indent=indent
)
)
|
def random_numbers ( n ) : return '' . join ( random . SystemRandom ( ) . choice ( string . digits ) for _ in range ( n ) )
| 0 |
how to generate random numbers multiple of 5 in python
|
Generate a random string from 0 - 9 : param n : length of the string : return : the random string
|
cosqa-train-13707
|
def random_numbers(n):
"""
Generate a random string from 0-9
:param n: length of the string
:return: the random string
"""
return ''.join(random.SystemRandom().choice(string.digits) for _ in range(n))
|
def write_config ( self , outfile ) : utils . write_yaml ( self . config , outfile , default_flow_style = False )
| 1 |
python output dictionary as yml
|
Write the configuration dictionary to an output file .
|
cosqa-train-13708
|
def write_config(self, outfile):
"""Write the configuration dictionary to an output file."""
utils.write_yaml(self.config, outfile, default_flow_style=False)
|
def find_one ( cls , * args , * * kw ) : if len ( args ) == 1 and not isinstance ( args [ 0 ] , Filter ) : args = ( getattr ( cls , cls . __pk__ ) == args [ 0 ] , ) Doc , collection , query , options = cls . _prepare_find ( * args , * * kw ) result = Doc . from_mongo ( collection . find_one ( query , * * options ) ) return result
| 1 |
how to get a document in a collection using mongoengine api server in python
|
Get a single document from the collection this class is bound to . Additional arguments are processed according to _prepare_find prior to passing to PyMongo where positional parameters are interpreted as query fragments parametric keyword arguments combined and other keyword arguments passed along with minor transformation . Automatically calls to_mongo with the retrieved data . https : // api . mongodb . com / python / current / api / pymongo / collection . html#pymongo . collection . Collection . find_one
|
cosqa-train-13709
|
def find_one(cls, *args, **kw):
"""Get a single document from the collection this class is bound to.
Additional arguments are processed according to `_prepare_find` prior to passing to PyMongo, where positional
parameters are interpreted as query fragments, parametric keyword arguments combined, and other keyword
arguments passed along with minor transformation.
Automatically calls `to_mongo` with the retrieved data.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one
"""
if len(args) == 1 and not isinstance(args[0], Filter):
args = (getattr(cls, cls.__pk__) == args[0], )
Doc, collection, query, options = cls._prepare_find(*args, **kw)
result = Doc.from_mongo(collection.find_one(query, **options))
return result
|
def downsample_with_striding ( array , factor ) : return array [ tuple ( np . s_ [ : : f ] for f in factor ) ]
| 1 |
python oversampling for each column
|
Downsample x by factor using striding .
|
cosqa-train-13710
|
def downsample_with_striding(array, factor):
"""Downsample x by factor using striding.
@return: The downsampled array, of the same type as x.
"""
return array[tuple(np.s_[::f] for f in factor)]
|
def get_mouse_location ( self ) : x = ctypes . c_int ( 0 ) y = ctypes . c_int ( 0 ) screen_num = ctypes . c_int ( 0 ) _libxdo . xdo_get_mouse_location ( self . _xdo , ctypes . byref ( x ) , ctypes . byref ( y ) , ctypes . byref ( screen_num ) ) return mouse_location ( x . value , y . value , screen_num . value )
| 1 |
how to get a mouse position in python
|
Get the current mouse location ( coordinates and screen number ) .
|
cosqa-train-13711
|
def get_mouse_location(self):
"""
Get the current mouse location (coordinates and screen number).
:return: a namedtuple with ``x``, ``y`` and ``screen_num`` fields
"""
x = ctypes.c_int(0)
y = ctypes.c_int(0)
screen_num = ctypes.c_int(0)
_libxdo.xdo_get_mouse_location(
self._xdo, ctypes.byref(x), ctypes.byref(y),
ctypes.byref(screen_num))
return mouse_location(x.value, y.value, screen_num.value)
|
def zero_pad ( m , n = 1 ) : return np . pad ( m , ( n , n ) , mode = 'constant' , constant_values = [ 0 ] )
| 1 |
python pad with front zeros
|
Pad a matrix with zeros on all sides .
|
cosqa-train-13712
|
def zero_pad(m, n=1):
"""Pad a matrix with zeros, on all sides."""
return np.pad(m, (n, n), mode='constant', constant_values=[0])
|
def dates_in_range ( start_date , end_date ) : return [ start_date + timedelta ( n ) for n in range ( int ( ( end_date - start_date ) . days ) ) ]
| 1 |
how to get all dates between two dates in python
|
Returns all dates between two dates .
|
cosqa-train-13713
|
def dates_in_range(start_date, end_date):
"""Returns all dates between two dates.
Inclusive of the start date but not the end date.
Args:
start_date (datetime.date)
end_date (datetime.date)
Returns:
(list) of datetime.date objects
"""
return [
start_date + timedelta(n)
for n in range(int((end_date - start_date).days))
]
|
def strip_spaces ( value , sep = None , join = True ) : value = value . strip ( ) value = [ v . strip ( ) for v in value . split ( sep ) ] join_sep = sep or ' ' return join_sep . join ( value ) if join else value
| 1 |
python panda strip white space in list
|
Cleans trailing whitespaces and replaces also multiple whitespaces with a single space .
|
cosqa-train-13714
|
def strip_spaces(value, sep=None, join=True):
"""Cleans trailing whitespaces and replaces also multiple whitespaces with a single space."""
value = value.strip()
value = [v.strip() for v in value.split(sep)]
join_sep = sep or ' '
return join_sep.join(value) if join else value
|
def __iter__ ( self ) : return iter ( [ v for k , v in sorted ( self . _modes . items ( ) ) ] )
| 1 |
how to get all modes python
|
Returns the list of modes .
|
cosqa-train-13715
|
def __iter__(self):
"""
Returns the list of modes.
:return:
"""
return iter([v for k, v in sorted(self._modes.items())])
|
def calculate_top_margin ( self ) : self . border_top = 5 if self . show_graph_title : self . border_top += self . title_font_size self . border_top += 5 if self . show_graph_subtitle : self . border_top += self . subtitle_font_size
| 1 |
python panda top border
|
Calculate the margin in pixels above the plot area setting border_top .
|
cosqa-train-13716
|
def calculate_top_margin(self):
"""
Calculate the margin in pixels above the plot area, setting
border_top.
"""
self.border_top = 5
if self.show_graph_title:
self.border_top += self.title_font_size
self.border_top += 5
if self.show_graph_subtitle:
self.border_top += self.subtitle_font_size
|
def dict_from_object ( obj : object ) : # If object is a dict instance, no need to convert. return ( obj if isinstance ( obj , dict ) else { attr : getattr ( obj , attr ) for attr in dir ( obj ) if not attr . startswith ( '_' ) } )
| 0 |
how to get all properties of object python
|
Convert a object into dictionary with all of its readable attributes .
|
cosqa-train-13717
|
def dict_from_object(obj: object):
"""Convert a object into dictionary with all of its readable attributes."""
# If object is a dict instance, no need to convert.
return (obj if isinstance(obj, dict)
else {attr: getattr(obj, attr)
for attr in dir(obj) if not attr.startswith('_')})
|
def top_class ( self ) : curr = self parent = self . parent while isinstance ( parent , class_t ) : curr = parent parent = parent . parent return curr
| 1 |
python parent clas name
|
reference to a parent class which contains this class and defined within a namespace
|
cosqa-train-13718
|
def top_class(self):
"""reference to a parent class, which contains this class and defined
within a namespace
if this class is defined under a namespace, self will be returned"""
curr = self
parent = self.parent
while isinstance(parent, class_t):
curr = parent
parent = parent.parent
return curr
|
def go_to_parent_directory ( self ) : self . chdir ( osp . abspath ( osp . join ( getcwd_or_home ( ) , os . pardir ) ) )
| 1 |
how to get back to parent directory python
|
Go to parent directory
|
cosqa-train-13719
|
def go_to_parent_directory(self):
"""Go to parent directory"""
self.chdir(osp.abspath(osp.join(getcwd_or_home(), os.pardir)))
|
def find_root ( self ) : cmd = self while cmd . parent : cmd = cmd . parent return cmd
| 1 |
python parent of an object
|
Traverse parent refs to top .
|
cosqa-train-13720
|
def find_root(self):
""" Traverse parent refs to top. """
cmd = self
while cmd.parent:
cmd = cmd.parent
return cmd
|
def bytes_to_c_array ( data ) : chars = [ "'{}'" . format ( encode_escape ( i ) ) for i in decode_escape ( data ) ] return ', ' . join ( chars ) + ', 0'
| 1 |
how to get char array from c to python
|
Make a C array using the given string .
|
cosqa-train-13721
|
def bytes_to_c_array(data):
"""
Make a C array using the given string.
"""
chars = [
"'{}'".format(encode_escape(i))
for i in decode_escape(data)
]
return ', '.join(chars) + ', 0'
|
def filter_query ( s ) : matches = re . findall ( r'(?:"([^"]*)")|([^"]*)' , s ) result_quoted = [ t [ 0 ] . strip ( ) for t in matches if t [ 0 ] ] result_unquoted = [ t [ 1 ] . strip ( ) for t in matches if t [ 1 ] ] return result_quoted , result_unquoted
| 1 |
python parse sql query string
|
Filters given query with the below regex and returns lists of quoted and unquoted strings
|
cosqa-train-13722
|
def filter_query(s):
"""
Filters given query with the below regex
and returns lists of quoted and unquoted strings
"""
matches = re.findall(r'(?:"([^"]*)")|([^"]*)', s)
result_quoted = [t[0].strip() for t in matches if t[0]]
result_unquoted = [t[1].strip() for t in matches if t[1]]
return result_quoted, result_unquoted
|
def _get_str_columns ( sf ) : return [ name for name in sf . column_names ( ) if sf [ name ] . dtype == str ]
| 1 |
how to get column names with data types in python
|
Returns a list of names of columns that are string type .
|
cosqa-train-13723
|
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 load_results ( result_files , options , run_set_id = None , columns = None , columns_relevant_for_diff = set ( ) ) : return parallel . map ( load_result , result_files , itertools . repeat ( options ) , itertools . repeat ( run_set_id ) , itertools . repeat ( columns ) , itertools . repeat ( columns_relevant_for_diff ) )
| 0 |
python parsing thousands of files parallel
|
Version of load_result for multiple input files that will be loaded concurrently .
|
cosqa-train-13724
|
def load_results(result_files, options, run_set_id=None, columns=None,
columns_relevant_for_diff=set()):
"""Version of load_result for multiple input files that will be loaded concurrently."""
return parallel.map(
load_result,
result_files,
itertools.repeat(options),
itertools.repeat(run_set_id),
itertools.repeat(columns),
itertools.repeat(columns_relevant_for_diff))
|
def screen_to_client ( self , x , y ) : return tuple ( win32 . ScreenToClient ( self . get_handle ( ) , ( x , y ) ) )
| 1 |
how to get coordinates of windows in python
|
Translates window screen coordinates to client coordinates .
|
cosqa-train-13725
|
def screen_to_client(self, x, y):
"""
Translates window screen coordinates to client coordinates.
@note: This is a simplified interface to some of the functionality of
the L{win32.Point} class.
@see: {win32.Point.screen_to_client}
@type x: int
@param x: Horizontal coordinate.
@type y: int
@param y: Vertical coordinate.
@rtype: tuple( int, int )
@return: Translated coordinates in a tuple (x, y).
@raise WindowsError: An error occured while processing this request.
"""
return tuple( win32.ScreenToClient( self.get_handle(), (x, y) ) )
|
def __next__ ( self , reward , ask_id , lbl ) : return self . next ( reward , ask_id , lbl )
| 1 |
python pass args to next function without *
|
For Python3 compatibility of generator .
|
cosqa-train-13726
|
def __next__(self, reward, ask_id, lbl):
"""For Python3 compatibility of generator."""
return self.next(reward, ask_id, lbl)
|
def get_month_start_end_day ( ) : t = date . today ( ) n = mdays [ t . month ] return ( date ( t . year , t . month , 1 ) , date ( t . year , t . month , n ) )
| 1 |
how to get days in a month in python
|
Get the month start date a nd end date
|
cosqa-train-13727
|
def get_month_start_end_day():
"""
Get the month start date a nd end date
"""
t = date.today()
n = mdays[t.month]
return (date(t.year, t.month, 1), date(t.year, t.month, n))
|
def cfloat64_array_to_numpy ( cptr , length ) : if isinstance ( cptr , ctypes . POINTER ( ctypes . c_double ) ) : return np . fromiter ( cptr , dtype = np . float64 , count = length ) else : raise RuntimeError ( 'Expected double pointer' )
| 1 |
python pass pointer of array to ctypes
|
Convert a ctypes double pointer array to a numpy array .
|
cosqa-train-13728
|
def cfloat64_array_to_numpy(cptr, length):
"""Convert a ctypes double pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_double)):
return np.fromiter(cptr, dtype=np.float64, count=length)
else:
raise RuntimeError('Expected double pointer')
|
def min_depth ( self , root ) : if root is None : return 0 if root . left is not None or root . right is not None : return max ( self . minDepth ( root . left ) , self . minDepth ( root . right ) ) + 1 return min ( self . minDepth ( root . left ) , self . minDepth ( root . right ) ) + 1
| 0 |
how to get depth of the node for binary tree in python
|
: type root : TreeNode : rtype : int
|
cosqa-train-13729
|
def min_depth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
if root.left is not None or root.right is not None:
return max(self.minDepth(root.left), self.minDepth(root.right))+1
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
|
def expand_path ( path ) : return os . path . abspath ( os . path . expandvars ( os . path . expanduser ( path ) ) )
| 1 |
python path expand envvar
|
Returns path as an absolute path with ~user and env var expansion applied .
|
cosqa-train-13730
|
def expand_path(path):
"""Returns ``path`` as an absolute path with ~user and env var expansion applied.
:API: public
"""
return os.path.abspath(os.path.expandvars(os.path.expanduser(path)))
|
def _get_gid ( name ) : if getgrnam is None or name is None : return None try : result = getgrnam ( name ) except KeyError : result = None if result is not None : return result [ 2 ] return None
| 1 |
how to get gid of a group python
|
Returns a gid given a group name .
|
cosqa-train-13731
|
def _get_gid(name):
"""Returns a gid, given a group name."""
if getgrnam is None or name is None:
return None
try:
result = getgrnam(name)
except KeyError:
result = None
if result is not None:
return result[2]
return None
|
def get_files ( dir_name ) : return [ ( os . path . join ( '.' , d ) , [ os . path . join ( d , f ) for f in files ] ) for d , _ , files in os . walk ( dir_name ) ]
| 0 |
python pathlib how to iterate over directories and subdirectories
|
Simple directory walker
|
cosqa-train-13732
|
def get_files(dir_name):
"""Simple directory walker"""
return [(os.path.join('.', d), [os.path.join(d, f) for f in files]) for d, _, files in os.walk(dir_name)]
|
def help_for_command ( command ) : help_text = pydoc . text . document ( command ) # remove backspaces return re . subn ( '.\\x08' , '' , help_text ) [ 0 ]
| 1 |
how to get help function in python
|
Get the help text ( signature + docstring ) for a command ( function ) .
|
cosqa-train-13733
|
def help_for_command(command):
"""Get the help text (signature + docstring) for a command (function)."""
help_text = pydoc.text.document(command)
# remove backspaces
return re.subn('.\\x08', '', help_text)[0]
|
def parent ( self , index ) : childItem = self . item ( index ) parentItem = childItem . parent if parentItem == self . rootItem : parentIndex = QModelIndex ( ) else : parentIndex = self . createIndex ( parentItem . row ( ) , 0 , parentItem ) return parentIndex
| 1 |
how to get index from parent as a child python
|
Return the index of the parent for a given index of the child . Unfortunately the name of the method has to be parent even though a more verbose name like parentIndex would avoid confusion about what parent actually is - an index or an item .
|
cosqa-train-13734
|
def parent(self, index):
"""Return the index of the parent for a given index of the
child. Unfortunately, the name of the method has to be parent,
even though a more verbose name like parentIndex, would avoid
confusion about what parent actually is - an index or an item.
"""
childItem = self.item(index)
parentItem = childItem.parent
if parentItem == self.rootItem:
parentIndex = QModelIndex()
else:
parentIndex = self.createIndex(parentItem.row(), 0, parentItem)
return parentIndex
|
def filter_regex ( names , regex ) : return tuple ( name for name in names if regex . search ( name ) is not None )
| 1 |
python pattern match tuple
|
Return a tuple of strings that match the regular expression pattern .
|
cosqa-train-13735
|
def filter_regex(names, regex):
"""
Return a tuple of strings that match the regular expression pattern.
"""
return tuple(name for name in names
if regex.search(name) is not None)
|
def get_lines ( handle , line ) : for i , l in enumerate ( handle ) : if i == line : return l
| 1 |
how to get index of lines in file using python
|
Get zero - indexed line from an open file - like .
|
cosqa-train-13736
|
def get_lines(handle, line):
"""
Get zero-indexed line from an open file-like.
"""
for i, l in enumerate(handle):
if i == line:
return l
|
def standardize ( table , with_std = True ) : if isinstance ( table , pandas . DataFrame ) : cat_columns = table . select_dtypes ( include = [ 'category' ] ) . columns else : cat_columns = [ ] new_frame = _apply_along_column ( table , standardize_column , with_std = with_std ) # work around for apply converting category dtype to object # https://github.com/pydata/pandas/issues/9573 for col in cat_columns : new_frame [ col ] = table [ col ] . copy ( ) return new_frame
| 1 |
python pd normalize multiple columns
|
Perform Z - Normalization on each numeric column of the given table .
|
cosqa-train-13737
|
def standardize(table, with_std=True):
"""
Perform Z-Normalization on each numeric column of the given table.
Parameters
----------
table : pandas.DataFrame or numpy.ndarray
Data to standardize.
with_std : bool, optional, default: True
If ``False`` data is only centered and not converted to unit variance.
Returns
-------
normalized : pandas.DataFrame
Table with numeric columns normalized.
Categorical columns in the input table remain unchanged.
"""
if isinstance(table, pandas.DataFrame):
cat_columns = table.select_dtypes(include=['category']).columns
else:
cat_columns = []
new_frame = _apply_along_column(table, standardize_column, with_std=with_std)
# work around for apply converting category dtype to object
# https://github.com/pydata/pandas/issues/9573
for col in cat_columns:
new_frame[col] = table[col].copy()
return new_frame
|
def index ( m , val ) : mm = np . array ( m ) idx_tuple = np . where ( mm == val ) idx = idx_tuple [ 0 ] . tolist ( ) return idx
| 0 |
how to get indexes of a value in an array in python
|
Return the indices of all the val in m
|
cosqa-train-13738
|
def index(m, val):
"""
Return the indices of all the ``val`` in ``m``
"""
mm = np.array(m)
idx_tuple = np.where(mm == val)
idx = idx_tuple[0].tolist()
return idx
|
def dimensions ( self ) : size = self . pdf . getPage ( 0 ) . mediaBox return { 'w' : float ( size [ 2 ] ) , 'h' : float ( size [ 3 ] ) }
| 1 |
python pdfminer size of page
|
Get width and height of a PDF
|
cosqa-train-13739
|
def dimensions(self):
"""Get width and height of a PDF"""
size = self.pdf.getPage(0).mediaBox
return {'w': float(size[2]), 'h': float(size[3])}
|
def validate_multiindex ( self , obj ) : levels = [ l if l is not None else "level_{0}" . format ( i ) for i , l in enumerate ( obj . index . names ) ] try : return obj . reset_index ( ) , levels except ValueError : raise ValueError ( "duplicate names/columns in the multi-index when " "storing as a table" )
| 1 |
how to get into multyindex python
|
validate that we can store the multi - index ; reset and return the new object
|
cosqa-train-13740
|
def validate_multiindex(self, obj):
"""validate that we can store the multi-index; reset and return the
new object
"""
levels = [l if l is not None else "level_{0}".format(i)
for i, l in enumerate(obj.index.names)]
try:
return obj.reset_index(), levels
except ValueError:
raise ValueError("duplicate names/columns in the multi-index when "
"storing as a table")
|
def PythonPercentFormat ( format_str ) : if format_str . startswith ( 'printf ' ) : fmt = format_str [ len ( 'printf ' ) : ] return lambda value : fmt % value else : return None
| 1 |
python percent % in string
|
Use Python % format strings as template format specifiers .
|
cosqa-train-13741
|
def PythonPercentFormat(format_str):
"""Use Python % format strings as template format specifiers."""
if format_str.startswith('printf '):
fmt = format_str[len('printf '):]
return lambda value: fmt % value
else:
return None
|
def _last_index ( x , default_dim ) : if x . get_shape ( ) . ndims is not None : return len ( x . get_shape ( ) ) - 1 else : return default_dim
| 1 |
how to get last element of an2d array in python
|
Returns the last dimension s index or default_dim if x has no shape .
|
cosqa-train-13742
|
def _last_index(x, default_dim):
"""Returns the last dimension's index or default_dim if x has no shape."""
if x.get_shape().ndims is not None:
return len(x.get_shape()) - 1
else:
return default_dim
|
def unpickle_file ( picklefile , * * kwargs ) : with open ( picklefile , 'rb' ) as f : return pickle . load ( f , * * kwargs )
| 1 |
python pickle load return object
|
Helper function to unpickle data from picklefile .
|
cosqa-train-13743
|
def unpickle_file(picklefile, **kwargs):
"""Helper function to unpickle data from `picklefile`."""
with open(picklefile, 'rb') as f:
return pickle.load(f, **kwargs)
|
def do_history ( self , line ) : self . _split_args ( line , 0 , 0 ) for idx , item in enumerate ( self . _history ) : d1_cli . impl . util . print_info ( "{0: 3d} {1}" . format ( idx , item ) )
| 1 |
how to get list of previous command in python
|
history Display a list of commands that have been entered .
|
cosqa-train-13744
|
def do_history(self, line):
"""history Display a list of commands that have been entered."""
self._split_args(line, 0, 0)
for idx, item in enumerate(self._history):
d1_cli.impl.util.print_info("{0: 3d} {1}".format(idx, item))
|
def unpickle_stats ( stats ) : stats = cPickle . loads ( stats ) stats . stream = True return stats
| 0 |
python pickle non type is not callable
|
Unpickle a pstats . Stats object
|
cosqa-train-13745
|
def unpickle_stats(stats):
"""Unpickle a pstats.Stats object"""
stats = cPickle.loads(stats)
stats.stream = True
return stats
|
def getScriptLocation ( ) : location = os . path . abspath ( "./" ) if __file__ . rfind ( "/" ) != - 1 : location = __file__ [ : __file__ . rfind ( "/" ) ] return location
| 1 |
how to get location python
|
Helper function to get the location of a Python file .
|
cosqa-train-13746
|
def getScriptLocation():
"""Helper function to get the location of a Python file."""
location = os.path.abspath("./")
if __file__.rfind("/") != -1:
location = __file__[:__file__.rfind("/")]
return location
|
def pid_exists ( pid ) : try : os . kill ( pid , 0 ) except OSError as exc : return exc . errno == errno . EPERM else : return True
| 1 |
python pid determine existence
|
Determines if a system process identifer exists in process table .
|
cosqa-train-13747
|
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 a2s ( a ) : s = np . zeros ( ( 6 , ) , 'f' ) # make the a matrix for i in range ( 3 ) : s [ i ] = a [ i ] [ i ] s [ 3 ] = a [ 0 ] [ 1 ] s [ 4 ] = a [ 1 ] [ 2 ] s [ 5 ] = a [ 0 ] [ 2 ] return s
| 1 |
how to get matrix as input in python
|
convert 3 3 a matrix to 6 element s list ( see Tauxe 1998 )
|
cosqa-train-13748
|
def a2s(a):
"""
convert 3,3 a matrix to 6 element "s" list (see Tauxe 1998)
"""
s = np.zeros((6,), 'f') # make the a matrix
for i in range(3):
s[i] = a[i][i]
s[3] = a[0][1]
s[4] = a[1][2]
s[5] = a[0][2]
return s
|
def show ( data , negate = False ) : from PIL import Image as pil data = np . array ( ( data - data . min ( ) ) * 255.0 / ( data . max ( ) - data . min ( ) ) , np . uint8 ) if negate : data = 255 - data img = pil . fromarray ( data ) img . show ( )
| 1 |
python pil images looks like a negative
|
Show the stretched data .
|
cosqa-train-13749
|
def show(data, negate=False):
"""Show the stretched data.
"""
from PIL import Image as pil
data = np.array((data - data.min()) * 255.0 /
(data.max() - data.min()), np.uint8)
if negate:
data = 255 - data
img = pil.fromarray(data)
img.show()
|
def best ( self ) : b = ( - 1e999999 , None ) for k , c in iteritems ( self . counts ) : b = max ( b , ( c , k ) ) return b [ 1 ]
| 1 |
how to get maximum in counter function in python
|
Returns the element with the highest probability .
|
cosqa-train-13750
|
def best(self):
"""
Returns the element with the highest probability.
"""
b = (-1e999999, None)
for k, c in iteritems(self.counts):
b = max(b, (c, k))
return b[1]
|
def set_ylimits ( self , row , column , min = None , max = None ) : subplot = self . get_subplot_at ( row , column ) subplot . set_ylimits ( min , max )
| 1 |
python plot use default yaxis limits
|
Set y - axis limits of a subplot .
|
cosqa-train-13751
|
def set_ylimits(self, row, column, min=None, max=None):
"""Set y-axis limits of a subplot.
:param row,column: specify the subplot.
:param min: minimal axis value
:param max: maximum axis value
"""
subplot = self.get_subplot_at(row, column)
subplot.set_ylimits(min, max)
|
def count_ ( self ) : try : num = len ( self . df . index ) except Exception as e : self . err ( e , "Can not count data" ) return return num
| 1 |
how to get number of rows from data frame in python
|
Returns the number of rows of the main dataframe
|
cosqa-train-13752
|
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 _encode_gif ( images , fps ) : writer = WholeVideoWriter ( fps ) writer . write_multi ( images ) return writer . finish ( )
| 1 |
python pngs to animation gif
|
Encodes numpy images into gif string .
|
cosqa-train-13753
|
def _encode_gif(images, fps):
"""Encodes numpy images into gif string.
Args:
images: A 4-D `uint8` `np.array` (or a list of 3-D images) of shape
`[time, height, width, channels]` where `channels` is 1 or 3.
fps: frames per second of the animation
Returns:
The encoded gif string.
Raises:
IOError: If the ffmpeg command returns an error.
"""
writer = WholeVideoWriter(fps)
writer.write_multi(images)
return writer.finish()
|
def getScriptLocation ( ) : location = os . path . abspath ( "./" ) if __file__ . rfind ( "/" ) != - 1 : location = __file__ [ : __file__ . rfind ( "/" ) ] return location
| 1 |
how to get python location
|
Helper function to get the location of a Python file .
|
cosqa-train-13754
|
def getScriptLocation():
"""Helper function to get the location of a Python file."""
location = os.path.abspath("./")
if __file__.rfind("/") != -1:
location = __file__[:__file__.rfind("/")]
return location
|
def imapchain ( * a , * * kwa ) : imap_results = map ( * a , * * kwa ) return itertools . chain ( * imap_results )
| 1 |
python pool imap mutltiple argements
|
Like map but also chains the results .
|
cosqa-train-13755
|
def imapchain(*a, **kwa):
""" Like map but also chains the results. """
imap_results = map( *a, **kwa )
return itertools.chain( *imap_results )
|
def eval_script ( self , expr ) : ret = self . conn . issue_command ( "Evaluate" , expr ) return json . loads ( "[%s]" % ret ) [ 0 ]
| 1 |
how to get python script return value in javascript
|
Evaluates a piece of Javascript in the context of the current page and returns its value .
|
cosqa-train-13756
|
def eval_script(self, expr):
""" Evaluates a piece of Javascript in the context of the current page and
returns its value. """
ret = self.conn.issue_command("Evaluate", expr)
return json.loads("[%s]" % ret)[0]
|
def asyncStarCmap ( asyncCallable , iterable ) : results = [ ] yield coopStar ( asyncCallable , results . append , iterable ) returnValue ( results )
| 0 |
python pool map with lambda function
|
itertools . starmap for deferred callables using cooperative multitasking
|
cosqa-train-13757
|
def asyncStarCmap(asyncCallable, iterable):
"""itertools.starmap for deferred callables using cooperative multitasking
"""
results = []
yield coopStar(asyncCallable, results.append, iterable)
returnValue(results)
|
def header_length ( bytearray ) : groups_of_3 , leftover = divmod ( len ( bytearray ) , 3 ) # 4 bytes out for each 3 bytes (or nonzero fraction thereof) in. n = groups_of_3 * 4 if leftover : n += 4 return n
| 1 |
how to get size of a byte string python
|
Return the length of s when it is encoded with base64 .
|
cosqa-train-13758
|
def header_length(bytearray):
"""Return the length of s when it is encoded with base64."""
groups_of_3, leftover = divmod(len(bytearray), 3)
# 4 bytes out for each 3 bytes (or nonzero fraction thereof) in.
n = groups_of_3 * 4
if leftover:
n += 4
return n
|
def pop ( self , index = - 1 ) : value = self . _list . pop ( index ) del self . _dict [ value ] return value
| 0 |
python pop without remove
|
Remove and return the item at index .
|
cosqa-train-13759
|
def pop(self, index=-1):
"""Remove and return the item at index."""
value = self._list.pop(index)
del self._dict[value]
return value
|
def debug_on_error ( type , value , tb ) : traceback . print_exc ( type , value , tb ) print ( ) pdb . pm ( )
| 1 |
how to get stack trace in python pdb
|
Code due to Thomas Heller - published in Python Cookbook ( O Reilley )
|
cosqa-train-13760
|
def debug_on_error(type, value, tb):
"""Code due to Thomas Heller - published in Python Cookbook (O'Reilley)"""
traceback.print_exc(type, value, tb)
print()
pdb.pm()
|
def _render_table ( data , fields = None ) : return IPython . core . display . HTML ( datalab . utils . commands . HtmlBuilder . render_table ( data , fields ) )
| 1 |
python posting table to html
|
Helper to render a list of dictionaries as an HTML display object .
|
cosqa-train-13761
|
def _render_table(data, fields=None):
""" Helper to render a list of dictionaries as an HTML display object. """
return IPython.core.display.HTML(datalab.utils.commands.HtmlBuilder.render_table(data, fields))
|
def get_example_features ( example ) : return ( example . features . feature if isinstance ( example , tf . train . Example ) else example . context . feature )
| 0 |
how to get tensorflow for python3
|
Returns the non - sequence features from the provided example .
|
cosqa-train-13762
|
def get_example_features(example):
"""Returns the non-sequence features from the provided example."""
return (example.features.feature if isinstance(example, tf.train.Example)
else example.context.feature)
|
def pp_xml ( body ) : pretty = xml . dom . minidom . parseString ( body ) return pretty . toprettyxml ( indent = " " )
| 0 |
python pretty xml with namespace
|
Pretty print format some XML so it s readable .
|
cosqa-train-13763
|
def pp_xml(body):
"""Pretty print format some XML so it's readable."""
pretty = xml.dom.minidom.parseString(body)
return pretty.toprettyxml(indent=" ")
|
def variance ( arr ) : avg = average ( arr ) return sum ( [ ( float ( x ) - avg ) ** 2 for x in arr ] ) / float ( len ( arr ) - 1 )
| 1 |
how to get the average of values in an array in python
|
variance of the values must have 2 or more entries .
|
cosqa-train-13764
|
def variance(arr):
"""variance of the values, must have 2 or more entries.
:param arr: list of numbers
:type arr: number[] a number array
:return: variance
:rtype: float
"""
avg = average(arr)
return sum([(float(x)-avg)**2 for x in arr])/float(len(arr)-1)
|
def format_prettytable ( table ) : for i , row in enumerate ( table . rows ) : for j , item in enumerate ( row ) : table . rows [ i ] [ j ] = format_output ( item ) ptable = table . prettytable ( ) ptable . hrules = prettytable . FRAME ptable . horizontal_char = '.' ptable . vertical_char = ':' ptable . junction_char = ':' return ptable
| 1 |
python prettytable to csv
|
Converts SoftLayer . CLI . formatting . Table instance to a prettytable .
|
cosqa-train-13765
|
def format_prettytable(table):
"""Converts SoftLayer.CLI.formatting.Table instance to a prettytable."""
for i, row in enumerate(table.rows):
for j, item in enumerate(row):
table.rows[i][j] = format_output(item)
ptable = table.prettytable()
ptable.hrules = prettytable.FRAME
ptable.horizontal_char = '.'
ptable.vertical_char = ':'
ptable.junction_char = ':'
return ptable
|
def _get_str_columns ( sf ) : return [ name for name in sf . column_names ( ) if sf [ name ] . dtype == str ]
| 1 |
how to get the column names in python dataset
|
Returns a list of names of columns that are string type .
|
cosqa-train-13766
|
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 print_item_with_children ( ac , classes , level ) : print_row ( ac . id , ac . name , f"{ac.allocation:,.2f}" , level ) print_children_recursively ( classes , ac , level + 1 )
| 1 |
python print contents of a tree object
|
Print the given item and all children items
|
cosqa-train-13767
|
def print_item_with_children(ac, classes, level):
""" Print the given item and all children items """
print_row(ac.id, ac.name, f"{ac.allocation:,.2f}", level)
print_children_recursively(classes, ac, level + 1)
|
def datatype ( dbtype , description , cursor ) : dt = cursor . db . introspection . get_field_type ( dbtype , description ) if type ( dt ) is tuple : return dt [ 0 ] else : return dt
| 1 |
how to get the datatype python
|
Google AppEngine Helper to convert a data type into a string .
|
cosqa-train-13768
|
def datatype(dbtype, description, cursor):
"""Google AppEngine Helper to convert a data type into a string."""
dt = cursor.db.introspection.get_field_type(dbtype, description)
if type(dt) is tuple:
return dt[0]
else:
return dt
|
def indented_show ( text , howmany = 1 ) : print ( StrTemplate . pad_indent ( text = text , howmany = howmany ) )
| 1 |
python print format string fixed width
|
Print a formatted indented text .
|
cosqa-train-13769
|
def indented_show(text, howmany=1):
"""Print a formatted indented text.
"""
print(StrTemplate.pad_indent(text=text, howmany=howmany))
|
def pformat ( object , indent = 1 , width = 80 , depth = None ) : return PrettyPrinter ( indent = indent , width = width , depth = depth ) . pformat ( object )
| 1 |
python print in fixed width
|
Format a Python object into a pretty - printed representation .
|
cosqa-train-13770
|
def pformat(object, indent=1, width=80, depth=None):
"""Format a Python object into a pretty-printed representation."""
return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
|
def _num_cpus_darwin ( ) : p = subprocess . Popen ( [ 'sysctl' , '-n' , 'hw.ncpu' ] , stdout = subprocess . PIPE ) return p . stdout . read ( )
| 1 |
how to get the number of cores on pc using python code
|
Return the number of active CPUs on a Darwin system .
|
cosqa-train-13771
|
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 pformat ( object , indent = 1 , width = 80 , depth = None ) : return PrettyPrinter ( indent = indent , width = width , depth = depth ) . pformat ( object )
| 1 |
python print keep precision
|
Format a Python object into a pretty - printed representation .
|
cosqa-train-13772
|
def pformat(object, indent=1, width=80, depth=None):
"""Format a Python object into a pretty-printed representation."""
return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
|
def getpackagepath ( ) : moduleDirectory = os . path . dirname ( __file__ ) packagePath = os . path . dirname ( __file__ ) + "/../" return packagePath
| 1 |
how to get the original directory of the python file
|
* Get the root path for this python package - used in unit testing code *
|
cosqa-train-13773
|
def getpackagepath():
"""
*Get the root path for this python package - used in unit testing code*
"""
moduleDirectory = os.path.dirname(__file__)
packagePath = os.path.dirname(__file__) + "/../"
return packagePath
|
def print_out ( self , * lst ) : self . print2file ( self . stdout , True , True , * lst )
| 0 |
python print method code
|
Print list of strings to the predefined stdout .
|
cosqa-train-13774
|
def print_out(self, *lst):
""" Print list of strings to the predefined stdout. """
self.print2file(self.stdout, True, True, *lst)
|
def get_system_root_directory ( ) : root = os . path . dirname ( __file__ ) root = os . path . dirname ( root ) root = os . path . abspath ( root ) return root
| 0 |
how to get the root using python
|
Get system root directory ( application installed root directory )
|
cosqa-train-13775
|
def get_system_root_directory():
"""
Get system root directory (application installed root directory)
Returns
-------
string
A full path
"""
root = os.path.dirname(__file__)
root = os.path.dirname(root)
root = os.path.abspath(root)
return root
|
def stdoutwriteline ( * args ) : s = "" for i in args : s += str ( i ) + " " s = s . strip ( ) sys . stdout . write ( str ( s ) + "\n" ) sys . stdout . flush ( ) return s
| 1 |
python print multiple lines in str function
|
cosqa-train-13776
|
def stdoutwriteline(*args):
"""
@type args: tuple
@return: None
"""
s = ""
for i in args:
s += str(i) + " "
s = s.strip()
sys.stdout.write(str(s) + "\n")
sys.stdout.flush()
return s
|
|
def find_lt ( a , x ) : i = bs . bisect_left ( a , x ) if i : return i - 1 raise ValueError
| 1 |
how to get the smallest value in a list in python
|
Find rightmost value less than x .
|
cosqa-train-13777
|
def find_lt(a, x):
"""Find rightmost value less than x."""
i = bs.bisect_left(a, x)
if i: return i - 1
raise ValueError
|
def format_exc ( limit = None ) : try : etype , value , tb = sys . exc_info ( ) return '' . join ( traceback . format_exception ( etype , value , tb , limit ) ) finally : etype = value = tb = None
| 0 |
python print stack trace extception
|
Like print_exc () but return a string . Backport for Python 2 . 3 .
|
cosqa-train-13778
|
def format_exc(limit=None):
"""Like print_exc() but return a string. Backport for Python 2.3."""
try:
etype, value, tb = sys.exc_info()
return ''.join(traceback.format_exception(etype, value, tb, limit))
finally:
etype = value = tb = None
|
def getTypeStr ( _type ) : if isinstance ( _type , CustomType ) : return str ( _type ) if hasattr ( _type , '__name__' ) : return _type . __name__ return ''
| 1 |
how to get the type of a variable python
|
r Gets the string representation of the given type .
|
cosqa-train-13779
|
def getTypeStr(_type):
r"""Gets the string representation of the given type.
"""
if isinstance(_type, CustomType):
return str(_type)
if hasattr(_type, '__name__'):
return _type.__name__
return ''
|
def ss ( * args , * * kwargs ) : if not args : raise ValueError ( "you didn't pass any arguments to print out" ) with Reflect . context ( args , * * kwargs ) as r : instance = V_CLASS ( r , stream , * * kwargs ) return instance . value ( ) . strip ( )
| 1 |
python print string to a varaible
|
exactly like s but doesn t return variable names or file positions ( useful for logging )
|
cosqa-train-13780
|
def ss(*args, **kwargs):
"""
exactly like s, but doesn't return variable names or file positions (useful for logging)
since -- 10-15-2015
return -- str
"""
if not args:
raise ValueError("you didn't pass any arguments to print out")
with Reflect.context(args, **kwargs) as r:
instance = V_CLASS(r, stream, **kwargs)
return instance.value().strip()
|
def get_width ( ) : # Get terminal size ws = struct . pack ( "HHHH" , 0 , 0 , 0 , 0 ) ws = fcntl . ioctl ( sys . stdout . fileno ( ) , termios . TIOCGWINSZ , ws ) lines , columns , x , y = struct . unpack ( "HHHH" , ws ) width = min ( columns * 39 // 40 , columns - 2 ) return width
| 0 |
how to get the width of the stdout area in python
|
Get terminal width
|
cosqa-train-13781
|
def get_width():
"""Get terminal width"""
# Get terminal size
ws = struct.pack("HHHH", 0, 0, 0, 0)
ws = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, ws)
lines, columns, x, y = struct.unpack("HHHH", ws)
width = min(columns * 39 // 40, columns - 2)
return width
|
def set_stop_handler ( self ) : signal . signal ( signal . SIGTERM , self . graceful_stop ) signal . signal ( signal . SIGABRT , self . graceful_stop ) signal . signal ( signal . SIGINT , self . graceful_stop )
| 1 |
python process force exit
|
Initializes functions that are invoked when the user or OS wants to kill this process . : return :
|
cosqa-train-13782
|
def set_stop_handler(self):
"""
Initializes functions that are invoked when the user or OS wants to kill this process.
:return:
"""
signal.signal(signal.SIGTERM, self.graceful_stop)
signal.signal(signal.SIGABRT, self.graceful_stop)
signal.signal(signal.SIGINT, self.graceful_stop)
|
def _async_requests ( urls ) : session = FuturesSession ( max_workers = 30 ) futures = [ session . get ( url ) for url in urls ] return [ future . result ( ) for future in futures ]
| 1 |
how to get thousands of http requests asynchronously python
|
Sends multiple non - blocking requests . Returns a list of responses .
|
cosqa-train-13783
|
def _async_requests(urls):
"""
Sends multiple non-blocking requests. Returns
a list of responses.
:param urls:
List of urls
"""
session = FuturesSession(max_workers=30)
futures = [
session.get(url)
for url in urls
]
return [ future.result() for future in futures ]
|
def angle_between_vectors ( x , y ) : dp = dot_product ( x , y ) if dp == 0 : return 0 xm = magnitude ( x ) ym = magnitude ( y ) return math . acos ( dp / ( xm * ym ) ) * ( 180. / math . pi )
| 1 |
python program calculating angle from two points
|
Compute the angle between vector x and y
|
cosqa-train-13784
|
def angle_between_vectors(x, y):
""" Compute the angle between vector x and y """
dp = dot_product(x, y)
if dp == 0:
return 0
xm = magnitude(x)
ym = magnitude(y)
return math.acos(dp / (xm*ym)) * (180. / math.pi)
|
def get_python ( ) : if sys . platform == 'win32' : python = path . join ( VE_ROOT , 'Scripts' , 'python.exe' ) else : python = path . join ( VE_ROOT , 'bin' , 'python' ) return python
| 1 |
how to get to python env var on windows
|
Determine the path to the virtualenv python
|
cosqa-train-13785
|
def get_python():
"""Determine the path to the virtualenv python"""
if sys.platform == 'win32':
python = path.join(VE_ROOT, 'Scripts', 'python.exe')
else:
python = path.join(VE_ROOT, 'bin', 'python')
return python
|
def tick ( self ) : self . current += 1 if self . current == self . factor : sys . stdout . write ( '+' ) sys . stdout . flush ( ) self . current = 0
| 1 |
python progressbar change color
|
Add one tick to progress bar
|
cosqa-train-13786
|
def tick(self):
"""Add one tick to progress bar"""
self.current += 1
if self.current == self.factor:
sys.stdout.write('+')
sys.stdout.flush()
self.current = 0
|
def readTuple ( self , line , n = 3 ) : numbers = [ num for num in line . split ( ' ' ) if num ] return [ float ( num ) for num in numbers [ 1 : n + 1 ] ]
| 1 |
how to get tuple from text file using python
|
Reads a tuple of numbers . e . g . vertices normals or teture coords .
|
cosqa-train-13787
|
def readTuple(self, line, n=3):
""" Reads a tuple of numbers. e.g. vertices, normals or teture coords.
"""
numbers = [num for num in line.split(' ') if num]
return [float(num) for num in numbers[1:n + 1]]
|
def prompt ( * args , * * kwargs ) : try : return click . prompt ( * args , * * kwargs ) except click . Abort : return False
| 1 |
python prompt user for confirmation
|
Prompt the user for input and handle any abort exceptions .
|
cosqa-train-13788
|
def prompt(*args, **kwargs):
"""Prompt the user for input and handle any abort exceptions."""
try:
return click.prompt(*args, **kwargs)
except click.Abort:
return False
|
def value_for_key ( membersuite_object_data , key ) : key_value_dicts = { d [ 'Key' ] : d [ 'Value' ] for d in membersuite_object_data [ "Fields" ] [ "KeyValueOfstringanyType" ] } return key_value_dicts [ key ]
| 1 |
how to get value for a key in python key values
|
Return the value for key of membersuite_object_data .
|
cosqa-train-13789
|
def value_for_key(membersuite_object_data, key):
"""Return the value for `key` of membersuite_object_data.
"""
key_value_dicts = {
d['Key']: d['Value'] for d
in membersuite_object_data["Fields"]["KeyValueOfstringanyType"]}
return key_value_dicts[key]
|
def _set_property ( self , val , * args ) : val = UserClassAdapter . _set_property ( self , val , * args ) if val : Adapter . _set_property ( self , val , * args ) return val
| 1 |
python property without setter
|
Private method that sets the value currently of the property
|
cosqa-train-13790
|
def _set_property(self, val, *args):
"""Private method that sets the value currently of the property"""
val = UserClassAdapter._set_property(self, val, *args)
if val:
Adapter._set_property(self, val, *args)
return val
|
def _baseattrs ( self ) : result = super ( ) . _baseattrs result [ "params" ] = ", " . join ( self . parameters ) return result
| 1 |
how to get values from base to super in python
|
A dict of members expressed in literals
|
cosqa-train-13791
|
def _baseattrs(self):
"""A dict of members expressed in literals"""
result = super()._baseattrs
result["params"] = ", ".join(self.parameters)
return result
|
def items ( self ) : return [ ( value_descriptor . name , value_descriptor . number ) for value_descriptor in self . _enum_type . values ]
| 1 |
python protobuf get enum text
|
Return a list of the ( name value ) pairs of the enum .
|
cosqa-train-13792
|
def items(self):
"""Return a list of the (name, value) pairs of the enum.
These are returned in the order they were defined in the .proto file.
"""
return [(value_descriptor.name, value_descriptor.number)
for value_descriptor in self._enum_type.values]
|
def has_edit_permission ( self , request ) : return request . user . is_authenticated and request . user . is_active and request . user . is_staff
| 1 |
how to give admin rights to python
|
Can edit this object
|
cosqa-train-13793
|
def has_edit_permission(self, request):
""" Can edit this object """
return request.user.is_authenticated and request.user.is_active and request.user.is_staff
|
def items ( self ) : return [ ( value_descriptor . name , value_descriptor . number ) for value_descriptor in self . _enum_type . values ]
| 1 |
python protobuf get enum value as text
|
Return a list of the ( name value ) pairs of the enum .
|
cosqa-train-13794
|
def items(self):
"""Return a list of the (name, value) pairs of the enum.
These are returned in the order they were defined in the .proto file.
"""
return [(value_descriptor.name, value_descriptor.number)
for value_descriptor in self._enum_type.values]
|
def _comment ( string ) : lines = [ line . strip ( ) for line in string . splitlines ( ) ] return "# " + ( "%s# " % linesep ) . join ( lines )
| 1 |
how to give comment line in python
|
return string as a comment
|
cosqa-train-13795
|
def _comment(string):
"""return string as a comment"""
lines = [line.strip() for line in string.splitlines()]
return "# " + ("%s# " % linesep).join(lines)
|
def set ( self , f ) : self . stop ( ) self . _create_timer ( f ) self . start ( )
| 1 |
python putting a function on a timer
|
Call a function after a delay unless another function is set in the meantime .
|
cosqa-train-13796
|
def set(self, f):
"""Call a function after a delay, unless another function is set
in the meantime."""
self.stop()
self._create_timer(f)
self.start()
|
def _parse_ranges ( ranges ) : for txt in ranges : if '-' in txt : low , high = txt . split ( '-' ) else : low , high = txt , txt yield int ( low ) , int ( high )
| 1 |
how to grab a range from a string python
|
Converts a list of string ranges to a list of [ low high ] tuples .
|
cosqa-train-13797
|
def _parse_ranges(ranges):
""" Converts a list of string ranges to a list of [low, high] tuples. """
for txt in ranges:
if '-' in txt:
low, high = txt.split('-')
else:
low, high = txt, txt
yield int(low), int(high)
|
def run_tests ( self ) : with _save_argv ( _sys . argv [ : 1 ] + self . addopts ) : result_code = __import__ ( 'pytest' ) . main ( ) if result_code : raise SystemExit ( result_code )
| 1 |
python pytest global variable
|
Invoke pytest replacing argv . Return result code .
|
cosqa-train-13798
|
def run_tests(self):
"""
Invoke pytest, replacing argv. Return result code.
"""
with _save_argv(_sys.argv[:1] + self.addopts):
result_code = __import__('pytest').main()
if result_code:
raise SystemExit(result_code)
|
def plot_pauli_transfer_matrix ( self , ax ) : title = "Estimated process" ut . plot_pauli_transfer_matrix ( self . r_est , ax , self . pauli_basis . labels , title )
| 1 |
how to have pi in label in python plot
|
Plot the elements of the Pauli transfer matrix .
|
cosqa-train-13799
|
def plot_pauli_transfer_matrix(self, ax):
"""
Plot the elements of the Pauli transfer matrix.
:param matplotlib.Axes ax: A matplotlib Axes object to plot into.
"""
title = "Estimated process"
ut.plot_pauli_transfer_matrix(self.r_est, ax, self.pauli_basis.labels, title)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.