code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _load_data(self, band):
"""From Morrissey+ 2005, with the actual data coming from
http://www.astro.caltech.edu/~capak/filters/. According to the latter,
these are in QE units and thus need to be multiplied by the wavelength
when integrating per-energy.
"""
# `band` s... | def function[_load_data, parameter[self, band]]:
constant[From Morrissey+ 2005, with the actual data coming from
http://www.astro.caltech.edu/~capak/filters/. According to the latter,
these are in QE units and thus need to be multiplied by the wavelength
when integrating per-energy.
... | keyword[def] identifier[_load_data] ( identifier[self] , identifier[band] ):
literal[string]
identifier[df] = identifier[bandpass_data_frame] ( literal[string] + identifier[band] + literal[string] , literal[string] )
identifier[df] . identifier[resp] *= identifier[df] . identifier... | def _load_data(self, band):
"""From Morrissey+ 2005, with the actual data coming from
http://www.astro.caltech.edu/~capak/filters/. According to the latter,
these are in QE units and thus need to be multiplied by the wavelength
when integrating per-energy.
"""
# `band` should be... |
def _get_parser(description):
"""Build an ArgumentParser with common arguments for both operations."""
parser = argparse.ArgumentParser(description=description)
parser.add_argument('key', help="Camellia key.")
parser.add_argument('input_file', nargs='*',
help="File(s) to read as ... | def function[_get_parser, parameter[description]]:
constant[Build an ArgumentParser with common arguments for both operations.]
variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
call[name[parser].add_argument, parameter[constant[key]]]
call[name[parser].add_argu... | keyword[def] identifier[_get_parser] ( identifier[description] ):
literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] ( identifier[description] = identifier[description] )
identifier[parser] . identifier[add_argument] ( literal[string] , identifier[help] = literal[st... | def _get_parser(description):
"""Build an ArgumentParser with common arguments for both operations."""
parser = argparse.ArgumentParser(description=description)
parser.add_argument('key', help='Camellia key.')
parser.add_argument('input_file', nargs='*', help='File(s) to read as input data. If none are ... |
def download_extract(url):
"""download and extract file."""
logger.info("Downloading %s", url)
request = urllib2.Request(url)
request.add_header('User-Agent',
'caelum/0.1 +https://github.com/nrcharles/caelum')
opener = urllib2.build_opener()
with tempfile.TemporaryFile(suf... | def function[download_extract, parameter[url]]:
constant[download and extract file.]
call[name[logger].info, parameter[constant[Downloading %s], name[url]]]
variable[request] assign[=] call[name[urllib2].Request, parameter[name[url]]]
call[name[request].add_header, parameter[constant[Use... | keyword[def] identifier[download_extract] ( identifier[url] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] , identifier[url] )
identifier[request] = identifier[urllib2] . identifier[Request] ( identifier[url] )
identifier[request] . identifier[add_header] ( literal[str... | def download_extract(url):
"""download and extract file."""
logger.info('Downloading %s', url)
request = urllib2.Request(url)
request.add_header('User-Agent', 'caelum/0.1 +https://github.com/nrcharles/caelum')
opener = urllib2.build_opener()
with tempfile.TemporaryFile(suffix='.zip', dir=env.WEA... |
def _collapse_list_of_sets(self, sets):
'''Input is a list of sets. Merges any intersecting sets in the list'''
found = True
while found:
found = False
to_intersect = None
for i in range(len(sets)):
for j in range(len(sets)):
... | def function[_collapse_list_of_sets, parameter[self, sets]]:
constant[Input is a list of sets. Merges any intersecting sets in the list]
variable[found] assign[=] constant[True]
while name[found] begin[:]
variable[found] assign[=] constant[False]
variable[to_inter... | keyword[def] identifier[_collapse_list_of_sets] ( identifier[self] , identifier[sets] ):
literal[string]
identifier[found] = keyword[True]
keyword[while] identifier[found] :
identifier[found] = keyword[False]
identifier[to_intersect] = keyword[None]
... | def _collapse_list_of_sets(self, sets):
"""Input is a list of sets. Merges any intersecting sets in the list"""
found = True
while found:
found = False
to_intersect = None
for i in range(len(sets)):
for j in range(len(sets)):
if i == j:
... |
def decompose(self):
"""Recursively destroys the contents of this tree."""
self.extract()
if len(self.contents) == 0:
return
current = self.contents[0]
while current is not None:
next = current.next
if isinstance(current, Tag):
... | def function[decompose, parameter[self]]:
constant[Recursively destroys the contents of this tree.]
call[name[self].extract, parameter[]]
if compare[call[name[len], parameter[name[self].contents]] equal[==] constant[0]] begin[:]
return[None]
variable[current] assign[=] call[name[... | keyword[def] identifier[decompose] ( identifier[self] ):
literal[string]
identifier[self] . identifier[extract] ()
keyword[if] identifier[len] ( identifier[self] . identifier[contents] )== literal[int] :
keyword[return]
identifier[current] = identifier[self] . ident... | def decompose(self):
"""Recursively destroys the contents of this tree."""
self.extract()
if len(self.contents) == 0:
return # depends on [control=['if'], data=[]]
current = self.contents[0]
while current is not None:
next = current.next
if isinstance(current, Tag):
... |
def direct_messages_show(self, id):
"""
Gets the direct message with the given id.
https://dev.twitter.com/docs/api/1.1/get/direct_messages/show
:param str id:
(*required*) The ID of the direct message.
:returns:
A direct message dict.
"""
... | def function[direct_messages_show, parameter[self, id]]:
constant[
Gets the direct message with the given id.
https://dev.twitter.com/docs/api/1.1/get/direct_messages/show
:param str id:
(*required*) The ID of the direct message.
:returns:
A direct mess... | keyword[def] identifier[direct_messages_show] ( identifier[self] , identifier[id] ):
literal[string]
identifier[params] ={}
identifier[set_str_param] ( identifier[params] , literal[string] , identifier[id] )
identifier[d] = identifier[self] . identifier[_get_api] ( literal[string]... | def direct_messages_show(self, id):
"""
Gets the direct message with the given id.
https://dev.twitter.com/docs/api/1.1/get/direct_messages/show
:param str id:
(*required*) The ID of the direct message.
:returns:
A direct message dict.
"""
param... |
def todict_using_struct(self, dict_struct=None, dict_post_processors=None):
"""
dict_struct:
{
'attrs': ['id', 'created_at'],
'rels': {
'merchandise': {
'attrs': ['id', 'label']
}
... | def function[todict_using_struct, parameter[self, dict_struct, dict_post_processors]]:
constant[
dict_struct:
{
'attrs': ['id', 'created_at'],
'rels': {
'merchandise': {
'attrs': ['id', 'label']
... | keyword[def] identifier[todict_using_struct] ( identifier[self] , identifier[dict_struct] = keyword[None] , identifier[dict_post_processors] = keyword[None] ):
literal[string]
identifier[dict_struct_to_use] =(
identifier[self] . identifier[_dict_struct_] keyword... | def todict_using_struct(self, dict_struct=None, dict_post_processors=None):
"""
dict_struct:
{
'attrs': ['id', 'created_at'],
'rels': {
'merchandise': {
'attrs': ['id', 'label']
}
... |
def uncurry_nested_dictionary(curried_dict):
"""
Transform dictionary from (key_a -> key_b -> float) to
(key_a, key_b) -> float
"""
result = {}
for a, a_dict in curried_dict.items():
for b, value in a_dict.items():
result[(a, b)] = value
return result | def function[uncurry_nested_dictionary, parameter[curried_dict]]:
constant[
Transform dictionary from (key_a -> key_b -> float) to
(key_a, key_b) -> float
]
variable[result] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name object at 0x7da18f721300>, <ast.Name object at 0x7da18... | keyword[def] identifier[uncurry_nested_dictionary] ( identifier[curried_dict] ):
literal[string]
identifier[result] ={}
keyword[for] identifier[a] , identifier[a_dict] keyword[in] identifier[curried_dict] . identifier[items] ():
keyword[for] identifier[b] , identifier[value] keyword[in] ... | def uncurry_nested_dictionary(curried_dict):
"""
Transform dictionary from (key_a -> key_b -> float) to
(key_a, key_b) -> float
"""
result = {}
for (a, a_dict) in curried_dict.items():
for (b, value) in a_dict.items():
result[a, b] = value # depends on [control=['for'], data... |
def parquet(self, path):
"""Loads a Parquet file stream, returning the result as a :class:`DataFrame`.
You can set the following Parquet-specific option(s) for reading Parquet files:
* ``mergeSchema``: sets whether we should merge schemas collected from all \
Parquet part-fi... | def function[parquet, parameter[self, path]]:
constant[Loads a Parquet file stream, returning the result as a :class:`DataFrame`.
You can set the following Parquet-specific option(s) for reading Parquet files:
* ``mergeSchema``: sets whether we should merge schemas collected from all ... | keyword[def] identifier[parquet] ( identifier[self] , identifier[path] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[path] , identifier[basestring] ):
keyword[return] identifier[self] . identifier[_df] ( identifier[self] . identifier[_jreader] . identifier[parque... | def parquet(self, path):
"""Loads a Parquet file stream, returning the result as a :class:`DataFrame`.
You can set the following Parquet-specific option(s) for reading Parquet files:
* ``mergeSchema``: sets whether we should merge schemas collected from all Parquet part-files. T... |
def exit_cleanly(error_number=0):
"""exit_cleanly
Performs standard error notification and exiting statements as necessary. This
assures more consistent error handling within the script.
"""
default = "An Unknown error has occurred!"
descriptions = \
{22: 'An improper input error has occurred.... | def function[exit_cleanly, parameter[error_number]]:
constant[exit_cleanly
Performs standard error notification and exiting statements as necessary. This
assures more consistent error handling within the script.
]
variable[default] assign[=] constant[An Unknown error has occurred!]
variabl... | keyword[def] identifier[exit_cleanly] ( identifier[error_number] = literal[int] ):
literal[string]
identifier[default] = literal[string]
identifier[descriptions] ={ literal[int] : literal[string] ,
literal[int] : literal[string] ,
literal[int] : literal[string] }
keyword[try] :
... | def exit_cleanly(error_number=0):
"""exit_cleanly
Performs standard error notification and exiting statements as necessary. This
assures more consistent error handling within the script.
"""
default = 'An Unknown error has occurred!'
descriptions = {22: 'An improper input error has occurred. Please s... |
def _connect(self):
""" Connect to the remote if not already connected. """
if not self.connected.is_set():
try:
self.lock.acquire()
# Another thread may have connected while we were
# waiting to acquire the lock
if not self.con... | def function[_connect, parameter[self]]:
constant[ Connect to the remote if not already connected. ]
if <ast.UnaryOp object at 0x7da1b1019ab0> begin[:]
<ast.Try object at 0x7da1b1018d60> | keyword[def] identifier[_connect] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[connected] . identifier[is_set] ():
keyword[try] :
identifier[self] . identifier[lock] . identifier[acquire] ()
... | def _connect(self):
""" Connect to the remote if not already connected. """
if not self.connected.is_set():
try:
self.lock.acquire()
# Another thread may have connected while we were
# waiting to acquire the lock
if not self.connected.is_set():
... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'document') and self.document is not None:
_dict['document'] = self.document._to_dict()
if hasattr(self, 'model_id') and self.model_id is not None:
_dict['model... | def function[_to_dict, parameter[self]]:
constant[Return a json dictionary representing this model.]
variable[_dict] assign[=] dictionary[[], []]
if <ast.BoolOp object at 0x7da204623070> begin[:]
call[name[_dict]][constant[document]] assign[=] call[name[self].document._to_dict, p... | keyword[def] identifier[_to_dict] ( identifier[self] ):
literal[string]
identifier[_dict] ={}
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ) keyword[and] identifier[self] . identifier[document] keyword[is] keyword[not] keyword[None] :
identifier[_d... | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'document') and self.document is not None:
_dict['document'] = self.document._to_dict() # depends on [control=['if'], data=[]]
if hasattr(self, 'model_id') and self.model_id is not None:
... |
def _condition_number(self):
"""Condition number of x; ratio of largest to smallest eigenvalue."""
ev = np.linalg.eig(np.matmul(self.xwins.swapaxes(1, 2), self.xwins))[0]
return np.sqrt(ev.max(axis=1) / ev.min(axis=1)) | def function[_condition_number, parameter[self]]:
constant[Condition number of x; ratio of largest to smallest eigenvalue.]
variable[ev] assign[=] call[call[name[np].linalg.eig, parameter[call[name[np].matmul, parameter[call[name[self].xwins.swapaxes, parameter[constant[1], constant[2]]], name[self].xwi... | keyword[def] identifier[_condition_number] ( identifier[self] ):
literal[string]
identifier[ev] = identifier[np] . identifier[linalg] . identifier[eig] ( identifier[np] . identifier[matmul] ( identifier[self] . identifier[xwins] . identifier[swapaxes] ( literal[int] , literal[int] ), identifier[s... | def _condition_number(self):
"""Condition number of x; ratio of largest to smallest eigenvalue."""
ev = np.linalg.eig(np.matmul(self.xwins.swapaxes(1, 2), self.xwins))[0]
return np.sqrt(ev.max(axis=1) / ev.min(axis=1)) |
def make_all_dirs(path, mode=0o777):
"""
Ensure local dir, with all its parent dirs, are created.
Unlike os.makedirs(), will not fail if the path already exists.
"""
# Avoid races inherent to doing this in two steps (check then create).
# Python 3 has exist_ok but the approach below works for Python 2+3.
... | def function[make_all_dirs, parameter[path, mode]]:
constant[
Ensure local dir, with all its parent dirs, are created.
Unlike os.makedirs(), will not fail if the path already exists.
]
<ast.Try object at 0x7da1b04ed420>
return[name[path]] | keyword[def] identifier[make_all_dirs] ( identifier[path] , identifier[mode] = literal[int] ):
literal[string]
keyword[try] :
identifier[os] . identifier[makedirs] ( identifier[path] , identifier[mode] = identifier[mode] )
keyword[except] identifier[OSError] keyword[as] identifier[e] :
... | def make_all_dirs(path, mode=511):
"""
Ensure local dir, with all its parent dirs, are created.
Unlike os.makedirs(), will not fail if the path already exists.
"""
# Avoid races inherent to doing this in two steps (check then create).
# Python 3 has exist_ok but the approach below works for Python 2+3... |
def SCG(f, gradf, x, optargs=(), maxiters=500, max_f_eval=np.inf, xtol=None, ftol=None, gtol=None):
"""
Optimisation through Scaled Conjugate Gradients (SCG)
f: the objective function
gradf : the gradient function (should return a 1D np.ndarray)
x : the initial condition
Returns
x the opti... | def function[SCG, parameter[f, gradf, x, optargs, maxiters, max_f_eval, xtol, ftol, gtol]]:
constant[
Optimisation through Scaled Conjugate Gradients (SCG)
f: the objective function
gradf : the gradient function (should return a 1D np.ndarray)
x : the initial condition
Returns
x the op... | keyword[def] identifier[SCG] ( identifier[f] , identifier[gradf] , identifier[x] , identifier[optargs] =(), identifier[maxiters] = literal[int] , identifier[max_f_eval] = identifier[np] . identifier[inf] , identifier[xtol] = keyword[None] , identifier[ftol] = keyword[None] , identifier[gtol] = keyword[None] ):
l... | def SCG(f, gradf, x, optargs=(), maxiters=500, max_f_eval=np.inf, xtol=None, ftol=None, gtol=None):
"""
Optimisation through Scaled Conjugate Gradients (SCG)
f: the objective function
gradf : the gradient function (should return a 1D np.ndarray)
x : the initial condition
Returns
x the opti... |
def field2choices(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for valid choices definition
:param Field field: A marshmallow field.
:rtype: dict
"""
attributes = {}
comparable = [
validator.comparable
for validato... | def function[field2choices, parameter[self, field]]:
constant[Return the dictionary of OpenAPI field attributes for valid choices definition
:param Field field: A marshmallow field.
:rtype: dict
]
variable[attributes] assign[=] dictionary[[], []]
variable[comparable] ass... | keyword[def] identifier[field2choices] ( identifier[self] , identifier[field] ,** identifier[kwargs] ):
literal[string]
identifier[attributes] ={}
identifier[comparable] =[
identifier[validator] . identifier[comparable]
keyword[for] identifier[validator] keyword[in] ... | def field2choices(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for valid choices definition
:param Field field: A marshmallow field.
:rtype: dict
"""
attributes = {}
comparable = [validator.comparable for validator in field.validators if hasattr(valid... |
def kinks(path, tol=1e-8):
"""returns indices of segments that start on a non-differentiable joint."""
kink_list = []
for idx in range(len(path)):
if idx == 0 and not path.isclosed():
continue
try:
u = path[(idx - 1) % len(path)].unit_tangent(1)
v = path[i... | def function[kinks, parameter[path, tol]]:
constant[returns indices of segments that start on a non-differentiable joint.]
variable[kink_list] assign[=] list[[]]
for taget[name[idx]] in starred[call[name[range], parameter[call[name[len], parameter[name[path]]]]]] begin[:]
if <ast... | keyword[def] identifier[kinks] ( identifier[path] , identifier[tol] = literal[int] ):
literal[string]
identifier[kink_list] =[]
keyword[for] identifier[idx] keyword[in] identifier[range] ( identifier[len] ( identifier[path] )):
keyword[if] identifier[idx] == literal[int] keyword[and] ke... | def kinks(path, tol=1e-08):
"""returns indices of segments that start on a non-differentiable joint."""
kink_list = []
for idx in range(len(path)):
if idx == 0 and (not path.isclosed()):
continue # depends on [control=['if'], data=[]]
try:
u = path[(idx - 1) % len(pa... |
def _glsa_list_process_output(output):
'''
Process output from glsa_check_list into a dict
Returns a dict containing the glsa id, description, status, and CVEs
'''
ret = dict()
for line in output:
try:
glsa_id, status, desc = line.split(None, 2)
if 'U' in status:... | def function[_glsa_list_process_output, parameter[output]]:
constant[
Process output from glsa_check_list into a dict
Returns a dict containing the glsa id, description, status, and CVEs
]
variable[ret] assign[=] call[name[dict], parameter[]]
for taget[name[line]] in starred[name[ou... | keyword[def] identifier[_glsa_list_process_output] ( identifier[output] ):
literal[string]
identifier[ret] = identifier[dict] ()
keyword[for] identifier[line] keyword[in] identifier[output] :
keyword[try] :
identifier[glsa_id] , identifier[status] , identifier[desc] = identifi... | def _glsa_list_process_output(output):
"""
Process output from glsa_check_list into a dict
Returns a dict containing the glsa id, description, status, and CVEs
"""
ret = dict()
for line in output:
try:
(glsa_id, status, desc) = line.split(None, 2)
if 'U' in statu... |
def update_line(self, trace, xdata, ydata, side='left', draw=False,
update_limits=True):
""" update a single trace, for faster redraw """
x = self.conf.get_mpl_line(trace)
x.set_data(xdata, ydata)
datarange = [xdata.min(), xdata.max(), ydata.min(), ydata.max()]
... | def function[update_line, parameter[self, trace, xdata, ydata, side, draw, update_limits]]:
constant[ update a single trace, for faster redraw ]
variable[x] assign[=] call[name[self].conf.get_mpl_line, parameter[name[trace]]]
call[name[x].set_data, parameter[name[xdata], name[ydata]]]
va... | keyword[def] identifier[update_line] ( identifier[self] , identifier[trace] , identifier[xdata] , identifier[ydata] , identifier[side] = literal[string] , identifier[draw] = keyword[False] ,
identifier[update_limits] = keyword[True] ):
literal[string]
identifier[x] = identifier[self] . identifier... | def update_line(self, trace, xdata, ydata, side='left', draw=False, update_limits=True):
""" update a single trace, for faster redraw """
x = self.conf.get_mpl_line(trace)
x.set_data(xdata, ydata)
datarange = [xdata.min(), xdata.max(), ydata.min(), ydata.max()]
self.conf.set_trace_datarange(datarang... |
def transitions(self, return_matrix=True):
"""Returns the routing probabilities for each vertex in the
graph.
Parameters
----------
return_matrix : bool (optional, the default is ``True``)
Specifies whether an :class:`~numpy.ndarray` is returned.
If ``Fal... | def function[transitions, parameter[self, return_matrix]]:
constant[Returns the routing probabilities for each vertex in the
graph.
Parameters
----------
return_matrix : bool (optional, the default is ``True``)
Specifies whether an :class:`~numpy.ndarray` is returned... | keyword[def] identifier[transitions] ( identifier[self] , identifier[return_matrix] = keyword[True] ):
literal[string]
keyword[if] identifier[return_matrix] :
identifier[mat] = identifier[np] . identifier[zeros] (( identifier[self] . identifier[nV] , identifier[self] . identifier[nV] ... | def transitions(self, return_matrix=True):
"""Returns the routing probabilities for each vertex in the
graph.
Parameters
----------
return_matrix : bool (optional, the default is ``True``)
Specifies whether an :class:`~numpy.ndarray` is returned.
If ``False``... |
def run(self):
"""
executes the script
:return: boolean if execution of script finished succesfully
"""
self.log_data.clear()
self._plot_refresh = True # flag that requests that plot axes are refreshed when self.plot is called next time
self.is_running = True
... | def function[run, parameter[self]]:
constant[
executes the script
:return: boolean if execution of script finished succesfully
]
call[name[self].log_data.clear, parameter[]]
name[self]._plot_refresh assign[=] constant[True]
name[self].is_running assign[=] constant... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
identifier[self] . identifier[log_data] . identifier[clear] ()
identifier[self] . identifier[_plot_refresh] = keyword[True]
identifier[self] . identifier[is_running] = keyword[True]
identifier[self] . id... | def run(self):
"""
executes the script
:return: boolean if execution of script finished succesfully
"""
self.log_data.clear()
self._plot_refresh = True # flag that requests that plot axes are refreshed when self.plot is called next time
self.is_running = True
self.start_time... |
def cancel(self):
"""Cancel a running :meth:`iterconsume` session."""
if self.channel_open:
try:
self.backend.cancel(self.consumer_tag)
except KeyError:
pass | def function[cancel, parameter[self]]:
constant[Cancel a running :meth:`iterconsume` session.]
if name[self].channel_open begin[:]
<ast.Try object at 0x7da1b0facc70> | keyword[def] identifier[cancel] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[channel_open] :
keyword[try] :
identifier[self] . identifier[backend] . identifier[cancel] ( identifier[self] . identifier[consumer_tag] )
keyw... | def cancel(self):
"""Cancel a running :meth:`iterconsume` session."""
if self.channel_open:
try:
self.backend.cancel(self.consumer_tag) # depends on [control=['try'], data=[]]
except KeyError:
pass # depends on [control=['except'], data=[]] # depends on [control=['if']... |
def float_to_knx2(floatval):
"""Convert a float to a 2 byte KNX float value"""
if floatval < -671088.64 or floatval > 670760.96:
raise KNXException("float {} out of valid range".format(floatval))
floatval = floatval * 100
i = 0
for i in range(0, 15):
exp = pow(2, i)
if ((f... | def function[float_to_knx2, parameter[floatval]]:
constant[Convert a float to a 2 byte KNX float value]
if <ast.BoolOp object at 0x7da18ede7d30> begin[:]
<ast.Raise object at 0x7da18ede6d10>
variable[floatval] assign[=] binary_operation[name[floatval] * constant[100]]
variable[i]... | keyword[def] identifier[float_to_knx2] ( identifier[floatval] ):
literal[string]
keyword[if] identifier[floatval] <- literal[int] keyword[or] identifier[floatval] > literal[int] :
keyword[raise] identifier[KNXException] ( literal[string] . identifier[format] ( identifier[floatval] ))
id... | def float_to_knx2(floatval):
"""Convert a float to a 2 byte KNX float value"""
if floatval < -671088.64 or floatval > 670760.96:
raise KNXException('float {} out of valid range'.format(floatval)) # depends on [control=['if'], data=[]]
floatval = floatval * 100
i = 0
for i in range(0, 15):
... |
def headers(self):
"""
Return only the headers as Python object
"""
d = {}
for k, v in self.message.items():
d[k] = decode_header_part(v)
return d | def function[headers, parameter[self]]:
constant[
Return only the headers as Python object
]
variable[d] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name object at 0x7da1b0719f90>, <ast.Name object at 0x7da1b0719480>]]] in starred[call[name[self].message.items, parameter[]... | keyword[def] identifier[headers] ( identifier[self] ):
literal[string]
identifier[d] ={}
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[self] . identifier[message] . identifier[items] ():
identifier[d] [ identifier[k] ]= identifier[decode_header_part] ( i... | def headers(self):
"""
Return only the headers as Python object
"""
d = {}
for (k, v) in self.message.items():
d[k] = decode_header_part(v) # depends on [control=['for'], data=[]]
return d |
def toxml(self, encoding="UTF-8"):
""" Return the manifest as XML """
domtree = self.todom()
# WARNING: The XML declaration has to follow the order
# version-encoding-standalone (standalone being optional), otherwise
# if it is embedded in an exe the exe will fail to launch!
... | def function[toxml, parameter[self, encoding]]:
constant[ Return the manifest as XML ]
variable[domtree] assign[=] call[name[self].todom, parameter[]]
variable[xmlstr] assign[=] call[call[name[domtree].toxml, parameter[name[encoding]]].replace, parameter[binary_operation[constant[<?xml version="... | keyword[def] identifier[toxml] ( identifier[self] , identifier[encoding] = literal[string] ):
literal[string]
identifier[domtree] = identifier[self] . identifier[todom] ()
identifier[xmlstr] = identifier[domtree] . identifier[toxml] ( identifier[encoding... | def toxml(self, encoding='UTF-8'):
""" Return the manifest as XML """
domtree = self.todom() # WARNING: The XML declaration has to follow the order
# version-encoding-standalone (standalone being optional), otherwise
# if it is embedded in an exe the exe will fail to launch!
# ('application conf... |
def _check_log_scale(base, sides, scales, coord):
"""
Check the log transforms
Parameters
----------
base : float or None
Base of the logarithm in which the ticks will be
calculated. If ``None``, the base of the log transform
the scale will be... | def function[_check_log_scale, parameter[base, sides, scales, coord]]:
constant[
Check the log transforms
Parameters
----------
base : float or None
Base of the logarithm in which the ticks will be
calculated. If ``None``, the base of the log transform
... | keyword[def] identifier[_check_log_scale] ( identifier[base] , identifier[sides] , identifier[scales] , identifier[coord] ):
literal[string]
keyword[def] identifier[is_log] ( identifier[trans] ):
keyword[return] ( identifier[trans] . identifier[__class__] . identifier[__name__] . iden... | def _check_log_scale(base, sides, scales, coord):
"""
Check the log transforms
Parameters
----------
base : float or None
Base of the logarithm in which the ticks will be
calculated. If ``None``, the base of the log transform
the scale will be use... |
def read_namespaced_stateful_set(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_stateful_set # noqa: E501
read the specified StatefulSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_re... | def function[read_namespaced_stateful_set, parameter[self, name, namespace]]:
constant[read_namespaced_stateful_set # noqa: E501
read the specified StatefulSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async... | keyword[def] identifier[read_namespaced_stateful_set] ( identifier[self] , identifier[name] , identifier[namespace] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
... | def read_namespaced_stateful_set(self, name, namespace, **kwargs): # noqa: E501
"read_namespaced_stateful_set # noqa: E501\n\n read the specified StatefulSet # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=... |
def isOnSiliconList(self, ra_deg, dec_deg, padding_pix=DEFAULT_PADDING):
"""similar to isOnSilicon() but takes lists as input"""
ch, col, row = self.getChannelColRowList(ra_deg, dec_deg)
out = np.zeros(len(ch), dtype=bool)
for channel in set(ch):
mask = (ch == channel)
... | def function[isOnSiliconList, parameter[self, ra_deg, dec_deg, padding_pix]]:
constant[similar to isOnSilicon() but takes lists as input]
<ast.Tuple object at 0x7da1b0a4c310> assign[=] call[name[self].getChannelColRowList, parameter[name[ra_deg], name[dec_deg]]]
variable[out] assign[=] call[name... | keyword[def] identifier[isOnSiliconList] ( identifier[self] , identifier[ra_deg] , identifier[dec_deg] , identifier[padding_pix] = identifier[DEFAULT_PADDING] ):
literal[string]
identifier[ch] , identifier[col] , identifier[row] = identifier[self] . identifier[getChannelColRowList] ( identifier[ra_... | def isOnSiliconList(self, ra_deg, dec_deg, padding_pix=DEFAULT_PADDING):
"""similar to isOnSilicon() but takes lists as input"""
(ch, col, row) = self.getChannelColRowList(ra_deg, dec_deg)
out = np.zeros(len(ch), dtype=bool)
for channel in set(ch):
mask = ch == channel
if channel in self... |
def pretty_xml(data):
"""Return a pretty formated xml
"""
parsed_string = minidom.parseString(data.decode('utf-8'))
return parsed_string.toprettyxml(indent='\t', encoding='utf-8') | def function[pretty_xml, parameter[data]]:
constant[Return a pretty formated xml
]
variable[parsed_string] assign[=] call[name[minidom].parseString, parameter[call[name[data].decode, parameter[constant[utf-8]]]]]
return[call[name[parsed_string].toprettyxml, parameter[]]] | keyword[def] identifier[pretty_xml] ( identifier[data] ):
literal[string]
identifier[parsed_string] = identifier[minidom] . identifier[parseString] ( identifier[data] . identifier[decode] ( literal[string] ))
keyword[return] identifier[parsed_string] . identifier[toprettyxml] ( identifier[indent] = l... | def pretty_xml(data):
"""Return a pretty formated xml
"""
parsed_string = minidom.parseString(data.decode('utf-8'))
return parsed_string.toprettyxml(indent='\t', encoding='utf-8') |
def solve_equilibrium_point(self, analyzer1, analyzer2,
delu_dict={}, delu_default=0, units="nanometers"):
"""
Gives the radial size of two particles where equilibrium is reached
between both particles. NOTE: the solution here is not the same
as th... | def function[solve_equilibrium_point, parameter[self, analyzer1, analyzer2, delu_dict, delu_default, units]]:
constant[
Gives the radial size of two particles where equilibrium is reached
between both particles. NOTE: the solution here is not the same
as the solution visualized i... | keyword[def] identifier[solve_equilibrium_point] ( identifier[self] , identifier[analyzer1] , identifier[analyzer2] ,
identifier[delu_dict] ={}, identifier[delu_default] = literal[int] , identifier[units] = literal[string] ):
literal[string]
identifier[wulff1] = identifier[analyzer1] . i... | def solve_equilibrium_point(self, analyzer1, analyzer2, delu_dict={}, delu_default=0, units='nanometers'):
"""
Gives the radial size of two particles where equilibrium is reached
between both particles. NOTE: the solution here is not the same
as the solution visualized in the plot be... |
def xfrange(start, stop, step=1, maxSize=-1):
"""
Returns a generator that yields the frames from start to stop, inclusive.
In other words it adds or subtracts a frame, as necessary, to return the
stop value as well, if the stepped range would touch that value.
Args:
start (int):
st... | def function[xfrange, parameter[start, stop, step, maxSize]]:
constant[
Returns a generator that yields the frames from start to stop, inclusive.
In other words it adds or subtracts a frame, as necessary, to return the
stop value as well, if the stepped range would touch that value.
Args:
... | keyword[def] identifier[xfrange] ( identifier[start] , identifier[stop] , identifier[step] = literal[int] , identifier[maxSize] =- literal[int] ):
literal[string]
keyword[if] identifier[start] <= identifier[stop] :
identifier[stop] , identifier[step] = identifier[stop] + literal[int] , identifier... | def xfrange(start, stop, step=1, maxSize=-1):
"""
Returns a generator that yields the frames from start to stop, inclusive.
In other words it adds or subtracts a frame, as necessary, to return the
stop value as well, if the stepped range would touch that value.
Args:
start (int):
st... |
def sign(self, value):
"""Signs the given string."""
return value + want_bytes(self.sep) + self.get_signature(value) | def function[sign, parameter[self, value]]:
constant[Signs the given string.]
return[binary_operation[binary_operation[name[value] + call[name[want_bytes], parameter[name[self].sep]]] + call[name[self].get_signature, parameter[name[value]]]]] | keyword[def] identifier[sign] ( identifier[self] , identifier[value] ):
literal[string]
keyword[return] identifier[value] + identifier[want_bytes] ( identifier[self] . identifier[sep] )+ identifier[self] . identifier[get_signature] ( identifier[value] ) | def sign(self, value):
"""Signs the given string."""
return value + want_bytes(self.sep) + self.get_signature(value) |
def initialize_hooks(self):
"""
Create SessionRunHooks for all callbacks, and hook it onto `self.sess` to create `self.hooked_sess`.
A new trainer may override this method to create multiple groups of hooks,
which can be useful when the training is not done by a single `train_op`.
... | def function[initialize_hooks, parameter[self]]:
constant[
Create SessionRunHooks for all callbacks, and hook it onto `self.sess` to create `self.hooked_sess`.
A new trainer may override this method to create multiple groups of hooks,
which can be useful when the training is not done by... | keyword[def] identifier[initialize_hooks] ( identifier[self] ):
literal[string]
identifier[hooks] = identifier[self] . identifier[_callbacks] . identifier[get_hooks] ()
identifier[self] . identifier[hooked_sess] = identifier[tfv1] . identifier[train] . identifier[MonitoredSession] (
... | def initialize_hooks(self):
"""
Create SessionRunHooks for all callbacks, and hook it onto `self.sess` to create `self.hooked_sess`.
A new trainer may override this method to create multiple groups of hooks,
which can be useful when the training is not done by a single `train_op`.
"... |
def filter_taxa(records, taxids, unclassified=False, discard=False):
'''
Selectively include or discard specified taxon IDs from tictax annotated FASTA/Qs
Filters all children of specified taxon IDs
Returns subset of input SeqRecords
Taxon IDs of 1 and 2 are considered unclassified
'''
taxi... | def function[filter_taxa, parameter[records, taxids, unclassified, discard]]:
constant[
Selectively include or discard specified taxon IDs from tictax annotated FASTA/Qs
Filters all children of specified taxon IDs
Returns subset of input SeqRecords
Taxon IDs of 1 and 2 are considered unclassifie... | keyword[def] identifier[filter_taxa] ( identifier[records] , identifier[taxids] , identifier[unclassified] = keyword[False] , identifier[discard] = keyword[False] ):
literal[string]
identifier[taxids] = identifier[set] ( identifier[taxids] )
identifier[kept_records] =[]
identifier[ncbi] = identif... | def filter_taxa(records, taxids, unclassified=False, discard=False):
"""
Selectively include or discard specified taxon IDs from tictax annotated FASTA/Qs
Filters all children of specified taxon IDs
Returns subset of input SeqRecords
Taxon IDs of 1 and 2 are considered unclassified
"""
taxi... |
def split_floats(op, min_num, value):
"""Split `value`, a list of numbers as a string, to a list of float numbers.
Also optionally insert a `l` or `L` operation depending on the operation
and the length of values.
Example: with op='m' and value='10,20 30,40,' the returned value will be
['m... | def function[split_floats, parameter[op, min_num, value]]:
constant[Split `value`, a list of numbers as a string, to a list of float numbers.
Also optionally insert a `l` or `L` operation depending on the operation
and the length of values.
Example: with op='m' and value='10,20 30,40,' the returned... | keyword[def] identifier[split_floats] ( identifier[op] , identifier[min_num] , identifier[value] ):
literal[string]
identifier[floats] =[ identifier[float] ( identifier[seq] ) keyword[for] identifier[seq] keyword[in] identifier[re] . identifier[findall] ( literal[string] , identifier[value] ) keyword[if... | def split_floats(op, min_num, value):
"""Split `value`, a list of numbers as a string, to a list of float numbers.
Also optionally insert a `l` or `L` operation depending on the operation
and the length of values.
Example: with op='m' and value='10,20 30,40,' the returned value will be
['m... |
def isglove(filepath):
""" Get the first word vector in a GloVE file and return its dimensionality or False if not a vector
>>> isglove(os.path.join(DATA_PATH, 'cats_and_dogs.txt'))
False
"""
with ensure_open(filepath, 'r') as f:
header_line = f.readline()
vector_line = f.readline(... | def function[isglove, parameter[filepath]]:
constant[ Get the first word vector in a GloVE file and return its dimensionality or False if not a vector
>>> isglove(os.path.join(DATA_PATH, 'cats_and_dogs.txt'))
False
]
with call[name[ensure_open], parameter[name[filepath], constant[r]]] begin... | keyword[def] identifier[isglove] ( identifier[filepath] ):
literal[string]
keyword[with] identifier[ensure_open] ( identifier[filepath] , literal[string] ) keyword[as] identifier[f] :
identifier[header_line] = identifier[f] . identifier[readline] ()
identifier[vector_line] = identifier... | def isglove(filepath):
""" Get the first word vector in a GloVE file and return its dimensionality or False if not a vector
>>> isglove(os.path.join(DATA_PATH, 'cats_and_dogs.txt'))
False
"""
with ensure_open(filepath, 'r') as f:
header_line = f.readline()
vector_line = f.readline()... |
def select_layout(self, layout=None):
"""Wrapper for ``$ tmux select-layout <layout>``.
Parameters
----------
layout : str, optional
string of the layout, 'even-horizontal', 'tiled', etc. Entering
None (leaving this blank) is same as ``select-layout`` with no
... | def function[select_layout, parameter[self, layout]]:
constant[Wrapper for ``$ tmux select-layout <layout>``.
Parameters
----------
layout : str, optional
string of the layout, 'even-horizontal', 'tiled', etc. Entering
None (leaving this blank) is same as ``selec... | keyword[def] identifier[select_layout] ( identifier[self] , identifier[layout] = keyword[None] ):
literal[string]
identifier[cmd] =[ literal[string] , literal[string] %( identifier[self] . identifier[get] ( literal[string] ), identifier[self] . identifier[index] )]
keyword[if] identifier... | def select_layout(self, layout=None):
"""Wrapper for ``$ tmux select-layout <layout>``.
Parameters
----------
layout : str, optional
string of the layout, 'even-horizontal', 'tiled', etc. Entering
None (leaving this blank) is same as ``select-layout`` with no
... |
def _compare_by_version(path1, path2):
"""Returns the current/latest learned path.
Checks if given paths are from same source/peer and then compares their
version number to determine which path is received later. If paths are from
different source/peer return None.
"""
if path1.source == path2.... | def function[_compare_by_version, parameter[path1, path2]]:
constant[Returns the current/latest learned path.
Checks if given paths are from same source/peer and then compares their
version number to determine which path is received later. If paths are from
different source/peer return None.
]
... | keyword[def] identifier[_compare_by_version] ( identifier[path1] , identifier[path2] ):
literal[string]
keyword[if] identifier[path1] . identifier[source] == identifier[path2] . identifier[source] :
keyword[if] identifier[path1] . identifier[source_version_num] > identifier[path2] . identifier[s... | def _compare_by_version(path1, path2):
"""Returns the current/latest learned path.
Checks if given paths are from same source/peer and then compares their
version number to determine which path is received later. If paths are from
different source/peer return None.
"""
if path1.source == path2.... |
def _call(self, f, out):
"""Implement ``self(vf, out)``."""
for vfi, oi, ran_wi, dom_wi in zip(self.vecfield, out,
self.__ran_weights, self.weights):
vfi.multiply(f, out=oi)
if not np.isclose(ran_wi, dom_wi):
oi *= dom_wi... | def function[_call, parameter[self, f, out]]:
constant[Implement ``self(vf, out)``.]
for taget[tuple[[<ast.Name object at 0x7da1b1e5c400>, <ast.Name object at 0x7da1b1e5c640>, <ast.Name object at 0x7da1b1e5e5c0>, <ast.Name object at 0x7da1b1e5dc30>]]] in starred[call[name[zip], parameter[name[self].vecf... | keyword[def] identifier[_call] ( identifier[self] , identifier[f] , identifier[out] ):
literal[string]
keyword[for] identifier[vfi] , identifier[oi] , identifier[ran_wi] , identifier[dom_wi] keyword[in] identifier[zip] ( identifier[self] . identifier[vecfield] , identifier[out] ,
identi... | def _call(self, f, out):
"""Implement ``self(vf, out)``."""
for (vfi, oi, ran_wi, dom_wi) in zip(self.vecfield, out, self.__ran_weights, self.weights):
vfi.multiply(f, out=oi)
if not np.isclose(ran_wi, dom_wi):
oi *= dom_wi / ran_wi # depends on [control=['if'], data=[]] # depends ... |
def raise_check_result(self):
"""Raise ACTIVE CHECK RESULT entry
Example : "ACTIVE HOST CHECK: server;DOWN;HARD;1;I don't know what to say..."
:return: None
"""
if not self.__class__.log_active_checks:
return
log_level = 'info'
if self.state == 'DOWN... | def function[raise_check_result, parameter[self]]:
constant[Raise ACTIVE CHECK RESULT entry
Example : "ACTIVE HOST CHECK: server;DOWN;HARD;1;I don't know what to say..."
:return: None
]
if <ast.UnaryOp object at 0x7da20c7cbf40> begin[:]
return[None]
variable[log_... | keyword[def] identifier[raise_check_result] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[__class__] . identifier[log_active_checks] :
keyword[return]
identifier[log_level] = literal[string]
keyword[if] identifier[s... | def raise_check_result(self):
"""Raise ACTIVE CHECK RESULT entry
Example : "ACTIVE HOST CHECK: server;DOWN;HARD;1;I don't know what to say..."
:return: None
"""
if not self.__class__.log_active_checks:
return # depends on [control=['if'], data=[]]
log_level = 'info'
if ... |
def _rescale(ar):
"""Shift and rescale array ar to the interval [-1, 1]"""
max = np.nanmax(ar)
min = np.nanmin(ar)
midpoint = (max + min) / 2.0
return 2.0 * (ar - midpoint) / (max - min) | def function[_rescale, parameter[ar]]:
constant[Shift and rescale array ar to the interval [-1, 1]]
variable[max] assign[=] call[name[np].nanmax, parameter[name[ar]]]
variable[min] assign[=] call[name[np].nanmin, parameter[name[ar]]]
variable[midpoint] assign[=] binary_operation[binary_o... | keyword[def] identifier[_rescale] ( identifier[ar] ):
literal[string]
identifier[max] = identifier[np] . identifier[nanmax] ( identifier[ar] )
identifier[min] = identifier[np] . identifier[nanmin] ( identifier[ar] )
identifier[midpoint] =( identifier[max] + identifier[min] )/ literal[int]
k... | def _rescale(ar):
"""Shift and rescale array ar to the interval [-1, 1]"""
max = np.nanmax(ar)
min = np.nanmin(ar)
midpoint = (max + min) / 2.0
return 2.0 * (ar - midpoint) / (max - min) |
def get_config(self):
"""Return configurations of EpsGreedyQPolicy
# Returns
Dict of config
"""
config = super(EpsGreedyQPolicy, self).get_config()
config['eps'] = self.eps
return config | def function[get_config, parameter[self]]:
constant[Return configurations of EpsGreedyQPolicy
# Returns
Dict of config
]
variable[config] assign[=] call[call[name[super], parameter[name[EpsGreedyQPolicy], name[self]]].get_config, parameter[]]
call[name[config]][const... | keyword[def] identifier[get_config] ( identifier[self] ):
literal[string]
identifier[config] = identifier[super] ( identifier[EpsGreedyQPolicy] , identifier[self] ). identifier[get_config] ()
identifier[config] [ literal[string] ]= identifier[self] . identifier[eps]
keyword[retur... | def get_config(self):
"""Return configurations of EpsGreedyQPolicy
# Returns
Dict of config
"""
config = super(EpsGreedyQPolicy, self).get_config()
config['eps'] = self.eps
return config |
def on_copy_remote(self, pair):
"""Called when the remote resource should be copied to local."""
status = pair.local_classification
self._log_action("copy", status, "<", pair.remote) | def function[on_copy_remote, parameter[self, pair]]:
constant[Called when the remote resource should be copied to local.]
variable[status] assign[=] name[pair].local_classification
call[name[self]._log_action, parameter[constant[copy], name[status], constant[<], name[pair].remote]] | keyword[def] identifier[on_copy_remote] ( identifier[self] , identifier[pair] ):
literal[string]
identifier[status] = identifier[pair] . identifier[local_classification]
identifier[self] . identifier[_log_action] ( literal[string] , identifier[status] , literal[string] , identifier[pair] ... | def on_copy_remote(self, pair):
"""Called when the remote resource should be copied to local."""
status = pair.local_classification
self._log_action('copy', status, '<', pair.remote) |
def _convert_to_boolean(self, value):
"""Return a boolean value translating from other types if necessary.
"""
if value.lower() not in self.BOOLEAN_STATES:
raise ValueError('Not a boolean: %s' % value)
return self.BOOLEAN_STATES[value.lower()] | def function[_convert_to_boolean, parameter[self, value]]:
constant[Return a boolean value translating from other types if necessary.
]
if compare[call[name[value].lower, parameter[]] <ast.NotIn object at 0x7da2590d7190> name[self].BOOLEAN_STATES] begin[:]
<ast.Raise object at 0x7da2047e... | keyword[def] identifier[_convert_to_boolean] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[value] . identifier[lower] () keyword[not] keyword[in] identifier[self] . identifier[BOOLEAN_STATES] :
keyword[raise] identifier[ValueError] ( literal[strin... | def _convert_to_boolean(self, value):
"""Return a boolean value translating from other types if necessary.
"""
if value.lower() not in self.BOOLEAN_STATES:
raise ValueError('Not a boolean: %s' % value) # depends on [control=['if'], data=[]]
return self.BOOLEAN_STATES[value.lower()] |
def is_state(self, status):
# pylint: disable=too-many-return-statements
"""Return True if status match the current service status
:param status: status to compare ( "o", "c", "w", "u", "x"). Usually comes from config files
:type status: str
:return: True if status <=> self.stat... | def function[is_state, parameter[self, status]]:
constant[Return True if status match the current service status
:param status: status to compare ( "o", "c", "w", "u", "x"). Usually comes from config files
:type status: str
:return: True if status <=> self.status, otherwise False
... | keyword[def] identifier[is_state] ( identifier[self] , identifier[status] ):
literal[string]
keyword[if] identifier[status] == identifier[self] . identifier[state] :
keyword[return] keyword[True]
keyword[if] identifier[status] == literal[string] keyword[and]... | def is_state(self, status):
# pylint: disable=too-many-return-statements
'Return True if status match the current service status\n\n :param status: status to compare ( "o", "c", "w", "u", "x"). Usually comes from config files\n :type status: str\n :return: True if status <=> self.status, ot... |
def _zerosamestates(self, A):
"""
zeros out states that should be identical
REQUIRED ARGUMENTS
A: the matrix whose entries are to be zeroed.
"""
for pair in self.samestates:
A[pair[0], pair[1]] = 0
A[pair[1], pair[0]] = 0 | def function[_zerosamestates, parameter[self, A]]:
constant[
zeros out states that should be identical
REQUIRED ARGUMENTS
A: the matrix whose entries are to be zeroed.
]
for taget[name[pair]] in starred[name[self].samestates] begin[:]
call[name[A]][tupl... | keyword[def] identifier[_zerosamestates] ( identifier[self] , identifier[A] ):
literal[string]
keyword[for] identifier[pair] keyword[in] identifier[self] . identifier[samestates] :
identifier[A] [ identifier[pair] [ literal[int] ], identifier[pair] [ literal[int] ]]= literal[int]
... | def _zerosamestates(self, A):
"""
zeros out states that should be identical
REQUIRED ARGUMENTS
A: the matrix whose entries are to be zeroed.
"""
for pair in self.samestates:
A[pair[0], pair[1]] = 0
A[pair[1], pair[0]] = 0 # depends on [control=['for'], data=['... |
def from_uri(cls, uri, socket_timeout=None, auto_decode=False):
"""Construct a synchronous Beanstalk Client from a URI.
The URI may be of the form beanstalk://host:port or beanstalkd://host:port
IPv6 literals must be wrapped in brackets as per RFC 2732.
"""
parts = six.moves.ur... | def function[from_uri, parameter[cls, uri, socket_timeout, auto_decode]]:
constant[Construct a synchronous Beanstalk Client from a URI.
The URI may be of the form beanstalk://host:port or beanstalkd://host:port
IPv6 literals must be wrapped in brackets as per RFC 2732.
]
variab... | keyword[def] identifier[from_uri] ( identifier[cls] , identifier[uri] , identifier[socket_timeout] = keyword[None] , identifier[auto_decode] = keyword[False] ):
literal[string]
identifier[parts] = identifier[six] . identifier[moves] . identifier[urllib] . identifier[parse] . identifier[urlparse] ( ... | def from_uri(cls, uri, socket_timeout=None, auto_decode=False):
"""Construct a synchronous Beanstalk Client from a URI.
The URI may be of the form beanstalk://host:port or beanstalkd://host:port
IPv6 literals must be wrapped in brackets as per RFC 2732.
"""
parts = six.moves.urllib.par... |
def Deserialize(self, reader):
"""
Deserialize full object.
Args:
reader (neo.IO.BinaryReader):
"""
super(Header, self).Deserialize(reader)
if reader.ReadByte() != 0:
raise Exception('Incorrect Header Format') | def function[Deserialize, parameter[self, reader]]:
constant[
Deserialize full object.
Args:
reader (neo.IO.BinaryReader):
]
call[call[name[super], parameter[name[Header], name[self]]].Deserialize, parameter[name[reader]]]
if compare[call[name[reader].ReadByt... | keyword[def] identifier[Deserialize] ( identifier[self] , identifier[reader] ):
literal[string]
identifier[super] ( identifier[Header] , identifier[self] ). identifier[Deserialize] ( identifier[reader] )
keyword[if] identifier[reader] . identifier[ReadByte] ()!= literal[int] :
... | def Deserialize(self, reader):
"""
Deserialize full object.
Args:
reader (neo.IO.BinaryReader):
"""
super(Header, self).Deserialize(reader)
if reader.ReadByte() != 0:
raise Exception('Incorrect Header Format') # depends on [control=['if'], data=[]] |
def map(self, callback):
"""
Run a map over each of the item.
:param callback: The map function
:type callback: callable
:rtype: Collection
"""
return self.__class__(list(map(callback, self.items))) | def function[map, parameter[self, callback]]:
constant[
Run a map over each of the item.
:param callback: The map function
:type callback: callable
:rtype: Collection
]
return[call[name[self].__class__, parameter[call[name[list], parameter[call[name[map], parameter[... | keyword[def] identifier[map] ( identifier[self] , identifier[callback] ):
literal[string]
keyword[return] identifier[self] . identifier[__class__] ( identifier[list] ( identifier[map] ( identifier[callback] , identifier[self] . identifier[items] ))) | def map(self, callback):
"""
Run a map over each of the item.
:param callback: The map function
:type callback: callable
:rtype: Collection
"""
return self.__class__(list(map(callback, self.items))) |
def _set_member_vlan(self, v, load=False):
"""
Setter method for member_vlan, mapped from YANG variable /topology_group/member_vlan (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_member_vlan is considered as a private
method. Backends looking to populate... | def function[_set_member_vlan, parameter[self, v, load]]:
constant[
Setter method for member_vlan, mapped from YANG variable /topology_group/member_vlan (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_member_vlan is considered as a private
method. Bac... | keyword[def] identifier[_set_member_vlan] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
id... | def _set_member_vlan(self, v, load=False):
"""
Setter method for member_vlan, mapped from YANG variable /topology_group/member_vlan (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_member_vlan is considered as a private
method. Backends looking to populate... |
def main():
""" Main entry point, expects doctopt arg dict as argd. """
global DEBUG
argd = docopt(USAGESTR, version=VERSIONSTR, script=SCRIPT)
DEBUG = argd['--debug']
width = parse_int(argd['--width'] or DEFAULT_WIDTH) or 1
indent = parse_int(argd['--indent'] or (argd['--INDENT'] or 0))
pr... | def function[main, parameter[]]:
constant[ Main entry point, expects doctopt arg dict as argd. ]
<ast.Global object at 0x7da18bcc9330>
variable[argd] assign[=] call[name[docopt], parameter[name[USAGESTR]]]
variable[DEBUG] assign[=] call[name[argd]][constant[--debug]]
variable[width] ... | keyword[def] identifier[main] ():
literal[string]
keyword[global] identifier[DEBUG]
identifier[argd] = identifier[docopt] ( identifier[USAGESTR] , identifier[version] = identifier[VERSIONSTR] , identifier[script] = identifier[SCRIPT] )
identifier[DEBUG] = identifier[argd] [ literal[string] ]
... | def main():
""" Main entry point, expects doctopt arg dict as argd. """
global DEBUG
argd = docopt(USAGESTR, version=VERSIONSTR, script=SCRIPT)
DEBUG = argd['--debug']
width = parse_int(argd['--width'] or DEFAULT_WIDTH) or 1
indent = parse_int(argd['--indent'] or (argd['--INDENT'] or 0))
pre... |
def work_items(self):
"""An iterable of all of WorkItems in the db.
This includes both WorkItems with and without results.
"""
cur = self._conn.cursor()
rows = cur.execute("SELECT * FROM work_items")
for row in rows:
yield _row_to_work_item(row) | def function[work_items, parameter[self]]:
constant[An iterable of all of WorkItems in the db.
This includes both WorkItems with and without results.
]
variable[cur] assign[=] call[name[self]._conn.cursor, parameter[]]
variable[rows] assign[=] call[name[cur].execute, parameter[c... | keyword[def] identifier[work_items] ( identifier[self] ):
literal[string]
identifier[cur] = identifier[self] . identifier[_conn] . identifier[cursor] ()
identifier[rows] = identifier[cur] . identifier[execute] ( literal[string] )
keyword[for] identifier[row] keyword[in] identif... | def work_items(self):
"""An iterable of all of WorkItems in the db.
This includes both WorkItems with and without results.
"""
cur = self._conn.cursor()
rows = cur.execute('SELECT * FROM work_items')
for row in rows:
yield _row_to_work_item(row) # depends on [control=['for'], d... |
def splitset(num_trials, skipstep=None):
""" Split-set cross validation
Use half the trials for training, and the other half for testing. Then
repeat the other way round.
Parameters
----------
num_trials : int
Total number of trials
skipstep : int
unused
Returns
--... | def function[splitset, parameter[num_trials, skipstep]]:
constant[ Split-set cross validation
Use half the trials for training, and the other half for testing. Then
repeat the other way round.
Parameters
----------
num_trials : int
Total number of trials
skipstep : int
... | keyword[def] identifier[splitset] ( identifier[num_trials] , identifier[skipstep] = keyword[None] ):
literal[string]
identifier[split] = identifier[num_trials] // literal[int]
identifier[a] = identifier[list] ( identifier[range] ( literal[int] , identifier[split] ))
identifier[b] = identifier[l... | def splitset(num_trials, skipstep=None):
""" Split-set cross validation
Use half the trials for training, and the other half for testing. Then
repeat the other way round.
Parameters
----------
num_trials : int
Total number of trials
skipstep : int
unused
Returns
--... |
def support_false_positive_count(m, m_hat):
"""Count the number of false positive support elements in
m_hat in one triangle, not including the diagonal.
"""
m_nnz, m_hat_nnz, intersection_nnz = _nonzero_intersection(m, m_hat)
return int((m_hat_nnz - intersection_nnz) / 2.0) | def function[support_false_positive_count, parameter[m, m_hat]]:
constant[Count the number of false positive support elements in
m_hat in one triangle, not including the diagonal.
]
<ast.Tuple object at 0x7da1b117a410> assign[=] call[name[_nonzero_intersection], parameter[name[m], name[m_hat]]]
... | keyword[def] identifier[support_false_positive_count] ( identifier[m] , identifier[m_hat] ):
literal[string]
identifier[m_nnz] , identifier[m_hat_nnz] , identifier[intersection_nnz] = identifier[_nonzero_intersection] ( identifier[m] , identifier[m_hat] )
keyword[return] identifier[int] (( identifier... | def support_false_positive_count(m, m_hat):
"""Count the number of false positive support elements in
m_hat in one triangle, not including the diagonal.
"""
(m_nnz, m_hat_nnz, intersection_nnz) = _nonzero_intersection(m, m_hat)
return int((m_hat_nnz - intersection_nnz) / 2.0) |
def getoptS(X, Y, M_E, E):
''' Find Sopt given X, Y
'''
n, r = X.shape
C = np.dot(np.dot(X.T, M_E), Y)
C = C.flatten()
A = np.zeros((r * r, r * r))
for i in range(r):
for j in range(r):
ind = j * r + i
temp = np.dot(
np.dot(X.T, np... | def function[getoptS, parameter[X, Y, M_E, E]]:
constant[ Find Sopt given X, Y
]
<ast.Tuple object at 0x7da1b1ad17b0> assign[=] name[X].shape
variable[C] assign[=] call[name[np].dot, parameter[call[name[np].dot, parameter[name[X].T, name[M_E]]], name[Y]]]
variable[C] assign[=] call[n... | keyword[def] identifier[getoptS] ( identifier[X] , identifier[Y] , identifier[M_E] , identifier[E] ):
literal[string]
identifier[n] , identifier[r] = identifier[X] . identifier[shape]
identifier[C] = identifier[np] . identifier[dot] ( identifier[np] . identifier[dot] ( identifier[X] . identifier[T... | def getoptS(X, Y, M_E, E):
""" Find Sopt given X, Y
"""
(n, r) = X.shape
C = np.dot(np.dot(X.T, M_E), Y)
C = C.flatten()
A = np.zeros((r * r, r * r))
for i in range(r):
for j in range(r):
ind = j * r + i
temp = np.dot(np.dot(X.T, np.dot(X[:, i, None], Y[:, j, ... |
def stats(self):
"""Return a dictionary with a bunch of instance-wide statistics
:rtype: dict
"""
with self._sock_ctx() as socket:
self._send_message('stats', socket)
body = self._receive_data_with_prefix(b'OK', socket)
stats = yaml_load(body)
... | def function[stats, parameter[self]]:
constant[Return a dictionary with a bunch of instance-wide statistics
:rtype: dict
]
with call[name[self]._sock_ctx, parameter[]] begin[:]
call[name[self]._send_message, parameter[constant[stats], name[socket]]]
varia... | keyword[def] identifier[stats] ( identifier[self] ):
literal[string]
keyword[with] identifier[self] . identifier[_sock_ctx] () keyword[as] identifier[socket] :
identifier[self] . identifier[_send_message] ( literal[string] , identifier[socket] )
identifier[body] = identi... | def stats(self):
"""Return a dictionary with a bunch of instance-wide statistics
:rtype: dict
"""
with self._sock_ctx() as socket:
self._send_message('stats', socket)
body = self._receive_data_with_prefix(b'OK', socket)
stats = yaml_load(body)
return stats # dep... |
def write_batch_report(self, input_directory, parameter):
"""
Collect all of the batch reports and concatenate the results. The report should be :
:param input_directory:
:param parameter: This is the parameter in which to report.
"""
# Check to see if there is an @ in... | def function[write_batch_report, parameter[self, input_directory, parameter]]:
constant[
Collect all of the batch reports and concatenate the results. The report should be :
:param input_directory:
:param parameter: This is the parameter in which to report.
]
if compare... | keyword[def] identifier[write_batch_report] ( identifier[self] , identifier[input_directory] , identifier[parameter] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[parameter] :
identifier[parameter_dir] = identifier[parameter] . identifier[split] ( l... | def write_batch_report(self, input_directory, parameter):
"""
Collect all of the batch reports and concatenate the results. The report should be :
:param input_directory:
:param parameter: This is the parameter in which to report.
"""
# Check to see if there is an @ in the para... |
def get_query_cache_key(compiler):
"""
Generates a cache key from a SQLCompiler.
This cache key is specific to the SQL query and its context
(which database is used). The same query in the same context
(= the same database) must generate the same cache key.
:arg compiler: A SQLCompiler that w... | def function[get_query_cache_key, parameter[compiler]]:
constant[
Generates a cache key from a SQLCompiler.
This cache key is specific to the SQL query and its context
(which database is used). The same query in the same context
(= the same database) must generate the same cache key.
:arg... | keyword[def] identifier[get_query_cache_key] ( identifier[compiler] ):
literal[string]
identifier[sql] , identifier[params] = identifier[compiler] . identifier[as_sql] ()
identifier[check_parameter_types] ( identifier[params] )
identifier[cache_key] = literal[string] %( identifier[compiler] . ide... | def get_query_cache_key(compiler):
"""
Generates a cache key from a SQLCompiler.
This cache key is specific to the SQL query and its context
(which database is used). The same query in the same context
(= the same database) must generate the same cache key.
:arg compiler: A SQLCompiler that w... |
def path_to_list(pathstr):
"""Conver a path string to a list of path elements."""
return [elem for elem in pathstr.split(os.path.pathsep) if elem] | def function[path_to_list, parameter[pathstr]]:
constant[Conver a path string to a list of path elements.]
return[<ast.ListComp object at 0x7da20c7cb2e0>] | keyword[def] identifier[path_to_list] ( identifier[pathstr] ):
literal[string]
keyword[return] [ identifier[elem] keyword[for] identifier[elem] keyword[in] identifier[pathstr] . identifier[split] ( identifier[os] . identifier[path] . identifier[pathsep] ) keyword[if] identifier[elem] ] | def path_to_list(pathstr):
"""Conver a path string to a list of path elements."""
return [elem for elem in pathstr.split(os.path.pathsep) if elem] |
def get(self, objectType, *args, **coolArgs) :
"""Raba Magic inside. This is th function that you use for
querying pyGeno's DB.
Usage examples:
* myGenome.get("Gene", name = 'TPST2')
* myGene.get(Protein, id = 'ENSID...')
* myGenome.get(Transcript, {'start >' : x, 'end <' : y})"""
ret =... | def function[get, parameter[self, objectType]]:
constant[Raba Magic inside. This is th function that you use for
querying pyGeno's DB.
Usage examples:
* myGenome.get("Gene", name = 'TPST2')
* myGene.get(Protein, id = 'ENSID...')
* myGenome.get(Transcript, {'start >' : x, 'end <' : y})]... | keyword[def] identifier[get] ( identifier[self] , identifier[objectType] ,* identifier[args] ,** identifier[coolArgs] ):
literal[string]
identifier[ret] =[]
keyword[for] identifier[e] keyword[in] identifier[self] . identifier[_makeLoadQuery] ( identifier[objectType] ,* identifier[args] ,** identifier[co... | def get(self, objectType, *args, **coolArgs):
"""Raba Magic inside. This is th function that you use for
querying pyGeno's DB.
Usage examples:
* myGenome.get("Gene", name = 'TPST2')
* myGene.get(Protein, id = 'ENSID...')
* myGenome.get(Transcript, {'start >' : x, 'end <' : y})"""
ret =... |
def _irregular(singular, plural):
"""
A convenience function to add appropriate rules to plurals and singular
for irregular words.
:param singular: irregular word in singular form
:param plural: irregular word in plural form
"""
def caseinsensitive(string):
return ''.join('[' + char... | def function[_irregular, parameter[singular, plural]]:
constant[
A convenience function to add appropriate rules to plurals and singular
for irregular words.
:param singular: irregular word in singular form
:param plural: irregular word in plural form
]
def function[caseinsensitive,... | keyword[def] identifier[_irregular] ( identifier[singular] , identifier[plural] ):
literal[string]
keyword[def] identifier[caseinsensitive] ( identifier[string] ):
keyword[return] literal[string] . identifier[join] ( literal[string] + identifier[char] + identifier[char] . identifier[upper] ()+ l... | def _irregular(singular, plural):
"""
A convenience function to add appropriate rules to plurals and singular
for irregular words.
:param singular: irregular word in singular form
:param plural: irregular word in plural form
"""
def caseinsensitive(string):
return ''.join(('[' + ch... |
def columnize(array, displaywidth=80, colsep = ' ',
arrange_vertical=True, ljust=True, lineprefix='',
opts={}):
"""Return a list of strings as a compact set of columns arranged
horizontally or vertically.
For example, for a line width of 4 characters (arranged vertically):
... | def function[columnize, parameter[array, displaywidth, colsep, arrange_vertical, ljust, lineprefix, opts]]:
constant[Return a list of strings as a compact set of columns arranged
horizontally or vertically.
For example, for a line width of 4 characters (arranged vertically):
['1', '2,', '3', '4... | keyword[def] identifier[columnize] ( identifier[array] , identifier[displaywidth] = literal[int] , identifier[colsep] = literal[string] ,
identifier[arrange_vertical] = keyword[True] , identifier[ljust] = keyword[True] , identifier[lineprefix] = literal[string] ,
identifier[opts] ={}):
literal[string]
ke... | def columnize(array, displaywidth=80, colsep=' ', arrange_vertical=True, ljust=True, lineprefix='', opts={}):
"""Return a list of strings as a compact set of columns arranged
horizontally or vertically.
For example, for a line width of 4 characters (arranged vertically):
['1', '2,', '3', '4'] => '... |
def cancel_job(self, job_id=None, job_name=None):
"""Cancel a running job.
Args:
job_id (str, optional): Identifier of job to be canceled.
job_name (str, optional): Name of job to be canceled.
Returns:
dict: JSON response for the job cancel operation.
... | def function[cancel_job, parameter[self, job_id, job_name]]:
constant[Cancel a running job.
Args:
job_id (str, optional): Identifier of job to be canceled.
job_name (str, optional): Name of job to be canceled.
Returns:
dict: JSON response for the job cancel ... | keyword[def] identifier[cancel_job] ( identifier[self] , identifier[job_id] = keyword[None] , identifier[job_name] = keyword[None] ):
literal[string]
identifier[payload] ={}
keyword[if] identifier[job_name] keyword[is] keyword[not] keyword[None] :
identifier[payload] [ lit... | def cancel_job(self, job_id=None, job_name=None):
"""Cancel a running job.
Args:
job_id (str, optional): Identifier of job to be canceled.
job_name (str, optional): Name of job to be canceled.
Returns:
dict: JSON response for the job cancel operation.
""... |
def network_profiles(self):
"""Get all the AP profiles."""
profiles = self._wifi_ctrl.network_profiles(self._raw_obj)
if self._logger.isEnabledFor(logging.INFO):
for profile in profiles:
self._logger.info("Get profile:")
self._logger.info("\tssid: %s... | def function[network_profiles, parameter[self]]:
constant[Get all the AP profiles.]
variable[profiles] assign[=] call[name[self]._wifi_ctrl.network_profiles, parameter[name[self]._raw_obj]]
if call[name[self]._logger.isEnabledFor, parameter[name[logging].INFO]] begin[:]
for taget... | keyword[def] identifier[network_profiles] ( identifier[self] ):
literal[string]
identifier[profiles] = identifier[self] . identifier[_wifi_ctrl] . identifier[network_profiles] ( identifier[self] . identifier[_raw_obj] )
keyword[if] identifier[self] . identifier[_logger] . identifier[isE... | def network_profiles(self):
"""Get all the AP profiles."""
profiles = self._wifi_ctrl.network_profiles(self._raw_obj)
if self._logger.isEnabledFor(logging.INFO):
for profile in profiles:
self._logger.info('Get profile:')
self._logger.info('\tssid: %s', profile.ssid)
... |
def parse_string_unsafe(s, system=SI):
"""Attempt to parse a string with ambiguous units and try to make a
bitmath object out of it.
This may produce inaccurate results if parsing shell output. For
example `ls` may say a 2730 Byte file is '2.7K'. 2730 Bytes == 2.73 kB
~= 2.666 KiB. See the documentation for all of... | def function[parse_string_unsafe, parameter[s, system]]:
constant[Attempt to parse a string with ambiguous units and try to make a
bitmath object out of it.
This may produce inaccurate results if parsing shell output. For
example `ls` may say a 2730 Byte file is '2.7K'. 2730 Bytes == 2.73 kB
~= 2.666 KiB. See ... | keyword[def] identifier[parse_string_unsafe] ( identifier[s] , identifier[system] = identifier[SI] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[s] ,( identifier[str] , identifier[unicode] )) keyword[and] keyword[not] identifier[isinstance] ( identifier[s] , identifier... | def parse_string_unsafe(s, system=SI):
"""Attempt to parse a string with ambiguous units and try to make a
bitmath object out of it.
This may produce inaccurate results if parsing shell output. For
example `ls` may say a 2730 Byte file is '2.7K'. 2730 Bytes == 2.73 kB
~= 2.666 KiB. See the documentation for all of... |
def table_schema(self):
"""
Returns the table schema.
:returns: dict
"""
if self.__dict__.get('_table_schema') is None:
self._table_schema = None
table_schema = {}
for row in self.query_schema():
name, default, dtype = self.db(... | def function[table_schema, parameter[self]]:
constant[
Returns the table schema.
:returns: dict
]
if compare[call[name[self].__dict__.get, parameter[constant[_table_schema]]] is constant[None]] begin[:]
name[self]._table_schema assign[=] constant[None]
... | keyword[def] identifier[table_schema] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[__dict__] . identifier[get] ( literal[string] ) keyword[is] keyword[None] :
identifier[self] . identifier[_table_schema] = keyword[None]
identifier[tabl... | def table_schema(self):
"""
Returns the table schema.
:returns: dict
"""
if self.__dict__.get('_table_schema') is None:
self._table_schema = None
table_schema = {}
for row in self.query_schema():
(name, default, dtype) = self.db().lexicon.column_info(... |
def format_seq(self, outstream=None, linewidth=70):
"""
Print a sequence in a readable format.
:param outstream: if `None`, formatted sequence is returned as a
string; otherwise, it is treated as a file-like
object and the formatted sequence i... | def function[format_seq, parameter[self, outstream, linewidth]]:
constant[
Print a sequence in a readable format.
:param outstream: if `None`, formatted sequence is returned as a
string; otherwise, it is treated as a file-like
object and the f... | keyword[def] identifier[format_seq] ( identifier[self] , identifier[outstream] = keyword[None] , identifier[linewidth] = literal[int] ):
literal[string]
keyword[if] identifier[linewidth] == literal[int] keyword[or] identifier[len] ( identifier[self] . identifier[seq] )<= identifier[linewidth] :
... | def format_seq(self, outstream=None, linewidth=70):
"""
Print a sequence in a readable format.
:param outstream: if `None`, formatted sequence is returned as a
string; otherwise, it is treated as a file-like
object and the formatted sequence is pr... |
def update_state(url, state_obj):
"""Update the state of a given model run. The state object is a Json
representation of the state as created by the SCO-Server.
Throws a ValueError if the resource is unknown or the update state
request failed.
Parameters
----------
... | def function[update_state, parameter[url, state_obj]]:
constant[Update the state of a given model run. The state object is a Json
representation of the state as created by the SCO-Server.
Throws a ValueError if the resource is unknown or the update state
request failed.
Paramet... | keyword[def] identifier[update_state] ( identifier[url] , identifier[state_obj] ):
literal[string]
keyword[try] :
identifier[req] = identifier[urllib2] . identifier[Request] ( identifier[url] )
identifier[req] . identifier[add_header] ( literal[string] , literal[s... | def update_state(url, state_obj):
"""Update the state of a given model run. The state object is a Json
representation of the state as created by the SCO-Server.
Throws a ValueError if the resource is unknown or the update state
request failed.
Parameters
----------
... |
def sequenceToWord(sequence):
"""
converts a sequence (one-hot) in a reber string
"""
reberString = ''
for i in xrange(len(sequence)):
index = np.where(sequence[i]==1.)[0][0]
reberString += chars[index]
return reberString | def function[sequenceToWord, parameter[sequence]]:
constant[
converts a sequence (one-hot) in a reber string
]
variable[reberString] assign[=] constant[]
for taget[name[i]] in starred[call[name[xrange], parameter[call[name[len], parameter[name[sequence]]]]]] begin[:]
vari... | keyword[def] identifier[sequenceToWord] ( identifier[sequence] ):
literal[string]
identifier[reberString] = literal[string]
keyword[for] identifier[i] keyword[in] identifier[xrange] ( identifier[len] ( identifier[sequence] )):
identifier[index] = identifier[np] . identifier[where] ( ident... | def sequenceToWord(sequence):
"""
converts a sequence (one-hot) in a reber string
"""
reberString = ''
for i in xrange(len(sequence)):
index = np.where(sequence[i] == 1.0)[0][0]
reberString += chars[index] # depends on [control=['for'], data=['i']]
return reberString |
def list_datacenters(kwargs=None, call=None):
'''
List all the data centers for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_datacenters my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_datacenters fun... | def function[list_datacenters, parameter[kwargs, call]]:
constant[
List all the data centers for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_datacenters my-vmware-config
]
if compare[name[call] not_equal[!=] constant[function]] begin[:]
... | keyword[def] identifier[list_datacenters] ( identifier[kwargs] = keyword[None] , identifier[call] = keyword[None] ):
literal[string]
keyword[if] identifier[call] != literal[string] :
keyword[raise] identifier[SaltCloudSystemExit] (
literal[string]
literal[string]
)
... | def list_datacenters(kwargs=None, call=None):
"""
List all the data centers for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_datacenters my-vmware-config
"""
if call != 'function':
raise SaltCloudSystemExit('The list_datacenters function must be... |
def oauth_required(f):
"""
decorator to add to a view to require an oauth user
:return: decorated function
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if 'oauth_user_uri' not in session or session['oauth_user_uri'] is None:
return re... | def function[oauth_required, parameter[f]]:
constant[
decorator to add to a view to require an oauth user
:return: decorated function
]
def function[decorated_function, parameter[]]:
if <ast.BoolOp object at 0x7da18fe918a0> begin[:]
return[call[name[re... | keyword[def] identifier[oauth_required] ( identifier[f] ):
literal[string]
@ identifier[wraps] ( identifier[f] )
keyword[def] identifier[decorated_function] (* identifier[args] ,** identifier[kwargs] ):
keyword[if] literal[string] keyword[not] keyword[in] identifier[sessio... | def oauth_required(f):
"""
decorator to add to a view to require an oauth user
:return: decorated function
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if 'oauth_user_uri' not in session or session['oauth_user_uri'] is None:
return redirect(url_for('.r_... |
def load( filename ):
"""
Loads the profile from the inputed filename.
:param filename | <str>
"""
try:
f = open(filename, 'r')
except IOError:
logger.exception('Could not load the file: %s' % filename)
return... | def function[load, parameter[filename]]:
constant[
Loads the profile from the inputed filename.
:param filename | <str>
]
<ast.Try object at 0x7da18bcc8100>
variable[strdata] assign[=] call[name[f].read, parameter[]]
call[name[f].close, parameter[]]
... | keyword[def] identifier[load] ( identifier[filename] ):
literal[string]
keyword[try] :
identifier[f] = identifier[open] ( identifier[filename] , literal[string] )
keyword[except] identifier[IOError] :
identifier[logger] . identifier[exception] ( literal[string] ... | def load(filename):
"""
Loads the profile from the inputed filename.
:param filename | <str>
"""
try:
f = open(filename, 'r') # depends on [control=['try'], data=[]]
except IOError:
logger.exception('Could not load the file: %s' % filename)
retu... |
def notify(self, level, value, target=None, ntype=None, rule=None):
"""Notify main reactor about event."""
# Did we see the event before?
if target in self.state and level == self.state[target]:
return False
# Do we see the event first time?
if target not in self.sta... | def function[notify, parameter[self, level, value, target, ntype, rule]]:
constant[Notify main reactor about event.]
if <ast.BoolOp object at 0x7da1b0e14190> begin[:]
return[constant[False]]
if <ast.BoolOp object at 0x7da1b0e161a0> begin[:]
return[constant[False]]
call[na... | keyword[def] identifier[notify] ( identifier[self] , identifier[level] , identifier[value] , identifier[target] = keyword[None] , identifier[ntype] = keyword[None] , identifier[rule] = keyword[None] ):
literal[string]
keyword[if] identifier[target] keyword[in] identifier[self] . identif... | def notify(self, level, value, target=None, ntype=None, rule=None):
"""Notify main reactor about event."""
# Did we see the event before?
if target in self.state and level == self.state[target]:
return False # depends on [control=['if'], data=[]]
# Do we see the event first time?
if target ... |
def add_object_file(self, obj_file):
"""
Add object file to the jit. object_file can be instance of
:class:ObjectFile or a string representing file system path
"""
if isinstance(obj_file, str):
obj_file = object_file.ObjectFileRef.from_path(obj_file)
ffi.lib.... | def function[add_object_file, parameter[self, obj_file]]:
constant[
Add object file to the jit. object_file can be instance of
:class:ObjectFile or a string representing file system path
]
if call[name[isinstance], parameter[name[obj_file], name[str]]] begin[:]
va... | keyword[def] identifier[add_object_file] ( identifier[self] , identifier[obj_file] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[obj_file] , identifier[str] ):
identifier[obj_file] = identifier[object_file] . identifier[ObjectFileRef] . identifier[from_path] ( ide... | def add_object_file(self, obj_file):
"""
Add object file to the jit. object_file can be instance of
:class:ObjectFile or a string representing file system path
"""
if isinstance(obj_file, str):
obj_file = object_file.ObjectFileRef.from_path(obj_file) # depends on [control=['if']... |
def search_item_by_name_and_folder_name(self, name, folder_name,
token=None):
"""
Return all items with a given name and parent folder name.
:param name: The name of the item to search by.
:type name: string
:param folder_name: The nam... | def function[search_item_by_name_and_folder_name, parameter[self, name, folder_name, token]]:
constant[
Return all items with a given name and parent folder name.
:param name: The name of the item to search by.
:type name: string
:param folder_name: The name of the parent folder... | keyword[def] identifier[search_item_by_name_and_folder_name] ( identifier[self] , identifier[name] , identifier[folder_name] ,
identifier[token] = keyword[None] ):
literal[string]
identifier[parameters] = identifier[dict] ()
identifier[parameters] [ literal[string] ]= identifier[name]
... | def search_item_by_name_and_folder_name(self, name, folder_name, token=None):
"""
Return all items with a given name and parent folder name.
:param name: The name of the item to search by.
:type name: string
:param folder_name: The name of the parent folder to search by.
:ty... |
def otsu_segmentation(image, k, mask=None):
"""
Otsu image segmentation
This is a very fast segmentation algorithm good for quick explortation,
but does not return probability maps.
ANTsR function: `thresholdImage(image, 'Otsu', k)`
Arguments
---------
image : ANTsImage
... | def function[otsu_segmentation, parameter[image, k, mask]]:
constant[
Otsu image segmentation
This is a very fast segmentation algorithm good for quick explortation,
but does not return probability maps.
ANTsR function: `thresholdImage(image, 'Otsu', k)`
Arguments
---------
i... | keyword[def] identifier[otsu_segmentation] ( identifier[image] , identifier[k] , identifier[mask] = keyword[None] ):
literal[string]
keyword[if] identifier[mask] keyword[is] keyword[not] keyword[None] :
identifier[image] = identifier[image] . identifier[mask_image] ( identifier[mask] )
i... | def otsu_segmentation(image, k, mask=None):
"""
Otsu image segmentation
This is a very fast segmentation algorithm good for quick explortation,
but does not return probability maps.
ANTsR function: `thresholdImage(image, 'Otsu', k)`
Arguments
---------
image : ANTsImage
... |
def rax(a, boot, threads, \
fast = False, run_rax = False, run_iq = False, model = False, cluster = False, node = False):
"""
run raxml on 'a' (alignment) with 'boot' (bootstraps) and 'threads' (threads)
store all files in raxml_a_b
1. give every sequence a short identifier
2. convert fa... | def function[rax, parameter[a, boot, threads, fast, run_rax, run_iq, model, cluster, node]]:
constant[
run raxml on 'a' (alignment) with 'boot' (bootstraps) and 'threads' (threads)
store all files in raxml_a_b
1. give every sequence a short identifier
2. convert fasta to phylip
3. run raxml
... | keyword[def] identifier[rax] ( identifier[a] , identifier[boot] , identifier[threads] , identifier[fast] = keyword[False] , identifier[run_rax] = keyword[False] , identifier[run_iq] = keyword[False] , identifier[model] = keyword[False] , identifier[cluster] = keyword[False] , identifier[node] = keyword[False] ):
... | def rax(a, boot, threads, fast=False, run_rax=False, run_iq=False, model=False, cluster=False, node=False):
"""
run raxml on 'a' (alignment) with 'boot' (bootstraps) and 'threads' (threads)
store all files in raxml_a_b
1. give every sequence a short identifier
2. convert fasta to phylip
3. run r... |
def bind_proxy(self, name, proxy):
"""Adds a mask that maps to a given proxy."""
if not len(name) or name[0] != '/' or name[-1] != '/':
raise ValueError(
"name must start and end with '/': {0}".format(name))
self._folder_proxys.insert(0, (name, proxy)) | def function[bind_proxy, parameter[self, name, proxy]]:
constant[Adds a mask that maps to a given proxy.]
if <ast.BoolOp object at 0x7da2043466e0> begin[:]
<ast.Raise object at 0x7da204345300>
call[name[self]._folder_proxys.insert, parameter[constant[0], tuple[[<ast.Name object at 0x7da2... | keyword[def] identifier[bind_proxy] ( identifier[self] , identifier[name] , identifier[proxy] ):
literal[string]
keyword[if] keyword[not] identifier[len] ( identifier[name] ) keyword[or] identifier[name] [ literal[int] ]!= literal[string] keyword[or] identifier[name] [- literal[int] ]!= litera... | def bind_proxy(self, name, proxy):
"""Adds a mask that maps to a given proxy."""
if not len(name) or name[0] != '/' or name[-1] != '/':
raise ValueError("name must start and end with '/': {0}".format(name)) # depends on [control=['if'], data=[]]
self._folder_proxys.insert(0, (name, proxy)) |
def _normalize(esfilter):
"""
TODO: DO NOT USE Data, WE ARE SPENDING TOO MUCH TIME WRAPPING/UNWRAPPING
REALLY, WE JUST COLLAPSE CASCADING `and` AND `or` FILTERS
"""
if esfilter == MATCH_ALL or esfilter == MATCH_NONE or esfilter.isNormal:
return esfilter
# Log.note("from: " + convert.val... | def function[_normalize, parameter[esfilter]]:
constant[
TODO: DO NOT USE Data, WE ARE SPENDING TOO MUCH TIME WRAPPING/UNWRAPPING
REALLY, WE JUST COLLAPSE CASCADING `and` AND `or` FILTERS
]
if <ast.BoolOp object at 0x7da1b0ab5780> begin[:]
return[name[esfilter]]
variable[isDi... | keyword[def] identifier[_normalize] ( identifier[esfilter] ):
literal[string]
keyword[if] identifier[esfilter] == identifier[MATCH_ALL] keyword[or] identifier[esfilter] == identifier[MATCH_NONE] keyword[or] identifier[esfilter] . identifier[isNormal] :
keyword[return] identifier[esfilter]
... | def _normalize(esfilter):
"""
TODO: DO NOT USE Data, WE ARE SPENDING TOO MUCH TIME WRAPPING/UNWRAPPING
REALLY, WE JUST COLLAPSE CASCADING `and` AND `or` FILTERS
"""
if esfilter == MATCH_ALL or esfilter == MATCH_NONE or esfilter.isNormal:
return esfilter # depends on [control=['if'], data=[]... |
def _flip_feature(self, feature, parent_len):
'''Adjust a feature's location when flipping DNA.
:param feature: The feature to flip.
:type feature: coral.Feature
:param parent_len: The length of the sequence to which the feature belongs.
:type parent_len: int
'''
copy = feature.copy()
... | def function[_flip_feature, parameter[self, feature, parent_len]]:
constant[Adjust a feature's location when flipping DNA.
:param feature: The feature to flip.
:type feature: coral.Feature
:param parent_len: The length of the sequence to which the feature belongs.
:type parent_len: int
]
... | keyword[def] identifier[_flip_feature] ( identifier[self] , identifier[feature] , identifier[parent_len] ):
literal[string]
identifier[copy] = identifier[feature] . identifier[copy] ()
keyword[if] identifier[copy] . identifier[strand] == literal[int] :
identifier[copy] . identifier[stra... | def _flip_feature(self, feature, parent_len):
"""Adjust a feature's location when flipping DNA.
:param feature: The feature to flip.
:type feature: coral.Feature
:param parent_len: The length of the sequence to which the feature belongs.
:type parent_len: int
"""
copy = feature.copy()
... |
def focusOutEvent(self, event):
"""
Processes when this widget loses focus.
:param event | <QFocusEvent>
"""
if not self.signalsBlocked():
self.focusChanged.emit(False)
self.focusExited.emit()
return super(XTextEdit... | def function[focusOutEvent, parameter[self, event]]:
constant[
Processes when this widget loses focus.
:param event | <QFocusEvent>
]
if <ast.UnaryOp object at 0x7da18f00fbe0> begin[:]
call[name[self].focusChanged.emit, parameter[constant[False]]]
... | keyword[def] identifier[focusOutEvent] ( identifier[self] , identifier[event] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[signalsBlocked] ():
identifier[self] . identifier[focusChanged] . identifier[emit] ( keyword[False] )
identifier[se... | def focusOutEvent(self, event):
"""
Processes when this widget loses focus.
:param event | <QFocusEvent>
"""
if not self.signalsBlocked():
self.focusChanged.emit(False)
self.focusExited.emit() # depends on [control=['if'], data=[]]
return super(XTextEdi... |
def consume(self, tokens):
'''Have this parameter consume some tokens.
This stores the consumed value for later use and returns the
modified tokens array for further processing.
'''
n = len(tokens) if self._nargs == -1 else self._nargs
if n > len(tokens):
exit('Error: Not enough arguments for "{}".'.for... | def function[consume, parameter[self, tokens]]:
constant[Have this parameter consume some tokens.
This stores the consumed value for later use and returns the
modified tokens array for further processing.
]
variable[n] assign[=] <ast.IfExp object at 0x7da2043450f0>
if compare[name[n] grea... | keyword[def] identifier[consume] ( identifier[self] , identifier[tokens] ):
literal[string]
identifier[n] = identifier[len] ( identifier[tokens] ) keyword[if] identifier[self] . identifier[_nargs] ==- literal[int] keyword[else] identifier[self] . identifier[_nargs]
keyword[if] identifier[n] > identifie... | def consume(self, tokens):
"""Have this parameter consume some tokens.
This stores the consumed value for later use and returns the
modified tokens array for further processing.
"""
n = len(tokens) if self._nargs == -1 else self._nargs
if n > len(tokens):
exit('Error: Not enough arguments for... |
def get_bytes(self, index, size):
"""
Extracts several bytes from a bitvector, where the index refers to the byte in a big-endian order
:param index: the byte index at which to start extracting
:param size: the number of bytes to extract
:return: A BV of size ``size * 8``
... | def function[get_bytes, parameter[self, index, size]]:
constant[
Extracts several bytes from a bitvector, where the index refers to the byte in a big-endian order
:param index: the byte index at which to start extracting
:param size: the number of bytes to extract
:return: A BV ... | keyword[def] identifier[get_bytes] ( identifier[self] , identifier[index] , identifier[size] ):
literal[string]
identifier[pos] = identifier[self] . identifier[size] ()// literal[int] - literal[int] - identifier[index]
keyword[return] identifier[self] [ identifier[pos] * literal[int] + l... | def get_bytes(self, index, size):
"""
Extracts several bytes from a bitvector, where the index refers to the byte in a big-endian order
:param index: the byte index at which to start extracting
:param size: the number of bytes to extract
:return: A BV of size ``size * 8``
""... |
def data2schema(
_data=None, _force=False, _besteffort=True, _registry=None,
_factory=None, _buildkwargs=None, **kwargs
):
"""Get the schema able to instanciate input data.
The default value of schema will be data.
Can be used such as a decorator:
..code-block:: python
@data2... | def function[data2schema, parameter[_data, _force, _besteffort, _registry, _factory, _buildkwargs]]:
constant[Get the schema able to instanciate input data.
The default value of schema will be data.
Can be used such as a decorator:
..code-block:: python
@data2schema
def example()... | keyword[def] identifier[data2schema] (
identifier[_data] = keyword[None] , identifier[_force] = keyword[False] , identifier[_besteffort] = keyword[True] , identifier[_registry] = keyword[None] ,
identifier[_factory] = keyword[None] , identifier[_buildkwargs] = keyword[None] ,** identifier[kwargs]
):
literal[s... | def data2schema(_data=None, _force=False, _besteffort=True, _registry=None, _factory=None, _buildkwargs=None, **kwargs):
"""Get the schema able to instanciate input data.
The default value of schema will be data.
Can be used such as a decorator:
..code-block:: python
@data2schema
def... |
def LJMP(cpu, cs_selector, target):
"""
We are just going to ignore the CS selector for now.
"""
logger.info("LJMP: Jumping to: %r:%r", cs_selector.read(), target.read())
cpu.CS = cs_selector.read()
cpu.PC = target.read() | def function[LJMP, parameter[cpu, cs_selector, target]]:
constant[
We are just going to ignore the CS selector for now.
]
call[name[logger].info, parameter[constant[LJMP: Jumping to: %r:%r], call[name[cs_selector].read, parameter[]], call[name[target].read, parameter[]]]]
name[cp... | keyword[def] identifier[LJMP] ( identifier[cpu] , identifier[cs_selector] , identifier[target] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] , identifier[cs_selector] . identifier[read] (), identifier[target] . identifier[read] ())
identifier[cpu] . identifier[... | def LJMP(cpu, cs_selector, target):
"""
We are just going to ignore the CS selector for now.
"""
logger.info('LJMP: Jumping to: %r:%r', cs_selector.read(), target.read())
cpu.CS = cs_selector.read()
cpu.PC = target.read() |
def _generate_examples(self, num_examples, data_path, label_path):
"""Generate MNIST examples as dicts.
Args:
num_examples (int): The number of example.
data_path (str): Path to the data files
label_path (str): Path to the labels
Yields:
Generator yielding the next examples
"""... | def function[_generate_examples, parameter[self, num_examples, data_path, label_path]]:
constant[Generate MNIST examples as dicts.
Args:
num_examples (int): The number of example.
data_path (str): Path to the data files
label_path (str): Path to the labels
Yields:
Generator yie... | keyword[def] identifier[_generate_examples] ( identifier[self] , identifier[num_examples] , identifier[data_path] , identifier[label_path] ):
literal[string]
identifier[images] = identifier[_extract_mnist_images] ( identifier[data_path] , identifier[num_examples] )
identifier[labels] = identifier[_ext... | def _generate_examples(self, num_examples, data_path, label_path):
"""Generate MNIST examples as dicts.
Args:
num_examples (int): The number of example.
data_path (str): Path to the data files
label_path (str): Path to the labels
Yields:
Generator yielding the next examples
"""... |
def _pretend_to_run(self, migration, method):
"""
Pretend to run the migration.
:param migration: The migration
:type migration: orator.migrations.migration.Migration
:param method: The method to execute
:type method: str
"""
self._note("")
names... | def function[_pretend_to_run, parameter[self, migration, method]]:
constant[
Pretend to run the migration.
:param migration: The migration
:type migration: orator.migrations.migration.Migration
:param method: The method to execute
:type method: str
]
cal... | keyword[def] identifier[_pretend_to_run] ( identifier[self] , identifier[migration] , identifier[method] ):
literal[string]
identifier[self] . identifier[_note] ( literal[string] )
identifier[names] =[]
keyword[for] identifier[query] keyword[in] identifier[self] . identifier[_g... | def _pretend_to_run(self, migration, method):
"""
Pretend to run the migration.
:param migration: The migration
:type migration: orator.migrations.migration.Migration
:param method: The method to execute
:type method: str
"""
self._note('')
names = []
fo... |
def Run(self, args):
"""Reads a buffer on the client and sends it to the server."""
# Make sure we limit the size of our output
if args.length > constants.CLIENT_MAX_BUFFER_SIZE:
raise RuntimeError("Can not read buffers this large.")
try:
fd = vfs.VFSOpen(args.pathspec, progress_callback=se... | def function[Run, parameter[self, args]]:
constant[Reads a buffer on the client and sends it to the server.]
if compare[name[args].length greater[>] name[constants].CLIENT_MAX_BUFFER_SIZE] begin[:]
<ast.Raise object at 0x7da1b1b876a0>
<ast.Try object at 0x7da1b1b87d00>
call[name[self... | keyword[def] identifier[Run] ( identifier[self] , identifier[args] ):
literal[string]
keyword[if] identifier[args] . identifier[length] > identifier[constants] . identifier[CLIENT_MAX_BUFFER_SIZE] :
keyword[raise] identifier[RuntimeError] ( literal[string] )
keyword[try] :
identi... | def Run(self, args):
"""Reads a buffer on the client and sends it to the server."""
# Make sure we limit the size of our output
if args.length > constants.CLIENT_MAX_BUFFER_SIZE:
raise RuntimeError('Can not read buffers this large.') # depends on [control=['if'], data=[]]
try:
fd = vfs.... |
def get_midi_data(self):
"""Collect and return the raw, binary MIDI data from the tracks."""
tracks = [t.get_midi_data() for t in self.tracks if t.track_data != '']
return self.header() + ''.join(tracks) | def function[get_midi_data, parameter[self]]:
constant[Collect and return the raw, binary MIDI data from the tracks.]
variable[tracks] assign[=] <ast.ListComp object at 0x7da1b26add50>
return[binary_operation[call[name[self].header, parameter[]] + call[constant[].join, parameter[name[tracks]]]]] | keyword[def] identifier[get_midi_data] ( identifier[self] ):
literal[string]
identifier[tracks] =[ identifier[t] . identifier[get_midi_data] () keyword[for] identifier[t] keyword[in] identifier[self] . identifier[tracks] keyword[if] identifier[t] . identifier[track_data] != literal[string] ]
... | def get_midi_data(self):
"""Collect and return the raw, binary MIDI data from the tracks."""
tracks = [t.get_midi_data() for t in self.tracks if t.track_data != '']
return self.header() + ''.join(tracks) |
def _get_encoder_data_shapes(self, bucket_key: int, batch_size: int) -> List[mx.io.DataDesc]:
"""
Returns data shapes of the encoder module.
:param bucket_key: Maximum input length.
:return: List of data descriptions.
"""
return [mx.io.DataDesc(name=C.SOURCE_NAME,
... | def function[_get_encoder_data_shapes, parameter[self, bucket_key, batch_size]]:
constant[
Returns data shapes of the encoder module.
:param bucket_key: Maximum input length.
:return: List of data descriptions.
]
return[list[[<ast.Call object at 0x7da1b1d23ca0>]]] | keyword[def] identifier[_get_encoder_data_shapes] ( identifier[self] , identifier[bucket_key] : identifier[int] , identifier[batch_size] : identifier[int] )-> identifier[List] [ identifier[mx] . identifier[io] . identifier[DataDesc] ]:
literal[string]
keyword[return] [ identifier[mx] . identifier[i... | def _get_encoder_data_shapes(self, bucket_key: int, batch_size: int) -> List[mx.io.DataDesc]:
"""
Returns data shapes of the encoder module.
:param bucket_key: Maximum input length.
:return: List of data descriptions.
"""
return [mx.io.DataDesc(name=C.SOURCE_NAME, shape=(batch_s... |
def ask_question(self, field_name, pattern=NAME_PATTERN, is_required=False,
password=False):
"""Ask a question and get the input values.
This method will validade the input values.
Args:
field_name(string): Field name used to ask for input value.
pat... | def function[ask_question, parameter[self, field_name, pattern, is_required, password]]:
constant[Ask a question and get the input values.
This method will validade the input values.
Args:
field_name(string): Field name used to ask for input value.
pattern(tuple): Patter... | keyword[def] identifier[ask_question] ( identifier[self] , identifier[field_name] , identifier[pattern] = identifier[NAME_PATTERN] , identifier[is_required] = keyword[False] ,
identifier[password] = keyword[False] ):
literal[string]
identifier[input_value] = literal[string]
identifier[qu... | def ask_question(self, field_name, pattern=NAME_PATTERN, is_required=False, password=False):
"""Ask a question and get the input values.
This method will validade the input values.
Args:
field_name(string): Field name used to ask for input value.
pattern(tuple): Pattern to v... |
def find_same_between_dicts(dict1, dict2):
"""
查找两个字典中的相同点,包括键、值、项,仅支持 hashable 对象
:param:
* dict1: (dict) 比较的字典 1
* dict2: (dict) 比较的字典 2
:return:
* dup_info: (namedtuple) 返回两个字典中相同的信息组成的具名元组
举例如下::
print('--- find_same_between_dicts demo---')
dict1 = {'x... | def function[find_same_between_dicts, parameter[dict1, dict2]]:
constant[
查找两个字典中的相同点,包括键、值、项,仅支持 hashable 对象
:param:
* dict1: (dict) 比较的字典 1
* dict2: (dict) 比较的字典 2
:return:
* dup_info: (namedtuple) 返回两个字典中相同的信息组成的具名元组
举例如下::
print('--- find_same_between_dict... | keyword[def] identifier[find_same_between_dicts] ( identifier[dict1] , identifier[dict2] ):
literal[string]
identifier[Same_info] = identifier[namedtuple] ( literal[string] ,[ literal[string] , literal[string] , literal[string] ])
identifier[same_info] = identifier[Same_info] ( identifier[set] ( ident... | def find_same_between_dicts(dict1, dict2):
"""
查找两个字典中的相同点,包括键、值、项,仅支持 hashable 对象
:param:
* dict1: (dict) 比较的字典 1
* dict2: (dict) 比较的字典 2
:return:
* dup_info: (namedtuple) 返回两个字典中相同的信息组成的具名元组
举例如下::
print('--- find_same_between_dicts demo---')
dict1 = {'x... |
def timestamp(num_params, p_levels, k_choices, N):
"""
Returns a uniform timestamp with parameter values for file identification
"""
string = "_v%s_l%s_gs%s_k%s_N%s_%s.txt" % (num_params,
p_levels,
k_choices,
... | def function[timestamp, parameter[num_params, p_levels, k_choices, N]]:
constant[
Returns a uniform timestamp with parameter values for file identification
]
variable[string] assign[=] binary_operation[constant[_v%s_l%s_gs%s_k%s_N%s_%s.txt] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name obj... | keyword[def] identifier[timestamp] ( identifier[num_params] , identifier[p_levels] , identifier[k_choices] , identifier[N] ):
literal[string]
identifier[string] = literal[string] %( identifier[num_params] ,
identifier[p_levels] ,
identifier[k_choices] ,
identifier[N] ,
identifier[dt] . ... | def timestamp(num_params, p_levels, k_choices, N):
"""
Returns a uniform timestamp with parameter values for file identification
"""
string = '_v%s_l%s_gs%s_k%s_N%s_%s.txt' % (num_params, p_levels, k_choices, N, dt.strftime(dt.now(), '%d%m%y%H%M%S'))
return string |
def remove_entry(self, entry):
"""
Remove specified entry.
:param entry: The Entry object to remove.
:type entry: :class:`keepassdb.model.Entry`
"""
if not isinstance(entry, Entry):
raise TypeError("entry param must be of type Entry.")
if not ... | def function[remove_entry, parameter[self, entry]]:
constant[
Remove specified entry.
:param entry: The Entry object to remove.
:type entry: :class:`keepassdb.model.Entry`
]
if <ast.UnaryOp object at 0x7da18fe939a0> begin[:]
<ast.Raise object at 0x7da18fe... | keyword[def] identifier[remove_entry] ( identifier[self] , identifier[entry] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[entry] , identifier[Entry] ):
keyword[raise] identifier[TypeError] ( literal[string] )
keyword[if] keyword[not] ide... | def remove_entry(self, entry):
"""
Remove specified entry.
:param entry: The Entry object to remove.
:type entry: :class:`keepassdb.model.Entry`
"""
if not isinstance(entry, Entry):
raise TypeError('entry param must be of type Entry.') # depends on [control=['if... |
def reply(self):
"""Reply to the selected status"""
status = self.get_selected_status()
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to reply", Color.RED)
return
compose_modal = ComposeModal(self.... | def function[reply, parameter[self]]:
constant[Reply to the selected status]
variable[status] assign[=] call[name[self].get_selected_status, parameter[]]
<ast.Tuple object at 0x7da1b1669150> assign[=] tuple[[<ast.Attribute object at 0x7da1b17dc340>, <ast.Attribute object at 0x7da1b17dde70>]]
... | keyword[def] identifier[reply] ( identifier[self] ):
literal[string]
identifier[status] = identifier[self] . identifier[get_selected_status] ()
identifier[app] , identifier[user] = identifier[self] . identifier[app] , identifier[self] . identifier[user]
keyword[if] keyword[not] ... | def reply(self):
"""Reply to the selected status"""
status = self.get_selected_status()
(app, user) = (self.app, self.user)
if not app or not user:
self.footer.draw_message('You must be logged in to reply', Color.RED)
return # depends on [control=['if'], data=[]]
compose_modal = Com... |
def moment(arr, moment=1, axis=0, **kwargs):
'''
Uses the scipy.stats.moment to calculate the Nth central
moment about the mean.
If `arr` is a 2D spectrogram returned by
ibmseti.dsp.raw_to_spectrogram(data), where each row
of the `arr` is a power spectrum at a particular time,
this function, then the Nth... | def function[moment, parameter[arr, moment, axis]]:
constant[
Uses the scipy.stats.moment to calculate the Nth central
moment about the mean.
If `arr` is a 2D spectrogram returned by
ibmseti.dsp.raw_to_spectrogram(data), where each row
of the `arr` is a power spectrum at a particular time,
this fun... | keyword[def] identifier[moment] ( identifier[arr] , identifier[moment] = literal[int] , identifier[axis] = literal[int] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[scipy] . identifier[stats] . identifier[moment] ( identifier[arr] , identifier[moment] = identifier[moment] , identifier[... | def moment(arr, moment=1, axis=0, **kwargs):
"""
Uses the scipy.stats.moment to calculate the Nth central
moment about the mean.
If `arr` is a 2D spectrogram returned by
ibmseti.dsp.raw_to_spectrogram(data), where each row
of the `arr` is a power spectrum at a particular time,
this function, then the N... |
def _make_verb_helper(verb_func, add_groups=False):
"""
Create function that prepares verb for the verb function
The functions created add expressions to be evaluated to
the verb, then call the core verb function
Parameters
----------
verb_func : function
Core verb function. This i... | def function[_make_verb_helper, parameter[verb_func, add_groups]]:
constant[
Create function that prepares verb for the verb function
The functions created add expressions to be evaluated to
the verb, then call the core verb function
Parameters
----------
verb_func : function
C... | keyword[def] identifier[_make_verb_helper] ( identifier[verb_func] , identifier[add_groups] = keyword[False] ):
literal[string]
@ identifier[wraps] ( identifier[verb_func] )
keyword[def] identifier[_verb_func] ( identifier[verb] ):
identifier[verb] . identifier[expressions] , identifier[new_... | def _make_verb_helper(verb_func, add_groups=False):
"""
Create function that prepares verb for the verb function
The functions created add expressions to be evaluated to
the verb, then call the core verb function
Parameters
----------
verb_func : function
Core verb function. This i... |
def fstab(jail):
'''
Display contents of a fstab(5) file defined in specified
jail's configuration. If no file is defined, return False.
CLI Example:
.. code-block:: bash
salt '*' jail.fstab <jail name>
'''
ret = []
config = show_config(jail)
if 'fstab' in config:
... | def function[fstab, parameter[jail]]:
constant[
Display contents of a fstab(5) file defined in specified
jail's configuration. If no file is defined, return False.
CLI Example:
.. code-block:: bash
salt '*' jail.fstab <jail name>
]
variable[ret] assign[=] list[[]]
... | keyword[def] identifier[fstab] ( identifier[jail] ):
literal[string]
identifier[ret] =[]
identifier[config] = identifier[show_config] ( identifier[jail] )
keyword[if] literal[string] keyword[in] identifier[config] :
identifier[c_fstab] = identifier[config] [ literal[string] ]
key... | def fstab(jail):
"""
Display contents of a fstab(5) file defined in specified
jail's configuration. If no file is defined, return False.
CLI Example:
.. code-block:: bash
salt '*' jail.fstab <jail name>
"""
ret = []
config = show_config(jail)
if 'fstab' in config:
... |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: CallSummaryContext for this CallSummaryInstance
:rtype: twilio.rest.insights.v1.summary.CallSumma... | def function[_proxy, parameter[self]]:
constant[
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: CallSummaryContext for this CallSummaryInstance
:rtype: twilio.rest.in... | keyword[def] identifier[_proxy] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_context] keyword[is] keyword[None] :
identifier[self] . identifier[_context] = identifier[CallSummaryContext] ( identifier[self] . identifier[_version] , identifier[call_... | def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: CallSummaryContext for this CallSummaryInstance
:rtype: twilio.rest.insights.v1.summary.CallSummaryCo... |
def _add_submenu(self, parent, data):
"""Adds items in data as a submenu to parent"""
for item in data:
obj = item[0]
if obj == wx.Menu:
try:
__, menuname, submenu, menu_id = item
except ValueError:
__, menu... | def function[_add_submenu, parameter[self, parent, data]]:
constant[Adds items in data as a submenu to parent]
for taget[name[item]] in starred[name[data]] begin[:]
variable[obj] assign[=] call[name[item]][constant[0]]
if compare[name[obj] equal[==] name[wx].Menu] begin[:... | keyword[def] identifier[_add_submenu] ( identifier[self] , identifier[parent] , identifier[data] ):
literal[string]
keyword[for] identifier[item] keyword[in] identifier[data] :
identifier[obj] = identifier[item] [ literal[int] ]
keyword[if] identifier[obj] == identifi... | def _add_submenu(self, parent, data):
"""Adds items in data as a submenu to parent"""
for item in data:
obj = item[0]
if obj == wx.Menu:
try:
(__, menuname, submenu, menu_id) = item # depends on [control=['try'], data=[]]
except ValueError:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.