code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def recursive_replace(list_, target, repl=-1):
r"""
Recursively removes target in all lists and sublists and replaces them with
the repl variable
"""
repl_list = [
recursive_replace(item, target, repl) if isinstance(item, (list, np.ndarray)) else
(repl if item == target else item)
... | def function[recursive_replace, parameter[list_, target, repl]]:
constant[
Recursively removes target in all lists and sublists and replaces them with
the repl variable
]
variable[repl_list] assign[=] <ast.ListComp object at 0x7da1b24ad450>
return[name[repl_list]] | keyword[def] identifier[recursive_replace] ( identifier[list_] , identifier[target] , identifier[repl] =- literal[int] ):
literal[string]
identifier[repl_list] =[
identifier[recursive_replace] ( identifier[item] , identifier[target] , identifier[repl] ) keyword[if] identifier[isinstance] ( identifier... | def recursive_replace(list_, target, repl=-1):
"""
Recursively removes target in all lists and sublists and replaces them with
the repl variable
"""
repl_list = [recursive_replace(item, target, repl) if isinstance(item, (list, np.ndarray)) else repl if item == target else item for item in list_]
... |
def plot_edoses(self, dos_pos=None, method="gaussian", step=0.01, width=0.1, **kwargs):
"""
Plot the band structure and the DOS.
Args:
dos_pos: Index of the task from which the DOS should be obtained.
None is all DOSes should be displayed. Accepts integer or lis... | def function[plot_edoses, parameter[self, dos_pos, method, step, width]]:
constant[
Plot the band structure and the DOS.
Args:
dos_pos: Index of the task from which the DOS should be obtained.
None is all DOSes should be displayed. Accepts integer or list of int... | keyword[def] identifier[plot_edoses] ( identifier[self] , identifier[dos_pos] = keyword[None] , identifier[method] = literal[string] , identifier[step] = literal[int] , identifier[width] = literal[int] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[dos_pos] keyword[is] keyword[... | def plot_edoses(self, dos_pos=None, method='gaussian', step=0.01, width=0.1, **kwargs):
"""
Plot the band structure and the DOS.
Args:
dos_pos: Index of the task from which the DOS should be obtained.
None is all DOSes should be displayed. Accepts integer or list of... |
def join(self, formatted_texts):
""":type formatted_texts: list[FormattedText]"""
formatted_texts = list(formatted_texts) # so that after the first iteration elements are not lost if generator
for formatted_text in formatted_texts:
assert self._is_compatible(formatted_text), "Cannot... | def function[join, parameter[self, formatted_texts]]:
constant[:type formatted_texts: list[FormattedText]]
variable[formatted_texts] assign[=] call[name[list], parameter[name[formatted_texts]]]
for taget[name[formatted_text]] in starred[name[formatted_texts]] begin[:]
assert[call[name[se... | keyword[def] identifier[join] ( identifier[self] , identifier[formatted_texts] ):
literal[string]
identifier[formatted_texts] = identifier[list] ( identifier[formatted_texts] )
keyword[for] identifier[formatted_text] keyword[in] identifier[formatted_texts] :
keyword[assert]... | def join(self, formatted_texts):
""":type formatted_texts: list[FormattedText]"""
formatted_texts = list(formatted_texts) # so that after the first iteration elements are not lost if generator
for formatted_text in formatted_texts:
assert self._is_compatible(formatted_text), 'Cannot join text with ... |
def save(html,fname=None,launch=False):
"""wrap HTML in a top and bottom (with css) and save to disk."""
html=html_top+html+html_bot
html=html.replace("~GENAT~",swhlab.common.datetimeToString())
if fname is None:
fname = tempfile.gettempdir()+"/temp.html"
launch=True
fname=os.path.ab... | def function[save, parameter[html, fname, launch]]:
constant[wrap HTML in a top and bottom (with css) and save to disk.]
variable[html] assign[=] binary_operation[binary_operation[name[html_top] + name[html]] + name[html_bot]]
variable[html] assign[=] call[name[html].replace, parameter[constant[... | keyword[def] identifier[save] ( identifier[html] , identifier[fname] = keyword[None] , identifier[launch] = keyword[False] ):
literal[string]
identifier[html] = identifier[html_top] + identifier[html] + identifier[html_bot]
identifier[html] = identifier[html] . identifier[replace] ( literal[string] ,... | def save(html, fname=None, launch=False):
"""wrap HTML in a top and bottom (with css) and save to disk."""
html = html_top + html + html_bot
html = html.replace('~GENAT~', swhlab.common.datetimeToString())
if fname is None:
fname = tempfile.gettempdir() + '/temp.html'
launch = True # de... |
def CopyTextToLabel(cls, text, prefix=''):
"""Copies a string to a label.
A label only supports a limited set of characters therefore
unsupported characters are replaced with an underscore.
Args:
text (str): label text.
prefix (Optional[str]): label prefix.
Returns:
str: label.
... | def function[CopyTextToLabel, parameter[cls, text, prefix]]:
constant[Copies a string to a label.
A label only supports a limited set of characters therefore
unsupported characters are replaced with an underscore.
Args:
text (str): label text.
prefix (Optional[str]): label prefix.
... | keyword[def] identifier[CopyTextToLabel] ( identifier[cls] , identifier[text] , identifier[prefix] = literal[string] ):
literal[string]
identifier[text] = literal[string] . identifier[format] ( identifier[prefix] , identifier[text] )
keyword[return] identifier[cls] . identifier[_INVALID_LABEL_CHARACT... | def CopyTextToLabel(cls, text, prefix=''):
"""Copies a string to a label.
A label only supports a limited set of characters therefore
unsupported characters are replaced with an underscore.
Args:
text (str): label text.
prefix (Optional[str]): label prefix.
Returns:
str: label.
... |
def single_path_generator(pathname):
"""
emits name,chunkgen pairs for the given file at pathname. If
pathname is a directory, will act recursively and will emit for
each file in the directory tree chunkgen is a generator that can
be iterated over to obtain the contents of the file in multiple
p... | def function[single_path_generator, parameter[pathname]]:
constant[
emits name,chunkgen pairs for the given file at pathname. If
pathname is a directory, will act recursively and will emit for
each file in the directory tree chunkgen is a generator that can
be iterated over to obtain the content... | keyword[def] identifier[single_path_generator] ( identifier[pathname] ):
literal[string]
keyword[if] identifier[isdir] ( identifier[pathname] ):
identifier[trim] = identifier[len] ( identifier[pathname] )
keyword[if] identifier[pathname] [- literal[int] ]!= identifier[sep] :
... | def single_path_generator(pathname):
"""
emits name,chunkgen pairs for the given file at pathname. If
pathname is a directory, will act recursively and will emit for
each file in the directory tree chunkgen is a generator that can
be iterated over to obtain the contents of the file in multiple
p... |
def is_iter(y, ignore=six.string_types):
'''
Test if an object is iterable, but not a string type.
Test if an object is an iterator or is iterable itself. By default this
does not return True for string objects.
The `ignore` argument defaults to a list of string types that are not
considered i... | def function[is_iter, parameter[y, ignore]]:
constant[
Test if an object is iterable, but not a string type.
Test if an object is an iterator or is iterable itself. By default this
does not return True for string objects.
The `ignore` argument defaults to a list of string types that are not
... | keyword[def] identifier[is_iter] ( identifier[y] , identifier[ignore] = identifier[six] . identifier[string_types] ):
literal[string]
keyword[if] identifier[ignore] keyword[and] identifier[isinstance] ( identifier[y] , identifier[ignore] ):
keyword[return] keyword[False]
keyword[try] :
... | def is_iter(y, ignore=six.string_types):
"""
Test if an object is iterable, but not a string type.
Test if an object is an iterator or is iterable itself. By default this
does not return True for string objects.
The `ignore` argument defaults to a list of string types that are not
considered i... |
def set_permission(permission, value, app):
"""Set a permission for the specified app
Value should be 'deny' or 'allow'
"""
# The object created to wrap PermissionSettingsModule is to work around
# an intermittent bug where it will sometimes be undefined.
script = """
const {classes: Cc... | def function[set_permission, parameter[permission, value, app]]:
constant[Set a permission for the specified app
Value should be 'deny' or 'allow'
]
variable[script] assign[=] constant[
const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
var a = {b: Cu.import... | keyword[def] identifier[set_permission] ( identifier[permission] , identifier[value] , identifier[app] ):
literal[string]
identifier[script] = literal[string]
identifier[app_url] = literal[string] + identifier[app]
identifier[run_marionette_script] ( identifier[script] %( identifier[p... | def set_permission(permission, value, app):
"""Set a permission for the specified app
Value should be 'deny' or 'allow'
"""
# The object created to wrap PermissionSettingsModule is to work around
# an intermittent bug where it will sometimes be undefined.
script = '\n const {classes: Cc,... |
def jackknife_stats(theta_subs, theta_full, N=None, d=1):
"""Compute Jackknife Estimates, SE, Bias, t-scores, p-values
Parameters:
-----------
theta_subs : ndarray
The metrics, estimates, parameters, etc. of
the model (see "func") for each subsample.
It is a <C x M> matrix, i.e.... | def function[jackknife_stats, parameter[theta_subs, theta_full, N, d]]:
constant[Compute Jackknife Estimates, SE, Bias, t-scores, p-values
Parameters:
-----------
theta_subs : ndarray
The metrics, estimates, parameters, etc. of
the model (see "func") for each subsample.
It i... | keyword[def] identifier[jackknife_stats] ( identifier[theta_subs] , identifier[theta_full] , identifier[N] = keyword[None] , identifier[d] = literal[int] ):
literal[string]
keyword[import] identifier[numpy] keyword[as] identifier[np]
identifier[theta_biased] = identifier[np] . identifier[mean... | def jackknife_stats(theta_subs, theta_full, N=None, d=1):
"""Compute Jackknife Estimates, SE, Bias, t-scores, p-values
Parameters:
-----------
theta_subs : ndarray
The metrics, estimates, parameters, etc. of
the model (see "func") for each subsample.
It is a <C x M> matrix, i.e.... |
def _get_with_criteria(self, criteria, offset=None, limit=None):
''' returns items selected by criteria
'''
SQL = SQLBuilder(self._table, criteria).select(offset=offset, limit=limit)
self._cursor.execute(SQL)
for item in self._cursor.fetchall():
yield self._make_item(... | def function[_get_with_criteria, parameter[self, criteria, offset, limit]]:
constant[ returns items selected by criteria
]
variable[SQL] assign[=] call[call[name[SQLBuilder], parameter[name[self]._table, name[criteria]]].select, parameter[]]
call[name[self]._cursor.execute, parameter[nam... | keyword[def] identifier[_get_with_criteria] ( identifier[self] , identifier[criteria] , identifier[offset] = keyword[None] , identifier[limit] = keyword[None] ):
literal[string]
identifier[SQL] = identifier[SQLBuilder] ( identifier[self] . identifier[_table] , identifier[criteria] ). identifier[sel... | def _get_with_criteria(self, criteria, offset=None, limit=None):
""" returns items selected by criteria
"""
SQL = SQLBuilder(self._table, criteria).select(offset=offset, limit=limit)
self._cursor.execute(SQL)
for item in self._cursor.fetchall():
yield self._make_item(item) # depends on ... |
def functions(self):
"""
A list of functions declared or defined in this module.
"""
return [v for v in self.globals.values()
if isinstance(v, values.Function)] | def function[functions, parameter[self]]:
constant[
A list of functions declared or defined in this module.
]
return[<ast.ListComp object at 0x7da1b194c250>] | keyword[def] identifier[functions] ( identifier[self] ):
literal[string]
keyword[return] [ identifier[v] keyword[for] identifier[v] keyword[in] identifier[self] . identifier[globals] . identifier[values] ()
keyword[if] identifier[isinstance] ( identifier[v] , identifier[values] . iden... | def functions(self):
"""
A list of functions declared or defined in this module.
"""
return [v for v in self.globals.values() if isinstance(v, values.Function)] |
def xs(self, key, axis=1):
"""
Return slice of panel along selected axis.
Parameters
----------
key : object
Label
axis : {'items', 'major', 'minor}, default 1/'major'
Returns
-------
y : ndim(self)-1
Notes
-----
... | def function[xs, parameter[self, key, axis]]:
constant[
Return slice of panel along selected axis.
Parameters
----------
key : object
Label
axis : {'items', 'major', 'minor}, default 1/'major'
Returns
-------
y : ndim(self)-1
... | keyword[def] identifier[xs] ( identifier[self] , identifier[key] , identifier[axis] = literal[int] ):
literal[string]
identifier[axis] = identifier[self] . identifier[_get_axis_number] ( identifier[axis] )
keyword[if] identifier[axis] == literal[int] :
keyword[return] identi... | def xs(self, key, axis=1):
"""
Return slice of panel along selected axis.
Parameters
----------
key : object
Label
axis : {'items', 'major', 'minor}, default 1/'major'
Returns
-------
y : ndim(self)-1
Notes
-----
... |
def get(self, CachableItem):
"""Returns current ICachedItem for ICachableItem
Args:
CachableItem: ICachableItem, used as a reference to find a cached version
Returns: ICachedItem or None, if CachableItem has not been cached
"""
return self.session.\
... | def function[get, parameter[self, CachableItem]]:
constant[Returns current ICachedItem for ICachableItem
Args:
CachableItem: ICachableItem, used as a reference to find a cached version
Returns: ICachedItem or None, if CachableItem has not been cached
]
r... | keyword[def] identifier[get] ( identifier[self] , identifier[CachableItem] ):
literal[string]
keyword[return] identifier[self] . identifier[session] . identifier[query] ( identifier[self] . identifier[mapper] . identifier[factory] (). identifier[__class__] ). identifier[filter] ( identifier[self] ... | def get(self, CachableItem):
"""Returns current ICachedItem for ICachableItem
Args:
CachableItem: ICachableItem, used as a reference to find a cached version
Returns: ICachedItem or None, if CachableItem has not been cached
"""
return self.session.query(self... |
def load_dataset(*args, **kwargs):
"""
`load_dataset` will be removed a future version of xarray. The current
behavior of this function can be achived by using
`tutorial.open_dataset(...).load()`.
See Also
--------
open_dataset
"""
warnings.warn(
"load_dataset` will be remov... | def function[load_dataset, parameter[]]:
constant[
`load_dataset` will be removed a future version of xarray. The current
behavior of this function can be achived by using
`tutorial.open_dataset(...).load()`.
See Also
--------
open_dataset
]
call[name[warnings].warn, paramet... | keyword[def] identifier[load_dataset] (* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[warnings] . identifier[warn] (
literal[string]
literal[string]
literal[string] ,
identifier[DeprecationWarning] , identifier[stacklevel] = literal[int] )
keyword[return]... | def load_dataset(*args, **kwargs):
"""
`load_dataset` will be removed a future version of xarray. The current
behavior of this function can be achived by using
`tutorial.open_dataset(...).load()`.
See Also
--------
open_dataset
"""
warnings.warn('load_dataset` will be removed in a f... |
def add_ch_grp_to_interface(
self, nexus_host, if_type, port, ch_grp):
"""Applies channel-group n to ethernet interface."""
if if_type != "ethernet":
LOG.error("Unexpected interface type %(iftype)s when "
"adding change group", {'iftype': if_type})
... | def function[add_ch_grp_to_interface, parameter[self, nexus_host, if_type, port, ch_grp]]:
constant[Applies channel-group n to ethernet interface.]
if compare[name[if_type] not_equal[!=] constant[ethernet]] begin[:]
call[name[LOG].error, parameter[constant[Unexpected interface type %(ift... | keyword[def] identifier[add_ch_grp_to_interface] (
identifier[self] , identifier[nexus_host] , identifier[if_type] , identifier[port] , identifier[ch_grp] ):
literal[string]
keyword[if] identifier[if_type] != literal[string] :
identifier[LOG] . identifier[error] ( literal[string]
... | def add_ch_grp_to_interface(self, nexus_host, if_type, port, ch_grp):
"""Applies channel-group n to ethernet interface."""
if if_type != 'ethernet':
LOG.error('Unexpected interface type %(iftype)s when adding change group', {'iftype': if_type})
return # depends on [control=['if'], data=['if_typ... |
def holidays(self, start=None, end=None, return_name=False):
"""
Returns a curve with holidays between start_date and end_date
Parameters
----------
start : starting date, datetime-like, optional
end : ending date, datetime-like, optional
return_name : bool, opti... | def function[holidays, parameter[self, start, end, return_name]]:
constant[
Returns a curve with holidays between start_date and end_date
Parameters
----------
start : starting date, datetime-like, optional
end : ending date, datetime-like, optional
return_name :... | keyword[def] identifier[holidays] ( identifier[self] , identifier[start] = keyword[None] , identifier[end] = keyword[None] , identifier[return_name] = keyword[False] ):
literal[string]
keyword[if] identifier[self] . identifier[rules] keyword[is] keyword[None] :
keyword[raise] ident... | def holidays(self, start=None, end=None, return_name=False):
"""
Returns a curve with holidays between start_date and end_date
Parameters
----------
start : starting date, datetime-like, optional
end : ending date, datetime-like, optional
return_name : bool, optional... |
def get_digital_channels(channel_list):
"""Goes through channel list and returns digital channels with ids
Dev1/port0/line08, Dev1/port0/line09... Dev1/port0/line30."""
dig_ids = digital_channel_ids()
dig_channels = []
for ln in dig_ids:
for ch in channel_list:
if ch.dct['id'] ==... | def function[get_digital_channels, parameter[channel_list]]:
constant[Goes through channel list and returns digital channels with ids
Dev1/port0/line08, Dev1/port0/line09... Dev1/port0/line30.]
variable[dig_ids] assign[=] call[name[digital_channel_ids], parameter[]]
variable[dig_channels] as... | keyword[def] identifier[get_digital_channels] ( identifier[channel_list] ):
literal[string]
identifier[dig_ids] = identifier[digital_channel_ids] ()
identifier[dig_channels] =[]
keyword[for] identifier[ln] keyword[in] identifier[dig_ids] :
keyword[for] identifier[ch] keyword[in] id... | def get_digital_channels(channel_list):
"""Goes through channel list and returns digital channels with ids
Dev1/port0/line08, Dev1/port0/line09... Dev1/port0/line30."""
dig_ids = digital_channel_ids()
dig_channels = []
for ln in dig_ids:
for ch in channel_list:
if ch.dct['id'] ==... |
def setParams(self, minSupport=0.3, minConfidence=0.8, itemsCol="items",
predictionCol="prediction", numPartitions=None):
"""
setParams(self, minSupport=0.3, minConfidence=0.8, itemsCol="items", \
predictionCol="prediction", numPartitions=None)
"""
kwa... | def function[setParams, parameter[self, minSupport, minConfidence, itemsCol, predictionCol, numPartitions]]:
constant[
setParams(self, minSupport=0.3, minConfidence=0.8, itemsCol="items", predictionCol="prediction", numPartitions=None)
]
variable[kwargs] assign[=] name[... | keyword[def] identifier[setParams] ( identifier[self] , identifier[minSupport] = literal[int] , identifier[minConfidence] = literal[int] , identifier[itemsCol] = literal[string] ,
identifier[predictionCol] = literal[string] , identifier[numPartitions] = keyword[None] ):
literal[string]
identifier[... | def setParams(self, minSupport=0.3, minConfidence=0.8, itemsCol='items', predictionCol='prediction', numPartitions=None):
"""
setParams(self, minSupport=0.3, minConfidence=0.8, itemsCol="items", predictionCol="prediction", numPartitions=None)
"""
kwargs = self._input_kwargs
... |
def authenticate_user(token):
"""
Add the content curation Authorizatino `token` header to `config.SESSION`.
"""
config.SESSION.headers.update({"Authorization": "Token {0}".format(token)})
try:
response = config.SESSION.post(config.authentication_url())
response.raise_for_status()
... | def function[authenticate_user, parameter[token]]:
constant[
Add the content curation Authorizatino `token` header to `config.SESSION`.
]
call[name[config].SESSION.headers.update, parameter[dictionary[[<ast.Constant object at 0x7da18f09d930>], [<ast.Call object at 0x7da18f09e6e0>]]]]
<ast.Tr... | keyword[def] identifier[authenticate_user] ( identifier[token] ):
literal[string]
identifier[config] . identifier[SESSION] . identifier[headers] . identifier[update] ({ literal[string] : literal[string] . identifier[format] ( identifier[token] )})
keyword[try] :
identifier[response] = identif... | def authenticate_user(token):
"""
Add the content curation Authorizatino `token` header to `config.SESSION`.
"""
config.SESSION.headers.update({'Authorization': 'Token {0}'.format(token)})
try:
response = config.SESSION.post(config.authentication_url())
response.raise_for_status()
... |
def expand_families(stmts_in, **kwargs):
"""Expand FamPlex Agents to individual genes.
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of statements to expand.
save : Optional[str]
The name of a pickle file to save the results (stmts_out) into.
Returns
... | def function[expand_families, parameter[stmts_in]]:
constant[Expand FamPlex Agents to individual genes.
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of statements to expand.
save : Optional[str]
The name of a pickle file to save the results (stmts_out... | keyword[def] identifier[expand_families] ( identifier[stmts_in] ,** identifier[kwargs] ):
literal[string]
keyword[from] identifier[indra] . identifier[tools] . identifier[expand_families] keyword[import] identifier[Expander]
identifier[logger] . identifier[info] ( literal[string] % identifier[len]... | def expand_families(stmts_in, **kwargs):
"""Expand FamPlex Agents to individual genes.
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of statements to expand.
save : Optional[str]
The name of a pickle file to save the results (stmts_out) into.
Returns
... |
def _construct(self, strings_collection):
"""
Naive generalized suffix tree construction algorithm,
with quadratic [O(n_1^2 + ... + n_m^2)] worst-case time complexity,
where m is the number of strings in collection.
"""
# 0. Add a unique character to eac... | def function[_construct, parameter[self, strings_collection]]:
constant[
Naive generalized suffix tree construction algorithm,
with quadratic [O(n_1^2 + ... + n_m^2)] worst-case time complexity,
where m is the number of strings in collection.
]
variable[strings_c... | keyword[def] identifier[_construct] ( identifier[self] , identifier[strings_collection] ):
literal[string]
identifier[strings_collection] = identifier[utils] . identifier[make_unique_endings] ( identifier[strings_collection] )
identifier[root] = identifier[ast] . identi... | def _construct(self, strings_collection):
"""
Naive generalized suffix tree construction algorithm,
with quadratic [O(n_1^2 + ... + n_m^2)] worst-case time complexity,
where m is the number of strings in collection.
"""
# 0. Add a unique character to each string in the c... |
def meta_model_fit(X_train, y_train, svm_hardness, fit_intercept, number_of_threads, regressor_type="LinearSVR"):
"""
Trains meta-labeler for predicting number of labels for each user.
Based on: Tang, L., Rajan, S., & Narayanan, V. K. (2009, April).
Large scale multi-label classification via ... | def function[meta_model_fit, parameter[X_train, y_train, svm_hardness, fit_intercept, number_of_threads, regressor_type]]:
constant[
Trains meta-labeler for predicting number of labels for each user.
Based on: Tang, L., Rajan, S., & Narayanan, V. K. (2009, April).
Large scale multi-label ... | keyword[def] identifier[meta_model_fit] ( identifier[X_train] , identifier[y_train] , identifier[svm_hardness] , identifier[fit_intercept] , identifier[number_of_threads] , identifier[regressor_type] = literal[string] ):
literal[string]
keyword[if] identifier[regressor_type] == literal[string] :
... | def meta_model_fit(X_train, y_train, svm_hardness, fit_intercept, number_of_threads, regressor_type='LinearSVR'):
"""
Trains meta-labeler for predicting number of labels for each user.
Based on: Tang, L., Rajan, S., & Narayanan, V. K. (2009, April).
Large scale multi-label classification via ... |
def disable_dao_fork(chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
Set the ``support_dao_fork`` flag to ``False`` on the
:class:`~eth.vm.forks.homestead.HomesteadVM`. Requires that presence of
the :class:`~eth.vm.forks.homestead.HomesteadVM` in the
``vm_configuration``
"""
homstead... | def function[disable_dao_fork, parameter[chain_class]]:
constant[
Set the ``support_dao_fork`` flag to ``False`` on the
:class:`~eth.vm.forks.homestead.HomesteadVM`. Requires that presence of
the :class:`~eth.vm.forks.homestead.HomesteadVM` in the
``vm_configuration``
]
variable[ho... | keyword[def] identifier[disable_dao_fork] ( identifier[chain_class] : identifier[Type] [ identifier[BaseChain] ])-> identifier[Type] [ identifier[BaseChain] ]:
literal[string]
identifier[homstead_vms_found] = identifier[any] (
identifier[_is_homestead] ( identifier[vm_class] ) keyword[for] identifier... | def disable_dao_fork(chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
Set the ``support_dao_fork`` flag to ``False`` on the
:class:`~eth.vm.forks.homestead.HomesteadVM`. Requires that presence of
the :class:`~eth.vm.forks.homestead.HomesteadVM` in the
``vm_configuration``
"""
homstead... |
def dmtoind(dm, f_min, f_max, nchan0, inttime, it):
"""
Given FDMT state, return indices to slice partial FDMT solution and sump to a given DM
"""
# maxDT = dmtodt(dm) # need to write
if it>0:
correction = dF/2.
else:
correction = 0
shift = []
nchan = nchan0/2**(iterati... | def function[dmtoind, parameter[dm, f_min, f_max, nchan0, inttime, it]]:
constant[
Given FDMT state, return indices to slice partial FDMT solution and sump to a given DM
]
if compare[name[it] greater[>] constant[0]] begin[:]
variable[correction] assign[=] binary_operation[name[dF... | keyword[def] identifier[dmtoind] ( identifier[dm] , identifier[f_min] , identifier[f_max] , identifier[nchan0] , identifier[inttime] , identifier[it] ):
literal[string]
keyword[if] identifier[it] > literal[int] :
identifier[correction] = identifier[dF] / literal[int]
keyword[else] :
... | def dmtoind(dm, f_min, f_max, nchan0, inttime, it):
"""
Given FDMT state, return indices to slice partial FDMT solution and sump to a given DM
"""
# maxDT = dmtodt(dm) # need to write
if it > 0:
correction = dF / 2.0 # depends on [control=['if'], data=[]]
else:
correction = 0... |
def get_clusters_representation(chromosome, count_clusters=None):
""" Convert chromosome to cluster representation:
chromosome : [0, 1, 1, 0, 2, 3, 3]
clusters: [[0, 3], [1, 2], [4], [5, 6]]
"""
if count_clusters is None:
count_clusters = ga_math.calc... | def function[get_clusters_representation, parameter[chromosome, count_clusters]]:
constant[ Convert chromosome to cluster representation:
chromosome : [0, 1, 1, 0, 2, 3, 3]
clusters: [[0, 3], [1, 2], [4], [5, 6]]
]
if compare[name[count_clusters] is constant[None]... | keyword[def] identifier[get_clusters_representation] ( identifier[chromosome] , identifier[count_clusters] = keyword[None] ):
literal[string]
keyword[if] identifier[count_clusters] keyword[is] keyword[None] :
identifier[count_clusters] = identifier[ga_math] . identifier[calc_count_... | def get_clusters_representation(chromosome, count_clusters=None):
""" Convert chromosome to cluster representation:
chromosome : [0, 1, 1, 0, 2, 3, 3]
clusters: [[0, 3], [1, 2], [4], [5, 6]]
"""
if count_clusters is None:
count_clusters = ga_math.calc_count_center... |
def _lclist_parallel_worker(task):
'''This is a parallel worker for makelclist.
Parameters
----------
task : tuple
This is a tuple containing the following items:
task[0] = lcf
task[1] = columns
task[2] = lcformat
task[3] = lcformatdir
task[4] = lcndetk... | def function[_lclist_parallel_worker, parameter[task]]:
constant[This is a parallel worker for makelclist.
Parameters
----------
task : tuple
This is a tuple containing the following items:
task[0] = lcf
task[1] = columns
task[2] = lcformat
task[3] = lcform... | keyword[def] identifier[_lclist_parallel_worker] ( identifier[task] ):
literal[string]
identifier[lcf] , identifier[columns] , identifier[lcformat] , identifier[lcformatdir] , identifier[lcndetkey] = identifier[task]
keyword[try] :
identifier[formatinfo] = identifier[ge... | def _lclist_parallel_worker(task):
"""This is a parallel worker for makelclist.
Parameters
----------
task : tuple
This is a tuple containing the following items:
task[0] = lcf
task[1] = columns
task[2] = lcformat
task[3] = lcformatdir
task[4] = lcndetk... |
def on_state_changed(self, state):
"""
Connects/disconnects slots to/from signals when the mode state
changed.
"""
super(GoToDefinitionMode, self).on_state_changed(state)
if state:
self.editor.mouse_moved.connect(self._on_mouse_moved)
self.editor.m... | def function[on_state_changed, parameter[self, state]]:
constant[
Connects/disconnects slots to/from signals when the mode state
changed.
]
call[call[name[super], parameter[name[GoToDefinitionMode], name[self]]].on_state_changed, parameter[name[state]]]
if name[state] beg... | keyword[def] identifier[on_state_changed] ( identifier[self] , identifier[state] ):
literal[string]
identifier[super] ( identifier[GoToDefinitionMode] , identifier[self] ). identifier[on_state_changed] ( identifier[state] )
keyword[if] identifier[state] :
identifier[self] . i... | def on_state_changed(self, state):
"""
Connects/disconnects slots to/from signals when the mode state
changed.
"""
super(GoToDefinitionMode, self).on_state_changed(state)
if state:
self.editor.mouse_moved.connect(self._on_mouse_moved)
self.editor.mouse_released.connec... |
def plot_factor_contribution_to_perf(
perf_attrib_data,
ax=None,
title='Cumulative common returns attribution',
):
"""
Plot each factor's contribution to performance.
Parameters
----------
perf_attrib_data : pd.DataFrame
df with factors, common returns, and specific ... | def function[plot_factor_contribution_to_perf, parameter[perf_attrib_data, ax, title]]:
constant[
Plot each factor's contribution to performance.
Parameters
----------
perf_attrib_data : pd.DataFrame
df with factors, common returns, and specific returns as columns,
and datetimes... | keyword[def] identifier[plot_factor_contribution_to_perf] (
identifier[perf_attrib_data] ,
identifier[ax] = keyword[None] ,
identifier[title] = literal[string] ,
):
literal[string]
keyword[if] identifier[ax] keyword[is] keyword[None] :
identifier[ax] = identifier[plt] . identifier[gca] ()
... | def plot_factor_contribution_to_perf(perf_attrib_data, ax=None, title='Cumulative common returns attribution'):
"""
Plot each factor's contribution to performance.
Parameters
----------
perf_attrib_data : pd.DataFrame
df with factors, common returns, and specific returns as columns,
... |
def connect(self, protocol=None):
"""Initialize DAP IO pins for JTAG or SWD"""
# Convert protocol to port enum.
if protocol is not None:
port = self.PORT_MAP[protocol]
else:
port = DAPAccess.PORT.DEFAULT
try:
self._link.connect(port)
... | def function[connect, parameter[self, protocol]]:
constant[Initialize DAP IO pins for JTAG or SWD]
if compare[name[protocol] is_not constant[None]] begin[:]
variable[port] assign[=] call[name[self].PORT_MAP][name[protocol]]
<ast.Try object at 0x7da1b18a2500>
variable[actualMo... | keyword[def] identifier[connect] ( identifier[self] , identifier[protocol] = keyword[None] ):
literal[string]
keyword[if] identifier[protocol] keyword[is] keyword[not] keyword[None] :
identifier[port] = identifier[self] . identifier[PORT_MAP] [ identifier[protocol] ]
... | def connect(self, protocol=None):
"""Initialize DAP IO pins for JTAG or SWD"""
# Convert protocol to port enum.
if protocol is not None:
port = self.PORT_MAP[protocol] # depends on [control=['if'], data=['protocol']]
else:
port = DAPAccess.PORT.DEFAULT
try:
self._link.connec... |
def uavionix_adsb_transceiver_health_report_send(self, rfHealth, force_mavlink1=False):
'''
Transceiver heartbeat with health report (updated every 10s)
rfHealth : ADS-B transponder messages (uint8_t)
'''
return self.send... | def function[uavionix_adsb_transceiver_health_report_send, parameter[self, rfHealth, force_mavlink1]]:
constant[
Transceiver heartbeat with health report (updated every 10s)
rfHealth : ADS-B transponder messages (uint8_t)
]
return[call[name[... | keyword[def] identifier[uavionix_adsb_transceiver_health_report_send] ( identifier[self] , identifier[rfHealth] , identifier[force_mavlink1] = keyword[False] ):
literal[string]
keyword[return] identifier[self] . identifier[send] ( identifier[self] . identifier[uavionix_adsb_transce... | def uavionix_adsb_transceiver_health_report_send(self, rfHealth, force_mavlink1=False):
"""
Transceiver heartbeat with health report (updated every 10s)
rfHealth : ADS-B transponder messages (uint8_t)
"""
return self.send(self.uavionix_adsb_tran... |
def _get_ansible_playbook(self, playbook, **kwargs):
"""
Get an instance of AnsiblePlaybook and returns it.
:param playbook: A string containing an absolute path to a
provisioner's playbook.
:param kwargs: An optional keyword arguments.
:return: object
"""
... | def function[_get_ansible_playbook, parameter[self, playbook]]:
constant[
Get an instance of AnsiblePlaybook and returns it.
:param playbook: A string containing an absolute path to a
provisioner's playbook.
:param kwargs: An optional keyword arguments.
:return: object
... | keyword[def] identifier[_get_ansible_playbook] ( identifier[self] , identifier[playbook] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[ansible_playbook] . identifier[AnsiblePlaybook] ( identifier[playbook] , identifier[self] . identifier[_config] ,
** identifier[kwar... | def _get_ansible_playbook(self, playbook, **kwargs):
"""
Get an instance of AnsiblePlaybook and returns it.
:param playbook: A string containing an absolute path to a
provisioner's playbook.
:param kwargs: An optional keyword arguments.
:return: object
"""
retur... |
def load(cls, sc, path):
"""Load an IsotonicRegressionModel."""
java_model = sc._jvm.org.apache.spark.mllib.regression.IsotonicRegressionModel.load(
sc._jsc.sc(), path)
py_boundaries = _java2py(sc, java_model.boundaryVector()).toArray()
py_predictions = _java2py(sc, java_mode... | def function[load, parameter[cls, sc, path]]:
constant[Load an IsotonicRegressionModel.]
variable[java_model] assign[=] call[name[sc]._jvm.org.apache.spark.mllib.regression.IsotonicRegressionModel.load, parameter[call[name[sc]._jsc.sc, parameter[]], name[path]]]
variable[py_boundaries] assign[=]... | keyword[def] identifier[load] ( identifier[cls] , identifier[sc] , identifier[path] ):
literal[string]
identifier[java_model] = identifier[sc] . identifier[_jvm] . identifier[org] . identifier[apache] . identifier[spark] . identifier[mllib] . identifier[regression] . identifier[IsotonicRegressionMo... | def load(cls, sc, path):
"""Load an IsotonicRegressionModel."""
java_model = sc._jvm.org.apache.spark.mllib.regression.IsotonicRegressionModel.load(sc._jsc.sc(), path)
py_boundaries = _java2py(sc, java_model.boundaryVector()).toArray()
py_predictions = _java2py(sc, java_model.predictionVector()).toArray... |
def visit_Assignment(self, node):
"""Visitor for `Assignment` AST node."""
var_name = node.left.identifier.name
var_symbol = self.table[var_name]
if var_symbol is not None and not var_symbol.is_mutable:
raise SementicError(f"Re-assignment of immutable variable `{var_name}`."... | def function[visit_Assignment, parameter[self, node]]:
constant[Visitor for `Assignment` AST node.]
variable[var_name] assign[=] name[node].left.identifier.name
variable[var_symbol] assign[=] call[name[self].table][name[var_name]]
if <ast.BoolOp object at 0x7da1b08051b0> begin[:]
... | keyword[def] identifier[visit_Assignment] ( identifier[self] , identifier[node] ):
literal[string]
identifier[var_name] = identifier[node] . identifier[left] . identifier[identifier] . identifier[name]
identifier[var_symbol] = identifier[self] . identifier[table] [ identifier[var_name] ]
... | def visit_Assignment(self, node):
"""Visitor for `Assignment` AST node."""
var_name = node.left.identifier.name
var_symbol = self.table[var_name]
if var_symbol is not None and (not var_symbol.is_mutable):
raise SementicError(f'Re-assignment of immutable variable `{var_name}`.') # depends on [co... |
def _maximization(X, posterior, force_weights=None):
"""Estimate new centers, weights, and concentrations from
Parameters
----------
posterior : array, [n_centers, n_examples]
The posterior matrix from the expectation step.
force_weights : None or array, [n_centers, ]
If None is pa... | def function[_maximization, parameter[X, posterior, force_weights]]:
constant[Estimate new centers, weights, and concentrations from
Parameters
----------
posterior : array, [n_centers, n_examples]
The posterior matrix from the expectation step.
force_weights : None or array, [n_center... | keyword[def] identifier[_maximization] ( identifier[X] , identifier[posterior] , identifier[force_weights] = keyword[None] ):
literal[string]
identifier[n_examples] , identifier[n_features] = identifier[X] . identifier[shape]
identifier[n_clusters] , identifier[n_examples] = identifier[posterior] . i... | def _maximization(X, posterior, force_weights=None):
"""Estimate new centers, weights, and concentrations from
Parameters
----------
posterior : array, [n_centers, n_examples]
The posterior matrix from the expectation step.
force_weights : None or array, [n_centers, ]
If None is pa... |
def viterbi_binary(prob, transition, p_state=None, p_init=None, return_logp=False):
'''Viterbi decoding from binary (multi-label), discriminative state predictions.
Given a sequence of conditional state predictions `prob[s, t]`,
indicating the conditional likelihood of state `s` being active
conditiona... | def function[viterbi_binary, parameter[prob, transition, p_state, p_init, return_logp]]:
constant[Viterbi decoding from binary (multi-label), discriminative state predictions.
Given a sequence of conditional state predictions `prob[s, t]`,
indicating the conditional likelihood of state `s` being active... | keyword[def] identifier[viterbi_binary] ( identifier[prob] , identifier[transition] , identifier[p_state] = keyword[None] , identifier[p_init] = keyword[None] , identifier[return_logp] = keyword[False] ):
literal[string]
identifier[prob] = identifier[np] . identifier[atleast_2d] ( identifier[prob] )
... | def viterbi_binary(prob, transition, p_state=None, p_init=None, return_logp=False):
"""Viterbi decoding from binary (multi-label), discriminative state predictions.
Given a sequence of conditional state predictions `prob[s, t]`,
indicating the conditional likelihood of state `s` being active
conditiona... |
def repeat_masker_iterator(fh, alignment_index=None,
header=True, verbose=False):
"""
Iterator for repeatmasker coordinate annotation files. These files describe
the location of repeat occurrences. There is (optionally) a two-line header
with the names of the fields (ignored by the it... | def function[repeat_masker_iterator, parameter[fh, alignment_index, header, verbose]]:
constant[
Iterator for repeatmasker coordinate annotation files. These files describe
the location of repeat occurrences. There is (optionally) a two-line header
with the names of the fields (ignored by the iterator, if... | keyword[def] identifier[repeat_masker_iterator] ( identifier[fh] , identifier[alignment_index] = keyword[None] ,
identifier[header] = keyword[True] , identifier[verbose] = keyword[False] ):
literal[string]
identifier[strm] = identifier[fh]
keyword[if] identifier[type] ( identifier[fh] ). identifier[__na... | def repeat_masker_iterator(fh, alignment_index=None, header=True, verbose=False):
"""
Iterator for repeatmasker coordinate annotation files. These files describe
the location of repeat occurrences. There is (optionally) a two-line header
with the names of the fields (ignored by the iterator, if present). Each... |
def remove_option(self, section, option):
"""Remove an option."""
if not section or section == DEFAULTSECT:
sectdict = self._defaults
else:
try:
sectdict = self._sections[section]
except KeyError:
raise NoSectionError(section)
... | def function[remove_option, parameter[self, section, option]]:
constant[Remove an option.]
if <ast.BoolOp object at 0x7da18f00da20> begin[:]
variable[sectdict] assign[=] name[self]._defaults
variable[option] assign[=] call[name[self].optionxform, parameter[name[option]]]
... | keyword[def] identifier[remove_option] ( identifier[self] , identifier[section] , identifier[option] ):
literal[string]
keyword[if] keyword[not] identifier[section] keyword[or] identifier[section] == identifier[DEFAULTSECT] :
identifier[sectdict] = identifier[self] . identifier[_de... | def remove_option(self, section, option):
"""Remove an option."""
if not section or section == DEFAULTSECT:
sectdict = self._defaults # depends on [control=['if'], data=[]]
else:
try:
sectdict = self._sections[section] # depends on [control=['try'], data=[]]
except KeyE... |
def f_delete_items(self, iterator, *args, **kwargs):
"""Deletes items from storage on disk.
Per default the item is NOT removed from the trajectory.
Links are NOT deleted on the hard disk, please delete links manually before deleting
data!
:param iterator:
A seque... | def function[f_delete_items, parameter[self, iterator]]:
constant[Deletes items from storage on disk.
Per default the item is NOT removed from the trajectory.
Links are NOT deleted on the hard disk, please delete links manually before deleting
data!
:param iterator:
... | keyword[def] identifier[f_delete_items] ( identifier[self] , identifier[iterator] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[remove_from_trajectory] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[False] )
identifier[recursive] = identifier... | def f_delete_items(self, iterator, *args, **kwargs):
"""Deletes items from storage on disk.
Per default the item is NOT removed from the trajectory.
Links are NOT deleted on the hard disk, please delete links manually before deleting
data!
:param iterator:
A sequence ... |
def update(self, list_id, webhook_id, data):
"""
Update the settings for an existing webhook.
:param list_id: The unique id for the list
:type list_id: :py:class:`str`
:param webhook_id: The unique id for the webhook
:type webhook_id: :py:class:`str`
"""
... | def function[update, parameter[self, list_id, webhook_id, data]]:
constant[
Update the settings for an existing webhook.
:param list_id: The unique id for the list
:type list_id: :py:class:`str`
:param webhook_id: The unique id for the webhook
:type webhook_id: :py:class... | keyword[def] identifier[update] ( identifier[self] , identifier[list_id] , identifier[webhook_id] , identifier[data] ):
literal[string]
identifier[self] . identifier[list_id] = identifier[list_id]
identifier[self] . identifier[webhook_id] = identifier[webhook_id]
keyword[return]... | def update(self, list_id, webhook_id, data):
"""
Update the settings for an existing webhook.
:param list_id: The unique id for the list
:type list_id: :py:class:`str`
:param webhook_id: The unique id for the webhook
:type webhook_id: :py:class:`str`
"""
self.lis... |
def _find_and_replace(self, date_string, captures):
"""
:warning: when multiple tz matches exist the last sorted capture will trump
:param date_string:
:return: date_string, tz_string
"""
# add timezones to replace
cloned_replacements = copy.copy(REPLACEMENTS) # ... | def function[_find_and_replace, parameter[self, date_string, captures]]:
constant[
:warning: when multiple tz matches exist the last sorted capture will trump
:param date_string:
:return: date_string, tz_string
]
variable[cloned_replacements] assign[=] call[name[copy].cop... | keyword[def] identifier[_find_and_replace] ( identifier[self] , identifier[date_string] , identifier[captures] ):
literal[string]
identifier[cloned_replacements] = identifier[copy] . identifier[copy] ( identifier[REPLACEMENTS] )
keyword[for] identifier[tz_string] keyword[in] id... | def _find_and_replace(self, date_string, captures):
"""
:warning: when multiple tz matches exist the last sorted capture will trump
:param date_string:
:return: date_string, tz_string
"""
# add timezones to replace
cloned_replacements = copy.copy(REPLACEMENTS) # don't mutate... |
def _symbol_bars(
self,
symbols,
size,
_from=None,
to=None,
limit=None):
'''
Query historic_agg either minute or day in parallel
for multiple symbols, and return in dict.
symbols: list[str]
size: str ('da... | def function[_symbol_bars, parameter[self, symbols, size, _from, to, limit]]:
constant[
Query historic_agg either minute or day in parallel
for multiple symbols, and return in dict.
symbols: list[str]
size: str ('day', 'minute')
_from: str or pd.Timestamp
to... | keyword[def] identifier[_symbol_bars] (
identifier[self] ,
identifier[symbols] ,
identifier[size] ,
identifier[_from] = keyword[None] ,
identifier[to] = keyword[None] ,
identifier[limit] = keyword[None] ):
literal[string]
keyword[assert] identifier[size] keyword[in] ( literal[string] , lite... | def _symbol_bars(self, symbols, size, _from=None, to=None, limit=None):
"""
Query historic_agg either minute or day in parallel
for multiple symbols, and return in dict.
symbols: list[str]
size: str ('day', 'minute')
_from: str or pd.Timestamp
to: str or pd... |
def leaf_list(cls, name, parent=None, interleave=None):
"""Create _list_ node for a leaf-list."""
node = cls("_list_", parent, interleave=interleave)
node.attr["name"] = name
node.keys = None
node.minEl = "0"
node.maxEl = None
node.occur = 3
return node | def function[leaf_list, parameter[cls, name, parent, interleave]]:
constant[Create _list_ node for a leaf-list.]
variable[node] assign[=] call[name[cls], parameter[constant[_list_], name[parent]]]
call[name[node].attr][constant[name]] assign[=] name[name]
name[node].keys assign[=] consta... | keyword[def] identifier[leaf_list] ( identifier[cls] , identifier[name] , identifier[parent] = keyword[None] , identifier[interleave] = keyword[None] ):
literal[string]
identifier[node] = identifier[cls] ( literal[string] , identifier[parent] , identifier[interleave] = identifier[interleave] )
... | def leaf_list(cls, name, parent=None, interleave=None):
"""Create _list_ node for a leaf-list."""
node = cls('_list_', parent, interleave=interleave)
node.attr['name'] = name
node.keys = None
node.minEl = '0'
node.maxEl = None
node.occur = 3
return node |
def pip(name):
'''Parse requirements file'''
with io.open(os.path.join('requirements', '{0}.pip'.format(name))) as f:
return f.readlines() | def function[pip, parameter[name]]:
constant[Parse requirements file]
with call[name[io].open, parameter[call[name[os].path.join, parameter[constant[requirements], call[constant[{0}.pip].format, parameter[name[name]]]]]]] begin[:]
return[call[name[f].readlines, parameter[]]] | keyword[def] identifier[pip] ( identifier[name] ):
literal[string]
keyword[with] identifier[io] . identifier[open] ( identifier[os] . identifier[path] . identifier[join] ( literal[string] , literal[string] . identifier[format] ( identifier[name] ))) keyword[as] identifier[f] :
keyword[return] i... | def pip(name):
"""Parse requirements file"""
with io.open(os.path.join('requirements', '{0}.pip'.format(name))) as f:
return f.readlines() # depends on [control=['with'], data=['f']] |
def get_imports(self, ast_body):
"""
Return all the import statements given an AST body (AST nodes).
Args:
ast_body (compiled code's body): the body to filter.
Returns:
list of dict: the import statements.
"""
imports = []
for node in ast... | def function[get_imports, parameter[self, ast_body]]:
constant[
Return all the import statements given an AST body (AST nodes).
Args:
ast_body (compiled code's body): the body to filter.
Returns:
list of dict: the import statements.
]
variable[im... | keyword[def] identifier[get_imports] ( identifier[self] , identifier[ast_body] ):
literal[string]
identifier[imports] =[]
keyword[for] identifier[node] keyword[in] identifier[ast_body] :
keyword[if] identifier[isinstance] ( identifier[node] , identifier[ast] . identifier[I... | def get_imports(self, ast_body):
"""
Return all the import statements given an AST body (AST nodes).
Args:
ast_body (compiled code's body): the body to filter.
Returns:
list of dict: the import statements.
"""
imports = []
for node in ast_body:
... |
def challenge_hash(peer_challenge, authenticator_challenge, username):
"""ChallengeHash"""
sha_hash = hashlib.sha1()
sha_hash.update(peer_challenge)
sha_hash.update(authenticator_challenge)
sha_hash.update(username)
return sha_hash.digest()[:8] | def function[challenge_hash, parameter[peer_challenge, authenticator_challenge, username]]:
constant[ChallengeHash]
variable[sha_hash] assign[=] call[name[hashlib].sha1, parameter[]]
call[name[sha_hash].update, parameter[name[peer_challenge]]]
call[name[sha_hash].update, parameter[name[a... | keyword[def] identifier[challenge_hash] ( identifier[peer_challenge] , identifier[authenticator_challenge] , identifier[username] ):
literal[string]
identifier[sha_hash] = identifier[hashlib] . identifier[sha1] ()
identifier[sha_hash] . identifier[update] ( identifier[peer_challenge] )
identifier... | def challenge_hash(peer_challenge, authenticator_challenge, username):
"""ChallengeHash"""
sha_hash = hashlib.sha1()
sha_hash.update(peer_challenge)
sha_hash.update(authenticator_challenge)
sha_hash.update(username)
return sha_hash.digest()[:8] |
async def apply(self, sender: str, recipient: str, mailbox: str,
append_msg: AppendMessage) \
-> Tuple[Optional[str], AppendMessage]:
"""Run the filter and return the mailbox where it should be appended,
or None to discard, and the message to be appended, which is usually... | <ast.AsyncFunctionDef object at 0x7da20e9551e0> | keyword[async] keyword[def] identifier[apply] ( identifier[self] , identifier[sender] : identifier[str] , identifier[recipient] : identifier[str] , identifier[mailbox] : identifier[str] ,
identifier[append_msg] : identifier[AppendMessage] )-> identifier[Tuple] [ identifier[Optional] [ identifier[str] ], identifier[... | async def apply(self, sender: str, recipient: str, mailbox: str, append_msg: AppendMessage) -> Tuple[Optional[str], AppendMessage]:
"""Run the filter and return the mailbox where it should be appended,
or None to discard, and the message to be appended, which is usually
the same as ``append_msg``.
... |
def wait_for_ready(self, instance_id, limit=14400, delay=10, pending=False):
"""Determine if a Server is ready.
A server is ready when no transactions are running on it.
:param int instance_id: The instance ID with the pending transaction
:param int limit: The maximum amount of seconds... | def function[wait_for_ready, parameter[self, instance_id, limit, delay, pending]]:
constant[Determine if a Server is ready.
A server is ready when no transactions are running on it.
:param int instance_id: The instance ID with the pending transaction
:param int limit: The maximum amoun... | keyword[def] identifier[wait_for_ready] ( identifier[self] , identifier[instance_id] , identifier[limit] = literal[int] , identifier[delay] = literal[int] , identifier[pending] = keyword[False] ):
literal[string]
identifier[now] = identifier[time] . identifier[time] ()
identifier[until] = ... | def wait_for_ready(self, instance_id, limit=14400, delay=10, pending=False):
"""Determine if a Server is ready.
A server is ready when no transactions are running on it.
:param int instance_id: The instance ID with the pending transaction
:param int limit: The maximum amount of seconds to ... |
def class2md(self, cls, depth=2):
"""Takes a class and creates markdown text to document its methods and variables.
"""
section = "#" * depth
subsection = "#" * (depth + 2)
clsname = cls.__name__
modname = cls.__module__
header = clsname
path = self.get_s... | def function[class2md, parameter[self, cls, depth]]:
constant[Takes a class and creates markdown text to document its methods and variables.
]
variable[section] assign[=] binary_operation[constant[#] * name[depth]]
variable[subsection] assign[=] binary_operation[constant[#] * binary_oper... | keyword[def] identifier[class2md] ( identifier[self] , identifier[cls] , identifier[depth] = literal[int] ):
literal[string]
identifier[section] = literal[string] * identifier[depth]
identifier[subsection] = literal[string] *( identifier[depth] + literal[int] )
identifier[clsnam... | def class2md(self, cls, depth=2):
"""Takes a class and creates markdown text to document its methods and variables.
"""
section = '#' * depth
subsection = '#' * (depth + 2)
clsname = cls.__name__
modname = cls.__module__
header = clsname
path = self.get_src_path(cls)
doc = self.d... |
def _get_item_labels(self, item, no_from_study=False):
"""
Returns the labels for the XNAT subject and sessions given
the frequency and provided IDs.
"""
subject_id = self.inv_map_subject_id(item.subject_id)
visit_id = self.inv_map_visit_id(item.visit_id)
subj_lab... | def function[_get_item_labels, parameter[self, item, no_from_study]]:
constant[
Returns the labels for the XNAT subject and sessions given
the frequency and provided IDs.
]
variable[subject_id] assign[=] call[name[self].inv_map_subject_id, parameter[name[item].subject_id]]
... | keyword[def] identifier[_get_item_labels] ( identifier[self] , identifier[item] , identifier[no_from_study] = keyword[False] ):
literal[string]
identifier[subject_id] = identifier[self] . identifier[inv_map_subject_id] ( identifier[item] . identifier[subject_id] )
identifier[visit_id] = id... | def _get_item_labels(self, item, no_from_study=False):
"""
Returns the labels for the XNAT subject and sessions given
the frequency and provided IDs.
"""
subject_id = self.inv_map_subject_id(item.subject_id)
visit_id = self.inv_map_visit_id(item.visit_id)
(subj_label, sess_label)... |
def get_network_params(self):
"""
get network params
"""
ip = self.__address[0]
mask = b''
gate = b''
cmd_response = self.__send_command(const.CMD_OPTIONS_RRQ, b'IPAddress\x00', 1024)
if cmd_response.get('status'):
ip = (self.__data.split(b'=',... | def function[get_network_params, parameter[self]]:
constant[
get network params
]
variable[ip] assign[=] call[name[self].__address][constant[0]]
variable[mask] assign[=] constant[b'']
variable[gate] assign[=] constant[b'']
variable[cmd_response] assign[=] call[nam... | keyword[def] identifier[get_network_params] ( identifier[self] ):
literal[string]
identifier[ip] = identifier[self] . identifier[__address] [ literal[int] ]
identifier[mask] = literal[string]
identifier[gate] = literal[string]
identifier[cmd_response] = identifier[self]... | def get_network_params(self):
"""
get network params
"""
ip = self.__address[0]
mask = b''
gate = b''
cmd_response = self.__send_command(const.CMD_OPTIONS_RRQ, b'IPAddress\x00', 1024)
if cmd_response.get('status'):
ip = self.__data.split(b'=', 1)[-1].split(b'\x00')[0] # ... |
def format_time(time_string):
'''
Format time string with invalid time elements in hours/minutes/seconds
Format for the timestring needs to be "%Y_%m_%d_%H_%M_%S"
e.g. 2014_03_31_24_10_11 => 2014_04_01_00_10_11
'''
subseconds = False
data = time_string.split("_")
hours, minutes, seconds... | def function[format_time, parameter[time_string]]:
constant[
Format time string with invalid time elements in hours/minutes/seconds
Format for the timestring needs to be "%Y_%m_%d_%H_%M_%S"
e.g. 2014_03_31_24_10_11 => 2014_04_01_00_10_11
]
variable[subseconds] assign[=] constant[False]
... | keyword[def] identifier[format_time] ( identifier[time_string] ):
literal[string]
identifier[subseconds] = keyword[False]
identifier[data] = identifier[time_string] . identifier[split] ( literal[string] )
identifier[hours] , identifier[minutes] , identifier[seconds] = identifier[int] ( identifie... | def format_time(time_string):
"""
Format time string with invalid time elements in hours/minutes/seconds
Format for the timestring needs to be "%Y_%m_%d_%H_%M_%S"
e.g. 2014_03_31_24_10_11 => 2014_04_01_00_10_11
"""
subseconds = False
data = time_string.split('_')
(hours, minutes, second... |
def fromtree(cls, tree):
"""
Create a METS from an ElementTree or Element.
:param ElementTree tree: ElementTree to build a METS document from.
"""
mets = cls()
mets.tree = tree
mets._parse_tree(tree)
return mets | def function[fromtree, parameter[cls, tree]]:
constant[
Create a METS from an ElementTree or Element.
:param ElementTree tree: ElementTree to build a METS document from.
]
variable[mets] assign[=] call[name[cls], parameter[]]
name[mets].tree assign[=] name[tree]
... | keyword[def] identifier[fromtree] ( identifier[cls] , identifier[tree] ):
literal[string]
identifier[mets] = identifier[cls] ()
identifier[mets] . identifier[tree] = identifier[tree]
identifier[mets] . identifier[_parse_tree] ( identifier[tree] )
keyword[return] identi... | def fromtree(cls, tree):
"""
Create a METS from an ElementTree or Element.
:param ElementTree tree: ElementTree to build a METS document from.
"""
mets = cls()
mets.tree = tree
mets._parse_tree(tree)
return mets |
def finalize(self):
"""Output the default sprite names found in the project."""
print('{} default sprite names found:'.format(self.total_default))
for name in self.list_default:
print(name) | def function[finalize, parameter[self]]:
constant[Output the default sprite names found in the project.]
call[name[print], parameter[call[constant[{} default sprite names found:].format, parameter[name[self].total_default]]]]
for taget[name[name]] in starred[name[self].list_default] begin[:]
... | keyword[def] identifier[finalize] ( identifier[self] ):
literal[string]
identifier[print] ( literal[string] . identifier[format] ( identifier[self] . identifier[total_default] ))
keyword[for] identifier[name] keyword[in] identifier[self] . identifier[list_default] :
identif... | def finalize(self):
"""Output the default sprite names found in the project."""
print('{} default sprite names found:'.format(self.total_default))
for name in self.list_default:
print(name) # depends on [control=['for'], data=['name']] |
def visible_devices(self):
"""Unify all visible devices across all connected adapters
Returns:
dict: A dictionary mapping UUIDs to device information dictionaries
"""
devs = {}
for device_id, adapters in self._devices.items():
dev = None
max... | def function[visible_devices, parameter[self]]:
constant[Unify all visible devices across all connected adapters
Returns:
dict: A dictionary mapping UUIDs to device information dictionaries
]
variable[devs] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name obje... | keyword[def] identifier[visible_devices] ( identifier[self] ):
literal[string]
identifier[devs] ={}
keyword[for] identifier[device_id] , identifier[adapters] keyword[in] identifier[self] . identifier[_devices] . identifier[items] ():
identifier[dev] = keyword[None]
... | def visible_devices(self):
"""Unify all visible devices across all connected adapters
Returns:
dict: A dictionary mapping UUIDs to device information dictionaries
"""
devs = {}
for (device_id, adapters) in self._devices.items():
dev = None
max_signal = None
... |
def imresize(img, size, interpolate="bilinear", channel_first=False, **kwargs):
"""
Resize ``img`` to ``size``.
As default, the shape of input image has to be (height, width, channel).
Args:
img (numpy.ndarray): Input image.
size (tuple of int): Output shape. The order is (width, height... | def function[imresize, parameter[img, size, interpolate, channel_first]]:
constant[
Resize ``img`` to ``size``.
As default, the shape of input image has to be (height, width, channel).
Args:
img (numpy.ndarray): Input image.
size (tuple of int): Output shape. The order is (width, he... | keyword[def] identifier[imresize] ( identifier[img] , identifier[size] , identifier[interpolate] = literal[string] , identifier[channel_first] = keyword[False] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[backend_manager] . identifier[module] . identifier[imresize] ( identifier[im... | def imresize(img, size, interpolate='bilinear', channel_first=False, **kwargs):
"""
Resize ``img`` to ``size``.
As default, the shape of input image has to be (height, width, channel).
Args:
img (numpy.ndarray): Input image.
size (tuple of int): Output shape. The order is (width, height... |
def forward(A, pobs, pi, T=None, alpha_out=None):
"""Compute P( obs | A, B, pi ) and all forward coefficients.
Parameters
----------
A : ndarray((N,N), dtype = float)
transition matrix of the hidden states
pobs : ndarray((T,N), dtype = float)
pobs[t,i] is the observation probability... | def function[forward, parameter[A, pobs, pi, T, alpha_out]]:
constant[Compute P( obs | A, B, pi ) and all forward coefficients.
Parameters
----------
A : ndarray((N,N), dtype = float)
transition matrix of the hidden states
pobs : ndarray((T,N), dtype = float)
pobs[t,i] is the ob... | keyword[def] identifier[forward] ( identifier[A] , identifier[pobs] , identifier[pi] , identifier[T] = keyword[None] , identifier[alpha_out] = keyword[None] ):
literal[string]
keyword[if] identifier[__impl__] == identifier[__IMPL_PYTHON__] :
keyword[return] identifier[ip] . identifier[forward] (... | def forward(A, pobs, pi, T=None, alpha_out=None):
"""Compute P( obs | A, B, pi ) and all forward coefficients.
Parameters
----------
A : ndarray((N,N), dtype = float)
transition matrix of the hidden states
pobs : ndarray((T,N), dtype = float)
pobs[t,i] is the observation probability... |
def _unpack_images(self, rdata):
"""
Set image data from RESTBase response
"""
image = rdata.get('image') # /page/mobile-sections-lead
originalimage = rdata.get('originalimage') # /page/summary
thumbnail = rdata.get('thumbnail') # /page/summary
if image or ori... | def function[_unpack_images, parameter[self, rdata]]:
constant[
Set image data from RESTBase response
]
variable[image] assign[=] call[name[rdata].get, parameter[constant[image]]]
variable[originalimage] assign[=] call[name[rdata].get, parameter[constant[originalimage]]]
... | keyword[def] identifier[_unpack_images] ( identifier[self] , identifier[rdata] ):
literal[string]
identifier[image] = identifier[rdata] . identifier[get] ( literal[string] )
identifier[originalimage] = identifier[rdata] . identifier[get] ( literal[string] )
identifier[thumbnail] =... | def _unpack_images(self, rdata):
"""
Set image data from RESTBase response
"""
image = rdata.get('image') # /page/mobile-sections-lead
originalimage = rdata.get('originalimage') # /page/summary
thumbnail = rdata.get('thumbnail') # /page/summary
if image or originalimage or thumbna... |
def _set_manifest_data(self, files_list):
"""
Write manifest files
:param files_list: list
:return:
"""
if files_list:
data = ",".join(files_list)
self.s3.put_object(Bucket=self.sitename,
Key=self.manifest_file,
... | def function[_set_manifest_data, parameter[self, files_list]]:
constant[
Write manifest files
:param files_list: list
:return:
]
if name[files_list] begin[:]
variable[data] assign[=] call[constant[,].join, parameter[name[files_list]]]
call[... | keyword[def] identifier[_set_manifest_data] ( identifier[self] , identifier[files_list] ):
literal[string]
keyword[if] identifier[files_list] :
identifier[data] = literal[string] . identifier[join] ( identifier[files_list] )
identifier[self] . identifier[s3] . identifier[... | def _set_manifest_data(self, files_list):
"""
Write manifest files
:param files_list: list
:return:
"""
if files_list:
data = ','.join(files_list)
self.s3.put_object(Bucket=self.sitename, Key=self.manifest_file, Body=data, ACL='private') # depends on [control=['i... |
def post_signup(self, user, login_user=None, send_email=None):
"""Executes post signup actions: sending the signal, logging in the user and
sending the welcome email
"""
self.signup_signal.send(self, user=user)
if (login_user is None and self.options["login_user_on_signup"]) or ... | def function[post_signup, parameter[self, user, login_user, send_email]]:
constant[Executes post signup actions: sending the signal, logging in the user and
sending the welcome email
]
call[name[self].signup_signal.send, parameter[name[self]]]
if <ast.BoolOp object at 0x7da18f09d... | keyword[def] identifier[post_signup] ( identifier[self] , identifier[user] , identifier[login_user] = keyword[None] , identifier[send_email] = keyword[None] ):
literal[string]
identifier[self] . identifier[signup_signal] . identifier[send] ( identifier[self] , identifier[user] = identifier[user] )
... | def post_signup(self, user, login_user=None, send_email=None):
"""Executes post signup actions: sending the signal, logging in the user and
sending the welcome email
"""
self.signup_signal.send(self, user=user)
if login_user is None and self.options['login_user_on_signup'] or login_user:
... |
def get_release_id(self, package_name: str, version: str) -> bytes:
"""
Returns the 32 byte identifier of a release for the given package name and version,
if they are available on the current registry.
"""
validate_package_name(package_name)
validate_package_version(vers... | def function[get_release_id, parameter[self, package_name, version]]:
constant[
Returns the 32 byte identifier of a release for the given package name and version,
if they are available on the current registry.
]
call[name[validate_package_name], parameter[name[package_name]]]
... | keyword[def] identifier[get_release_id] ( identifier[self] , identifier[package_name] : identifier[str] , identifier[version] : identifier[str] )-> identifier[bytes] :
literal[string]
identifier[validate_package_name] ( identifier[package_name] )
identifier[validate_package_version] ( iden... | def get_release_id(self, package_name: str, version: str) -> bytes:
"""
Returns the 32 byte identifier of a release for the given package name and version,
if they are available on the current registry.
"""
validate_package_name(package_name)
validate_package_version(version)
sel... |
def _show(self):
""" Return a list of unsorted bridge details. """
p = _runshell([brctlexe, 'show', self.name],
"Could not show %s." % self.name)
return p.stdout.read().split()[7:] | def function[_show, parameter[self]]:
constant[ Return a list of unsorted bridge details. ]
variable[p] assign[=] call[name[_runshell], parameter[list[[<ast.Name object at 0x7da1b0ce4310>, <ast.Constant object at 0x7da1b0ce7880>, <ast.Attribute object at 0x7da1b0ce44f0>]], binary_operation[constant[Coul... | keyword[def] identifier[_show] ( identifier[self] ):
literal[string]
identifier[p] = identifier[_runshell] ([ identifier[brctlexe] , literal[string] , identifier[self] . identifier[name] ],
literal[string] % identifier[self] . identifier[name] )
keyword[return] identifier[p] . id... | def _show(self):
""" Return a list of unsorted bridge details. """
p = _runshell([brctlexe, 'show', self.name], 'Could not show %s.' % self.name)
return p.stdout.read().split()[7:] |
def get_ccc_handle_from_uuid(self, uuid):
"""Utility function to retrieve the client characteristic configuration
descriptor handle for a given characteristic.
Args:
uuid (str): a string containing the hex-encoded UUID
Returns:
None if an err... | def function[get_ccc_handle_from_uuid, parameter[self, uuid]]:
constant[Utility function to retrieve the client characteristic configuration
descriptor handle for a given characteristic.
Args:
uuid (str): a string containing the hex-encoded UUID
Returns:... | keyword[def] identifier[get_ccc_handle_from_uuid] ( identifier[self] , identifier[uuid] ):
literal[string]
keyword[if] identifier[uuid] keyword[in] identifier[self] . identifier[uuid_cccds] :
keyword[return] identifier[self] . identifier[uuid_cccds] [ identifier[uuid] ]. identifie... | def get_ccc_handle_from_uuid(self, uuid):
"""Utility function to retrieve the client characteristic configuration
descriptor handle for a given characteristic.
Args:
uuid (str): a string containing the hex-encoded UUID
Returns:
None if an error o... |
def _CreateStyleForRoute(self, doc, route):
"""Create a KML Style element for the route.
The style sets the line colour if the route colour is specified. The
line thickness is set depending on the vehicle type.
Args:
doc: The KML Document ElementTree.Element instance.
route: The transitfee... | def function[_CreateStyleForRoute, parameter[self, doc, route]]:
constant[Create a KML Style element for the route.
The style sets the line colour if the route colour is specified. The
line thickness is set depending on the vehicle type.
Args:
doc: The KML Document ElementTree.Element instan... | keyword[def] identifier[_CreateStyleForRoute] ( identifier[self] , identifier[doc] , identifier[route] ):
literal[string]
identifier[style_id] = literal[string] % identifier[route] . identifier[route_id]
identifier[style] = identifier[ET] . identifier[SubElement] ( identifier[doc] , literal[string] ,... | def _CreateStyleForRoute(self, doc, route):
"""Create a KML Style element for the route.
The style sets the line colour if the route colour is specified. The
line thickness is set depending on the vehicle type.
Args:
doc: The KML Document ElementTree.Element instance.
route: The transitfee... |
def CreateGroup(self, GroupName):
"""Creates a custom contact group.
:Parameters:
GroupName : unicode
Group name.
:return: A group object.
:rtype: `Group`
:see: `DeleteGroup`
"""
groups = self.CustomGroups
self._DoCommand('CREATE G... | def function[CreateGroup, parameter[self, GroupName]]:
constant[Creates a custom contact group.
:Parameters:
GroupName : unicode
Group name.
:return: A group object.
:rtype: `Group`
:see: `DeleteGroup`
]
variable[groups] assign[=] name[sel... | keyword[def] identifier[CreateGroup] ( identifier[self] , identifier[GroupName] ):
literal[string]
identifier[groups] = identifier[self] . identifier[CustomGroups]
identifier[self] . identifier[_DoCommand] ( literal[string] % identifier[tounicode] ( identifier[GroupName] ))
keywo... | def CreateGroup(self, GroupName):
"""Creates a custom contact group.
:Parameters:
GroupName : unicode
Group name.
:return: A group object.
:rtype: `Group`
:see: `DeleteGroup`
"""
groups = self.CustomGroups
self._DoCommand('CREATE GROUP %s' % t... |
def _parse_repo_file(filename):
'''
Turn a single repo file into a dict
'''
parsed = configparser.ConfigParser()
config = {}
try:
parsed.read(filename)
except configparser.MissingSectionHeaderError as err:
log.error(
'Failed to parse file %s, error: %s',
... | def function[_parse_repo_file, parameter[filename]]:
constant[
Turn a single repo file into a dict
]
variable[parsed] assign[=] call[name[configparser].ConfigParser, parameter[]]
variable[config] assign[=] dictionary[[], []]
<ast.Try object at 0x7da18f58f4c0>
for taget[name[s... | keyword[def] identifier[_parse_repo_file] ( identifier[filename] ):
literal[string]
identifier[parsed] = identifier[configparser] . identifier[ConfigParser] ()
identifier[config] ={}
keyword[try] :
identifier[parsed] . identifier[read] ( identifier[filename] )
keyword[except] iden... | def _parse_repo_file(filename):
"""
Turn a single repo file into a dict
"""
parsed = configparser.ConfigParser()
config = {}
try:
parsed.read(filename) # depends on [control=['try'], data=[]]
except configparser.MissingSectionHeaderError as err:
log.error('Failed to parse fi... |
def remove_my_api_key_from_groups(self, body, **kwargs): # noqa: E501
"""Remove API key from groups. # noqa: E501
An endpoint for removing API key from groups. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/api-keys/me/groups -d '[0162056a9a1586f30242590700000000,0117056a... | def function[remove_my_api_key_from_groups, parameter[self, body]]:
constant[Remove API key from groups. # noqa: E501
An endpoint for removing API key from groups. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/api-keys/me/groups -d '[0162056a9a1586f30242590700000000,01170... | keyword[def] identifier[remove_my_api_key_from_groups] ( identifier[self] , identifier[body] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] ... | def remove_my_api_key_from_groups(self, body, **kwargs): # noqa: E501
"Remove API key from groups. # noqa: E501\n\n An endpoint for removing API key from groups. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/api-keys/me/groups -d '[0162056a9a1586f30242590700000000,0117056a9a15... |
def get_securities(self, page=1, **filter_param):
"""
Queries /<security_type> endpoint to return a paged
list of securities.
"""
url_path = self._build_url_path(None, None)
params = {'page': page}
# the endpoints respond just fine to invaliid query params,
... | def function[get_securities, parameter[self, page]]:
constant[
Queries /<security_type> endpoint to return a paged
list of securities.
]
variable[url_path] assign[=] call[name[self]._build_url_path, parameter[constant[None], constant[None]]]
variable[params] assign[=] dic... | keyword[def] identifier[get_securities] ( identifier[self] , identifier[page] = literal[int] ,** identifier[filter_param] ):
literal[string]
identifier[url_path] = identifier[self] . identifier[_build_url_path] ( keyword[None] , keyword[None] )
identifier[params] ={ literal[string] : ident... | def get_securities(self, page=1, **filter_param):
"""
Queries /<security_type> endpoint to return a paged
list of securities.
"""
url_path = self._build_url_path(None, None)
params = {'page': page}
# the endpoints respond just fine to invaliid query params,
# they just ignore... |
def get_service_endpoints_by_names(self, project, endpoint_names, type=None, auth_schemes=None, include_failed=None, include_details=None):
"""GetServiceEndpointsByNames.
[Preview API] Get the service endpoints by name.
:param str project: Project ID or project name
:param [str] endpoint... | def function[get_service_endpoints_by_names, parameter[self, project, endpoint_names, type, auth_schemes, include_failed, include_details]]:
constant[GetServiceEndpointsByNames.
[Preview API] Get the service endpoints by name.
:param str project: Project ID or project name
:param [str] e... | keyword[def] identifier[get_service_endpoints_by_names] ( identifier[self] , identifier[project] , identifier[endpoint_names] , identifier[type] = keyword[None] , identifier[auth_schemes] = keyword[None] , identifier[include_failed] = keyword[None] , identifier[include_details] = keyword[None] ):
literal[str... | def get_service_endpoints_by_names(self, project, endpoint_names, type=None, auth_schemes=None, include_failed=None, include_details=None):
"""GetServiceEndpointsByNames.
[Preview API] Get the service endpoints by name.
:param str project: Project ID or project name
:param [str] endpoint_nam... |
def categorical_to_numeric(table):
"""Encode categorical columns to numeric by converting each category to
an integer value.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
Returns
-------
encoded : pandas.DataFrame
Table with ca... | def function[categorical_to_numeric, parameter[table]]:
constant[Encode categorical columns to numeric by converting each category to
an integer value.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
Returns
-------
encoded : pandas.... | keyword[def] identifier[categorical_to_numeric] ( identifier[table] ):
literal[string]
keyword[def] identifier[transform] ( identifier[column] ):
keyword[if] identifier[is_categorical_dtype] ( identifier[column] . identifier[dtype] ):
keyword[return] identifier[column] . identifier... | def categorical_to_numeric(table):
"""Encode categorical columns to numeric by converting each category to
an integer value.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
Returns
-------
encoded : pandas.DataFrame
Table with ca... |
def ensure_path(path, mode=0o777):
"""Ensure that path exists in a multiprocessing safe way.
If the path does not exist, recursively create it and its parent
directories using the provided mode. If the path already exists,
do nothing. The umask is cleared to enable the mode to be set,
and then re... | def function[ensure_path, parameter[path, mode]]:
constant[Ensure that path exists in a multiprocessing safe way.
If the path does not exist, recursively create it and its parent
directories using the provided mode. If the path already exists,
do nothing. The umask is cleared to enable the mode t... | keyword[def] identifier[ensure_path] ( identifier[path] , identifier[mode] = literal[int] ):
literal[string]
keyword[if] identifier[path] :
keyword[try] :
identifier[umask] = identifier[os] . identifier[umask] ( literal[int] )
identifier[os] . identifier[makedirs] ( ide... | def ensure_path(path, mode=511):
"""Ensure that path exists in a multiprocessing safe way.
If the path does not exist, recursively create it and its parent
directories using the provided mode. If the path already exists,
do nothing. The umask is cleared to enable the mode to be set,
and then rese... |
def each(coro, iterable, limit=0, loop=None,
collect=False, timeout=None, return_exceptions=False, *args, **kw):
"""
Concurrently iterates values yielded from an iterable, passing them to
an asynchronous coroutine.
You can optionally collect yielded values passing collect=True param,
which... | def function[each, parameter[coro, iterable, limit, loop, collect, timeout, return_exceptions]]:
constant[
Concurrently iterates values yielded from an iterable, passing them to
an asynchronous coroutine.
You can optionally collect yielded values passing collect=True param,
which would be equiv... | keyword[def] identifier[each] ( identifier[coro] , identifier[iterable] , identifier[limit] = literal[int] , identifier[loop] = keyword[None] ,
identifier[collect] = keyword[False] , identifier[timeout] = keyword[None] , identifier[return_exceptions] = keyword[False] ,* identifier[args] ,** identifier[kw] ):
li... | def each(coro, iterable, limit=0, loop=None, collect=False, timeout=None, return_exceptions=False, *args, **kw):
"""
Concurrently iterates values yielded from an iterable, passing them to
an asynchronous coroutine.
You can optionally collect yielded values passing collect=True param,
which would be... |
def parse_bamPEFragmentSize(self):
"""Find bamPEFragmentSize output. Supports the --table option"""
self.deeptools_bamPEFragmentSize = dict()
for f in self.find_log_files('deeptools/bamPEFragmentSizeTable'):
parsed_data = self.parseBamPEFile(f)
for k, v in parsed_data.ite... | def function[parse_bamPEFragmentSize, parameter[self]]:
constant[Find bamPEFragmentSize output. Supports the --table option]
name[self].deeptools_bamPEFragmentSize assign[=] call[name[dict], parameter[]]
for taget[name[f]] in starred[call[name[self].find_log_files, parameter[constant[deeptools/b... | keyword[def] identifier[parse_bamPEFragmentSize] ( identifier[self] ):
literal[string]
identifier[self] . identifier[deeptools_bamPEFragmentSize] = identifier[dict] ()
keyword[for] identifier[f] keyword[in] identifier[self] . identifier[find_log_files] ( literal[string] ):
... | def parse_bamPEFragmentSize(self):
"""Find bamPEFragmentSize output. Supports the --table option"""
self.deeptools_bamPEFragmentSize = dict()
for f in self.find_log_files('deeptools/bamPEFragmentSizeTable'):
parsed_data = self.parseBamPEFile(f)
for (k, v) in parsed_data.items():
... |
def rename_file_group_to_serial_nums(file_lst):
"""Will rename all files in file_lst to a padded serial
number plus its extension
:param file_lst: list of path.py paths
"""
file_lst.sort()
c = 1
for f in file_lst:
dirname = get_abspath(f.dirname())
fdest = f.joinpath(dirname... | def function[rename_file_group_to_serial_nums, parameter[file_lst]]:
constant[Will rename all files in file_lst to a padded serial
number plus its extension
:param file_lst: list of path.py paths
]
call[name[file_lst].sort, parameter[]]
variable[c] assign[=] constant[1]
for ... | keyword[def] identifier[rename_file_group_to_serial_nums] ( identifier[file_lst] ):
literal[string]
identifier[file_lst] . identifier[sort] ()
identifier[c] = literal[int]
keyword[for] identifier[f] keyword[in] identifier[file_lst] :
identifier[dirname] = identifier[get_abspath] ( id... | def rename_file_group_to_serial_nums(file_lst):
"""Will rename all files in file_lst to a padded serial
number plus its extension
:param file_lst: list of path.py paths
"""
file_lst.sort()
c = 1
for f in file_lst:
dirname = get_abspath(f.dirname())
fdest = f.joinpath(dirname... |
def check_groups_on_profile_update(sender, instance, created, *args, **kwargs):
"""
Trigger check when main character or state changes.
"""
AutogroupsConfig.objects.update_groups_for_user(instance.user) | def function[check_groups_on_profile_update, parameter[sender, instance, created]]:
constant[
Trigger check when main character or state changes.
]
call[name[AutogroupsConfig].objects.update_groups_for_user, parameter[name[instance].user]] | keyword[def] identifier[check_groups_on_profile_update] ( identifier[sender] , identifier[instance] , identifier[created] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[AutogroupsConfig] . identifier[objects] . identifier[update_groups_for_user] ( identifier[instance] . identifier... | def check_groups_on_profile_update(sender, instance, created, *args, **kwargs):
"""
Trigger check when main character or state changes.
"""
AutogroupsConfig.objects.update_groups_for_user(instance.user) |
def deserialize(raw):
"""Instantiate :py:class:`ofxclient.Account` subclass from dictionary
:param raw: serilized Account
:param type: dict as given by :py:meth:`~ofxclient.Account.serialize`
:rtype: subclass of :py:class:`ofxclient.Account`
"""
from ofxclient.instituti... | def function[deserialize, parameter[raw]]:
constant[Instantiate :py:class:`ofxclient.Account` subclass from dictionary
:param raw: serilized Account
:param type: dict as given by :py:meth:`~ofxclient.Account.serialize`
:rtype: subclass of :py:class:`ofxclient.Account`
]
fro... | keyword[def] identifier[deserialize] ( identifier[raw] ):
literal[string]
keyword[from] identifier[ofxclient] . identifier[institution] keyword[import] identifier[Institution]
identifier[institution] = identifier[Institution] . identifier[deserialize] ( identifier[raw] [ literal[string... | def deserialize(raw):
"""Instantiate :py:class:`ofxclient.Account` subclass from dictionary
:param raw: serilized Account
:param type: dict as given by :py:meth:`~ofxclient.Account.serialize`
:rtype: subclass of :py:class:`ofxclient.Account`
"""
from ofxclient.institution impor... |
def resolved_task(cls, task):
"""Task instance representing 'task', if any"""
for t in cls.tasks:
if t is task or t.execute is task:
return t | def function[resolved_task, parameter[cls, task]]:
constant[Task instance representing 'task', if any]
for taget[name[t]] in starred[name[cls].tasks] begin[:]
if <ast.BoolOp object at 0x7da1b242b280> begin[:]
return[name[t]] | keyword[def] identifier[resolved_task] ( identifier[cls] , identifier[task] ):
literal[string]
keyword[for] identifier[t] keyword[in] identifier[cls] . identifier[tasks] :
keyword[if] identifier[t] keyword[is] identifier[task] keyword[or] identifier[t] . identifier[execute] ke... | def resolved_task(cls, task):
"""Task instance representing 'task', if any"""
for t in cls.tasks:
if t is task or t.execute is task:
return t # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['t']] |
def get_public_ip(self, addr_family=None, *args, **kwargs):
"""Alias for get_ip('public')"""
return self.get_ip('public', addr_family, *args, **kwargs) | def function[get_public_ip, parameter[self, addr_family]]:
constant[Alias for get_ip('public')]
return[call[name[self].get_ip, parameter[constant[public], name[addr_family], <ast.Starred object at 0x7da1b0e33d90>]]] | keyword[def] identifier[get_public_ip] ( identifier[self] , identifier[addr_family] = keyword[None] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[get_ip] ( literal[string] , identifier[addr_family] ,* identifier[args] ,** identifier[kwa... | def get_public_ip(self, addr_family=None, *args, **kwargs):
"""Alias for get_ip('public')"""
return self.get_ip('public', addr_family, *args, **kwargs) |
def get_interfaces_counters(self):
"""Return interfaces counters."""
query = junos_views.junos_iface_counter_table(self.device)
query.get()
interface_counters = {}
for interface, counters in query.items():
interface_counters[interface] = {
k: v if v is... | def function[get_interfaces_counters, parameter[self]]:
constant[Return interfaces counters.]
variable[query] assign[=] call[name[junos_views].junos_iface_counter_table, parameter[name[self].device]]
call[name[query].get, parameter[]]
variable[interface_counters] assign[=] dictionary[[],... | keyword[def] identifier[get_interfaces_counters] ( identifier[self] ):
literal[string]
identifier[query] = identifier[junos_views] . identifier[junos_iface_counter_table] ( identifier[self] . identifier[device] )
identifier[query] . identifier[get] ()
identifier[interface_counters... | def get_interfaces_counters(self):
"""Return interfaces counters."""
query = junos_views.junos_iface_counter_table(self.device)
query.get()
interface_counters = {}
for (interface, counters) in query.items():
interface_counters[interface] = {k: v if v is not None else -1 for (k, v) in counter... |
def get_aws_regions(*, force=False):
"""Load a list of AWS regions from the AWS static data.
Args:
force (`bool`): Force fetch list of regions even if we already have a cached version
Returns:
:obj:`list` of `str`
"""
from cloud_inquisitor.config import dbconfig
global __region... | def function[get_aws_regions, parameter[]]:
constant[Load a list of AWS regions from the AWS static data.
Args:
force (`bool`): Force fetch list of regions even if we already have a cached version
Returns:
:obj:`list` of `str`
]
from relative_module[cloud_inquisitor.config] imp... | keyword[def] identifier[get_aws_regions] (*, identifier[force] = keyword[False] ):
literal[string]
keyword[from] identifier[cloud_inquisitor] . identifier[config] keyword[import] identifier[dbconfig]
keyword[global] identifier[__regions]
keyword[if] identifier[force] keyword[or] keyword... | def get_aws_regions(*, force=False):
"""Load a list of AWS regions from the AWS static data.
Args:
force (`bool`): Force fetch list of regions even if we already have a cached version
Returns:
:obj:`list` of `str`
"""
from cloud_inquisitor.config import dbconfig
global __region... |
def email_address_to_list(email_address):
"""Convert an email address to a list."""
realname, address = email.utils.parseaddr(email_address)
return (
[address, realname] if realname and address else
[email_address, email_address]
) | def function[email_address_to_list, parameter[email_address]]:
constant[Convert an email address to a list.]
<ast.Tuple object at 0x7da204564700> assign[=] call[name[email].utils.parseaddr, parameter[name[email_address]]]
return[<ast.IfExp object at 0x7da204564df0>] | keyword[def] identifier[email_address_to_list] ( identifier[email_address] ):
literal[string]
identifier[realname] , identifier[address] = identifier[email] . identifier[utils] . identifier[parseaddr] ( identifier[email_address] )
keyword[return] (
[ identifier[address] , identifier[realname] ] ke... | def email_address_to_list(email_address):
"""Convert an email address to a list."""
(realname, address) = email.utils.parseaddr(email_address)
return [address, realname] if realname and address else [email_address, email_address] |
def validate_services_by_name(self, sentry_services):
"""Validate system service status by service name, automatically
detecting init system based on Ubuntu release codename.
:param sentry_services: dict with sentry keys and svc list values
:returns: None if successful, Failure strin... | def function[validate_services_by_name, parameter[self, sentry_services]]:
constant[Validate system service status by service name, automatically
detecting init system based on Ubuntu release codename.
:param sentry_services: dict with sentry keys and svc list values
:returns: None i... | keyword[def] identifier[validate_services_by_name] ( identifier[self] , identifier[sentry_services] ):
literal[string]
identifier[self] . identifier[log] . identifier[debug] ( literal[string] )
identifier[systemd_switch] = identifier[self] . identifier[ubuntu_releases] . identifi... | def validate_services_by_name(self, sentry_services):
"""Validate system service status by service name, automatically
detecting init system based on Ubuntu release codename.
:param sentry_services: dict with sentry keys and svc list values
:returns: None if successful, Failure string me... |
async def multipart_parser(request, file_handler=default_file_handler):
"""
:param file_handler: callable to save file, this should always return the file path
:return: dictionary containing files and data
"""
multipart_data = {
'files': {},
'data': {}
}
if request.content_ty... | <ast.AsyncFunctionDef object at 0x7da20e9b2770> | keyword[async] keyword[def] identifier[multipart_parser] ( identifier[request] , identifier[file_handler] = identifier[default_file_handler] ):
literal[string]
identifier[multipart_data] ={
literal[string] :{},
literal[string] :{}
}
keyword[if] identifier[request] . identifier[content_... | async def multipart_parser(request, file_handler=default_file_handler):
"""
:param file_handler: callable to save file, this should always return the file path
:return: dictionary containing files and data
"""
multipart_data = {'files': {}, 'data': {}}
if request.content_type == 'multipart/form-... |
def check_lifecycle(self):
"""
Tests if the state of the component must be updated, based on its own
state and on the state of its dependencies
"""
with self._lock:
# Validation flags
was_valid = self.state == StoredInstance.VALID
can_validate ... | def function[check_lifecycle, parameter[self]]:
constant[
Tests if the state of the component must be updated, based on its own
state and on the state of its dependencies
]
with name[self]._lock begin[:]
variable[was_valid] assign[=] compare[name[self].state equal... | keyword[def] identifier[check_lifecycle] ( identifier[self] ):
literal[string]
keyword[with] identifier[self] . identifier[_lock] :
identifier[was_valid] = identifier[self] . identifier[state] == identifier[StoredInstance] . identifier[VALID]
identifier[can_vali... | def check_lifecycle(self):
"""
Tests if the state of the component must be updated, based on its own
state and on the state of its dependencies
"""
with self._lock:
# Validation flags
was_valid = self.state == StoredInstance.VALID
can_validate = self.state not in ... |
def remove_all_matching(self, address=None, name=None):
"""
Remove all HostsEntry instances from the Hosts object
where the supplied ip address or name matches
:param address: An ipv4 or ipv6 address
:param name: A host name
:return: None
"""
if self.entri... | def function[remove_all_matching, parameter[self, address, name]]:
constant[
Remove all HostsEntry instances from the Hosts object
where the supplied ip address or name matches
:param address: An ipv4 or ipv6 address
:param name: A host name
:return: None
]
... | keyword[def] identifier[remove_all_matching] ( identifier[self] , identifier[address] = keyword[None] , identifier[name] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[entries] :
keyword[if] identifier[address] keyword[and] identifier[name] :
... | def remove_all_matching(self, address=None, name=None):
"""
Remove all HostsEntry instances from the Hosts object
where the supplied ip address or name matches
:param address: An ipv4 or ipv6 address
:param name: A host name
:return: None
"""
if self.entries:
... |
def substrings_indexes(seq, reverse=False):
"""Yield all substrings and their positions in *seq*
The items yielded will be a tuple of the form ``(substr, i, j)``, where
``substr == seq[i:j]``.
This function only works for iterables that support slicing, such as
``str`` objects.
>>> for item i... | def function[substrings_indexes, parameter[seq, reverse]]:
constant[Yield all substrings and their positions in *seq*
The items yielded will be a tuple of the form ``(substr, i, j)``, where
``substr == seq[i:j]``.
This function only works for iterables that support slicing, such as
``str`` obj... | keyword[def] identifier[substrings_indexes] ( identifier[seq] , identifier[reverse] = keyword[False] ):
literal[string]
identifier[r] = identifier[range] ( literal[int] , identifier[len] ( identifier[seq] )+ literal[int] )
keyword[if] identifier[reverse] :
identifier[r] = identifier[reversed... | def substrings_indexes(seq, reverse=False):
"""Yield all substrings and their positions in *seq*
The items yielded will be a tuple of the form ``(substr, i, j)``, where
``substr == seq[i:j]``.
This function only works for iterables that support slicing, such as
``str`` objects.
>>> for item i... |
def gather_candidates(self):
"""Gather candidates from the slave environments.
The candidates are stored in :attr:`candidates`, overriding any
previous candidates.
"""
async def slave_task(addr):
r_manager = await self.env.connect(addr)
return await r_man... | def function[gather_candidates, parameter[self]]:
constant[Gather candidates from the slave environments.
The candidates are stored in :attr:`candidates`, overriding any
previous candidates.
]
<ast.AsyncFunctionDef object at 0x7da2046238b0>
if name[self]._single_env begin[:]... | keyword[def] identifier[gather_candidates] ( identifier[self] ):
literal[string]
keyword[async] keyword[def] identifier[slave_task] ( identifier[addr] ):
identifier[r_manager] = keyword[await] identifier[self] . identifier[env] . identifier[connect] ( identifier[addr] )
... | def gather_candidates(self):
"""Gather candidates from the slave environments.
The candidates are stored in :attr:`candidates`, overriding any
previous candidates.
"""
async def slave_task(addr):
r_manager = await self.env.connect(addr)
return await r_manager.get_candid... |
def BuildFindSpecs(self, environment_variables=None):
"""Build find specification from a filter file.
Args:
environment_variables (Optional[list[EnvironmentVariableArtifact]]):
environment variables.
Returns:
list[dfvfs.FindSpec]: find specification.
"""
path_attributes = {}
... | def function[BuildFindSpecs, parameter[self, environment_variables]]:
constant[Build find specification from a filter file.
Args:
environment_variables (Optional[list[EnvironmentVariableArtifact]]):
environment variables.
Returns:
list[dfvfs.FindSpec]: find specification.
]
... | keyword[def] identifier[BuildFindSpecs] ( identifier[self] , identifier[environment_variables] = keyword[None] ):
literal[string]
identifier[path_attributes] ={}
keyword[if] identifier[environment_variables] :
keyword[for] identifier[environment_variable] keyword[in] identifier[environment_... | def BuildFindSpecs(self, environment_variables=None):
"""Build find specification from a filter file.
Args:
environment_variables (Optional[list[EnvironmentVariableArtifact]]):
environment variables.
Returns:
list[dfvfs.FindSpec]: find specification.
"""
path_attributes = {}
... |
def verts_str(verts, pad=1):
r""" makes a string from a list of integer verticies """
if verts is None:
return 'None'
fmtstr = ', '.join(['%' + six.text_type(pad) + 'd' +
', %' + six.text_type(pad) + 'd'] * 1)
return ', '.join(['(' + fmtstr % vert + ')' for vert in verts]... | def function[verts_str, parameter[verts, pad]]:
constant[ makes a string from a list of integer verticies ]
if compare[name[verts] is constant[None]] begin[:]
return[constant[None]]
variable[fmtstr] assign[=] call[constant[, ].join, parameter[binary_operation[list[[<ast.BinOp object at 0... | keyword[def] identifier[verts_str] ( identifier[verts] , identifier[pad] = literal[int] ):
literal[string]
keyword[if] identifier[verts] keyword[is] keyword[None] :
keyword[return] literal[string]
identifier[fmtstr] = literal[string] . identifier[join] ([ literal[string] + identifier[six... | def verts_str(verts, pad=1):
""" makes a string from a list of integer verticies """
if verts is None:
return 'None' # depends on [control=['if'], data=[]]
fmtstr = ', '.join(['%' + six.text_type(pad) + 'd' + ', %' + six.text_type(pad) + 'd'] * 1)
return ', '.join(['(' + fmtstr % vert + ')' for... |
def _prompt_choice(var_name, options):
'''
Prompt the user to choose between a list of options, index each one by adding an enumerator
based on https://github.com/audreyr/cookiecutter/blob/master/cookiecutter/prompt.py#L51
:param var_name: The question to ask the user
:type var_name: ``str``
... | def function[_prompt_choice, parameter[var_name, options]]:
constant[
Prompt the user to choose between a list of options, index each one by adding an enumerator
based on https://github.com/audreyr/cookiecutter/blob/master/cookiecutter/prompt.py#L51
:param var_name: The question to ask the user
... | keyword[def] identifier[_prompt_choice] ( identifier[var_name] , identifier[options] ):
literal[string]
identifier[choice_map] = identifier[OrderedDict] (
( literal[string] . identifier[format] ( identifier[i] ), identifier[value] ) keyword[for] identifier[i] , identifier[value] keyword[in] identifi... | def _prompt_choice(var_name, options):
"""
Prompt the user to choose between a list of options, index each one by adding an enumerator
based on https://github.com/audreyr/cookiecutter/blob/master/cookiecutter/prompt.py#L51
:param var_name: The question to ask the user
:type var_name: ``str``
... |
def u128(self, name, value=None, align=None):
"""Add an unsigned 16 byte integer field to template.
This is an convenience method that simply calls `Uint` keyword with predefined length."""
self.uint(16, name, value, align) | def function[u128, parameter[self, name, value, align]]:
constant[Add an unsigned 16 byte integer field to template.
This is an convenience method that simply calls `Uint` keyword with predefined length.]
call[name[self].uint, parameter[constant[16], name[name], name[value], name[align]]] | keyword[def] identifier[u128] ( identifier[self] , identifier[name] , identifier[value] = keyword[None] , identifier[align] = keyword[None] ):
literal[string]
identifier[self] . identifier[uint] ( literal[int] , identifier[name] , identifier[value] , identifier[align] ) | def u128(self, name, value=None, align=None):
"""Add an unsigned 16 byte integer field to template.
This is an convenience method that simply calls `Uint` keyword with predefined length."""
self.uint(16, name, value, align) |
def make_dist_mat(xy1, xy2, longlat=True):
"""
Return a distance matrix between two set of coordinates.
Use geometric distance (default) or haversine distance (if longlat=True).
Parameters
----------
xy1 : numpy.array
The first set of coordinates as [(x, y), (x, y), (x, y)].
xy2 : n... | def function[make_dist_mat, parameter[xy1, xy2, longlat]]:
constant[
Return a distance matrix between two set of coordinates.
Use geometric distance (default) or haversine distance (if longlat=True).
Parameters
----------
xy1 : numpy.array
The first set of coordinates as [(x, y), (x... | keyword[def] identifier[make_dist_mat] ( identifier[xy1] , identifier[xy2] , identifier[longlat] = keyword[True] ):
literal[string]
keyword[if] identifier[longlat] :
keyword[return] identifier[hav_dist] ( identifier[xy1] [:, keyword[None] ], identifier[xy2] )
keyword[else] :
identi... | def make_dist_mat(xy1, xy2, longlat=True):
"""
Return a distance matrix between two set of coordinates.
Use geometric distance (default) or haversine distance (if longlat=True).
Parameters
----------
xy1 : numpy.array
The first set of coordinates as [(x, y), (x, y), (x, y)].
xy2 : n... |
def _damerau_levenshtein(a, b):
"""Returns Damerau-Levenshtein edit distance from a to b."""
memo = {}
def distance(x, y):
"""Recursively defined string distance with memoization."""
if (x, y) in memo:
return memo[x, y]
if not x:
d = len(y)
elif not y:
d = len(x)
else:
... | def function[_damerau_levenshtein, parameter[a, b]]:
constant[Returns Damerau-Levenshtein edit distance from a to b.]
variable[memo] assign[=] dictionary[[], []]
def function[distance, parameter[x, y]]:
constant[Recursively defined string distance with memoization.]
... | keyword[def] identifier[_damerau_levenshtein] ( identifier[a] , identifier[b] ):
literal[string]
identifier[memo] ={}
keyword[def] identifier[distance] ( identifier[x] , identifier[y] ):
literal[string]
keyword[if] ( identifier[x] , identifier[y] ) keyword[in] identifier[memo] :
keyword... | def _damerau_levenshtein(a, b):
"""Returns Damerau-Levenshtein edit distance from a to b."""
memo = {}
def distance(x, y):
"""Recursively defined string distance with memoization."""
if (x, y) in memo:
return memo[x, y] # depends on [control=['if'], data=['memo']]
if no... |
def numeric_range(cls, field, from_value, to_value, include_lower=None, include_upper=None):
'''
http://www.elasticsearch.org/guide/reference/query-dsl/numeric-range-filter.html
Filters documents with fields that have values within a certain numeric range. Similar to range filter, except that it... | def function[numeric_range, parameter[cls, field, from_value, to_value, include_lower, include_upper]]:
constant[
http://www.elasticsearch.org/guide/reference/query-dsl/numeric-range-filter.html
Filters documents with fields that have values within a certain numeric range. Similar to range filte... | keyword[def] identifier[numeric_range] ( identifier[cls] , identifier[field] , identifier[from_value] , identifier[to_value] , identifier[include_lower] = keyword[None] , identifier[include_upper] = keyword[None] ):
literal[string]
identifier[instance] = identifier[cls] ( identifier[numeric_range] ... | def numeric_range(cls, field, from_value, to_value, include_lower=None, include_upper=None):
"""
http://www.elasticsearch.org/guide/reference/query-dsl/numeric-range-filter.html
Filters documents with fields that have values within a certain numeric range. Similar to range filter, except that it wor... |
def request_url(self, request, proxies):
"""Obtain the url to use when making the final request.
If the message is being sent through a HTTP proxy, the full URL has to
be used. Otherwise, we should only use the path portion of the URL.
This should not be called from user code, and is o... | def function[request_url, parameter[self, request, proxies]]:
constant[Obtain the url to use when making the final request.
If the message is being sent through a HTTP proxy, the full URL has to
be used. Otherwise, we should only use the path portion of the URL.
This should not be call... | keyword[def] identifier[request_url] ( identifier[self] , identifier[request] , identifier[proxies] ):
literal[string]
identifier[proxy] = identifier[select_proxy] ( identifier[request] . identifier[url] , identifier[proxies] )
identifier[scheme] = identifier[urlparse] ( identifier[request... | def request_url(self, request, proxies):
"""Obtain the url to use when making the final request.
If the message is being sent through a HTTP proxy, the full URL has to
be used. Otherwise, we should only use the path portion of the URL.
This should not be called from user code, and is only ... |
def get_instance(self, payload):
"""
Build an instance of MobileInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileInstance
:rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.Mob... | def function[get_instance, parameter[self, payload]]:
constant[
Build an instance of MobileInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileInstance
:rtype: twilio.rest.api.v2010.account.incom... | keyword[def] identifier[get_instance] ( identifier[self] , identifier[payload] ):
literal[string]
keyword[return] identifier[MobileInstance] ( identifier[self] . identifier[_version] , identifier[payload] , identifier[account_sid] = identifier[self] . identifier[_solution] [ literal[string] ],) | def get_instance(self, payload):
"""
Build an instance of MobileInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileInstance
:rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileI... |
def show_all(key):
'''
Context:
- abbr
- metadata
- bill
- sources
- nav_active
Templates:
- billy/web/public/bill_all_{key}.html
- where key is passed in, like "actions", etc.
'''
def func(request, abbr, session, bill_id, key):
# ... | def function[show_all, parameter[key]]:
constant[
Context:
- abbr
- metadata
- bill
- sources
- nav_active
Templates:
- billy/web/public/bill_all_{key}.html
- where key is passed in, like "actions", etc.
]
def function[func, parame... | keyword[def] identifier[show_all] ( identifier[key] ):
literal[string]
keyword[def] identifier[func] ( identifier[request] , identifier[abbr] , identifier[session] , identifier[bill_id] , identifier[key] ):
identifier[fixed_bill_id] = identifier[fix_bill_id] ( identifier[bill_id] )
... | def show_all(key):
"""
Context:
- abbr
- metadata
- bill
- sources
- nav_active
Templates:
- billy/web/public/bill_all_{key}.html
- where key is passed in, like "actions", etc.
"""
def func(request, abbr, session, bill_id, key):
#... |
def rule_collection(href, cls):
"""
Rule collections insert a ``create`` and ``create_rule_section`` method
into the collection. This collection type is returned when accessing rules
through a reference, as::
policy = FirewallPolicy('mypolicy')
policy.fw_ipv4_access_rules.create(....)
... | def function[rule_collection, parameter[href, cls]]:
constant[
Rule collections insert a ``create`` and ``create_rule_section`` method
into the collection. This collection type is returned when accessing rules
through a reference, as::
policy = FirewallPolicy('mypolicy')
policy.fw_i... | keyword[def] identifier[rule_collection] ( identifier[href] , identifier[cls] ):
literal[string]
identifier[instance] = identifier[cls] ( identifier[href] = identifier[href] )
identifier[meth] = identifier[getattr] ( identifier[instance] , literal[string] )
keyword[return] identifier[type] (
... | def rule_collection(href, cls):
"""
Rule collections insert a ``create`` and ``create_rule_section`` method
into the collection. This collection type is returned when accessing rules
through a reference, as::
policy = FirewallPolicy('mypolicy')
policy.fw_ipv4_access_rules.create(....)
... |
def get_spec(self):
"""
Return the Core ML spec
"""
if _mac_ver() >= (10, 14):
return self.vggish_model.get_spec()
else:
vggish_model_file = VGGish()
coreml_model_path = vggish_model_file.get_model_path(format='coreml')
return MLMod... | def function[get_spec, parameter[self]]:
constant[
Return the Core ML spec
]
if compare[call[name[_mac_ver], parameter[]] greater_or_equal[>=] tuple[[<ast.Constant object at 0x7da204961de0>, <ast.Constant object at 0x7da204963a00>]]] begin[:]
return[call[name[self].vggish_model.g... | keyword[def] identifier[get_spec] ( identifier[self] ):
literal[string]
keyword[if] identifier[_mac_ver] ()>=( literal[int] , literal[int] ):
keyword[return] identifier[self] . identifier[vggish_model] . identifier[get_spec] ()
keyword[else] :
identifier[vggish_... | def get_spec(self):
"""
Return the Core ML spec
"""
if _mac_ver() >= (10, 14):
return self.vggish_model.get_spec() # depends on [control=['if'], data=[]]
else:
vggish_model_file = VGGish()
coreml_model_path = vggish_model_file.get_model_path(format='coreml')
... |
def strip_tags(html):
"""Stripts HTML tags from text.
Note fields on several Mambu entities come with additional HTML tags
(they are rich text fields, I guess that's why). Sometimes they are
useless, so stripping them is a good idea.
"""
from html.parser import HTMLParser
class MLStripper(H... | def function[strip_tags, parameter[html]]:
constant[Stripts HTML tags from text.
Note fields on several Mambu entities come with additional HTML tags
(they are rich text fields, I guess that's why). Sometimes they are
useless, so stripping them is a good idea.
]
from relative_module[html.pa... | keyword[def] identifier[strip_tags] ( identifier[html] ):
literal[string]
keyword[from] identifier[html] . identifier[parser] keyword[import] identifier[HTMLParser]
keyword[class] identifier[MLStripper] ( identifier[HTMLParser] ):
literal[string]
keyword[def] identifier[__init... | def strip_tags(html):
"""Stripts HTML tags from text.
Note fields on several Mambu entities come with additional HTML tags
(they are rich text fields, I guess that's why). Sometimes they are
useless, so stripping them is a good idea.
"""
from html.parser import HTMLParser
class MLStripper(... |
def delete_service_settings_on_scope_delete(sender, instance, **kwargs):
""" If VM that contains service settings were deleted - all settings
resources could be safely deleted from NC.
"""
for service_settings in ServiceSettings.objects.filter(scope=instance):
service_settings.unlink_descend... | def function[delete_service_settings_on_scope_delete, parameter[sender, instance]]:
constant[ If VM that contains service settings were deleted - all settings
resources could be safely deleted from NC.
]
for taget[name[service_settings]] in starred[call[name[ServiceSettings].objects.filter, ... | keyword[def] identifier[delete_service_settings_on_scope_delete] ( identifier[sender] , identifier[instance] ,** identifier[kwargs] ):
literal[string]
keyword[for] identifier[service_settings] keyword[in] identifier[ServiceSettings] . identifier[objects] . identifier[filter] ( identifier[scope] = identi... | def delete_service_settings_on_scope_delete(sender, instance, **kwargs):
""" If VM that contains service settings were deleted - all settings
resources could be safely deleted from NC.
"""
for service_settings in ServiceSettings.objects.filter(scope=instance):
service_settings.unlink_descend... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.