code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def all_tokens(self, delimiter=' '):
"""
Return a list of all tokens occurring in the label-list.
Args:
delimiter (str): The delimiter used to split labels into tokens
(see :meth:`audiomate.annotations.Label.tokenized`).
Returns:
:c... | def function[all_tokens, parameter[self, delimiter]]:
constant[
Return a list of all tokens occurring in the label-list.
Args:
delimiter (str): The delimiter used to split labels into tokens
(see :meth:`audiomate.annotations.Label.tokenized`).
R... | keyword[def] identifier[all_tokens] ( identifier[self] , identifier[delimiter] = literal[string] ):
literal[string]
identifier[tokens] = identifier[set] ()
keyword[for] identifier[label] keyword[in] identifier[self] :
identifier[tokens] = identifier[tokens] . identifier[un... | def all_tokens(self, delimiter=' '):
"""
Return a list of all tokens occurring in the label-list.
Args:
delimiter (str): The delimiter used to split labels into tokens
(see :meth:`audiomate.annotations.Label.tokenized`).
Returns:
:class... |
def domagicmag(file, Recs):
"""
converts a magic record back into the SIO mag format
"""
for rec in Recs:
type = ".0"
meths = []
tmp = rec["magic_method_codes"].split(':')
for meth in tmp:
meths.append(meth.strip())
if 'LT-T-I' in meths:
ty... | def function[domagicmag, parameter[file, Recs]]:
constant[
converts a magic record back into the SIO mag format
]
for taget[name[rec]] in starred[name[Recs]] begin[:]
variable[type] assign[=] constant[.0]
variable[meths] assign[=] list[[]]
variable... | keyword[def] identifier[domagicmag] ( identifier[file] , identifier[Recs] ):
literal[string]
keyword[for] identifier[rec] keyword[in] identifier[Recs] :
identifier[type] = literal[string]
identifier[meths] =[]
identifier[tmp] = identifier[rec] [ literal[string] ]. identifier[... | def domagicmag(file, Recs):
"""
converts a magic record back into the SIO mag format
"""
for rec in Recs:
type = '.0'
meths = []
tmp = rec['magic_method_codes'].split(':')
for meth in tmp:
meths.append(meth.strip()) # depends on [control=['for'], data=['meth'... |
def setter(self, name: str, rename: Optional[str] = None) -> 'ProxyAttr':
"""
为类设置代理 setter
"""
if rename is None:
rename = name
if self.reuse_handle(name, rename, self._setter):
return self
def proxy_set(this: Any, val: Any) -> None:
... | def function[setter, parameter[self, name, rename]]:
constant[
为类设置代理 setter
]
if compare[name[rename] is constant[None]] begin[:]
variable[rename] assign[=] name[name]
if call[name[self].reuse_handle, parameter[name[name], name[rename], name[self]._setter]] begin... | keyword[def] identifier[setter] ( identifier[self] , identifier[name] : identifier[str] , identifier[rename] : identifier[Optional] [ identifier[str] ]= keyword[None] )-> literal[string] :
literal[string]
keyword[if] identifier[rename] keyword[is] keyword[None] :
identifier[rename] ... | def setter(self, name: str, rename: Optional[str]=None) -> 'ProxyAttr':
"""
为类设置代理 setter
"""
if rename is None:
rename = name # depends on [control=['if'], data=['rename']]
if self.reuse_handle(name, rename, self._setter):
return self # depends on [control=['if'], data=[]]... |
def dlogpdf_link_dvar(self, link_f, y, Y_metadata=None):
"""
Gradient of the log-likelihood function at y given link(f), w.r.t variance parameter (noise_variance)
.. math::
\\frac{d \\ln p(y_{i}|\\lambda(f_{i}))}{d\\sigma^{2}} = -\\frac{N}{2\\sigma^{2}} + \\frac{(y_{i} - \\lambda(f_... | def function[dlogpdf_link_dvar, parameter[self, link_f, y, Y_metadata]]:
constant[
Gradient of the log-likelihood function at y given link(f), w.r.t variance parameter (noise_variance)
.. math::
\frac{d \ln p(y_{i}|\lambda(f_{i}))}{d\sigma^{2}} = -\frac{N}{2\sigma^{2}} + \frac{(y_{i... | keyword[def] identifier[dlogpdf_link_dvar] ( identifier[self] , identifier[link_f] , identifier[y] , identifier[Y_metadata] = keyword[None] ):
literal[string]
identifier[e] = identifier[y] - identifier[link_f]
identifier[s_4] = literal[int] /( identifier[self] . identifier[variance] ** li... | def dlogpdf_link_dvar(self, link_f, y, Y_metadata=None):
"""
Gradient of the log-likelihood function at y given link(f), w.r.t variance parameter (noise_variance)
.. math::
\\frac{d \\ln p(y_{i}|\\lambda(f_{i}))}{d\\sigma^{2}} = -\\frac{N}{2\\sigma^{2}} + \\frac{(y_{i} - \\lambda(f_{i})... |
def get_tasks(self, thread_name):
"""
Args:
thread_name (str): name of the thread to get the tasks for
Returns:
OrderedDict of str, Task: list of task names and log records for
each for the given thread
"""
if thread_name not in self.tasks... | def function[get_tasks, parameter[self, thread_name]]:
constant[
Args:
thread_name (str): name of the thread to get the tasks for
Returns:
OrderedDict of str, Task: list of task names and log records for
each for the given thread
]
if comp... | keyword[def] identifier[get_tasks] ( identifier[self] , identifier[thread_name] ):
literal[string]
keyword[if] identifier[thread_name] keyword[not] keyword[in] identifier[self] . identifier[tasks_by_thread] :
keyword[with] identifier[self] . identifier[_tasks_lock] :
... | def get_tasks(self, thread_name):
"""
Args:
thread_name (str): name of the thread to get the tasks for
Returns:
OrderedDict of str, Task: list of task names and log records for
each for the given thread
"""
if thread_name not in self.tasks_by_thre... |
def get_hashed_signature(self, url):
"""
Process from Membersuite Docs: http://bit.ly/2eSIDxz
"""
data = "%s%s" % (url, self.association_id)
if self.session_id:
data = "%s%s" % (data, self.session_id)
data_b = bytearray(data, 'utf-8')
secret_key = base... | def function[get_hashed_signature, parameter[self, url]]:
constant[
Process from Membersuite Docs: http://bit.ly/2eSIDxz
]
variable[data] assign[=] binary_operation[constant[%s%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da1b2370be0>, <ast.Attribute object at 0x7d... | keyword[def] identifier[get_hashed_signature] ( identifier[self] , identifier[url] ):
literal[string]
identifier[data] = literal[string] %( identifier[url] , identifier[self] . identifier[association_id] )
keyword[if] identifier[self] . identifier[session_id] :
identifier[dat... | def get_hashed_signature(self, url):
"""
Process from Membersuite Docs: http://bit.ly/2eSIDxz
"""
data = '%s%s' % (url, self.association_id)
if self.session_id:
data = '%s%s' % (data, self.session_id) # depends on [control=['if'], data=[]]
data_b = bytearray(data, 'utf-8')
s... |
def download(self, output_dir, url, overwrite):
""" Dowload file to /tmp """
tmp = self.url2tmp(output_dir, url)
if os.path.isfile(tmp) and not overwrite:
logging.info("File {0} already exists. Skipping download.".format(tmp))
return tmp
f = open(tmp, 'wb')
... | def function[download, parameter[self, output_dir, url, overwrite]]:
constant[ Dowload file to /tmp ]
variable[tmp] assign[=] call[name[self].url2tmp, parameter[name[output_dir], name[url]]]
if <ast.BoolOp object at 0x7da1b1835ea0> begin[:]
call[name[logging].info, parameter[call... | keyword[def] identifier[download] ( identifier[self] , identifier[output_dir] , identifier[url] , identifier[overwrite] ):
literal[string]
identifier[tmp] = identifier[self] . identifier[url2tmp] ( identifier[output_dir] , identifier[url] )
keyword[if] identifier[os] . identifier[path] . ... | def download(self, output_dir, url, overwrite):
""" Dowload file to /tmp """
tmp = self.url2tmp(output_dir, url)
if os.path.isfile(tmp) and (not overwrite):
logging.info('File {0} already exists. Skipping download.'.format(tmp))
return tmp # depends on [control=['if'], data=[]]
f = open... |
async def unformat(self):
"""Unformat this block device."""
self._data = await self._handler.unformat(
system_id=self.node.system_id, id=self.id) | <ast.AsyncFunctionDef object at 0x7da18eb57580> | keyword[async] keyword[def] identifier[unformat] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_data] = keyword[await] identifier[self] . identifier[_handler] . identifier[unformat] (
identifier[system_id] = identifier[self] . identifier[node] . identifier[system_id... | async def unformat(self):
"""Unformat this block device."""
self._data = await self._handler.unformat(system_id=self.node.system_id, id=self.id) |
def grant_permission_for(brain_or_object, permission, roles, acquire=0):
"""Grant the permission for the object to the defined roles
Code extracted from `IRoleManager.manage_permission`
:param brain_or_object: Catalog brain or object
:param permission: The permission to be granted
:param roles: Th... | def function[grant_permission_for, parameter[brain_or_object, permission, roles, acquire]]:
constant[Grant the permission for the object to the defined roles
Code extracted from `IRoleManager.manage_permission`
:param brain_or_object: Catalog brain or object
:param permission: The permission to be... | keyword[def] identifier[grant_permission_for] ( identifier[brain_or_object] , identifier[permission] , identifier[roles] , identifier[acquire] = literal[int] ):
literal[string]
identifier[obj] = identifier[api] . identifier[get_object] ( identifier[brain_or_object] )
identifier[valid_roles] = identifi... | def grant_permission_for(brain_or_object, permission, roles, acquire=0):
"""Grant the permission for the object to the defined roles
Code extracted from `IRoleManager.manage_permission`
:param brain_or_object: Catalog brain or object
:param permission: The permission to be granted
:param roles: Th... |
def deriv(f,c,dx=0.0001):
"""
deriv(f,c,dx) --> float
Returns f'(x), computed as a symmetric difference quotient.
"""
return (f(c+dx)-f(c-dx))/(2*dx) | def function[deriv, parameter[f, c, dx]]:
constant[
deriv(f,c,dx) --> float
Returns f'(x), computed as a symmetric difference quotient.
]
return[binary_operation[binary_operation[call[name[f], parameter[binary_operation[name[c] + name[dx]]]] - call[name[f], parameter[binary_operation[name[... | keyword[def] identifier[deriv] ( identifier[f] , identifier[c] , identifier[dx] = literal[int] ):
literal[string]
keyword[return] ( identifier[f] ( identifier[c] + identifier[dx] )- identifier[f] ( identifier[c] - identifier[dx] ))/( literal[int] * identifier[dx] ) | def deriv(f, c, dx=0.0001):
"""
deriv(f,c,dx) --> float
Returns f'(x), computed as a symmetric difference quotient.
"""
return (f(c + dx) - f(c - dx)) / (2 * dx) |
def dispatch_event(event):
""" Dispatch the event being represented by the Event object.
Args:
event: Object holding information about the request to be dispatched to the Optimizely backend.
"""
try:
if event.http_verb == enums.HTTPVerbs.GET:
requests.get(event.url, params=event.pa... | def function[dispatch_event, parameter[event]]:
constant[ Dispatch the event being represented by the Event object.
Args:
event: Object holding information about the request to be dispatched to the Optimizely backend.
]
<ast.Try object at 0x7da18bc72aa0> | keyword[def] identifier[dispatch_event] ( identifier[event] ):
literal[string]
keyword[try] :
keyword[if] identifier[event] . identifier[http_verb] == identifier[enums] . identifier[HTTPVerbs] . identifier[GET] :
identifier[requests] . identifier[get] ( identifier[event] . identifier[url]... | def dispatch_event(event):
""" Dispatch the event being represented by the Event object.
Args:
event: Object holding information about the request to be dispatched to the Optimizely backend.
"""
try:
if event.http_verb == enums.HTTPVerbs.GET:
requests.get(event.url, params=eve... |
def unlink_learners(self):
"""
Iterate over each learner and unlink inactive SAP channel learners.
This method iterates over each enterprise learner and unlink learner
from the enterprise if the learner is marked inactive in the related
integrated channel.
"""
sa... | def function[unlink_learners, parameter[self]]:
constant[
Iterate over each learner and unlink inactive SAP channel learners.
This method iterates over each enterprise learner and unlink learner
from the enterprise if the learner is marked inactive in the related
integrated chan... | keyword[def] identifier[unlink_learners] ( identifier[self] ):
literal[string]
identifier[sap_inactive_learners] = identifier[self] . identifier[client] . identifier[get_inactive_sap_learners] ()
identifier[enterprise_customer] = identifier[self] . identifier[enterprise_configuration] . id... | def unlink_learners(self):
"""
Iterate over each learner and unlink inactive SAP channel learners.
This method iterates over each enterprise learner and unlink learner
from the enterprise if the learner is marked inactive in the related
integrated channel.
"""
sap_inacti... |
def split(self, meta=False):
"""
split disconnected structure to connected substructures
:param meta: copy metadata to each substructure
:return: list of substructures
"""
return [self.substructure(c, meta, False) for c in connected_components(self)] | def function[split, parameter[self, meta]]:
constant[
split disconnected structure to connected substructures
:param meta: copy metadata to each substructure
:return: list of substructures
]
return[<ast.ListComp object at 0x7da20c6c4a30>] | keyword[def] identifier[split] ( identifier[self] , identifier[meta] = keyword[False] ):
literal[string]
keyword[return] [ identifier[self] . identifier[substructure] ( identifier[c] , identifier[meta] , keyword[False] ) keyword[for] identifier[c] keyword[in] identifier[connected_components] ( i... | def split(self, meta=False):
"""
split disconnected structure to connected substructures
:param meta: copy metadata to each substructure
:return: list of substructures
"""
return [self.substructure(c, meta, False) for c in connected_components(self)] |
def capture_payment(request):
"""
Capture the payment for a basket and create an order
request.data should contain:
'address': Dict with the following fields:
shipping_name
shipping_address_line1
shipping_address_city
shipping_address_zip
shipping_address_countr... | def function[capture_payment, parameter[request]]:
constant[
Capture the payment for a basket and create an order
request.data should contain:
'address': Dict with the following fields:
shipping_name
shipping_address_line1
shipping_address_city
shipping_address_zip
... | keyword[def] identifier[capture_payment] ( identifier[request] ):
literal[string]
identifier[address] = identifier[request] . identifier[data] [ literal[string] ]
identifier[email] = identifier[request] . identifier[data] . identifier[get] ( literal[string] , keyword[None] )
identifier[shipp... | def capture_payment(request):
"""
Capture the payment for a basket and create an order
request.data should contain:
'address': Dict with the following fields:
shipping_name
shipping_address_line1
shipping_address_city
shipping_address_zip
shipping_address_countr... |
def scatter(self, x, y, s=None, c=None, **kwds):
"""
Create a scatter plot with varying marker point size and color.
The coordinates of each point are defined by two dataframe columns and
filled circles are used to represent each point. This kind of plot is
useful to see complex... | def function[scatter, parameter[self, x, y, s, c]]:
constant[
Create a scatter plot with varying marker point size and color.
The coordinates of each point are defined by two dataframe columns and
filled circles are used to represent each point. This kind of plot is
useful to se... | keyword[def] identifier[scatter] ( identifier[self] , identifier[x] , identifier[y] , identifier[s] = keyword[None] , identifier[c] = keyword[None] ,** identifier[kwds] ):
literal[string]
keyword[return] identifier[self] ( identifier[kind] = literal[string] , identifier[x] = identifier[x] , identi... | def scatter(self, x, y, s=None, c=None, **kwds):
"""
Create a scatter plot with varying marker point size and color.
The coordinates of each point are defined by two dataframe columns and
filled circles are used to represent each point. This kind of plot is
useful to see complex cor... |
def validate_qparams(self):
"""
Check if the keys specified by the user in qparams are supported.
Raise:
`ValueError` if errors.
"""
# No validation for ShellAdapter.
if isinstance(self, ShellAdapter): return
# Parse the template so that we know the ... | def function[validate_qparams, parameter[self]]:
constant[
Check if the keys specified by the user in qparams are supported.
Raise:
`ValueError` if errors.
]
if call[name[isinstance], parameter[name[self], name[ShellAdapter]]] begin[:]
return[None]
va... | keyword[def] identifier[validate_qparams] ( identifier[self] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[self] , identifier[ShellAdapter] ): keyword[return]
identifier[err_msg] = literal[string]
keyword[for] identifier[param] keyword[... | def validate_qparams(self):
"""
Check if the keys specified by the user in qparams are supported.
Raise:
`ValueError` if errors.
"""
# No validation for ShellAdapter.
if isinstance(self, ShellAdapter):
return # depends on [control=['if'], data=[]]
# Parse th... |
def make_fits_keys_dict(keys):
"""
Returns a dictionary to translate to unique FITS header keys up to 8 characters long
This is similar to Windows making up 8-character names for filenames that
are longer than this
"The keyword names may be up to 8 characters long and can only contain
... | def function[make_fits_keys_dict, parameter[keys]]:
constant[
Returns a dictionary to translate to unique FITS header keys up to 8 characters long
This is similar to Windows making up 8-character names for filenames that
are longer than this
"The keyword names may be up to 8 characters long an... | keyword[def] identifier[make_fits_keys_dict] ( identifier[keys] ):
literal[string]
identifier[key_dict] ={}
identifier[new_keys] =[]
keyword[for] identifier[key] keyword[in] identifier[keys] :
identifier[fits_key] = identifier[valid_fits_key] ( identifier[key] )
... | def make_fits_keys_dict(keys):
"""
Returns a dictionary to translate to unique FITS header keys up to 8 characters long
This is similar to Windows making up 8-character names for filenames that
are longer than this
"The keyword names may be up to 8 characters long and can only contain
uppercas... |
def _build_youtube_dl_coprocessor(cls, session: AppSession, proxy_port: int):
'''Build youtube-dl coprocessor.'''
# Test early for executable
wpull.processor.coprocessor.youtubedl.get_version(session.args.youtube_dl_exe)
coprocessor = session.factory.new(
'YoutubeDlCoproces... | def function[_build_youtube_dl_coprocessor, parameter[cls, session, proxy_port]]:
constant[Build youtube-dl coprocessor.]
call[name[wpull].processor.coprocessor.youtubedl.get_version, parameter[name[session].args.youtube_dl_exe]]
variable[coprocessor] assign[=] call[name[session].factory.new, pa... | keyword[def] identifier[_build_youtube_dl_coprocessor] ( identifier[cls] , identifier[session] : identifier[AppSession] , identifier[proxy_port] : identifier[int] ):
literal[string]
identifier[wpull] . identifier[processor] . identifier[coprocessor] . identifier[youtubedl] . identifier[ge... | def _build_youtube_dl_coprocessor(cls, session: AppSession, proxy_port: int):
"""Build youtube-dl coprocessor."""
# Test early for executable
wpull.processor.coprocessor.youtubedl.get_version(session.args.youtube_dl_exe)
# Proxy will always present a invalid MITM cert
#check_certificate=session.args... |
def __check_for_extra_arguments(self, args_required, args_allowed):
"""
Report an error in case any extra arguments are detected.
Does nothing if reporting extra arguments as exceptions has not been
enabled.
May only be called after the argument processing has been completed.
... | def function[__check_for_extra_arguments, parameter[self, args_required, args_allowed]]:
constant[
Report an error in case any extra arguments are detected.
Does nothing if reporting extra arguments as exceptions has not been
enabled.
May only be called after the argument proce... | keyword[def] identifier[__check_for_extra_arguments] ( identifier[self] , identifier[args_required] , identifier[args_allowed] ):
literal[string]
keyword[assert] keyword[not] identifier[self] . identifier[active] ()
keyword[if] keyword[not] identifier[self] . identifier[__extra_paramet... | def __check_for_extra_arguments(self, args_required, args_allowed):
"""
Report an error in case any extra arguments are detected.
Does nothing if reporting extra arguments as exceptions has not been
enabled.
May only be called after the argument processing has been completed.
... |
def data64_send(self, type, len, data, force_mavlink1=False):
'''
Data packet, size 64
type : data type (uint8_t)
len : data length (uint8_t)
data : raw data (uint8_t)
... | def function[data64_send, parameter[self, type, len, data, force_mavlink1]]:
constant[
Data packet, size 64
type : data type (uint8_t)
len : data length (uint8_t)
data : raw data (uin... | keyword[def] identifier[data64_send] ( identifier[self] , identifier[type] , identifier[len] , identifier[data] , identifier[force_mavlink1] = keyword[False] ):
literal[string]
keyword[return] identifier[self] . identifier[send] ( identifier[self] . identifier[data64_encode] ( iden... | def data64_send(self, type, len, data, force_mavlink1=False):
"""
Data packet, size 64
type : data type (uint8_t)
len : data length (uint8_t)
data : raw data (uint8_t)
""... |
def execstr(self, local_name):
"""returns a string which when evaluated will
add the stored variables to the current namespace
localname is the name of the variable in the current scope
* use locals().update(dyn.to_dict()) instead
"""
execstr = ''
for (k... | def function[execstr, parameter[self, local_name]]:
constant[returns a string which when evaluated will
add the stored variables to the current namespace
localname is the name of the variable in the current scope
* use locals().update(dyn.to_dict()) instead
]
va... | keyword[def] identifier[execstr] ( identifier[self] , identifier[local_name] ):
literal[string]
identifier[execstr] = literal[string]
keyword[for] ( identifier[key] , identifier[val] ) keyword[in] identifier[six] . identifier[iteritems] ( identifier[self] . identifier[__dict__] ):
... | def execstr(self, local_name):
"""returns a string which when evaluated will
add the stored variables to the current namespace
localname is the name of the variable in the current scope
* use locals().update(dyn.to_dict()) instead
"""
execstr = ''
for (key, val) in ... |
def poke(self, context):
"""
Check for message on subscribed queue and write to xcom the message with key ``messages``
:param context: the context object
:type context: dict
:return: ``True`` if message is available or ``False``
"""
sqs_hook = SQSHook(aws_conn_i... | def function[poke, parameter[self, context]]:
constant[
Check for message on subscribed queue and write to xcom the message with key ``messages``
:param context: the context object
:type context: dict
:return: ``True`` if message is available or ``False``
]
varia... | keyword[def] identifier[poke] ( identifier[self] , identifier[context] ):
literal[string]
identifier[sqs_hook] = identifier[SQSHook] ( identifier[aws_conn_id] = identifier[self] . identifier[aws_conn_id] )
identifier[sqs_conn] = identifier[sqs_hook] . identifier[get_conn] ()
ide... | def poke(self, context):
"""
Check for message on subscribed queue and write to xcom the message with key ``messages``
:param context: the context object
:type context: dict
:return: ``True`` if message is available or ``False``
"""
sqs_hook = SQSHook(aws_conn_id=self.aw... |
def _eval_target_brutal(state, ip, limit):
"""
The traditional way of evaluating symbolic jump targets.
:param state: A SimState instance.
:param ip: The AST of the instruction pointer to evaluate.
:param limit: The maximum number of concrete IPs.
:return: ... | def function[_eval_target_brutal, parameter[state, ip, limit]]:
constant[
The traditional way of evaluating symbolic jump targets.
:param state: A SimState instance.
:param ip: The AST of the instruction pointer to evaluate.
:param limit: The maximum number of concrete ... | keyword[def] identifier[_eval_target_brutal] ( identifier[state] , identifier[ip] , identifier[limit] ):
literal[string]
identifier[addrs] = identifier[state] . identifier[solver] . identifier[eval_upto] ( identifier[ip] , identifier[limit] )
keyword[return] [( identifier[ip] == identifi... | def _eval_target_brutal(state, ip, limit):
"""
The traditional way of evaluating symbolic jump targets.
:param state: A SimState instance.
:param ip: The AST of the instruction pointer to evaluate.
:param limit: The maximum number of concrete IPs.
:return: A ... |
def BEQ(self, params):
"""
BEQ label
Branch to the instruction at label if the Z flag is set
"""
label = self.get_one_parameter(self.ONE_PARAMETER, params)
self.check_arguments(label_exists=(label,))
# BEQ label
def BEQ_func():
if self.is_Z_... | def function[BEQ, parameter[self, params]]:
constant[
BEQ label
Branch to the instruction at label if the Z flag is set
]
variable[label] assign[=] call[name[self].get_one_parameter, parameter[name[self].ONE_PARAMETER, name[params]]]
call[name[self].check_arguments, para... | keyword[def] identifier[BEQ] ( identifier[self] , identifier[params] ):
literal[string]
identifier[label] = identifier[self] . identifier[get_one_parameter] ( identifier[self] . identifier[ONE_PARAMETER] , identifier[params] )
identifier[self] . identifier[check_arguments] ( identifier[la... | def BEQ(self, params):
"""
BEQ label
Branch to the instruction at label if the Z flag is set
"""
label = self.get_one_parameter(self.ONE_PARAMETER, params)
self.check_arguments(label_exists=(label,))
# BEQ label
def BEQ_func():
if self.is_Z_set():
self.r... |
def stop(self):
'''
stop display
:rtype: self
'''
self.redirect_display(False)
EasyProcess.stop(self)
if self.use_xauth:
self._clear_xauth()
return self | def function[stop, parameter[self]]:
constant[
stop display
:rtype: self
]
call[name[self].redirect_display, parameter[constant[False]]]
call[name[EasyProcess].stop, parameter[name[self]]]
if name[self].use_xauth begin[:]
call[name[self]._clear_xa... | keyword[def] identifier[stop] ( identifier[self] ):
literal[string]
identifier[self] . identifier[redirect_display] ( keyword[False] )
identifier[EasyProcess] . identifier[stop] ( identifier[self] )
keyword[if] identifier[self] . identifier[use_xauth] :
identifier[se... | def stop(self):
"""
stop display
:rtype: self
"""
self.redirect_display(False)
EasyProcess.stop(self)
if self.use_xauth:
self._clear_xauth() # depends on [control=['if'], data=[]]
return self |
def read_config(self, config_file):
"""
Parses the specified configuration file and stores the values. Raises
an InvalidConfigurationFile exception if the file is not well-formed.
"""
cfg = ConfigParser.SafeConfigParser()
try:
cfg.read(config_file)
exc... | def function[read_config, parameter[self, config_file]]:
constant[
Parses the specified configuration file and stores the values. Raises
an InvalidConfigurationFile exception if the file is not well-formed.
]
variable[cfg] assign[=] call[name[ConfigParser].SafeConfigParser, param... | keyword[def] identifier[read_config] ( identifier[self] , identifier[config_file] ):
literal[string]
identifier[cfg] = identifier[ConfigParser] . identifier[SafeConfigParser] ()
keyword[try] :
identifier[cfg] . identifier[read] ( identifier[config_file] )
keyword[exce... | def read_config(self, config_file):
"""
Parses the specified configuration file and stores the values. Raises
an InvalidConfigurationFile exception if the file is not well-formed.
"""
cfg = ConfigParser.SafeConfigParser()
try:
cfg.read(config_file) # depends on [control=['tr... |
def is_ancestor(self, ancestor_rev, rev):
"""Check if a commit is an ancestor of another
:param ancestor_rev: Rev which should be an ancestor
:param rev: Rev to test against ancestor_rev
:return: ``True``, ancestor_rev is an accestor to rev.
"""
try:
self.gi... | def function[is_ancestor, parameter[self, ancestor_rev, rev]]:
constant[Check if a commit is an ancestor of another
:param ancestor_rev: Rev which should be an ancestor
:param rev: Rev to test against ancestor_rev
:return: ``True``, ancestor_rev is an accestor to rev.
]
<as... | keyword[def] identifier[is_ancestor] ( identifier[self] , identifier[ancestor_rev] , identifier[rev] ):
literal[string]
keyword[try] :
identifier[self] . identifier[git] . identifier[merge_base] ( identifier[ancestor_rev] , identifier[rev] , identifier[is_ancestor] = keyword[True] )
... | def is_ancestor(self, ancestor_rev, rev):
"""Check if a commit is an ancestor of another
:param ancestor_rev: Rev which should be an ancestor
:param rev: Rev to test against ancestor_rev
:return: ``True``, ancestor_rev is an accestor to rev.
"""
try:
self.git.merge_base... |
def to_app(app):
"""Serializes app to id string
:param app: object to serialize
:return: string id
"""
from sevenbridges.models.app import App
if not app:
raise SbgError('App is required!')
elif isinstance(app, App):
return app.id
e... | def function[to_app, parameter[app]]:
constant[Serializes app to id string
:param app: object to serialize
:return: string id
]
from relative_module[sevenbridges.models.app] import module[App]
if <ast.UnaryOp object at 0x7da18fe902e0> begin[:]
<ast.Raise object at 0x7... | keyword[def] identifier[to_app] ( identifier[app] ):
literal[string]
keyword[from] identifier[sevenbridges] . identifier[models] . identifier[app] keyword[import] identifier[App]
keyword[if] keyword[not] identifier[app] :
keyword[raise] identifier[SbgError] ( literal[st... | def to_app(app):
"""Serializes app to id string
:param app: object to serialize
:return: string id
"""
from sevenbridges.models.app import App
if not app:
raise SbgError('App is required!') # depends on [control=['if'], data=[]]
elif isinstance(app, App):
return ... |
def map_is_in_fov(m: tcod.map.Map, x: int, y: int) -> bool:
"""Return True if the cell at x,y is lit by the last field-of-view
algorithm.
.. note::
This function is slow.
.. deprecated:: 4.5
Use :any:`tcod.map.Map.fov` to check this property.
"""
return bool(lib.TCOD_map_is_in_f... | def function[map_is_in_fov, parameter[m, x, y]]:
constant[Return True if the cell at x,y is lit by the last field-of-view
algorithm.
.. note::
This function is slow.
.. deprecated:: 4.5
Use :any:`tcod.map.Map.fov` to check this property.
]
return[call[name[bool], parameter[c... | keyword[def] identifier[map_is_in_fov] ( identifier[m] : identifier[tcod] . identifier[map] . identifier[Map] , identifier[x] : identifier[int] , identifier[y] : identifier[int] )-> identifier[bool] :
literal[string]
keyword[return] identifier[bool] ( identifier[lib] . identifier[TCOD_map_is_in_fov] ( ide... | def map_is_in_fov(m: tcod.map.Map, x: int, y: int) -> bool:
"""Return True if the cell at x,y is lit by the last field-of-view
algorithm.
.. note::
This function is slow.
.. deprecated:: 4.5
Use :any:`tcod.map.Map.fov` to check this property.
"""
return bool(lib.TCOD_map_is_in_f... |
def text_has_been_edited(self, text):
"""Find text has been edited (this slot won't be triggered when
setting the search pattern combo box text programmatically)"""
self.find(changed=True, forward=True, start_highlight_timer=True) | def function[text_has_been_edited, parameter[self, text]]:
constant[Find text has been edited (this slot won't be triggered when
setting the search pattern combo box text programmatically)]
call[name[self].find, parameter[]] | keyword[def] identifier[text_has_been_edited] ( identifier[self] , identifier[text] ):
literal[string]
identifier[self] . identifier[find] ( identifier[changed] = keyword[True] , identifier[forward] = keyword[True] , identifier[start_highlight_timer] = keyword[True] ) | def text_has_been_edited(self, text):
"""Find text has been edited (this slot won't be triggered when
setting the search pattern combo box text programmatically)"""
self.find(changed=True, forward=True, start_highlight_timer=True) |
def add_dependency(id=None, name=None, dependency_id=None, dependency_name=None):
"""
Add an existing BuildConfiguration as a dependency to another BuildConfiguration.
"""
data = add_dependency_raw(id, name, dependency_id, dependency_name)
if data:
return utils.format_json_list(data) | def function[add_dependency, parameter[id, name, dependency_id, dependency_name]]:
constant[
Add an existing BuildConfiguration as a dependency to another BuildConfiguration.
]
variable[data] assign[=] call[name[add_dependency_raw], parameter[name[id], name[name], name[dependency_id], name[depen... | keyword[def] identifier[add_dependency] ( identifier[id] = keyword[None] , identifier[name] = keyword[None] , identifier[dependency_id] = keyword[None] , identifier[dependency_name] = keyword[None] ):
literal[string]
identifier[data] = identifier[add_dependency_raw] ( identifier[id] , identifier[name] , id... | def add_dependency(id=None, name=None, dependency_id=None, dependency_name=None):
"""
Add an existing BuildConfiguration as a dependency to another BuildConfiguration.
"""
data = add_dependency_raw(id, name, dependency_id, dependency_name)
if data:
return utils.format_json_list(data) # depe... |
def clean(self):
"""Delete all of the records"""
# Deleting seems to be really weird and unrelable.
self._session \
.query(Process) \
.filter(Process.d_vid == self._d_vid) \
.delete(synchronize_session='fetch')
for r in self.records:
self... | def function[clean, parameter[self]]:
constant[Delete all of the records]
call[call[call[name[self]._session.query, parameter[name[Process]]].filter, parameter[compare[name[Process].d_vid equal[==] name[self]._d_vid]]].delete, parameter[]]
for taget[name[r]] in starred[name[self].records] begin[... | keyword[def] identifier[clean] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_session] . identifier[query] ( identifier[Process] ). identifier[filter] ( identifier[Process] . identifier[d_vid] == identifier[self] . identifier[_d_vid] ). identifier[delete] ( identifie... | def clean(self):
"""Delete all of the records"""
# Deleting seems to be really weird and unrelable.
self._session.query(Process).filter(Process.d_vid == self._d_vid).delete(synchronize_session='fetch')
for r in self.records:
self._session.delete(r) # depends on [control=['for'], data=['r']]
... |
def __needs_encoding(self, s):
"""
Get whether string I{s} contains special characters.
@param s: A string to check.
@type s: str
@return: True if needs encoding.
@rtype: boolean
"""
if isinstance(s, basestring):
for c in self.special:
... | def function[__needs_encoding, parameter[self, s]]:
constant[
Get whether string I{s} contains special characters.
@param s: A string to check.
@type s: str
@return: True if needs encoding.
@rtype: boolean
]
if call[name[isinstance], parameter[name[s], n... | keyword[def] identifier[__needs_encoding] ( identifier[self] , identifier[s] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[s] , identifier[basestring] ):
keyword[for] identifier[c] keyword[in] identifier[self] . identifier[special] :
keyword[if... | def __needs_encoding(self, s):
"""
Get whether string I{s} contains special characters.
@param s: A string to check.
@type s: str
@return: True if needs encoding.
@rtype: boolean
"""
if isinstance(s, basestring):
for c in self.special:
if c i... |
def _normalise(self):
"""Object is guaranteed to be a unit quaternion after calling this
operation UNLESS the object is equivalent to Quaternion(0)
"""
if not self.is_unit():
n = self.norm
if n > 0:
self.q = self.q / n | def function[_normalise, parameter[self]]:
constant[Object is guaranteed to be a unit quaternion after calling this
operation UNLESS the object is equivalent to Quaternion(0)
]
if <ast.UnaryOp object at 0x7da1b08b1030> begin[:]
variable[n] assign[=] name[self].norm
... | keyword[def] identifier[_normalise] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[is_unit] ():
identifier[n] = identifier[self] . identifier[norm]
keyword[if] identifier[n] > literal[int] :
identifier[self... | def _normalise(self):
"""Object is guaranteed to be a unit quaternion after calling this
operation UNLESS the object is equivalent to Quaternion(0)
"""
if not self.is_unit():
n = self.norm
if n > 0:
self.q = self.q / n # depends on [control=['if'], data=['n']] # dep... |
def join(self, mucjid, nick, *,
password=None, history=None, autorejoin=True):
"""
Join a multi-user chat and create a conversation for it.
:param mucjid: The bare JID of the room to join.
:type mucjid: :class:`~aioxmpp.JID`.
:param nick: The nickname to use in the ... | def function[join, parameter[self, mucjid, nick]]:
constant[
Join a multi-user chat and create a conversation for it.
:param mucjid: The bare JID of the room to join.
:type mucjid: :class:`~aioxmpp.JID`.
:param nick: The nickname to use in the room.
:type nick: :class:`s... | keyword[def] identifier[join] ( identifier[self] , identifier[mucjid] , identifier[nick] ,*,
identifier[password] = keyword[None] , identifier[history] = keyword[None] , identifier[autorejoin] = keyword[True] ):
literal[string]
keyword[if] identifier[history] keyword[is] keyword[not] keyword[N... | def join(self, mucjid, nick, *, password=None, history=None, autorejoin=True):
"""
Join a multi-user chat and create a conversation for it.
:param mucjid: The bare JID of the room to join.
:type mucjid: :class:`~aioxmpp.JID`.
:param nick: The nickname to use in the room.
:ty... |
def point_to_t(self, point):
"""If the point lies on the Line, returns its `t` parameter.
If the point does not lie on the Line, returns None."""
# Single-precision floats have only 7 significant figures of
# resolution, so test that we're within 6 sig figs.
if np.isclose(point,... | def function[point_to_t, parameter[self, point]]:
constant[If the point lies on the Line, returns its `t` parameter.
If the point does not lie on the Line, returns None.]
if call[name[np].isclose, parameter[name[point], name[self].start]] begin[:]
return[constant[0.0]]
variable[p... | keyword[def] identifier[point_to_t] ( identifier[self] , identifier[point] ):
literal[string]
keyword[if] identifier[np] . identifier[isclose] ( identifier[point] , identifier[self] . identifier[start] , identifier[rtol] = literal[int] , identifier[atol] = literal[int] ):
... | def point_to_t(self, point):
"""If the point lies on the Line, returns its `t` parameter.
If the point does not lie on the Line, returns None."""
# Single-precision floats have only 7 significant figures of
# resolution, so test that we're within 6 sig figs.
if np.isclose(point, self.start, rtol... |
def _generate_altered_sql_dependencies(self, dep_changed_keys):
"""
Generate forward operations for changing/creating SQL item dependencies.
Dependencies are only in-memory and should be reflecting database dependencies, so
changing them in SQL config does not alter database. Such actio... | def function[_generate_altered_sql_dependencies, parameter[self, dep_changed_keys]]:
constant[
Generate forward operations for changing/creating SQL item dependencies.
Dependencies are only in-memory and should be reflecting database dependencies, so
changing them in SQL config does not... | keyword[def] identifier[_generate_altered_sql_dependencies] ( identifier[self] , identifier[dep_changed_keys] ):
literal[string]
keyword[for] identifier[key] , identifier[removed_deps] , identifier[added_deps] keyword[in] identifier[dep_changed_keys] :
identifier[app_label] , identi... | def _generate_altered_sql_dependencies(self, dep_changed_keys):
"""
Generate forward operations for changing/creating SQL item dependencies.
Dependencies are only in-memory and should be reflecting database dependencies, so
changing them in SQL config does not alter database. Such actions a... |
def create(cls, amount, counterparty_alias, description,
monetary_account_id=None, attachment=None,
merchant_reference=None, allow_bunqto=None, custom_headers=None):
"""
Create a new Payment.
:type user_id: int
:type monetary_account_id: int
:param ... | def function[create, parameter[cls, amount, counterparty_alias, description, monetary_account_id, attachment, merchant_reference, allow_bunqto, custom_headers]]:
constant[
Create a new Payment.
:type user_id: int
:type monetary_account_id: int
:param amount: The Amount to transf... | keyword[def] identifier[create] ( identifier[cls] , identifier[amount] , identifier[counterparty_alias] , identifier[description] ,
identifier[monetary_account_id] = keyword[None] , identifier[attachment] = keyword[None] ,
identifier[merchant_reference] = keyword[None] , identifier[allow_bunqto] = keyword[None] , i... | def create(cls, amount, counterparty_alias, description, monetary_account_id=None, attachment=None, merchant_reference=None, allow_bunqto=None, custom_headers=None):
"""
Create a new Payment.
:type user_id: int
:type monetary_account_id: int
:param amount: The Amount to transfer wit... |
def count_funs(self) -> int:
""" Count function define by this scope """
n = 0
for s in self._hsig.values():
if hasattr(s, 'is_fun') and s.is_fun:
n += 1
return n | def function[count_funs, parameter[self]]:
constant[ Count function define by this scope ]
variable[n] assign[=] constant[0]
for taget[name[s]] in starred[call[name[self]._hsig.values, parameter[]]] begin[:]
if <ast.BoolOp object at 0x7da1b013d8a0> begin[:]
<ast.AugAs... | keyword[def] identifier[count_funs] ( identifier[self] )-> identifier[int] :
literal[string]
identifier[n] = literal[int]
keyword[for] identifier[s] keyword[in] identifier[self] . identifier[_hsig] . identifier[values] ():
keyword[if] identifier[hasattr] ( identifier[s] ,... | def count_funs(self) -> int:
""" Count function define by this scope """
n = 0
for s in self._hsig.values():
if hasattr(s, 'is_fun') and s.is_fun:
n += 1 # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['s']]
return n |
def insert_data_frame(col, df, int_col=None, binary_col=None, minimal_size=5):
"""Insert ``pandas.DataFrame``.
:param col: :class:`pymongo.collection.Collection` instance.
:param df: :class:`pandas.DataFrame` instance.
:param int_col: list of integer-type column.
:param binary_col: list of binary-t... | def function[insert_data_frame, parameter[col, df, int_col, binary_col, minimal_size]]:
constant[Insert ``pandas.DataFrame``.
:param col: :class:`pymongo.collection.Collection` instance.
:param df: :class:`pandas.DataFrame` instance.
:param int_col: list of integer-type column.
:param binary_co... | keyword[def] identifier[insert_data_frame] ( identifier[col] , identifier[df] , identifier[int_col] = keyword[None] , identifier[binary_col] = keyword[None] , identifier[minimal_size] = literal[int] ):
literal[string]
identifier[data] = identifier[transform] . identifier[to_dict_list_generic_type] ( identi... | def insert_data_frame(col, df, int_col=None, binary_col=None, minimal_size=5):
"""Insert ``pandas.DataFrame``.
:param col: :class:`pymongo.collection.Collection` instance.
:param df: :class:`pandas.DataFrame` instance.
:param int_col: list of integer-type column.
:param binary_col: list of binary-t... |
def movieframe(args):
"""
%prog movieframe tour test.clm contigs.ref.anchors
Draw heatmap and synteny in the same plot.
"""
p = OptionParser(movieframe.__doc__)
p.add_option("--label", help="Figure title")
p.set_beds()
p.set_outfile(outfile=None)
opts, args, iopts = p.set_image_opti... | def function[movieframe, parameter[args]]:
constant[
%prog movieframe tour test.clm contigs.ref.anchors
Draw heatmap and synteny in the same plot.
]
variable[p] assign[=] call[name[OptionParser], parameter[name[movieframe].__doc__]]
call[name[p].add_option, parameter[constant[--labe... | keyword[def] identifier[movieframe] ( identifier[args] ):
literal[string]
identifier[p] = identifier[OptionParser] ( identifier[movieframe] . identifier[__doc__] )
identifier[p] . identifier[add_option] ( literal[string] , identifier[help] = literal[string] )
identifier[p] . identifier[set_beds] ... | def movieframe(args):
"""
%prog movieframe tour test.clm contigs.ref.anchors
Draw heatmap and synteny in the same plot.
"""
p = OptionParser(movieframe.__doc__)
p.add_option('--label', help='Figure title')
p.set_beds()
p.set_outfile(outfile=None)
(opts, args, iopts) = p.set_image_op... |
def __EncodedAttribute_encode_rgb24(self, rgb24, width=0, height=0):
"""Encode a 24 bit color image (no compression)
:param rgb24: an object containning image information
:type rgb24: :py:obj:`str` or :class:`numpy.ndarray` or seq< seq<element> >
:param width: image width. **MUST**... | def function[__EncodedAttribute_encode_rgb24, parameter[self, rgb24, width, height]]:
constant[Encode a 24 bit color image (no compression)
:param rgb24: an object containning image information
:type rgb24: :py:obj:`str` or :class:`numpy.ndarray` or seq< seq<element> >
:param w... | keyword[def] identifier[__EncodedAttribute_encode_rgb24] ( identifier[self] , identifier[rgb24] , identifier[width] = literal[int] , identifier[height] = literal[int] ):
literal[string]
identifier[self] . identifier[_generic_encode_rgb24] ( identifier[rgb24] , identifier[width] = identifier[width] , identi... | def __EncodedAttribute_encode_rgb24(self, rgb24, width=0, height=0):
"""Encode a 24 bit color image (no compression)
:param rgb24: an object containning image information
:type rgb24: :py:obj:`str` or :class:`numpy.ndarray` or seq< seq<element> >
:param width: image width. **MUST**... |
def get_api_endpoints(self, apiname):
"""Returns the API endpoints"""
try:
return self.services_by_name\
.get(apiname)\
.get("endpoints")\
.copy()
except AttributeError:
raise Exception(f"Couldn't find the API en... | def function[get_api_endpoints, parameter[self, apiname]]:
constant[Returns the API endpoints]
<ast.Try object at 0x7da18f09e920> | keyword[def] identifier[get_api_endpoints] ( identifier[self] , identifier[apiname] ):
literal[string]
keyword[try] :
keyword[return] identifier[self] . identifier[services_by_name] . identifier[get] ( identifier[apiname] ). identifier[get] ( literal[string] ). identifier[copy] ()
... | def get_api_endpoints(self, apiname):
"""Returns the API endpoints"""
try:
return self.services_by_name.get(apiname).get('endpoints').copy() # depends on [control=['try'], data=[]]
except AttributeError:
raise Exception(f"Couldn't find the API endpoints") # depends on [control=['except'], ... |
def _get_consecutive_portions_of_front(front):
"""
Yields lists of the form [(f, s), (f, s)], one at a time from the given front (which is a list of the same form),
such that each list yielded is consecutive in frequency.
"""
last_f = None
ls = []
for f, s in front:
if last_f is not ... | def function[_get_consecutive_portions_of_front, parameter[front]]:
constant[
Yields lists of the form [(f, s), (f, s)], one at a time from the given front (which is a list of the same form),
such that each list yielded is consecutive in frequency.
]
variable[last_f] assign[=] constant[None]... | keyword[def] identifier[_get_consecutive_portions_of_front] ( identifier[front] ):
literal[string]
identifier[last_f] = keyword[None]
identifier[ls] =[]
keyword[for] identifier[f] , identifier[s] keyword[in] identifier[front] :
keyword[if] identifier[last_f] keyword[is] keyword[no... | def _get_consecutive_portions_of_front(front):
"""
Yields lists of the form [(f, s), (f, s)], one at a time from the given front (which is a list of the same form),
such that each list yielded is consecutive in frequency.
"""
last_f = None
ls = []
for (f, s) in front:
if last_f is no... |
def wrap(self, word, width, hyphen='-'):
"""
Return the longest possible first part and the last part of the
hyphenated word. The first part has the hyphen already attached.
Returns None, if there is no hyphenation point before width, or
if the word could not be hyphenated.
... | def function[wrap, parameter[self, word, width, hyphen]]:
constant[
Return the longest possible first part and the last part of the
hyphenated word. The first part has the hyphen already attached.
Returns None, if there is no hyphenation point before width, or
if the word could n... | keyword[def] identifier[wrap] ( identifier[self] , identifier[word] , identifier[width] , identifier[hyphen] = literal[string] ):
literal[string]
identifier[width] -= identifier[len] ( identifier[hyphen] )
keyword[for] identifier[w1] , identifier[w2] keyword[in] identifier[self] . ident... | def wrap(self, word, width, hyphen='-'):
"""
Return the longest possible first part and the last part of the
hyphenated word. The first part has the hyphen already attached.
Returns None, if there is no hyphenation point before width, or
if the word could not be hyphenated.
"... |
def get_response_content_type(self):
"""Figure out what content type will be used in the response."""
if self._best_response_match is None:
settings = get_settings(self.application, force_instance=True)
acceptable = headers.parse_accept(
self.request.headers.get(
... | def function[get_response_content_type, parameter[self]]:
constant[Figure out what content type will be used in the response.]
if compare[name[self]._best_response_match is constant[None]] begin[:]
variable[settings] assign[=] call[name[get_settings], parameter[name[self].application]]
... | keyword[def] identifier[get_response_content_type] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_best_response_match] keyword[is] keyword[None] :
identifier[settings] = identifier[get_settings] ( identifier[self] . identifier[application] , identif... | def get_response_content_type(self):
"""Figure out what content type will be used in the response."""
if self._best_response_match is None:
settings = get_settings(self.application, force_instance=True)
acceptable = headers.parse_accept(self.request.headers.get('Accept', settings.default_content... |
def conv2d(self, filter_size, output_channels, stride=1, padding='SAME', stoch=None, bn=True, test=False, activation_fn=tf.nn.relu, b_value=0.0, s_value=1.0):
"""
2D Convolutional Layer.
:param filter_size: int. assumes square filter
:param output_channels: int
:param stride: int... | def function[conv2d, parameter[self, filter_size, output_channels, stride, padding, stoch, bn, test, activation_fn, b_value, s_value]]:
constant[
2D Convolutional Layer.
:param filter_size: int. assumes square filter
:param output_channels: int
:param stride: int
:param p... | keyword[def] identifier[conv2d] ( identifier[self] , identifier[filter_size] , identifier[output_channels] , identifier[stride] = literal[int] , identifier[padding] = literal[string] , identifier[stoch] = keyword[None] , identifier[bn] = keyword[True] , identifier[test] = keyword[False] , identifier[activation_fn] = ... | def conv2d(self, filter_size, output_channels, stride=1, padding='SAME', stoch=None, bn=True, test=False, activation_fn=tf.nn.relu, b_value=0.0, s_value=1.0):
"""
2D Convolutional Layer.
:param filter_size: int. assumes square filter
:param output_channels: int
:param stride: int
... |
def s3_cache_timeout(self):
"""
The socket timeout in seconds for connections to Amazon S3 (an integer).
This value is injected into Boto's configuration to override the
default socket timeout used for connections to Amazon S3.
- Environment variable: ``$PIP_ACCEL_S3_TIMEOUT``
... | def function[s3_cache_timeout, parameter[self]]:
constant[
The socket timeout in seconds for connections to Amazon S3 (an integer).
This value is injected into Boto's configuration to override the
default socket timeout used for connections to Amazon S3.
- Environment variable:... | keyword[def] identifier[s3_cache_timeout] ( identifier[self] ):
literal[string]
identifier[value] = identifier[self] . identifier[get] ( identifier[property_name] = literal[string] ,
identifier[environment_variable] = literal[string] ,
identifier[configuration_option] = literal[st... | def s3_cache_timeout(self):
"""
The socket timeout in seconds for connections to Amazon S3 (an integer).
This value is injected into Boto's configuration to override the
default socket timeout used for connections to Amazon S3.
- Environment variable: ``$PIP_ACCEL_S3_TIMEOUT``
... |
def get_datetime_issue_in_progress(self, issue):
"""
If the issue is in progress, gets that most recent time that the issue became 'In Progress'
"""
histories = issue.changelog.histories
for history in reversed(histories):
history_items = history.items
for... | def function[get_datetime_issue_in_progress, parameter[self, issue]]:
constant[
If the issue is in progress, gets that most recent time that the issue became 'In Progress'
]
variable[histories] assign[=] name[issue].changelog.histories
for taget[name[history]] in starred[call[nam... | keyword[def] identifier[get_datetime_issue_in_progress] ( identifier[self] , identifier[issue] ):
literal[string]
identifier[histories] = identifier[issue] . identifier[changelog] . identifier[histories]
keyword[for] identifier[history] keyword[in] identifier[reversed] ( identifier[his... | def get_datetime_issue_in_progress(self, issue):
"""
If the issue is in progress, gets that most recent time that the issue became 'In Progress'
"""
histories = issue.changelog.histories
for history in reversed(histories):
history_items = history.items
for item in history_ite... |
def _set_if_type(self, v, load=False):
"""
Setter method for if_type, mapped from YANG variable /mpls_state/dynamic_bypass/dynamic_bypass_interface/if_type (mpls-if-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_if_type is considered as a private
method. Backe... | def function[_set_if_type, parameter[self, v, load]]:
constant[
Setter method for if_type, mapped from YANG variable /mpls_state/dynamic_bypass/dynamic_bypass_interface/if_type (mpls-if-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_if_type is considered as a ... | keyword[def] identifier[_set_if_type] ( 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] :
identi... | def _set_if_type(self, v, load=False):
"""
Setter method for if_type, mapped from YANG variable /mpls_state/dynamic_bypass/dynamic_bypass_interface/if_type (mpls-if-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_if_type is considered as a private
method. Backe... |
def use(network=False):
"""
Creates a new isolated mock engine to be used via context manager.
Example::
with pook.use() as engine:
pook.mock('server.com/foo').reply(404)
res = requests.get('server.com/foo')
assert res.status_code == 404
"""
global _eng... | def function[use, parameter[network]]:
constant[
Creates a new isolated mock engine to be used via context manager.
Example::
with pook.use() as engine:
pook.mock('server.com/foo').reply(404)
res = requests.get('server.com/foo')
assert res.status_code == 40... | keyword[def] identifier[use] ( identifier[network] = keyword[False] ):
literal[string]
keyword[global] identifier[_engine]
identifier[__engine] = identifier[_engine]
identifier[activated] = identifier[__engine] . identifier[active]
keyword[if] identifier[activated] :
iden... | def use(network=False):
"""
Creates a new isolated mock engine to be used via context manager.
Example::
with pook.use() as engine:
pook.mock('server.com/foo').reply(404)
res = requests.get('server.com/foo')
assert res.status_code == 404
"""
global _eng... |
def inet_ntop(family, address):
"""Convert the binary form of a network address into its textual form.
@param family: the address family
@type family: int
@param address: the binary address
@type address: string
@raises NotImplementedError: the address family specified is not
implemented.
... | def function[inet_ntop, parameter[family, address]]:
constant[Convert the binary form of a network address into its textual form.
@param family: the address family
@type family: int
@param address: the binary address
@type address: string
@raises NotImplementedError: the address family spec... | keyword[def] identifier[inet_ntop] ( identifier[family] , identifier[address] ):
literal[string]
keyword[if] identifier[family] == identifier[AF_INET] :
keyword[return] identifier[dns] . identifier[ipv4] . identifier[inet_ntoa] ( identifier[address] )
keyword[elif] identifier[family] == id... | def inet_ntop(family, address):
"""Convert the binary form of a network address into its textual form.
@param family: the address family
@type family: int
@param address: the binary address
@type address: string
@raises NotImplementedError: the address family specified is not
implemented.
... |
def cascade_delete(self, name):
"this fails under diamond inheritance"
for child in self[name].child_tables:
self.cascade_delete(child.name)
del self[name] | def function[cascade_delete, parameter[self, name]]:
constant[this fails under diamond inheritance]
for taget[name[child]] in starred[call[name[self]][name[name]].child_tables] begin[:]
call[name[self].cascade_delete, parameter[name[child].name]]
<ast.Delete object at 0x7da1b158b0d0> | keyword[def] identifier[cascade_delete] ( identifier[self] , identifier[name] ):
literal[string]
keyword[for] identifier[child] keyword[in] identifier[self] [ identifier[name] ]. identifier[child_tables] :
identifier[self] . identifier[cascade_delete] ( identifier[child] . identifier[name] )
... | def cascade_delete(self, name):
"""this fails under diamond inheritance"""
for child in self[name].child_tables:
self.cascade_delete(child.name) # depends on [control=['for'], data=['child']]
del self[name] |
def get_framebuffer_size(window):
"""
Retrieves the size of the framebuffer of the specified window.
Wrapper for:
void glfwGetFramebufferSize(GLFWwindow* window, int* width, int* height);
"""
width_value = ctypes.c_int(0)
width = ctypes.pointer(width_value)
height_value = ctypes.c_i... | def function[get_framebuffer_size, parameter[window]]:
constant[
Retrieves the size of the framebuffer of the specified window.
Wrapper for:
void glfwGetFramebufferSize(GLFWwindow* window, int* width, int* height);
]
variable[width_value] assign[=] call[name[ctypes].c_int, parameter... | keyword[def] identifier[get_framebuffer_size] ( identifier[window] ):
literal[string]
identifier[width_value] = identifier[ctypes] . identifier[c_int] ( literal[int] )
identifier[width] = identifier[ctypes] . identifier[pointer] ( identifier[width_value] )
identifier[height_value] = identifier[ct... | def get_framebuffer_size(window):
"""
Retrieves the size of the framebuffer of the specified window.
Wrapper for:
void glfwGetFramebufferSize(GLFWwindow* window, int* width, int* height);
"""
width_value = ctypes.c_int(0)
width = ctypes.pointer(width_value)
height_value = ctypes.c_i... |
async def get_updates(self, offset: typing.Union[base.Integer, None] = None,
limit: typing.Union[base.Integer, None] = None,
timeout: typing.Union[base.Integer, None] = None,
allowed_updates:
typing.Union[typing.List... | <ast.AsyncFunctionDef object at 0x7da1b17bb8b0> | keyword[async] keyword[def] identifier[get_updates] ( identifier[self] , identifier[offset] : identifier[typing] . identifier[Union] [ identifier[base] . identifier[Integer] , keyword[None] ]= keyword[None] ,
identifier[limit] : identifier[typing] . identifier[Union] [ identifier[base] . identifier[Integer] , keywo... | async def get_updates(self, offset: typing.Union[base.Integer, None]=None, limit: typing.Union[base.Integer, None]=None, timeout: typing.Union[base.Integer, None]=None, allowed_updates: typing.Union[typing.List[base.String], None]=None) -> typing.List[types.Update]:
"""
Use this method to receive incoming u... |
def delete(sld, tld, nameserver):
'''
Deletes a nameserver. Returns ``True`` if the nameserver was deleted
successfully
sld
SLD of the domain name
tld
TLD of the domain name
nameserver
Nameserver to delete
CLI Example:
.. code-block:: bash
salt '*' n... | def function[delete, parameter[sld, tld, nameserver]]:
constant[
Deletes a nameserver. Returns ``True`` if the nameserver was deleted
successfully
sld
SLD of the domain name
tld
TLD of the domain name
nameserver
Nameserver to delete
CLI Example:
.. code-b... | keyword[def] identifier[delete] ( identifier[sld] , identifier[tld] , identifier[nameserver] ):
literal[string]
identifier[opts] = identifier[salt] . identifier[utils] . identifier[namecheap] . identifier[get_opts] ( literal[string] )
identifier[opts] [ literal[string] ]= identifier[sld]
identif... | def delete(sld, tld, nameserver):
"""
Deletes a nameserver. Returns ``True`` if the nameserver was deleted
successfully
sld
SLD of the domain name
tld
TLD of the domain name
nameserver
Nameserver to delete
CLI Example:
.. code-block:: bash
salt '*' n... |
def _sasl_authenticate(self, stream, username, authzid):
"""Start SASL authentication process.
[initiating entity only]
:Parameters:
- `username`: user name.
- `authzid`: authorization ID.
- `mechanism`: SASL mechanism to use."""
if not stream.initia... | def function[_sasl_authenticate, parameter[self, stream, username, authzid]]:
constant[Start SASL authentication process.
[initiating entity only]
:Parameters:
- `username`: user name.
- `authzid`: authorization ID.
- `mechanism`: SASL mechanism to use.]
... | keyword[def] identifier[_sasl_authenticate] ( identifier[self] , identifier[stream] , identifier[username] , identifier[authzid] ):
literal[string]
keyword[if] keyword[not] identifier[stream] . identifier[initiator] :
keyword[raise] identifier[SASLAuthenticationFailed] ( literal[str... | def _sasl_authenticate(self, stream, username, authzid):
"""Start SASL authentication process.
[initiating entity only]
:Parameters:
- `username`: user name.
- `authzid`: authorization ID.
- `mechanism`: SASL mechanism to use."""
if not stream.initiator:
... |
def get_param_WLS(A, C_D_inv, d, inv_bool=True):
"""
returns the parameter values given
:param A: response matrix Nd x Ns (Nd = # data points, Ns = # parameters)
:param C_D_inv: inverse covariance matrix of the data, Nd x Nd, diagonal form
:param d: data array, 1-d Nd
:param inv_bool: boolean, w... | def function[get_param_WLS, parameter[A, C_D_inv, d, inv_bool]]:
constant[
returns the parameter values given
:param A: response matrix Nd x Ns (Nd = # data points, Ns = # parameters)
:param C_D_inv: inverse covariance matrix of the data, Nd x Nd, diagonal form
:param d: data array, 1-d Nd
:... | keyword[def] identifier[get_param_WLS] ( identifier[A] , identifier[C_D_inv] , identifier[d] , identifier[inv_bool] = keyword[True] ):
literal[string]
identifier[M] = identifier[A] . identifier[T] . identifier[dot] ( identifier[np] . identifier[multiply] ( identifier[C_D_inv] , identifier[A] . identifier[T... | def get_param_WLS(A, C_D_inv, d, inv_bool=True):
"""
returns the parameter values given
:param A: response matrix Nd x Ns (Nd = # data points, Ns = # parameters)
:param C_D_inv: inverse covariance matrix of the data, Nd x Nd, diagonal form
:param d: data array, 1-d Nd
:param inv_bool: boolean, w... |
def _w_within_shard(args: Dict[str, Any]):
"""Applies a W gate when the gate acts only within a shard."""
index = args['index']
half_turns = args['half_turns']
axis_half_turns = args['axis_half_turns']
state = _state_shard(args)
pm_vect = _pm_vects(args)[index]
num_shard_qubits = args['num_s... | def function[_w_within_shard, parameter[args]]:
constant[Applies a W gate when the gate acts only within a shard.]
variable[index] assign[=] call[name[args]][constant[index]]
variable[half_turns] assign[=] call[name[args]][constant[half_turns]]
variable[axis_half_turns] assign[=] call[na... | keyword[def] identifier[_w_within_shard] ( identifier[args] : identifier[Dict] [ identifier[str] , identifier[Any] ]):
literal[string]
identifier[index] = identifier[args] [ literal[string] ]
identifier[half_turns] = identifier[args] [ literal[string] ]
identifier[axis_half_turns] = identifier[ar... | def _w_within_shard(args: Dict[str, Any]):
"""Applies a W gate when the gate acts only within a shard."""
index = args['index']
half_turns = args['half_turns']
axis_half_turns = args['axis_half_turns']
state = _state_shard(args)
pm_vect = _pm_vects(args)[index]
num_shard_qubits = args['num_s... |
def render_with(template=None, json=False, jsonp=False):
"""
Decorator to render the wrapped function with the given template (or dictionary
of mimetype keys to templates, where the template is a string name of a template
file or a callable that returns a Response). The function's return value must be
... | def function[render_with, parameter[template, json, jsonp]]:
constant[
Decorator to render the wrapped function with the given template (or dictionary
of mimetype keys to templates, where the template is a string name of a template
file or a callable that returns a Response). The function's return v... | keyword[def] identifier[render_with] ( identifier[template] = keyword[None] , identifier[json] = keyword[False] , identifier[jsonp] = keyword[False] ):
literal[string]
keyword[if] identifier[jsonp] :
identifier[templates] ={
literal[string] : identifier[dict_jsonp] ,
literal[str... | def render_with(template=None, json=False, jsonp=False):
"""
Decorator to render the wrapped function with the given template (or dictionary
of mimetype keys to templates, where the template is a string name of a template
file or a callable that returns a Response). The function's return value must be
... |
def _parallel_predict_proba(estimators, estimators_features, X, n_classes, combination, estimators_weight):
"""Private function used to compute (proba-)predictions within a job."""
n_samples = X.shape[0]
proba = np.zeros((n_samples, n_classes))
for estimator, features, weight in zip(estimators, estimat... | def function[_parallel_predict_proba, parameter[estimators, estimators_features, X, n_classes, combination, estimators_weight]]:
constant[Private function used to compute (proba-)predictions within a job.]
variable[n_samples] assign[=] call[name[X].shape][constant[0]]
variable[proba] assign[=] c... | keyword[def] identifier[_parallel_predict_proba] ( identifier[estimators] , identifier[estimators_features] , identifier[X] , identifier[n_classes] , identifier[combination] , identifier[estimators_weight] ):
literal[string]
identifier[n_samples] = identifier[X] . identifier[shape] [ literal[int] ]
id... | def _parallel_predict_proba(estimators, estimators_features, X, n_classes, combination, estimators_weight):
"""Private function used to compute (proba-)predictions within a job."""
n_samples = X.shape[0]
proba = np.zeros((n_samples, n_classes))
for (estimator, features, weight) in zip(estimators, estima... |
def get(self, id, seq, intf): # pylint: disable=invalid-name,redefined-builtin
"""Get a capture.
:param id: Result ID as an int.
:param seq: TestResult sequence ID as an int.
:param intf: Interface name as string.
:return: :class:`captures.Capture <captures.Capture>` object
... | def function[get, parameter[self, id, seq, intf]]:
constant[Get a capture.
:param id: Result ID as an int.
:param seq: TestResult sequence ID as an int.
:param intf: Interface name as string.
:return: :class:`captures.Capture <captures.Capture>` object
:rtype: captures.C... | keyword[def] identifier[get] ( identifier[self] , identifier[id] , identifier[seq] , identifier[intf] ):
literal[string]
identifier[schema] = identifier[CaptureSchema] ()
identifier[resp] = identifier[self] . identifier[service] . identifier[get_id] ( identifier[self] . identifier[_base] (... | def get(self, id, seq, intf): # pylint: disable=invalid-name,redefined-builtin
'Get a capture.\n\n :param id: Result ID as an int.\n :param seq: TestResult sequence ID as an int.\n :param intf: Interface name as string.\n :return: :class:`captures.Capture <captures.Capture>` object\n ... |
def reader(path):
"""
Turns a path to a dump file into a file-like object of (decompressed)
XML data assuming that '7z' is installed and will know what to do.
:Parameters:
path : `str`
the path to the dump file to read
"""
p = subprocess.Popen(
['7z', 'e', '-so', pat... | def function[reader, parameter[path]]:
constant[
Turns a path to a dump file into a file-like object of (decompressed)
XML data assuming that '7z' is installed and will know what to do.
:Parameters:
path : `str`
the path to the dump file to read
]
variable[p] assign[... | keyword[def] identifier[reader] ( identifier[path] ):
literal[string]
identifier[p] = identifier[subprocess] . identifier[Popen] (
[ literal[string] , literal[string] , literal[string] , identifier[path] ],
identifier[stdout] = identifier[subprocess] . identifier[PIPE] ,
identifier[stderr] = ... | def reader(path):
"""
Turns a path to a dump file into a file-like object of (decompressed)
XML data assuming that '7z' is installed and will know what to do.
:Parameters:
path : `str`
the path to the dump file to read
"""
p = subprocess.Popen(['7z', 'e', '-so', path], stdou... |
def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs):
"""Initializes a urllib3 PoolManager.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
... | def function[init_poolmanager, parameter[self, connections, maxsize, block]]:
constant[Initializes a urllib3 PoolManager.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:par... | keyword[def] identifier[init_poolmanager] ( identifier[self] , identifier[connections] , identifier[maxsize] , identifier[block] = identifier[DEFAULT_POOLBLOCK] ,** identifier[pool_kwargs] ):
literal[string]
identifier[self] . identifier[_pool_connections] = identifier[connections]
... | def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs):
"""Initializes a urllib3 PoolManager.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:p... |
def geneinfo(args):
"""
%prog geneinfo pineapple.20141004.bed liftover.bed pineapple.20150413.bed \
note.txt interproscan.txt
Build gene info table from various sources. The three beds contain
information on the original scaffolds, linkage groups, and final selected
loci (after r... | def function[geneinfo, parameter[args]]:
constant[
%prog geneinfo pineapple.20141004.bed liftover.bed pineapple.20150413.bed note.txt interproscan.txt
Build gene info table from various sources. The three beds contain
information on the original scaffolds, linkage groups, and fin... | keyword[def] identifier[geneinfo] ( identifier[args] ):
literal[string]
identifier[p] = identifier[OptionParser] ( identifier[geneinfo] . identifier[__doc__] )
identifier[opts] , identifier[args] = identifier[p] . identifier[parse_args] ( identifier[args] )
keyword[if] identifier[len] ( identif... | def geneinfo(args):
"""
%prog geneinfo pineapple.20141004.bed liftover.bed pineapple.20150413.bed note.txt interproscan.txt
Build gene info table from various sources. The three beds contain
information on the original scaffolds, linkage groups, and final selected
loci (after rem... |
def banner(cls, content_="Well Come"):
"""生成占3行的字符串"""
# char def
sp_char = "#"
# length calc
itsays = content_.strip()
effective_length = int(len(itsays))
# gen contents
side_space = ' ' * int(effective_length * ((1 - 0.618) / 0.618) / 2)
content_... | def function[banner, parameter[cls, content_]]:
constant[生成占3行的字符串]
variable[sp_char] assign[=] constant[#]
variable[itsays] assign[=] call[name[content_].strip, parameter[]]
variable[effective_length] assign[=] call[name[int], parameter[call[name[len], parameter[name[itsays]]]]]
... | keyword[def] identifier[banner] ( identifier[cls] , identifier[content_] = literal[string] ):
literal[string]
identifier[sp_char] = literal[string]
identifier[itsays] = identifier[content_] . identifier[strip] ()
identifier[effective_length] = identifier[int] ( ... | def banner(cls, content_='Well Come'):
"""生成占3行的字符串"""
# char def
sp_char = '#'
# length calc
itsays = content_.strip()
effective_length = int(len(itsays))
# gen contents
side_space = ' ' * int(effective_length * ((1 - 0.618) / 0.618) / 2)
content_line = sp_char + side_space + itsays... |
def get_instance(self, payload):
"""
Build an instance of ReservationInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationInstance
:rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.Reser... | def function[get_instance, parameter[self, payload]]:
constant[
Build an instance of ReservationInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationInstance
:rtype: twilio.rest.taskrouter.v1.works... | keyword[def] identifier[get_instance] ( identifier[self] , identifier[payload] ):
literal[string]
keyword[return] identifier[ReservationInstance] (
identifier[self] . identifier[_version] ,
identifier[payload] ,
identifier[workspace_sid] = identifier[self] . identifier[_... | def get_instance(self, payload):
"""
Build an instance of ReservationInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationInstance
:rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.Reservati... |
def coerce_to_array(values, dtype, mask=None, copy=False):
"""
Coerce the input values array to numpy arrays with a mask
Parameters
----------
values : 1D list-like
dtype : integer dtype
mask : boolean 1D array, optional
copy : boolean, default False
if True, copy the input
... | def function[coerce_to_array, parameter[values, dtype, mask, copy]]:
constant[
Coerce the input values array to numpy arrays with a mask
Parameters
----------
values : 1D list-like
dtype : integer dtype
mask : boolean 1D array, optional
copy : boolean, default False
if True,... | keyword[def] identifier[coerce_to_array] ( identifier[values] , identifier[dtype] , identifier[mask] = keyword[None] , identifier[copy] = keyword[False] ):
literal[string]
keyword[if] identifier[dtype] keyword[is] keyword[None] keyword[and] identifier[hasattr] ( identifier[values] , literal[strin... | def coerce_to_array(values, dtype, mask=None, copy=False):
"""
Coerce the input values array to numpy arrays with a mask
Parameters
----------
values : 1D list-like
dtype : integer dtype
mask : boolean 1D array, optional
copy : boolean, default False
if True, copy the input
... |
def multiple_replace(d: Dict[str, str], text: str) -> str:
""" Performs string replacement from dict in a single pass. Taken from
https://www.oreilly.com/library/view/python-cookbook/0596001673/ch03s15.html
"""
# Create a regular expression from all of the dictionary keys
regex = re.compile("|".join(m... | def function[multiple_replace, parameter[d, text]]:
constant[ Performs string replacement from dict in a single pass. Taken from
https://www.oreilly.com/library/view/python-cookbook/0596001673/ch03s15.html
]
variable[regex] assign[=] call[name[re].compile, parameter[call[constant[|].join, parame... | keyword[def] identifier[multiple_replace] ( identifier[d] : identifier[Dict] [ identifier[str] , identifier[str] ], identifier[text] : identifier[str] )-> identifier[str] :
literal[string]
identifier[regex] = identifier[re] . identifier[compile] ( literal[string] . identifier[join] ( identifier[map] (... | def multiple_replace(d: Dict[str, str], text: str) -> str:
""" Performs string replacement from dict in a single pass. Taken from
https://www.oreilly.com/library/view/python-cookbook/0596001673/ch03s15.html
"""
# Create a regular expression from all of the dictionary keys
regex = re.compile('|'.join... |
def _get_inputs(self, old_inputs):
"""Converts command line args into a list of template inputs
"""
# Convert inputs to dict to facilitate overriding by channel name
# Also, drop DataNode ID and keep only contents.
input_dict = {}
for input in old_inputs:
# St... | def function[_get_inputs, parameter[self, old_inputs]]:
constant[Converts command line args into a list of template inputs
]
variable[input_dict] assign[=] dictionary[[], []]
for taget[name[input]] in starred[name[old_inputs]] begin[:]
call[name[input]][constant[data]] as... | keyword[def] identifier[_get_inputs] ( identifier[self] , identifier[old_inputs] ):
literal[string]
identifier[input_dict] ={}
keyword[for] identifier[input] keyword[in] identifier[old_inputs] :
identifier[input] [ literal[string] ]={ literal[stri... | def _get_inputs(self, old_inputs):
"""Converts command line args into a list of template inputs
"""
# Convert inputs to dict to facilitate overriding by channel name
# Also, drop DataNode ID and keep only contents.
input_dict = {}
for input in old_inputs:
# Strip out DataNode UUID an... |
def data(self, column, role):
"""Return the data for the specified column and role
The column addresses one attribute of the data.
:param column: the data column
:type column: int
:param role: the data role
:type role: QtCore.Qt.ItemDataRole
:returns: data depen... | def function[data, parameter[self, column, role]]:
constant[Return the data for the specified column and role
The column addresses one attribute of the data.
:param column: the data column
:type column: int
:param role: the data role
:type role: QtCore.Qt.ItemDataRole
... | keyword[def] identifier[data] ( identifier[self] , identifier[column] , identifier[role] ):
literal[string]
keyword[return] identifier[self] . identifier[columns] [ identifier[column] ]( identifier[self] . identifier[_Department] , identifier[role] ) | def data(self, column, role):
"""Return the data for the specified column and role
The column addresses one attribute of the data.
:param column: the data column
:type column: int
:param role: the data role
:type role: QtCore.Qt.ItemDataRole
:returns: data depending... |
def options(self, context, module_options):
'''
PATH Path to the file containing raw shellcode to inject
PROCID Process ID to inject into (default: current powershell process)
'''
if not 'PATH' in module_options:
context.log.error('PATH option is requir... | def function[options, parameter[self, context, module_options]]:
constant[
PATH Path to the file containing raw shellcode to inject
PROCID Process ID to inject into (default: current powershell process)
]
if <ast.UnaryOp object at 0x7da1b1c351b0> begin[:]
... | keyword[def] identifier[options] ( identifier[self] , identifier[context] , identifier[module_options] ):
literal[string]
keyword[if] keyword[not] literal[string] keyword[in] identifier[module_options] :
identifier[context] . identifier[log] . identifier[error] ( literal[string] )... | def options(self, context, module_options):
"""
PATH Path to the file containing raw shellcode to inject
PROCID Process ID to inject into (default: current powershell process)
"""
if not 'PATH' in module_options:
context.log.error('PATH option is required!')
... |
def getOrCreate(cls, conf=None):
"""
Get or instantiate a SparkContext and register it as a singleton object.
:param conf: SparkConf (optional)
"""
with SparkContext._lock:
if SparkContext._active_spark_context is None:
SparkContext(conf=conf or Spark... | def function[getOrCreate, parameter[cls, conf]]:
constant[
Get or instantiate a SparkContext and register it as a singleton object.
:param conf: SparkConf (optional)
]
with name[SparkContext]._lock begin[:]
if compare[name[SparkContext]._active_spark_context is c... | keyword[def] identifier[getOrCreate] ( identifier[cls] , identifier[conf] = keyword[None] ):
literal[string]
keyword[with] identifier[SparkContext] . identifier[_lock] :
keyword[if] identifier[SparkContext] . identifier[_active_spark_context] keyword[is] keyword[None] :
... | def getOrCreate(cls, conf=None):
"""
Get or instantiate a SparkContext and register it as a singleton object.
:param conf: SparkConf (optional)
"""
with SparkContext._lock:
if SparkContext._active_spark_context is None:
SparkContext(conf=conf or SparkConf()) # depen... |
def from_array(array):
"""
Deserialize a new OrderInfo from a given dictionary.
:return: new OrderInfo instance.
:rtype: OrderInfo
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array"... | def function[from_array, parameter[array]]:
constant[
Deserialize a new OrderInfo from a given dictionary.
:return: new OrderInfo instance.
:rtype: OrderInfo
]
if <ast.BoolOp object at 0x7da1b0400ac0> begin[:]
return[constant[None]]
call[name[assert_type_... | keyword[def] identifier[from_array] ( identifier[array] ):
literal[string]
keyword[if] identifier[array] keyword[is] keyword[None] keyword[or] keyword[not] identifier[array] :
keyword[return] keyword[None]
identifier[assert_type_or_raise] ( identifier[arra... | def from_array(array):
"""
Deserialize a new OrderInfo from a given dictionary.
:return: new OrderInfo instance.
:rtype: OrderInfo
"""
if array is None or not array:
return None # depends on [control=['if'], data=[]]
# end if
assert_type_or_raise(array, dict, pa... |
def _authenticate_client(self, client):
"""Authenticate the client if necessary."""
if self.login and not self.restart_required:
try:
db = client[self.auth_source]
if self.x509_extra_user:
db.authenticate(
DEFAULT_SU... | def function[_authenticate_client, parameter[self, client]]:
constant[Authenticate the client if necessary.]
if <ast.BoolOp object at 0x7da20c6e6bf0> begin[:]
<ast.Try object at 0x7da20c6e4ac0> | keyword[def] identifier[_authenticate_client] ( identifier[self] , identifier[client] ):
literal[string]
keyword[if] identifier[self] . identifier[login] keyword[and] keyword[not] identifier[self] . identifier[restart_required] :
keyword[try] :
identifier[db] = ide... | def _authenticate_client(self, client):
"""Authenticate the client if necessary."""
if self.login and (not self.restart_required):
try:
db = client[self.auth_source]
if self.x509_extra_user:
db.authenticate(DEFAULT_SUBJECT, mechanism='MONGODB-X509') # depends on ... |
def add_section(self):
"""Add a section, a sub-CodeBuilder."""
sect = CodeBuilder(self.indent_amount)
self.code.append(sect)
return sect | def function[add_section, parameter[self]]:
constant[Add a section, a sub-CodeBuilder.]
variable[sect] assign[=] call[name[CodeBuilder], parameter[name[self].indent_amount]]
call[name[self].code.append, parameter[name[sect]]]
return[name[sect]] | keyword[def] identifier[add_section] ( identifier[self] ):
literal[string]
identifier[sect] = identifier[CodeBuilder] ( identifier[self] . identifier[indent_amount] )
identifier[self] . identifier[code] . identifier[append] ( identifier[sect] )
keyword[return] identifier[sect] | def add_section(self):
"""Add a section, a sub-CodeBuilder."""
sect = CodeBuilder(self.indent_amount)
self.code.append(sect)
return sect |
def get_plot(self, width=8, height=8):
"""
Returns a plot object.
Args:
width: Width of the plot. Defaults to 8 in.
height: Height of the plot. Defaults to 6 in.
Returns:
A matplotlib plot object.
"""
plt = pretty_plot(width, height)
... | def function[get_plot, parameter[self, width, height]]:
constant[
Returns a plot object.
Args:
width: Width of the plot. Defaults to 8 in.
height: Height of the plot. Defaults to 6 in.
Returns:
A matplotlib plot object.
]
variable[plt... | keyword[def] identifier[get_plot] ( identifier[self] , identifier[width] = literal[int] , identifier[height] = literal[int] ):
literal[string]
identifier[plt] = identifier[pretty_plot] ( identifier[width] , identifier[height] )
keyword[for] identifier[label] , identifier[electrode] keywo... | def get_plot(self, width=8, height=8):
"""
Returns a plot object.
Args:
width: Width of the plot. Defaults to 8 in.
height: Height of the plot. Defaults to 6 in.
Returns:
A matplotlib plot object.
"""
plt = pretty_plot(width, height)
for ... |
def ExtractEvents(self, parser_mediator, registry_key, **kwargs):
"""Extracts events from a Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows ... | def function[ExtractEvents, parameter[self, parser_mediator, registry_key]]:
constant[Extracts events from a Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinR... | keyword[def] identifier[ExtractEvents] ( identifier[self] , identifier[parser_mediator] , identifier[registry_key] ,** identifier[kwargs] ):
literal[string]
identifier[values_dict] ={}
keyword[if] identifier[registry_key] . identifier[number_of_values] == literal[int] :
identifier[values_dict... | def ExtractEvents(self, parser_mediator, registry_key, **kwargs):
"""Extracts events from a Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows ... |
def register_monitors(self, *monitors):
"""
Register monitors they should be tuple of name and Theano variable.
"""
for key, node in monitors:
if key not in self._registered_monitors:
node *= 1.0 # Avoid CudaNdarray
self.training_monitors.appen... | def function[register_monitors, parameter[self]]:
constant[
Register monitors they should be tuple of name and Theano variable.
]
for taget[tuple[[<ast.Name object at 0x7da1b05c4250>, <ast.Name object at 0x7da1b05c66e0>]]] in starred[name[monitors]] begin[:]
if compare[na... | keyword[def] identifier[register_monitors] ( identifier[self] ,* identifier[monitors] ):
literal[string]
keyword[for] identifier[key] , identifier[node] keyword[in] identifier[monitors] :
keyword[if] identifier[key] keyword[not] keyword[in] identifier[self] . identifier[_registe... | def register_monitors(self, *monitors):
"""
Register monitors they should be tuple of name and Theano variable.
"""
for (key, node) in monitors:
if key not in self._registered_monitors:
node *= 1.0 # Avoid CudaNdarray
self.training_monitors.append((key, node))
... |
def get_qc_tools(data):
"""Retrieve a list of QC tools to use based on configuration and analysis type.
Uses defaults if previously set.
"""
if dd.get_algorithm_qc(data):
return dd.get_algorithm_qc(data)
analysis = data["analysis"].lower()
to_run = []
if tz.get_in(["config", "algori... | def function[get_qc_tools, parameter[data]]:
constant[Retrieve a list of QC tools to use based on configuration and analysis type.
Uses defaults if previously set.
]
if call[name[dd].get_algorithm_qc, parameter[name[data]]] begin[:]
return[call[name[dd].get_algorithm_qc, parameter[name[... | keyword[def] identifier[get_qc_tools] ( identifier[data] ):
literal[string]
keyword[if] identifier[dd] . identifier[get_algorithm_qc] ( identifier[data] ):
keyword[return] identifier[dd] . identifier[get_algorithm_qc] ( identifier[data] )
identifier[analysis] = identifier[data] [ literal[st... | def get_qc_tools(data):
"""Retrieve a list of QC tools to use based on configuration and analysis type.
Uses defaults if previously set.
"""
if dd.get_algorithm_qc(data):
return dd.get_algorithm_qc(data) # depends on [control=['if'], data=[]]
analysis = data['analysis'].lower()
to_run ... |
def add_edges(self, edges, src_field=None, dst_field=None):
"""
Add edges to the SGraph. Edges should be input as a list of
:class:`~turicreate.Edge` objects, an :class:`~turicreate.SFrame`, or a
Pandas DataFrame. If the new edges are in an SFrame or DataFrame, then
``src_field``... | def function[add_edges, parameter[self, edges, src_field, dst_field]]:
constant[
Add edges to the SGraph. Edges should be input as a list of
:class:`~turicreate.Edge` objects, an :class:`~turicreate.SFrame`, or a
Pandas DataFrame. If the new edges are in an SFrame or DataFrame, then
... | keyword[def] identifier[add_edges] ( identifier[self] , identifier[edges] , identifier[src_field] = keyword[None] , identifier[dst_field] = keyword[None] ):
literal[string]
identifier[sf] = identifier[_edge_data_to_sframe] ( identifier[edges] , identifier[src_field] , identifier[dst_field] )
... | def add_edges(self, edges, src_field=None, dst_field=None):
"""
Add edges to the SGraph. Edges should be input as a list of
:class:`~turicreate.Edge` objects, an :class:`~turicreate.SFrame`, or a
Pandas DataFrame. If the new edges are in an SFrame or DataFrame, then
``src_field`` and... |
def get_version(path=VERSION_PATH):
"""
Reads the python file defined in the VERSION_PATH to find the get_version
function, and executes it to ensure that it is loaded correctly. Separating
the version in this way ensures no additional code is executed.
"""
namespace = {}
exec(read(path), na... | def function[get_version, parameter[path]]:
constant[
Reads the python file defined in the VERSION_PATH to find the get_version
function, and executes it to ensure that it is loaded correctly. Separating
the version in this way ensures no additional code is executed.
]
variable[namespace... | keyword[def] identifier[get_version] ( identifier[path] = identifier[VERSION_PATH] ):
literal[string]
identifier[namespace] ={}
identifier[exec] ( identifier[read] ( identifier[path] ), identifier[namespace] )
keyword[return] identifier[namespace] [ literal[string] ]( identifier[short] = keyword... | def get_version(path=VERSION_PATH):
"""
Reads the python file defined in the VERSION_PATH to find the get_version
function, and executes it to ensure that it is loaded correctly. Separating
the version in this way ensures no additional code is executed.
"""
namespace = {}
exec(read(path), na... |
def __callback (self, img):
'''
Callback function to receive and save Images.
@param img: ROS Image received
@type img: sensor_msgs.msg.Image
'''
image = imageMsg2Image(img, self.bridge)
self.lock.acquire()
self.data = image
self.lock.... | def function[__callback, parameter[self, img]]:
constant[
Callback function to receive and save Images.
@param img: ROS Image received
@type img: sensor_msgs.msg.Image
]
variable[image] assign[=] call[name[imageMsg2Image], parameter[name[img], name[self].bridg... | keyword[def] identifier[__callback] ( identifier[self] , identifier[img] ):
literal[string]
identifier[image] = identifier[imageMsg2Image] ( identifier[img] , identifier[self] . identifier[bridge] )
identifier[self] . identifier[lock] . identifier[acquire] ()
identifier[self] . i... | def __callback(self, img):
"""
Callback function to receive and save Images.
@param img: ROS Image received
@type img: sensor_msgs.msg.Image
"""
image = imageMsg2Image(img, self.bridge)
self.lock.acquire()
self.data = image
self.lock.release() |
def update(self):
"""Cache the list into the data section of the record"""
from ambry.orm.exc import NotFoundError
from requests.exceptions import ConnectionError, HTTPError
from boto.exception import S3ResponseError
d = {}
try:
for k, v in self.list(full=T... | def function[update, parameter[self]]:
constant[Cache the list into the data section of the record]
from relative_module[ambry.orm.exc] import module[NotFoundError]
from relative_module[requests.exceptions] import module[ConnectionError], module[HTTPError]
from relative_module[boto.exception] import... | keyword[def] identifier[update] ( identifier[self] ):
literal[string]
keyword[from] identifier[ambry] . identifier[orm] . identifier[exc] keyword[import] identifier[NotFoundError]
keyword[from] identifier[requests] . identifier[exceptions] keyword[import] identifier[ConnectionError... | def update(self):
"""Cache the list into the data section of the record"""
from ambry.orm.exc import NotFoundError
from requests.exceptions import ConnectionError, HTTPError
from boto.exception import S3ResponseError
d = {}
try:
for (k, v) in self.list(full=True):
if not v:
... |
def order_by_json_path(self, json_path, language_code=None, order='asc'):
"""
Makes the method available through the manager (i.e. `Model.objects`).
Usage example:
MyModel.objects.order_by_json_path('title', order='desc')
MyModel.objects.order_by_json_path('title', langu... | def function[order_by_json_path, parameter[self, json_path, language_code, order]]:
constant[
Makes the method available through the manager (i.e. `Model.objects`).
Usage example:
MyModel.objects.order_by_json_path('title', order='desc')
MyModel.objects.order_by_json_pat... | keyword[def] identifier[order_by_json_path] ( identifier[self] , identifier[json_path] , identifier[language_code] = keyword[None] , identifier[order] = literal[string] ):
literal[string]
keyword[return] identifier[self] . identifier[get_queryset] ( identifier[language_code] ). identifier[order_by... | def order_by_json_path(self, json_path, language_code=None, order='asc'):
"""
Makes the method available through the manager (i.e. `Model.objects`).
Usage example:
MyModel.objects.order_by_json_path('title', order='desc')
MyModel.objects.order_by_json_path('title', language_... |
def RegisterIntKey(cls, key, atomid, min_value=0, max_value=(2 ** 16) - 1):
"""Register a scalar integer key.
"""
def getter(tags, key):
return list(map(text_type, tags[atomid]))
def setter(tags, key, value):
clamp = lambda x: int(min(max(min_value, x), max_valu... | def function[RegisterIntKey, parameter[cls, key, atomid, min_value, max_value]]:
constant[Register a scalar integer key.
]
def function[getter, parameter[tags, key]]:
return[call[name[list], parameter[call[name[map], parameter[name[text_type], call[name[tags]][name[atomid]]]]]]]
... | keyword[def] identifier[RegisterIntKey] ( identifier[cls] , identifier[key] , identifier[atomid] , identifier[min_value] = literal[int] , identifier[max_value] =( literal[int] ** literal[int] )- literal[int] ):
literal[string]
keyword[def] identifier[getter] ( identifier[tags] , identifier[key] )... | def RegisterIntKey(cls, key, atomid, min_value=0, max_value=2 ** 16 - 1):
"""Register a scalar integer key.
"""
def getter(tags, key):
return list(map(text_type, tags[atomid]))
def setter(tags, key, value):
clamp = lambda x: int(min(max(min_value, x), max_value))
tags[atomi... |
def predict(self, eval_data, num_batch=None, merge_batches=True, reset=True,
always_output_list=False, sparse_row_id_fn=None):
"""Runs prediction and collects the outputs.
When `merge_batches` is ``True`` (by default), the return value will be a list
``[out1, out2, out3]``, wher... | def function[predict, parameter[self, eval_data, num_batch, merge_batches, reset, always_output_list, sparse_row_id_fn]]:
constant[Runs prediction and collects the outputs.
When `merge_batches` is ``True`` (by default), the return value will be a list
``[out1, out2, out3]``, where each element ... | keyword[def] identifier[predict] ( identifier[self] , identifier[eval_data] , identifier[num_batch] = keyword[None] , identifier[merge_batches] = keyword[True] , identifier[reset] = keyword[True] ,
identifier[always_output_list] = keyword[False] , identifier[sparse_row_id_fn] = keyword[None] ):
literal[stri... | def predict(self, eval_data, num_batch=None, merge_batches=True, reset=True, always_output_list=False, sparse_row_id_fn=None):
"""Runs prediction and collects the outputs.
When `merge_batches` is ``True`` (by default), the return value will be a list
``[out1, out2, out3]``, where each element is fo... |
def to_dict(self):
"""Return this Context as a dict suitable for json encoding."""
import copy
options = copy.deepcopy(self._options)
if self._insert_tasks:
options['insert_tasks'] = reference_to_path(self._insert_tasks)
if self._persistence_engine:
opt... | def function[to_dict, parameter[self]]:
constant[Return this Context as a dict suitable for json encoding.]
import module[copy]
variable[options] assign[=] call[name[copy].deepcopy, parameter[name[self]._options]]
if name[self]._insert_tasks begin[:]
call[name[options]][const... | keyword[def] identifier[to_dict] ( identifier[self] ):
literal[string]
keyword[import] identifier[copy]
identifier[options] = identifier[copy] . identifier[deepcopy] ( identifier[self] . identifier[_options] )
keyword[if] identifier[self] . identifier[_insert_tasks] :
... | def to_dict(self):
"""Return this Context as a dict suitable for json encoding."""
import copy
options = copy.deepcopy(self._options)
if self._insert_tasks:
options['insert_tasks'] = reference_to_path(self._insert_tasks) # depends on [control=['if'], data=[]]
if self._persistence_engine:
... |
def empty(cls: Type[BoardT], *, chess960: bool = False) -> BoardT:
"""Creates a new empty board. Also see :func:`~chess.Board.clear()`."""
return cls(None, chess960=chess960) | def function[empty, parameter[cls]]:
constant[Creates a new empty board. Also see :func:`~chess.Board.clear()`.]
return[call[name[cls], parameter[constant[None]]]] | keyword[def] identifier[empty] ( identifier[cls] : identifier[Type] [ identifier[BoardT] ],*, identifier[chess960] : identifier[bool] = keyword[False] )-> identifier[BoardT] :
literal[string]
keyword[return] identifier[cls] ( keyword[None] , identifier[chess960] = identifier[chess960] ) | def empty(cls: Type[BoardT], *, chess960: bool=False) -> BoardT:
"""Creates a new empty board. Also see :func:`~chess.Board.clear()`."""
return cls(None, chess960=chess960) |
def rpc_spec_table(app):
"""Collects methods which are speced as RPC."""
table = {}
for attr, value in inspect.getmembers(app):
rpc_spec = get_rpc_spec(value, default=None)
if rpc_spec is None:
continue
table[rpc_spec.name] = (value, rpc_spec)
return table | def function[rpc_spec_table, parameter[app]]:
constant[Collects methods which are speced as RPC.]
variable[table] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name object at 0x7da1b0290310>, <ast.Name object at 0x7da1b0291270>]]] in starred[call[name[inspect].getmembers, parameter[name[app... | keyword[def] identifier[rpc_spec_table] ( identifier[app] ):
literal[string]
identifier[table] ={}
keyword[for] identifier[attr] , identifier[value] keyword[in] identifier[inspect] . identifier[getmembers] ( identifier[app] ):
identifier[rpc_spec] = identifier[get_rpc_spec] ( identifier[va... | def rpc_spec_table(app):
"""Collects methods which are speced as RPC."""
table = {}
for (attr, value) in inspect.getmembers(app):
rpc_spec = get_rpc_spec(value, default=None)
if rpc_spec is None:
continue # depends on [control=['if'], data=[]]
table[rpc_spec.name] = (val... |
def userKicked(self, kickee, channel, kicker, message):
"""Called when I see another user get kicked."""
self.dispatch('population', 'userKicked', kickee, channel, kicker,
message) | def function[userKicked, parameter[self, kickee, channel, kicker, message]]:
constant[Called when I see another user get kicked.]
call[name[self].dispatch, parameter[constant[population], constant[userKicked], name[kickee], name[channel], name[kicker], name[message]]] | keyword[def] identifier[userKicked] ( identifier[self] , identifier[kickee] , identifier[channel] , identifier[kicker] , identifier[message] ):
literal[string]
identifier[self] . identifier[dispatch] ( literal[string] , literal[string] , identifier[kickee] , identifier[channel] , identifier[kicker]... | def userKicked(self, kickee, channel, kicker, message):
"""Called when I see another user get kicked."""
self.dispatch('population', 'userKicked', kickee, channel, kicker, message) |
def get_next_step(self):
"""Find the proper step when user clicks the Next button.
:returns: The step to be switched to.
:rtype: WizardStep instance or None
"""
if self.layer_purpose != layer_purpose_aggregation:
subcategory = self.parent.step_kw_subcategory.\
... | def function[get_next_step, parameter[self]]:
constant[Find the proper step when user clicks the Next button.
:returns: The step to be switched to.
:rtype: WizardStep instance or None
]
if compare[name[self].layer_purpose not_equal[!=] name[layer_purpose_aggregation]] begin[:]
... | keyword[def] identifier[get_next_step] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[layer_purpose] != identifier[layer_purpose_aggregation] :
identifier[subcategory] = identifier[self] . identifier[parent] . identifier[step_kw_subcategory] . identifi... | def get_next_step(self):
"""Find the proper step when user clicks the Next button.
:returns: The step to be switched to.
:rtype: WizardStep instance or None
"""
if self.layer_purpose != layer_purpose_aggregation:
subcategory = self.parent.step_kw_subcategory.selected_subcategory... |
def spinner(
spinner_name=None,
start_text=None,
handler_map=None,
nospin=False,
write_to_stdout=True,
):
"""Get a spinner object or a dummy spinner to wrap a context.
:param str spinner_name: A spinner type e.g. "dots" or "bouncingBar" (default: {"bouncingBar"})
:param str start_text: ... | def function[spinner, parameter[spinner_name, start_text, handler_map, nospin, write_to_stdout]]:
constant[Get a spinner object or a dummy spinner to wrap a context.
:param str spinner_name: A spinner type e.g. "dots" or "bouncingBar" (default: {"bouncingBar"})
:param str start_text: Text to start off ... | keyword[def] identifier[spinner] (
identifier[spinner_name] = keyword[None] ,
identifier[start_text] = keyword[None] ,
identifier[handler_map] = keyword[None] ,
identifier[nospin] = keyword[False] ,
identifier[write_to_stdout] = keyword[True] ,
):
literal[string]
keyword[from] . identifier[spin] key... | def spinner(spinner_name=None, start_text=None, handler_map=None, nospin=False, write_to_stdout=True):
"""Get a spinner object or a dummy spinner to wrap a context.
:param str spinner_name: A spinner type e.g. "dots" or "bouncingBar" (default: {"bouncingBar"})
:param str start_text: Text to start off the s... |
def on_click(self, event):
"""
Switch the displayed module or pass the event on to the active module
"""
if event["button"] == self.button_reset:
self._change_active(0)
elif event["button"] == self.button_change_time_format:
self.active_time_format += 1
... | def function[on_click, parameter[self, event]]:
constant[
Switch the displayed module or pass the event on to the active module
]
if compare[call[name[event]][constant[button]] equal[==] name[self].button_reset] begin[:]
call[name[self]._change_active, parameter[constant[... | keyword[def] identifier[on_click] ( identifier[self] , identifier[event] ):
literal[string]
keyword[if] identifier[event] [ literal[string] ]== identifier[self] . identifier[button_reset] :
identifier[self] . identifier[_change_active] ( literal[int] )
keyword[elif] identifi... | def on_click(self, event):
"""
Switch the displayed module or pass the event on to the active module
"""
if event['button'] == self.button_reset:
self._change_active(0) # depends on [control=['if'], data=[]]
elif event['button'] == self.button_change_time_format:
self.active... |
def _read_join_ack(self, bits, size, kind):
"""Read Join Connection option for Third ACK.
Positional arguments:
* bits - str, 4-bit data
* size - int, length of option
* kind - int, 30 (Multipath TCP)
Returns:
* dict -- extracted Join Connection ... | def function[_read_join_ack, parameter[self, bits, size, kind]]:
constant[Read Join Connection option for Third ACK.
Positional arguments:
* bits - str, 4-bit data
* size - int, length of option
* kind - int, 30 (Multipath TCP)
Returns:
* dict --... | keyword[def] identifier[_read_join_ack] ( identifier[self] , identifier[bits] , identifier[size] , identifier[kind] ):
literal[string]
identifier[temp] = identifier[self] . identifier[_read_fileng] ( literal[int] )
identifier[data] = identifier[dict] (
identifier[kind] = identifi... | def _read_join_ack(self, bits, size, kind):
"""Read Join Connection option for Third ACK.
Positional arguments:
* bits - str, 4-bit data
* size - int, length of option
* kind - int, 30 (Multipath TCP)
Returns:
* dict -- extracted Join Connection (MP_... |
def replace_command(command, broken, matched):
"""Helper for *_no_command rules."""
new_cmds = get_close_matches(broken, matched, cutoff=0.1)
return [replace_argument(command.script, broken, new_cmd.strip())
for new_cmd in new_cmds] | def function[replace_command, parameter[command, broken, matched]]:
constant[Helper for *_no_command rules.]
variable[new_cmds] assign[=] call[name[get_close_matches], parameter[name[broken], name[matched]]]
return[<ast.ListComp object at 0x7da1b2028790>] | keyword[def] identifier[replace_command] ( identifier[command] , identifier[broken] , identifier[matched] ):
literal[string]
identifier[new_cmds] = identifier[get_close_matches] ( identifier[broken] , identifier[matched] , identifier[cutoff] = literal[int] )
keyword[return] [ identifier[replace_argume... | def replace_command(command, broken, matched):
"""Helper for *_no_command rules."""
new_cmds = get_close_matches(broken, matched, cutoff=0.1)
return [replace_argument(command.script, broken, new_cmd.strip()) for new_cmd in new_cmds] |
def post(self, request, *args, **kwargs):
""" Handles POST requests. """
self.init_attachment_cache()
# Stores a boolean indicating if we are considering a preview
self.preview = 'preview' in self.request.POST
# Initializes the forms
post_form_class = self.get_post_form... | def function[post, parameter[self, request]]:
constant[ Handles POST requests. ]
call[name[self].init_attachment_cache, parameter[]]
name[self].preview assign[=] compare[constant[preview] in name[self].request.POST]
variable[post_form_class] assign[=] call[name[self].get_post_form_class,... | keyword[def] identifier[post] ( identifier[self] , identifier[request] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[init_attachment_cache] ()
identifier[self] . identifier[preview] = literal[string] keyword[in] identifier[self] . i... | def post(self, request, *args, **kwargs):
""" Handles POST requests. """
self.init_attachment_cache()
# Stores a boolean indicating if we are considering a preview
self.preview = 'preview' in self.request.POST
# Initializes the forms
post_form_class = self.get_post_form_class()
post_form = s... |
def _parse_hparams(hparams):
"""Split hparams, based on key prefixes.
Args:
hparams: hyperparameters
Returns:
Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer.
"""
prefixes = ["agent_", "optimizer_", "runner_", "replay_buffer_"]
ret = []
for prefix in prefixes:
ret_... | def function[_parse_hparams, parameter[hparams]]:
constant[Split hparams, based on key prefixes.
Args:
hparams: hyperparameters
Returns:
Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer.
]
variable[prefixes] assign[=] list[[<ast.Constant object at 0x7da1b20f9330>... | keyword[def] identifier[_parse_hparams] ( identifier[hparams] ):
literal[string]
identifier[prefixes] =[ literal[string] , literal[string] , literal[string] , literal[string] ]
identifier[ret] =[]
keyword[for] identifier[prefix] keyword[in] identifier[prefixes] :
identifier[ret_dict] ={}
ke... | def _parse_hparams(hparams):
"""Split hparams, based on key prefixes.
Args:
hparams: hyperparameters
Returns:
Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer.
"""
prefixes = ['agent_', 'optimizer_', 'runner_', 'replay_buffer_']
ret = []
for prefix in prefixes:
... |
def is_void(func):
"""
Determines if a function is a void function, i.e., one whose body contains
nothing but a docstring or an ellipsis. A void function can be used to introduce
an overloaded function without actually registering an implementation.
"""
try:
source = dedent(inspect.getso... | def function[is_void, parameter[func]]:
constant[
Determines if a function is a void function, i.e., one whose body contains
nothing but a docstring or an ellipsis. A void function can be used to introduce
an overloaded function without actually registering an implementation.
]
<ast.Try obje... | keyword[def] identifier[is_void] ( identifier[func] ):
literal[string]
keyword[try] :
identifier[source] = identifier[dedent] ( identifier[inspect] . identifier[getsource] ( identifier[func] ))
keyword[except] ( identifier[OSError] , identifier[IOError] ):
keyword[return] keyword[Fa... | def is_void(func):
"""
Determines if a function is a void function, i.e., one whose body contains
nothing but a docstring or an ellipsis. A void function can be used to introduce
an overloaded function without actually registering an implementation.
"""
try:
source = dedent(inspect.getso... |
def _get_fill_value(dtype, fill_value=None, fill_value_typ=None):
""" return the correct fill value for the dtype of the values """
if fill_value is not None:
return fill_value
if _na_ok_dtype(dtype):
if fill_value_typ is None:
return np.nan
else:
if fill_valu... | def function[_get_fill_value, parameter[dtype, fill_value, fill_value_typ]]:
constant[ return the correct fill value for the dtype of the values ]
if compare[name[fill_value] is_not constant[None]] begin[:]
return[name[fill_value]]
if call[name[_na_ok_dtype], parameter[name[dtype]]] begi... | keyword[def] identifier[_get_fill_value] ( identifier[dtype] , identifier[fill_value] = keyword[None] , identifier[fill_value_typ] = keyword[None] ):
literal[string]
keyword[if] identifier[fill_value] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[fill_value]
keywor... | def _get_fill_value(dtype, fill_value=None, fill_value_typ=None):
""" return the correct fill value for the dtype of the values """
if fill_value is not None:
return fill_value # depends on [control=['if'], data=['fill_value']]
if _na_ok_dtype(dtype):
if fill_value_typ is None:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.