code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _deserialize_from_store(profile):
"""
Takes data from the store and integrates into the application.
"""
# we first serialize to avoid deserialization merge conflicts
_serialize_into_store(profile)
fk_cache = {}
with transaction.atomic():
syncable_dict = _profile_models[profile]... | def function[_deserialize_from_store, parameter[profile]]:
constant[
Takes data from the store and integrates into the application.
]
call[name[_serialize_into_store], parameter[name[profile]]]
variable[fk_cache] assign[=] dictionary[[], []]
with call[name[transaction].atomic, pa... | keyword[def] identifier[_deserialize_from_store] ( identifier[profile] ):
literal[string]
identifier[_serialize_into_store] ( identifier[profile] )
identifier[fk_cache] ={}
keyword[with] identifier[transaction] . identifier[atomic] ():
identifier[syncable_dict] = identifier[_profi... | def _deserialize_from_store(profile):
"""
Takes data from the store and integrates into the application.
"""
# we first serialize to avoid deserialization merge conflicts
_serialize_into_store(profile)
fk_cache = {}
with transaction.atomic():
syncable_dict = _profile_models[profile]
... |
def rmtree(path):
"""Remove the given recursively.
:note: we use shutil rmtree but adjust its behaviour to see whether files that
couldn't be deleted are read-only. Windows will not remove them in that case"""
def onerror(func, path, exc_info):
# Is the error an access error ?
os.c... | def function[rmtree, parameter[path]]:
constant[Remove the given recursively.
:note: we use shutil rmtree but adjust its behaviour to see whether files that
couldn't be deleted are read-only. Windows will not remove them in that case]
def function[onerror, parameter[func, path, exc_info]]:
... | keyword[def] identifier[rmtree] ( identifier[path] ):
literal[string]
keyword[def] identifier[onerror] ( identifier[func] , identifier[path] , identifier[exc_info] ):
identifier[os] . identifier[chmod] ( identifier[path] , identifier[stat] . identifier[S_IWUSR] )
keyword[try] :
... | def rmtree(path):
"""Remove the given recursively.
:note: we use shutil rmtree but adjust its behaviour to see whether files that
couldn't be deleted are read-only. Windows will not remove them in that case"""
def onerror(func, path, exc_info):
# Is the error an access error ?
os.c... |
def get_module_class(self):
"""Return the module and class as a tuple of the given class in the
initializer.
:param reload: if ``True`` then reload the module before returning the
class
"""
pkg, cname = self.parse_module_class()
logger.debug(f'pkg: {pkg}, class:... | def function[get_module_class, parameter[self]]:
constant[Return the module and class as a tuple of the given class in the
initializer.
:param reload: if ``True`` then reload the module before returning the
class
]
<ast.Tuple object at 0x7da1b0f42770> assign[=] call[nam... | keyword[def] identifier[get_module_class] ( identifier[self] ):
literal[string]
identifier[pkg] , identifier[cname] = identifier[self] . identifier[parse_module_class] ()
identifier[logger] . identifier[debug] ( literal[string] )
identifier[pkg] = identifier[pkg] . identifier[spli... | def get_module_class(self):
"""Return the module and class as a tuple of the given class in the
initializer.
:param reload: if ``True`` then reload the module before returning the
class
"""
(pkg, cname) = self.parse_module_class()
logger.debug(f'pkg: {pkg}, class: {cname}')... |
def get_learning_rate(self, iter):
'''
Get learning rate with exponential decay based on current iteration.
Args:
iter (int): Current iteration (starting with 0).
Returns:
float: Learning rate
'''
lr = self.scheduler.get_learning_rate(iter)
... | def function[get_learning_rate, parameter[self, iter]]:
constant[
Get learning rate with exponential decay based on current iteration.
Args:
iter (int): Current iteration (starting with 0).
Returns:
float: Learning rate
]
variable[lr] assign[=] c... | keyword[def] identifier[get_learning_rate] ( identifier[self] , identifier[iter] ):
literal[string]
identifier[lr] = identifier[self] . identifier[scheduler] . identifier[get_learning_rate] ( identifier[iter] )
keyword[if] identifier[iter] < identifier[self] . identifier[warmup_iter] :
... | def get_learning_rate(self, iter):
"""
Get learning rate with exponential decay based on current iteration.
Args:
iter (int): Current iteration (starting with 0).
Returns:
float: Learning rate
"""
lr = self.scheduler.get_learning_rate(iter)
if iter <... |
def decode_body(cls, header, f):
"""Generates a `MqttSubscribe` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `subscribe`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Ra... | def function[decode_body, parameter[cls, header, f]]:
constant[Generates a `MqttSubscribe` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `subscribe`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with... | keyword[def] identifier[decode_body] ( identifier[cls] , identifier[header] , identifier[f] ):
literal[string]
keyword[assert] identifier[header] . identifier[packet_type] == identifier[MqttControlPacketType] . identifier[subscribe]
identifier[decoder] = identifier[mqtt_io] . identifier... | def decode_body(cls, header, f):
"""Generates a `MqttSubscribe` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `subscribe`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises... |
def _generate_splice(self, slice_ind):
'''
Creates a splice size version of the ZeroList
'''
step_size = slice_ind.step if slice_ind.step else 1
# Check for each of the four possible scenarios
if slice_ind.start != None:
if slice_ind.stop != None:
... | def function[_generate_splice, parameter[self, slice_ind]]:
constant[
Creates a splice size version of the ZeroList
]
variable[step_size] assign[=] <ast.IfExp object at 0x7da1b15f1cc0>
if compare[name[slice_ind].start not_equal[!=] constant[None]] begin[:]
if comp... | keyword[def] identifier[_generate_splice] ( identifier[self] , identifier[slice_ind] ):
literal[string]
identifier[step_size] = identifier[slice_ind] . identifier[step] keyword[if] identifier[slice_ind] . identifier[step] keyword[else] literal[int]
keyword[if] identifier[sli... | def _generate_splice(self, slice_ind):
"""
Creates a splice size version of the ZeroList
"""
step_size = slice_ind.step if slice_ind.step else 1
# Check for each of the four possible scenarios
if slice_ind.start != None:
if slice_ind.stop != None:
newListLen = (get_no... |
def register_config(self, cls, name):
"""
register a configuration class
:param cls:
:param name:
:return:
"""
self._configs.add(cls)
self._config_names.add(name) | def function[register_config, parameter[self, cls, name]]:
constant[
register a configuration class
:param cls:
:param name:
:return:
]
call[name[self]._configs.add, parameter[name[cls]]]
call[name[self]._config_names.add, parameter[name[name]]] | keyword[def] identifier[register_config] ( identifier[self] , identifier[cls] , identifier[name] ):
literal[string]
identifier[self] . identifier[_configs] . identifier[add] ( identifier[cls] )
identifier[self] . identifier[_config_names] . identifier[add] ( identifier[name] ) | def register_config(self, cls, name):
"""
register a configuration class
:param cls:
:param name:
:return:
"""
self._configs.add(cls)
self._config_names.add(name) |
def consumer(function):
"""Decorator that makes a generator function automatically advance to its
first yield point when initially called (PEP 342)."""
@wraps(function)
def wrapper(*args, **kwargs):
generator = function(*args, **kwargs)
next(generator)
return generator
return... | def function[consumer, parameter[function]]:
constant[Decorator that makes a generator function automatically advance to its
first yield point when initially called (PEP 342).]
def function[wrapper, parameter[]]:
variable[generator] assign[=] call[name[function], parameter[<ast.Starr... | keyword[def] identifier[consumer] ( identifier[function] ):
literal[string]
@ identifier[wraps] ( identifier[function] )
keyword[def] identifier[wrapper] (* identifier[args] ,** identifier[kwargs] ):
identifier[generator] = identifier[function] (* identifier[args] ,** identifier[kwargs] )
... | def consumer(function):
"""Decorator that makes a generator function automatically advance to its
first yield point when initially called (PEP 342)."""
@wraps(function)
def wrapper(*args, **kwargs):
generator = function(*args, **kwargs)
next(generator)
return generator
retur... |
def delete(self,pool_or_cursor):
".. warning:: pgmock doesn't support delete yet, so this isn't tested"
vals=self.pkey_vals()
whereclause=' and '.join('%s=%%s'%k for k in self.PKEY.split(','))
q='delete from %s where %s'%(self.TABLE,whereclause)
commit_or_execute(pool_or_cursor,q,vals) | def function[delete, parameter[self, pool_or_cursor]]:
constant[.. warning:: pgmock doesn't support delete yet, so this isn't tested]
variable[vals] assign[=] call[name[self].pkey_vals, parameter[]]
variable[whereclause] assign[=] call[constant[ and ].join, parameter[<ast.GeneratorExp object at ... | keyword[def] identifier[delete] ( identifier[self] , identifier[pool_or_cursor] ):
literal[string]
identifier[vals] = identifier[self] . identifier[pkey_vals] ()
identifier[whereclause] = literal[string] . identifier[join] ( literal[string] % identifier[k] keyword[for] identifier[k] keyword[in] ... | def delete(self, pool_or_cursor):
""".. warning:: pgmock doesn't support delete yet, so this isn't tested"""
vals = self.pkey_vals()
whereclause = ' and '.join(('%s=%%s' % k for k in self.PKEY.split(',')))
q = 'delete from %s where %s' % (self.TABLE, whereclause)
commit_or_execute(pool_or_cursor, q,... |
def join_field(path):
"""
RETURN field SEQUENCE AS STRING
"""
output = ".".join([f.replace(".", "\\.") for f in path if f != None])
return output if output else "." | def function[join_field, parameter[path]]:
constant[
RETURN field SEQUENCE AS STRING
]
variable[output] assign[=] call[constant[.].join, parameter[<ast.ListComp object at 0x7da18f7204c0>]]
return[<ast.IfExp object at 0x7da18f721ae0>] | keyword[def] identifier[join_field] ( identifier[path] ):
literal[string]
identifier[output] = literal[string] . identifier[join] ([ identifier[f] . identifier[replace] ( literal[string] , literal[string] ) keyword[for] identifier[f] keyword[in] identifier[path] keyword[if] identifier[f] != keyword[No... | def join_field(path):
"""
RETURN field SEQUENCE AS STRING
"""
output = '.'.join([f.replace('.', '\\.') for f in path if f != None])
return output if output else '.' |
def _post_clean(self):
"""Run password validaton after clean methods
When clean methods are run, the user instance does not yet
exist. To properly compare model values agains the password (in
the UserAttributeSimilarityValidator), we wait until we have an
instance to compare ag... | def function[_post_clean, parameter[self]]:
constant[Run password validaton after clean methods
When clean methods are run, the user instance does not yet
exist. To properly compare model values agains the password (in
the UserAttributeSimilarityValidator), we wait until we have an
... | keyword[def] identifier[_post_clean] ( identifier[self] ):
literal[string]
identifier[super] (). identifier[_post_clean] ()
identifier[password] = identifier[self] . identifier[cleaned_data] . identifier[get] ( literal[string] )
keyword[if] identifier[password] :
key... | def _post_clean(self):
"""Run password validaton after clean methods
When clean methods are run, the user instance does not yet
exist. To properly compare model values agains the password (in
the UserAttributeSimilarityValidator), we wait until we have an
instance to compare agains... |
def _ast_op_multiply_to_code(self, opr, ignore_whitespace=False, **kwargs):
"""Convert an AST multiply op to python source code."""
opl, opr = opr.operands
if isinstance(opl, Number):
times = opl.value
subject = self._ast_to_code(opr)
else:
times = opr.value
subject = self._ast_... | def function[_ast_op_multiply_to_code, parameter[self, opr, ignore_whitespace]]:
constant[Convert an AST multiply op to python source code.]
<ast.Tuple object at 0x7da1b01fc2b0> assign[=] name[opr].operands
if call[name[isinstance], parameter[name[opl], name[Number]]] begin[:]
va... | keyword[def] identifier[_ast_op_multiply_to_code] ( identifier[self] , identifier[opr] , identifier[ignore_whitespace] = keyword[False] ,** identifier[kwargs] ):
literal[string]
identifier[opl] , identifier[opr] = identifier[opr] . identifier[operands]
keyword[if] identifier[isinstance] ( identifie... | def _ast_op_multiply_to_code(self, opr, ignore_whitespace=False, **kwargs):
"""Convert an AST multiply op to python source code."""
(opl, opr) = opr.operands
if isinstance(opl, Number):
times = opl.value
subject = self._ast_to_code(opr) # depends on [control=['if'], data=[]]
else:
... |
def duration_to_number(duration, units='seconds'):
"""If duration is already a numeric type, then just return
duration. If duration is a timedelta, return a duration in
seconds.
TODO: allow for multiple types of units.
"""
if isinstance(duration, (int, float, long)):
return duration
... | def function[duration_to_number, parameter[duration, units]]:
constant[If duration is already a numeric type, then just return
duration. If duration is a timedelta, return a duration in
seconds.
TODO: allow for multiple types of units.
]
if call[name[isinstance], parameter[name[duratio... | keyword[def] identifier[duration_to_number] ( identifier[duration] , identifier[units] = literal[string] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[duration] ,( identifier[int] , identifier[float] , identifier[long] )):
keyword[return] identifier[duration]
keyword[e... | def duration_to_number(duration, units='seconds'):
"""If duration is already a numeric type, then just return
duration. If duration is a timedelta, return a duration in
seconds.
TODO: allow for multiple types of units.
"""
if isinstance(duration, (int, float, long)):
return duration #... |
def add_url_rule(self, host, rule_string, endpoint, **options):
"""Add a url rule to the app instance.
The url rule is the same with Flask apps and other Werkzeug apps.
:param host: the matched hostname. e.g. "www.python.org"
:param rule_string: the matched path pattern. e.g. "/news/<i... | def function[add_url_rule, parameter[self, host, rule_string, endpoint]]:
constant[Add a url rule to the app instance.
The url rule is the same with Flask apps and other Werkzeug apps.
:param host: the matched hostname. e.g. "www.python.org"
:param rule_string: the matched path pattern... | keyword[def] identifier[add_url_rule] ( identifier[self] , identifier[host] , identifier[rule_string] , identifier[endpoint] ,** identifier[options] ):
literal[string]
identifier[rule] = identifier[Rule] ( identifier[rule_string] , identifier[host] = identifier[host] , identifier[endpoint] = identi... | def add_url_rule(self, host, rule_string, endpoint, **options):
"""Add a url rule to the app instance.
The url rule is the same with Flask apps and other Werkzeug apps.
:param host: the matched hostname. e.g. "www.python.org"
:param rule_string: the matched path pattern. e.g. "/news/<int:i... |
def attach_template(self, _template, _key, **unbound_var_values):
"""Attaches the template to this with the _key is supplied with this layer.
Note: names were chosen to avoid conflicts.
Args:
_template: The template to construct.
_key: The key that this layer should replace.
**unbound_va... | def function[attach_template, parameter[self, _template, _key]]:
constant[Attaches the template to this with the _key is supplied with this layer.
Note: names were chosen to avoid conflicts.
Args:
_template: The template to construct.
_key: The key that this layer should replace.
**u... | keyword[def] identifier[attach_template] ( identifier[self] , identifier[_template] , identifier[_key] ,** identifier[unbound_var_values] ):
literal[string]
keyword[if] identifier[_key] keyword[in] identifier[unbound_var_values] :
keyword[raise] identifier[ValueError] ( literal[string] % identif... | def attach_template(self, _template, _key, **unbound_var_values):
"""Attaches the template to this with the _key is supplied with this layer.
Note: names were chosen to avoid conflicts.
Args:
_template: The template to construct.
_key: The key that this layer should replace.
**unbound_va... |
def load(self, filename, offset):
"""Loads NTFS volume information
Args:
filename (str): Path to file/device to read the volume \
information from.
offset (uint): Valid NTFS partition offset from the beginning \
of the file/device.
Raises:
... | def function[load, parameter[self, filename, offset]]:
constant[Loads NTFS volume information
Args:
filename (str): Path to file/device to read the volume information from.
offset (uint): Valid NTFS partition offset from the beginning of the file/device.
... | keyword[def] identifier[load] ( identifier[self] , identifier[filename] , identifier[offset] ):
literal[string]
identifier[self] . identifier[offset] = identifier[offset]
identifier[self] . identifier[filename] = identifier[filename]
identifier[self] . identifier[bootsector] = ... | def load(self, filename, offset):
"""Loads NTFS volume information
Args:
filename (str): Path to file/device to read the volume information from.
offset (uint): Valid NTFS partition offset from the beginning of the file/device.
Raises:
IO... |
def dehydrate(self, iterator):
"""
Pass in an iterator of tweets' JSON and get back an iterator of the
IDs of each tweet.
"""
for line in iterator:
try:
yield json.loads(line)['id_str']
except Exception as e:
log.error("uhoh... | def function[dehydrate, parameter[self, iterator]]:
constant[
Pass in an iterator of tweets' JSON and get back an iterator of the
IDs of each tweet.
]
for taget[name[line]] in starred[name[iterator]] begin[:]
<ast.Try object at 0x7da1b17d7d60> | keyword[def] identifier[dehydrate] ( identifier[self] , identifier[iterator] ):
literal[string]
keyword[for] identifier[line] keyword[in] identifier[iterator] :
keyword[try] :
keyword[yield] identifier[json] . identifier[loads] ( identifier[line] )[ literal[string]... | def dehydrate(self, iterator):
"""
Pass in an iterator of tweets' JSON and get back an iterator of the
IDs of each tweet.
"""
for line in iterator:
try:
yield json.loads(line)['id_str'] # depends on [control=['try'], data=[]]
except Exception as e:
... |
def prepare_modules(module_paths: list, available: dict) -> dict:
"""
Scan all paths for external modules and form key-value dict.
:param module_paths: list of external modules (either python packages or third-party scripts)
:param available: dict of all registered python modules (can contain python mod... | def function[prepare_modules, parameter[module_paths, available]]:
constant[
Scan all paths for external modules and form key-value dict.
:param module_paths: list of external modules (either python packages or third-party scripts)
:param available: dict of all registered python modules (can contain... | keyword[def] identifier[prepare_modules] ( identifier[module_paths] : identifier[list] , identifier[available] : identifier[dict] )-> identifier[dict] :
literal[string]
identifier[indexed] ={}
keyword[for] identifier[path] keyword[in] identifier[module_paths] :
keyword[if] keyword[not] i... | def prepare_modules(module_paths: list, available: dict) -> dict:
"""
Scan all paths for external modules and form key-value dict.
:param module_paths: list of external modules (either python packages or third-party scripts)
:param available: dict of all registered python modules (can contain python mod... |
def get_channelstate_settled(
chain_state: ChainState,
payment_network_id: PaymentNetworkID,
token_address: TokenAddress,
) -> List[NettingChannelState]:
"""Return the state of settled channels in a token network."""
return get_channelstate_filter(
chain_state,
payment_ne... | def function[get_channelstate_settled, parameter[chain_state, payment_network_id, token_address]]:
constant[Return the state of settled channels in a token network.]
return[call[name[get_channelstate_filter], parameter[name[chain_state], name[payment_network_id], name[token_address], <ast.Lambda object at 0... | keyword[def] identifier[get_channelstate_settled] (
identifier[chain_state] : identifier[ChainState] ,
identifier[payment_network_id] : identifier[PaymentNetworkID] ,
identifier[token_address] : identifier[TokenAddress] ,
)-> identifier[List] [ identifier[NettingChannelState] ]:
literal[string]
keyword[... | def get_channelstate_settled(chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress) -> List[NettingChannelState]:
"""Return the state of settled channels in a token network."""
return get_channelstate_filter(chain_state, payment_network_id, token_address, lambda channel_stat... |
def _validate_channel_definition(self, jp2h, colr):
"""Validate the channel definition box."""
cdef_lst = [j for (j, box) in enumerate(jp2h.box)
if box.box_id == 'cdef']
if len(cdef_lst) > 1:
msg = ("Only one channel definition box is allowed in the "
... | def function[_validate_channel_definition, parameter[self, jp2h, colr]]:
constant[Validate the channel definition box.]
variable[cdef_lst] assign[=] <ast.ListComp object at 0x7da1b26aed70>
if compare[call[name[len], parameter[name[cdef_lst]]] greater[>] constant[1]] begin[:]
vari... | keyword[def] identifier[_validate_channel_definition] ( identifier[self] , identifier[jp2h] , identifier[colr] ):
literal[string]
identifier[cdef_lst] =[ identifier[j] keyword[for] ( identifier[j] , identifier[box] ) keyword[in] identifier[enumerate] ( identifier[jp2h] . identifier[box] )
... | def _validate_channel_definition(self, jp2h, colr):
"""Validate the channel definition box."""
cdef_lst = [j for (j, box) in enumerate(jp2h.box) if box.box_id == 'cdef']
if len(cdef_lst) > 1:
msg = 'Only one channel definition box is allowed in the JP2 header.'
raise IOError(msg) # depends ... |
def wait_for_link_text(self, link_text, timeout=settings.LARGE_TIMEOUT):
""" The shorter version of wait_for_link_text_visible() """
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return self.wait_for_link_text_visible(link... | def function[wait_for_link_text, parameter[self, link_text, timeout]]:
constant[ The shorter version of wait_for_link_text_visible() ]
if <ast.BoolOp object at 0x7da1b1beec20> begin[:]
variable[timeout] assign[=] call[name[self].__get_new_timeout, parameter[name[timeout]]]
return[cal... | keyword[def] identifier[wait_for_link_text] ( identifier[self] , identifier[link_text] , identifier[timeout] = identifier[settings] . identifier[LARGE_TIMEOUT] ):
literal[string]
keyword[if] identifier[self] . identifier[timeout_multiplier] keyword[and] identifier[timeout] == identifier[settings... | def wait_for_link_text(self, link_text, timeout=settings.LARGE_TIMEOUT):
""" The shorter version of wait_for_link_text_visible() """
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout) # depends on [control=['if'], data=[]]
return self.wait_fo... |
def status(ctx):
"""Print a status of this Lambda function"""
status = ctx.status()
click.echo(click.style('Policy', bold=True))
if status['policy']:
line = ' {} ({})'.format(
status['policy']['PolicyName'],
status['policy']['Arn'])
click.echo(click.style(line,... | def function[status, parameter[ctx]]:
constant[Print a status of this Lambda function]
variable[status] assign[=] call[name[ctx].status, parameter[]]
call[name[click].echo, parameter[call[name[click].style, parameter[constant[Policy]]]]]
if call[name[status]][constant[policy]] begin[:]
... | keyword[def] identifier[status] ( identifier[ctx] ):
literal[string]
identifier[status] = identifier[ctx] . identifier[status] ()
identifier[click] . identifier[echo] ( identifier[click] . identifier[style] ( literal[string] , identifier[bold] = keyword[True] ))
keyword[if] identifier[status] [ ... | def status(ctx):
"""Print a status of this Lambda function"""
status = ctx.status()
click.echo(click.style('Policy', bold=True))
if status['policy']:
line = ' {} ({})'.format(status['policy']['PolicyName'], status['policy']['Arn'])
click.echo(click.style(line, fg='green')) # depends ... |
def _set_vcs(self, v, load=False):
"""
Setter method for vcs, mapped from YANG variable /event_handler/event_handler_list/trigger/vcs (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_vcs is considered as a private
method. Backends looking to populate thi... | def function[_set_vcs, parameter[self, v, load]]:
constant[
Setter method for vcs, mapped from YANG variable /event_handler/event_handler_list/trigger/vcs (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_vcs is considered as a private
method. Backend... | keyword[def] identifier[_set_vcs] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
identifier... | def _set_vcs(self, v, load=False):
"""
Setter method for vcs, mapped from YANG variable /event_handler/event_handler_list/trigger/vcs (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_vcs is considered as a private
method. Backends looking to populate thi... |
def get_requirement(self, line):
"""Gets requirement name and id."""
res = self.REQ_SEARCH.search(line)
try:
name, tc_id = res.group(1), res.group(2)
except (AttributeError, IndexError):
return None
return LogItem(name, tc_id, None) | def function[get_requirement, parameter[self, line]]:
constant[Gets requirement name and id.]
variable[res] assign[=] call[name[self].REQ_SEARCH.search, parameter[name[line]]]
<ast.Try object at 0x7da18eb55a20>
return[call[name[LogItem], parameter[name[name], name[tc_id], constant[None]]]] | keyword[def] identifier[get_requirement] ( identifier[self] , identifier[line] ):
literal[string]
identifier[res] = identifier[self] . identifier[REQ_SEARCH] . identifier[search] ( identifier[line] )
keyword[try] :
identifier[name] , identifier[tc_id] = identifier[res] . ident... | def get_requirement(self, line):
"""Gets requirement name and id."""
res = self.REQ_SEARCH.search(line)
try:
(name, tc_id) = (res.group(1), res.group(2)) # depends on [control=['try'], data=[]]
except (AttributeError, IndexError):
return None # depends on [control=['except'], data=[]]
... |
def await_message(self, *args, **kwargs) -> 'asyncio.Future[Message]':
"""
Block until a message matches. See `on_message`
"""
fut = asyncio.Future()
@self.on_message(*args, **kwargs)
async def handler(message):
fut.set_result(message)
# remove handler... | def function[await_message, parameter[self]]:
constant[
Block until a message matches. See `on_message`
]
variable[fut] assign[=] call[name[asyncio].Future, parameter[]]
<ast.AsyncFunctionDef object at 0x7da2054a5a80>
call[name[fut].add_done_callback, parameter[<ast.Lambda ob... | keyword[def] identifier[await_message] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] )-> literal[string] :
literal[string]
identifier[fut] = identifier[asyncio] . identifier[Future] ()
@ identifier[self] . identifier[on_message] (* identifier[args] ,** identifier[kwargs] )
... | def await_message(self, *args, **kwargs) -> 'asyncio.Future[Message]':
"""
Block until a message matches. See `on_message`
"""
fut = asyncio.Future()
@self.on_message(*args, **kwargs)
async def handler(message):
fut.set_result(message)
# remove handler when done or cancelled... |
def getmergerequest(self, project_id, mergerequest_id):
"""
Get information about a specific merge request.
:param project_id: ID of the project
:param mergerequest_id: ID of the merge request
:return: dict of the merge request
"""
request = requests.get(
... | def function[getmergerequest, parameter[self, project_id, mergerequest_id]]:
constant[
Get information about a specific merge request.
:param project_id: ID of the project
:param mergerequest_id: ID of the merge request
:return: dict of the merge request
]
variab... | keyword[def] identifier[getmergerequest] ( identifier[self] , identifier[project_id] , identifier[mergerequest_id] ):
literal[string]
identifier[request] = identifier[requests] . identifier[get] (
literal[string] . identifier[format] ( identifier[self] . identifier[projects_url] , identifi... | def getmergerequest(self, project_id, mergerequest_id):
"""
Get information about a specific merge request.
:param project_id: ID of the project
:param mergerequest_id: ID of the merge request
:return: dict of the merge request
"""
request = requests.get('{0}/{1}/merge_r... |
def remove_stderr_file(self):
"""Remove stderr_file associated with the client."""
try:
# Defer closing the stderr_handle until the client
# is closed because jupyter_client needs it open
# while it tries to restart the kernel
self.stderr_handle.clos... | def function[remove_stderr_file, parameter[self]]:
constant[Remove stderr_file associated with the client.]
<ast.Try object at 0x7da18c4ce890> | keyword[def] identifier[remove_stderr_file] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[self] . identifier[stderr_handle] . identifier[close] ()
identifier[os] . identifier[remove] ( identifier[self] . identifier[stderr... | def remove_stderr_file(self):
"""Remove stderr_file associated with the client."""
try: # Defer closing the stderr_handle until the client
# is closed because jupyter_client needs it open
# while it tries to restart the kernel
self.stderr_handle.close()
os.remove(self.stderr_fil... |
def _add_step(self, step):
"""Add a step to the workflow.
Args:
step (Step): a step from the steps library.
"""
self._closed()
self.has_workflow_step = self.has_workflow_step or step.is_workflow
self.wf_steps[step.name_in_workflow] = step | def function[_add_step, parameter[self, step]]:
constant[Add a step to the workflow.
Args:
step (Step): a step from the steps library.
]
call[name[self]._closed, parameter[]]
name[self].has_workflow_step assign[=] <ast.BoolOp object at 0x7da18f8139d0>
call[na... | keyword[def] identifier[_add_step] ( identifier[self] , identifier[step] ):
literal[string]
identifier[self] . identifier[_closed] ()
identifier[self] . identifier[has_workflow_step] = identifier[self] . identifier[has_workflow_step] keyword[or] identifier[step] . identifier[is_workflow... | def _add_step(self, step):
"""Add a step to the workflow.
Args:
step (Step): a step from the steps library.
"""
self._closed()
self.has_workflow_step = self.has_workflow_step or step.is_workflow
self.wf_steps[step.name_in_workflow] = step |
def get_pokemon_by_number(self, number):
"""
Returns an array of Pokemon objects containing all the forms of the
Pokemon specified the Pokedex number.
"""
endpoint = '/pokemon/' + str(number)
return self.make_request(self.BASE_URL + endpoint) | def function[get_pokemon_by_number, parameter[self, number]]:
constant[
Returns an array of Pokemon objects containing all the forms of the
Pokemon specified the Pokedex number.
]
variable[endpoint] assign[=] binary_operation[constant[/pokemon/] + call[name[str], parameter[name[n... | keyword[def] identifier[get_pokemon_by_number] ( identifier[self] , identifier[number] ):
literal[string]
identifier[endpoint] = literal[string] + identifier[str] ( identifier[number] )
keyword[return] identifier[self] . identifier[make_request] ( identifier[self] . identifier[BASE_URL] +... | def get_pokemon_by_number(self, number):
"""
Returns an array of Pokemon objects containing all the forms of the
Pokemon specified the Pokedex number.
"""
endpoint = '/pokemon/' + str(number)
return self.make_request(self.BASE_URL + endpoint) |
async def _readline(self, reader):
"""
Readline helper
"""
ret = await reader.readline()
if len(ret) == 0 and reader.at_eof():
raise EOFError()
return ret | <ast.AsyncFunctionDef object at 0x7da1b1caf700> | keyword[async] keyword[def] identifier[_readline] ( identifier[self] , identifier[reader] ):
literal[string]
identifier[ret] = keyword[await] identifier[reader] . identifier[readline] ()
keyword[if] identifier[len] ( identifier[ret] )== literal[int] keyword[and] identifier[reader] . i... | async def _readline(self, reader):
"""
Readline helper
"""
ret = await reader.readline()
if len(ret) == 0 and reader.at_eof():
raise EOFError() # depends on [control=['if'], data=[]]
return ret |
def add_missing_children(models,request,include_children_for,modelgb):
"helper for do_check. mutates request"
for (nombre,pkey),model in models.items():
for modelclass,pkeys in model.refkeys(include_children_for.get(nombre,())).items():
# warning: this is defaulting to all fields of child object. don't gi... | def function[add_missing_children, parameter[models, request, include_children_for, modelgb]]:
constant[helper for do_check. mutates request]
for taget[tuple[[<ast.Tuple object at 0x7da2044c1cf0>, <ast.Name object at 0x7da2044c26e0>]]] in starred[call[name[models].items, parameter[]]] begin[:]
... | keyword[def] identifier[add_missing_children] ( identifier[models] , identifier[request] , identifier[include_children_for] , identifier[modelgb] ):
literal[string]
keyword[for] ( identifier[nombre] , identifier[pkey] ), identifier[model] keyword[in] identifier[models] . identifier[items] ():
keyword[fo... | def add_missing_children(models, request, include_children_for, modelgb):
"""helper for do_check. mutates request"""
for ((nombre, pkey), model) in models.items():
for (modelclass, pkeys) in model.refkeys(include_children_for.get(nombre, ())).items():
# warning: this is defaulting to all fie... |
def _GetKeysDefaultEmpty(self, top_level, keys, depth=1):
"""Retrieves plist keys, defaulting to empty values.
Args:
top_level (plistlib._InternalDict): top level plist object.
keys (set[str]): names of keys that should be returned.
depth (int): depth within the plist, where 1 is top level.
... | def function[_GetKeysDefaultEmpty, parameter[self, top_level, keys, depth]]:
constant[Retrieves plist keys, defaulting to empty values.
Args:
top_level (plistlib._InternalDict): top level plist object.
keys (set[str]): names of keys that should be returned.
depth (int): depth within the p... | keyword[def] identifier[_GetKeysDefaultEmpty] ( identifier[self] , identifier[top_level] , identifier[keys] , identifier[depth] = literal[int] ):
literal[string]
identifier[keys] = identifier[set] ( identifier[keys] )
identifier[match] ={}
keyword[if] identifier[depth] == literal[int] :
... | def _GetKeysDefaultEmpty(self, top_level, keys, depth=1):
"""Retrieves plist keys, defaulting to empty values.
Args:
top_level (plistlib._InternalDict): top level plist object.
keys (set[str]): names of keys that should be returned.
depth (int): depth within the plist, where 1 is top level.
... |
def pstdev(data):
"""Calculates the population standard deviation."""
#: http://stackoverflow.com/a/27758326
n = len(data)
if n < 2:
raise ValueError('variance requires at least two data points')
ss = _ss(data)
pvar = ss/n # the population variance
return pvar**0.5 | def function[pstdev, parameter[data]]:
constant[Calculates the population standard deviation.]
variable[n] assign[=] call[name[len], parameter[name[data]]]
if compare[name[n] less[<] constant[2]] begin[:]
<ast.Raise object at 0x7da20c6aaaa0>
variable[ss] assign[=] call[name[_ss],... | keyword[def] identifier[pstdev] ( identifier[data] ):
literal[string]
identifier[n] = identifier[len] ( identifier[data] )
keyword[if] identifier[n] < literal[int] :
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[ss] = identifier[_ss] ( identifier[data] )
... | def pstdev(data):
"""Calculates the population standard deviation."""
#: http://stackoverflow.com/a/27758326
n = len(data)
if n < 2:
raise ValueError('variance requires at least two data points') # depends on [control=['if'], data=[]]
ss = _ss(data)
pvar = ss / n # the population varia... |
def remove_term(self, t):
"""Only removes top-level terms. Child terms can be removed at the parent. """
try:
self.terms.remove(t)
except ValueError:
pass
if t.section and t.parent_term_lc == 'root':
t.section = self.add_section(t.section)
... | def function[remove_term, parameter[self, t]]:
constant[Only removes top-level terms. Child terms can be removed at the parent. ]
<ast.Try object at 0x7da18f00e950>
if <ast.BoolOp object at 0x7da20e7484f0> begin[:]
name[t].section assign[=] call[name[self].add_section, parameter[name... | keyword[def] identifier[remove_term] ( identifier[self] , identifier[t] ):
literal[string]
keyword[try] :
identifier[self] . identifier[terms] . identifier[remove] ( identifier[t] )
keyword[except] identifier[ValueError] :
keyword[pass]
keyword[if] i... | def remove_term(self, t):
"""Only removes top-level terms. Child terms can be removed at the parent. """
try:
self.terms.remove(t) # depends on [control=['try'], data=[]]
except ValueError:
pass # depends on [control=['except'], data=[]]
if t.section and t.parent_term_lc == 'root':
... |
def updateImage(self, imgdata, xaxis=None, yaxis=None):
"""Updates the Widget image directly.
:type imgdata: numpy.ndarray, see :meth:`pyqtgraph:pyqtgraph.ImageItem.setImage`
:param xaxis: x-axis values, length should match dimension 1 of imgdata
:param yaxis: y-axis values, length shou... | def function[updateImage, parameter[self, imgdata, xaxis, yaxis]]:
constant[Updates the Widget image directly.
:type imgdata: numpy.ndarray, see :meth:`pyqtgraph:pyqtgraph.ImageItem.setImage`
:param xaxis: x-axis values, length should match dimension 1 of imgdata
:param yaxis: y-axis va... | keyword[def] identifier[updateImage] ( identifier[self] , identifier[imgdata] , identifier[xaxis] = keyword[None] , identifier[yaxis] = keyword[None] ):
literal[string]
identifier[imgdata] = identifier[imgdata] . identifier[T]
identifier[self] . identifier[img] . identifier[setImage] ( id... | def updateImage(self, imgdata, xaxis=None, yaxis=None):
"""Updates the Widget image directly.
:type imgdata: numpy.ndarray, see :meth:`pyqtgraph:pyqtgraph.ImageItem.setImage`
:param xaxis: x-axis values, length should match dimension 1 of imgdata
:param yaxis: y-axis values, length should m... |
def _lightness(color, **kwargs):
""" Get lightness value of HSL color.
"""
l = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[1]
return NumberValue((l * 100, '%')) | def function[_lightness, parameter[color]]:
constant[ Get lightness value of HSL color.
]
variable[l] assign[=] call[call[name[colorsys].rgb_to_hls, parameter[<ast.Starred object at 0x7da1b27ecd00>]]][constant[1]]
return[call[name[NumberValue], parameter[tuple[[<ast.BinOp object at 0x7da1b27ee35... | keyword[def] identifier[_lightness] ( identifier[color] ,** identifier[kwargs] ):
literal[string]
identifier[l] = identifier[colorsys] . identifier[rgb_to_hls] (*[ identifier[x] / literal[int] keyword[for] identifier[x] keyword[in] identifier[color] . identifier[value] [: literal[int] ]])[ literal[int]... | def _lightness(color, **kwargs):
""" Get lightness value of HSL color.
"""
l = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[1]
return NumberValue((l * 100, '%')) |
def _prepare_servers(self):
"""
Prepare the variables that are exposed to the servers.
Most attributes in the server config are used directly. However, due
to variations in how cloud providers treat regions and availability
zones, this method allows either the ``availability_zo... | def function[_prepare_servers, parameter[self]]:
constant[
Prepare the variables that are exposed to the servers.
Most attributes in the server config are used directly. However, due
to variations in how cloud providers treat regions and availability
zones, this method allows e... | keyword[def] identifier[_prepare_servers] ( identifier[self] ):
literal[string]
identifier[stack] ={
identifier[A] . identifier[NAME] : identifier[self] [ identifier[A] . identifier[NAME] ],
identifier[A] . identifier[VERSION] : identifier[self] [ identifier[A] . identifier[VERSIO... | def _prepare_servers(self):
"""
Prepare the variables that are exposed to the servers.
Most attributes in the server config are used directly. However, due
to variations in how cloud providers treat regions and availability
zones, this method allows either the ``availability_zone``... |
def smooth_magseries_gaussfilt(mags, windowsize, windowfwhm=7):
'''This smooths the magseries with a Gaussian kernel.
Parameters
----------
mags : np.array
The input mags/flux time-series to smooth.
windowsize : int
This is a odd integer containing the smoothing window size.
... | def function[smooth_magseries_gaussfilt, parameter[mags, windowsize, windowfwhm]]:
constant[This smooths the magseries with a Gaussian kernel.
Parameters
----------
mags : np.array
The input mags/flux time-series to smooth.
windowsize : int
This is a odd integer containing the... | keyword[def] identifier[smooth_magseries_gaussfilt] ( identifier[mags] , identifier[windowsize] , identifier[windowfwhm] = literal[int] ):
literal[string]
identifier[convkernel] = identifier[Gaussian1DKernel] ( identifier[windowfwhm] , identifier[x_size] = identifier[windowsize] )
identifier[smoothed... | def smooth_magseries_gaussfilt(mags, windowsize, windowfwhm=7):
"""This smooths the magseries with a Gaussian kernel.
Parameters
----------
mags : np.array
The input mags/flux time-series to smooth.
windowsize : int
This is a odd integer containing the smoothing window size.
... |
def status_codes_chart():
"""Chart for status codes."""
stats = status_codes_stats()
chart_options = {
'chart': {
'type': 'pie'
},
'title': {
'text': ''
},
'subtitle': {
'text': ''
},
'tooltip': {
'formatt... | def function[status_codes_chart, parameter[]]:
constant[Chart for status codes.]
variable[stats] assign[=] call[name[status_codes_stats], parameter[]]
variable[chart_options] assign[=] dictionary[[<ast.Constant object at 0x7da1b25589d0>, <ast.Constant object at 0x7da1b2559f30>, <ast.Constant obj... | keyword[def] identifier[status_codes_chart] ():
literal[string]
identifier[stats] = identifier[status_codes_stats] ()
identifier[chart_options] ={
literal[string] :{
literal[string] : literal[string]
},
literal[string] :{
literal[string] : literal[string]
},
literal... | def status_codes_chart():
"""Chart for status codes."""
stats = status_codes_stats()
chart_options = {'chart': {'type': 'pie'}, 'title': {'text': ''}, 'subtitle': {'text': ''}, 'tooltip': {'formatter': "return this.y + '/' + this.total + ' (' + Highcharts.numberFormat(this.percentage, 1) + '%)';"}, 'legend'... |
def _get_nsymop(self):
"""Returns total number of symmetry operations."""
if self.centrosymmetric:
return 2 * len(self._rotations) * len(self._subtrans)
else:
return len(self._rotations) * len(self._subtrans) | def function[_get_nsymop, parameter[self]]:
constant[Returns total number of symmetry operations.]
if name[self].centrosymmetric begin[:]
return[binary_operation[binary_operation[constant[2] * call[name[len], parameter[name[self]._rotations]]] * call[name[len], parameter[name[self]._subtrans]]]] | keyword[def] identifier[_get_nsymop] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[centrosymmetric] :
keyword[return] literal[int] * identifier[len] ( identifier[self] . identifier[_rotations] )* identifier[len] ( identifier[self] . identifier[_subtr... | def _get_nsymop(self):
"""Returns total number of symmetry operations."""
if self.centrosymmetric:
return 2 * len(self._rotations) * len(self._subtrans) # depends on [control=['if'], data=[]]
else:
return len(self._rotations) * len(self._subtrans) |
def set_object_acl(self, obj):
""" Set object ACL on creation if not already present. """
if not obj._acl:
from nefertari_guards import engine as guards_engine
acl = self._factory(self.request).generate_item_acl(obj)
obj._acl = guards_engine.ACLField.stringify_acl(acl... | def function[set_object_acl, parameter[self, obj]]:
constant[ Set object ACL on creation if not already present. ]
if <ast.UnaryOp object at 0x7da1b1123850> begin[:]
from relative_module[nefertari_guards] import module[engine]
variable[acl] assign[=] call[call[name[self]._factory... | keyword[def] identifier[set_object_acl] ( identifier[self] , identifier[obj] ):
literal[string]
keyword[if] keyword[not] identifier[obj] . identifier[_acl] :
keyword[from] identifier[nefertari_guards] keyword[import] identifier[engine] keyword[as] identifier[guards_engine]
... | def set_object_acl(self, obj):
""" Set object ACL on creation if not already present. """
if not obj._acl:
from nefertari_guards import engine as guards_engine
acl = self._factory(self.request).generate_item_acl(obj)
obj._acl = guards_engine.ACLField.stringify_acl(acl) # depends on [con... |
def update(self, query, doc, *args, **kwargs):
"""BAckwards compatibility with update"""
if isinstance(doc, list):
return [
self.update_one(query, item, *args, **kwargs)
for item in doc
]
else:
return self.update_one(query, doc,... | def function[update, parameter[self, query, doc]]:
constant[BAckwards compatibility with update]
if call[name[isinstance], parameter[name[doc], name[list]]] begin[:]
return[<ast.ListComp object at 0x7da20e9541f0>] | keyword[def] identifier[update] ( identifier[self] , identifier[query] , identifier[doc] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[doc] , identifier[list] ):
keyword[return] [
identifier[self] . identifie... | def update(self, query, doc, *args, **kwargs):
"""BAckwards compatibility with update"""
if isinstance(doc, list):
return [self.update_one(query, item, *args, **kwargs) for item in doc] # depends on [control=['if'], data=[]]
else:
return self.update_one(query, doc, *args, **kwargs) |
def enum_value(self):
"""Return the value of an enum constant."""
if not hasattr(self, '_enum_value'):
assert self.kind == CursorKind.ENUM_CONSTANT_DECL
# Figure out the underlying type of the enum to know if it
# is a signed or unsigned quantity.
underlyi... | def function[enum_value, parameter[self]]:
constant[Return the value of an enum constant.]
if <ast.UnaryOp object at 0x7da18f09ce80> begin[:]
assert[compare[name[self].kind equal[==] name[CursorKind].ENUM_CONSTANT_DECL]]
variable[underlying_type] assign[=] name[self].type
... | keyword[def] identifier[enum_value] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[self] , literal[string] ):
keyword[assert] identifier[self] . identifier[kind] == identifier[CursorKind] . identifier[ENUM_CONSTANT_DECL]
... | def enum_value(self):
"""Return the value of an enum constant."""
if not hasattr(self, '_enum_value'):
assert self.kind == CursorKind.ENUM_CONSTANT_DECL
# Figure out the underlying type of the enum to know if it
# is a signed or unsigned quantity.
underlying_type = self.type
... |
def execute(self, task):
"""Execute a task.
"""
taskid = str(task)
res = None
try:
# Try to run the task. If we catch an exception, then
# it becomes the result.
self.time_start = time.time()
self.setstatus('executing %s' % taskid... | def function[execute, parameter[self, task]]:
constant[Execute a task.
]
variable[taskid] assign[=] call[name[str], parameter[name[task]]]
variable[res] assign[=] constant[None]
<ast.Try object at 0x7da18bcc95d0> | keyword[def] identifier[execute] ( identifier[self] , identifier[task] ):
literal[string]
identifier[taskid] = identifier[str] ( identifier[task] )
identifier[res] = keyword[None]
keyword[try] :
identifier[self] . identifier[time_start] = identifie... | def execute(self, task):
"""Execute a task.
"""
taskid = str(task)
res = None
try:
# Try to run the task. If we catch an exception, then
# it becomes the result.
self.time_start = time.time()
self.setstatus('executing %s' % taskid)
self.logger.debug("now ... |
def __check_mem(self):
''' raise exception on RAM exceeded '''
mem_free = psutil.virtual_memory().available / 2**20
self.log.debug("Memory free: %s/%s", mem_free, self.mem_limit)
if mem_free < self.mem_limit:
raise RuntimeError(
"Not enough resources: free mem... | def function[__check_mem, parameter[self]]:
constant[ raise exception on RAM exceeded ]
variable[mem_free] assign[=] binary_operation[call[name[psutil].virtual_memory, parameter[]].available / binary_operation[constant[2] ** constant[20]]]
call[name[self].log.debug, parameter[constant[Memory fre... | keyword[def] identifier[__check_mem] ( identifier[self] ):
literal[string]
identifier[mem_free] = identifier[psutil] . identifier[virtual_memory] (). identifier[available] / literal[int] ** literal[int]
identifier[self] . identifier[log] . identifier[debug] ( literal[string] , identifier[... | def __check_mem(self):
""" raise exception on RAM exceeded """
mem_free = psutil.virtual_memory().available / 2 ** 20
self.log.debug('Memory free: %s/%s', mem_free, self.mem_limit)
if mem_free < self.mem_limit:
raise RuntimeError('Not enough resources: free memory less than %sMB: %sMB' % (self.m... |
async def apply_commandline(self, cmdline):
"""
interprets a command line string
i.e., splits it into separate command strings,
instanciates :class:`Commands <alot.commands.Command>`
accordingly and applies then in sequence.
:param cmdline: command line to interpret
... | <ast.AsyncFunctionDef object at 0x7da1b080b5e0> | keyword[async] keyword[def] identifier[apply_commandline] ( identifier[self] , identifier[cmdline] ):
literal[string]
identifier[cmdline] = identifier[cmdline] . identifier[lstrip] ()
keyword[def] identifier[apply_... | async def apply_commandline(self, cmdline):
"""
interprets a command line string
i.e., splits it into separate command strings,
instanciates :class:`Commands <alot.commands.Command>`
accordingly and applies then in sequence.
:param cmdline: command line to interpret
... |
def accounts(self):
"""
:rtype: twilio.rest.api.v2010.account.AccountList
"""
if self._accounts is None:
self._accounts = AccountList(self)
return self._accounts | def function[accounts, parameter[self]]:
constant[
:rtype: twilio.rest.api.v2010.account.AccountList
]
if compare[name[self]._accounts is constant[None]] begin[:]
name[self]._accounts assign[=] call[name[AccountList], parameter[name[self]]]
return[name[self]._accounts... | keyword[def] identifier[accounts] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_accounts] keyword[is] keyword[None] :
identifier[self] . identifier[_accounts] = identifier[AccountList] ( identifier[self] )
keyword[return] identifier[self]... | def accounts(self):
"""
:rtype: twilio.rest.api.v2010.account.AccountList
"""
if self._accounts is None:
self._accounts = AccountList(self) # depends on [control=['if'], data=[]]
return self._accounts |
def links(self,**args):
'''
Return Gist URL-Link, Clone-Link and Script-Link to embed
'''
if 'name' in args:
self.gist_name = args['name']
self.gist_id = self.getMyID(self.gist_name)
elif 'id' in args:
self.gist_id = args['id']
else:
raise Exception('Gist Name/ID must be provided')
if self.gis... | def function[links, parameter[self]]:
constant[
Return Gist URL-Link, Clone-Link and Script-Link to embed
]
if compare[constant[name] in name[args]] begin[:]
name[self].gist_name assign[=] call[name[args]][constant[name]]
name[self].gist_id assign[=] call[name[self].g... | keyword[def] identifier[links] ( identifier[self] ,** identifier[args] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[args] :
identifier[self] . identifier[gist_name] = identifier[args] [ literal[string] ]
identifier[self] . identifier[gist_id] = identifier[self] . identifier[... | def links(self, **args):
"""
Return Gist URL-Link, Clone-Link and Script-Link to embed
"""
if 'name' in args:
self.gist_name = args['name']
self.gist_id = self.getMyID(self.gist_name) # depends on [control=['if'], data=['args']]
elif 'id' in args:
self.gist_id = args['id'] # de... |
def __merge_by_signle_link(self):
"""!
@brief Merges the most similar clusters in line with single link type.
"""
minimum_single_distance = float('Inf');
indexes = None;
for index_cluster1 in range(0, len(self.__clusters)):
for index... | def function[__merge_by_signle_link, parameter[self]]:
constant[!
@brief Merges the most similar clusters in line with single link type.
]
variable[minimum_single_distance] assign[=] call[name[float], parameter[constant[Inf]]]
variable[indexes] assign[=] constant[None]
... | keyword[def] identifier[__merge_by_signle_link] ( identifier[self] ):
literal[string]
identifier[minimum_single_distance] = identifier[float] ( literal[string] );
identifier[indexes] = keyword[None] ;
keyword[for] identifier[index_cluster1] keyword[in] identifier[range] ( lit... | def __merge_by_signle_link(self):
"""!
@brief Merges the most similar clusters in line with single link type.
"""
minimum_single_distance = float('Inf')
indexes = None
for index_cluster1 in range(0, len(self.__clusters)):
for index_cluster2 in range(index_cluster1 + 1, l... |
def mouseMoveEvent( self, event ):
"""
Sets the value for the slider at the event position.
:param event | <QMouseEvent>
"""
self.setValue(self.valueAt(event.pos().x())) | def function[mouseMoveEvent, parameter[self, event]]:
constant[
Sets the value for the slider at the event position.
:param event | <QMouseEvent>
]
call[name[self].setValue, parameter[call[name[self].valueAt, parameter[call[call[name[event].pos, parameter[]].x, para... | keyword[def] identifier[mouseMoveEvent] ( identifier[self] , identifier[event] ):
literal[string]
identifier[self] . identifier[setValue] ( identifier[self] . identifier[valueAt] ( identifier[event] . identifier[pos] (). identifier[x] ())) | def mouseMoveEvent(self, event):
"""
Sets the value for the slider at the event position.
:param event | <QMouseEvent>
"""
self.setValue(self.valueAt(event.pos().x())) |
def _get_columns_relevant_for_diff(columns_to_show):
"""
Extract columns that are relevant for the diff table.
@param columns_to_show: (list) A list of columns that should be shown
@return: (set) Set of columns that are relevant for the diff table. If
none is marked relevant, the column na... | def function[_get_columns_relevant_for_diff, parameter[columns_to_show]]:
constant[
Extract columns that are relevant for the diff table.
@param columns_to_show: (list) A list of columns that should be shown
@return: (set) Set of columns that are relevant for the diff table. If
none is... | keyword[def] identifier[_get_columns_relevant_for_diff] ( identifier[columns_to_show] ):
literal[string]
identifier[cols] = identifier[set] ([ identifier[col] . identifier[title] keyword[for] identifier[col] keyword[in] identifier[columns_to_show] keyword[if] identifier[col] . identifier[relevant_for... | def _get_columns_relevant_for_diff(columns_to_show):
"""
Extract columns that are relevant for the diff table.
@param columns_to_show: (list) A list of columns that should be shown
@return: (set) Set of columns that are relevant for the diff table. If
none is marked relevant, the column na... |
def regexp(__string: str, __pattern: str, __repl: Union[Callable, str], *,
count: int = 0, flags: int = 0) -> str:
"""Jinja filter for regexp replacements.
See :func:`re.sub` for documentation.
Returns:
Text with substitutions applied
"""
return re.sub(__pattern, __repl, __strin... | def function[regexp, parameter[__string, __pattern, __repl]]:
constant[Jinja filter for regexp replacements.
See :func:`re.sub` for documentation.
Returns:
Text with substitutions applied
]
return[call[name[re].sub, parameter[name[__pattern], name[__repl], name[__string], name[count], ... | keyword[def] identifier[regexp] ( identifier[__string] : identifier[str] , identifier[__pattern] : identifier[str] , identifier[__repl] : identifier[Union] [ identifier[Callable] , identifier[str] ],*,
identifier[count] : identifier[int] = literal[int] , identifier[flags] : identifier[int] = literal[int] )-> identif... | def regexp(__string: str, __pattern: str, __repl: Union[Callable, str], *, count: int=0, flags: int=0) -> str:
"""Jinja filter for regexp replacements.
See :func:`re.sub` for documentation.
Returns:
Text with substitutions applied
"""
return re.sub(__pattern, __repl, __string, count, flags... |
def start(self):
"""
Start the node on the cloud using the given instance properties.
This method is non-blocking: as soon as the node id is returned from
the cloud provider, it will return. The `is_alive`:meth: and
`update_ips`:meth: methods should be used to further gather det... | def function[start, parameter[self]]:
constant[
Start the node on the cloud using the given instance properties.
This method is non-blocking: as soon as the node id is returned from
the cloud provider, it will return. The `is_alive`:meth: and
`update_ips`:meth: methods should be... | keyword[def] identifier[start] ( identifier[self] ):
literal[string]
identifier[log] . identifier[info] ( literal[string] ,
identifier[self] . identifier[name] , identifier[self] . identifier[image_id] , identifier[self] . identifier[flavor] )
identifier[self] . identifier[instanc... | def start(self):
"""
Start the node on the cloud using the given instance properties.
This method is non-blocking: as soon as the node id is returned from
the cloud provider, it will return. The `is_alive`:meth: and
`update_ips`:meth: methods should be used to further gather details... |
def cleanDescriptor(self, dir=os.getcwd()):
"""
Cleans the build artifacts for the Unreal project or plugin in the specified directory
"""
# Verify that an Unreal project or plugin exists in the specified directory
descriptor = self.getDescriptor(dir)
# Because performing a clean will also delete the ... | def function[cleanDescriptor, parameter[self, dir]]:
constant[
Cleans the build artifacts for the Unreal project or plugin in the specified directory
]
variable[descriptor] assign[=] call[name[self].getDescriptor, parameter[name[dir]]]
call[name[shutil].rmtree, parameter[call[name[os].path.j... | keyword[def] identifier[cleanDescriptor] ( identifier[self] , identifier[dir] = identifier[os] . identifier[getcwd] ()):
literal[string]
identifier[descriptor] = identifier[self] . identifier[getDescriptor] ( identifier[dir] )
identifier[shutil] . identifier[rmtree] ( identifier[os] . identifier[... | def cleanDescriptor(self, dir=os.getcwd()):
"""
Cleans the build artifacts for the Unreal project or plugin in the specified directory
""" # Verify that an Unreal project or plugin exists in the specified directory
descriptor = self.getDescriptor(dir) # Because performing a clean will also delete the engi... |
def _handle_request(self, scheme, netloc, path, headers, body=None, method="GET"):
"""
Run the actual request
"""
backend_url = "{}://{}{}".format(scheme, netloc, path)
try:
response = self.http_request.request(backend_url, method=method, body=body, headers=dict(heade... | def function[_handle_request, parameter[self, scheme, netloc, path, headers, body, method]]:
constant[
Run the actual request
]
variable[backend_url] assign[=] call[constant[{}://{}{}].format, parameter[name[scheme], name[netloc], name[path]]]
<ast.Try object at 0x7da1affe5990> | keyword[def] identifier[_handle_request] ( identifier[self] , identifier[scheme] , identifier[netloc] , identifier[path] , identifier[headers] , identifier[body] = keyword[None] , identifier[method] = literal[string] ):
literal[string]
identifier[backend_url] = literal[string] . identifier[format] ... | def _handle_request(self, scheme, netloc, path, headers, body=None, method='GET'):
"""
Run the actual request
"""
backend_url = '{}://{}{}'.format(scheme, netloc, path)
try:
response = self.http_request.request(backend_url, method=method, body=body, headers=dict(headers))
sel... |
def _get_go2nt(self, goids):
"""Get go2nt for given goids."""
go2nt_all = self.grprobj.go2nt
return {go:go2nt_all[go] for go in goids} | def function[_get_go2nt, parameter[self, goids]]:
constant[Get go2nt for given goids.]
variable[go2nt_all] assign[=] name[self].grprobj.go2nt
return[<ast.DictComp object at 0x7da20c6a98d0>] | keyword[def] identifier[_get_go2nt] ( identifier[self] , identifier[goids] ):
literal[string]
identifier[go2nt_all] = identifier[self] . identifier[grprobj] . identifier[go2nt]
keyword[return] { identifier[go] : identifier[go2nt_all] [ identifier[go] ] keyword[for] identifier[go] keywor... | def _get_go2nt(self, goids):
"""Get go2nt for given goids."""
go2nt_all = self.grprobj.go2nt
return {go: go2nt_all[go] for go in goids} |
def get_and_cache_account(self, addr):
"""Gets and caches an account for an addres, creates blank if not
found.
:param addr:
:return:
"""
if addr in self.cache:
return self.cache[addr]
rlpdata = self.secure_trie.get(addr)
if (
rlp... | def function[get_and_cache_account, parameter[self, addr]]:
constant[Gets and caches an account for an addres, creates blank if not
found.
:param addr:
:return:
]
if compare[name[addr] in name[self].cache] begin[:]
return[call[name[self].cache][name[addr]]]
... | keyword[def] identifier[get_and_cache_account] ( identifier[self] , identifier[addr] ):
literal[string]
keyword[if] identifier[addr] keyword[in] identifier[self] . identifier[cache] :
keyword[return] identifier[self] . identifier[cache] [ identifier[addr] ]
identifier[rlp... | def get_and_cache_account(self, addr):
"""Gets and caches an account for an addres, creates blank if not
found.
:param addr:
:return:
"""
if addr in self.cache:
return self.cache[addr] # depends on [control=['if'], data=['addr']]
rlpdata = self.secure_trie.get(addr)... |
def remove(self):
"""
Remove the PID file.
"""
if isfile(self.pid_file):
try:
remove(self.pid_file)
except Exception as e:
self.die('Failed to remove PID file: {}'.format(str(e)))
else:
return True | def function[remove, parameter[self]]:
constant[
Remove the PID file.
]
if call[name[isfile], parameter[name[self].pid_file]] begin[:]
<ast.Try object at 0x7da18f722dd0> | keyword[def] identifier[remove] ( identifier[self] ):
literal[string]
keyword[if] identifier[isfile] ( identifier[self] . identifier[pid_file] ):
keyword[try] :
identifier[remove] ( identifier[self] . identifier[pid_file] )
keyword[except] identifier[Exc... | def remove(self):
"""
Remove the PID file.
"""
if isfile(self.pid_file):
try:
remove(self.pid_file) # depends on [control=['try'], data=[]]
except Exception as e:
self.die('Failed to remove PID file: {}'.format(str(e))) # depends on [control=['except'], ... |
def add_filehandler(level, fmt, filename, mode, backup_count, limit, when):
"""Add a file handler to the global logger."""
kwargs = {}
# If the filename is not set, use the default filename
if filename is None:
filename = getattr(sys.modules['__main__'], '__file__', 'log.py')
filename ... | def function[add_filehandler, parameter[level, fmt, filename, mode, backup_count, limit, when]]:
constant[Add a file handler to the global logger.]
variable[kwargs] assign[=] dictionary[[], []]
if compare[name[filename] is constant[None]] begin[:]
variable[filename] assign[=] cal... | keyword[def] identifier[add_filehandler] ( identifier[level] , identifier[fmt] , identifier[filename] , identifier[mode] , identifier[backup_count] , identifier[limit] , identifier[when] ):
literal[string]
identifier[kwargs] ={}
keyword[if] identifier[filename] keyword[is] keyword[None] :
... | def add_filehandler(level, fmt, filename, mode, backup_count, limit, when):
"""Add a file handler to the global logger."""
kwargs = {}
# If the filename is not set, use the default filename
if filename is None:
filename = getattr(sys.modules['__main__'], '__file__', 'log.py')
filename = ... |
def WIFI(frame, no_rtap=False):
"""calls wifi packet discriminator and constructor.
:frame: ctypes.Structure
:no_rtap: Bool
:return: packet object in success
:return: int
-1 on known error
:return: int
-2 on unknown error
"""
pack = None
try:
pack = WiHelper.g... | def function[WIFI, parameter[frame, no_rtap]]:
constant[calls wifi packet discriminator and constructor.
:frame: ctypes.Structure
:no_rtap: Bool
:return: packet object in success
:return: int
-1 on known error
:return: int
-2 on unknown error
]
variable[pack] assi... | keyword[def] identifier[WIFI] ( identifier[frame] , identifier[no_rtap] = keyword[False] ):
literal[string]
identifier[pack] = keyword[None]
keyword[try] :
identifier[pack] = identifier[WiHelper] . identifier[get_wifi_packet] ( identifier[frame] , identifier[no_rtap] )
keyword[except] ... | def WIFI(frame, no_rtap=False):
"""calls wifi packet discriminator and constructor.
:frame: ctypes.Structure
:no_rtap: Bool
:return: packet object in success
:return: int
-1 on known error
:return: int
-2 on unknown error
"""
pack = None
try:
pack = WiHelper.g... |
def _uses_aiohttp_session(func):
"""This is a decorator that creates an async with statement around a function, and makes sure that a _session argument is always passed.
Only usable on async functions of course.
The _session argument is (supposed to be) an aiohttp.ClientSession instance in all f... | def function[_uses_aiohttp_session, parameter[func]]:
constant[This is a decorator that creates an async with statement around a function, and makes sure that a _session argument is always passed.
Only usable on async functions of course.
The _session argument is (supposed to be) an aiohttp.Clie... | keyword[def] identifier[_uses_aiohttp_session] ( identifier[func] ):
literal[string]
keyword[async] keyword[def] identifier[decorated_func] (* identifier[args] , identifier[session] = keyword[None] ,** identifier[kwargs] ):
keyword[if] identifier[session] keyword[is] key... | def _uses_aiohttp_session(func):
"""This is a decorator that creates an async with statement around a function, and makes sure that a _session argument is always passed.
Only usable on async functions of course.
The _session argument is (supposed to be) an aiohttp.ClientSession instance in all funct... |
def filter_convolve(data, filters, filter_rot=False, method='scipy'):
r"""Filter convolve
This method convolves the input image with the wavelet filters
Parameters
----------
data : np.ndarray
Input data, 2D array
filters : np.ndarray
Wavelet filters, 3D array
filter_rot : ... | def function[filter_convolve, parameter[data, filters, filter_rot, method]]:
constant[Filter convolve
This method convolves the input image with the wavelet filters
Parameters
----------
data : np.ndarray
Input data, 2D array
filters : np.ndarray
Wavelet filters, 3D array
... | keyword[def] identifier[filter_convolve] ( identifier[data] , identifier[filters] , identifier[filter_rot] = keyword[False] , identifier[method] = literal[string] ):
literal[string]
keyword[if] identifier[filter_rot] :
keyword[return] identifier[np] . identifier[sum] ([ identifier[convolve] ( i... | def filter_convolve(data, filters, filter_rot=False, method='scipy'):
"""Filter convolve
This method convolves the input image with the wavelet filters
Parameters
----------
data : np.ndarray
Input data, 2D array
filters : np.ndarray
Wavelet filters, 3D array
filter_rot : b... |
def hosts_to_endpoints(hosts, port=2181):
"""
return a list of (host, port) tuples from a given host[:port],... str
"""
endpoints = []
for host in hosts.split(","):
endpoints.append(tuple(host.rsplit(":", 1)) if ":" in host else (host, port))
return endpoints | def function[hosts_to_endpoints, parameter[hosts, port]]:
constant[
return a list of (host, port) tuples from a given host[:port],... str
]
variable[endpoints] assign[=] list[[]]
for taget[name[host]] in starred[call[name[hosts].split, parameter[constant[,]]]] begin[:]
ca... | keyword[def] identifier[hosts_to_endpoints] ( identifier[hosts] , identifier[port] = literal[int] ):
literal[string]
identifier[endpoints] =[]
keyword[for] identifier[host] keyword[in] identifier[hosts] . identifier[split] ( literal[string] ):
identifier[endpoints] . identifier[append] ( i... | def hosts_to_endpoints(hosts, port=2181):
"""
return a list of (host, port) tuples from a given host[:port],... str
"""
endpoints = []
for host in hosts.split(','):
endpoints.append(tuple(host.rsplit(':', 1)) if ':' in host else (host, port)) # depends on [control=['for'], data=['host']]
... |
def predict(self, data, output_margin=False, ntree_limit=0, pred_leaf=False):
"""
Predict with data.
NOTE: This function is not thread safe.
For each booster object, predict can only be called from one thread.
If you want to run prediction using multiple thread, call... | def function[predict, parameter[self, data, output_margin, ntree_limit, pred_leaf]]:
constant[
Predict with data.
NOTE: This function is not thread safe.
For each booster object, predict can only be called from one thread.
If you want to run prediction using multiple... | keyword[def] identifier[predict] ( identifier[self] , identifier[data] , identifier[output_margin] = keyword[False] , identifier[ntree_limit] = literal[int] , identifier[pred_leaf] = keyword[False] ):
literal[string]
identifier[option_mask] = literal[int]
keyword[if] identifier[output_ma... | def predict(self, data, output_margin=False, ntree_limit=0, pred_leaf=False):
"""
Predict with data.
NOTE: This function is not thread safe.
For each booster object, predict can only be called from one thread.
If you want to run prediction using multiple thread, call bst... |
def get_cluster_config(
cluster_type,
cluster_name=None,
kafka_topology_base_path=None,
):
"""Return the cluster configuration.
Use the local cluster if cluster_name is not specified.
:param cluster_type: the type of the cluster
:type cluster_type: string
:param cluster_name: the name o... | def function[get_cluster_config, parameter[cluster_type, cluster_name, kafka_topology_base_path]]:
constant[Return the cluster configuration.
Use the local cluster if cluster_name is not specified.
:param cluster_type: the type of the cluster
:type cluster_type: string
:param cluster_name: the ... | keyword[def] identifier[get_cluster_config] (
identifier[cluster_type] ,
identifier[cluster_name] = keyword[None] ,
identifier[kafka_topology_base_path] = keyword[None] ,
):
literal[string]
keyword[if] keyword[not] identifier[kafka_topology_base_path] :
identifier[config_dirs] = identifier[ge... | def get_cluster_config(cluster_type, cluster_name=None, kafka_topology_base_path=None):
"""Return the cluster configuration.
Use the local cluster if cluster_name is not specified.
:param cluster_type: the type of the cluster
:type cluster_type: string
:param cluster_name: the name of the cluster
... |
def power(maf=0.5,beta=0.1, N=100, cutoff=5e-8):
"""
estimate power for a given allele frequency, effect size beta and sample size N
Assumption:
z-score = beta_ML distributed as p(0) = N(0,1.0(maf*(1-maf)*N))) under the null hypothesis
the actual beta_ML is distributed as p(alt) = N( beta , 1.0/(maf*(1-maf)N) )... | def function[power, parameter[maf, beta, N, cutoff]]:
constant[
estimate power for a given allele frequency, effect size beta and sample size N
Assumption:
z-score = beta_ML distributed as p(0) = N(0,1.0(maf*(1-maf)*N))) under the null hypothesis
the actual beta_ML is distributed as p(alt) = N( beta , 1.... | keyword[def] identifier[power] ( identifier[maf] = literal[int] , identifier[beta] = literal[int] , identifier[N] = literal[int] , identifier[cutoff] = literal[int] ):
literal[string]
literal[string]
keyword[assert] identifier[maf] >= literal[int] keyword[and] identifier[maf] <= literal[int] , literal[str... | def power(maf=0.5, beta=0.1, N=100, cutoff=5e-08):
"""
estimate power for a given allele frequency, effect size beta and sample size N
Assumption:
z-score = beta_ML distributed as p(0) = N(0,1.0(maf*(1-maf)*N))) under the null hypothesis
the actual beta_ML is distributed as p(alt) = N( beta , 1.0/(maf*(1-maf... |
def mat_to_numpy_arr(self):
''' convert list to numpy array - numpy arrays can not be saved as json '''
import numpy as np
self.dat['mat'] = np.asarray(self.dat['mat']) | def function[mat_to_numpy_arr, parameter[self]]:
constant[ convert list to numpy array - numpy arrays can not be saved as json ]
import module[numpy] as alias[np]
call[name[self].dat][constant[mat]] assign[=] call[name[np].asarray, parameter[call[name[self].dat][constant[mat]]]] | keyword[def] identifier[mat_to_numpy_arr] ( identifier[self] ):
literal[string]
keyword[import] identifier[numpy] keyword[as] identifier[np]
identifier[self] . identifier[dat] [ literal[string] ]= identifier[np] . identifier[asarray] ( identifier[self] . identifier[dat] [ literal[string] ]) | def mat_to_numpy_arr(self):
""" convert list to numpy array - numpy arrays can not be saved as json """
import numpy as np
self.dat['mat'] = np.asarray(self.dat['mat']) |
def read(config_file, configspec, server_mode=False, default_section='default_settings', list_values=True):
'''
Read the config file with spec validation
'''
# configspec = ConfigObj(path.join(path.abspath(path.dirname(__file__)), configspec),
# encoding='UTF8',
# ... | def function[read, parameter[config_file, configspec, server_mode, default_section, list_values]]:
constant[
Read the config file with spec validation
]
variable[config] assign[=] call[name[ConfigObj], parameter[name[config_file]]]
variable[validation] assign[=] call[name[config].validat... | keyword[def] identifier[read] ( identifier[config_file] , identifier[configspec] , identifier[server_mode] = keyword[False] , identifier[default_section] = literal[string] , identifier[list_values] = keyword[True] ):
literal[string]
identifier[config] = identifier[ConfigObj] ( iden... | def read(config_file, configspec, server_mode=False, default_section='default_settings', list_values=True):
"""
Read the config file with spec validation
"""
# configspec = ConfigObj(path.join(path.abspath(path.dirname(__file__)), configspec),
# encoding='UTF8',
# ... |
def serviceQueues(self, limit=None):
"""
Process `limit` number of messages in the inBox.
:param limit: the maximum number of messages to process
:return: the number of messages successfully processed
"""
# TODO should handle SuspiciousNode here
r = self.dequeue_... | def function[serviceQueues, parameter[self, limit]]:
constant[
Process `limit` number of messages in the inBox.
:param limit: the maximum number of messages to process
:return: the number of messages successfully processed
]
variable[r] assign[=] call[name[self].dequeue_... | keyword[def] identifier[serviceQueues] ( identifier[self] , identifier[limit] = keyword[None] ):
literal[string]
identifier[r] = identifier[self] . identifier[dequeue_pre_prepares] ()
identifier[r] += identifier[self] . identifier[inBoxRouter] . identifier[handleAllSync] ( identif... | def serviceQueues(self, limit=None):
"""
Process `limit` number of messages in the inBox.
:param limit: the maximum number of messages to process
:return: the number of messages successfully processed
"""
# TODO should handle SuspiciousNode here
r = self.dequeue_pre_prepares... |
def surfacemass_z(self,R,nz=7,zmax=1.,fixed_quad=True,fixed_order=8,
**kwargs):
"""
NAME:
surfacemass_z
PURPOSE:
calculate the vertically-integrated surface density
INPUT:
R - Galactocentric radius (can be Quantity)
... | def function[surfacemass_z, parameter[self, R, nz, zmax, fixed_quad, fixed_order]]:
constant[
NAME:
surfacemass_z
PURPOSE:
calculate the vertically-integrated surface density
INPUT:
R - Galactocentric radius (can be Quantity)
fixed_quad= ... | keyword[def] identifier[surfacemass_z] ( identifier[self] , identifier[R] , identifier[nz] = literal[int] , identifier[zmax] = literal[int] , identifier[fixed_quad] = keyword[True] , identifier[fixed_order] = literal[int] ,
** identifier[kwargs] ):
literal[string]
keyword[if] identifier[fixed_quad... | def surfacemass_z(self, R, nz=7, zmax=1.0, fixed_quad=True, fixed_order=8, **kwargs):
"""
NAME:
surfacemass_z
PURPOSE:
calculate the vertically-integrated surface density
INPUT:
R - Galactocentric radius (can be Quantity)
fixed_quad= if True ... |
def plot_whiteness(var, h, repeats=1000, axis=None):
""" Draw distribution of the Portmanteu whiteness test.
Parameters
----------
var : :class:`~scot.var.VARBase`-like object
Vector autoregressive model (VAR) object whose residuals are tested for whiteness.
h : int
Maximum lag to i... | def function[plot_whiteness, parameter[var, h, repeats, axis]]:
constant[ Draw distribution of the Portmanteu whiteness test.
Parameters
----------
var : :class:`~scot.var.VARBase`-like object
Vector autoregressive model (VAR) object whose residuals are tested for whiteness.
h : int
... | keyword[def] identifier[plot_whiteness] ( identifier[var] , identifier[h] , identifier[repeats] = literal[int] , identifier[axis] = keyword[None] ):
literal[string]
identifier[pr] , identifier[q0] , identifier[q] = identifier[var] . identifier[test_whiteness] ( identifier[h] , identifier[repeats] , keyword... | def plot_whiteness(var, h, repeats=1000, axis=None):
""" Draw distribution of the Portmanteu whiteness test.
Parameters
----------
var : :class:`~scot.var.VARBase`-like object
Vector autoregressive model (VAR) object whose residuals are tested for whiteness.
h : int
Maximum lag to i... |
def loop(self):
'''
Tracks the time in a loop. The estimated time to completion
can be calculated and if verbose is set to *True*, the object will print
estimated time to completion, and percent complete.
Actived in every loop to keep track'''
self.count += 1
sel... | def function[loop, parameter[self]]:
constant[
Tracks the time in a loop. The estimated time to completion
can be calculated and if verbose is set to *True*, the object will print
estimated time to completion, and percent complete.
Actived in every loop to keep track]
<ast.Au... | keyword[def] identifier[loop] ( identifier[self] ):
literal[string]
identifier[self] . identifier[count] += literal[int]
identifier[self] . identifier[tf] = identifier[time] . identifier[time] ()
identifier[self] . identifier[elapsed] = identifier[self] . identifier[tf] - identi... | def loop(self):
"""
Tracks the time in a loop. The estimated time to completion
can be calculated and if verbose is set to *True*, the object will print
estimated time to completion, and percent complete.
Actived in every loop to keep track"""
self.count += 1
self.tf = time.t... |
def radius_server_host_key(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
radius_server = ET.SubElement(config, "radius-server", xmlns="urn:brocade.com:mgmt:brocade-aaa")
host = ET.SubElement(radius_server, "host")
hostname_key = ET.SubElement(h... | def function[radius_server_host_key, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[radius_server] assign[=] call[name[ET].SubElement, parameter[name[config], constant[radius-server]]]
varia... | keyword[def] identifier[radius_server_host_key] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[radius_server] = identifier[ET] . identifier[SubElement] ( identifier[config] , literal[stri... | def radius_server_host_key(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
radius_server = ET.SubElement(config, 'radius-server', xmlns='urn:brocade.com:mgmt:brocade-aaa')
host = ET.SubElement(radius_server, 'host')
hostname_key = ET.SubElement(host, 'hostname')
... |
def load(self, callback=None, errback=None, reload=False):
"""
Load Scopegroup data from the API.
"""
if not reload and self.data:
raise ScopegroupException('Scope Group already loaded')
def success(result, *args):
self.data = result
self.id =... | def function[load, parameter[self, callback, errback, reload]]:
constant[
Load Scopegroup data from the API.
]
if <ast.BoolOp object at 0x7da204621de0> begin[:]
<ast.Raise object at 0x7da204620af0>
def function[success, parameter[result]]:
name[self].data ... | keyword[def] identifier[load] ( identifier[self] , identifier[callback] = keyword[None] , identifier[errback] = keyword[None] , identifier[reload] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[reload] keyword[and] identifier[self] . identifier[data] :
keyw... | def load(self, callback=None, errback=None, reload=False):
"""
Load Scopegroup data from the API.
"""
if not reload and self.data:
raise ScopegroupException('Scope Group already loaded') # depends on [control=['if'], data=[]]
def success(result, *args):
self.data = result
... |
def ids_for(self, city_name, country=None, matching='nocase'):
"""
Returns a list of tuples in the form (long, str, str) corresponding to
the int IDs and relative toponyms and 2-chars country of the cities
matching the provided city name.
The rule for identifying matchings is acc... | def function[ids_for, parameter[self, city_name, country, matching]]:
constant[
Returns a list of tuples in the form (long, str, str) corresponding to
the int IDs and relative toponyms and 2-chars country of the cities
matching the provided city name.
The rule for identifying mat... | keyword[def] identifier[ids_for] ( identifier[self] , identifier[city_name] , identifier[country] = keyword[None] , identifier[matching] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[city_name] :
keyword[return] []
keyword[if] identifier[matching]... | def ids_for(self, city_name, country=None, matching='nocase'):
"""
Returns a list of tuples in the form (long, str, str) corresponding to
the int IDs and relative toponyms and 2-chars country of the cities
matching the provided city name.
The rule for identifying matchings is accordi... |
def get_element_with_id(self, id):
"""Return the element with the specified ID."""
# Should we maintain a hashmap of ids to make this more efficient? Probably overkill.
# TODO: Elements can contain nested elements (captions, footnotes, table cells, etc.)
return next((el for el in self.el... | def function[get_element_with_id, parameter[self, id]]:
constant[Return the element with the specified ID.]
return[call[name[next], parameter[<ast.GeneratorExp object at 0x7da18fe90a90>, constant[None]]]] | keyword[def] identifier[get_element_with_id] ( identifier[self] , identifier[id] ):
literal[string]
keyword[return] identifier[next] (( identifier[el] keyword[for] identifier[el] keyword[in] identifier[self] . identifier[elements] keyword[if] identifier[el] . identifier[id]... | def get_element_with_id(self, id):
"""Return the element with the specified ID."""
# Should we maintain a hashmap of ids to make this more efficient? Probably overkill.
# TODO: Elements can contain nested elements (captions, footnotes, table cells, etc.)
return next((el for el in self.elements if el.id ... |
def download_tabular_key_value(self, url, **kwargs):
# type: (str, Any) -> Dict
"""Download 2 column csv from url and return a dictionary of keys (first column) and values (second column)
Args:
url (str): URL to download
**kwargs:
headers (Union[int, List[int... | def function[download_tabular_key_value, parameter[self, url]]:
constant[Download 2 column csv from url and return a dictionary of keys (first column) and values (second column)
Args:
url (str): URL to download
**kwargs:
headers (Union[int, List[int], List[str]]): Nu... | keyword[def] identifier[download_tabular_key_value] ( identifier[self] , identifier[url] ,** identifier[kwargs] ):
literal[string]
identifier[output_dict] = identifier[dict] ()
keyword[for] identifier[row] keyword[in] identifier[self] . identifier[get_tabular_rows] ( identifier[url] ,*... | def download_tabular_key_value(self, url, **kwargs):
# type: (str, Any) -> Dict
'Download 2 column csv from url and return a dictionary of keys (first column) and values (second column)\n\n Args:\n url (str): URL to download\n **kwargs:\n headers (Union[int, List[int], Li... |
def check(text):
"""Check the text."""
err = "oxymorons.misc"
msg = u"'{}' is an oxymoron."
oxymorons = [
"amateur expert",
"increasingly less",
"advancing backwards?",
"alludes explicitly to",
"explicitly alludes to",
"totally obsolescent",
"comp... | def function[check, parameter[text]]:
constant[Check the text.]
variable[err] assign[=] constant[oxymorons.misc]
variable[msg] assign[=] constant['{}' is an oxymoron.]
variable[oxymorons] assign[=] list[[<ast.Constant object at 0x7da1b0862680>, <ast.Constant object at 0x7da1b0862740>, <a... | keyword[def] identifier[check] ( identifier[text] ):
literal[string]
identifier[err] = literal[string]
identifier[msg] = literal[string]
identifier[oxymorons] =[
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
literal[stri... | def check(text):
"""Check the text."""
err = 'oxymorons.misc'
msg = u"'{}' is an oxymoron."
# "pretty ugly",
# "sure bet",
# "executive secretary",
oxymorons = ['amateur expert', 'increasingly less', 'advancing backwards?', 'alludes explicitly to', 'explicitly alludes to', 'totally obsolesce... |
def simulate(t=1000, poly=(0.,), sinusoids=None, sigma=0, rw=0, irw=0, rrw=0):
"""Simulate a random signal with seasonal (sinusoids), linear and quadratic trend, RW, IRW, and RRW
Arguments:
t (int or list of float): number of samples or time vector, default = 1000
poly (list of float): polynomial c... | def function[simulate, parameter[t, poly, sinusoids, sigma, rw, irw, rrw]]:
constant[Simulate a random signal with seasonal (sinusoids), linear and quadratic trend, RW, IRW, and RRW
Arguments:
t (int or list of float): number of samples or time vector, default = 1000
poly (list of float): polyn... | keyword[def] identifier[simulate] ( identifier[t] = literal[int] , identifier[poly] =( literal[int] ,), identifier[sinusoids] = keyword[None] , identifier[sigma] = literal[int] , identifier[rw] = literal[int] , identifier[irw] = literal[int] , identifier[rrw] = literal[int] ):
literal[string]
keyword[if] ... | def simulate(t=1000, poly=(0.0,), sinusoids=None, sigma=0, rw=0, irw=0, rrw=0):
"""Simulate a random signal with seasonal (sinusoids), linear and quadratic trend, RW, IRW, and RRW
Arguments:
t (int or list of float): number of samples or time vector, default = 1000
poly (list of float): polynomial ... |
def merge_cycles(self):
"""Work on this graph and remove cycles, with nodes containing concatonated lists of payloads"""
while True:
### remove any self edges
own_edges = self.get_self_edges()
if len(own_edges) > 0:
for e in own_edges: self.remove_edge(e)
c = ... | def function[merge_cycles, parameter[self]]:
constant[Work on this graph and remove cycles, with nodes containing concatonated lists of payloads]
while constant[True] begin[:]
variable[own_edges] assign[=] call[name[self].get_self_edges, parameter[]]
if compare[call[name[... | keyword[def] identifier[merge_cycles] ( identifier[self] ):
literal[string]
keyword[while] keyword[True] :
identifier[own_edges] = identifier[self] . identifier[get_self_edges] ()
keyword[if] identifier[len] ( identifier[own_edges] )> literal[int] :
keyword[for... | def merge_cycles(self):
"""Work on this graph and remove cycles, with nodes containing concatonated lists of payloads"""
while True:
### remove any self edges
own_edges = self.get_self_edges()
if len(own_edges) > 0:
for e in own_edges:
self.remove_edge(e) # d... |
def dict_to_htmlrow(d):
"""
converts a dictionary to a HTML table row
"""
res = "<TR>\n"
for k, v in d.items():
if type(v) == str:
res = res + '<TD><p>' + k + ':</p></TD><TD><p>' + v + '</p></TD>'
else:
res = res + '<TD><p>' + k + ':</p></TD><TD><p>' + str(v) ... | def function[dict_to_htmlrow, parameter[d]]:
constant[
converts a dictionary to a HTML table row
]
variable[res] assign[=] constant[<TR>
]
for taget[tuple[[<ast.Name object at 0x7da18f00f430>, <ast.Name object at 0x7da18f00ff70>]]] in starred[call[name[d].items, parameter[]]] begin[:]
... | keyword[def] identifier[dict_to_htmlrow] ( identifier[d] ):
literal[string]
identifier[res] = literal[string]
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[d] . identifier[items] ():
keyword[if] identifier[type] ( identifier[v] )== identifier[str] :
ident... | def dict_to_htmlrow(d):
"""
converts a dictionary to a HTML table row
"""
res = '<TR>\n'
for (k, v) in d.items():
if type(v) == str:
res = res + '<TD><p>' + k + ':</p></TD><TD><p>' + v + '</p></TD>' # depends on [control=['if'], data=[]]
else:
res = res + '<T... |
def translate(self, frame=0):
'''Returns a Fasta sequence, translated into amino acids. Starts translating from 'frame', where frame expected to be 0,1 or 2'''
return Fasta(self.id, ''.join([genetic_codes.codes[genetic_code].get(self.seq[x:x+3].upper(), 'X') for x in range(frame, len(self)-1-frame, 3)])... | def function[translate, parameter[self, frame]]:
constant[Returns a Fasta sequence, translated into amino acids. Starts translating from 'frame', where frame expected to be 0,1 or 2]
return[call[name[Fasta], parameter[name[self].id, call[constant[].join, parameter[<ast.ListComp object at 0x7da1affe5ff0>]]]]... | keyword[def] identifier[translate] ( identifier[self] , identifier[frame] = literal[int] ):
literal[string]
keyword[return] identifier[Fasta] ( identifier[self] . identifier[id] , literal[string] . identifier[join] ([ identifier[genetic_codes] . identifier[codes] [ identifier[genetic_code] ]. iden... | def translate(self, frame=0):
"""Returns a Fasta sequence, translated into amino acids. Starts translating from 'frame', where frame expected to be 0,1 or 2"""
return Fasta(self.id, ''.join([genetic_codes.codes[genetic_code].get(self.seq[x:x + 3].upper(), 'X') for x in range(frame, len(self) - 1 - frame, 3)])) |
def last(self, values, axis=0):
"""return values at last occurance of its associated key
Parameters
----------
values : array_like, [keys, ...]
values to pick the last value of per group
axis : int, optional
alternative reduction axis for values
... | def function[last, parameter[self, values, axis]]:
constant[return values at last occurance of its associated key
Parameters
----------
values : array_like, [keys, ...]
values to pick the last value of per group
axis : int, optional
alternative reduction ... | keyword[def] identifier[last] ( identifier[self] , identifier[values] , identifier[axis] = literal[int] ):
literal[string]
identifier[values] = identifier[np] . identifier[asarray] ( identifier[values] )
keyword[return] identifier[self] . identifier[unique] , identifier[np] . identifier[t... | def last(self, values, axis=0):
"""return values at last occurance of its associated key
Parameters
----------
values : array_like, [keys, ...]
values to pick the last value of per group
axis : int, optional
alternative reduction axis for values
Retu... |
def head(self, x, y, layers=None, aq=None):
"""Head at `x`, `y`
Returns
-------
h : array length `naq` or `len(layers)`
head in all `layers` (if not `None`), or all layers of aquifer (otherwise)
"""
if aq is None: aq = self.aq.find_a... | def function[head, parameter[self, x, y, layers, aq]]:
constant[Head at `x`, `y`
Returns
-------
h : array length `naq` or `len(layers)`
head in all `layers` (if not `None`), or all layers of aquifer (otherwise)
]
if compare[name[aq] is const... | keyword[def] identifier[head] ( identifier[self] , identifier[x] , identifier[y] , identifier[layers] = keyword[None] , identifier[aq] = keyword[None] ):
literal[string]
keyword[if] identifier[aq] keyword[is] keyword[None] : identifier[aq] = identifier[self] . identifier[aq] . identifier[find_a... | def head(self, x, y, layers=None, aq=None):
"""Head at `x`, `y`
Returns
-------
h : array length `naq` or `len(layers)`
head in all `layers` (if not `None`), or all layers of aquifer (otherwise)
"""
if aq is None:
aq = self.aq.find_aquifer_da... |
def convert_idx_to_name(self, y, lens):
"""Convert label index to name.
Args:
y (list): label index list.
lens (list): true length of y.
Returns:
y: label name list.
Examples:
>>> # assumes that id2label = {1: 'B-LOC', 2: 'I-LOC'}
... | def function[convert_idx_to_name, parameter[self, y, lens]]:
constant[Convert label index to name.
Args:
y (list): label index list.
lens (list): true length of y.
Returns:
y: label name list.
Examples:
>>> # assumes that id2label = {1: ... | keyword[def] identifier[convert_idx_to_name] ( identifier[self] , identifier[y] , identifier[lens] ):
literal[string]
identifier[y] =[[ identifier[self] . identifier[id2label] [ identifier[idx] ] keyword[for] identifier[idx] keyword[in] identifier[row] [: identifier[l] ]]
keyword[for] ... | def convert_idx_to_name(self, y, lens):
"""Convert label index to name.
Args:
y (list): label index list.
lens (list): true length of y.
Returns:
y: label name list.
Examples:
>>> # assumes that id2label = {1: 'B-LOC', 2: 'I-LOC'}
... |
def _generate_label_matrix(self):
"""Generate an [n,m] label matrix with entries in {0,...,k}"""
self.L = np.zeros((self.n, self.m))
self.Y = np.zeros(self.n, dtype=np.int64)
for i in range(self.n):
y = choice(self.k, p=self.p) + 1 # Note that y \in {1,...,k}
sel... | def function[_generate_label_matrix, parameter[self]]:
constant[Generate an [n,m] label matrix with entries in {0,...,k}]
name[self].L assign[=] call[name[np].zeros, parameter[tuple[[<ast.Attribute object at 0x7da1b1b47880>, <ast.Attribute object at 0x7da1b1b47190>]]]]
name[self].Y assign[=] cal... | keyword[def] identifier[_generate_label_matrix] ( identifier[self] ):
literal[string]
identifier[self] . identifier[L] = identifier[np] . identifier[zeros] (( identifier[self] . identifier[n] , identifier[self] . identifier[m] ))
identifier[self] . identifier[Y] = identifier[np] . identifi... | def _generate_label_matrix(self):
"""Generate an [n,m] label matrix with entries in {0,...,k}"""
self.L = np.zeros((self.n, self.m))
self.Y = np.zeros(self.n, dtype=np.int64)
for i in range(self.n):
y = choice(self.k, p=self.p) + 1 # Note that y \in {1,...,k}
self.Y[i] = y
for j... |
def addClass(self, className):
'''
addClass - append a class name to the end of the "class" attribute, if not present
@param className <str> - The name of the class to add
'''
className = stripWordsOnly(className)
if not className:
return None
... | def function[addClass, parameter[self, className]]:
constant[
addClass - append a class name to the end of the "class" attribute, if not present
@param className <str> - The name of the class to add
]
variable[className] assign[=] call[name[stripWordsOnly], parameter... | keyword[def] identifier[addClass] ( identifier[self] , identifier[className] ):
literal[string]
identifier[className] = identifier[stripWordsOnly] ( identifier[className] )
keyword[if] keyword[not] identifier[className] :
keyword[return] keyword[None]
keyword[if... | def addClass(self, className):
"""
addClass - append a class name to the end of the "class" attribute, if not present
@param className <str> - The name of the class to add
"""
className = stripWordsOnly(className)
if not className:
return None # depends on [cont... |
def replace_greek(self, name):
"""Replace text representing greek letters with greek letters."""
name = name.replace('gamma-delta', 'gammadelta')
name = name.replace('interleukin-1 beta', 'interleukin-1beta')
greek_present = False
for greek_txt, uni in self.greek2uni.items():
... | def function[replace_greek, parameter[self, name]]:
constant[Replace text representing greek letters with greek letters.]
variable[name] assign[=] call[name[name].replace, parameter[constant[gamma-delta], constant[gammadelta]]]
variable[name] assign[=] call[name[name].replace, parameter[constant... | keyword[def] identifier[replace_greek] ( identifier[self] , identifier[name] ):
literal[string]
identifier[name] = identifier[name] . identifier[replace] ( literal[string] , literal[string] )
identifier[name] = identifier[name] . identifier[replace] ( literal[string] , literal[string] )
... | def replace_greek(self, name):
"""Replace text representing greek letters with greek letters."""
name = name.replace('gamma-delta', 'gammadelta')
name = name.replace('interleukin-1 beta', 'interleukin-1beta')
greek_present = False
for (greek_txt, uni) in self.greek2uni.items():
if greek_txt ... |
async def sinterstore(self, dest, keys, *args):
"""
Store the intersection of sets specified by ``keys`` into a new
set named ``dest``. Returns the number of keys in the new set.
"""
args = list_or_args(keys, args)
return await self.execute_command('SINTERSTORE', dest, *... | <ast.AsyncFunctionDef object at 0x7da1b077b850> | keyword[async] keyword[def] identifier[sinterstore] ( identifier[self] , identifier[dest] , identifier[keys] ,* identifier[args] ):
literal[string]
identifier[args] = identifier[list_or_args] ( identifier[keys] , identifier[args] )
keyword[return] keyword[await] identifier[self] . ident... | async def sinterstore(self, dest, keys, *args):
"""
Store the intersection of sets specified by ``keys`` into a new
set named ``dest``. Returns the number of keys in the new set.
"""
args = list_or_args(keys, args)
return await self.execute_command('SINTERSTORE', dest, *args) |
def popen(self, args, **kwargs):
"""
creates a subprocess with passed args
"""
self.log.debug("popen %s", ' '.join(args))
return vaping.io.subprocess.Popen(args, **kwargs) | def function[popen, parameter[self, args]]:
constant[
creates a subprocess with passed args
]
call[name[self].log.debug, parameter[constant[popen %s], call[constant[ ].join, parameter[name[args]]]]]
return[call[name[vaping].io.subprocess.Popen, parameter[name[args]]]] | keyword[def] identifier[popen] ( identifier[self] , identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[log] . identifier[debug] ( literal[string] , literal[string] . identifier[join] ( identifier[args] ))
keyword[return] identifier[vaping] . identifie... | def popen(self, args, **kwargs):
"""
creates a subprocess with passed args
"""
self.log.debug('popen %s', ' '.join(args))
return vaping.io.subprocess.Popen(args, **kwargs) |
def relation(self, rel):
"""Process each relation."""
rel_type = rel.tags.get('type')
if any([rel.deleted,
not rel.visible,
not self.is_new_version(rel),
rel_type not in ['route', 'public_transport']]):
return
route_tag = rel.t... | def function[relation, parameter[self, rel]]:
constant[Process each relation.]
variable[rel_type] assign[=] call[name[rel].tags.get, parameter[constant[type]]]
if call[name[any], parameter[list[[<ast.Attribute object at 0x7da1b038b340>, <ast.UnaryOp object at 0x7da1b03883d0>, <ast.UnaryOp object... | keyword[def] identifier[relation] ( identifier[self] , identifier[rel] ):
literal[string]
identifier[rel_type] = identifier[rel] . identifier[tags] . identifier[get] ( literal[string] )
keyword[if] identifier[any] ([ identifier[rel] . identifier[deleted] ,
keyword[not] identifie... | def relation(self, rel):
"""Process each relation."""
rel_type = rel.tags.get('type')
if any([rel.deleted, not rel.visible, not self.is_new_version(rel), rel_type not in ['route', 'public_transport']]):
return # depends on [control=['if'], data=[]]
route_tag = rel.tags.get('route')
if rel_t... |
def nn_y(self, y, dims=None, k = 1, radius=np.inf, eps=0.0, p=2):
"""Find the k nearest neighbors of y in the observed output data
@see Databag.nn() for argument description
@return distance and indexes of found nearest neighbors.
"""
if dims is None:
assert len(y) =... | def function[nn_y, parameter[self, y, dims, k, radius, eps, p]]:
constant[Find the k nearest neighbors of y in the observed output data
@see Databag.nn() for argument description
@return distance and indexes of found nearest neighbors.
]
if compare[name[dims] is constant[None]] ... | keyword[def] identifier[nn_y] ( identifier[self] , identifier[y] , identifier[dims] = keyword[None] , identifier[k] = literal[int] , identifier[radius] = identifier[np] . identifier[inf] , identifier[eps] = literal[int] , identifier[p] = literal[int] ):
literal[string]
keyword[if] identifier[dims]... | def nn_y(self, y, dims=None, k=1, radius=np.inf, eps=0.0, p=2):
"""Find the k nearest neighbors of y in the observed output data
@see Databag.nn() for argument description
@return distance and indexes of found nearest neighbors.
"""
if dims is None:
assert len(y) == self.dim_y
... |
def tiles_from_bounds(self, bounds, zoom):
"""
Return all tiles intersecting with bounds.
Bounds values will be cleaned if they cross the antimeridian or are
outside of the Northern or Southern tile pyramid bounds.
Parameters
----------
bounds : tuple
... | def function[tiles_from_bounds, parameter[self, bounds, zoom]]:
constant[
Return all tiles intersecting with bounds.
Bounds values will be cleaned if they cross the antimeridian or are
outside of the Northern or Southern tile pyramid bounds.
Parameters
----------
... | keyword[def] identifier[tiles_from_bounds] ( identifier[self] , identifier[bounds] , identifier[zoom] ):
literal[string]
keyword[for] identifier[tile] keyword[in] identifier[self] . identifier[tiles_from_bbox] ( identifier[box] (* identifier[bounds] ), identifier[zoom] ):
keyword[yi... | def tiles_from_bounds(self, bounds, zoom):
"""
Return all tiles intersecting with bounds.
Bounds values will be cleaned if they cross the antimeridian or are
outside of the Northern or Southern tile pyramid bounds.
Parameters
----------
bounds : tuple
(l... |
def activate_membercard(self, membership_number, code, **kwargs):
"""
激活会员卡 - 接口激活方式
详情请参见
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025283
参数示例:
{
"init_bonus": 100,
"init_bonus_record":"旧积分同步",
"init_balance": 200,
... | def function[activate_membercard, parameter[self, membership_number, code]]:
constant[
激活会员卡 - 接口激活方式
详情请参见
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025283
参数示例:
{
"init_bonus": 100,
"init_bonus_record":"旧积分同步",
"init... | keyword[def] identifier[activate_membercard] ( identifier[self] , identifier[membership_number] , identifier[code] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= identifier[membership_number]
identifier[kwargs] [ literal[string] ]= identifier[code]
... | def activate_membercard(self, membership_number, code, **kwargs):
"""
激活会员卡 - 接口激活方式
详情请参见
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025283
参数示例:
{
"init_bonus": 100,
"init_bonus_record":"旧积分同步",
"init_balance": 200,
... |
def reset_stats_history(self):
"""Reset the stats history (dict of GlancesAttribute)."""
if self.history_enable():
reset_list = [a['name'] for a in self.get_items_history_list()]
logger.debug("Reset history for plugin {} (items: {})".format(self.plugin_name, reset_list))
... | def function[reset_stats_history, parameter[self]]:
constant[Reset the stats history (dict of GlancesAttribute).]
if call[name[self].history_enable, parameter[]] begin[:]
variable[reset_list] assign[=] <ast.ListComp object at 0x7da2044c02b0>
call[name[logger].debug, param... | keyword[def] identifier[reset_stats_history] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[history_enable] ():
identifier[reset_list] =[ identifier[a] [ literal[string] ] keyword[for] identifier[a] keyword[in] identifier[self] . identifier[get_item... | def reset_stats_history(self):
"""Reset the stats history (dict of GlancesAttribute)."""
if self.history_enable():
reset_list = [a['name'] for a in self.get_items_history_list()]
logger.debug('Reset history for plugin {} (items: {})'.format(self.plugin_name, reset_list))
self.stats_histo... |
def get_remote_content_len(self, remote, headers=None):
"""
:param remote:
:return: size of remote file
"""
if headers is None:
headers = self._get_default_request_headers()
req = urllib.request.Request(remote, headers=headers)
try:
resp... | def function[get_remote_content_len, parameter[self, remote, headers]]:
constant[
:param remote:
:return: size of remote file
]
if compare[name[headers] is constant[None]] begin[:]
variable[headers] assign[=] call[name[self]._get_default_request_headers, parameter... | keyword[def] identifier[get_remote_content_len] ( identifier[self] , identifier[remote] , identifier[headers] = keyword[None] ):
literal[string]
keyword[if] identifier[headers] keyword[is] keyword[None] :
identifier[headers] = identifier[self] . identifier[_get_default_request_head... | def get_remote_content_len(self, remote, headers=None):
"""
:param remote:
:return: size of remote file
"""
if headers is None:
headers = self._get_default_request_headers() # depends on [control=['if'], data=['headers']]
req = urllib.request.Request(remote, headers=headers)... |
def get_pub_id(title, authors, year):
"construct publication id"
if len(title.split(' ')) > 1 \
and title.split(' ')[0].lower() in ['the', 'a']:
_first_word = title.split(' ')[1].split('_')[0]
else:
_first_word = title.split(' ')[0].split('_')[0]
pub_id = authors[0].split(',')[0]... | def function[get_pub_id, parameter[title, authors, year]]:
constant[construct publication id]
if <ast.BoolOp object at 0x7da18dc06950> begin[:]
variable[_first_word] assign[=] call[call[call[call[name[title].split, parameter[constant[ ]]]][constant[1]].split, parameter[constant[_]]]][con... | keyword[def] identifier[get_pub_id] ( identifier[title] , identifier[authors] , identifier[year] ):
literal[string]
keyword[if] identifier[len] ( identifier[title] . identifier[split] ( literal[string] ))> literal[int] keyword[and] identifier[title] . identifier[split] ( literal[string] )[ literal[int] ... | def get_pub_id(title, authors, year):
"""construct publication id"""
if len(title.split(' ')) > 1 and title.split(' ')[0].lower() in ['the', 'a']:
_first_word = title.split(' ')[1].split('_')[0] # depends on [control=['if'], data=[]]
else:
_first_word = title.split(' ')[0].split('_')[0]
... |
def remove_callback(self, handle):
"""Remove a callback."""
if self._poll is None:
raise RuntimeError('poll instance is closed')
remove_callback(self, handle)
if handle.extra & READABLE:
self._readers -= 1
if handle.extra & WRITABLE:
self._writ... | def function[remove_callback, parameter[self, handle]]:
constant[Remove a callback.]
if compare[name[self]._poll is constant[None]] begin[:]
<ast.Raise object at 0x7da1b02461d0>
call[name[remove_callback], parameter[name[self], name[handle]]]
if binary_operation[name[handle].extr... | keyword[def] identifier[remove_callback] ( identifier[self] , identifier[handle] ):
literal[string]
keyword[if] identifier[self] . identifier[_poll] keyword[is] keyword[None] :
keyword[raise] identifier[RuntimeError] ( literal[string] )
identifier[remove_callback] ( identi... | def remove_callback(self, handle):
"""Remove a callback."""
if self._poll is None:
raise RuntimeError('poll instance is closed') # depends on [control=['if'], data=[]]
remove_callback(self, handle)
if handle.extra & READABLE:
self._readers -= 1 # depends on [control=['if'], data=[]]
... |
def poke(self, context):
"""
Execute the bash command in a temporary directory
which will be cleaned afterwards
"""
bash_command = self.bash_command
self.log.info("Tmp dir root location: \n %s", gettempdir())
with TemporaryDirectory(prefix='airflowtmp') as tmp_dir... | def function[poke, parameter[self, context]]:
constant[
Execute the bash command in a temporary directory
which will be cleaned afterwards
]
variable[bash_command] assign[=] name[self].bash_command
call[name[self].log.info, parameter[constant[Tmp dir root location:
%s],... | keyword[def] identifier[poke] ( identifier[self] , identifier[context] ):
literal[string]
identifier[bash_command] = identifier[self] . identifier[bash_command]
identifier[self] . identifier[log] . identifier[info] ( literal[string] , identifier[gettempdir] ())
keyword[with] ide... | def poke(self, context):
"""
Execute the bash command in a temporary directory
which will be cleaned afterwards
"""
bash_command = self.bash_command
self.log.info('Tmp dir root location: \n %s', gettempdir())
with TemporaryDirectory(prefix='airflowtmp') as tmp_dir:
with N... |
def set_window_geometry(geometry):
"""Set window geometry.
Parameters
==========
geometry : tuple (4 integers) or None
x, y, dx, dy values employed to set the Qt backend geometry.
"""
if geometry is not None:
x_geom, y_geom, dx_geom, dy_geom = geometry
mngr = plt.get_c... | def function[set_window_geometry, parameter[geometry]]:
constant[Set window geometry.
Parameters
==========
geometry : tuple (4 integers) or None
x, y, dx, dy values employed to set the Qt backend geometry.
]
if compare[name[geometry] is_not constant[None]] begin[:]
... | keyword[def] identifier[set_window_geometry] ( identifier[geometry] ):
literal[string]
keyword[if] identifier[geometry] keyword[is] keyword[not] keyword[None] :
identifier[x_geom] , identifier[y_geom] , identifier[dx_geom] , identifier[dy_geom] = identifier[geometry]
identifier[mngr... | def set_window_geometry(geometry):
"""Set window geometry.
Parameters
==========
geometry : tuple (4 integers) or None
x, y, dx, dy values employed to set the Qt backend geometry.
"""
if geometry is not None:
(x_geom, y_geom, dx_geom, dy_geom) = geometry
mngr = plt.get_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.