code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _restore_port_binding(self,
switch_ip, pvlan_ids,
port, native_vlan):
"""Restores a set of vlans for a given port."""
intf_type, nexus_port = nexus_help.split_interface_name(port)
# If native_vlan is configured, this is isolated sin... | def function[_restore_port_binding, parameter[self, switch_ip, pvlan_ids, port, native_vlan]]:
constant[Restores a set of vlans for a given port.]
<ast.Tuple object at 0x7da1b1be6980> assign[=] call[name[nexus_help].split_interface_name, parameter[name[port]]]
if compare[name[native_vlan] not_eq... | keyword[def] identifier[_restore_port_binding] ( identifier[self] ,
identifier[switch_ip] , identifier[pvlan_ids] ,
identifier[port] , identifier[native_vlan] ):
literal[string]
identifier[intf_type] , identifier[nexus_port] = identifier[nexus_help] . identifier[split_interface_name] ( identifie... | def _restore_port_binding(self, switch_ip, pvlan_ids, port, native_vlan):
"""Restores a set of vlans for a given port."""
(intf_type, nexus_port) = nexus_help.split_interface_name(port)
# If native_vlan is configured, this is isolated since
# two configs (native + trunk) must be sent for this vlan only.... |
def variant (name, parents_or_properties, explicit_properties = []):
""" Declares a new variant.
First determines explicit properties for this variant, by
refining parents' explicit properties with the passed explicit
properties. The result is remembered and will be used if
this vari... | def function[variant, parameter[name, parents_or_properties, explicit_properties]]:
constant[ Declares a new variant.
First determines explicit properties for this variant, by
refining parents' explicit properties with the passed explicit
properties. The result is remembered and will be ... | keyword[def] identifier[variant] ( identifier[name] , identifier[parents_or_properties] , identifier[explicit_properties] =[]):
literal[string]
identifier[parents] =[]
keyword[if] keyword[not] identifier[explicit_properties] :
identifier[explicit_properties] = identifier[parents_or_properti... | def variant(name, parents_or_properties, explicit_properties=[]):
""" Declares a new variant.
First determines explicit properties for this variant, by
refining parents' explicit properties with the passed explicit
properties. The result is remembered and will be used if
this variant... |
def remove_child(self, child):
"""Removes a child instance from the Tag's children.
Args:
child (Tag): The child to be removed.
"""
if child in self.children.values() and hasattr(child, 'identifier'):
for k in self.children.keys():
if hasattr(self... | def function[remove_child, parameter[self, child]]:
constant[Removes a child instance from the Tag's children.
Args:
child (Tag): The child to be removed.
]
if <ast.BoolOp object at 0x7da18dc9b220> begin[:]
for taget[name[k]] in starred[call[name[self].childr... | keyword[def] identifier[remove_child] ( identifier[self] , identifier[child] ):
literal[string]
keyword[if] identifier[child] keyword[in] identifier[self] . identifier[children] . identifier[values] () keyword[and] identifier[hasattr] ( identifier[child] , literal[string] ):
keywor... | def remove_child(self, child):
"""Removes a child instance from the Tag's children.
Args:
child (Tag): The child to be removed.
"""
if child in self.children.values() and hasattr(child, 'identifier'):
for k in self.children.keys():
if hasattr(self.children[k], 'i... |
def decrypt(self, binary):
'''
Decrypt and unpack the original OpenConfig object,
serialized using MessagePack.
Raise BadSignatureException when the signature
was forged or corrupted.
'''
try:
encrypted = self.verify_key.verify(binary)
except B... | def function[decrypt, parameter[self, binary]]:
constant[
Decrypt and unpack the original OpenConfig object,
serialized using MessagePack.
Raise BadSignatureException when the signature
was forged or corrupted.
]
<ast.Try object at 0x7da20c990cd0>
<ast.Try object ... | keyword[def] identifier[decrypt] ( identifier[self] , identifier[binary] ):
literal[string]
keyword[try] :
identifier[encrypted] = identifier[self] . identifier[verify_key] . identifier[verify] ( identifier[binary] )
keyword[except] identifier[BadSignatureError] :
... | def decrypt(self, binary):
"""
Decrypt and unpack the original OpenConfig object,
serialized using MessagePack.
Raise BadSignatureException when the signature
was forged or corrupted.
"""
try:
encrypted = self.verify_key.verify(binary) # depends on [control=['try... |
def fancy_transpose(data, roll=1):
"""Fancy transpose
This method transposes a multidimensional matrix.
Parameters
----------
data : np.ndarray
Input data array
roll : int
Roll direction and amount. Default (roll=1)
Returns
-------
np.ndarray transposed data
N... | def function[fancy_transpose, parameter[data, roll]]:
constant[Fancy transpose
This method transposes a multidimensional matrix.
Parameters
----------
data : np.ndarray
Input data array
roll : int
Roll direction and amount. Default (roll=1)
Returns
-------
np.n... | keyword[def] identifier[fancy_transpose] ( identifier[data] , identifier[roll] = literal[int] ):
literal[string]
identifier[axis_roll] = identifier[np] . identifier[roll] ( identifier[np] . identifier[arange] ( identifier[data] . identifier[ndim] ), identifier[roll] )
keyword[return] identifier[np]... | def fancy_transpose(data, roll=1):
"""Fancy transpose
This method transposes a multidimensional matrix.
Parameters
----------
data : np.ndarray
Input data array
roll : int
Roll direction and amount. Default (roll=1)
Returns
-------
np.ndarray transposed data
N... |
def _parseStats(self, lines, parse_slabs = False):
"""Parse stats output from memcached and return dictionary of stats-
@param lines: Array of lines of input text.
@param parse_slabs: Parse slab stats if True.
@return: Stats dictionary.
"""
... | def function[_parseStats, parameter[self, lines, parse_slabs]]:
constant[Parse stats output from memcached and return dictionary of stats-
@param lines: Array of lines of input text.
@param parse_slabs: Parse slab stats if True.
@return: Stats dictionary.
... | keyword[def] identifier[_parseStats] ( identifier[self] , identifier[lines] , identifier[parse_slabs] = keyword[False] ):
literal[string]
identifier[info_dict] ={}
identifier[info_dict] [ literal[string] ]={}
keyword[for] identifier[line] keyword[in] identifier[lines] :
... | def _parseStats(self, lines, parse_slabs=False):
"""Parse stats output from memcached and return dictionary of stats-
@param lines: Array of lines of input text.
@param parse_slabs: Parse slab stats if True.
@return: Stats dictionary.
"""
info_d... |
def before_sleep_func_accept_retry_state(fn):
"""Wrap "before_sleep" function to accept "retry_state"."""
if not six.callable(fn):
return fn
if func_takes_retry_state(fn):
return fn
@_utils.wraps(fn)
def wrapped_before_sleep_func(retry_state):
# retry_object, sleep, last_re... | def function[before_sleep_func_accept_retry_state, parameter[fn]]:
constant[Wrap "before_sleep" function to accept "retry_state".]
if <ast.UnaryOp object at 0x7da204564ee0> begin[:]
return[name[fn]]
if call[name[func_takes_retry_state], parameter[name[fn]]] begin[:]
return[name[f... | keyword[def] identifier[before_sleep_func_accept_retry_state] ( identifier[fn] ):
literal[string]
keyword[if] keyword[not] identifier[six] . identifier[callable] ( identifier[fn] ):
keyword[return] identifier[fn]
keyword[if] identifier[func_takes_retry_state] ( identifier[fn] ):
... | def before_sleep_func_accept_retry_state(fn):
"""Wrap "before_sleep" function to accept "retry_state"."""
if not six.callable(fn):
return fn # depends on [control=['if'], data=[]]
if func_takes_retry_state(fn):
return fn # depends on [control=['if'], data=[]]
@_utils.wraps(fn)
def... |
def setSurfaces(self, normalSurface, downSurface=None, highlightSurface=None):
"""Switch the button to a custom image type of button (rather than a
text button). You can specify either a pygame.Surface object or a
string of a filename to load for each of the three button appearance
state... | def function[setSurfaces, parameter[self, normalSurface, downSurface, highlightSurface]]:
constant[Switch the button to a custom image type of button (rather than a
text button). You can specify either a pygame.Surface object or a
string of a filename to load for each of the three button appeara... | keyword[def] identifier[setSurfaces] ( identifier[self] , identifier[normalSurface] , identifier[downSurface] = keyword[None] , identifier[highlightSurface] = keyword[None] ):
literal[string]
keyword[if] identifier[downSurface] keyword[is] keyword[None] :
identifier[downSurface] = i... | def setSurfaces(self, normalSurface, downSurface=None, highlightSurface=None):
"""Switch the button to a custom image type of button (rather than a
text button). You can specify either a pygame.Surface object or a
string of a filename to load for each of the three button appearance
states.""... |
def op_gen(mcode):
"""Generate a machine instruction using the op gen table."""
gen = op_tbl[mcode[0]]
ret = gen[0] # opcode
nargs = len(gen)
i = 1
while i < nargs:
if i < len(mcode): # or assume they are same len
ret |= (mcode[i]&gen[i][0]) << gen[i][1]
i += 1
re... | def function[op_gen, parameter[mcode]]:
constant[Generate a machine instruction using the op gen table.]
variable[gen] assign[=] call[name[op_tbl]][call[name[mcode]][constant[0]]]
variable[ret] assign[=] call[name[gen]][constant[0]]
variable[nargs] assign[=] call[name[len], parameter[nam... | keyword[def] identifier[op_gen] ( identifier[mcode] ):
literal[string]
identifier[gen] = identifier[op_tbl] [ identifier[mcode] [ literal[int] ]]
identifier[ret] = identifier[gen] [ literal[int] ]
identifier[nargs] = identifier[len] ( identifier[gen] )
identifier[i] = literal[int]
keyw... | def op_gen(mcode):
"""Generate a machine instruction using the op gen table."""
gen = op_tbl[mcode[0]]
ret = gen[0] # opcode
nargs = len(gen)
i = 1
while i < nargs:
if i < len(mcode): # or assume they are same len
ret |= (mcode[i] & gen[i][0]) << gen[i][1] # depends on [co... |
def field_items(self, path=str(), **options):
""" Returns a **flatten** list of ``('field path', field item)`` tuples
for each :class:`Field` *nested* in the `Sequence`.
:param str path: field path of the `Sequence`.
:keyword bool nested: if ``True`` all :class:`Pointer` fields in the
... | def function[field_items, parameter[self, path]]:
constant[ Returns a **flatten** list of ``('field path', field item)`` tuples
for each :class:`Field` *nested* in the `Sequence`.
:param str path: field path of the `Sequence`.
:keyword bool nested: if ``True`` all :class:`Pointer` field... | keyword[def] identifier[field_items] ( identifier[self] , identifier[path] = identifier[str] (),** identifier[options] ):
literal[string]
identifier[items] = identifier[list] ()
keyword[for] identifier[index] , identifier[item] keyword[in] identifier[enumerate] ( identifier[self] ):
... | def field_items(self, path=str(), **options):
""" Returns a **flatten** list of ``('field path', field item)`` tuples
for each :class:`Field` *nested* in the `Sequence`.
:param str path: field path of the `Sequence`.
:keyword bool nested: if ``True`` all :class:`Pointer` fields in the
... |
def from_class(metacls, cls, auto_store=True):
"""Create proper PySchema class from cls
Any methods and attributes will be transferred to the
new object
"""
if auto_store:
def wrap(cls):
return cls
else:
wrap = no_auto_store()
... | def function[from_class, parameter[metacls, cls, auto_store]]:
constant[Create proper PySchema class from cls
Any methods and attributes will be transferred to the
new object
]
if name[auto_store] begin[:]
def function[wrap, parameter[cls]]:
return[na... | keyword[def] identifier[from_class] ( identifier[metacls] , identifier[cls] , identifier[auto_store] = keyword[True] ):
literal[string]
keyword[if] identifier[auto_store] :
keyword[def] identifier[wrap] ( identifier[cls] ):
keyword[return] identifier[cls]
... | def from_class(metacls, cls, auto_store=True):
"""Create proper PySchema class from cls
Any methods and attributes will be transferred to the
new object
"""
if auto_store:
def wrap(cls):
return cls # depends on [control=['if'], data=[]]
else:
wrap = no_... |
def construct(self, sp_entity_id, attrconvs, policy, issuer, farg,
authn_class=None, authn_auth=None, authn_decl=None,
encrypt=None, sec_context=None, authn_decl_ref=None,
authn_instant="", subject_locality="", authn_statem=None,
name_id=None, sess... | def function[construct, parameter[self, sp_entity_id, attrconvs, policy, issuer, farg, authn_class, authn_auth, authn_decl, encrypt, sec_context, authn_decl_ref, authn_instant, subject_locality, authn_statem, name_id, session_not_on_or_after]]:
constant[ Construct the Assertion
:param sp_entity_id: The... | keyword[def] identifier[construct] ( identifier[self] , identifier[sp_entity_id] , identifier[attrconvs] , identifier[policy] , identifier[issuer] , identifier[farg] ,
identifier[authn_class] = keyword[None] , identifier[authn_auth] = keyword[None] , identifier[authn_decl] = keyword[None] ,
identifier[encrypt] = ke... | def construct(self, sp_entity_id, attrconvs, policy, issuer, farg, authn_class=None, authn_auth=None, authn_decl=None, encrypt=None, sec_context=None, authn_decl_ref=None, authn_instant='', subject_locality='', authn_statem=None, name_id=None, session_not_on_or_after=None):
""" Construct the Assertion
:par... |
def out_format(data, out, opts=None, **kwargs):
'''
Return the formatted outputter string for the passed data
'''
return try_printout(data, out, opts, **kwargs) | def function[out_format, parameter[data, out, opts]]:
constant[
Return the formatted outputter string for the passed data
]
return[call[name[try_printout], parameter[name[data], name[out], name[opts]]]] | keyword[def] identifier[out_format] ( identifier[data] , identifier[out] , identifier[opts] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[try_printout] ( identifier[data] , identifier[out] , identifier[opts] ,** identifier[kwargs] ) | def out_format(data, out, opts=None, **kwargs):
"""
Return the formatted outputter string for the passed data
"""
return try_printout(data, out, opts, **kwargs) |
def ofp_instruction_from_jsondict(dp, jsonlist, encap=True):
"""
This function is intended to be used with
ryu.lib.ofctl_string.ofp_instruction_from_str.
It is very similar to ofp_msg_from_jsondict, but works on
a list of OFPInstructions/OFPActions. It also encapsulates
OFPAction into OFPInstruc... | def function[ofp_instruction_from_jsondict, parameter[dp, jsonlist, encap]]:
constant[
This function is intended to be used with
ryu.lib.ofctl_string.ofp_instruction_from_str.
It is very similar to ofp_msg_from_jsondict, but works on
a list of OFPInstructions/OFPActions. It also encapsulates
... | keyword[def] identifier[ofp_instruction_from_jsondict] ( identifier[dp] , identifier[jsonlist] , identifier[encap] = keyword[True] ):
literal[string]
identifier[proto] = identifier[dp] . identifier[ofproto]
identifier[parser] = identifier[dp] . identifier[ofproto_parser]
identifier[actions] =[]... | def ofp_instruction_from_jsondict(dp, jsonlist, encap=True):
"""
This function is intended to be used with
ryu.lib.ofctl_string.ofp_instruction_from_str.
It is very similar to ofp_msg_from_jsondict, but works on
a list of OFPInstructions/OFPActions. It also encapsulates
OFPAction into OFPInstruc... |
def close(self):
"""Close the authentication layer and cleanup
all the authentication wrapper objects.
"""
self.sasl.mechanism.destroy()
self.sasl_client.get_client().destroy()
self._underlying_xio.destroy() | def function[close, parameter[self]]:
constant[Close the authentication layer and cleanup
all the authentication wrapper objects.
]
call[name[self].sasl.mechanism.destroy, parameter[]]
call[call[name[self].sasl_client.get_client, parameter[]].destroy, parameter[]]
call[na... | keyword[def] identifier[close] ( identifier[self] ):
literal[string]
identifier[self] . identifier[sasl] . identifier[mechanism] . identifier[destroy] ()
identifier[self] . identifier[sasl_client] . identifier[get_client] (). identifier[destroy] ()
identifier[self] . identifier[_u... | def close(self):
"""Close the authentication layer and cleanup
all the authentication wrapper objects.
"""
self.sasl.mechanism.destroy()
self.sasl_client.get_client().destroy()
self._underlying_xio.destroy() |
def cli(ctx, ftdi_enable, ftdi_disable, serial_enable, serial_disable):
"""Manage FPGA boards drivers."""
exit_code = 0
if ftdi_enable: # pragma: no cover
exit_code = Drivers().ftdi_enable()
elif ftdi_disable: # pragma: no cover
exit_code = Drivers().ftdi_disable()
elif serial_... | def function[cli, parameter[ctx, ftdi_enable, ftdi_disable, serial_enable, serial_disable]]:
constant[Manage FPGA boards drivers.]
variable[exit_code] assign[=] constant[0]
if name[ftdi_enable] begin[:]
variable[exit_code] assign[=] call[call[name[Drivers], parameter[]].ftdi_enab... | keyword[def] identifier[cli] ( identifier[ctx] , identifier[ftdi_enable] , identifier[ftdi_disable] , identifier[serial_enable] , identifier[serial_disable] ):
literal[string]
identifier[exit_code] = literal[int]
keyword[if] identifier[ftdi_enable] :
identifier[exit_code] = identifier[Dri... | def cli(ctx, ftdi_enable, ftdi_disable, serial_enable, serial_disable):
"""Manage FPGA boards drivers."""
exit_code = 0
if ftdi_enable: # pragma: no cover
exit_code = Drivers().ftdi_enable() # depends on [control=['if'], data=[]]
elif ftdi_disable: # pragma: no cover
exit_code = Drive... |
def mirror_video(self, is_mirror, callback=None):
'''
Mirror video
``is_mirror``: 0 not mirror, 1 mirror
'''
params = {'isMirror': is_mirror}
return self.execute_command('mirrorVideo', params, callback=callback) | def function[mirror_video, parameter[self, is_mirror, callback]]:
constant[
Mirror video
``is_mirror``: 0 not mirror, 1 mirror
]
variable[params] assign[=] dictionary[[<ast.Constant object at 0x7da1b1a76e60>], [<ast.Name object at 0x7da1b1a775b0>]]
return[call[name[self].execu... | keyword[def] identifier[mirror_video] ( identifier[self] , identifier[is_mirror] , identifier[callback] = keyword[None] ):
literal[string]
identifier[params] ={ literal[string] : identifier[is_mirror] }
keyword[return] identifier[self] . identifier[execute_command] ( literal[string] , ide... | def mirror_video(self, is_mirror, callback=None):
"""
Mirror video
``is_mirror``: 0 not mirror, 1 mirror
"""
params = {'isMirror': is_mirror}
return self.execute_command('mirrorVideo', params, callback=callback) |
def get_proficiencies_by_ids(self, proficiency_ids):
"""Gets a ``ProficiencyList`` corresponding to the given ``IdList``.
arg: proficiency_ids (osid.id.IdList): the list of ``Ids`` to
retrieve
return: (osid.learning.ProficiencyList) - the returned
``Proficienc... | def function[get_proficiencies_by_ids, parameter[self, proficiency_ids]]:
constant[Gets a ``ProficiencyList`` corresponding to the given ``IdList``.
arg: proficiency_ids (osid.id.IdList): the list of ``Ids`` to
retrieve
return: (osid.learning.ProficiencyList) - the returned
... | keyword[def] identifier[get_proficiencies_by_ids] ( identifier[self] , identifier[proficiency_ids] ):
literal[string]
identifier[collection] = identifier[JSONClientValidated] ( literal[string] ,
identifier[collection] = literal[string] ,
identifier[runti... | def get_proficiencies_by_ids(self, proficiency_ids):
"""Gets a ``ProficiencyList`` corresponding to the given ``IdList``.
arg: proficiency_ids (osid.id.IdList): the list of ``Ids`` to
retrieve
return: (osid.learning.ProficiencyList) - the returned
``Proficiency`` ... |
def auth_aliases(d):
"""Interpret user/password aliases.
"""
for alias, real in ((USER_KEY, "readonly_user"),
(PASS_KEY, "readonly_password")):
if alias in d:
d[real] = d[alias]
del d[alias] | def function[auth_aliases, parameter[d]]:
constant[Interpret user/password aliases.
]
for taget[tuple[[<ast.Name object at 0x7da20c9935b0>, <ast.Name object at 0x7da20c9912d0>]]] in starred[tuple[[<ast.Tuple object at 0x7da20c991a50>, <ast.Tuple object at 0x7da20c990a00>]]] begin[:]
... | keyword[def] identifier[auth_aliases] ( identifier[d] ):
literal[string]
keyword[for] identifier[alias] , identifier[real] keyword[in] (( identifier[USER_KEY] , literal[string] ),
( identifier[PASS_KEY] , literal[string] )):
keyword[if] identifier[alias] keyword[in] identifier[d] :
... | def auth_aliases(d):
"""Interpret user/password aliases.
"""
for (alias, real) in ((USER_KEY, 'readonly_user'), (PASS_KEY, 'readonly_password')):
if alias in d:
d[real] = d[alias]
del d[alias] # depends on [control=['if'], data=['alias', 'd']] # depends on [control=['for'],... |
def cast(self, method, args={}, declare=None, retry=None,
retry_policy=None, type=None, exchange=None, **props):
"""Send message to actor. Discarding replies."""
retry = self.retry if retry is None else retry
body = {'class': self.name, 'method': method, 'args': args}
_ret... | def function[cast, parameter[self, method, args, declare, retry, retry_policy, type, exchange]]:
constant[Send message to actor. Discarding replies.]
variable[retry] assign[=] <ast.IfExp object at 0x7da1b138a5f0>
variable[body] assign[=] dictionary[[<ast.Constant object at 0x7da1b1389f30>, <ast... | keyword[def] identifier[cast] ( identifier[self] , identifier[method] , identifier[args] ={}, identifier[declare] = keyword[None] , identifier[retry] = keyword[None] ,
identifier[retry_policy] = keyword[None] , identifier[type] = keyword[None] , identifier[exchange] = keyword[None] ,** identifier[props] ):
... | def cast(self, method, args={}, declare=None, retry=None, retry_policy=None, type=None, exchange=None, **props):
"""Send message to actor. Discarding replies."""
retry = self.retry if retry is None else retry
body = {'class': self.name, 'method': method, 'args': args}
_retry_policy = self.retry_policy
... |
def _pdb_frame(self):
"""Return current Pdb frame if there is any"""
if self._pdb_obj is not None and self._pdb_obj.curframe is not None:
return self._pdb_obj.curframe | def function[_pdb_frame, parameter[self]]:
constant[Return current Pdb frame if there is any]
if <ast.BoolOp object at 0x7da20e955690> begin[:]
return[name[self]._pdb_obj.curframe] | keyword[def] identifier[_pdb_frame] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_pdb_obj] keyword[is] keyword[not] keyword[None] keyword[and] identifier[self] . identifier[_pdb_obj] . identifier[curframe] keyword[is] keyword[not] keyword[None] :
... | def _pdb_frame(self):
"""Return current Pdb frame if there is any"""
if self._pdb_obj is not None and self._pdb_obj.curframe is not None:
return self._pdb_obj.curframe # depends on [control=['if'], data=[]] |
def get_log_entry_query_session_for_log(self, log_id, proxy):
"""Gets the ``OsidSession`` associated with the log entry query service for the given log.
arg: log_id (osid.id.Id): the ``Id`` of the ``Log``
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.logging.LogEntryQuerySe... | def function[get_log_entry_query_session_for_log, parameter[self, log_id, proxy]]:
constant[Gets the ``OsidSession`` associated with the log entry query service for the given log.
arg: log_id (osid.id.Id): the ``Id`` of the ``Log``
arg: proxy (osid.proxy.Proxy): a proxy
return: (o... | keyword[def] identifier[get_log_entry_query_session_for_log] ( identifier[self] , identifier[log_id] , identifier[proxy] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[supports_log_entry_query] ():
keyword[raise] identifier[errors] . identifier[Unimplement... | def get_log_entry_query_session_for_log(self, log_id, proxy):
"""Gets the ``OsidSession`` associated with the log entry query service for the given log.
arg: log_id (osid.id.Id): the ``Id`` of the ``Log``
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.logging.LogEntryQuerySessio... |
def file_sha1(path):
"""
Compute SHA1 hash of a file.
"""
sha1 = hashlib.sha1()
with open(path, "rb") as f:
while True:
block = f.read(2 ** 10)
if not block:
break
sha1.update(block)
return sha1.hexdigest() | def function[file_sha1, parameter[path]]:
constant[
Compute SHA1 hash of a file.
]
variable[sha1] assign[=] call[name[hashlib].sha1, parameter[]]
with call[name[open], parameter[name[path], constant[rb]]] begin[:]
while constant[True] begin[:]
variable... | keyword[def] identifier[file_sha1] ( identifier[path] ):
literal[string]
identifier[sha1] = identifier[hashlib] . identifier[sha1] ()
keyword[with] identifier[open] ( identifier[path] , literal[string] ) keyword[as] identifier[f] :
keyword[while] keyword[True] :
identifier[block] = identifier... | def file_sha1(path):
"""
Compute SHA1 hash of a file.
"""
sha1 = hashlib.sha1()
with open(path, 'rb') as f:
while True:
block = f.read(2 ** 10)
if not block:
break # depends on [control=['if'], data=[]]
sha1.update(block) # depends on [contro... |
def options(self, context, module_options):
'''
PATH Path to dll/exe to inject
PROCID Process ID to inject into (default: current powershell process)
EXEARGS Arguments to pass to the executable being reflectively loaded (default: None)
'''
if not 'PATH... | def function[options, parameter[self, context, module_options]]:
constant[
PATH Path to dll/exe to inject
PROCID Process ID to inject into (default: current powershell process)
EXEARGS Arguments to pass to the executable being reflectively loaded (default: None)
... | 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 dll/exe to inject
PROCID Process ID to inject into (default: current powershell process)
EXEARGS Arguments to pass to the executable being reflectively loaded (default: None)
"""
if not 'PATH' in modu... |
def exists(self, **kwargs):
"""Providing a partition is not necessary on topology; causes errors"""
kwargs.pop('partition', None)
kwargs['transform_name'] = True
return self._exists(**kwargs) | def function[exists, parameter[self]]:
constant[Providing a partition is not necessary on topology; causes errors]
call[name[kwargs].pop, parameter[constant[partition], constant[None]]]
call[name[kwargs]][constant[transform_name]] assign[=] constant[True]
return[call[name[self]._exists, para... | keyword[def] identifier[exists] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] . identifier[pop] ( literal[string] , keyword[None] )
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[return] identifier[self] . identifier[_exists] (** ... | def exists(self, **kwargs):
"""Providing a partition is not necessary on topology; causes errors"""
kwargs.pop('partition', None)
kwargs['transform_name'] = True
return self._exists(**kwargs) |
def keep_entry_range(entry, lows, highs, converter, regex):
"""
Check if an entry falls into a desired range.
Every number in the entry will be extracted using *regex*,
if any are within a given low to high range the entry will
be kept.
Parameters
----------
entry : str
lows : iter... | def function[keep_entry_range, parameter[entry, lows, highs, converter, regex]]:
constant[
Check if an entry falls into a desired range.
Every number in the entry will be extracted using *regex*,
if any are within a given low to high range the entry will
be kept.
Parameters
----------
... | keyword[def] identifier[keep_entry_range] ( identifier[entry] , identifier[lows] , identifier[highs] , identifier[converter] , identifier[regex] ):
literal[string]
keyword[return] identifier[any] (
identifier[low] <= identifier[converter] ( identifier[num] )<= identifier[high]
keyword[for] ide... | def keep_entry_range(entry, lows, highs, converter, regex):
"""
Check if an entry falls into a desired range.
Every number in the entry will be extracted using *regex*,
if any are within a given low to high range the entry will
be kept.
Parameters
----------
entry : str
lows : iter... |
def load_tool_info(tool_name):
"""
Load the tool-info class.
@param tool_name: The name of the tool-info module.
Either a full Python package name or a name within the benchexec.tools package.
@return: A tuple of the full name of the used tool-info module and an instance of the tool-info class.
... | def function[load_tool_info, parameter[tool_name]]:
constant[
Load the tool-info class.
@param tool_name: The name of the tool-info module.
Either a full Python package name or a name within the benchexec.tools package.
@return: A tuple of the full name of the used tool-info module and an instan... | keyword[def] identifier[load_tool_info] ( identifier[tool_name] ):
literal[string]
identifier[tool_module] = identifier[tool_name] keyword[if] literal[string] keyword[in] identifier[tool_name] keyword[else] ( literal[string] + identifier[tool_name] )
keyword[try] :
identifier[tool] = ide... | def load_tool_info(tool_name):
"""
Load the tool-info class.
@param tool_name: The name of the tool-info module.
Either a full Python package name or a name within the benchexec.tools package.
@return: A tuple of the full name of the used tool-info module and an instance of the tool-info class.
... |
def insert_header(self, hkey, value, index=None):
"""
This will insert/overwrite a value to the header and hkeys.
Parameters
----------
hkey
Header key. Will be appended to self.hkeys if non existent, or
inserted at the specified index.
If h... | def function[insert_header, parameter[self, hkey, value, index]]:
constant[
This will insert/overwrite a value to the header and hkeys.
Parameters
----------
hkey
Header key. Will be appended to self.hkeys if non existent, or
inserted at the specified in... | keyword[def] identifier[insert_header] ( identifier[self] , identifier[hkey] , identifier[value] , identifier[index] = keyword[None] ):
literal[string]
keyword[if] identifier[type] ( identifier[hkey] ) keyword[in] [ identifier[int] , identifier[int] ]: identifier[hkey] = identif... | def insert_header(self, hkey, value, index=None):
"""
This will insert/overwrite a value to the header and hkeys.
Parameters
----------
hkey
Header key. Will be appended to self.hkeys if non existent, or
inserted at the specified index.
If hkey ... |
def create_cookie(host, path, secure, expires, name, value):
"""Shortcut function to create a cookie
"""
return http.cookiejar.Cookie(0, name, value, None, False, host, host.startswith('.'), host.startswith('.'), path,
True, secure, expires, False, None, None, {}) | def function[create_cookie, parameter[host, path, secure, expires, name, value]]:
constant[Shortcut function to create a cookie
]
return[call[name[http].cookiejar.Cookie, parameter[constant[0], name[name], name[value], constant[None], constant[False], name[host], call[name[host].startswith, parameter[co... | keyword[def] identifier[create_cookie] ( identifier[host] , identifier[path] , identifier[secure] , identifier[expires] , identifier[name] , identifier[value] ):
literal[string]
keyword[return] identifier[http] . identifier[cookiejar] . identifier[Cookie] ( literal[int] , identifier[name] , identifier[val... | def create_cookie(host, path, secure, expires, name, value):
"""Shortcut function to create a cookie
"""
return http.cookiejar.Cookie(0, name, value, None, False, host, host.startswith('.'), host.startswith('.'), path, True, secure, expires, False, None, None, {}) |
def ll(self,*args,**kwargs):
"""
NAME:
ll
PURPOSE:
return Galactic longitude
INPUT:
t - (optional) time at which to get ll
obs=[X,Y,Z] - (optional) position of observer (in kpc)
(default=Object-wide default)
... | def function[ll, parameter[self]]:
constant[
NAME:
ll
PURPOSE:
return Galactic longitude
INPUT:
t - (optional) time at which to get ll
obs=[X,Y,Z] - (optional) position of observer (in kpc)
(default=Object-wide default... | keyword[def] identifier[ll] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[_check_roSet] ( identifier[self] , identifier[kwargs] , literal[string] )
identifier[lbd] = identifier[self] . identifier[_lbd] (* identifier[args] ,** identifier[kwargs]... | def ll(self, *args, **kwargs):
"""
NAME:
ll
PURPOSE:
return Galactic longitude
INPUT:
t - (optional) time at which to get ll
obs=[X,Y,Z] - (optional) position of observer (in kpc)
(default=Object-wide default)
... |
def load(name,
split=None,
data_dir=None,
batch_size=1,
download=True,
as_supervised=False,
with_info=False,
builder_kwargs=None,
download_and_prepare_kwargs=None,
as_dataset_kwargs=None,
try_gcs=False):
"""Loads the named datas... | def function[load, parameter[name, split, data_dir, batch_size, download, as_supervised, with_info, builder_kwargs, download_and_prepare_kwargs, as_dataset_kwargs, try_gcs]]:
constant[Loads the named dataset into a `tf.data.Dataset`.
If `split=None` (the default), returns all splits for the dataset. Otherwis... | keyword[def] identifier[load] ( identifier[name] ,
identifier[split] = keyword[None] ,
identifier[data_dir] = keyword[None] ,
identifier[batch_size] = literal[int] ,
identifier[download] = keyword[True] ,
identifier[as_supervised] = keyword[False] ,
identifier[with_info] = keyword[False] ,
identifier[builder_k... | def load(name, split=None, data_dir=None, batch_size=1, download=True, as_supervised=False, with_info=False, builder_kwargs=None, download_and_prepare_kwargs=None, as_dataset_kwargs=None, try_gcs=False):
"""Loads the named dataset into a `tf.data.Dataset`.
If `split=None` (the default), returns all splits for th... |
def validate(self, raw_data, **kwargs):
"""The string ``'True'`` (case insensitive) will be converted
to ``True``, as will any positive integers.
"""
super(BooleanField, self).validate(raw_data, **kwargs)
if isinstance(raw_data, string_types):
valid_data = raw_data.s... | def function[validate, parameter[self, raw_data]]:
constant[The string ``'True'`` (case insensitive) will be converted
to ``True``, as will any positive integers.
]
call[call[name[super], parameter[name[BooleanField], name[self]]].validate, parameter[name[raw_data]]]
if call[nam... | keyword[def] identifier[validate] ( identifier[self] , identifier[raw_data] ,** identifier[kwargs] ):
literal[string]
identifier[super] ( identifier[BooleanField] , identifier[self] ). identifier[validate] ( identifier[raw_data] ,** identifier[kwargs] )
keyword[if] identifier[isinstance] ... | def validate(self, raw_data, **kwargs):
"""The string ``'True'`` (case insensitive) will be converted
to ``True``, as will any positive integers.
"""
super(BooleanField, self).validate(raw_data, **kwargs)
if isinstance(raw_data, string_types):
valid_data = raw_data.strip().lower() =... |
def direction_to_tile(from_tile_id, to_tile_id):
"""
Convenience method wrapping tile_tile_offset_to_direction. Used to get the direction
of the offset between two tiles. The tiles must be adjacent.
:param from_tile_id: tile identifier, int
:param to_tile_id: tile identifier, int
:return: direc... | def function[direction_to_tile, parameter[from_tile_id, to_tile_id]]:
constant[
Convenience method wrapping tile_tile_offset_to_direction. Used to get the direction
of the offset between two tiles. The tiles must be adjacent.
:param from_tile_id: tile identifier, int
:param to_tile_id: tile ide... | keyword[def] identifier[direction_to_tile] ( identifier[from_tile_id] , identifier[to_tile_id] ):
literal[string]
identifier[coord_from] = identifier[tile_id_to_coord] ( identifier[from_tile_id] )
identifier[coord_to] = identifier[tile_id_to_coord] ( identifier[to_tile_id] )
identifier[direction]... | def direction_to_tile(from_tile_id, to_tile_id):
"""
Convenience method wrapping tile_tile_offset_to_direction. Used to get the direction
of the offset between two tiles. The tiles must be adjacent.
:param from_tile_id: tile identifier, int
:param to_tile_id: tile identifier, int
:return: direc... |
def dfa_complementation(dfa: dict) -> dict:
""" Returns a DFA that accepts any word but he ones accepted
by the input DFA.
Let A be a completed DFA, :math:`Ā = (Σ, S, s_0 , ρ, S − F )`
is the DFA that runs A but accepts whatever word A does not.
:param dict dfa: input DFA.
:return: *(dict)* re... | def function[dfa_complementation, parameter[dfa]]:
constant[ Returns a DFA that accepts any word but he ones accepted
by the input DFA.
Let A be a completed DFA, :math:`Ā = (Σ, S, s_0 , ρ, S − F )`
is the DFA that runs A but accepts whatever word A does not.
:param dict dfa: input DFA.
:re... | keyword[def] identifier[dfa_complementation] ( identifier[dfa] : identifier[dict] )-> identifier[dict] :
literal[string]
identifier[dfa_complement] = identifier[dfa_completion] ( identifier[deepcopy] ( identifier[dfa] ))
identifier[dfa_complement] [ literal[string] ]= identifier[dfa_complement] [ lite... | def dfa_complementation(dfa: dict) -> dict:
""" Returns a DFA that accepts any word but he ones accepted
by the input DFA.
Let A be a completed DFA, :math:`Ā = (Σ, S, s_0 , ρ, S − F )`
is the DFA that runs A but accepts whatever word A does not.
:param dict dfa: input DFA.
:return: *(dict)* re... |
def _parse_endofnames(client, command, actor, args):
"""Parse an ENDOFNAMES and dispatch a NAMES event for the channel."""
args = args.split(" :", 1)[0] # Strip off human-readable message
_, _, channel = args.rpartition(' ')
channel = client.server.get_channel(channel) or channel.lower()
client.disp... | def function[_parse_endofnames, parameter[client, command, actor, args]]:
constant[Parse an ENDOFNAMES and dispatch a NAMES event for the channel.]
variable[args] assign[=] call[call[name[args].split, parameter[constant[ :], constant[1]]]][constant[0]]
<ast.Tuple object at 0x7da20c795480> assign... | keyword[def] identifier[_parse_endofnames] ( identifier[client] , identifier[command] , identifier[actor] , identifier[args] ):
literal[string]
identifier[args] = identifier[args] . identifier[split] ( literal[string] , literal[int] )[ literal[int] ]
identifier[_] , identifier[_] , identifier[channel]... | def _parse_endofnames(client, command, actor, args):
"""Parse an ENDOFNAMES and dispatch a NAMES event for the channel."""
args = args.split(' :', 1)[0] # Strip off human-readable message
(_, _, channel) = args.rpartition(' ')
channel = client.server.get_channel(channel) or channel.lower()
client.d... |
def create(self, datapath, tracker_urls, comment=None, root_name=None,
created_by=None, private=False, no_date=False, progress=None,
callback=None):
""" Create a metafile with the path given on object creation.
Returns the last metafile dict that was written... | def function[create, parameter[self, datapath, tracker_urls, comment, root_name, created_by, private, no_date, progress, callback]]:
constant[ Create a metafile with the path given on object creation.
Returns the last metafile dict that was written (as an object, not bencoded).
]
if ... | keyword[def] identifier[create] ( identifier[self] , identifier[datapath] , identifier[tracker_urls] , identifier[comment] = keyword[None] , identifier[root_name] = keyword[None] ,
identifier[created_by] = keyword[None] , identifier[private] = keyword[False] , identifier[no_date] = keyword[False] , identifier[progre... | def create(self, datapath, tracker_urls, comment=None, root_name=None, created_by=None, private=False, no_date=False, progress=None, callback=None):
""" Create a metafile with the path given on object creation.
Returns the last metafile dict that was written (as an object, not bencoded).
"""
... |
async def send_chat_action(self, chat_id: typing.Union[base.Integer, base.String],
action: base.String) -> base.Boolean:
"""
Use this method when you need to tell the user that something is happening on the bot's side.
The status is set for 5 seconds or less
... | <ast.AsyncFunctionDef object at 0x7da1b17aa140> | keyword[async] keyword[def] identifier[send_chat_action] ( identifier[self] , identifier[chat_id] : identifier[typing] . identifier[Union] [ identifier[base] . identifier[Integer] , identifier[base] . identifier[String] ],
identifier[action] : identifier[base] . identifier[String] )-> identifier[base] . identifier[... | async def send_chat_action(self, chat_id: typing.Union[base.Integer, base.String], action: base.String) -> base.Boolean:
"""
Use this method when you need to tell the user that something is happening on the bot's side.
The status is set for 5 seconds or less
(when a message arrives from your... |
def time_delays(self, kwargs_lens, kwargs_ps, kappa_ext=0):
"""
predicts the time delays of the image positions
:param kwargs_lens: lens model parameters
:param kwargs_ps: point source parameters
:param kappa_ext: external convergence (optional)
:return: time delays at i... | def function[time_delays, parameter[self, kwargs_lens, kwargs_ps, kappa_ext]]:
constant[
predicts the time delays of the image positions
:param kwargs_lens: lens model parameters
:param kwargs_ps: point source parameters
:param kappa_ext: external convergence (optional)
... | keyword[def] identifier[time_delays] ( identifier[self] , identifier[kwargs_lens] , identifier[kwargs_ps] , identifier[kappa_ext] = literal[int] ):
literal[string]
identifier[fermat_pot] = identifier[self] . identifier[lens_analysis] . identifier[fermat_potential] ( identifier[kwargs_lens] , identi... | def time_delays(self, kwargs_lens, kwargs_ps, kappa_ext=0):
"""
predicts the time delays of the image positions
:param kwargs_lens: lens model parameters
:param kwargs_ps: point source parameters
:param kappa_ext: external convergence (optional)
:return: time delays at image... |
def printcolour(text, sameline=False, colour=get_colour("ENDC")):
"""
Print color text using escape codes
"""
if sameline:
sep = ''
else:
sep = '\n'
sys.stdout.write(get_colour(colour) + text + bcolours["ENDC"] + sep) | def function[printcolour, parameter[text, sameline, colour]]:
constant[
Print color text using escape codes
]
if name[sameline] begin[:]
variable[sep] assign[=] constant[]
call[name[sys].stdout.write, parameter[binary_operation[binary_operation[binary_operation[call[name[... | keyword[def] identifier[printcolour] ( identifier[text] , identifier[sameline] = keyword[False] , identifier[colour] = identifier[get_colour] ( literal[string] )):
literal[string]
keyword[if] identifier[sameline] :
identifier[sep] = literal[string]
keyword[else] :
identifier[sep] =... | def printcolour(text, sameline=False, colour=get_colour('ENDC')):
"""
Print color text using escape codes
"""
if sameline:
sep = '' # depends on [control=['if'], data=[]]
else:
sep = '\n'
sys.stdout.write(get_colour(colour) + text + bcolours['ENDC'] + sep) |
def busca_cep_correios(cep):
''' Pesquisa o CEP informado no site dos correios '''
if cep is None or not isinstance(cep, str):
raise AttributeError("O CEP deve ser do tipo string!")
elif not cep.isdigit() or len(cep) != 8:
raise AttributeError("O CEP deve conter apenas 8 dígitos!")
url... | def function[busca_cep_correios, parameter[cep]]:
constant[ Pesquisa o CEP informado no site dos correios ]
if <ast.BoolOp object at 0x7da1b15a38e0> begin[:]
<ast.Raise object at 0x7da1b15a20b0>
variable[url] assign[=] constant[http://www.buscacep.correios.com.br/sistemas/buscacep/result... | keyword[def] identifier[busca_cep_correios] ( identifier[cep] ):
literal[string]
keyword[if] identifier[cep] keyword[is] keyword[None] keyword[or] keyword[not] identifier[isinstance] ( identifier[cep] , identifier[str] ):
keyword[raise] identifier[AttributeError] ( literal[string] )
k... | def busca_cep_correios(cep):
""" Pesquisa o CEP informado no site dos correios """
if cep is None or not isinstance(cep, str):
raise AttributeError('O CEP deve ser do tipo string!') # depends on [control=['if'], data=[]]
elif not cep.isdigit() or len(cep) != 8:
raise AttributeError('O CEP d... |
def addFeatureSet(self):
"""
Adds a new feature set into this repo
"""
self._openRepo()
dataset = self._repo.getDatasetByName(self._args.datasetName)
filePath = self._getFilePath(self._args.filePath,
self._args.relativePath)
na... | def function[addFeatureSet, parameter[self]]:
constant[
Adds a new feature set into this repo
]
call[name[self]._openRepo, parameter[]]
variable[dataset] assign[=] call[name[self]._repo.getDatasetByName, parameter[name[self]._args.datasetName]]
variable[filePath] assign[=... | keyword[def] identifier[addFeatureSet] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_openRepo] ()
identifier[dataset] = identifier[self] . identifier[_repo] . identifier[getDatasetByName] ( identifier[self] . identifier[_args] . identifier[datasetName] )
ide... | def addFeatureSet(self):
"""
Adds a new feature set into this repo
"""
self._openRepo()
dataset = self._repo.getDatasetByName(self._args.datasetName)
filePath = self._getFilePath(self._args.filePath, self._args.relativePath)
name = getNameFromPath(self._args.filePath)
featureSet ... |
def list_all_files(self):
""" Utility method that yields all files on the device's file
systems.
"""
def list_files_recursively(directory):
f_gen = itertools.chain(
directory.files,
*tuple(list_files_recursively(d)
fo... | def function[list_all_files, parameter[self]]:
constant[ Utility method that yields all files on the device's file
systems.
]
def function[list_files_recursively, parameter[directory]]:
variable[f_gen] assign[=] call[name[itertools].chain, parameter[name[directory].fi... | keyword[def] identifier[list_all_files] ( identifier[self] ):
literal[string]
keyword[def] identifier[list_files_recursively] ( identifier[directory] ):
identifier[f_gen] = identifier[itertools] . identifier[chain] (
identifier[directory] . identifier[files] ,
... | def list_all_files(self):
""" Utility method that yields all files on the device's file
systems.
"""
def list_files_recursively(directory):
f_gen = itertools.chain(directory.files, *tuple((list_files_recursively(d) for d in directory.directories)))
for f in f_gen:
... |
def detect_response_encoding(response, is_html=False, peek=131072):
'''Return the likely encoding of the response document.
Args:
response (Response): An instance of :class:`.http.Response`.
is_html (bool): See :func:`.util.detect_encoding`.
peek (int): The maximum number of bytes of th... | def function[detect_response_encoding, parameter[response, is_html, peek]]:
constant[Return the likely encoding of the response document.
Args:
response (Response): An instance of :class:`.http.Response`.
is_html (bool): See :func:`.util.detect_encoding`.
peek (int): The maximum num... | keyword[def] identifier[detect_response_encoding] ( identifier[response] , identifier[is_html] = keyword[False] , identifier[peek] = literal[int] ):
literal[string]
identifier[encoding] = identifier[get_heading_encoding] ( identifier[response] )
identifier[encoding] = identifier[wpull] . identifier[s... | def detect_response_encoding(response, is_html=False, peek=131072):
"""Return the likely encoding of the response document.
Args:
response (Response): An instance of :class:`.http.Response`.
is_html (bool): See :func:`.util.detect_encoding`.
peek (int): The maximum number of bytes of th... |
def from_json(cls, json_data):
"""Deserialize a JSON-serialized instance.
Inverse to :meth:`to_json`.
Args:
json_data: dict or string, Serialized JSON (as a string or an
already parsed dictionary) representing a credential.
Returns:
Servi... | def function[from_json, parameter[cls, json_data]]:
constant[Deserialize a JSON-serialized instance.
Inverse to :meth:`to_json`.
Args:
json_data: dict or string, Serialized JSON (as a string or an
already parsed dictionary) representing a credential.
... | keyword[def] identifier[from_json] ( identifier[cls] , identifier[json_data] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[json_data] , identifier[dict] ):
identifier[json_data] = identifier[json] . identifier[loads] ( identifier[_helpers] . identifi... | def from_json(cls, json_data):
"""Deserialize a JSON-serialized instance.
Inverse to :meth:`to_json`.
Args:
json_data: dict or string, Serialized JSON (as a string or an
already parsed dictionary) representing a credential.
Returns:
ServiceAc... |
def generate_message_definitions(basename, xml):
'''generate files for one XML file'''
directory = os.path.join(basename, xml.basename)
print("Generating Objective-C implementation in directory %s" % directory)
mavparse.mkdir_p(directory)
xml.basename_camel_case = camel_case_from_underscores(xml.... | def function[generate_message_definitions, parameter[basename, xml]]:
constant[generate files for one XML file]
variable[directory] assign[=] call[name[os].path.join, parameter[name[basename], name[xml].basename]]
call[name[print], parameter[binary_operation[constant[Generating Objective-C imple... | keyword[def] identifier[generate_message_definitions] ( identifier[basename] , identifier[xml] ):
literal[string]
identifier[directory] = identifier[os] . identifier[path] . identifier[join] ( identifier[basename] , identifier[xml] . identifier[basename] )
identifier[print] ( literal[string] % ident... | def generate_message_definitions(basename, xml):
"""generate files for one XML file"""
directory = os.path.join(basename, xml.basename)
print('Generating Objective-C implementation in directory %s' % directory)
mavparse.mkdir_p(directory)
xml.basename_camel_case = camel_case_from_underscores(xml.bas... |
def get_address_nonce(self, address, api_token):
"""
Looks up the address nonce of this address
Neccesary for the transaction creation
"""
broadcast_url = self.base_url + '?module=proxy&action=eth_getTransactionCount'
broadcast_url += '&address=%s' % address
broad... | def function[get_address_nonce, parameter[self, address, api_token]]:
constant[
Looks up the address nonce of this address
Neccesary for the transaction creation
]
variable[broadcast_url] assign[=] binary_operation[name[self].base_url + constant[?module=proxy&action=eth_getTransa... | keyword[def] identifier[get_address_nonce] ( identifier[self] , identifier[address] , identifier[api_token] ):
literal[string]
identifier[broadcast_url] = identifier[self] . identifier[base_url] + literal[string]
identifier[broadcast_url] += literal[string] % identifier[address]
... | def get_address_nonce(self, address, api_token):
"""
Looks up the address nonce of this address
Neccesary for the transaction creation
"""
broadcast_url = self.base_url + '?module=proxy&action=eth_getTransactionCount'
broadcast_url += '&address=%s' % address
broadcast_url += '&ta... |
def wait(self, timeout=15):
"""
block until pod is not ready, raises an exc ProbeTimeout if timeout is reached
:param timeout: int or float (seconds), time to wait for pod to run
:return: None
"""
Probe(timeout=timeout, fnc=self.is_ready, expected_retval=True).run() | def function[wait, parameter[self, timeout]]:
constant[
block until pod is not ready, raises an exc ProbeTimeout if timeout is reached
:param timeout: int or float (seconds), time to wait for pod to run
:return: None
]
call[call[name[Probe], parameter[]].run, parameter[]] | keyword[def] identifier[wait] ( identifier[self] , identifier[timeout] = literal[int] ):
literal[string]
identifier[Probe] ( identifier[timeout] = identifier[timeout] , identifier[fnc] = identifier[self] . identifier[is_ready] , identifier[expected_retval] = keyword[True] ). identifier[run] () | def wait(self, timeout=15):
"""
block until pod is not ready, raises an exc ProbeTimeout if timeout is reached
:param timeout: int or float (seconds), time to wait for pod to run
:return: None
"""
Probe(timeout=timeout, fnc=self.is_ready, expected_retval=True).run() |
def auth(self, password):
"""Request for authentication in a password-protected Redis server.
Redis can be instructed to require a password before allowing clients
to execute commands. This is done using the ``requirepass`` directive
in the configuration file.
If the password do... | def function[auth, parameter[self, password]]:
constant[Request for authentication in a password-protected Redis server.
Redis can be instructed to require a password before allowing clients
to execute commands. This is done using the ``requirepass`` directive
in the configuration file.
... | keyword[def] identifier[auth] ( identifier[self] , identifier[password] ):
literal[string]
identifier[future] = identifier[concurrent] . identifier[TracebackFuture] ()
keyword[def] identifier[on_response] ( identifier[response] ):
literal[string]
identifier[exc... | def auth(self, password):
"""Request for authentication in a password-protected Redis server.
Redis can be instructed to require a password before allowing clients
to execute commands. This is done using the ``requirepass`` directive
in the configuration file.
If the password does n... |
def to_date(value, default=None):
"""Tries to convert the passed in value to Zope's DateTime
:param value: The value to be converted to a valid DateTime
:type value: str, DateTime or datetime
:return: The DateTime representation of the value passed in or default
"""
if isinstance(value, DateTim... | def function[to_date, parameter[value, default]]:
constant[Tries to convert the passed in value to Zope's DateTime
:param value: The value to be converted to a valid DateTime
:type value: str, DateTime or datetime
:return: The DateTime representation of the value passed in or default
]
... | keyword[def] identifier[to_date] ( identifier[value] , identifier[default] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[value] , identifier[DateTime] ):
keyword[return] identifier[value]
keyword[if] keyword[not] identifier[value] :
keyword[i... | def to_date(value, default=None):
"""Tries to convert the passed in value to Zope's DateTime
:param value: The value to be converted to a valid DateTime
:type value: str, DateTime or datetime
:return: The DateTime representation of the value passed in or default
"""
if isinstance(value, DateTim... |
def retry_mkstemp(suffix='', prefix='tmp', directory=None, max_retries=3):
"""
Make mkstemp more robust against AFS glitches.
"""
if directory is None:
directory = current_app.config['CFG_TMPSHAREDDIR']
for retry_count in range(1, max_retries + 1):
try:
tmp_file_fd, tmp_f... | def function[retry_mkstemp, parameter[suffix, prefix, directory, max_retries]]:
constant[
Make mkstemp more robust against AFS glitches.
]
if compare[name[directory] is constant[None]] begin[:]
variable[directory] assign[=] call[name[current_app].config][constant[CFG_TMPSHAREDDIR... | keyword[def] identifier[retry_mkstemp] ( identifier[suffix] = literal[string] , identifier[prefix] = literal[string] , identifier[directory] = keyword[None] , identifier[max_retries] = literal[int] ):
literal[string]
keyword[if] identifier[directory] keyword[is] keyword[None] :
identifier[direc... | def retry_mkstemp(suffix='', prefix='tmp', directory=None, max_retries=3):
"""
Make mkstemp more robust against AFS glitches.
"""
if directory is None:
directory = current_app.config['CFG_TMPSHAREDDIR'] # depends on [control=['if'], data=['directory']]
for retry_count in range(1, max_retrie... |
def GetReportDownloadHeaders(self, **kwargs):
"""Returns a dictionary of headers for a report download request.
Note that the given keyword arguments will override any settings configured
from the googleads.yaml file.
Args:
**kwargs: Optional keyword arguments.
Keyword Arguments:
clie... | def function[GetReportDownloadHeaders, parameter[self]]:
constant[Returns a dictionary of headers for a report download request.
Note that the given keyword arguments will override any settings configured
from the googleads.yaml file.
Args:
**kwargs: Optional keyword arguments.
Keyword ... | keyword[def] identifier[GetReportDownloadHeaders] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[headers] = identifier[self] . identifier[_adwords_client] . identifier[oauth2_client] . identifier[CreateHttpHeader] ()
identifier[headers] . identifier[update] ({
literal[str... | def GetReportDownloadHeaders(self, **kwargs):
"""Returns a dictionary of headers for a report download request.
Note that the given keyword arguments will override any settings configured
from the googleads.yaml file.
Args:
**kwargs: Optional keyword arguments.
Keyword Arguments:
clie... |
def installedDependents(self, target):
"""
Return an iterable of things installed on the target that
require this item.
"""
for dc in self.store.query(_DependencyConnector,
_DependencyConnector.target == target):
depends = dependentsOf(dc.installee.__class__)
... | def function[installedDependents, parameter[self, target]]:
constant[
Return an iterable of things installed on the target that
require this item.
]
for taget[name[dc]] in starred[call[name[self].store.query, parameter[name[_DependencyConnector], compare[name[_DependencyConnector].target equ... | keyword[def] identifier[installedDependents] ( identifier[self] , identifier[target] ):
literal[string]
keyword[for] identifier[dc] keyword[in] identifier[self] . identifier[store] . identifier[query] ( identifier[_DependencyConnector] ,
identifier[_DependencyConnector] . identifier[target] == iden... | def installedDependents(self, target):
"""
Return an iterable of things installed on the target that
require this item.
"""
for dc in self.store.query(_DependencyConnector, _DependencyConnector.target == target):
depends = dependentsOf(dc.installee.__class__)
if self.__class__ in dep... |
def permute(sequence, permutation):
"""Apply a permutation sigma({j}) to an arbitrary sequence.
:param sequence: Any finite length sequence ``[l_1,l_2,...l_n]``. If it is a list, tuple or str, the return type will be the same.
:param permutation: permutation image tuple
:type permutation: tuple
:re... | def function[permute, parameter[sequence, permutation]]:
constant[Apply a permutation sigma({j}) to an arbitrary sequence.
:param sequence: Any finite length sequence ``[l_1,l_2,...l_n]``. If it is a list, tuple or str, the return type will be the same.
:param permutation: permutation image tuple
:... | keyword[def] identifier[permute] ( identifier[sequence] , identifier[permutation] ):
literal[string]
keyword[if] identifier[len] ( identifier[sequence] )!= identifier[len] ( identifier[permutation] ):
keyword[raise] identifier[ValueError] (( identifier[sequence] , identifier[permutation] ))
... | def permute(sequence, permutation):
"""Apply a permutation sigma({j}) to an arbitrary sequence.
:param sequence: Any finite length sequence ``[l_1,l_2,...l_n]``. If it is a list, tuple or str, the return type will be the same.
:param permutation: permutation image tuple
:type permutation: tuple
:re... |
def run(self, dag):
"""
Run the StochasticSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
Raises:
TranspilerError: if the coupling map or the layout are not
compatible with the DAG
... | def function[run, parameter[self, dag]]:
constant[
Run the StochasticSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
Raises:
TranspilerError: if the coupling map or the layout are not
co... | keyword[def] identifier[run] ( identifier[self] , identifier[dag] ):
literal[string]
keyword[if] identifier[self] . identifier[initial_layout] keyword[is] keyword[None] :
keyword[if] identifier[self] . identifier[property_set] [ literal[string] ]:
identifier[self]... | def run(self, dag):
"""
Run the StochasticSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
Raises:
TranspilerError: if the coupling map or the layout are not
compatible with the DAG
"... |
def validation_scatter(self, log_lam, b, masks, pre_v, gp, flux,
time, med):
'''
Computes the scatter in the validation set.
'''
# Update the lambda matrix
self.lam[b] = 10 ** log_lam
# Validation set scatter
scatter = [None for i in ... | def function[validation_scatter, parameter[self, log_lam, b, masks, pre_v, gp, flux, time, med]]:
constant[
Computes the scatter in the validation set.
]
call[name[self].lam][name[b]] assign[=] binary_operation[constant[10] ** name[log_lam]]
variable[scatter] assign[=] <ast.List... | keyword[def] identifier[validation_scatter] ( identifier[self] , identifier[log_lam] , identifier[b] , identifier[masks] , identifier[pre_v] , identifier[gp] , identifier[flux] ,
identifier[time] , identifier[med] ):
literal[string]
identifier[self] . identifier[lam] [ identifier[b] ]= l... | def validation_scatter(self, log_lam, b, masks, pre_v, gp, flux, time, med):
"""
Computes the scatter in the validation set.
"""
# Update the lambda matrix
self.lam[b] = 10 ** log_lam
# Validation set scatter
scatter = [None for i in range(len(masks))]
for i in range(len(masks))... |
def _write_error_batch_wait(future, batch, database, measurement,
measurements):
"""Invoked by the IOLoop, this method checks if the HTTP request future
created by :meth:`_write_error_batch` is done. If it's done it will
evaluate the result, logging any error and moving on to the... | def function[_write_error_batch_wait, parameter[future, batch, database, measurement, measurements]]:
constant[Invoked by the IOLoop, this method checks if the HTTP request future
created by :meth:`_write_error_batch` is done. If it's done it will
evaluate the result, logging any error and moving on to ... | keyword[def] identifier[_write_error_batch_wait] ( identifier[future] , identifier[batch] , identifier[database] , identifier[measurement] ,
identifier[measurements] ):
literal[string]
keyword[if] keyword[not] identifier[future] . identifier[done] ():
identifier[ioloop] . identifier[IOLoop] . i... | def _write_error_batch_wait(future, batch, database, measurement, measurements):
"""Invoked by the IOLoop, this method checks if the HTTP request future
created by :meth:`_write_error_batch` is done. If it's done it will
evaluate the result, logging any error and moving on to the next
measurement. If th... |
def _persist_metadata(self):
"""
Write all script meta-data, including the persistent script Store.
The Store instance might contain arbitrary user data, like function objects, OpenCL contexts, or whatever other
non-serializable objects, both as keys or values.
Try to serialize t... | def function[_persist_metadata, parameter[self]]:
constant[
Write all script meta-data, including the persistent script Store.
The Store instance might contain arbitrary user data, like function objects, OpenCL contexts, or whatever other
non-serializable objects, both as keys or values.... | keyword[def] identifier[_persist_metadata] ( identifier[self] ):
literal[string]
identifier[serializable_data] = identifier[self] . identifier[get_serializable] ()
keyword[try] :
identifier[self] . identifier[_try_persist_metadata] ( identifier[serializable_data] )
ke... | def _persist_metadata(self):
"""
Write all script meta-data, including the persistent script Store.
The Store instance might contain arbitrary user data, like function objects, OpenCL contexts, or whatever other
non-serializable objects, both as keys or values.
Try to serialize the d... |
def wrap_cell_expression(source, template='{expr}'):
"""
If a cell ends in an expression that could be displaying a HoloViews
object (as determined using the AST), wrap it with a given prefix
and suffix string.
If the cell doesn't end in an expression, return the source unchanged.
"""
cell_... | def function[wrap_cell_expression, parameter[source, template]]:
constant[
If a cell ends in an expression that could be displaying a HoloViews
object (as determined using the AST), wrap it with a given prefix
and suffix string.
If the cell doesn't end in an expression, return the source unchan... | keyword[def] identifier[wrap_cell_expression] ( identifier[source] , identifier[template] = literal[string] ):
literal[string]
identifier[cell_output_types] =( identifier[ast] . identifier[IfExp] , identifier[ast] . identifier[BoolOp] , identifier[ast] . identifier[BinOp] , identifier[ast] . identifier[Cal... | def wrap_cell_expression(source, template='{expr}'):
"""
If a cell ends in an expression that could be displaying a HoloViews
object (as determined using the AST), wrap it with a given prefix
and suffix string.
If the cell doesn't end in an expression, return the source unchanged.
"""
cell_... |
def encode_bytes(obj, nsprefix=None):
""" Encodes an OpenMath element into a string.
:param obj: Object to encode as string.
:type obj: OMAny
:rtype: bytes
"""
node = encode_xml(obj, nsprefix)
return etree.tostring(node) | def function[encode_bytes, parameter[obj, nsprefix]]:
constant[ Encodes an OpenMath element into a string.
:param obj: Object to encode as string.
:type obj: OMAny
:rtype: bytes
]
variable[node] assign[=] call[name[encode_xml], parameter[name[obj], name[nsprefix]]]
return[call[name... | keyword[def] identifier[encode_bytes] ( identifier[obj] , identifier[nsprefix] = keyword[None] ):
literal[string]
identifier[node] = identifier[encode_xml] ( identifier[obj] , identifier[nsprefix] )
keyword[return] identifier[etree] . identifier[tostring] ( identifier[node] ) | def encode_bytes(obj, nsprefix=None):
""" Encodes an OpenMath element into a string.
:param obj: Object to encode as string.
:type obj: OMAny
:rtype: bytes
"""
node = encode_xml(obj, nsprefix)
return etree.tostring(node) |
def funcNrlTcMotPred(idxPrc,
varPixX,
varPixY,
NrlMdlChunk,
varNumTP,
aryBoxCar, # aryCond
path,
varNumNrlMdls,
varNumMtDrctn,
var... | def function[funcNrlTcMotPred, parameter[idxPrc, varPixX, varPixY, NrlMdlChunk, varNumTP, aryBoxCar, path, varNumNrlMdls, varNumMtDrctn, varPar, queOut]]:
constant[
Function for creating neural time course models.
This function should be used to create neural models if different
predictors for every... | keyword[def] identifier[funcNrlTcMotPred] ( identifier[idxPrc] ,
identifier[varPixX] ,
identifier[varPixY] ,
identifier[NrlMdlChunk] ,
identifier[varNumTP] ,
identifier[aryBoxCar] ,
identifier[path] ,
identifier[varNumNrlMdls] ,
identifier[varNumMtDrctn] ,
identifier[varPar] ,
identifier[queOut] ):
lit... | def funcNrlTcMotPred(idxPrc, varPixX, varPixY, NrlMdlChunk, varNumTP, aryBoxCar, path, varNumNrlMdls, varNumMtDrctn, varPar, queOut): # aryCond
'\n Function for creating neural time course models.\n This function should be used to create neural models if different\n predictors for every motion direction a... |
def compute_batch(self, duplicate_manager=None, context_manager=None):
"""
Computes the elements of the batch sequentially by penalizing the acquisition.
"""
from ...acquisitions import AcquisitionLP
assert isinstance(self.acquisition, AcquisitionLP)
self.acquisition.upd... | def function[compute_batch, parameter[self, duplicate_manager, context_manager]]:
constant[
Computes the elements of the batch sequentially by penalizing the acquisition.
]
from relative_module[acquisitions] import module[AcquisitionLP]
assert[call[name[isinstance], parameter[name[self].... | keyword[def] identifier[compute_batch] ( identifier[self] , identifier[duplicate_manager] = keyword[None] , identifier[context_manager] = keyword[None] ):
literal[string]
keyword[from] ... identifier[acquisitions] keyword[import] identifier[AcquisitionLP]
keyword[assert] identifier[isi... | def compute_batch(self, duplicate_manager=None, context_manager=None):
"""
Computes the elements of the batch sequentially by penalizing the acquisition.
"""
from ...acquisitions import AcquisitionLP
assert isinstance(self.acquisition, AcquisitionLP)
self.acquisition.update_batches(None,... |
def pr_auc(fg_vals, bg_vals):
"""
Computes the Precision-Recall Area Under Curve (PR AUC)
Parameters
----------
fg_vals : array_like
list of values for positive set
bg_vals : array_like
list of values for negative set
Returns
-------
score : float
PR AU... | def function[pr_auc, parameter[fg_vals, bg_vals]]:
constant[
Computes the Precision-Recall Area Under Curve (PR AUC)
Parameters
----------
fg_vals : array_like
list of values for positive set
bg_vals : array_like
list of values for negative set
Returns
-------
... | keyword[def] identifier[pr_auc] ( identifier[fg_vals] , identifier[bg_vals] ):
literal[string]
identifier[y_true] , identifier[y_score] = identifier[values_to_labels] ( identifier[fg_vals] , identifier[bg_vals] )
keyword[return] identifier[average_precision_score] ( identifier[y_true] , identif... | def pr_auc(fg_vals, bg_vals):
"""
Computes the Precision-Recall Area Under Curve (PR AUC)
Parameters
----------
fg_vals : array_like
list of values for positive set
bg_vals : array_like
list of values for negative set
Returns
-------
score : float
PR AU... |
def kill_chain_phase_names(instance):
"""Ensure the `kill_chain_name` and `phase_name` properties of
`kill_chain_phase` objects follow naming style conventions.
"""
if instance['type'] in enums.KILL_CHAIN_PHASE_USES and 'kill_chain_phases' in instance:
for phase in instance['kill_chain_phases']:... | def function[kill_chain_phase_names, parameter[instance]]:
constant[Ensure the `kill_chain_name` and `phase_name` properties of
`kill_chain_phase` objects follow naming style conventions.
]
if <ast.BoolOp object at 0x7da1b0fc45e0> begin[:]
for taget[name[phase]] in starred[call[n... | keyword[def] identifier[kill_chain_phase_names] ( identifier[instance] ):
literal[string]
keyword[if] identifier[instance] [ literal[string] ] keyword[in] identifier[enums] . identifier[KILL_CHAIN_PHASE_USES] keyword[and] literal[string] keyword[in] identifier[instance] :
keyword[for] ident... | def kill_chain_phase_names(instance):
"""Ensure the `kill_chain_name` and `phase_name` properties of
`kill_chain_phase` objects follow naming style conventions.
"""
if instance['type'] in enums.KILL_CHAIN_PHASE_USES and 'kill_chain_phases' in instance:
for phase in instance['kill_chain_phases']:... |
def report_errors(audit, url):
"""
Args:
audit: results of `AxeCoreAudit.do_audit()`.
url: the url of the page being audited.
Raises: `AccessibilityError`
"""
errors = AxeCoreAudit.get_errors(audit)
if errors["total"] > 0:
msg = u"URL... | def function[report_errors, parameter[audit, url]]:
constant[
Args:
audit: results of `AxeCoreAudit.do_audit()`.
url: the url of the page being audited.
Raises: `AccessibilityError`
]
variable[errors] assign[=] call[name[AxeCoreAudit].get_errors, paramet... | keyword[def] identifier[report_errors] ( identifier[audit] , identifier[url] ):
literal[string]
identifier[errors] = identifier[AxeCoreAudit] . identifier[get_errors] ( identifier[audit] )
keyword[if] identifier[errors] [ literal[string] ]> literal[int] :
identifier[msg] = li... | def report_errors(audit, url):
"""
Args:
audit: results of `AxeCoreAudit.do_audit()`.
url: the url of the page being audited.
Raises: `AccessibilityError`
"""
errors = AxeCoreAudit.get_errors(audit)
if errors['total'] > 0:
msg = u"URL '{}' has {} err... |
def move(self, parent, index=None):
"""
Move this group to a new parent.
:param parent: The new parent group; if None will be root group.
:type parent: :class:`keepassdb.model.Group`
:param index: The 0-based index within the parent (defaults to appending
... | def function[move, parameter[self, parent, index]]:
constant[
Move this group to a new parent.
:param parent: The new parent group; if None will be root group.
:type parent: :class:`keepassdb.model.Group`
:param index: The 0-based index within the parent (defaults to app... | keyword[def] identifier[move] ( identifier[self] , identifier[parent] , identifier[index] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[db] . identifier[move_group] ( identifier[self] , identifier[parent] , identifier[index] = identifier[index] ) | def move(self, parent, index=None):
"""
Move this group to a new parent.
:param parent: The new parent group; if None will be root group.
:type parent: :class:`keepassdb.model.Group`
:param index: The 0-based index within the parent (defaults to appending
... |
def application(self, app_id):
"""Update the context to use the given application ID and stop the
application when done.
For example::
with cn.application(54):
# All commands in this block will use app_id=54.
# On leaving the block `cn.send_signal("s... | def function[application, parameter[self, app_id]]:
constant[Update the context to use the given application ID and stop the
application when done.
For example::
with cn.application(54):
# All commands in this block will use app_id=54.
# On leaving t... | keyword[def] identifier[application] ( identifier[self] , identifier[app_id] ):
literal[string]
identifier[context] = identifier[self] ( identifier[app_id] = identifier[app_id] )
identifier[context] . identifier[before_close] ( keyword[lambda] : identifier[self] . identif... | def application(self, app_id):
"""Update the context to use the given application ID and stop the
application when done.
For example::
with cn.application(54):
# All commands in this block will use app_id=54.
# On leaving the block `cn.send_signal("stop"... |
def validate(cls, mapper_spec):
"""Validates mapper spec and all mapper parameters.
Args:
mapper_spec: The MapperSpec for this InputReader.
Raises:
BadReaderParamsError: required parameters are missing or invalid.
"""
if mapper_spec.input_reader_class() != cls:
raise BadReaderPar... | def function[validate, parameter[cls, mapper_spec]]:
constant[Validates mapper spec and all mapper parameters.
Args:
mapper_spec: The MapperSpec for this InputReader.
Raises:
BadReaderParamsError: required parameters are missing or invalid.
]
if compare[call[name[mapper_spec].i... | keyword[def] identifier[validate] ( identifier[cls] , identifier[mapper_spec] ):
literal[string]
keyword[if] identifier[mapper_spec] . identifier[input_reader_class] ()!= identifier[cls] :
keyword[raise] identifier[BadReaderParamsError] ( literal[string] )
identifier[params] = identifier[_get... | def validate(cls, mapper_spec):
"""Validates mapper spec and all mapper parameters.
Args:
mapper_spec: The MapperSpec for this InputReader.
Raises:
BadReaderParamsError: required parameters are missing or invalid.
"""
if mapper_spec.input_reader_class() != cls:
raise BadReaderP... |
def keep_path(self, path):
"""
Given a path, returns True if the path should be kept, False if it should be cut.
"""
if len(path.addr_trace) < 2:
return True
return self.should_take_exit(path.addr_trace[-2], path.addr_trace[-1]) | def function[keep_path, parameter[self, path]]:
constant[
Given a path, returns True if the path should be kept, False if it should be cut.
]
if compare[call[name[len], parameter[name[path].addr_trace]] less[<] constant[2]] begin[:]
return[constant[True]]
return[call[name[sel... | keyword[def] identifier[keep_path] ( identifier[self] , identifier[path] ):
literal[string]
keyword[if] identifier[len] ( identifier[path] . identifier[addr_trace] )< literal[int] :
keyword[return] keyword[True]
keyword[return] identifier[self] . identifier[should_take_ex... | def keep_path(self, path):
"""
Given a path, returns True if the path should be kept, False if it should be cut.
"""
if len(path.addr_trace) < 2:
return True # depends on [control=['if'], data=[]]
return self.should_take_exit(path.addr_trace[-2], path.addr_trace[-1]) |
def analyze(self, handle, filename):
"""Submit a file for analysis.
:type handle: File handle
:param handle: Handle to file to upload for analysis.
:type filename: str
:param filename: File name.
:rtype: str
:return: Task ID as a string
"""
... | def function[analyze, parameter[self, handle, filename]]:
constant[Submit a file for analysis.
:type handle: File handle
:param handle: Handle to file to upload for analysis.
:type filename: str
:param filename: File name.
:rtype: str
:return: Task ID as ... | keyword[def] identifier[analyze] ( identifier[self] , identifier[handle] , identifier[filename] ):
literal[string]
identifier[handle] . identifier[seek] ( literal[int] )
keyword[try] :
keyword[return] identifier[self] . identifier[jbx] . identifier[submit_sample] ( ... | def analyze(self, handle, filename):
"""Submit a file for analysis.
:type handle: File handle
:param handle: Handle to file to upload for analysis.
:type filename: str
:param filename: File name.
:rtype: str
:return: Task ID as a string
"""
# ensu... |
def format_call(self, api_version, api_call):
""" Return properly formatted QualysGuard API call according to api_version etiquette.
"""
# Remove possible starting slashes or trailing question marks in call.
api_call = api_call.lstrip('/')
api_call = api_call.rstrip('?')
... | def function[format_call, parameter[self, api_version, api_call]]:
constant[ Return properly formatted QualysGuard API call according to api_version etiquette.
]
variable[api_call] assign[=] call[name[api_call].lstrip, parameter[constant[/]]]
variable[api_call] assign[=] call[name[api_c... | keyword[def] identifier[format_call] ( identifier[self] , identifier[api_version] , identifier[api_call] ):
literal[string]
identifier[api_call] = identifier[api_call] . identifier[lstrip] ( literal[string] )
identifier[api_call] = identifier[api_call] . identifier[rstrip] ( liter... | def format_call(self, api_version, api_call):
""" Return properly formatted QualysGuard API call according to api_version etiquette.
"""
# Remove possible starting slashes or trailing question marks in call.
api_call = api_call.lstrip('/')
api_call = api_call.rstrip('?')
logger.debug('api_c... |
def as_html(self):
"""
Return the OGC WKT which corresponds to the CRS as HTML.
For example::
>>> print(get(27700).as_html()) # doctest: +ELLIPSIS
<div class="syntax"><pre><span class="gh">PROJCS</span><span...
"""
url = '{prefix}{code}.html?download'.... | def function[as_html, parameter[self]]:
constant[
Return the OGC WKT which corresponds to the CRS as HTML.
For example::
>>> print(get(27700).as_html()) # doctest: +ELLIPSIS
<div class="syntax"><pre><span class="gh">PROJCS</span><span...
]
variable[url... | keyword[def] identifier[as_html] ( identifier[self] ):
literal[string]
identifier[url] = literal[string] . identifier[format] ( identifier[prefix] = identifier[EPSG_IO_URL] ,
identifier[code] = identifier[self] . identifier[id] )
keyword[return] identifier[requests] . identifier[... | def as_html(self):
"""
Return the OGC WKT which corresponds to the CRS as HTML.
For example::
>>> print(get(27700).as_html()) # doctest: +ELLIPSIS
<div class="syntax"><pre><span class="gh">PROJCS</span><span...
"""
url = '{prefix}{code}.html?download'.format(p... |
def parseDoc(cur):
"""parse an XML in-memory document and build a tree. """
ret = libxml2mod.xmlParseDoc(cur)
if ret is None:raise parserError('xmlParseDoc() failed')
return xmlDoc(_obj=ret) | def function[parseDoc, parameter[cur]]:
constant[parse an XML in-memory document and build a tree. ]
variable[ret] assign[=] call[name[libxml2mod].xmlParseDoc, parameter[name[cur]]]
if compare[name[ret] is constant[None]] begin[:]
<ast.Raise object at 0x7da1b1fa7340>
return[call[name... | keyword[def] identifier[parseDoc] ( identifier[cur] ):
literal[string]
identifier[ret] = identifier[libxml2mod] . identifier[xmlParseDoc] ( identifier[cur] )
keyword[if] identifier[ret] keyword[is] keyword[None] : keyword[raise] identifier[parserError] ( literal[string] )
keyword[return] ide... | def parseDoc(cur):
"""parse an XML in-memory document and build a tree. """
ret = libxml2mod.xmlParseDoc(cur)
if ret is None:
raise parserError('xmlParseDoc() failed') # depends on [control=['if'], data=[]]
return xmlDoc(_obj=ret) |
def rprint(sep='\n', end='\n', file=sys.stdout, flush=False):
"""A coroutine sink which prints received items stdout
Args:
sep: Optional separator to be printed between received items.
end: Optional terminator to be printed after the last item.
file: Optional stream to which to print.
... | def function[rprint, parameter[sep, end, file, flush]]:
constant[A coroutine sink which prints received items stdout
Args:
sep: Optional separator to be printed between received items.
end: Optional terminator to be printed after the last item.
file: Optional stream to which to prin... | keyword[def] identifier[rprint] ( identifier[sep] = literal[string] , identifier[end] = literal[string] , identifier[file] = identifier[sys] . identifier[stdout] , identifier[flush] = keyword[False] ):
literal[string]
keyword[try] :
identifier[first_item] =( keyword[yield] )
identifier[fi... | def rprint(sep='\n', end='\n', file=sys.stdout, flush=False):
"""A coroutine sink which prints received items stdout
Args:
sep: Optional separator to be printed between received items.
end: Optional terminator to be printed after the last item.
file: Optional stream to which to print.
... |
def save(self, filename=None, lineendings='default', encoding='latin-1'):
"""
Save the IDF as a text file with the optional filename passed, or with
the current idfname of the IDF.
Parameters
----------
filename : str, optional
Filepath to save the file. If N... | def function[save, parameter[self, filename, lineendings, encoding]]:
constant[
Save the IDF as a text file with the optional filename passed, or with
the current idfname of the IDF.
Parameters
----------
filename : str, optional
Filepath to save the file. If... | keyword[def] identifier[save] ( identifier[self] , identifier[filename] = keyword[None] , identifier[lineendings] = literal[string] , identifier[encoding] = literal[string] ):
literal[string]
keyword[if] identifier[filename] keyword[is] keyword[None] :
identifier[filename] = identif... | def save(self, filename=None, lineendings='default', encoding='latin-1'):
"""
Save the IDF as a text file with the optional filename passed, or with
the current idfname of the IDF.
Parameters
----------
filename : str, optional
Filepath to save the file. If None ... |
def raw_filter(self, filters):
"""Sends all filters to the API.
No fancy, just a wrapper. Any advanced functionality shall be implemented as another method.
Args:
filters: List of filters (strings)
Returns: :py:class:`SearchResult`
"""
return SearchResult(s... | def function[raw_filter, parameter[self, filters]]:
constant[Sends all filters to the API.
No fancy, just a wrapper. Any advanced functionality shall be implemented as another method.
Args:
filters: List of filters (strings)
Returns: :py:class:`SearchResult`
]
... | keyword[def] identifier[raw_filter] ( identifier[self] , identifier[filters] ):
literal[string]
keyword[return] identifier[SearchResult] ( identifier[self] , identifier[self] . identifier[_api] . identifier[get] ( identifier[self] . identifier[_href] ,**{ literal[string] : identifier[filters] })) | def raw_filter(self, filters):
"""Sends all filters to the API.
No fancy, just a wrapper. Any advanced functionality shall be implemented as another method.
Args:
filters: List of filters (strings)
Returns: :py:class:`SearchResult`
"""
return SearchResult(self, sel... |
def replace_customer_by_id(cls, customer_id, customer, **kwargs):
"""Replace Customer
Replace all attributes of Customer
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_customer_by_id(... | def function[replace_customer_by_id, parameter[cls, customer_id, customer]]:
constant[Replace Customer
Replace all attributes of Customer
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replac... | keyword[def] identifier[replace_customer_by_id] ( identifier[cls] , identifier[customer_id] , identifier[customer] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
... | def replace_customer_by_id(cls, customer_id, customer, **kwargs):
"""Replace Customer
Replace all attributes of Customer
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_customer_by_id(cust... |
def d_x(data, axis, boundary='forward-backward'):
'''
Calculates a second-order centered finite difference of data along the
specified axis.
Parameters
----------
data : ndarray
Data on which we are taking a derivative.
axis : int
Index of the data array on which to take the difference.
boundary : string,... | def function[d_x, parameter[data, axis, boundary]]:
constant[
Calculates a second-order centered finite difference of data along the
specified axis.
Parameters
----------
data : ndarray
Data on which we are taking a derivative.
axis : int
Index of the data array on which to take the difference.
bounda... | keyword[def] identifier[d_x] ( identifier[data] , identifier[axis] , identifier[boundary] = literal[string] ):
literal[string]
keyword[if] identifier[abs] ( identifier[axis] )> identifier[len] ( identifier[data] . identifier[shape] ):
keyword[raise] identifier[ValueError] ( literal[string] )
... | def d_x(data, axis, boundary='forward-backward'):
"""
Calculates a second-order centered finite difference of data along the
specified axis.
Parameters
----------
data : ndarray
Data on which we are taking a derivative.
axis : int
Index of the data array on which to take the difference.
boundary : string,... |
def create(cls, name, situation_context, attacker=None, target=None,
severity='information', situation_type=None, description=None,
comment=None):
"""
Create an inspection situation.
:param str name: name of the situation
:param InspectionSituationC... | def function[create, parameter[cls, name, situation_context, attacker, target, severity, situation_type, description, comment]]:
constant[
Create an inspection situation.
:param str name: name of the situation
:param InspectionSituationContext situation_context: The situation
... | keyword[def] identifier[create] ( identifier[cls] , identifier[name] , identifier[situation_context] , identifier[attacker] = keyword[None] , identifier[target] = keyword[None] ,
identifier[severity] = literal[string] , identifier[situation_type] = keyword[None] , identifier[description] = keyword[None] ,
identifie... | def create(cls, name, situation_context, attacker=None, target=None, severity='information', situation_type=None, description=None, comment=None):
"""
Create an inspection situation.
:param str name: name of the situation
:param InspectionSituationContext situation_context: The situ... |
def calculate_dates(self, dt):
"""
Given a date, find that day's open and period end (open + offset).
"""
period_start, period_close = self.cal.open_and_close_for_session(
self.cal.minute_to_session_label(dt),
)
# Align the market open and close times here wi... | def function[calculate_dates, parameter[self, dt]]:
constant[
Given a date, find that day's open and period end (open + offset).
]
<ast.Tuple object at 0x7da1b2046110> assign[=] call[name[self].cal.open_and_close_for_session, parameter[call[name[self].cal.minute_to_session_label, paramet... | keyword[def] identifier[calculate_dates] ( identifier[self] , identifier[dt] ):
literal[string]
identifier[period_start] , identifier[period_close] = identifier[self] . identifier[cal] . identifier[open_and_close_for_session] (
identifier[self] . identifier[cal] . identifier[minute_to_sess... | def calculate_dates(self, dt):
"""
Given a date, find that day's open and period end (open + offset).
"""
(period_start, period_close) = self.cal.open_and_close_for_session(self.cal.minute_to_session_label(dt))
# Align the market open and close times here with the execution times
# used ... |
def runner_argspec(module=''):
'''
Return the argument specification of functions in Salt runner
modules.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' sys.runner_argspec state
salt '*' sys.runner_argspec http
salt '*' sys.runner_argspec
R... | def function[runner_argspec, parameter[module]]:
constant[
Return the argument specification of functions in Salt runner
modules.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' sys.runner_argspec state
salt '*' sys.runner_argspec http
salt '... | keyword[def] identifier[runner_argspec] ( identifier[module] = literal[string] ):
literal[string]
identifier[run_] = identifier[salt] . identifier[runner] . identifier[Runner] ( identifier[__opts__] )
keyword[return] identifier[salt] . identifier[utils] . identifier[args] . identifier[argspec_report]... | def runner_argspec(module=''):
"""
Return the argument specification of functions in Salt runner
modules.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' sys.runner_argspec state
salt '*' sys.runner_argspec http
salt '*' sys.runner_argspec
R... |
def match_deadline(self, start, end, match):
"""Matches assessments whose end time falls between the specified range inclusive.
arg: start (osid.calendaring.DateTime): start of range
arg: end (osid.calendaring.DateTime): end of range
arg: match (boolean): ``true`` for a positiv... | def function[match_deadline, parameter[self, start, end, match]]:
constant[Matches assessments whose end time falls between the specified range inclusive.
arg: start (osid.calendaring.DateTime): start of range
arg: end (osid.calendaring.DateTime): end of range
arg: match (boole... | keyword[def] identifier[match_deadline] ( identifier[self] , identifier[start] , identifier[end] , identifier[match] ):
literal[string]
identifier[self] . identifier[_match_minimum_date_time] ( literal[string] , identifier[start] , identifier[match] )
identifier[self] . identifier[_match_m... | def match_deadline(self, start, end, match):
"""Matches assessments whose end time falls between the specified range inclusive.
arg: start (osid.calendaring.DateTime): start of range
arg: end (osid.calendaring.DateTime): end of range
arg: match (boolean): ``true`` for a positive ma... |
def version():
'''
Return server version from varnishd -V
CLI Example:
.. code-block:: bash
salt '*' varnish.version
'''
cmd = ['varnishd', '-V']
out = __salt__['cmd.run'](cmd, python_shell=False)
ret = re.search(r'\(varnish-([^\)]+)\)', out).group(1)
return ret | def function[version, parameter[]]:
constant[
Return server version from varnishd -V
CLI Example:
.. code-block:: bash
salt '*' varnish.version
]
variable[cmd] assign[=] list[[<ast.Constant object at 0x7da1b2169a80>, <ast.Constant object at 0x7da1b21686a0>]]
variable[o... | keyword[def] identifier[version] ():
literal[string]
identifier[cmd] =[ literal[string] , literal[string] ]
identifier[out] = identifier[__salt__] [ literal[string] ]( identifier[cmd] , identifier[python_shell] = keyword[False] )
identifier[ret] = identifier[re] . identifier[search] ( literal[str... | def version():
"""
Return server version from varnishd -V
CLI Example:
.. code-block:: bash
salt '*' varnish.version
"""
cmd = ['varnishd', '-V']
out = __salt__['cmd.run'](cmd, python_shell=False)
ret = re.search('\\(varnish-([^\\)]+)\\)', out).group(1)
return ret |
def random_pos(self, context_iterable, num_permutations):
"""Obtains random positions w/ replacement which match sequence context.
Parameters
----------
context_iterable: iterable containing two element tuple
Records number of mutations in each context. context_iterable
... | def function[random_pos, parameter[self, context_iterable, num_permutations]]:
constant[Obtains random positions w/ replacement which match sequence context.
Parameters
----------
context_iterable: iterable containing two element tuple
Records number of mutations in each con... | keyword[def] identifier[random_pos] ( identifier[self] , identifier[context_iterable] , identifier[num_permutations] ):
literal[string]
identifier[position_list] =[]
keyword[for] identifier[contxt] , identifier[n] keyword[in] identifier[context_iterable] :
identifier[pos_ar... | def random_pos(self, context_iterable, num_permutations):
"""Obtains random positions w/ replacement which match sequence context.
Parameters
----------
context_iterable: iterable containing two element tuple
Records number of mutations in each context. context_iterable
... |
def prefetch_translations(instances, **kwargs):
"""
Prefetches translations for the given instances.
Can be useful for a list of instances.
"""
from .mixins import ModelMixin
if not isinstance(instances, collections.Iterable):
instances = [instances]
populate_missing = kwargs.get("... | def function[prefetch_translations, parameter[instances]]:
constant[
Prefetches translations for the given instances.
Can be useful for a list of instances.
]
from relative_module[mixins] import module[ModelMixin]
if <ast.UnaryOp object at 0x7da20e9b1150> begin[:]
variabl... | keyword[def] identifier[prefetch_translations] ( identifier[instances] ,** identifier[kwargs] ):
literal[string]
keyword[from] . identifier[mixins] keyword[import] identifier[ModelMixin]
keyword[if] keyword[not] identifier[isinstance] ( identifier[instances] , identifier[collections] . identifie... | def prefetch_translations(instances, **kwargs):
"""
Prefetches translations for the given instances.
Can be useful for a list of instances.
"""
from .mixins import ModelMixin
if not isinstance(instances, collections.Iterable):
instances = [instances] # depends on [control=['if'], data=[... |
def sell(self, quantity, **kwargs):
""" Shortcut for ``instrument.order("SELL", ...)`` and accepts all of its
`optional parameters <#qtpylib.instrument.Instrument.order>`_
:Parameters:
quantity : int
Order quantity
"""
self.parent.order("SELL", self, ... | def function[sell, parameter[self, quantity]]:
constant[ Shortcut for ``instrument.order("SELL", ...)`` and accepts all of its
`optional parameters <#qtpylib.instrument.Instrument.order>`_
:Parameters:
quantity : int
Order quantity
]
call[name[self].p... | keyword[def] identifier[sell] ( identifier[self] , identifier[quantity] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[parent] . identifier[order] ( literal[string] , identifier[self] , identifier[quantity] = identifier[quantity] ,** identifier[kwargs] ) | def sell(self, quantity, **kwargs):
""" Shortcut for ``instrument.order("SELL", ...)`` and accepts all of its
`optional parameters <#qtpylib.instrument.Instrument.order>`_
:Parameters:
quantity : int
Order quantity
"""
self.parent.order('SELL', self, quantity... |
def designspace(self):
"""Get a designspace Document instance that links the masters together
and holds instance data.
"""
if self._designspace_is_complete:
return self._designspace
self._designspace_is_complete = True
list(self.masters) # Make sure that the... | def function[designspace, parameter[self]]:
constant[Get a designspace Document instance that links the masters together
and holds instance data.
]
if name[self]._designspace_is_complete begin[:]
return[name[self]._designspace]
name[self]._designspace_is_complete assign[=... | keyword[def] identifier[designspace] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_designspace_is_complete] :
keyword[return] identifier[self] . identifier[_designspace]
identifier[self] . identifier[_designspace_is_complete] = keyword[Tr... | def designspace(self):
"""Get a designspace Document instance that links the masters together
and holds instance data.
"""
if self._designspace_is_complete:
return self._designspace # depends on [control=['if'], data=[]]
self._designspace_is_complete = True
list(self.masters) #... |
def setTimeout(self, time):
"""Set global timeout value, in seconds, for all DDE calls"""
self.conversation.SetDDETimeout(round(time))
return self.conversation.GetDDETimeout() | def function[setTimeout, parameter[self, time]]:
constant[Set global timeout value, in seconds, for all DDE calls]
call[name[self].conversation.SetDDETimeout, parameter[call[name[round], parameter[name[time]]]]]
return[call[name[self].conversation.GetDDETimeout, parameter[]]] | keyword[def] identifier[setTimeout] ( identifier[self] , identifier[time] ):
literal[string]
identifier[self] . identifier[conversation] . identifier[SetDDETimeout] ( identifier[round] ( identifier[time] ))
keyword[return] identifier[self] . identifier[conversation] . identifier[GetDDETim... | def setTimeout(self, time):
"""Set global timeout value, in seconds, for all DDE calls"""
self.conversation.SetDDETimeout(round(time))
return self.conversation.GetDDETimeout() |
def _count_expected_bids(self, recipients):
'''
Count the expected number of bids (after receiving them we close the
contract. If the recipient type is broadcast return None which denotes
unknown number of bids (contract will be closed after timeout).
'''
count = 0
... | def function[_count_expected_bids, parameter[self, recipients]]:
constant[
Count the expected number of bids (after receiving them we close the
contract. If the recipient type is broadcast return None which denotes
unknown number of bids (contract will be closed after timeout).
]... | keyword[def] identifier[_count_expected_bids] ( identifier[self] , identifier[recipients] ):
literal[string]
identifier[count] = literal[int]
keyword[for] identifier[recp] keyword[in] identifier[recipients] :
keyword[if] identifier[recp] . identifier[type] == identifier[R... | def _count_expected_bids(self, recipients):
"""
Count the expected number of bids (after receiving them we close the
contract. If the recipient type is broadcast return None which denotes
unknown number of bids (contract will be closed after timeout).
"""
count = 0
for recp i... |
def sources(self):
"""
Returns a dictionary containing all defined sources (of any kind)
:return: collections.OrderedDict()
"""
sources = collections.OrderedDict()
for d in (self.point_sources, self.extended_sources, self.particle_sources):
sources.update... | def function[sources, parameter[self]]:
constant[
Returns a dictionary containing all defined sources (of any kind)
:return: collections.OrderedDict()
]
variable[sources] assign[=] call[name[collections].OrderedDict, parameter[]]
for taget[name[d]] in starred[tuple[[<as... | keyword[def] identifier[sources] ( identifier[self] ):
literal[string]
identifier[sources] = identifier[collections] . identifier[OrderedDict] ()
keyword[for] identifier[d] keyword[in] ( identifier[self] . identifier[point_sources] , identifier[self] . identifier[extended_sources] , id... | def sources(self):
"""
Returns a dictionary containing all defined sources (of any kind)
:return: collections.OrderedDict()
"""
sources = collections.OrderedDict()
for d in (self.point_sources, self.extended_sources, self.particle_sources):
sources.update(d) # depends on [... |
def saturate_color(color, amount):
"""Saturate a hex color."""
r, g, b = hex_to_rgb(color)
r, g, b = [x/255.0 for x in (r, g, b)]
h, l, s = colorsys.rgb_to_hls(r, g, b)
s = amount
r, g, b = colorsys.hls_to_rgb(h, l, s)
r, g, b = [x*255.0 for x in (r, g, b)]
return rgb_to_hex((int(r), in... | def function[saturate_color, parameter[color, amount]]:
constant[Saturate a hex color.]
<ast.Tuple object at 0x7da1b18be680> assign[=] call[name[hex_to_rgb], parameter[name[color]]]
<ast.Tuple object at 0x7da1b18d1bd0> assign[=] <ast.ListComp object at 0x7da1b18d1450>
<ast.Tuple object a... | keyword[def] identifier[saturate_color] ( identifier[color] , identifier[amount] ):
literal[string]
identifier[r] , identifier[g] , identifier[b] = identifier[hex_to_rgb] ( identifier[color] )
identifier[r] , identifier[g] , identifier[b] =[ identifier[x] / literal[int] keyword[for] identifier[x] k... | def saturate_color(color, amount):
"""Saturate a hex color."""
(r, g, b) = hex_to_rgb(color)
(r, g, b) = [x / 255.0 for x in (r, g, b)]
(h, l, s) = colorsys.rgb_to_hls(r, g, b)
s = amount
(r, g, b) = colorsys.hls_to_rgb(h, l, s)
(r, g, b) = [x * 255.0 for x in (r, g, b)]
return rgb_to_he... |
def seqlogo(letter_heights, vocab="DNA", ax=None):
"""Make a logo plot
# Arguments
letter_heights: "motif length" x "vocabulary size" numpy array
Can also contain negative values.
vocab: str, Vocabulary name. Can be: DNA, RNA, AA, RNAStruct.
ax: matplotlib axis
"""
ax = ax o... | def function[seqlogo, parameter[letter_heights, vocab, ax]]:
constant[Make a logo plot
# Arguments
letter_heights: "motif length" x "vocabulary size" numpy array
Can also contain negative values.
vocab: str, Vocabulary name. Can be: DNA, RNA, AA, RNAStruct.
ax: matplotlib axis
... | keyword[def] identifier[seqlogo] ( identifier[letter_heights] , identifier[vocab] = literal[string] , identifier[ax] = keyword[None] ):
literal[string]
identifier[ax] = identifier[ax] keyword[or] identifier[plt] . identifier[gca] ()
keyword[assert] identifier[letter_heights] . identifier[shape] [ ... | def seqlogo(letter_heights, vocab='DNA', ax=None):
"""Make a logo plot
# Arguments
letter_heights: "motif length" x "vocabulary size" numpy array
Can also contain negative values.
vocab: str, Vocabulary name. Can be: DNA, RNA, AA, RNAStruct.
ax: matplotlib axis
"""
ax = ax o... |
def _generic_matrix_calc(fn, trees, normalise, min_overlap=4, overlap_fail_value=0, show_progress=True):
"""(fn, trees, normalise)
Calculates all pairwise distances between trees given in the parameter 'trees'.
Distance functions:
eucdist_matrix
geodist_matrix
rfdist_matrix
... | def function[_generic_matrix_calc, parameter[fn, trees, normalise, min_overlap, overlap_fail_value, show_progress]]:
constant[(fn, trees, normalise)
Calculates all pairwise distances between trees given in the parameter 'trees'.
Distance functions:
eucdist_matrix
geodist_matrix
... | keyword[def] identifier[_generic_matrix_calc] ( identifier[fn] , identifier[trees] , identifier[normalise] , identifier[min_overlap] = literal[int] , identifier[overlap_fail_value] = literal[int] , identifier[show_progress] = keyword[True] ):
literal[string]
identifier[jobs] = identifier[itertools] . ident... | def _generic_matrix_calc(fn, trees, normalise, min_overlap=4, overlap_fail_value=0, show_progress=True):
"""(fn, trees, normalise)
Calculates all pairwise distances between trees given in the parameter 'trees'.
Distance functions:
eucdist_matrix
geodist_matrix
rfdist_matrix
... |
def process_context_token(self, context_token):
"""
Provides a way to pass an asynchronous token to the security context, outside of the normal
context-establishment token passing flow. This method is not normally used, but some
example uses are:
* when the initiator's context i... | def function[process_context_token, parameter[self, context_token]]:
constant[
Provides a way to pass an asynchronous token to the security context, outside of the normal
context-establishment token passing flow. This method is not normally used, but some
example uses are:
* whe... | keyword[def] identifier[process_context_token] ( identifier[self] , identifier[context_token] ):
literal[string]
identifier[minor_status] = identifier[ffi] . identifier[new] ( literal[string] )
identifier[context_token_buffer] = identifier[ffi] . identifier[new] ( literal[string] )
... | def process_context_token(self, context_token):
"""
Provides a way to pass an asynchronous token to the security context, outside of the normal
context-establishment token passing flow. This method is not normally used, but some
example uses are:
* when the initiator's context is es... |
def cdf(self, y, f, n):
r"""
Cumulative density function of the likelihood.
Parameters
----------
y: ndarray
query quantiles, i.e.\ :math:`P(Y \leq y)`.
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Ph... | def function[cdf, parameter[self, y, f, n]]:
constant[
Cumulative density function of the likelihood.
Parameters
----------
y: ndarray
query quantiles, i.e.\ :math:`P(Y \leq y)`.
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
... | keyword[def] identifier[cdf] ( identifier[self] , identifier[y] , identifier[f] , identifier[n] ):
literal[string]
keyword[return] identifier[binom] . identifier[cdf] ( identifier[y] , identifier[n] = identifier[n] , identifier[p] = identifier[expit] ( identifier[f] )) | def cdf(self, y, f, n):
"""
Cumulative density function of the likelihood.
Parameters
----------
y: ndarray
query quantiles, i.e.\\ :math:`P(Y \\leq y)`.
f: ndarray
latent function from the GLM prior (:math:`\\mathbf{f} =
\\boldsymbol\\Ph... |
def eventgroups(ctx, sport):
""" [bookie] List event groups for a sport
:param str sport: Sports id
"""
sport = Sport(sport, peerplays_instance=ctx.peerplays)
click.echo(pretty_print(sport.eventgroups, ctx=ctx)) | def function[eventgroups, parameter[ctx, sport]]:
constant[ [bookie] List event groups for a sport
:param str sport: Sports id
]
variable[sport] assign[=] call[name[Sport], parameter[name[sport]]]
call[name[click].echo, parameter[call[name[pretty_print], parameter[name[sport].eventg... | keyword[def] identifier[eventgroups] ( identifier[ctx] , identifier[sport] ):
literal[string]
identifier[sport] = identifier[Sport] ( identifier[sport] , identifier[peerplays_instance] = identifier[ctx] . identifier[peerplays] )
identifier[click] . identifier[echo] ( identifier[pretty_print] ( identif... | def eventgroups(ctx, sport):
""" [bookie] List event groups for a sport
:param str sport: Sports id
"""
sport = Sport(sport, peerplays_instance=ctx.peerplays)
click.echo(pretty_print(sport.eventgroups, ctx=ctx)) |
def reduce_sorted_to_intersect(ar1, ar2):
"""
Takes two sorted arrays and return the intersection ar1 in ar2, ar2 in ar1.
Parameters
----------
ar1 : (M,) array_like
Input array.
ar2 : array_like
Input array.
Returns
-------
ar1, ar1 : ndarray, ndarray
The ... | def function[reduce_sorted_to_intersect, parameter[ar1, ar2]]:
constant[
Takes two sorted arrays and return the intersection ar1 in ar2, ar2 in ar1.
Parameters
----------
ar1 : (M,) array_like
Input array.
ar2 : array_like
Input array.
Returns
-------
ar1, ar1 ... | keyword[def] identifier[reduce_sorted_to_intersect] ( identifier[ar1] , identifier[ar2] ):
literal[string]
identifier[ar1] = identifier[np] . identifier[asarray] ( identifier[ar1] ). identifier[ravel] ()
identifier[ar2] = identifier[np] . identifier[asarray] ( identifier[ar2] ). identifier[ravel]... | def reduce_sorted_to_intersect(ar1, ar2):
"""
Takes two sorted arrays and return the intersection ar1 in ar2, ar2 in ar1.
Parameters
----------
ar1 : (M,) array_like
Input array.
ar2 : array_like
Input array.
Returns
-------
ar1, ar1 : ndarray, ndarray
The ... |
def get_file_to_stream(self, stream, share_name, directory_name, file_name, **kwargs):
"""
Download a file from Azure File Share.
:param stream: A filehandle to store the file to.
:type stream: file-like object
:param share_name: Name of the share.
:type share_name: str
... | def function[get_file_to_stream, parameter[self, stream, share_name, directory_name, file_name]]:
constant[
Download a file from Azure File Share.
:param stream: A filehandle to store the file to.
:type stream: file-like object
:param share_name: Name of the share.
:type... | keyword[def] identifier[get_file_to_stream] ( identifier[self] , identifier[stream] , identifier[share_name] , identifier[directory_name] , identifier[file_name] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[connection] . identifier[get_file_to_stream] ( identifier[share_n... | def get_file_to_stream(self, stream, share_name, directory_name, file_name, **kwargs):
"""
Download a file from Azure File Share.
:param stream: A filehandle to store the file to.
:type stream: file-like object
:param share_name: Name of the share.
:type share_name: str
... |
def __fetch_crate_version_downloads(self, crate_id):
"""Get crate version downloads"""
raw_version_downloads = self.client.crate_attribute(crate_id, "downloads")
version_downloads = json.loads(raw_version_downloads)
return version_downloads | def function[__fetch_crate_version_downloads, parameter[self, crate_id]]:
constant[Get crate version downloads]
variable[raw_version_downloads] assign[=] call[name[self].client.crate_attribute, parameter[name[crate_id], constant[downloads]]]
variable[version_downloads] assign[=] call[name[json].... | keyword[def] identifier[__fetch_crate_version_downloads] ( identifier[self] , identifier[crate_id] ):
literal[string]
identifier[raw_version_downloads] = identifier[self] . identifier[client] . identifier[crate_attribute] ( identifier[crate_id] , literal[string] )
identifier[version_down... | def __fetch_crate_version_downloads(self, crate_id):
"""Get crate version downloads"""
raw_version_downloads = self.client.crate_attribute(crate_id, 'downloads')
version_downloads = json.loads(raw_version_downloads)
return version_downloads |
def tb_c_file_creation(target, source, env):
"""Compile tilebus file into a .h/.c pair for compilation into an ARM object"""
files = [str(x) for x in source]
try:
desc = TBDescriptor(files)
except pyparsing.ParseException as e:
raise BuildError("Could not parse tilebus file", parsing_e... | def function[tb_c_file_creation, parameter[target, source, env]]:
constant[Compile tilebus file into a .h/.c pair for compilation into an ARM object]
variable[files] assign[=] <ast.ListComp object at 0x7da2045668c0>
<ast.Try object at 0x7da204566830>
variable[block] assign[=] call[name[desc]... | keyword[def] identifier[tb_c_file_creation] ( identifier[target] , identifier[source] , identifier[env] ):
literal[string]
identifier[files] =[ identifier[str] ( identifier[x] ) keyword[for] identifier[x] keyword[in] identifier[source] ]
keyword[try] :
identifier[desc] = identifier[TBDes... | def tb_c_file_creation(target, source, env):
"""Compile tilebus file into a .h/.c pair for compilation into an ARM object"""
files = [str(x) for x in source]
try:
desc = TBDescriptor(files) # depends on [control=['try'], data=[]]
except pyparsing.ParseException as e:
raise BuildError('C... |
def is_course_run_upgradeable(course_run):
"""
Return true if the course run has a verified seat with an unexpired upgrade deadline, false otherwise.
"""
now = datetime.datetime.now(pytz.UTC)
for seat in course_run.get('seats', []):
if seat.get('type') == 'verified':
upgrade_dead... | def function[is_course_run_upgradeable, parameter[course_run]]:
constant[
Return true if the course run has a verified seat with an unexpired upgrade deadline, false otherwise.
]
variable[now] assign[=] call[name[datetime].datetime.now, parameter[name[pytz].UTC]]
for taget[name[seat]] in... | keyword[def] identifier[is_course_run_upgradeable] ( identifier[course_run] ):
literal[string]
identifier[now] = identifier[datetime] . identifier[datetime] . identifier[now] ( identifier[pytz] . identifier[UTC] )
keyword[for] identifier[seat] keyword[in] identifier[course_run] . identifier[get] ( ... | def is_course_run_upgradeable(course_run):
"""
Return true if the course run has a verified seat with an unexpired upgrade deadline, false otherwise.
"""
now = datetime.datetime.now(pytz.UTC)
for seat in course_run.get('seats', []):
if seat.get('type') == 'verified':
upgrade_dead... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.