code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def encode_cf_variable(var, needs_copy=True, name=None):
"""
Converts an Variable into an Variable which follows some
of the CF conventions:
- Nans are masked using _FillValue (or the deprecated missing_value)
- Rescaling via: scale_factor and add_offset
- datetimes are converted to... | def function[encode_cf_variable, parameter[var, needs_copy, name]]:
constant[
Converts an Variable into an Variable which follows some
of the CF conventions:
- Nans are masked using _FillValue (or the deprecated missing_value)
- Rescaling via: scale_factor and add_offset
- datet... | keyword[def] identifier[encode_cf_variable] ( identifier[var] , identifier[needs_copy] = keyword[True] , identifier[name] = keyword[None] ):
literal[string]
identifier[ensure_not_multiindex] ( identifier[var] , identifier[name] = identifier[name] )
keyword[for] identifier[coder] keyword[in] [ ident... | def encode_cf_variable(var, needs_copy=True, name=None):
"""
Converts an Variable into an Variable which follows some
of the CF conventions:
- Nans are masked using _FillValue (or the deprecated missing_value)
- Rescaling via: scale_factor and add_offset
- datetimes are converted to... |
def matlab_formatter(level, vertices, codes=None):
"""`MATLAB`_ style contour formatter.
Contours are returned as a single Nx2, `MATLAB`_ style, contour array.
There are two types of rows in this format:
* Header: The first element of a header row is the level of the contour
(the lower level for... | def function[matlab_formatter, parameter[level, vertices, codes]]:
constant[`MATLAB`_ style contour formatter.
Contours are returned as a single Nx2, `MATLAB`_ style, contour array.
There are two types of rows in this format:
* Header: The first element of a header row is the level of the contour
... | keyword[def] identifier[matlab_formatter] ( identifier[level] , identifier[vertices] , identifier[codes] = keyword[None] ):
literal[string]
identifier[vertices] = identifier[numpy_formatter] ( identifier[level] , identifier[vertices] , identifier[codes] )
keyword[if] identifier[codes] keyword[is] k... | def matlab_formatter(level, vertices, codes=None):
"""`MATLAB`_ style contour formatter.
Contours are returned as a single Nx2, `MATLAB`_ style, contour array.
There are two types of rows in this format:
* Header: The first element of a header row is the level of the contour
(the lower level for... |
def _get_dvs_infrastructure_traffic_resources(dvs_name,
dvs_infra_traffic_ress):
'''
Returns a list of dict representations of the DVS infrastructure traffic
resource
dvs_name
The name of the DVS
dvs_infra_traffic_ress
The DVS infrastru... | def function[_get_dvs_infrastructure_traffic_resources, parameter[dvs_name, dvs_infra_traffic_ress]]:
constant[
Returns a list of dict representations of the DVS infrastructure traffic
resource
dvs_name
The name of the DVS
dvs_infra_traffic_ress
The DVS infrastructure traffic r... | keyword[def] identifier[_get_dvs_infrastructure_traffic_resources] ( identifier[dvs_name] ,
identifier[dvs_infra_traffic_ress] ):
literal[string]
identifier[log] . identifier[trace] ( literal[string]
literal[string] , identifier[dvs_name] )
identifier[res_dicts] =[]
keyword[for] identifie... | def _get_dvs_infrastructure_traffic_resources(dvs_name, dvs_infra_traffic_ress):
"""
Returns a list of dict representations of the DVS infrastructure traffic
resource
dvs_name
The name of the DVS
dvs_infra_traffic_ress
The DVS infrastructure traffic resources
"""
log.trace(... |
def BindVar(self, var_id, value):
"""Associates a value with given variable.
This can be called multiple times to associate multiple values.
Args:
var_id: A variable id to bind the values to.
value: A value to bind to the specified variable.
Raises:
KeyError: If given variable is no... | def function[BindVar, parameter[self, var_id, value]]:
constant[Associates a value with given variable.
This can be called multiple times to associate multiple values.
Args:
var_id: A variable id to bind the values to.
value: A value to bind to the specified variable.
Raises:
Ke... | keyword[def] identifier[BindVar] ( identifier[self] , identifier[var_id] , identifier[value] ):
literal[string]
keyword[if] identifier[var_id] keyword[not] keyword[in] identifier[self] . identifier[_vars] :
keyword[raise] identifier[KeyError] ( identifier[var_id] )
identifier[self] . iden... | def BindVar(self, var_id, value):
"""Associates a value with given variable.
This can be called multiple times to associate multiple values.
Args:
var_id: A variable id to bind the values to.
value: A value to bind to the specified variable.
Raises:
KeyError: If given variable is no... |
def install_package(package,
wheels_path,
venv=None,
requirement_files=None,
upgrade=False,
install_args=None):
"""Install a Python package.
Can specify a specific version.
Can specify a prerelease.
Can ... | def function[install_package, parameter[package, wheels_path, venv, requirement_files, upgrade, install_args]]:
constant[Install a Python package.
Can specify a specific version.
Can specify a prerelease.
Can specify a venv to install in.
Can specify a list of paths or urls to requirement txt f... | keyword[def] identifier[install_package] ( identifier[package] ,
identifier[wheels_path] ,
identifier[venv] = keyword[None] ,
identifier[requirement_files] = keyword[None] ,
identifier[upgrade] = keyword[False] ,
identifier[install_args] = keyword[None] ):
literal[string]
identifier[requirement_files]... | def install_package(package, wheels_path, venv=None, requirement_files=None, upgrade=False, install_args=None):
"""Install a Python package.
Can specify a specific version.
Can specify a prerelease.
Can specify a venv to install in.
Can specify a list of paths or urls to requirement txt files.
... |
def enableSync(self, url, definition = None):
"""Enables Sync capability for an AGOL feature service.
Args:
url (str): The URL of the feature service.
definition (dict): A dictionary containing valid definition values. Defaults to ``None``.
Returns:
dict: The... | def function[enableSync, parameter[self, url, definition]]:
constant[Enables Sync capability for an AGOL feature service.
Args:
url (str): The URL of the feature service.
definition (dict): A dictionary containing valid definition values. Defaults to ``None``.
Returns:
... | keyword[def] identifier[enableSync] ( identifier[self] , identifier[url] , identifier[definition] = keyword[None] ):
literal[string]
identifier[adminFS] = identifier[AdminFeatureService] ( identifier[url] = identifier[url] , identifier[securityHandler] = identifier[self] . identifier[_securityHandl... | def enableSync(self, url, definition=None):
"""Enables Sync capability for an AGOL feature service.
Args:
url (str): The URL of the feature service.
definition (dict): A dictionary containing valid definition values. Defaults to ``None``.
Returns:
dict: The resul... |
async def move_rel(self, mount: top_types.Mount, delta: top_types.Point,
speed: float = None):
""" Move the critical point of the specified mount by a specified
displacement in a specified direction, at the specified speed.
'speed' sets the speed of all axes to the given v... | <ast.AsyncFunctionDef object at 0x7da204345540> | keyword[async] keyword[def] identifier[move_rel] ( identifier[self] , identifier[mount] : identifier[top_types] . identifier[Mount] , identifier[delta] : identifier[top_types] . identifier[Point] ,
identifier[speed] : identifier[float] = keyword[None] ):
literal[string]
keyword[if] keyword[not] ... | async def move_rel(self, mount: top_types.Mount, delta: top_types.Point, speed: float=None):
""" Move the critical point of the specified mount by a specified
displacement in a specified direction, at the specified speed.
'speed' sets the speed of all axes to the given value. So, if multiple
... |
def sort_depth(vals, reverse=False):
"""Sort bids or asks by price
"""
lst = [[float(price), quantity] for price, quantity in vals.items()]
lst = sorted(lst, key=itemgetter(0), reverse=reverse)
return lst | def function[sort_depth, parameter[vals, reverse]]:
constant[Sort bids or asks by price
]
variable[lst] assign[=] <ast.ListComp object at 0x7da2054a6320>
variable[lst] assign[=] call[name[sorted], parameter[name[lst]]]
return[name[lst]] | keyword[def] identifier[sort_depth] ( identifier[vals] , identifier[reverse] = keyword[False] ):
literal[string]
identifier[lst] =[[ identifier[float] ( identifier[price] ), identifier[quantity] ] keyword[for] identifier[price] , identifier[quantity] keyword[in] identifier[vals] . identifier[ite... | def sort_depth(vals, reverse=False):
"""Sort bids or asks by price
"""
lst = [[float(price), quantity] for (price, quantity) in vals.items()]
lst = sorted(lst, key=itemgetter(0), reverse=reverse)
return lst |
def name():
"""
Generates a random person's name which has the following structure
<optional prefix> <first name> <second name> <optional suffix>
:return: a random name.
"""
result = ""
if RandomBoolean.chance(3, 5):
result += random.choice(_name_pre... | def function[name, parameter[]]:
constant[
Generates a random person's name which has the following structure
<optional prefix> <first name> <second name> <optional suffix>
:return: a random name.
]
variable[result] assign[=] constant[]
if call[name[RandomBoolean... | keyword[def] identifier[name] ():
literal[string]
identifier[result] = literal[string]
keyword[if] identifier[RandomBoolean] . identifier[chance] ( literal[int] , literal[int] ):
identifier[result] += identifier[random] . identifier[choice] ( identifier[_name_prefixes] )+ l... | def name():
"""
Generates a random person's name which has the following structure
<optional prefix> <first name> <second name> <optional suffix>
:return: a random name.
"""
result = ''
if RandomBoolean.chance(3, 5):
result += random.choice(_name_prefixes) + ' ' # d... |
def fetch(self, is_dl_forced=False):
"""
Note there is a unpublished mydrug client that works like this:
from mydrug import MyDrugInfo
md = MyDrugInfo()
r = list(md.query('_exists_:aeolus', fetch_all=True))
:param is_dl_forced: boolean, force download
:return:
... | def function[fetch, parameter[self, is_dl_forced]]:
constant[
Note there is a unpublished mydrug client that works like this:
from mydrug import MyDrugInfo
md = MyDrugInfo()
r = list(md.query('_exists_:aeolus', fetch_all=True))
:param is_dl_forced: boolean, force downloa... | keyword[def] identifier[fetch] ( identifier[self] , identifier[is_dl_forced] = keyword[False] ):
literal[string]
identifier[dir_path] = identifier[Path] ( identifier[self] . identifier[rawdir] )
identifier[aeolus_file] = identifier[dir_path] / identifier[self] . identifier[files] [ literal... | def fetch(self, is_dl_forced=False):
"""
Note there is a unpublished mydrug client that works like this:
from mydrug import MyDrugInfo
md = MyDrugInfo()
r = list(md.query('_exists_:aeolus', fetch_all=True))
:param is_dl_forced: boolean, force download
:return:
... |
def to_query(self):
"""
Returns a json-serializable representation.
"""
query = {}
for field_instance in self.fields:
query.update(field_instance.to_query())
return query | def function[to_query, parameter[self]]:
constant[
Returns a json-serializable representation.
]
variable[query] assign[=] dictionary[[], []]
for taget[name[field_instance]] in starred[name[self].fields] begin[:]
call[name[query].update, parameter[call[name[field_... | keyword[def] identifier[to_query] ( identifier[self] ):
literal[string]
identifier[query] ={}
keyword[for] identifier[field_instance] keyword[in] identifier[self] . identifier[fields] :
identifier[query] . identifier[update] ( identifier[field_instance] . identifier[to_que... | def to_query(self):
"""
Returns a json-serializable representation.
"""
query = {}
for field_instance in self.fields:
query.update(field_instance.to_query()) # depends on [control=['for'], data=['field_instance']]
return query |
def create(cls, data, id_=None, **kwargs):
r"""Create a new record instance and store it in the database.
#. Send a signal :data:`invenio_records.signals.before_record_insert`
with the new record as parameter.
#. Validate the new record data.
#. Add the new record in the da... | def function[create, parameter[cls, data, id_]]:
constant[Create a new record instance and store it in the database.
#. Send a signal :data:`invenio_records.signals.before_record_insert`
with the new record as parameter.
#. Validate the new record data.
#. Add the new recor... | keyword[def] identifier[create] ( identifier[cls] , identifier[data] , identifier[id_] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[from] . identifier[models] keyword[import] identifier[RecordMetadata]
keyword[with] identifier[db] . identifier[session] . identifier... | def create(cls, data, id_=None, **kwargs):
"""Create a new record instance and store it in the database.
#. Send a signal :data:`invenio_records.signals.before_record_insert`
with the new record as parameter.
#. Validate the new record data.
#. Add the new record in the databas... |
def clear_numeric_score_increment(self):
"""Clears the numeric score increment.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for ... | def function[clear_numeric_score_increment, parameter[self]]:
constant[Clears the numeric score increment.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
]
if <ast... | keyword[def] identifier[clear_numeric_score_increment] ( identifier[self] ):
literal[string]
keyword[if] ( identifier[self] . identifier[get_numeric_score_increment_metadata] (). identifier[is_read_only] () keyword[or]
identifier[self] . identifier[get_numeric_score_increment_met... | def clear_numeric_score_increment(self):
"""Clears the numeric score increment.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.gra... |
def filter_short(terms):
'''
only keep if brute-force possibilities are greater than this word's rank in the dictionary
'''
return [term for i, term in enumerate(terms) if 26**(len(term)) > i] | def function[filter_short, parameter[terms]]:
constant[
only keep if brute-force possibilities are greater than this word's rank in the dictionary
]
return[<ast.ListComp object at 0x7da1b0a81150>] | keyword[def] identifier[filter_short] ( identifier[terms] ):
literal[string]
keyword[return] [ identifier[term] keyword[for] identifier[i] , identifier[term] keyword[in] identifier[enumerate] ( identifier[terms] ) keyword[if] literal[int] **( identifier[len] ( identifier[term] ))> identifier[i] ] | def filter_short(terms):
"""
only keep if brute-force possibilities are greater than this word's rank in the dictionary
"""
return [term for (i, term) in enumerate(terms) if 26 ** len(term) > i] |
def _parse_variable(self, parent, patch_nml=None):
"""Parse a variable and return its name and values."""
if not patch_nml:
patch_nml = Namelist()
v_name = self.prior_token
v_values = []
# Patch state
patch_values = None
# Derived type parent index ... | def function[_parse_variable, parameter[self, parent, patch_nml]]:
constant[Parse a variable and return its name and values.]
if <ast.UnaryOp object at 0x7da1b04d7df0> begin[:]
variable[patch_nml] assign[=] call[name[Namelist], parameter[]]
variable[v_name] assign[=] name[self].p... | keyword[def] identifier[_parse_variable] ( identifier[self] , identifier[parent] , identifier[patch_nml] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[patch_nml] :
identifier[patch_nml] = identifier[Namelist] ()
identifier[v_name] = identifier[self]... | def _parse_variable(self, parent, patch_nml=None):
"""Parse a variable and return its name and values."""
if not patch_nml:
patch_nml = Namelist() # depends on [control=['if'], data=[]]
v_name = self.prior_token
v_values = []
# Patch state
patch_values = None
# Derived type parent i... |
def reorder_matrix(m1, cost='line', verbose=False, H=1e4, Texp=10, T0=1e-3, Hbrk=10):
'''
This function rearranges the nodes in matrix M1 such that the matrix
elements are squeezed along the main diagonal. The function uses a
version of simulated annealing.
Parameters
----------
M1 : NxN n... | def function[reorder_matrix, parameter[m1, cost, verbose, H, Texp, T0, Hbrk]]:
constant[
This function rearranges the nodes in matrix M1 such that the matrix
elements are squeezed along the main diagonal. The function uses a
version of simulated annealing.
Parameters
----------
M1 : Nx... | keyword[def] identifier[reorder_matrix] ( identifier[m1] , identifier[cost] = literal[string] , identifier[verbose] = keyword[False] , identifier[H] = literal[int] , identifier[Texp] = literal[int] , identifier[T0] = literal[int] , identifier[Hbrk] = literal[int] ):
literal[string]
keyword[from] identifie... | def reorder_matrix(m1, cost='line', verbose=False, H=10000.0, Texp=10, T0=0.001, Hbrk=10):
"""
This function rearranges the nodes in matrix M1 such that the matrix
elements are squeezed along the main diagonal. The function uses a
version of simulated annealing.
Parameters
----------
M1 : ... |
def _dequeue_update(self,change):
""" Only update when all changes are done """
self._update_count -=1
if self._update_count !=0:
return
self.update_shape(change) | def function[_dequeue_update, parameter[self, change]]:
constant[ Only update when all changes are done ]
<ast.AugAssign object at 0x7da2041dbbb0>
if compare[name[self]._update_count not_equal[!=] constant[0]] begin[:]
return[None]
call[name[self].update_shape, parameter[name[change]... | keyword[def] identifier[_dequeue_update] ( identifier[self] , identifier[change] ):
literal[string]
identifier[self] . identifier[_update_count] -= literal[int]
keyword[if] identifier[self] . identifier[_update_count] != literal[int] :
keyword[return]
identifi... | def _dequeue_update(self, change):
""" Only update when all changes are done """
self._update_count -= 1
if self._update_count != 0:
return # depends on [control=['if'], data=[]]
self.update_shape(change) |
def sub(self, key):
"""Returns new Vyper instance representing a sub tree of this instance.
"""
subv = Vyper()
data = self.get(key)
if isinstance(data, dict):
subv._config = data
return subv
else:
return None | def function[sub, parameter[self, key]]:
constant[Returns new Vyper instance representing a sub tree of this instance.
]
variable[subv] assign[=] call[name[Vyper], parameter[]]
variable[data] assign[=] call[name[self].get, parameter[name[key]]]
if call[name[isinstance], parameter... | keyword[def] identifier[sub] ( identifier[self] , identifier[key] ):
literal[string]
identifier[subv] = identifier[Vyper] ()
identifier[data] = identifier[self] . identifier[get] ( identifier[key] )
keyword[if] identifier[isinstance] ( identifier[data] , identifier[dict] ):
... | def sub(self, key):
"""Returns new Vyper instance representing a sub tree of this instance.
"""
subv = Vyper()
data = self.get(key)
if isinstance(data, dict):
subv._config = data
return subv # depends on [control=['if'], data=[]]
else:
return None |
def nupicBindingsPrereleaseInstalled():
"""
Make an attempt to determine if a pre-release version of nupic.bindings is
installed already.
@return: boolean
"""
try:
nupicDistribution = pkg_resources.get_distribution("nupic.bindings")
if pkg_resources.parse_version(nupicDistribution.version).is_prere... | def function[nupicBindingsPrereleaseInstalled, parameter[]]:
constant[
Make an attempt to determine if a pre-release version of nupic.bindings is
installed already.
@return: boolean
]
<ast.Try object at 0x7da18dc98b20>
return[constant[False]] | keyword[def] identifier[nupicBindingsPrereleaseInstalled] ():
literal[string]
keyword[try] :
identifier[nupicDistribution] = identifier[pkg_resources] . identifier[get_distribution] ( literal[string] )
keyword[if] identifier[pkg_resources] . identifier[parse_version] ( identifier[nupicDistribution] ... | def nupicBindingsPrereleaseInstalled():
"""
Make an attempt to determine if a pre-release version of nupic.bindings is
installed already.
@return: boolean
"""
try:
nupicDistribution = pkg_resources.get_distribution('nupic.bindings')
if pkg_resources.parse_version(nupicDistribution.versi... |
def get_parent_id(chebi_id):
'''Returns parent id'''
if len(__PARENT_IDS) == 0:
__parse_compounds()
return __PARENT_IDS[chebi_id] if chebi_id in __PARENT_IDS else float('NaN') | def function[get_parent_id, parameter[chebi_id]]:
constant[Returns parent id]
if compare[call[name[len], parameter[name[__PARENT_IDS]]] equal[==] constant[0]] begin[:]
call[name[__parse_compounds], parameter[]]
return[<ast.IfExp object at 0x7da1b0283f40>] | keyword[def] identifier[get_parent_id] ( identifier[chebi_id] ):
literal[string]
keyword[if] identifier[len] ( identifier[__PARENT_IDS] )== literal[int] :
identifier[__parse_compounds] ()
keyword[return] identifier[__PARENT_IDS] [ identifier[chebi_id] ] keyword[if] identifier[chebi_id] k... | def get_parent_id(chebi_id):
"""Returns parent id"""
if len(__PARENT_IDS) == 0:
__parse_compounds() # depends on [control=['if'], data=[]]
return __PARENT_IDS[chebi_id] if chebi_id in __PARENT_IDS else float('NaN') |
def dropKey(self, key):
'''Drop an attribute/element/key-value pair from all the dictionaries.
If the dictionary key does not exist in a particular dictionary, then
that dictionary is left unchanged.
Side effect: if the key is a number and it matches a list (interpreted
as a di... | def function[dropKey, parameter[self, key]]:
constant[Drop an attribute/element/key-value pair from all the dictionaries.
If the dictionary key does not exist in a particular dictionary, then
that dictionary is left unchanged.
Side effect: if the key is a number and it matches a list (... | keyword[def] identifier[dropKey] ( identifier[self] , identifier[key] ):
literal[string]
identifier[result] =[]
keyword[for] identifier[row] keyword[in] identifier[self] . identifier[table] :
identifier[result] . identifier[append] ( identifier[internal] . identifier[remove... | def dropKey(self, key):
"""Drop an attribute/element/key-value pair from all the dictionaries.
If the dictionary key does not exist in a particular dictionary, then
that dictionary is left unchanged.
Side effect: if the key is a number and it matches a list (interpreted
as a dictio... |
def static(self, uri, file_or_directory, pattern=r'/?.+',
use_modified_since=True, use_content_range=False):
'''Register a root to serve files from. The input can either be a
file or a directory. See
'''
static_register(self, uri, file_or_directory, pattern,
... | def function[static, parameter[self, uri, file_or_directory, pattern, use_modified_since, use_content_range]]:
constant[Register a root to serve files from. The input can either be a
file or a directory. See
]
call[name[static_register], parameter[name[self], name[uri], name[file_or_dire... | keyword[def] identifier[static] ( identifier[self] , identifier[uri] , identifier[file_or_directory] , identifier[pattern] = literal[string] ,
identifier[use_modified_since] = keyword[True] , identifier[use_content_range] = keyword[False] ):
literal[string]
identifier[static_register] ( identifier... | def static(self, uri, file_or_directory, pattern='/?.+', use_modified_since=True, use_content_range=False):
"""Register a root to serve files from. The input can either be a
file or a directory. See
"""
static_register(self, uri, file_or_directory, pattern, use_modified_since, use_content_range) |
def check_actors(self, actors):
"""
Performs checks on the actors that are to be used. Raises an exception if invalid setup.
:param actors: the actors to check
:type actors: list
"""
super(Tee, self).check_actors(actors)
actor = self.first_active
if actor... | def function[check_actors, parameter[self, actors]]:
constant[
Performs checks on the actors that are to be used. Raises an exception if invalid setup.
:param actors: the actors to check
:type actors: list
]
call[call[name[super], parameter[name[Tee], name[self]]].check_... | keyword[def] identifier[check_actors] ( identifier[self] , identifier[actors] ):
literal[string]
identifier[super] ( identifier[Tee] , identifier[self] ). identifier[check_actors] ( identifier[actors] )
identifier[actor] = identifier[self] . identifier[first_active]
keyword[if] ... | def check_actors(self, actors):
"""
Performs checks on the actors that are to be used. Raises an exception if invalid setup.
:param actors: the actors to check
:type actors: list
"""
super(Tee, self).check_actors(actors)
actor = self.first_active
if actor is None:
... |
def number(self) -> int:
"""Episode number.
Unique for an anime and episode type, but not unique across episode
types for the same anime.
"""
match = self._NUMBER_SUFFIX.search(self.epno)
return int(match.group(1)) | def function[number, parameter[self]]:
constant[Episode number.
Unique for an anime and episode type, but not unique across episode
types for the same anime.
]
variable[match] assign[=] call[name[self]._NUMBER_SUFFIX.search, parameter[name[self].epno]]
return[call[name[int],... | keyword[def] identifier[number] ( identifier[self] )-> identifier[int] :
literal[string]
identifier[match] = identifier[self] . identifier[_NUMBER_SUFFIX] . identifier[search] ( identifier[self] . identifier[epno] )
keyword[return] identifier[int] ( identifier[match] . identifier[group] (... | def number(self) -> int:
"""Episode number.
Unique for an anime and episode type, but not unique across episode
types for the same anime.
"""
match = self._NUMBER_SUFFIX.search(self.epno)
return int(match.group(1)) |
def extract_tmaster(self, topology):
"""
Returns the representation of tmaster that will
be returned from Tracker.
"""
tmasterLocation = {
"name": None,
"id": None,
"host": None,
"controller_port": None,
"master_port": None,
"stats_port": None,
}
... | def function[extract_tmaster, parameter[self, topology]]:
constant[
Returns the representation of tmaster that will
be returned from Tracker.
]
variable[tmasterLocation] assign[=] dictionary[[<ast.Constant object at 0x7da20c76f1f0>, <ast.Constant object at 0x7da20c76d7e0>, <ast.Constant obje... | keyword[def] identifier[extract_tmaster] ( identifier[self] , identifier[topology] ):
literal[string]
identifier[tmasterLocation] ={
literal[string] : keyword[None] ,
literal[string] : keyword[None] ,
literal[string] : keyword[None] ,
literal[string] : keyword[None] ,
literal[strin... | def extract_tmaster(self, topology):
"""
Returns the representation of tmaster that will
be returned from Tracker.
"""
tmasterLocation = {'name': None, 'id': None, 'host': None, 'controller_port': None, 'master_port': None, 'stats_port': None}
if topology.tmaster:
tmasterLocation['name']... |
def set_default_moe_hparams(hparams):
"""Add necessary hyperparameters for mixture-of-experts."""
hparams.moe_num_experts = 16
hparams.moe_loss_coef = 1e-2
hparams.add_hparam("moe_gating", "top_2")
# Experts have fixed capacity per batch. We need some extra capacity
# in case gating is not perfectly balanc... | def function[set_default_moe_hparams, parameter[hparams]]:
constant[Add necessary hyperparameters for mixture-of-experts.]
name[hparams].moe_num_experts assign[=] constant[16]
name[hparams].moe_loss_coef assign[=] constant[0.01]
call[name[hparams].add_hparam, parameter[constant[moe_gatin... | keyword[def] identifier[set_default_moe_hparams] ( identifier[hparams] ):
literal[string]
identifier[hparams] . identifier[moe_num_experts] = literal[int]
identifier[hparams] . identifier[moe_loss_coef] = literal[int]
identifier[hparams] . identifier[add_hparam] ( literal[string] , literal[string] )
... | def set_default_moe_hparams(hparams):
"""Add necessary hyperparameters for mixture-of-experts."""
hparams.moe_num_experts = 16
hparams.moe_loss_coef = 0.01
hparams.add_hparam('moe_gating', 'top_2')
# Experts have fixed capacity per batch. We need some extra capacity
# in case gating is not perf... |
def add_request_log_fields(
self, log_fields: LogFields,
call_details: Union[grpc.HandlerCallDetails,
grpc.ClientCallDetails]
):
"""Add log fields related to a request to the provided log fields
:param log_fields: log fields instance to which ... | def function[add_request_log_fields, parameter[self, log_fields, call_details]]:
constant[Add log fields related to a request to the provided log fields
:param log_fields: log fields instance to which to add the fields
:param call_details: some information regarding the call
]
... | keyword[def] identifier[add_request_log_fields] (
identifier[self] , identifier[log_fields] : identifier[LogFields] ,
identifier[call_details] : identifier[Union] [ identifier[grpc] . identifier[HandlerCallDetails] ,
identifier[grpc] . identifier[ClientCallDetails] ]
):
literal[string]
identifie... | def add_request_log_fields(self, log_fields: LogFields, call_details: Union[grpc.HandlerCallDetails, grpc.ClientCallDetails]):
"""Add log fields related to a request to the provided log fields
:param log_fields: log fields instance to which to add the fields
:param call_details: some information re... |
def data_log_send(self, fl_1, fl_2, fl_3, fl_4, fl_5, fl_6, force_mavlink1=False):
'''
Configurable data log probes to be used inside Simulink
fl_1 : Log value 1 (float)
fl_2 : Log value 2 (float)
... | def function[data_log_send, parameter[self, fl_1, fl_2, fl_3, fl_4, fl_5, fl_6, force_mavlink1]]:
constant[
Configurable data log probes to be used inside Simulink
fl_1 : Log value 1 (float)
fl_2 : Log value 2 (float)
... | keyword[def] identifier[data_log_send] ( identifier[self] , identifier[fl_1] , identifier[fl_2] , identifier[fl_3] , identifier[fl_4] , identifier[fl_5] , identifier[fl_6] , identifier[force_mavlink1] = keyword[False] ):
literal[string]
keyword[return] identifier[self] . identifier... | def data_log_send(self, fl_1, fl_2, fl_3, fl_4, fl_5, fl_6, force_mavlink1=False):
"""
Configurable data log probes to be used inside Simulink
fl_1 : Log value 1 (float)
fl_2 : Log value 2 (float)
fl_3 ... |
def _get_vi_mode(cli):
"""Get the current vi mode for display."""
return {
InputMode.INSERT: 'I',
InputMode.NAVIGATION: 'N',
InputMode.REPLACE: 'R',
InputMode.INSERT_MULTIPLE: 'M'
}[cli.vi_state.input_mode] | def function[_get_vi_mode, parameter[cli]]:
constant[Get the current vi mode for display.]
return[call[dictionary[[<ast.Attribute object at 0x7da2041d85b0>, <ast.Attribute object at 0x7da2041d89d0>, <ast.Attribute object at 0x7da2041dac50>, <ast.Attribute object at 0x7da2041d9db0>], [<ast.Constant object at... | keyword[def] identifier[_get_vi_mode] ( identifier[cli] ):
literal[string]
keyword[return] {
identifier[InputMode] . identifier[INSERT] : literal[string] ,
identifier[InputMode] . identifier[NAVIGATION] : literal[string] ,
identifier[InputMode] . identifier[REPLACE] : literal[string] ,
... | def _get_vi_mode(cli):
"""Get the current vi mode for display."""
return {InputMode.INSERT: 'I', InputMode.NAVIGATION: 'N', InputMode.REPLACE: 'R', InputMode.INSERT_MULTIPLE: 'M'}[cli.vi_state.input_mode] |
def pages(self):
"""The total number of pages"""
if self.per_page == 0 or self.total is None:
pages = 0
else:
pages = int(ceil(self.total / float(self.per_page)))
return pages | def function[pages, parameter[self]]:
constant[The total number of pages]
if <ast.BoolOp object at 0x7da1b21bbdf0> begin[:]
variable[pages] assign[=] constant[0]
return[name[pages]] | keyword[def] identifier[pages] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[per_page] == literal[int] keyword[or] identifier[self] . identifier[total] keyword[is] keyword[None] :
identifier[pages] = literal[int]
keyword[else] :
... | def pages(self):
"""The total number of pages"""
if self.per_page == 0 or self.total is None:
pages = 0 # depends on [control=['if'], data=[]]
else:
pages = int(ceil(self.total / float(self.per_page)))
return pages |
def sweep(crypto, private_key, to_address, fee=None, password=None, **modes):
"""
Move all funds by private key to another address.
"""
from moneywagon.tx import Transaction
tx = Transaction(crypto, verbose=modes.get('verbose', False))
tx.add_inputs(private_key=private_key, password=password, **... | def function[sweep, parameter[crypto, private_key, to_address, fee, password]]:
constant[
Move all funds by private key to another address.
]
from relative_module[moneywagon.tx] import module[Transaction]
variable[tx] assign[=] call[name[Transaction], parameter[name[crypto]]]
call[na... | keyword[def] identifier[sweep] ( identifier[crypto] , identifier[private_key] , identifier[to_address] , identifier[fee] = keyword[None] , identifier[password] = keyword[None] ,** identifier[modes] ):
literal[string]
keyword[from] identifier[moneywagon] . identifier[tx] keyword[import] identifier[Transa... | def sweep(crypto, private_key, to_address, fee=None, password=None, **modes):
"""
Move all funds by private key to another address.
"""
from moneywagon.tx import Transaction
tx = Transaction(crypto, verbose=modes.get('verbose', False))
tx.add_inputs(private_key=private_key, password=password, **... |
def strip_seq_cntrl(self, idx):
"""strip(2 byte) wlan.seq(12 bit) and wlan.fram(4 bit)
number information.
:seq_cntrl: ctypes.Structure
:return: int
sequence number
:return: int
fragment number
"""
seq_cntrl = struct.unpack('H', self._packe... | def function[strip_seq_cntrl, parameter[self, idx]]:
constant[strip(2 byte) wlan.seq(12 bit) and wlan.fram(4 bit)
number information.
:seq_cntrl: ctypes.Structure
:return: int
sequence number
:return: int
fragment number
]
variable[seq_cntr... | keyword[def] identifier[strip_seq_cntrl] ( identifier[self] , identifier[idx] ):
literal[string]
identifier[seq_cntrl] = identifier[struct] . identifier[unpack] ( literal[string] , identifier[self] . identifier[_packet] [ identifier[idx] : identifier[idx] + literal[int] ])[ literal[int] ]
... | def strip_seq_cntrl(self, idx):
"""strip(2 byte) wlan.seq(12 bit) and wlan.fram(4 bit)
number information.
:seq_cntrl: ctypes.Structure
:return: int
sequence number
:return: int
fragment number
"""
seq_cntrl = struct.unpack('H', self._packet[idx:id... |
def _save_files(self, data, dtype_out_time):
"""Save the data to netcdf files in direc_out."""
path = self.path_out[dtype_out_time]
if not os.path.isdir(self.dir_out):
os.makedirs(self.dir_out)
if 'reg' in dtype_out_time:
try:
reg_data = xr.open_da... | def function[_save_files, parameter[self, data, dtype_out_time]]:
constant[Save the data to netcdf files in direc_out.]
variable[path] assign[=] call[name[self].path_out][name[dtype_out_time]]
if <ast.UnaryOp object at 0x7da1b0477d30> begin[:]
call[name[os].makedirs, parameter[na... | keyword[def] identifier[_save_files] ( identifier[self] , identifier[data] , identifier[dtype_out_time] ):
literal[string]
identifier[path] = identifier[self] . identifier[path_out] [ identifier[dtype_out_time] ]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isd... | def _save_files(self, data, dtype_out_time):
"""Save the data to netcdf files in direc_out."""
path = self.path_out[dtype_out_time]
if not os.path.isdir(self.dir_out):
os.makedirs(self.dir_out) # depends on [control=['if'], data=[]]
if 'reg' in dtype_out_time:
try:
reg_data ... |
def regexes_match_sublist(regexes, match_candidates):
"""
Filter the match_candidates list to return only the candidate that match the regex
:param regexes: a list of regex used to filter the list of candidates
:param match_candidates: the list of candidates
:return: the filtered list of only the ca... | def function[regexes_match_sublist, parameter[regexes, match_candidates]]:
constant[
Filter the match_candidates list to return only the candidate that match the regex
:param regexes: a list of regex used to filter the list of candidates
:param match_candidates: the list of candidates
:return: t... | keyword[def] identifier[regexes_match_sublist] ( identifier[regexes] , identifier[match_candidates] ):
literal[string]
keyword[return] [ identifier[match] keyword[for] identifier[sublist] keyword[in] [ identifier[regex_match_sublist] ( identifier[rgx] , identifier[match_candidates] ) keyword[for] iden... | def regexes_match_sublist(regexes, match_candidates):
"""
Filter the match_candidates list to return only the candidate that match the regex
:param regexes: a list of regex used to filter the list of candidates
:param match_candidates: the list of candidates
:return: the filtered list of only the ca... |
def update(self, **kwargs):
"""Updates the server with any changes you've made to the current input
along with any additional arguments you specify.
:param kwargs: Additional arguments (optional). For more about the
available parameters, see `Input parameters <http://dev.splunk.com/... | def function[update, parameter[self]]:
constant[Updates the server with any changes you've made to the current input
along with any additional arguments you specify.
:param kwargs: Additional arguments (optional). For more about the
available parameters, see `Input parameters <http:... | keyword[def] identifier[update] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[self] . identifier[kind] keyword[not] keyword[in] [ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ]:
keywor... | def update(self, **kwargs):
"""Updates the server with any changes you've made to the current input
along with any additional arguments you specify.
:param kwargs: Additional arguments (optional). For more about the
available parameters, see `Input parameters <http://dev.splunk.com/view... |
def load(self, data, many=None, partial=None, unknown=None):
"""Deserialize a data structure to an object defined by this Schema's fields.
:param dict data: The data to deserialize.
:param bool many: Whether to deserialize `data` as a collection. If `None`, the
value for `self.many`... | def function[load, parameter[self, data, many, partial, unknown]]:
constant[Deserialize a data structure to an object defined by this Schema's fields.
:param dict data: The data to deserialize.
:param bool many: Whether to deserialize `data` as a collection. If `None`, the
value for... | keyword[def] identifier[load] ( identifier[self] , identifier[data] , identifier[many] = keyword[None] , identifier[partial] = keyword[None] , identifier[unknown] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[_do_load] (
identifier[data] , identifier[man... | def load(self, data, many=None, partial=None, unknown=None):
"""Deserialize a data structure to an object defined by this Schema's fields.
:param dict data: The data to deserialize.
:param bool many: Whether to deserialize `data` as a collection. If `None`, the
value for `self.many` is ... |
def to_yaml(self):
"""Store an instance to the referenced YAML file."""
import yaml
with self.__reference__.open('w') as fp:
yaml.dump(self.asjsonld(), fp, default_flow_style=False) | def function[to_yaml, parameter[self]]:
constant[Store an instance to the referenced YAML file.]
import module[yaml]
with call[name[self].__reference__.open, parameter[constant[w]]] begin[:]
call[name[yaml].dump, parameter[call[name[self].asjsonld, parameter[]], name[fp]]] | keyword[def] identifier[to_yaml] ( identifier[self] ):
literal[string]
keyword[import] identifier[yaml]
keyword[with] identifier[self] . identifier[__reference__] . identifier[open] ( literal[string] ) keyword[as] identifier[fp] :
identifier[yaml] . identifier[dump] ( ide... | def to_yaml(self):
"""Store an instance to the referenced YAML file."""
import yaml
with self.__reference__.open('w') as fp:
yaml.dump(self.asjsonld(), fp, default_flow_style=False) # depends on [control=['with'], data=['fp']] |
def CallApiHandler(handler, args, token=None):
"""Handles API call to a given handler with given args and token."""
result = handler.Handle(args, token=token)
expected_type = handler.result_type
if expected_type is None:
expected_type = None.__class__
if result.__class__ != expected_type:
... | def function[CallApiHandler, parameter[handler, args, token]]:
constant[Handles API call to a given handler with given args and token.]
variable[result] assign[=] call[name[handler].Handle, parameter[name[args]]]
variable[expected_type] assign[=] name[handler].result_type
if compare[name... | keyword[def] identifier[CallApiHandler] ( identifier[handler] , identifier[args] , identifier[token] = keyword[None] ):
literal[string]
identifier[result] = identifier[handler] . identifier[Handle] ( identifier[args] , identifier[token] = identifier[token] )
identifier[expected_type] = identifier[ha... | def CallApiHandler(handler, args, token=None):
"""Handles API call to a given handler with given args and token."""
result = handler.Handle(args, token=token)
expected_type = handler.result_type
if expected_type is None:
expected_type = None.__class__ # depends on [control=['if'], data=['expect... |
def detectability(self,**kwargs):
"""
An a priori detectability proxy.
"""
distance_modulus = kwargs.get('distance_modulus')
distance = mod2dist(distance_modulus)
stellar_mass = kwargs.get('stellar_mass')
extension = kwargs.get('extension')
# Normalized t... | def function[detectability, parameter[self]]:
constant[
An a priori detectability proxy.
]
variable[distance_modulus] assign[=] call[name[kwargs].get, parameter[constant[distance_modulus]]]
variable[distance] assign[=] call[name[mod2dist], parameter[name[distance_modulus]]]
... | keyword[def] identifier[detectability] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[distance_modulus] = identifier[kwargs] . identifier[get] ( literal[string] )
identifier[distance] = identifier[mod2dist] ( identifier[distance_modulus] )
identifier[stell... | def detectability(self, **kwargs):
"""
An a priori detectability proxy.
"""
distance_modulus = kwargs.get('distance_modulus')
distance = mod2dist(distance_modulus)
stellar_mass = kwargs.get('stellar_mass')
extension = kwargs.get('extension')
# Normalized to 10^3 Msolar at mod=18
... |
def describe_features(self, traj):
"""Return a list of dictionaries describing the atom pair features.
Parameters
----------
traj : mdtraj.Trajectory
The trajectory to describe
Returns
-------
feature_descs : list of dict
Dictionary descr... | def function[describe_features, parameter[self, traj]]:
constant[Return a list of dictionaries describing the atom pair features.
Parameters
----------
traj : mdtraj.Trajectory
The trajectory to describe
Returns
-------
feature_descs : list of dict
... | keyword[def] identifier[describe_features] ( identifier[self] , identifier[traj] ):
literal[string]
identifier[feature_descs] =[]
identifier[top] = identifier[traj] . identifier[topology]
identifier[residue_indices] =[[ identifier[top] . identifier[atom] ( identifier[i] [ litera... | def describe_features(self, traj):
"""Return a list of dictionaries describing the atom pair features.
Parameters
----------
traj : mdtraj.Trajectory
The trajectory to describe
Returns
-------
feature_descs : list of dict
Dictionary describin... |
def endpoint_get(service, region=None, profile=None, interface=None, **connection_args):
'''
Return a specific endpoint (keystone endpoint-get)
CLI Example:
.. code-block:: bash
salt 'v2' keystone.endpoint_get nova [region=RegionOne]
salt 'v3' keystone.endpoint_get nova interface=adm... | def function[endpoint_get, parameter[service, region, profile, interface]]:
constant[
Return a specific endpoint (keystone endpoint-get)
CLI Example:
.. code-block:: bash
salt 'v2' keystone.endpoint_get nova [region=RegionOne]
salt 'v3' keystone.endpoint_get nova interface=admin ... | keyword[def] identifier[endpoint_get] ( identifier[service] , identifier[region] = keyword[None] , identifier[profile] = keyword[None] , identifier[interface] = keyword[None] ,** identifier[connection_args] ):
literal[string]
identifier[auth] ( identifier[profile] ,** identifier[connection_args] )
ide... | def endpoint_get(service, region=None, profile=None, interface=None, **connection_args):
"""
Return a specific endpoint (keystone endpoint-get)
CLI Example:
.. code-block:: bash
salt 'v2' keystone.endpoint_get nova [region=RegionOne]
salt 'v3' keystone.endpoint_get nova interface=adm... |
def _make_standalone_handler(preamble):
"""Class factory used so that preamble can be passed to :py:class:`_StandaloneHandler`
without use of static members"""
class _StandaloneHandler(BaseHTTPRequestHandler, object):
"""HTTP Handler for standalone mode"""
def do_GET(self):
sel... | def function[_make_standalone_handler, parameter[preamble]]:
constant[Class factory used so that preamble can be passed to :py:class:`_StandaloneHandler`
without use of static members]
class class[_StandaloneHandler, parameter[]] begin[:]
constant[HTTP Handler for standalone mode]
... | keyword[def] identifier[_make_standalone_handler] ( identifier[preamble] ):
literal[string]
keyword[class] identifier[_StandaloneHandler] ( identifier[BaseHTTPRequestHandler] , identifier[object] ):
literal[string]
keyword[def] identifier[do_GET] ( identifier[self] ):
ide... | def _make_standalone_handler(preamble):
"""Class factory used so that preamble can be passed to :py:class:`_StandaloneHandler`
without use of static members"""
class _StandaloneHandler(BaseHTTPRequestHandler, object):
"""HTTP Handler for standalone mode"""
def do_GET(self):
se... |
def FitRadius(z, SampleFreq, Damping, HistBins=100):
"""
Fits the dynamical potential to the Steady
State Potential by varying the Radius.
z : ndarray
Position data
SampleFreq : float
frequency at which the position data was
sampled
Damping : float
value of... | def function[FitRadius, parameter[z, SampleFreq, Damping, HistBins]]:
constant[
Fits the dynamical potential to the Steady
State Potential by varying the Radius.
z : ndarray
Position data
SampleFreq : float
frequency at which the position data was
sampled
Dampi... | keyword[def] identifier[FitRadius] ( identifier[z] , identifier[SampleFreq] , identifier[Damping] , identifier[HistBins] = literal[int] ):
literal[string]
identifier[dt] = literal[int] / identifier[SampleFreq]
identifier[boltzmann] = identifier[scipy] . identifier[constants] . identifier[Boltzmann]
... | def FitRadius(z, SampleFreq, Damping, HistBins=100):
"""
Fits the dynamical potential to the Steady
State Potential by varying the Radius.
z : ndarray
Position data
SampleFreq : float
frequency at which the position data was
sampled
Damping : float
value of... |
def format_baseline_for_output(baseline):
"""
:type baseline: dict
:rtype: str
"""
for filename, secret_list in baseline['results'].items():
baseline['results'][filename] = sorted(
secret_list,
key=lambda x: (x['line_number'], x['hashed_secret'],),
)
retu... | def function[format_baseline_for_output, parameter[baseline]]:
constant[
:type baseline: dict
:rtype: str
]
for taget[tuple[[<ast.Name object at 0x7da20c6e64d0>, <ast.Name object at 0x7da20c6e75e0>]]] in starred[call[call[name[baseline]][constant[results]].items, parameter[]]] begin[:]
... | keyword[def] identifier[format_baseline_for_output] ( identifier[baseline] ):
literal[string]
keyword[for] identifier[filename] , identifier[secret_list] keyword[in] identifier[baseline] [ literal[string] ]. identifier[items] ():
identifier[baseline] [ literal[string] ][ identifier[filename] ]=... | def format_baseline_for_output(baseline):
"""
:type baseline: dict
:rtype: str
"""
for (filename, secret_list) in baseline['results'].items():
baseline['results'][filename] = sorted(secret_list, key=lambda x: (x['line_number'], x['hashed_secret'])) # depends on [control=['for'], data=[]]
... |
def patch_worker_factory():
"""
Patches the ``luigi.interface._WorkerSchedulerFactory`` to include sandboxing information when
create a worker instance.
"""
def create_worker(self, scheduler, worker_processes, assistant=False):
worker = luigi.worker.Worker(scheduler=scheduler, worker_process... | def function[patch_worker_factory, parameter[]]:
constant[
Patches the ``luigi.interface._WorkerSchedulerFactory`` to include sandboxing information when
create a worker instance.
]
def function[create_worker, parameter[self, scheduler, worker_processes, assistant]]:
variable... | keyword[def] identifier[patch_worker_factory] ():
literal[string]
keyword[def] identifier[create_worker] ( identifier[self] , identifier[scheduler] , identifier[worker_processes] , identifier[assistant] = keyword[False] ):
identifier[worker] = identifier[luigi] . identifier[worker] . identifier[W... | def patch_worker_factory():
"""
Patches the ``luigi.interface._WorkerSchedulerFactory`` to include sandboxing information when
create a worker instance.
"""
def create_worker(self, scheduler, worker_processes, assistant=False):
worker = luigi.worker.Worker(scheduler=scheduler, worker_proces... |
def collect_instance(self, nick, host, port, unix_socket, auth):
"""Collect metrics from a single Redis instance
:param str nick: nickname of redis instance
:param str host: redis host
:param int port: redis port
:param str unix_socket: unix socket, if applicable
:param str auth: authentication password
... | def function[collect_instance, parameter[self, nick, host, port, unix_socket, auth]]:
constant[Collect metrics from a single Redis instance
:param str nick: nickname of redis instance
:param str host: redis host
:param int port: redis port
:param str unix_socket: unix socket, if applicable
:param str auth: aut... | keyword[def] identifier[collect_instance] ( identifier[self] , identifier[nick] , identifier[host] , identifier[port] , identifier[unix_socket] , identifier[auth] ):
literal[string]
identifier[info] = identifier[self] . identifier[_get_info] ( identifier[host] , identifier[port] , identif... | def collect_instance(self, nick, host, port, unix_socket, auth):
"""Collect metrics from a single Redis instance
:param str nick: nickname of redis instance
:param str host: redis host
:param int port: redis port
:param str unix_socket: unix socket, if applicable
:param str auth: authentication password
"... |
def whisper_filename(self):
"""Build a file path to the Whisper database"""
source_name = self.source_id and self.source.name or ''
return get_valid_filename("{0}__{1}.wsp".format(source_name,
self.name)) | def function[whisper_filename, parameter[self]]:
constant[Build a file path to the Whisper database]
variable[source_name] assign[=] <ast.BoolOp object at 0x7da20c991cc0>
return[call[name[get_valid_filename], parameter[call[constant[{0}__{1}.wsp].format, parameter[name[source_name], name[self].name]... | keyword[def] identifier[whisper_filename] ( identifier[self] ):
literal[string]
identifier[source_name] = identifier[self] . identifier[source_id] keyword[and] identifier[self] . identifier[source] . identifier[name] keyword[or] literal[string]
keyword[return] identifier[get_valid_fi... | def whisper_filename(self):
"""Build a file path to the Whisper database"""
source_name = self.source_id and self.source.name or ''
return get_valid_filename('{0}__{1}.wsp'.format(source_name, self.name)) |
def get_critical_compositions(self, comp1, comp2):
"""
Get the critical compositions along the tieline between two
compositions. I.e. where the decomposition products change.
The endpoints are also returned.
Args:
comp1, comp2 (Composition): compositions that define t... | def function[get_critical_compositions, parameter[self, comp1, comp2]]:
constant[
Get the critical compositions along the tieline between two
compositions. I.e. where the decomposition products change.
The endpoints are also returned.
Args:
comp1, comp2 (Composition):... | keyword[def] identifier[get_critical_compositions] ( identifier[self] , identifier[comp1] , identifier[comp2] ):
literal[string]
identifier[n1] = identifier[comp1] . identifier[num_atoms]
identifier[n2] = identifier[comp2] . identifier[num_atoms]
identifier[pd_els] = identifier... | def get_critical_compositions(self, comp1, comp2):
"""
Get the critical compositions along the tieline between two
compositions. I.e. where the decomposition products change.
The endpoints are also returned.
Args:
comp1, comp2 (Composition): compositions that define the t... |
def add_static_route(self, method: Union[str, Methods], route: str, handler: Callable,
skip_middleware=False):
"""
Adds a static route. A static route is a special route that
doesnt follow any of the normal rules, and never has any path
parameters.
Ideall... | def function[add_static_route, parameter[self, method, route, handler, skip_middleware]]:
constant[
Adds a static route. A static route is a special route that
doesnt follow any of the normal rules, and never has any path
parameters.
Ideally, this is used for non-public facing en... | keyword[def] identifier[add_static_route] ( identifier[self] , identifier[method] : identifier[Union] [ identifier[str] , identifier[Methods] ], identifier[route] : identifier[str] , identifier[handler] : identifier[Callable] ,
identifier[skip_middleware] = keyword[False] ):
literal[string]
keywor... | def add_static_route(self, method: Union[str, Methods], route: str, handler: Callable, skip_middleware=False):
"""
Adds a static route. A static route is a special route that
doesnt follow any of the normal rules, and never has any path
parameters.
Ideally, this is used for non-publi... |
def _copy_id_str_old(self):
'''
Return the string to execute ssh-copy-id
'''
if self.passwd:
# Using single quotes prevents shell expansion and
# passwords containing '$'
return "{0} {1} '{2} -p {3} {4} {5}@{6}'".format(
'ssh-copy-i... | def function[_copy_id_str_old, parameter[self]]:
constant[
Return the string to execute ssh-copy-id
]
if name[self].passwd begin[:]
return[call[constant[{0} {1} '{2} -p {3} {4} {5}@{6}'].format, parameter[constant[ssh-copy-id], call[constant[-i {0}.pub].format, parameter[name[sel... | keyword[def] identifier[_copy_id_str_old] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[passwd] :
keyword[return] literal[string] . identifier[format] (
literal[string] ,
literal[string] . identifier[format... | def _copy_id_str_old(self):
"""
Return the string to execute ssh-copy-id
"""
if self.passwd:
# Using single quotes prevents shell expansion and
# passwords containing '$'
return "{0} {1} '{2} -p {3} {4} {5}@{6}'".format('ssh-copy-id', '-i {0}.pub'.format(self.priv), self.... |
def anchor_idx(self):
"""int or str representing index of anchor element in dimension.
When the anchor is an operation, like 'top' or 'bottom'
"""
anchor = self.anchor
if anchor in ["top", "bottom"]:
return anchor
return self.valid_elements.get_by_id(anchor).... | def function[anchor_idx, parameter[self]]:
constant[int or str representing index of anchor element in dimension.
When the anchor is an operation, like 'top' or 'bottom'
]
variable[anchor] assign[=] name[self].anchor
if compare[name[anchor] in list[[<ast.Constant object at 0x7da... | keyword[def] identifier[anchor_idx] ( identifier[self] ):
literal[string]
identifier[anchor] = identifier[self] . identifier[anchor]
keyword[if] identifier[anchor] keyword[in] [ literal[string] , literal[string] ]:
keyword[return] identifier[anchor]
keyword[retur... | def anchor_idx(self):
"""int or str representing index of anchor element in dimension.
When the anchor is an operation, like 'top' or 'bottom'
"""
anchor = self.anchor
if anchor in ['top', 'bottom']:
return anchor # depends on [control=['if'], data=['anchor']]
return self.valid... |
def gradient(self):
"""Gradient operator of the functional."""
if self.operator is None:
return ConstantOperator(self.vector, self.domain)
else:
if not self.operator.is_linear:
# TODO: Acutally works otherwise, but needs more work
raise Not... | def function[gradient, parameter[self]]:
constant[Gradient operator of the functional.]
if compare[name[self].operator is constant[None]] begin[:]
return[call[name[ConstantOperator], parameter[name[self].vector, name[self].domain]]] | keyword[def] identifier[gradient] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[operator] keyword[is] keyword[None] :
keyword[return] identifier[ConstantOperator] ( identifier[self] . identifier[vector] , identifier[self] . identifier[domain] )
... | def gradient(self):
"""Gradient operator of the functional."""
if self.operator is None:
return ConstantOperator(self.vector, self.domain) # depends on [control=['if'], data=[]]
else:
if not self.operator.is_linear:
# TODO: Acutally works otherwise, but needs more work
... |
def generate(basename, xml):
'''generate complete javascript implementation'''
if basename.endswith('.js'):
filename = basename
else:
filename = basename + '.js'
msgs = []
enums = []
filelist = []
for x in xml:
msgs.extend(x.message)
enums.extend(x.enum)
... | def function[generate, parameter[basename, xml]]:
constant[generate complete javascript implementation]
if call[name[basename].endswith, parameter[constant[.js]]] begin[:]
variable[filename] assign[=] name[basename]
variable[msgs] assign[=] list[[]]
variable[enums] assign... | keyword[def] identifier[generate] ( identifier[basename] , identifier[xml] ):
literal[string]
keyword[if] identifier[basename] . identifier[endswith] ( literal[string] ):
identifier[filename] = identifier[basename]
keyword[else] :
identifier[filename] = identifier[basename] + lite... | def generate(basename, xml):
"""generate complete javascript implementation"""
if basename.endswith('.js'):
filename = basename # depends on [control=['if'], data=[]]
else:
filename = basename + '.js'
msgs = []
enums = []
filelist = []
for x in xml:
msgs.extend(x.mes... |
def log_wrap(origfunc):
"""
DRY: Use magic instead of code to get a string for the correct log
level when calling ``print_log_msg``. Because writing the same
boilerplate code in each log_XXX def was too painful to commit.
"""
def orig_func_wraper(msg, *args):
# Take the callers name and ... | def function[log_wrap, parameter[origfunc]]:
constant[
DRY: Use magic instead of code to get a string for the correct log
level when calling ``print_log_msg``. Because writing the same
boilerplate code in each log_XXX def was too painful to commit.
]
def function[orig_func_wraper, parame... | keyword[def] identifier[log_wrap] ( identifier[origfunc] ):
literal[string]
keyword[def] identifier[orig_func_wraper] ( identifier[msg] ,* identifier[args] ):
identifier[log_level] = identifier[origfunc] . identifier[__name__] . identifier[split] ( literal[string] )[ literal[int] ]
... | def log_wrap(origfunc):
"""
DRY: Use magic instead of code to get a string for the correct log
level when calling ``print_log_msg``. Because writing the same
boilerplate code in each log_XXX def was too painful to commit.
"""
def orig_func_wraper(msg, *args):
# Take the callers name and... |
def k15(k15file, dir_path='.', input_dir_path='',
meas_file='measurements.txt', aniso_outfile='specimens.txt',
samp_file="samples.txt", result_file ="rmag_anisotropy.txt",
specnum=0, sample_naming_con='1', location="unknown",
data_model_num=3):
"""
converts .k15 format data to Ma... | def function[k15, parameter[k15file, dir_path, input_dir_path, meas_file, aniso_outfile, samp_file, result_file, specnum, sample_naming_con, location, data_model_num]]:
constant[
converts .k15 format data to MagIC format.
assumes Jelinek Kappabridge measurement scheme.
Parameters
----------
... | keyword[def] identifier[k15] ( identifier[k15file] , identifier[dir_path] = literal[string] , identifier[input_dir_path] = literal[string] ,
identifier[meas_file] = literal[string] , identifier[aniso_outfile] = literal[string] ,
identifier[samp_file] = literal[string] , identifier[result_file] = literal[string] ,
... | def k15(k15file, dir_path='.', input_dir_path='', meas_file='measurements.txt', aniso_outfile='specimens.txt', samp_file='samples.txt', result_file='rmag_anisotropy.txt', specnum=0, sample_naming_con='1', location='unknown', data_model_num=3):
"""
converts .k15 format data to MagIC format.
assumes Jelinek ... |
def delete_folder(self, folder_id, recursive=True):
"""Delete an existing folder
Args:
folder_id (int): ID of the folder to delete.
recursive (bool): Delete all subfolder if True.
Returns:
dict. Response from Box.
Raises:
BoxError: An er... | def function[delete_folder, parameter[self, folder_id, recursive]]:
constant[Delete an existing folder
Args:
folder_id (int): ID of the folder to delete.
recursive (bool): Delete all subfolder if True.
Returns:
dict. Response from Box.
Raises:
... | keyword[def] identifier[delete_folder] ( identifier[self] , identifier[folder_id] , identifier[recursive] = keyword[True] ):
literal[string]
keyword[return] identifier[self] . identifier[__request] ( literal[string] , literal[string] %( identifier[folder_id] ,),
identifier[querystring] ={... | def delete_folder(self, folder_id, recursive=True):
"""Delete an existing folder
Args:
folder_id (int): ID of the folder to delete.
recursive (bool): Delete all subfolder if True.
Returns:
dict. Response from Box.
Raises:
BoxError: An error ... |
def gen_rand_str(*size, use=None, keyspace=None):
""" Generates a random string using random module specified in @use within
the @keyspace
@*size: #int size range for the length of the string
@use: the random module to use
@keyspace: #str chars allowed in the random string
.... | def function[gen_rand_str, parameter[]]:
constant[ Generates a random string using random module specified in @use within
the @keyspace
@*size: #int size range for the length of the string
@use: the random module to use
@keyspace: #str chars allowed in the random string
... | keyword[def] identifier[gen_rand_str] (* identifier[size] , identifier[use] = keyword[None] , identifier[keyspace] = keyword[None] ):
literal[string]
identifier[keyspace] = identifier[keyspace] keyword[or] ( identifier[string] . identifier[ascii_letters] + identifier[string] . identifier[digits] )
id... | def gen_rand_str(*size, use=None, keyspace=None):
""" Generates a random string using random module specified in @use within
the @keyspace
@*size: #int size range for the length of the string
@use: the random module to use
@keyspace: #str chars allowed in the random string
.... |
def do_photometry(self, image, init_guesses=None):
"""
Perform PSF photometry in ``image``.
This method assumes that ``psf_model`` has centroids and flux
parameters which will be fitted to the data provided in
``image``. A compound model, in fact a sum of ``psf_model``,
... | def function[do_photometry, parameter[self, image, init_guesses]]:
constant[
Perform PSF photometry in ``image``.
This method assumes that ``psf_model`` has centroids and flux
parameters which will be fitted to the data provided in
``image``. A compound model, in fact a sum of `... | keyword[def] identifier[do_photometry] ( identifier[self] , identifier[image] , identifier[init_guesses] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[bkg_estimator] keyword[is] keyword[not] keyword[None] :
identifier[image] = identifier[image] - ide... | def do_photometry(self, image, init_guesses=None):
"""
Perform PSF photometry in ``image``.
This method assumes that ``psf_model`` has centroids and flux
parameters which will be fitted to the data provided in
``image``. A compound model, in fact a sum of ``psf_model``,
will... |
def f_store(self, recursive=True, store_data=pypetconstants.STORE_DATA,
max_depth=None):
"""Stores a group node to disk
:param recursive:
Whether recursively all children should be stored too. Default is ``True``.
:param store_data:
For how to choose '... | def function[f_store, parameter[self, recursive, store_data, max_depth]]:
constant[Stores a group node to disk
:param recursive:
Whether recursively all children should be stored too. Default is ``True``.
:param store_data:
For how to choose 'store_data' see :ref:`mor... | keyword[def] identifier[f_store] ( identifier[self] , identifier[recursive] = keyword[True] , identifier[store_data] = identifier[pypetconstants] . identifier[STORE_DATA] ,
identifier[max_depth] = keyword[None] ):
literal[string]
identifier[traj] = identifier[self] . identifier[_nn_interface] . id... | def f_store(self, recursive=True, store_data=pypetconstants.STORE_DATA, max_depth=None):
"""Stores a group node to disk
:param recursive:
Whether recursively all children should be stored too. Default is ``True``.
:param store_data:
For how to choose 'store_data' see :ref... |
def OPTIONS(self, *args, **kwargs):
"""Handles CORS requests for this controller
if self.cors is False then this will raise a 405, otherwise it sets everything
necessary to satisfy the request in self.response
"""
if not self.cors:
raise CallError(405)
req =... | def function[OPTIONS, parameter[self]]:
constant[Handles CORS requests for this controller
if self.cors is False then this will raise a 405, otherwise it sets everything
necessary to satisfy the request in self.response
]
if <ast.UnaryOp object at 0x7da20c992fe0> begin[:]
... | keyword[def] identifier[OPTIONS] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[cors] :
keyword[raise] identifier[CallError] ( literal[int] )
identifier[req] = identifier[self] . ident... | def OPTIONS(self, *args, **kwargs):
"""Handles CORS requests for this controller
if self.cors is False then this will raise a 405, otherwise it sets everything
necessary to satisfy the request in self.response
"""
if not self.cors:
raise CallError(405) # depends on [control=['i... |
def _perform_call(self, query_url, default_response=None, timeout=10):
"""Returns the raw results from the API"""
try:
response = requests.get(query_url, timeout=timeout)
except socket.timeout:
current_plugin.logger.warning("Timeout contacting Piwik server")
r... | def function[_perform_call, parameter[self, query_url, default_response, timeout]]:
constant[Returns the raw results from the API]
<ast.Try object at 0x7da1b0383fa0>
return[name[response].content] | keyword[def] identifier[_perform_call] ( identifier[self] , identifier[query_url] , identifier[default_response] = keyword[None] , identifier[timeout] = literal[int] ):
literal[string]
keyword[try] :
identifier[response] = identifier[requests] . identifier[get] ( identifier[query_url] ... | def _perform_call(self, query_url, default_response=None, timeout=10):
"""Returns the raw results from the API"""
try:
response = requests.get(query_url, timeout=timeout) # depends on [control=['try'], data=[]]
except socket.timeout:
current_plugin.logger.warning('Timeout contacting Piwik s... |
def import_locations(self, zone_file):
"""Parse zoneinfo zone description data files.
``import_locations()`` returns a list of :class:`Zone` objects.
It expects data files in one of the following formats::
AN +1211-06900 America/Curacao
AO -0848+01314 Africa/Luanda
... | def function[import_locations, parameter[self, zone_file]]:
constant[Parse zoneinfo zone description data files.
``import_locations()`` returns a list of :class:`Zone` objects.
It expects data files in one of the following formats::
AN +1211-06900 America/Curacao
AO -0... | keyword[def] identifier[import_locations] ( identifier[self] , identifier[zone_file] ):
literal[string]
identifier[self] . identifier[_zone_file] = identifier[zone_file]
identifier[field_names] =( literal[string] , literal[string] , literal[string] , literal[string] )
identifier... | def import_locations(self, zone_file):
"""Parse zoneinfo zone description data files.
``import_locations()`` returns a list of :class:`Zone` objects.
It expects data files in one of the following formats::
AN +1211-06900 America/Curacao
AO -0848+01314 Africa/Luanda
... |
def build_state(
cls,
db: BaseAtomicDB,
header: BlockHeader,
previous_hashes: Iterable[Hash32] = ()) -> BaseState:
"""
You probably want `VM().state` instead of this.
Occasionally, you want to build custom state against a particular header and DB,... | def function[build_state, parameter[cls, db, header, previous_hashes]]:
constant[
You probably want `VM().state` instead of this.
Occasionally, you want to build custom state against a particular header and DB,
even if you don't have the VM initialized. This is a convenience method to d... | keyword[def] identifier[build_state] (
identifier[cls] ,
identifier[db] : identifier[BaseAtomicDB] ,
identifier[header] : identifier[BlockHeader] ,
identifier[previous_hashes] : identifier[Iterable] [ identifier[Hash32] ]=())-> identifier[BaseState] :
literal[string]
identifier[execution_conte... | def build_state(cls, db: BaseAtomicDB, header: BlockHeader, previous_hashes: Iterable[Hash32]=()) -> BaseState:
"""
You probably want `VM().state` instead of this.
Occasionally, you want to build custom state against a particular header and DB,
even if you don't have the VM initialized. Thi... |
def remove_api_key(self, api_id, stage_name):
"""
Remove a generated API key for api_id and stage_name
"""
response = self.apigateway_client.get_api_keys(
limit=1,
nameQuery='{}_{}'.format(stage_name, api_id)
)
for api_key in response.get('items'):... | def function[remove_api_key, parameter[self, api_id, stage_name]]:
constant[
Remove a generated API key for api_id and stage_name
]
variable[response] assign[=] call[name[self].apigateway_client.get_api_keys, parameter[]]
for taget[name[api_key]] in starred[call[name[response].ge... | keyword[def] identifier[remove_api_key] ( identifier[self] , identifier[api_id] , identifier[stage_name] ):
literal[string]
identifier[response] = identifier[self] . identifier[apigateway_client] . identifier[get_api_keys] (
identifier[limit] = literal[int] ,
identifier[nameQuery]... | def remove_api_key(self, api_id, stage_name):
"""
Remove a generated API key for api_id and stage_name
"""
response = self.apigateway_client.get_api_keys(limit=1, nameQuery='{}_{}'.format(stage_name, api_id))
for api_key in response.get('items'):
self.apigateway_client.delete_api_key... |
def dpss(N, NW=None, k=None):
r"""Discrete prolate spheroidal (Slepian) sequences
Calculation of the Discrete Prolate Spheroidal Sequences also known as the
slepian sequences, and the corresponding eigenvalues.
:param int N: desired window length
:param float NW: The time half bandwidth parameter ... | def function[dpss, parameter[N, NW, k]]:
constant[Discrete prolate spheroidal (Slepian) sequences
Calculation of the Discrete Prolate Spheroidal Sequences also known as the
slepian sequences, and the corresponding eigenvalues.
:param int N: desired window length
:param float NW: The time half ... | keyword[def] identifier[dpss] ( identifier[N] , identifier[NW] = keyword[None] , identifier[k] = keyword[None] ):
literal[string]
keyword[assert] identifier[NW] < identifier[N] / literal[int] , literal[string] . identifier[format] ( identifier[NW] , identifier[N] )
keyword[if] identifier[k] keyword... | def dpss(N, NW=None, k=None):
"""Discrete prolate spheroidal (Slepian) sequences
Calculation of the Discrete Prolate Spheroidal Sequences also known as the
slepian sequences, and the corresponding eigenvalues.
:param int N: desired window length
:param float NW: The time half bandwidth parameter (... |
def create_dns(self):
"""Create DNS for the defined app and environment."""
utils.banner("Creating DNS")
elb_subnet = self.configs[self.env]['elb']['subnet_purpose']
regions = self.configs[self.env]['regions']
failover = self.configs[self.env]['dns']['failover_dns']
prima... | def function[create_dns, parameter[self]]:
constant[Create DNS for the defined app and environment.]
call[name[utils].banner, parameter[constant[Creating DNS]]]
variable[elb_subnet] assign[=] call[call[call[name[self].configs][name[self].env]][constant[elb]]][constant[subnet_purpose]]
va... | keyword[def] identifier[create_dns] ( identifier[self] ):
literal[string]
identifier[utils] . identifier[banner] ( literal[string] )
identifier[elb_subnet] = identifier[self] . identifier[configs] [ identifier[self] . identifier[env] ][ literal[string] ][ literal[string] ]
identif... | def create_dns(self):
"""Create DNS for the defined app and environment."""
utils.banner('Creating DNS')
elb_subnet = self.configs[self.env]['elb']['subnet_purpose']
regions = self.configs[self.env]['regions']
failover = self.configs[self.env]['dns']['failover_dns']
primary_region = self.configs... |
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
# Download images and annotations that come in separate archives.
# Note, that the extension of archives is .tar.gz even though the actual
# archives format is uncompressed tar.
dl_paths = dl_manager.download_and_extract({
... | def function[_split_generators, parameter[self, dl_manager]]:
constant[Returns SplitGenerators.]
variable[dl_paths] assign[=] call[name[dl_manager].download_and_extract, parameter[dictionary[[<ast.Constant object at 0x7da1b2006f80>, <ast.Constant object at 0x7da1b20060b0>, <ast.Constant object at 0x7da1... | keyword[def] identifier[_split_generators] ( identifier[self] , identifier[dl_manager] ):
literal[string]
identifier[dl_paths] = identifier[dl_manager] . identifier[download_and_extract] ({
literal[string] : identifier[tfds] . identifier[download] . identifier[Resource] (
identifie... | def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
# Download images and annotations that come in separate archives.
# Note, that the extension of archives is .tar.gz even though the actual
# archives format is uncompressed tar.
dl_paths = dl_manager.download_and_extract({'image... |
def up(self):
''' Bring up the bridge interface. Equivalent to ifconfig [iface] up. '''
# Get existing device flags
ifreq = struct.pack('16sh', self.name, 0)
flags = struct.unpack('16sh', fcntl.ioctl(sockfd, SIOCGIFFLAGS, ifreq))[1]
# Set new flags
flags = flags | IFF_U... | def function[up, parameter[self]]:
constant[ Bring up the bridge interface. Equivalent to ifconfig [iface] up. ]
variable[ifreq] assign[=] call[name[struct].pack, parameter[constant[16sh], name[self].name, constant[0]]]
variable[flags] assign[=] call[call[name[struct].unpack, parameter[constant[... | keyword[def] identifier[up] ( identifier[self] ):
literal[string]
identifier[ifreq] = identifier[struct] . identifier[pack] ( literal[string] , identifier[self] . identifier[name] , literal[int] )
identifier[flags] = identifier[struct] . identifier[unpack] ( literal[string] , ide... | def up(self):
""" Bring up the bridge interface. Equivalent to ifconfig [iface] up. """
# Get existing device flags
ifreq = struct.pack('16sh', self.name, 0)
flags = struct.unpack('16sh', fcntl.ioctl(sockfd, SIOCGIFFLAGS, ifreq))[1]
# Set new flags
flags = flags | IFF_UP
ifreq = struct.pack(... |
def bind_to_channel(self):
"""
Binds (subscribes) users private exchange to channel exchange
Automatically called at creation of subscription record.
"""
if self.channel.code_name != self.user.prv_exchange:
channel = self._connect_mq()
channel.exchange_bin... | def function[bind_to_channel, parameter[self]]:
constant[
Binds (subscribes) users private exchange to channel exchange
Automatically called at creation of subscription record.
]
if compare[name[self].channel.code_name not_equal[!=] name[self].user.prv_exchange] begin[:]
... | keyword[def] identifier[bind_to_channel] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[channel] . identifier[code_name] != identifier[self] . identifier[user] . identifier[prv_exchange] :
identifier[channel] = identifier[self] . identifier[_connect_mq... | def bind_to_channel(self):
"""
Binds (subscribes) users private exchange to channel exchange
Automatically called at creation of subscription record.
"""
if self.channel.code_name != self.user.prv_exchange:
channel = self._connect_mq()
channel.exchange_bind(source=self.ch... |
def set_reverb(self, roomsize=-1.0, damping=-1.0, width=-1.0, level=-1.0):
"""
roomsize Reverb room size value (0.0-1.2)
damping Reverb damping value (0.0-1.0)
width Reverb width value (0.0-100.0)
level Reverb level value (0.0-1.0)
"""
... | def function[set_reverb, parameter[self, roomsize, damping, width, level]]:
constant[
roomsize Reverb room size value (0.0-1.2)
damping Reverb damping value (0.0-1.0)
width Reverb width value (0.0-100.0)
level Reverb level value (0.0-1.0)
... | keyword[def] identifier[set_reverb] ( identifier[self] , identifier[roomsize] =- literal[int] , identifier[damping] =- literal[int] , identifier[width] =- literal[int] , identifier[level] =- literal[int] ):
literal[string]
identifier[set] = literal[int]
keyword[if] identifier[roomsize] >... | def set_reverb(self, roomsize=-1.0, damping=-1.0, width=-1.0, level=-1.0):
"""
roomsize Reverb room size value (0.0-1.2)
damping Reverb damping value (0.0-1.0)
width Reverb width value (0.0-100.0)
level Reverb level value (0.0-1.0)
"""
se... |
def static(self):
"""
Configures the server to use a static IP.
"""
fn = self.render_to_file('ip/ip_interfaces_static.template')
r = self.local_renderer
r.put(local_path=fn, remote_path=r.env.interfaces_fn, use_sudo=True) | def function[static, parameter[self]]:
constant[
Configures the server to use a static IP.
]
variable[fn] assign[=] call[name[self].render_to_file, parameter[constant[ip/ip_interfaces_static.template]]]
variable[r] assign[=] name[self].local_renderer
call[name[r].put, par... | keyword[def] identifier[static] ( identifier[self] ):
literal[string]
identifier[fn] = identifier[self] . identifier[render_to_file] ( literal[string] )
identifier[r] = identifier[self] . identifier[local_renderer]
identifier[r] . identifier[put] ( identifier[local_path] = identi... | def static(self):
"""
Configures the server to use a static IP.
"""
fn = self.render_to_file('ip/ip_interfaces_static.template')
r = self.local_renderer
r.put(local_path=fn, remote_path=r.env.interfaces_fn, use_sudo=True) |
def compare_states(self, sl, sr):
"""
Compares two states for similarity.
"""
joint_solver = claripy.Solver()
# make sure the canonicalized constraints are the same
n_map, n_counter, n_canon_constraint = claripy.And(*sr.solver.constraints).canonicalize() #pylint:disable=... | def function[compare_states, parameter[self, sl, sr]]:
constant[
Compares two states for similarity.
]
variable[joint_solver] assign[=] call[name[claripy].Solver, parameter[]]
<ast.Tuple object at 0x7da20c76d6c0> assign[=] call[call[name[claripy].And, parameter[<ast.Starred objec... | keyword[def] identifier[compare_states] ( identifier[self] , identifier[sl] , identifier[sr] ):
literal[string]
identifier[joint_solver] = identifier[claripy] . identifier[Solver] ()
identifier[n_map] , identifier[n_counter] , identifier[n_canon_constraint] = identifier[claripy] ... | def compare_states(self, sl, sr):
"""
Compares two states for similarity.
"""
joint_solver = claripy.Solver()
# make sure the canonicalized constraints are the same
(n_map, n_counter, n_canon_constraint) = claripy.And(*sr.solver.constraints).canonicalize() #pylint:disable=no-member
... |
def show_grid(data_frame,
show_toolbar=None,
precision=None,
grid_options=None,
column_options=None,
column_definitions=None,
row_edit_callback=None):
"""
Renders a DataFrame or Series as an interactive qgrid, represented by
... | def function[show_grid, parameter[data_frame, show_toolbar, precision, grid_options, column_options, column_definitions, row_edit_callback]]:
constant[
Renders a DataFrame or Series as an interactive qgrid, represented by
an instance of the ``QgridWidget`` class. The ``QgridWidget`` instance
is con... | keyword[def] identifier[show_grid] ( identifier[data_frame] ,
identifier[show_toolbar] = keyword[None] ,
identifier[precision] = keyword[None] ,
identifier[grid_options] = keyword[None] ,
identifier[column_options] = keyword[None] ,
identifier[column_definitions] = keyword[None] ,
identifier[row_edit_callback] ... | def show_grid(data_frame, show_toolbar=None, precision=None, grid_options=None, column_options=None, column_definitions=None, row_edit_callback=None):
"""
Renders a DataFrame or Series as an interactive qgrid, represented by
an instance of the ``QgridWidget`` class. The ``QgridWidget`` instance
is cons... |
def _make_token_request(session, token_request_data):
"""Make OAuth token request.
Raises GoogleAuthError if authentication fails.
Returns dict response.
"""
try:
r = session.post(OAUTH2_TOKEN_REQUEST_URL, data=token_request_data)
r.raise_for_status()
except requests.RequestExc... | def function[_make_token_request, parameter[session, token_request_data]]:
constant[Make OAuth token request.
Raises GoogleAuthError if authentication fails.
Returns dict response.
]
<ast.Try object at 0x7da20c991ab0> | keyword[def] identifier[_make_token_request] ( identifier[session] , identifier[token_request_data] ):
literal[string]
keyword[try] :
identifier[r] = identifier[session] . identifier[post] ( identifier[OAUTH2_TOKEN_REQUEST_URL] , identifier[data] = identifier[token_request_data] )
identif... | def _make_token_request(session, token_request_data):
"""Make OAuth token request.
Raises GoogleAuthError if authentication fails.
Returns dict response.
"""
try:
r = session.post(OAUTH2_TOKEN_REQUEST_URL, data=token_request_data)
r.raise_for_status() # depends on [control=['try']... |
def validate_email_with_regex(email_address):
"""
Note that this will only filter out syntax mistakes in emailaddresses.
If a human would think it is probably a valid email, it will most likely pass.
However, it could still very well be that the actual emailaddress has simply
not be claimed by anyon... | def function[validate_email_with_regex, parameter[email_address]]:
constant[
Note that this will only filter out syntax mistakes in emailaddresses.
If a human would think it is probably a valid email, it will most likely pass.
However, it could still very well be that the actual emailaddress has sim... | keyword[def] identifier[validate_email_with_regex] ( identifier[email_address] ):
literal[string]
keyword[if] keyword[not] identifier[re] . identifier[match] ( identifier[VALID_ADDRESS_REGEXP] , identifier[email_address] ):
identifier[emsg] = literal[string] . identifier[format] (
ident... | def validate_email_with_regex(email_address):
"""
Note that this will only filter out syntax mistakes in emailaddresses.
If a human would think it is probably a valid email, it will most likely pass.
However, it could still very well be that the actual emailaddress has simply
not be claimed by anyon... |
def Rconverter(Robj, dataframe=False):
"""
Convert an object in R's namespace to one suitable
for ipython's namespace.
For a data.frame, it tries to return a structured array.
It first checks for colnames, then names.
If all are NULL, it returns np.asarray(Robj), else
it tries to construct ... | def function[Rconverter, parameter[Robj, dataframe]]:
constant[
Convert an object in R's namespace to one suitable
for ipython's namespace.
For a data.frame, it tries to return a structured array.
It first checks for colnames, then names.
If all are NULL, it returns np.asarray(Robj), else
... | keyword[def] identifier[Rconverter] ( identifier[Robj] , identifier[dataframe] = keyword[False] ):
literal[string]
identifier[is_data_frame] = identifier[ro] . identifier[r] ( literal[string] )
identifier[colnames] = identifier[ro] . identifier[r] ( literal[string] )
identifier[rownames] = identi... | def Rconverter(Robj, dataframe=False):
"""
Convert an object in R's namespace to one suitable
for ipython's namespace.
For a data.frame, it tries to return a structured array.
It first checks for colnames, then names.
If all are NULL, it returns np.asarray(Robj), else
it tries to construct ... |
def arm(self, value):
"""Arm or disarm system."""
if value:
return api.request_system_arm(self.blink, self.network_id)
return api.request_system_disarm(self.blink, self.network_id) | def function[arm, parameter[self, value]]:
constant[Arm or disarm system.]
if name[value] begin[:]
return[call[name[api].request_system_arm, parameter[name[self].blink, name[self].network_id]]]
return[call[name[api].request_system_disarm, parameter[name[self].blink, name[self].network_id]]] | keyword[def] identifier[arm] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[value] :
keyword[return] identifier[api] . identifier[request_system_arm] ( identifier[self] . identifier[blink] , identifier[self] . identifier[network_id] )
keywo... | def arm(self, value):
"""Arm or disarm system."""
if value:
return api.request_system_arm(self.blink, self.network_id) # depends on [control=['if'], data=[]]
return api.request_system_disarm(self.blink, self.network_id) |
def checkFinite(value, name='value'):
"""Check that value is a finite number.
If it is, return it. If not, raise GraphError describing the
problem, using name in the error message.
"""
if math.isnan(value):
raise GraphError('Encountered NaN %s' % (name,))
eli... | def function[checkFinite, parameter[value, name]]:
constant[Check that value is a finite number.
If it is, return it. If not, raise GraphError describing the
problem, using name in the error message.
]
if call[name[math].isnan, parameter[name[value]]] begin[:]
<ast.Raise... | keyword[def] identifier[checkFinite] ( identifier[value] , identifier[name] = literal[string] ):
literal[string]
keyword[if] identifier[math] . identifier[isnan] ( identifier[value] ):
keyword[raise] identifier[GraphError] ( literal[string] %( identifier[name] ,))
keyword[el... | def checkFinite(value, name='value'):
"""Check that value is a finite number.
If it is, return it. If not, raise GraphError describing the
problem, using name in the error message.
"""
if math.isnan(value):
raise GraphError('Encountered NaN %s' % (name,)) # depends on [control=... |
def write(self, data):
"""
write data on the OUT endpoint associated to the HID interface
"""
for _ in range(64 - len(data)):
data.append(0)
#logging.debug("send: %s", data)
self.report.send(bytearray([0]) + data)
return | def function[write, parameter[self, data]]:
constant[
write data on the OUT endpoint associated to the HID interface
]
for taget[name[_]] in starred[call[name[range], parameter[binary_operation[constant[64] - call[name[len], parameter[name[data]]]]]]] begin[:]
call[name[d... | keyword[def] identifier[write] ( identifier[self] , identifier[data] ):
literal[string]
keyword[for] identifier[_] keyword[in] identifier[range] ( literal[int] - identifier[len] ( identifier[data] )):
identifier[data] . identifier[append] ( literal[int] )
ident... | def write(self, data):
"""
write data on the OUT endpoint associated to the HID interface
"""
for _ in range(64 - len(data)):
data.append(0) # depends on [control=['for'], data=[]]
#logging.debug("send: %s", data)
self.report.send(bytearray([0]) + data)
return |
def _write_branch_and_tag_to_meta_yaml(self):
"""
Write branch and tag to meta.yaml by editing in place
"""
## set the branch to pull source from
with open(self.meta_yaml.replace("meta", "template"), 'r') as infile:
dat = infile.read()
newdat = dat.format(... | def function[_write_branch_and_tag_to_meta_yaml, parameter[self]]:
constant[
Write branch and tag to meta.yaml by editing in place
]
with call[name[open], parameter[call[name[self].meta_yaml.replace, parameter[constant[meta], constant[template]]], constant[r]]] begin[:]
v... | keyword[def] identifier[_write_branch_and_tag_to_meta_yaml] ( identifier[self] ):
literal[string]
keyword[with] identifier[open] ( identifier[self] . identifier[meta_yaml] . identifier[replace] ( literal[string] , literal[string] ), literal[string] ) keyword[as] identifier[infile] :
... | def _write_branch_and_tag_to_meta_yaml(self):
"""
Write branch and tag to meta.yaml by editing in place
"""
## set the branch to pull source from
with open(self.meta_yaml.replace('meta', 'template'), 'r') as infile:
dat = infile.read()
newdat = dat.format(**{'tag': self.tag, ... |
def get_sequence_properties(self, clean_seq=False, representatives_only=True):
"""Run Biopython ProteinAnalysis and EMBOSS pepstats to summarize basic statistics of all protein sequences.
Results are stored in the protein's respective SeqProp objects at ``.annotations``
Args:
repres... | def function[get_sequence_properties, parameter[self, clean_seq, representatives_only]]:
constant[Run Biopython ProteinAnalysis and EMBOSS pepstats to summarize basic statistics of all protein sequences.
Results are stored in the protein's respective SeqProp objects at ``.annotations``
Args:
... | keyword[def] identifier[get_sequence_properties] ( identifier[self] , identifier[clean_seq] = keyword[False] , identifier[representatives_only] = keyword[True] ):
literal[string]
keyword[for] identifier[g] keyword[in] identifier[tqdm] ( identifier[self] . identifier[genes] ):
identi... | def get_sequence_properties(self, clean_seq=False, representatives_only=True):
"""Run Biopython ProteinAnalysis and EMBOSS pepstats to summarize basic statistics of all protein sequences.
Results are stored in the protein's respective SeqProp objects at ``.annotations``
Args:
representa... |
def del_restriction(self, command, user, event_types):
"""
Removes restriction for given `command`.
:param command: command on which the restriction should be removed.
:type command: str
:param user: username for which restriction should be removed.
:type user: str
... | def function[del_restriction, parameter[self, command, user, event_types]]:
constant[
Removes restriction for given `command`.
:param command: command on which the restriction should be removed.
:type command: str
:param user: username for which restriction should be removed.
... | keyword[def] identifier[del_restriction] ( identifier[self] , identifier[command] , identifier[user] , identifier[event_types] ):
literal[string]
keyword[if] identifier[user] . identifier[lower] () keyword[in] identifier[self] . identifier[commands_rights] [ identifier[command] ]:
ke... | def del_restriction(self, command, user, event_types):
"""
Removes restriction for given `command`.
:param command: command on which the restriction should be removed.
:type command: str
:param user: username for which restriction should be removed.
:type user: str
:... |
def status(context):
"""See which files have changed, checked in, and uploaded"""
context.obj.find_repo_type()
context.obj.call([context.obj.vc_name, 'status']) | def function[status, parameter[context]]:
constant[See which files have changed, checked in, and uploaded]
call[name[context].obj.find_repo_type, parameter[]]
call[name[context].obj.call, parameter[list[[<ast.Attribute object at 0x7da18f723850>, <ast.Constant object at 0x7da18f7206d0>]]]] | keyword[def] identifier[status] ( identifier[context] ):
literal[string]
identifier[context] . identifier[obj] . identifier[find_repo_type] ()
identifier[context] . identifier[obj] . identifier[call] ([ identifier[context] . identifier[obj] . identifier[vc_name] , literal[string] ]) | def status(context):
"""See which files have changed, checked in, and uploaded"""
context.obj.find_repo_type()
context.obj.call([context.obj.vc_name, 'status']) |
def gen_tx(self):
"""Generate a :class:`Transaction
<stellar_base.transaction.Transaction>` object from the list of
operations contained within this object.
:return: A transaction representing all of the operations that have
been appended to this builder.
:rtype: :cl... | def function[gen_tx, parameter[self]]:
constant[Generate a :class:`Transaction
<stellar_base.transaction.Transaction>` object from the list of
operations contained within this object.
:return: A transaction representing all of the operations that have
been appended to this b... | keyword[def] identifier[gen_tx] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[address] :
keyword[raise] identifier[StellarAddressInvalidError] ( literal[string] )
keyword[if] identifier[self] . identifier[sequence] keyword[is... | def gen_tx(self):
"""Generate a :class:`Transaction
<stellar_base.transaction.Transaction>` object from the list of
operations contained within this object.
:return: A transaction representing all of the operations that have
been appended to this builder.
:rtype: :class:... |
def _rest_patch(self, suburi, request_headers, request_body):
"""REST PATCH operation.
HTTP response codes could be 500, 404, 202 etc.
"""
return self._rest_op('PATCH', suburi, request_headers, request_body) | def function[_rest_patch, parameter[self, suburi, request_headers, request_body]]:
constant[REST PATCH operation.
HTTP response codes could be 500, 404, 202 etc.
]
return[call[name[self]._rest_op, parameter[constant[PATCH], name[suburi], name[request_headers], name[request_body]]]] | keyword[def] identifier[_rest_patch] ( identifier[self] , identifier[suburi] , identifier[request_headers] , identifier[request_body] ):
literal[string]
keyword[return] identifier[self] . identifier[_rest_op] ( literal[string] , identifier[suburi] , identifier[request_headers] , identifier[request... | def _rest_patch(self, suburi, request_headers, request_body):
"""REST PATCH operation.
HTTP response codes could be 500, 404, 202 etc.
"""
return self._rest_op('PATCH', suburi, request_headers, request_body) |
def to_capabilities(self):
"""
Creates a capabilities with all the options that have been set and
returns a dictionary with everything
"""
caps = self._caps
browser_options = {}
if self.binary_location:
browser_options["binary"] = self.binary_location... | def function[to_capabilities, parameter[self]]:
constant[
Creates a capabilities with all the options that have been set and
returns a dictionary with everything
]
variable[caps] assign[=] name[self]._caps
variable[browser_options] assign[=] dictionary[[], []]
if ... | keyword[def] identifier[to_capabilities] ( identifier[self] ):
literal[string]
identifier[caps] = identifier[self] . identifier[_caps]
identifier[browser_options] ={}
keyword[if] identifier[self] . identifier[binary_location] :
identifier[browser_options] [ literal... | def to_capabilities(self):
"""
Creates a capabilities with all the options that have been set and
returns a dictionary with everything
"""
caps = self._caps
browser_options = {}
if self.binary_location:
browser_options['binary'] = self.binary_location # depends on [contr... |
def get_previous_version(self):
"""Query GitHub releases to find the previous production release"""
gh = self.get_github_api()
repo = gh.repository(self.repo_owner, self.repo_name)
most_recent = None
for release in repo.releases():
# Return the second release that mat... | def function[get_previous_version, parameter[self]]:
constant[Query GitHub releases to find the previous production release]
variable[gh] assign[=] call[name[self].get_github_api, parameter[]]
variable[repo] assign[=] call[name[gh].repository, parameter[name[self].repo_owner, name[self].repo_nam... | keyword[def] identifier[get_previous_version] ( identifier[self] ):
literal[string]
identifier[gh] = identifier[self] . identifier[get_github_api] ()
identifier[repo] = identifier[gh] . identifier[repository] ( identifier[self] . identifier[repo_owner] , identifier[self] . identifier[repo_... | def get_previous_version(self):
"""Query GitHub releases to find the previous production release"""
gh = self.get_github_api()
repo = gh.repository(self.repo_owner, self.repo_name)
most_recent = None
for release in repo.releases():
# Return the second release that matches the release prefix
... |
def logical_chassis_fwdl_status_output_cluster_fwdl_entries_fwdl_entries_date_and_time_info(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
logical_chassis_fwdl_status = ET.Element("logical_chassis_fwdl_status")
config = logical_chassis_fwdl_status
... | def function[logical_chassis_fwdl_status_output_cluster_fwdl_entries_fwdl_entries_date_and_time_info, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[logical_chassis_fwdl_status] assign[=] call[name[... | keyword[def] identifier[logical_chassis_fwdl_status_output_cluster_fwdl_entries_fwdl_entries_date_and_time_info] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[logical_chassis_fwdl_status... | def logical_chassis_fwdl_status_output_cluster_fwdl_entries_fwdl_entries_date_and_time_info(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
logical_chassis_fwdl_status = ET.Element('logical_chassis_fwdl_status')
config = logical_chassis_fwdl_status
output = ET.SubEl... |
def aggregation_summary(aggregate_hazard, aggregation):
"""Compute the summary from the aggregate hazard to the analysis layer.
Source layer :
| haz_id | haz_class | aggr_id | aggr_name | total_feature |
Target layer :
| aggr_id | aggr_name |
Output layer :
| aggr_id | aggr_name | count o... | def function[aggregation_summary, parameter[aggregate_hazard, aggregation]]:
constant[Compute the summary from the aggregate hazard to the analysis layer.
Source layer :
| haz_id | haz_class | aggr_id | aggr_name | total_feature |
Target layer :
| aggr_id | aggr_name |
Output layer :
... | keyword[def] identifier[aggregation_summary] ( identifier[aggregate_hazard] , identifier[aggregation] ):
literal[string]
identifier[source_fields] = identifier[aggregate_hazard] . identifier[keywords] [ literal[string] ]
identifier[target_fields] = identifier[aggregation] . identifier[keywords] [ lite... | def aggregation_summary(aggregate_hazard, aggregation):
"""Compute the summary from the aggregate hazard to the analysis layer.
Source layer :
| haz_id | haz_class | aggr_id | aggr_name | total_feature |
Target layer :
| aggr_id | aggr_name |
Output layer :
| aggr_id | aggr_name | count o... |
def _addRawResult(self, resid, values={}, override=False):
""" Structure of values dict (dict entry for each analysis/field):
{'ALC': {'ALC': '13.55',
'DefaultResult': 'ALC',
'Remarks': ''},
'CO2': {'CO2': '0.66',
'DefaultR... | def function[_addRawResult, parameter[self, resid, values, override]]:
constant[ Structure of values dict (dict entry for each analysis/field):
{'ALC': {'ALC': '13.55',
'DefaultResult': 'ALC',
'Remarks': ''},
'CO2': {'CO2': '0.66',
... | keyword[def] identifier[_addRawResult] ( identifier[self] , identifier[resid] , identifier[values] ={}, identifier[override] = keyword[False] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[values] keyword[and] literal[string] keyword[in] identifier[values] :
... | def _addRawResult(self, resid, values={}, override=False):
""" Structure of values dict (dict entry for each analysis/field):
{'ALC': {'ALC': '13.55',
'DefaultResult': 'ALC',
'Remarks': ''},
'CO2': {'CO2': '0.66',
'DefaultResul... |
def pin_assets(self, file_or_dir_path: Path) -> List[Dict[str, str]]:
"""
Return a dict containing the IPFS hash, file name, and size of a file.
"""
if file_or_dir_path.is_dir():
asset_data = [dummy_ipfs_pin(path) for path in file_or_dir_path.glob("*")]
elif file_or_d... | def function[pin_assets, parameter[self, file_or_dir_path]]:
constant[
Return a dict containing the IPFS hash, file name, and size of a file.
]
if call[name[file_or_dir_path].is_dir, parameter[]] begin[:]
variable[asset_data] assign[=] <ast.ListComp object at 0x7da18f58d4... | keyword[def] identifier[pin_assets] ( identifier[self] , identifier[file_or_dir_path] : identifier[Path] )-> identifier[List] [ identifier[Dict] [ identifier[str] , identifier[str] ]]:
literal[string]
keyword[if] identifier[file_or_dir_path] . identifier[is_dir] ():
identifier[asset_d... | def pin_assets(self, file_or_dir_path: Path) -> List[Dict[str, str]]:
"""
Return a dict containing the IPFS hash, file name, and size of a file.
"""
if file_or_dir_path.is_dir():
asset_data = [dummy_ipfs_pin(path) for path in file_or_dir_path.glob('*')] # depends on [control=['if'], dat... |
def add_service_subnet(self, context_id, subnet_id):
"""Adds a service subnet to a tunnel context.
:param int context_id: The id-value representing the context instance.
:param int subnet_id: The id-value representing the service subnet.
:return bool: True if service subnet addition was... | def function[add_service_subnet, parameter[self, context_id, subnet_id]]:
constant[Adds a service subnet to a tunnel context.
:param int context_id: The id-value representing the context instance.
:param int subnet_id: The id-value representing the service subnet.
:return bool: True if ... | keyword[def] identifier[add_service_subnet] ( identifier[self] , identifier[context_id] , identifier[subnet_id] ):
literal[string]
keyword[return] identifier[self] . identifier[context] . identifier[addServiceSubnetToNetworkTunnel] ( identifier[subnet_id] ,
identifier[id] = identifier[con... | def add_service_subnet(self, context_id, subnet_id):
"""Adds a service subnet to a tunnel context.
:param int context_id: The id-value representing the context instance.
:param int subnet_id: The id-value representing the service subnet.
:return bool: True if service subnet addition was suc... |
def evaluate(self, filename):
"""Runs the lemmatize function over the contents of the file, counting the proportion of unfound lemmas."""
with open(filename, 'r') as infile:
lines = infile.read().splitlines()
lemma_count = 0
token_count = 0
for line in lines:
line = re.sub(r'[.,!?:;0-9]',... | def function[evaluate, parameter[self, filename]]:
constant[Runs the lemmatize function over the contents of the file, counting the proportion of unfound lemmas.]
with call[name[open], parameter[name[filename], constant[r]]] begin[:]
variable[lines] assign[=] call[call[name[infile].read,... | keyword[def] identifier[evaluate] ( identifier[self] , identifier[filename] ):
literal[string]
keyword[with] identifier[open] ( identifier[filename] , literal[string] ) keyword[as] identifier[infile] :
identifier[lines] = identifier[infile] . identifier[read] (). identifier[splitlines] ()
ident... | def evaluate(self, filename):
"""Runs the lemmatize function over the contents of the file, counting the proportion of unfound lemmas."""
with open(filename, 'r') as infile:
lines = infile.read().splitlines()
lemma_count = 0
token_count = 0
for line in lines:
line = r... |
def OnApprove(self, event):
"""File approve event handler"""
if not self.main_window.safe_mode:
return
msg = _(u"You are going to approve and trust a file that\n"
u"you have not created yourself.\n"
u"After proceeding, the file is executed.\n \n"
... | def function[OnApprove, parameter[self, event]]:
constant[File approve event handler]
if <ast.UnaryOp object at 0x7da204620040> begin[:]
return[None]
variable[msg] assign[=] call[name[_], parameter[constant[You are going to approve and trust a file that
you have not created yourself.
Aft... | keyword[def] identifier[OnApprove] ( identifier[self] , identifier[event] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[main_window] . identifier[safe_mode] :
keyword[return]
identifier[msg] = identifier[_] ( literal[string]
literal[s... | def OnApprove(self, event):
"""File approve event handler"""
if not self.main_window.safe_mode:
return # depends on [control=['if'], data=[]]
msg = _(u'You are going to approve and trust a file that\nyou have not created yourself.\nAfter proceeding, the file is executed.\n \nIt may harm your system... |
def get_trail_ids(cls, event, mode):
"""extract resources ids from a cloud trail event."""
resource_ids = ()
event_name = event['detail']['eventName']
event_source = event['detail']['eventSource']
for e in mode.get('events', []):
if not isinstance(e, dict):
... | def function[get_trail_ids, parameter[cls, event, mode]]:
constant[extract resources ids from a cloud trail event.]
variable[resource_ids] assign[=] tuple[[]]
variable[event_name] assign[=] call[call[name[event]][constant[detail]]][constant[eventName]]
variable[event_source] assign[=] ca... | keyword[def] identifier[get_trail_ids] ( identifier[cls] , identifier[event] , identifier[mode] ):
literal[string]
identifier[resource_ids] =()
identifier[event_name] = identifier[event] [ literal[string] ][ literal[string] ]
identifier[event_source] = identifier[event] [ literal[... | def get_trail_ids(cls, event, mode):
"""extract resources ids from a cloud trail event."""
resource_ids = ()
event_name = event['detail']['eventName']
event_source = event['detail']['eventSource']
for e in mode.get('events', []):
if not isinstance(e, dict):
# Check if we have a s... |
def _locateAll_opencv(needleImage, haystackImage, grayscale=None, limit=10000, region=None, step=1,
confidence=0.999):
""" faster but more memory-intensive than pure python
step 2 skips every other row and column = ~3x faster but prone to miss;
to compensate, the algorithm ... | def function[_locateAll_opencv, parameter[needleImage, haystackImage, grayscale, limit, region, step, confidence]]:
constant[ faster but more memory-intensive than pure python
step 2 skips every other row and column = ~3x faster but prone to miss;
to compensate, the algorithm automatically r... | keyword[def] identifier[_locateAll_opencv] ( identifier[needleImage] , identifier[haystackImage] , identifier[grayscale] = keyword[None] , identifier[limit] = literal[int] , identifier[region] = keyword[None] , identifier[step] = literal[int] ,
identifier[confidence] = literal[int] ):
literal[string]
keyw... | def _locateAll_opencv(needleImage, haystackImage, grayscale=None, limit=10000, region=None, step=1, confidence=0.999):
""" faster but more memory-intensive than pure python
step 2 skips every other row and column = ~3x faster but prone to miss;
to compensate, the algorithm automatically reduces ... |
def iter_sprite_scripts(scratch):
"""A generator for all scripts contained in a scratch file.
yields stage scripts first, then scripts for each sprite
"""
for script in scratch.stage.scripts:
if not isinstance(script, kurt.Comment):
yield ('Stage', script)
... | def function[iter_sprite_scripts, parameter[scratch]]:
constant[A generator for all scripts contained in a scratch file.
yields stage scripts first, then scripts for each sprite
]
for taget[name[script]] in starred[name[scratch].stage.scripts] begin[:]
if <ast.UnaryOp o... | keyword[def] identifier[iter_sprite_scripts] ( identifier[scratch] ):
literal[string]
keyword[for] identifier[script] keyword[in] identifier[scratch] . identifier[stage] . identifier[scripts] :
keyword[if] keyword[not] identifier[isinstance] ( identifier[script] , identifier[kurt]... | def iter_sprite_scripts(scratch):
"""A generator for all scripts contained in a scratch file.
yields stage scripts first, then scripts for each sprite
"""
for script in scratch.stage.scripts:
if not isinstance(script, kurt.Comment):
yield ('Stage', script) # depends on [co... |
def spherical_to_cartesian(r,theta,phi):
"""
Simple conversion of spherical to cartesian coordinates
Args:
r,theta,phi = scalar spherical coordinates
Returns:
x,y,z = scalar cartesian coordinates
"""
x = r * np.sin(phi) * np.cos(theta)
y = r * np.sin(phi) * np.sin(t... | def function[spherical_to_cartesian, parameter[r, theta, phi]]:
constant[
Simple conversion of spherical to cartesian coordinates
Args:
r,theta,phi = scalar spherical coordinates
Returns:
x,y,z = scalar cartesian coordinates
]
variable[x] assign[=] binary_operat... | keyword[def] identifier[spherical_to_cartesian] ( identifier[r] , identifier[theta] , identifier[phi] ):
literal[string]
identifier[x] = identifier[r] * identifier[np] . identifier[sin] ( identifier[phi] )* identifier[np] . identifier[cos] ( identifier[theta] )
identifier[y] = identifier[r] * identifi... | def spherical_to_cartesian(r, theta, phi):
"""
Simple conversion of spherical to cartesian coordinates
Args:
r,theta,phi = scalar spherical coordinates
Returns:
x,y,z = scalar cartesian coordinates
"""
x = r * np.sin(phi) * np.cos(theta)
y = r * np.sin(phi) * np.sin... |
def _ltu16(ins):
''' Compares & pops top 2 operands out of the stack, and checks
if the 1st operand < 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
16 bit unsigned version
'''
output = _16bit_oper(ins.quad[2], ins.quad[3])
output.append('or a')
output.append(... | def function[_ltu16, parameter[ins]]:
constant[ Compares & pops top 2 operands out of the stack, and checks
if the 1st operand < 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
16 bit unsigned version
]
variable[output] assign[=] call[name[_16bit_oper], paramet... | keyword[def] identifier[_ltu16] ( identifier[ins] ):
literal[string]
identifier[output] = identifier[_16bit_oper] ( identifier[ins] . identifier[quad] [ literal[int] ], identifier[ins] . identifier[quad] [ literal[int] ])
identifier[output] . identifier[append] ( literal[string] )
identifier[outp... | def _ltu16(ins):
""" Compares & pops top 2 operands out of the stack, and checks
if the 1st operand < 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
16 bit unsigned version
"""
output = _16bit_oper(ins.quad[2], ins.quad[3])
output.append('or a')
output.append(... |
def get_intersections_with_segments(self):
"""
Return a list of unordered intersection '(point, segment)' pairs,
where segments may contain 2 or more values.
"""
if Real is float:
return [
(p, [event.segment for event in event_set])
for... | def function[get_intersections_with_segments, parameter[self]]:
constant[
Return a list of unordered intersection '(point, segment)' pairs,
where segments may contain 2 or more values.
]
if compare[name[Real] is name[float]] begin[:]
return[<ast.ListComp object at 0x7da20... | keyword[def] identifier[get_intersections_with_segments] ( identifier[self] ):
literal[string]
keyword[if] identifier[Real] keyword[is] identifier[float] :
keyword[return] [
( identifier[p] ,[ identifier[event] . identifier[segment] keyword[for] identifier[event] keyw... | def get_intersections_with_segments(self):
"""
Return a list of unordered intersection '(point, segment)' pairs,
where segments may contain 2 or more values.
"""
if Real is float:
return [(p, [event.segment for event in event_set]) for (p, event_set) in self.intersections.items()... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.