code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def tf_next_step(self, x, iteration, deltas, improvement, last_improvement, estimated_improvement):
"""
Termination condition: max number of iterations, or no improvement for last step, or
improvement less than acceptable ratio, or estimated value not positive.
Args:
x: Cu... | def function[tf_next_step, parameter[self, x, iteration, deltas, improvement, last_improvement, estimated_improvement]]:
constant[
Termination condition: max number of iterations, or no improvement for last step, or
improvement less than acceptable ratio, or estimated value not positive.
... | keyword[def] identifier[tf_next_step] ( identifier[self] , identifier[x] , identifier[iteration] , identifier[deltas] , identifier[improvement] , identifier[last_improvement] , identifier[estimated_improvement] ):
literal[string]
identifier[next_step] = identifier[super] ( identifier[LineSearch] , ... | def tf_next_step(self, x, iteration, deltas, improvement, last_improvement, estimated_improvement):
"""
Termination condition: max number of iterations, or no improvement for last step, or
improvement less than acceptable ratio, or estimated value not positive.
Args:
x: Curren... |
def create_request_elements(
cls, request_type, credentials, url, method='GET', params=None,
headers=None, body='', secret=None, redirect_uri='', scope='',
csrf='', user_state=''
):
"""
Creates |oauth2| request elements.
"""
headers = headers or {... | def function[create_request_elements, parameter[cls, request_type, credentials, url, method, params, headers, body, secret, redirect_uri, scope, csrf, user_state]]:
constant[
Creates |oauth2| request elements.
]
variable[headers] assign[=] <ast.BoolOp object at 0x7da1b0399b40>
va... | keyword[def] identifier[create_request_elements] (
identifier[cls] , identifier[request_type] , identifier[credentials] , identifier[url] , identifier[method] = literal[string] , identifier[params] = keyword[None] ,
identifier[headers] = keyword[None] , identifier[body] = literal[string] , identifier[secret] = keyw... | def create_request_elements(cls, request_type, credentials, url, method='GET', params=None, headers=None, body='', secret=None, redirect_uri='', scope='', csrf='', user_state=''):
"""
Creates |oauth2| request elements.
"""
headers = headers or {}
params = params or {}
consumer_key = cred... |
def namespace(ns_key):
'''Construct a validation schema for a given namespace.
Parameters
----------
ns_key : str
Namespace key identifier (eg, 'beat' or 'segment_tut')
Returns
-------
schema : dict
JSON schema of `namespace`
'''
if ns_key not in __NAMESPACE__:
... | def function[namespace, parameter[ns_key]]:
constant[Construct a validation schema for a given namespace.
Parameters
----------
ns_key : str
Namespace key identifier (eg, 'beat' or 'segment_tut')
Returns
-------
schema : dict
JSON schema of `namespace`
]
if ... | keyword[def] identifier[namespace] ( identifier[ns_key] ):
literal[string]
keyword[if] identifier[ns_key] keyword[not] keyword[in] identifier[__NAMESPACE__] :
keyword[raise] identifier[NamespaceError] ( literal[string] . identifier[format] ( identifier[ns_key] ))
identifier[sch] = iden... | def namespace(ns_key):
"""Construct a validation schema for a given namespace.
Parameters
----------
ns_key : str
Namespace key identifier (eg, 'beat' or 'segment_tut')
Returns
-------
schema : dict
JSON schema of `namespace`
"""
if ns_key not in __NAMESPACE__:
... |
def GetRemainder(self):
"""Method to get the remainder of the buffered XML. this
method stops the parser, set its state to End Of File and
return the input stream with what is left that the parser
did not use. The implementation is not good, the parser
certainly procgres... | def function[GetRemainder, parameter[self]]:
constant[Method to get the remainder of the buffered XML. this
method stops the parser, set its state to End Of File and
return the input stream with what is left that the parser
did not use. The implementation is not good, the parser
... | keyword[def] identifier[GetRemainder] ( identifier[self] ):
literal[string]
identifier[ret] = identifier[libxml2mod] . identifier[xmlTextReaderGetRemainder] ( identifier[self] . identifier[_o] )
keyword[if] identifier[ret] keyword[is] keyword[None] : keyword[raise] identifier[treeError... | def GetRemainder(self):
"""Method to get the remainder of the buffered XML. this
method stops the parser, set its state to End Of File and
return the input stream with what is left that the parser
did not use. The implementation is not good, the parser
certainly procgressed ... |
def _branch_name(cls, version):
"""Defines a mapping between versions and branches.
In particular, `-dev` suffixed releases always live on master. Any other (modern) release
lives in a branch.
"""
suffix = version.public[len(version.base_version):]
components = version.base_version.split('.') +... | def function[_branch_name, parameter[cls, version]]:
constant[Defines a mapping between versions and branches.
In particular, `-dev` suffixed releases always live on master. Any other (modern) release
lives in a branch.
]
variable[suffix] assign[=] call[name[version].public][<ast.Slice obje... | keyword[def] identifier[_branch_name] ( identifier[cls] , identifier[version] ):
literal[string]
identifier[suffix] = identifier[version] . identifier[public] [ identifier[len] ( identifier[version] . identifier[base_version] ):]
identifier[components] = identifier[version] . identifier[base_version] ... | def _branch_name(cls, version):
"""Defines a mapping between versions and branches.
In particular, `-dev` suffixed releases always live on master. Any other (modern) release
lives in a branch.
"""
suffix = version.public[len(version.base_version):]
components = version.base_version.split('.') +... |
def pad_version(left, right):
"""Returns two sequences of the same length so that they can be compared.
The shorter of the two arguments is lengthened by inserting extra zeros
before non-integer components. The algorithm attempts to align character
components."""
pair = vcmp(left), vcmp(right)
... | def function[pad_version, parameter[left, right]]:
constant[Returns two sequences of the same length so that they can be compared.
The shorter of the two arguments is lengthened by inserting extra zeros
before non-integer components. The algorithm attempts to align character
components.]
va... | keyword[def] identifier[pad_version] ( identifier[left] , identifier[right] ):
literal[string]
identifier[pair] = identifier[vcmp] ( identifier[left] ), identifier[vcmp] ( identifier[right] )
identifier[mn] , identifier[mx] = identifier[min] ( identifier[pair] , identifier[key] = identifier[len] ), i... | def pad_version(left, right):
"""Returns two sequences of the same length so that they can be compared.
The shorter of the two arguments is lengthened by inserting extra zeros
before non-integer components. The algorithm attempts to align character
components."""
pair = (vcmp(left), vcmp(right))
... |
def __get_depth(root):
"""
return 0 if unbalanced else depth + 1
"""
if root is None:
return 0
left = __get_depth(root.left)
right = __get_depth(root.right)
if abs(left-right) > 1 or -1 in [left, right]:
return -1
return 1 + max(left, right) | def function[__get_depth, parameter[root]]:
constant[
return 0 if unbalanced else depth + 1
]
if compare[name[root] is constant[None]] begin[:]
return[constant[0]]
variable[left] assign[=] call[name[__get_depth], parameter[name[root].left]]
variable[right] assign[=] call[... | keyword[def] identifier[__get_depth] ( identifier[root] ):
literal[string]
keyword[if] identifier[root] keyword[is] keyword[None] :
keyword[return] literal[int]
identifier[left] = identifier[__get_depth] ( identifier[root] . identifier[left] )
identifier[right] = identifier[__get_de... | def __get_depth(root):
"""
return 0 if unbalanced else depth + 1
"""
if root is None:
return 0 # depends on [control=['if'], data=[]]
left = __get_depth(root.left)
right = __get_depth(root.right)
if abs(left - right) > 1 or -1 in [left, right]:
return -1 # depends on [contr... |
def cython_enums():
"""generate `enum: ZMQ_CONST` block for constant_enums.pxi"""
lines = []
for name in all_names:
if no_prefix(name):
lines.append('enum: ZMQ_{0} "{0}"'.format(name))
else:
lines.append('enum: ZMQ_{0}'.format(name))
return dict(ZMQ_E... | def function[cython_enums, parameter[]]:
constant[generate `enum: ZMQ_CONST` block for constant_enums.pxi]
variable[lines] assign[=] list[[]]
for taget[name[name]] in starred[name[all_names]] begin[:]
if call[name[no_prefix], parameter[name[name]]] begin[:]
... | keyword[def] identifier[cython_enums] ():
literal[string]
identifier[lines] =[]
keyword[for] identifier[name] keyword[in] identifier[all_names] :
keyword[if] identifier[no_prefix] ( identifier[name] ):
identifier[lines] . identifier[append] ( literal[string] . identifier[form... | def cython_enums():
"""generate `enum: ZMQ_CONST` block for constant_enums.pxi"""
lines = []
for name in all_names:
if no_prefix(name):
lines.append('enum: ZMQ_{0} "{0}"'.format(name)) # depends on [control=['if'], data=[]]
else:
lines.append('enum: ZMQ_{0}'.format(n... |
def initiate(self, request):
"""
Initiates a device management request, such as reboot.
In case of failure it throws APIException
"""
url = MgmtRequests.mgmtRequests
r = self._apiClient.post(url, request)
if r.status_code == 202:
return r.json()
... | def function[initiate, parameter[self, request]]:
constant[
Initiates a device management request, such as reboot.
In case of failure it throws APIException
]
variable[url] assign[=] name[MgmtRequests].mgmtRequests
variable[r] assign[=] call[name[self]._apiClient.post, pa... | keyword[def] identifier[initiate] ( identifier[self] , identifier[request] ):
literal[string]
identifier[url] = identifier[MgmtRequests] . identifier[mgmtRequests]
identifier[r] = identifier[self] . identifier[_apiClient] . identifier[post] ( identifier[url] , identifier[request] )
... | def initiate(self, request):
"""
Initiates a device management request, such as reboot.
In case of failure it throws APIException
"""
url = MgmtRequests.mgmtRequests
r = self._apiClient.post(url, request)
if r.status_code == 202:
return r.json() # depends on [control=['i... |
def update(self, **kwargs):
"""When setting useProxyServer to enable we need to supply
proxyServerPool value as well
"""
if 'useProxyServer' in kwargs and kwargs['useProxyServer'] == 'enabled':
if 'proxyServerPool' not in kwargs:
error = 'Missing proxySer... | def function[update, parameter[self]]:
constant[When setting useProxyServer to enable we need to supply
proxyServerPool value as well
]
if <ast.BoolOp object at 0x7da20e962dd0> begin[:]
if compare[constant[proxyServerPool] <ast.NotIn object at 0x7da2590d7190> name[kw... | keyword[def] identifier[update] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[kwargs] keyword[and] identifier[kwargs] [ literal[string] ]== literal[string] :
keyword[if] literal[string] keyword[not] keyword[in] ... | def update(self, **kwargs):
"""When setting useProxyServer to enable we need to supply
proxyServerPool value as well
"""
if 'useProxyServer' in kwargs and kwargs['useProxyServer'] == 'enabled':
if 'proxyServerPool' not in kwargs:
error = 'Missing proxyServerPool paramete... |
def auto_convert_numeric_string_cell(flagable, cell_str, position, worksheet, flags, units):
'''
Handles the string containing numeric case of cell and attempts
auto-conversion for auto_convert_cell.
'''
def numerify_str(cell_str, flag_level='minor', flag_text=""):
'''
Differentiates... | def function[auto_convert_numeric_string_cell, parameter[flagable, cell_str, position, worksheet, flags, units]]:
constant[
Handles the string containing numeric case of cell and attempts
auto-conversion for auto_convert_cell.
]
def function[numerify_str, parameter[cell_str, flag_level, flag... | keyword[def] identifier[auto_convert_numeric_string_cell] ( identifier[flagable] , identifier[cell_str] , identifier[position] , identifier[worksheet] , identifier[flags] , identifier[units] ):
literal[string]
keyword[def] identifier[numerify_str] ( identifier[cell_str] , identifier[flag_level] = literal[... | def auto_convert_numeric_string_cell(flagable, cell_str, position, worksheet, flags, units):
"""
Handles the string containing numeric case of cell and attempts
auto-conversion for auto_convert_cell.
"""
def numerify_str(cell_str, flag_level='minor', flag_text=''):
"""
Differentiate... |
def data(self):
"""
Return the raw data block which makes up this record as a bytestring.
@rtype str
@return A string that is a copy of the buffer that makes
up this record.
"""
return self._buf[self.offset():self.offset() + self.size()] | def function[data, parameter[self]]:
constant[
Return the raw data block which makes up this record as a bytestring.
@rtype str
@return A string that is a copy of the buffer that makes
up this record.
]
return[call[name[self]._buf][<ast.Slice object at 0x7da1b20e70... | keyword[def] identifier[data] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] . identifier[_buf] [ identifier[self] . identifier[offset] (): identifier[self] . identifier[offset] ()+ identifier[self] . identifier[size] ()] | def data(self):
"""
Return the raw data block which makes up this record as a bytestring.
@rtype str
@return A string that is a copy of the buffer that makes
up this record.
"""
return self._buf[self.offset():self.offset() + self.size()] |
def list_set_indent(lst: list, indent: int=1):
"""recurs into list for indentation"""
for i in lst:
if isinstance(i, indentable):
i.set_indent(indent)
if isinstance(i, list):
list_set_indent(i, indent) | def function[list_set_indent, parameter[lst, indent]]:
constant[recurs into list for indentation]
for taget[name[i]] in starred[name[lst]] begin[:]
if call[name[isinstance], parameter[name[i], name[indentable]]] begin[:]
call[name[i].set_indent, parameter[name[ind... | keyword[def] identifier[list_set_indent] ( identifier[lst] : identifier[list] , identifier[indent] : identifier[int] = literal[int] ):
literal[string]
keyword[for] identifier[i] keyword[in] identifier[lst] :
keyword[if] identifier[isinstance] ( identifier[i] , identifier[indentable] ):
... | def list_set_indent(lst: list, indent: int=1):
"""recurs into list for indentation"""
for i in lst:
if isinstance(i, indentable):
i.set_indent(indent) # depends on [control=['if'], data=[]]
if isinstance(i, list):
list_set_indent(i, indent) # depends on [control=['if'],... |
def _max_of_integrand(t_val, f, g, inverse_time=None, return_log=False):
'''
Evaluates max_tau f(t+tau)*g(tau) or max_tau f(t-tau)g(tau) if inverse time is TRUE
Parameters
-----------
t_val : double
Time point
f : Interpolation object
First multiplier in convolution
g... | def function[_max_of_integrand, parameter[t_val, f, g, inverse_time, return_log]]:
constant[
Evaluates max_tau f(t+tau)*g(tau) or max_tau f(t-tau)g(tau) if inverse time is TRUE
Parameters
-----------
t_val : double
Time point
f : Interpolation object
First multiplier in ... | keyword[def] identifier[_max_of_integrand] ( identifier[t_val] , identifier[f] , identifier[g] , identifier[inverse_time] = keyword[None] , identifier[return_log] = keyword[False] ):
literal[string]
identifier[FG] = identifier[_convolution_integrand] ( identifier[t_val] , identifier[f] , identifier[g... | def _max_of_integrand(t_val, f, g, inverse_time=None, return_log=False):
"""
Evaluates max_tau f(t+tau)*g(tau) or max_tau f(t-tau)g(tau) if inverse time is TRUE
Parameters
-----------
t_val : double
Time point
f : Interpolation object
First multiplier in convolution
g ... |
def get_entropy(hsm, iterations, entropy_ratio):
"""
Read entropy from YubiHSM and feed it to Linux as entropy using ioctl() syscall.
"""
fd = os.open("/dev/random", os.O_WRONLY)
# struct rand_pool_info {
# int entropy_count;
# int buf_size;
# __u32 buf[0];
# };
... | def function[get_entropy, parameter[hsm, iterations, entropy_ratio]]:
constant[
Read entropy from YubiHSM and feed it to Linux as entropy using ioctl() syscall.
]
variable[fd] assign[=] call[name[os].open, parameter[constant[/dev/random], name[os].O_WRONLY]]
variable[fmt] assign[=] binar... | keyword[def] identifier[get_entropy] ( identifier[hsm] , identifier[iterations] , identifier[entropy_ratio] ):
literal[string]
identifier[fd] = identifier[os] . identifier[open] ( literal[string] , identifier[os] . identifier[O_WRONLY] )
identifier[fmt] = literal[string] %( id... | def get_entropy(hsm, iterations, entropy_ratio):
"""
Read entropy from YubiHSM and feed it to Linux as entropy using ioctl() syscall.
"""
fd = os.open('/dev/random', os.O_WRONLY)
# struct rand_pool_info {
# int entropy_count;
# int buf_size;
# __u32 buf[0];
# };
... |
def init_fundamental_types(self):
"""Registers all fundamental typekind handlers"""
for _id in range(2, 25):
setattr(self, TypeKind.from_id(_id).name,
self._handle_fundamental_types) | def function[init_fundamental_types, parameter[self]]:
constant[Registers all fundamental typekind handlers]
for taget[name[_id]] in starred[call[name[range], parameter[constant[2], constant[25]]]] begin[:]
call[name[setattr], parameter[name[self], call[name[TypeKind].from_id, parameter[... | keyword[def] identifier[init_fundamental_types] ( identifier[self] ):
literal[string]
keyword[for] identifier[_id] keyword[in] identifier[range] ( literal[int] , literal[int] ):
identifier[setattr] ( identifier[self] , identifier[TypeKind] . identifier[from_id] ( identifier[_id] ). ... | def init_fundamental_types(self):
"""Registers all fundamental typekind handlers"""
for _id in range(2, 25):
setattr(self, TypeKind.from_id(_id).name, self._handle_fundamental_types) # depends on [control=['for'], data=['_id']] |
def trigger(self, name, *args, **kwargs):
"""
Execute the callbacks for the listeners on the specified event with the
supplied arguments.
All extra arguments are passed through to each callback.
:param name: the name of the event
:type name: string
"""
f... | def function[trigger, parameter[self, name]]:
constant[
Execute the callbacks for the listeners on the specified event with the
supplied arguments.
All extra arguments are passed through to each callback.
:param name: the name of the event
:type name: string
]
... | keyword[def] identifier[trigger] ( identifier[self] , identifier[name] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[for] identifier[ev] keyword[in] identifier[self] . identifier[__listeners] [ identifier[name] ]:
identifier[ev] (* identifier[args] ,** identi... | def trigger(self, name, *args, **kwargs):
"""
Execute the callbacks for the listeners on the specified event with the
supplied arguments.
All extra arguments are passed through to each callback.
:param name: the name of the event
:type name: string
"""
for ev in... |
def activation(self, activation_hash):
"""
Endpoint to expose an activation url, this url
is sent to the user by email, when accessed the user is inserted
and activated
"""
reg = self.appbuilder.sm.find_register_user(activation_hash)
if not reg:
... | def function[activation, parameter[self, activation_hash]]:
constant[
Endpoint to expose an activation url, this url
is sent to the user by email, when accessed the user is inserted
and activated
]
variable[reg] assign[=] call[name[self].appbuilder.sm.find_reg... | keyword[def] identifier[activation] ( identifier[self] , identifier[activation_hash] ):
literal[string]
identifier[reg] = identifier[self] . identifier[appbuilder] . identifier[sm] . identifier[find_register_user] ( identifier[activation_hash] )
keyword[if] keyword[not] identifier[reg] :... | def activation(self, activation_hash):
"""
Endpoint to expose an activation url, this url
is sent to the user by email, when accessed the user is inserted
and activated
"""
reg = self.appbuilder.sm.find_register_user(activation_hash)
if not reg:
log.error(... |
def __liftover_coordinates_genomic_insertions(self, intersecting_region):
"""
Lift a region that overlaps the genomic occurrence of this repeat to the
consensus sequence coordinates using just coordinates (not the full
alignment, even if it is avaialble), when the length of the genomic match
is grea... | def function[__liftover_coordinates_genomic_insertions, parameter[self, intersecting_region]]:
constant[
Lift a region that overlaps the genomic occurrence of this repeat to the
consensus sequence coordinates using just coordinates (not the full
alignment, even if it is avaialble), when the length o... | keyword[def] identifier[__liftover_coordinates_genomic_insertions] ( identifier[self] , identifier[intersecting_region] ):
literal[string]
identifier[consensus_match_length] = identifier[self] . identifier[consensus_end] - identifier[self] . identifier[consensus_start]
identifier[size_dif] = ide... | def __liftover_coordinates_genomic_insertions(self, intersecting_region):
"""
Lift a region that overlaps the genomic occurrence of this repeat to the
consensus sequence coordinates using just coordinates (not the full
alignment, even if it is avaialble), when the length of the genomic match
is grea... |
def is_json(value,
schema = None,
json_serializer = None,
**kwargs):
"""Indicate whether ``value`` is a valid JSON object.
.. note::
``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the
meta-schema using a ``$schema`` property, the ... | def function[is_json, parameter[value, schema, json_serializer]]:
constant[Indicate whether ``value`` is a valid JSON object.
.. note::
``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the
meta-schema using a ``$schema`` property, the schema will be assumed to con... | keyword[def] identifier[is_json] ( identifier[value] ,
identifier[schema] = keyword[None] ,
identifier[json_serializer] = keyword[None] ,
** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[value] = identifier[validators] . identifier[json] ( identifier[value] ,
identifie... | def is_json(value, schema=None, json_serializer=None, **kwargs):
"""Indicate whether ``value`` is a valid JSON object.
.. note::
``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the
meta-schema using a ``$schema`` property, the schema will be assumed to conform to
... |
def get_dimension_by_unit_id(unit_id, do_accept_unit_id_none=False, **kwargs):
"""
Return the physical dimension a given unit id refers to.
if do_accept_unit_id_none is False, it raises an exception if unit_id is not valid or None
if do_accept_unit_id_none is True, and unit_id is None, the f... | def function[get_dimension_by_unit_id, parameter[unit_id, do_accept_unit_id_none]]:
constant[
Return the physical dimension a given unit id refers to.
if do_accept_unit_id_none is False, it raises an exception if unit_id is not valid or None
if do_accept_unit_id_none is True, and unit_id... | keyword[def] identifier[get_dimension_by_unit_id] ( identifier[unit_id] , identifier[do_accept_unit_id_none] = keyword[False] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[do_accept_unit_id_none] == keyword[True] keyword[and] identifier[unit_id] keyword[is] keyword[None] :
... | def get_dimension_by_unit_id(unit_id, do_accept_unit_id_none=False, **kwargs):
"""
Return the physical dimension a given unit id refers to.
if do_accept_unit_id_none is False, it raises an exception if unit_id is not valid or None
if do_accept_unit_id_none is True, and unit_id is None, the f... |
def circ_permutation(items):
"""Calculate the circular permutation for a given list of items."""
permutations = []
for i in range(len(items)):
permutations.append(items[i:] + items[:i])
return permutations | def function[circ_permutation, parameter[items]]:
constant[Calculate the circular permutation for a given list of items.]
variable[permutations] assign[=] list[[]]
for taget[name[i]] in starred[call[name[range], parameter[call[name[len], parameter[name[items]]]]]] begin[:]
call[n... | keyword[def] identifier[circ_permutation] ( identifier[items] ):
literal[string]
identifier[permutations] =[]
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[len] ( identifier[items] )):
identifier[permutations] . identifier[append] ( identifier[items] [ identifier[i]... | def circ_permutation(items):
"""Calculate the circular permutation for a given list of items."""
permutations = []
for i in range(len(items)):
permutations.append(items[i:] + items[:i]) # depends on [control=['for'], data=['i']]
return permutations |
def bi_backtrace(node_a, node_b):
"""
Backtrace from start and end node, returns the path for bi-directional A*
(including both start and end nodes)
"""
path_a = backtrace(node_a)
path_b = backtrace(node_b)
path_b.reverse()
return path_a + path_b | def function[bi_backtrace, parameter[node_a, node_b]]:
constant[
Backtrace from start and end node, returns the path for bi-directional A*
(including both start and end nodes)
]
variable[path_a] assign[=] call[name[backtrace], parameter[name[node_a]]]
variable[path_b] assign[=] call[... | keyword[def] identifier[bi_backtrace] ( identifier[node_a] , identifier[node_b] ):
literal[string]
identifier[path_a] = identifier[backtrace] ( identifier[node_a] )
identifier[path_b] = identifier[backtrace] ( identifier[node_b] )
identifier[path_b] . identifier[reverse] ()
keyword[return] ... | def bi_backtrace(node_a, node_b):
"""
Backtrace from start and end node, returns the path for bi-directional A*
(including both start and end nodes)
"""
path_a = backtrace(node_a)
path_b = backtrace(node_b)
path_b.reverse()
return path_a + path_b |
def absent(name, orgname=None, profile='grafana'):
'''
Ensure the named grafana dashboard is absent.
name
Name of the grafana dashboard.
orgname
Name of the organization in which the dashboard should be present.
profile
Configuration profile used to connect to the Grafana ... | def function[absent, parameter[name, orgname, profile]]:
constant[
Ensure the named grafana dashboard is absent.
name
Name of the grafana dashboard.
orgname
Name of the organization in which the dashboard should be present.
profile
Configuration profile used to connect... | keyword[def] identifier[absent] ( identifier[name] , identifier[orgname] = keyword[None] , identifier[profile] = literal[string] ):
literal[string]
identifier[ret] ={ literal[string] : identifier[name] , literal[string] : keyword[True] , literal[string] : literal[string] , literal[string] :{}}
keywor... | def absent(name, orgname=None, profile='grafana'):
"""
Ensure the named grafana dashboard is absent.
name
Name of the grafana dashboard.
orgname
Name of the organization in which the dashboard should be present.
profile
Configuration profile used to connect to the Grafana ... |
def loose_search(self, asset_manager_id, query='', **kwargs):
"""
Asset search API.
Possible kwargs:
* threshold: int (default = 0)
* page_no: int (default = 1)
* page_size: int (default = 100)
* sort_fields: list (default = [])
* asset_typ... | def function[loose_search, parameter[self, asset_manager_id, query]]:
constant[
Asset search API.
Possible kwargs:
* threshold: int (default = 0)
* page_no: int (default = 1)
* page_size: int (default = 100)
* sort_fields: list (default = [])
... | keyword[def] identifier[loose_search] ( identifier[self] , identifier[asset_manager_id] , identifier[query] = literal[string] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[logger] . identifier[info] ( literal[string] , identifier[asset_manager_id] )
identifier[url... | def loose_search(self, asset_manager_id, query='', **kwargs):
"""
Asset search API.
Possible kwargs:
* threshold: int (default = 0)
* page_no: int (default = 1)
* page_size: int (default = 100)
* sort_fields: list (default = [])
* asset_types: ... |
def main():
"""
NAME
remanence_aniso_magic.py
DESCRIPTION
This program is similar to aarm_magic.py and atrm_magic.py with minor modifications.
Converts magic measurement file with ATRM/AARM data to best-fit tensor (6 elements plus sigma)
following Hext (1963), and calculate... | def function[main, parameter[]]:
constant[
NAME
remanence_aniso_magic.py
DESCRIPTION
This program is similar to aarm_magic.py and atrm_magic.py with minor modifications.
Converts magic measurement file with ATRM/AARM data to best-fit tensor (6 elements plus sigma)
follo... | keyword[def] identifier[main] ():
literal[string]
identifier[meas_file] = literal[string]
identifier[args] = identifier[sys] . identifier[argv]
identifier[dir_path] = literal[string]
keyword[if] literal[string] keyword[in] identifier[args] :
identifier[i... | def main():
"""
NAME
remanence_aniso_magic.py
DESCRIPTION
This program is similar to aarm_magic.py and atrm_magic.py with minor modifications.
Converts magic measurement file with ATRM/AARM data to best-fit tensor (6 elements plus sigma)
following Hext (1963), and calculate... |
def _init_forms(self):
"""
Init forms for Add and Edit
"""
super(BaseCRUDView, self)._init_forms()
conv = GeneralModelConverter(self.datamodel)
if not self.add_form:
self.add_form = conv.create_form(
self.label_columns,
self... | def function[_init_forms, parameter[self]]:
constant[
Init forms for Add and Edit
]
call[call[name[super], parameter[name[BaseCRUDView], name[self]]]._init_forms, parameter[]]
variable[conv] assign[=] call[name[GeneralModelConverter], parameter[name[self].datamodel]]
... | keyword[def] identifier[_init_forms] ( identifier[self] ):
literal[string]
identifier[super] ( identifier[BaseCRUDView] , identifier[self] ). identifier[_init_forms] ()
identifier[conv] = identifier[GeneralModelConverter] ( identifier[self] . identifier[datamodel] )
keyword[if] k... | def _init_forms(self):
"""
Init forms for Add and Edit
"""
super(BaseCRUDView, self)._init_forms()
conv = GeneralModelConverter(self.datamodel)
if not self.add_form:
self.add_form = conv.create_form(self.label_columns, self.add_columns, self.description_columns, self.validato... |
def post(self):
"""Create a new template"""
self.reqparse.add_argument('templateName', type=str, required=True)
self.reqparse.add_argument('template', type=str, required=True)
args = self.reqparse.parse_args()
template = db.Template.find_one(template_name=args['templateName'])
... | def function[post, parameter[self]]:
constant[Create a new template]
call[name[self].reqparse.add_argument, parameter[constant[templateName]]]
call[name[self].reqparse.add_argument, parameter[constant[template]]]
variable[args] assign[=] call[name[self].reqparse.parse_args, parameter[]]
... | keyword[def] identifier[post] ( identifier[self] ):
literal[string]
identifier[self] . identifier[reqparse] . identifier[add_argument] ( literal[string] , identifier[type] = identifier[str] , identifier[required] = keyword[True] )
identifier[self] . identifier[reqparse] . identifier[add_ar... | def post(self):
"""Create a new template"""
self.reqparse.add_argument('templateName', type=str, required=True)
self.reqparse.add_argument('template', type=str, required=True)
args = self.reqparse.parse_args()
template = db.Template.find_one(template_name=args['templateName'])
if template:
... |
def metadata_lint(old, new, locations):
"""Run the linter over the new metadata, comparing to the old."""
# ensure we don't modify the metadata
old = old.copy()
new = new.copy()
# remove version info
old.pop('$version', None)
new.pop('$version', None)
for old_group_name in old:
... | def function[metadata_lint, parameter[old, new, locations]]:
constant[Run the linter over the new metadata, comparing to the old.]
variable[old] assign[=] call[name[old].copy, parameter[]]
variable[new] assign[=] call[name[new].copy, parameter[]]
call[name[old].pop, parameter[constant[$v... | keyword[def] identifier[metadata_lint] ( identifier[old] , identifier[new] , identifier[locations] ):
literal[string]
identifier[old] = identifier[old] . identifier[copy] ()
identifier[new] = identifier[new] . identifier[copy] ()
identifier[old] . identifier[pop] ( literal[string] , key... | def metadata_lint(old, new, locations):
"""Run the linter over the new metadata, comparing to the old."""
# ensure we don't modify the metadata
old = old.copy()
new = new.copy()
# remove version info
old.pop('$version', None)
new.pop('$version', None)
for old_group_name in old:
i... |
def hostloc(self):
"""return host:port"""
hostloc = self.hostname
if self.port:
hostloc = '{hostloc}:{port}'.format(hostloc=hostloc, port=self.port)
return hostloc | def function[hostloc, parameter[self]]:
constant[return host:port]
variable[hostloc] assign[=] name[self].hostname
if name[self].port begin[:]
variable[hostloc] assign[=] call[constant[{hostloc}:{port}].format, parameter[]]
return[name[hostloc]] | keyword[def] identifier[hostloc] ( identifier[self] ):
literal[string]
identifier[hostloc] = identifier[self] . identifier[hostname]
keyword[if] identifier[self] . identifier[port] :
identifier[hostloc] = literal[string] . identifier[format] ( identifier[hostloc] = identifie... | def hostloc(self):
"""return host:port"""
hostloc = self.hostname
if self.port:
hostloc = '{hostloc}:{port}'.format(hostloc=hostloc, port=self.port) # depends on [control=['if'], data=[]]
return hostloc |
def user_identity_delete(self, user_id, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/user_identities#delete-identity"
api_path = "/api/v2/users/{user_id}/identities/{id}.json"
api_path = api_path.format(user_id=user_id, id=id)
return self.call(api_path, method="DELETE... | def function[user_identity_delete, parameter[self, user_id, id]]:
constant[https://developer.zendesk.com/rest_api/docs/core/user_identities#delete-identity]
variable[api_path] assign[=] constant[/api/v2/users/{user_id}/identities/{id}.json]
variable[api_path] assign[=] call[name[api_path].format... | keyword[def] identifier[user_identity_delete] ( identifier[self] , identifier[user_id] , identifier[id] ,** identifier[kwargs] ):
literal[string]
identifier[api_path] = literal[string]
identifier[api_path] = identifier[api_path] . identifier[format] ( identifier[user_id] = identifier[user... | def user_identity_delete(self, user_id, id, **kwargs):
"""https://developer.zendesk.com/rest_api/docs/core/user_identities#delete-identity"""
api_path = '/api/v2/users/{user_id}/identities/{id}.json'
api_path = api_path.format(user_id=user_id, id=id)
return self.call(api_path, method='DELETE', **kwargs) |
def get_(*keyname):
'''
Get metadata
keyname : string
name of key
.. note::
If no keynames are specified, we get all (public) properties
CLI Example:
.. code-block:: bash
salt '*' mdata.get salt:role
salt '*' mdata.get user-script salt:role
'''
mdata... | def function[get_, parameter[]]:
constant[
Get metadata
keyname : string
name of key
.. note::
If no keynames are specified, we get all (public) properties
CLI Example:
.. code-block:: bash
salt '*' mdata.get salt:role
salt '*' mdata.get user-script salt... | keyword[def] identifier[get_] (* identifier[keyname] ):
literal[string]
identifier[mdata] = identifier[_check_mdata_get] ()
identifier[ret] ={}
keyword[if] keyword[not] identifier[keyname] :
identifier[keyname] = identifier[list_] ()
keyword[for] identifier[k] keyword[in] ide... | def get_(*keyname):
"""
Get metadata
keyname : string
name of key
.. note::
If no keynames are specified, we get all (public) properties
CLI Example:
.. code-block:: bash
salt '*' mdata.get salt:role
salt '*' mdata.get user-script salt:role
"""
mdata... |
def out_of_service(self, args):
"""
Set the Out_Of_Service property so the Present_Value of an I/O may be written.
:param args: String with <addr> <type> <inst> <prop> <value> [ <indx> ] [ <priority> ]
"""
if not self._started:
raise ApplicationNotStarted("B... | def function[out_of_service, parameter[self, args]]:
constant[
Set the Out_Of_Service property so the Present_Value of an I/O may be written.
:param args: String with <addr> <type> <inst> <prop> <value> [ <indx> ] [ <priority> ]
]
if <ast.UnaryOp object at 0x7da1b0650dc0> begin... | keyword[def] identifier[out_of_service] ( identifier[self] , identifier[args] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_started] :
keyword[raise] identifier[ApplicationNotStarted] ( literal[string] )
identifier[args] = id... | def out_of_service(self, args):
"""
Set the Out_Of_Service property so the Present_Value of an I/O may be written.
:param args: String with <addr> <type> <inst> <prop> <value> [ <indx> ] [ <priority> ]
"""
if not self._started:
raise ApplicationNotStarted('BACnet stack not runn... |
def translate(conic, vector):
"""
Translates a conic by a vector
"""
# Translation matrix
T = N.identity(len(conic))
T[:-1,-1] = -vector
return conic.transform(T) | def function[translate, parameter[conic, vector]]:
constant[
Translates a conic by a vector
]
variable[T] assign[=] call[name[N].identity, parameter[call[name[len], parameter[name[conic]]]]]
call[name[T]][tuple[[<ast.Slice object at 0x7da1b1973f70>, <ast.UnaryOp object at 0x7da1b... | keyword[def] identifier[translate] ( identifier[conic] , identifier[vector] ):
literal[string]
identifier[T] = identifier[N] . identifier[identity] ( identifier[len] ( identifier[conic] ))
identifier[T] [:- literal[int] ,- literal[int] ]=- identifier[vector]
keyword[retu... | def translate(conic, vector):
"""
Translates a conic by a vector
"""
# Translation matrix
T = N.identity(len(conic))
T[:-1, -1] = -vector
return conic.transform(T) |
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None... | def function[update_floatingip, parameter[floatingip_id, port, profile]]:
constant[
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associat... | keyword[def] identifier[update_floatingip] ( identifier[floatingip_id] , identifier[port] = keyword[None] , identifier[profile] = keyword[None] ):
literal[string]
identifier[conn] = identifier[_auth] ( identifier[profile] )
keyword[return] identifier[conn] . identifier[update_floatingip] ( identifier... | def update_floatingip(floatingip_id, port=None, profile=None):
"""
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None... |
async def trace_back_to_tree(chain):
"""Trace the chain back to the tree.
task.metadata.source: "https://hg.mozilla.org/projects/date//file/a80373508881bfbff67a2a49297c328ff8052572/taskcluster/ci/build"
task.payload.env.GECKO_HEAD_REPOSITORY "https://hg.mozilla.org/projects/date/"
Args:
chain ... | <ast.AsyncFunctionDef object at 0x7da1b0e9c4f0> | keyword[async] keyword[def] identifier[trace_back_to_tree] ( identifier[chain] ):
literal[string]
identifier[errors] =[]
identifier[repos] ={}
identifier[restricted_privs] = keyword[None]
identifier[rules] ={}
keyword[for] identifier[my_key] , identifier[config_key] keyword[in] {
... | async def trace_back_to_tree(chain):
"""Trace the chain back to the tree.
task.metadata.source: "https://hg.mozilla.org/projects/date//file/a80373508881bfbff67a2a49297c328ff8052572/taskcluster/ci/build"
task.payload.env.GECKO_HEAD_REPOSITORY "https://hg.mozilla.org/projects/date/"
Args:
chain ... |
def ghmean(nums):
"""Return geometric-harmonic mean.
Iterates between geometric & harmonic means until they converge to
a single value (rounded to 12 digits).
Cf. https://en.wikipedia.org/wiki/Geometric-harmonic_mean
Parameters
----------
nums : list
A series of numbers
Retur... | def function[ghmean, parameter[nums]]:
constant[Return geometric-harmonic mean.
Iterates between geometric & harmonic means until they converge to
a single value (rounded to 12 digits).
Cf. https://en.wikipedia.org/wiki/Geometric-harmonic_mean
Parameters
----------
nums : list
... | keyword[def] identifier[ghmean] ( identifier[nums] ):
literal[string]
identifier[m_g] = identifier[gmean] ( identifier[nums] )
identifier[m_h] = identifier[hmean] ( identifier[nums] )
keyword[if] identifier[math] . identifier[isnan] ( identifier[m_g] ) keyword[or] identifier[math] . identifier[... | def ghmean(nums):
"""Return geometric-harmonic mean.
Iterates between geometric & harmonic means until they converge to
a single value (rounded to 12 digits).
Cf. https://en.wikipedia.org/wiki/Geometric-harmonic_mean
Parameters
----------
nums : list
A series of numbers
Retur... |
def handle_request(self, environ, start_response):
"""Handle an HTTP request from the client.
This is the entry point of the Engine.IO application, using the same
interface as a WSGI application. For the typical usage, this function
is invoked by the :class:`Middleware` instance, but it... | def function[handle_request, parameter[self, environ, start_response]]:
constant[Handle an HTTP request from the client.
This is the entry point of the Engine.IO application, using the same
interface as a WSGI application. For the typical usage, this function
is invoked by the :class:`M... | keyword[def] identifier[handle_request] ( identifier[self] , identifier[environ] , identifier[start_response] ):
literal[string]
identifier[method] = identifier[environ] [ literal[string] ]
identifier[query] = identifier[urllib] . identifier[parse] . identifier[parse_qs] ( identifier[envir... | def handle_request(self, environ, start_response):
"""Handle an HTTP request from the client.
This is the entry point of the Engine.IO application, using the same
interface as a WSGI application. For the typical usage, this function
is invoked by the :class:`Middleware` instance, but it can... |
def _interp_limit(invalid, fw_limit, bw_limit):
"""
Get indexers of values that won't be filled
because they exceed the limits.
Parameters
----------
invalid : boolean ndarray
fw_limit : int or None
forward limit to index
bw_limit : int or None
backward limit to index
... | def function[_interp_limit, parameter[invalid, fw_limit, bw_limit]]:
constant[
Get indexers of values that won't be filled
because they exceed the limits.
Parameters
----------
invalid : boolean ndarray
fw_limit : int or None
forward limit to index
bw_limit : int or None
... | keyword[def] identifier[_interp_limit] ( identifier[invalid] , identifier[fw_limit] , identifier[bw_limit] ):
literal[string]
identifier[N] = identifier[len] ( identifier[invalid] )
identifier[f_idx] = identifier[set] ()
identifier[b_idx] = identifier[set] ()
keyword[def] id... | def _interp_limit(invalid, fw_limit, bw_limit):
"""
Get indexers of values that won't be filled
because they exceed the limits.
Parameters
----------
invalid : boolean ndarray
fw_limit : int or None
forward limit to index
bw_limit : int or None
backward limit to index
... |
def addError(self, test, err, capt=None):
"""Add error output to Xunit report.
"""
exc_type, exc_val, tb = err
tb = ''.join(traceback.format_exception(
exc_type,
exc_val if isinstance(exc_val, exc_type) else exc_type(exc_val),
tb
))
nam... | def function[addError, parameter[self, test, err, capt]]:
constant[Add error output to Xunit report.
]
<ast.Tuple object at 0x7da18c4cf550> assign[=] name[err]
variable[tb] assign[=] call[constant[].join, parameter[call[name[traceback].format_exception, parameter[name[exc_type], <ast.IfE... | keyword[def] identifier[addError] ( identifier[self] , identifier[test] , identifier[err] , identifier[capt] = keyword[None] ):
literal[string]
identifier[exc_type] , identifier[exc_val] , identifier[tb] = identifier[err]
identifier[tb] = literal[string] . identifier[join] ( identifier[tr... | def addError(self, test, err, capt=None):
"""Add error output to Xunit report.
"""
(exc_type, exc_val, tb) = err
tb = ''.join(traceback.format_exception(exc_type, exc_val if isinstance(exc_val, exc_type) else exc_type(exc_val), tb))
name = id_split(test.id())
group = self.report_data[name[0]... |
def read_dates_by_service_ids(
path: str
) -> Dict[FrozenSet[str], FrozenSet[datetime.date]]:
"""Find dates with identical service"""
feed = load_raw_feed(path)
return _dates_by_service_ids(feed) | def function[read_dates_by_service_ids, parameter[path]]:
constant[Find dates with identical service]
variable[feed] assign[=] call[name[load_raw_feed], parameter[name[path]]]
return[call[name[_dates_by_service_ids], parameter[name[feed]]]] | keyword[def] identifier[read_dates_by_service_ids] (
identifier[path] : identifier[str]
)-> identifier[Dict] [ identifier[FrozenSet] [ identifier[str] ], identifier[FrozenSet] [ identifier[datetime] . identifier[date] ]]:
literal[string]
identifier[feed] = identifier[load_raw_feed] ( identifier[path] )
... | def read_dates_by_service_ids(path: str) -> Dict[FrozenSet[str], FrozenSet[datetime.date]]:
"""Find dates with identical service"""
feed = load_raw_feed(path)
return _dates_by_service_ids(feed) |
def get(name):
"""
Returns a matcher instance by class or alias name.
Arguments:
name (str): matcher class name or alias.
Returns:
matcher: found matcher instance, otherwise ``None``.
"""
for matcher in matchers:
if matcher.__name__ == name or getattr(matcher, 'name', N... | def function[get, parameter[name]]:
constant[
Returns a matcher instance by class or alias name.
Arguments:
name (str): matcher class name or alias.
Returns:
matcher: found matcher instance, otherwise ``None``.
]
for taget[name[matcher]] in starred[name[matchers]] begin... | keyword[def] identifier[get] ( identifier[name] ):
literal[string]
keyword[for] identifier[matcher] keyword[in] identifier[matchers] :
keyword[if] identifier[matcher] . identifier[__name__] == identifier[name] keyword[or] identifier[getattr] ( identifier[matcher] , literal[string] , keyword[... | def get(name):
"""
Returns a matcher instance by class or alias name.
Arguments:
name (str): matcher class name or alias.
Returns:
matcher: found matcher instance, otherwise ``None``.
"""
for matcher in matchers:
if matcher.__name__ == name or getattr(matcher, 'name', N... |
def prepare_sql(sql, add_semicolon=True, invalid_starts=('--', '/*', '*/', ';')):
"""Wrapper method for PrepareSQL class."""
return PrepareSQL(sql, add_semicolon, invalid_starts).prepared | def function[prepare_sql, parameter[sql, add_semicolon, invalid_starts]]:
constant[Wrapper method for PrepareSQL class.]
return[call[name[PrepareSQL], parameter[name[sql], name[add_semicolon], name[invalid_starts]]].prepared] | keyword[def] identifier[prepare_sql] ( identifier[sql] , identifier[add_semicolon] = keyword[True] , identifier[invalid_starts] =( literal[string] , literal[string] , literal[string] , literal[string] )):
literal[string]
keyword[return] identifier[PrepareSQL] ( identifier[sql] , identifier[add_semicolon] ... | def prepare_sql(sql, add_semicolon=True, invalid_starts=('--', '/*', '*/', ';')):
"""Wrapper method for PrepareSQL class."""
return PrepareSQL(sql, add_semicolon, invalid_starts).prepared |
def _Close(self):
"""Closes the file system object.
Raises:
IOError: if the close failed.
"""
self._zip_file.close()
self._zip_file = None
self._file_object.close()
self._file_object = None | def function[_Close, parameter[self]]:
constant[Closes the file system object.
Raises:
IOError: if the close failed.
]
call[name[self]._zip_file.close, parameter[]]
name[self]._zip_file assign[=] constant[None]
call[name[self]._file_object.close, parameter[]]
name[... | keyword[def] identifier[_Close] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_zip_file] . identifier[close] ()
identifier[self] . identifier[_zip_file] = keyword[None]
identifier[self] . identifier[_file_object] . identifier[close] ()
identifier[self] . identifier[_f... | def _Close(self):
"""Closes the file system object.
Raises:
IOError: if the close failed.
"""
self._zip_file.close()
self._zip_file = None
self._file_object.close()
self._file_object = None |
def to_funset(self, index, name="clamped"):
"""
Converts the clamping to a set of `gringo.Fun`_ object instances
Parameters
----------
index : int
An external identifier to associate several clampings together in ASP
name : str
A function name fo... | def function[to_funset, parameter[self, index, name]]:
constant[
Converts the clamping to a set of `gringo.Fun`_ object instances
Parameters
----------
index : int
An external identifier to associate several clampings together in ASP
name : str
A... | keyword[def] identifier[to_funset] ( identifier[self] , identifier[index] , identifier[name] = literal[string] ):
literal[string]
identifier[fs] = identifier[set] ()
keyword[for] identifier[var] , identifier[sign] keyword[in] identifier[self] :
identifier[fs] . identifier[a... | def to_funset(self, index, name='clamped'):
"""
Converts the clamping to a set of `gringo.Fun`_ object instances
Parameters
----------
index : int
An external identifier to associate several clampings together in ASP
name : str
A function name for th... |
def validate_variable_name(self, name):
"""
Validate variable name.
Arguments:
name (string): Property name.
Returns:
bool: ``True`` if variable name is valid.
"""
if not name:
raise SerializerError("Variable name is empty".format(nam... | def function[validate_variable_name, parameter[self, name]]:
constant[
Validate variable name.
Arguments:
name (string): Property name.
Returns:
bool: ``True`` if variable name is valid.
]
if <ast.UnaryOp object at 0x7da204566350> begin[:]
... | keyword[def] identifier[validate_variable_name] ( identifier[self] , identifier[name] ):
literal[string]
keyword[if] keyword[not] identifier[name] :
keyword[raise] identifier[SerializerError] ( literal[string] . identifier[format] ( identifier[name] ))
keyword[if] identif... | def validate_variable_name(self, name):
"""
Validate variable name.
Arguments:
name (string): Property name.
Returns:
bool: ``True`` if variable name is valid.
"""
if not name:
raise SerializerError('Variable name is empty'.format(name)) # depen... |
def compute_bg(self, which_data="phase",
fit_offset="mean", fit_profile="tilt",
border_m=0, border_perc=0, border_px=0,
from_mask=None, ret_mask=False):
"""Compute background correction
Parameters
----------
which_data: str or lis... | def function[compute_bg, parameter[self, which_data, fit_offset, fit_profile, border_m, border_perc, border_px, from_mask, ret_mask]]:
constant[Compute background correction
Parameters
----------
which_data: str or list of str
From which type of data to remove the background... | keyword[def] identifier[compute_bg] ( identifier[self] , identifier[which_data] = literal[string] ,
identifier[fit_offset] = literal[string] , identifier[fit_profile] = literal[string] ,
identifier[border_m] = literal[int] , identifier[border_perc] = literal[int] , identifier[border_px] = literal[int] ,
identifier... | def compute_bg(self, which_data='phase', fit_offset='mean', fit_profile='tilt', border_m=0, border_perc=0, border_px=0, from_mask=None, ret_mask=False):
"""Compute background correction
Parameters
----------
which_data: str or list of str
From which type of data to remove the ba... |
async def states(self, country: str) -> list:
"""Return a list of supported states in a country."""
data = await self._request(
'get', 'states', params={'country': country})
return [d['state'] for d in data['data']] | <ast.AsyncFunctionDef object at 0x7da18dc98d00> | keyword[async] keyword[def] identifier[states] ( identifier[self] , identifier[country] : identifier[str] )-> identifier[list] :
literal[string]
identifier[data] = keyword[await] identifier[self] . identifier[_request] (
literal[string] , literal[string] , identifier[params] ={ literal[s... | async def states(self, country: str) -> list:
"""Return a list of supported states in a country."""
data = await self._request('get', 'states', params={'country': country})
return [d['state'] for d in data['data']] |
def AddKeywordsForName(self, name, keywords):
"""Associates keywords with name.
Records that keywords are associated with name.
Args:
name: A name which should be associated with some keywords.
keywords: A collection of keywords to associate with name.
"""
data_store.DB.IndexAddKeyword... | def function[AddKeywordsForName, parameter[self, name, keywords]]:
constant[Associates keywords with name.
Records that keywords are associated with name.
Args:
name: A name which should be associated with some keywords.
keywords: A collection of keywords to associate with name.
]
... | keyword[def] identifier[AddKeywordsForName] ( identifier[self] , identifier[name] , identifier[keywords] ):
literal[string]
identifier[data_store] . identifier[DB] . identifier[IndexAddKeywordsForName] ( identifier[self] . identifier[urn] , identifier[name] , identifier[keywords] ) | def AddKeywordsForName(self, name, keywords):
"""Associates keywords with name.
Records that keywords are associated with name.
Args:
name: A name which should be associated with some keywords.
keywords: A collection of keywords to associate with name.
"""
data_store.DB.IndexAddKeyword... |
def get_radii(self):
"""
Get the inner and outer radii of the thread.
:return: (<inner radius>, <outer radius>)
:rtype: :class:`tuple`
.. note::
Ideally this method is overridden in inheriting classes to
mathematically determine the radii.
... | def function[get_radii, parameter[self]]:
constant[
Get the inner and outer radii of the thread.
:return: (<inner radius>, <outer radius>)
:rtype: :class:`tuple`
.. note::
Ideally this method is overridden in inheriting classes to
mathematically determi... | keyword[def] identifier[get_radii] ( identifier[self] ):
literal[string]
identifier[bb] = identifier[self] . identifier[profile] . identifier[val] (). identifier[BoundingBox] ()
keyword[return] ( identifier[bb] . identifier[xmin] , identifier[bb] . identifier[xmax] ) | def get_radii(self):
"""
Get the inner and outer radii of the thread.
:return: (<inner radius>, <outer radius>)
:rtype: :class:`tuple`
.. note::
Ideally this method is overridden in inheriting classes to
mathematically determine the radii.
Defa... |
async def _string_data(self, data):
"""
This is a private message handler method.
It is the message handler for String data messages that will be
printed to the console.
:param data: message
:returns: None - message is sent to console
"""
reply = ''
... | <ast.AsyncFunctionDef object at 0x7da207f03e20> | keyword[async] keyword[def] identifier[_string_data] ( identifier[self] , identifier[data] ):
literal[string]
identifier[reply] = literal[string]
identifier[data] = identifier[data] [ literal[int] :- literal[int] ]
keyword[for] identifier[x] keyword[in] identifier[data] :
... | async def _string_data(self, data):
"""
This is a private message handler method.
It is the message handler for String data messages that will be
printed to the console.
:param data: message
:returns: None - message is sent to console
"""
reply = ''
data = d... |
def download(self):
'''
Download all waypoints from the vehicle.
The download is asynchronous. Use :py:func:`wait_ready()` to block your thread until the download is complete.
'''
self.wait_ready()
self._vehicle._ready_attrs.remove('commands')
self._vehicle._wp_lo... | def function[download, parameter[self]]:
constant[
Download all waypoints from the vehicle.
The download is asynchronous. Use :py:func:`wait_ready()` to block your thread until the download is complete.
]
call[name[self].wait_ready, parameter[]]
call[name[self]._vehicle._... | keyword[def] identifier[download] ( identifier[self] ):
literal[string]
identifier[self] . identifier[wait_ready] ()
identifier[self] . identifier[_vehicle] . identifier[_ready_attrs] . identifier[remove] ( literal[string] )
identifier[self] . identifier[_vehicle] . identifier[_wp... | def download(self):
"""
Download all waypoints from the vehicle.
The download is asynchronous. Use :py:func:`wait_ready()` to block your thread until the download is complete.
"""
self.wait_ready()
self._vehicle._ready_attrs.remove('commands')
self._vehicle._wp_loaded = False
... |
def get_page_number(self, index):
"""
Given an index, return page label as specified by
catalog['PageLabels']['Nums']
In a PDF, page labels are stored as a list of pairs, like
[starting_index, label_format, starting_index, label_format ...]
For example:
... | def function[get_page_number, parameter[self, index]]:
constant[
Given an index, return page label as specified by
catalog['PageLabels']['Nums']
In a PDF, page labels are stored as a list of pairs, like
[starting_index, label_format, starting_index, label_format ...]
Fo... | keyword[def] identifier[get_page_number] ( identifier[self] , identifier[index] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[self] , literal[string] ):
keyword[try] :
identifier[page_ranges] = identifier[resolve1] ( ide... | def get_page_number(self, index):
"""
Given an index, return page label as specified by
catalog['PageLabels']['Nums']
In a PDF, page labels are stored as a list of pairs, like
[starting_index, label_format, starting_index, label_format ...]
For example:
[0, {'S': 'D... |
def go_online(self, comment=None):
"""
Executes a Go-Online operation on the specified node
typically done when the node has already been forced offline
via :func:`go_offline`
:param str comment: (optional) comment to audit
:raises NodeCommandFailed: online not available... | def function[go_online, parameter[self, comment]]:
constant[
Executes a Go-Online operation on the specified node
typically done when the node has already been forced offline
via :func:`go_offline`
:param str comment: (optional) comment to audit
:raises NodeCommandFailed... | keyword[def] identifier[go_online] ( identifier[self] , identifier[comment] = keyword[None] ):
literal[string]
identifier[self] . identifier[make_request] (
identifier[NodeCommandFailed] ,
identifier[method] = literal[string] ,
identifier[resource] = literal[string] ,
... | def go_online(self, comment=None):
"""
Executes a Go-Online operation on the specified node
typically done when the node has already been forced offline
via :func:`go_offline`
:param str comment: (optional) comment to audit
:raises NodeCommandFailed: online not available
... |
def make(self):
""" Evaluate the command, and write it to a file. """
eval = self.command.eval()
with open(self.filename, 'w') as f:
f.write(eval) | def function[make, parameter[self]]:
constant[ Evaluate the command, and write it to a file. ]
variable[eval] assign[=] call[name[self].command.eval, parameter[]]
with call[name[open], parameter[name[self].filename, constant[w]]] begin[:]
call[name[f].write, parameter[name[eval]]... | keyword[def] identifier[make] ( identifier[self] ):
literal[string]
identifier[eval] = identifier[self] . identifier[command] . identifier[eval] ()
keyword[with] identifier[open] ( identifier[self] . identifier[filename] , literal[string] ) keyword[as] identifier[f] :
identi... | def make(self):
""" Evaluate the command, and write it to a file. """
eval = self.command.eval()
with open(self.filename, 'w') as f:
f.write(eval) # depends on [control=['with'], data=['f']] |
def event(self, name, **kwargs):
"""Add Event data to Batch object.
Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
event_date (str, kwargs): The event datetime expression for this Group.
... | def function[event, parameter[self, name]]:
constant[Add Event data to Batch object.
Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
event_date (str, kwargs): The event datetime expression for this Gr... | keyword[def] identifier[event] ( identifier[self] , identifier[name] ,** identifier[kwargs] ):
literal[string]
identifier[group_obj] = identifier[Event] ( identifier[name] ,** identifier[kwargs] )
keyword[return] identifier[self] . identifier[_group] ( identifier[group_obj] ) | def event(self, name, **kwargs):
"""Add Event data to Batch object.
Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
event_date (str, kwargs): The event datetime expression for this Group.
stat... |
def save(self, force_insert=False, force_update=False, commit=True):
""" Se sobreescribe el método save para crear o modificar al User en caso
que el parámetro commit sea True.
"""
usuario = super().save(commit=False)
if commit:
user = None
if self.instance.pk is not None:
user... | def function[save, parameter[self, force_insert, force_update, commit]]:
constant[ Se sobreescribe el método save para crear o modificar al User en caso
que el parámetro commit sea True.
]
variable[usuario] assign[=] call[call[name[super], parameter[]].save, parameter[]]
if name[commit]... | keyword[def] identifier[save] ( identifier[self] , identifier[force_insert] = keyword[False] , identifier[force_update] = keyword[False] , identifier[commit] = keyword[True] ):
literal[string]
identifier[usuario] = identifier[super] (). identifier[save] ( identifier[commit] = keyword[False] )
keyword... | def save(self, force_insert=False, force_update=False, commit=True):
""" Se sobreescribe el método save para crear o modificar al User en caso
que el parámetro commit sea True.
"""
usuario = super().save(commit=False)
if commit:
user = None
if self.instance.pk is not None:
... |
def node_equal(node1, node2):
'''node_equal
High-level api: Evaluate whether two nodes are equal.
Parameters
----------
node1 : `Element`
A node in a model tree.
node2 : `Element`
A node in another model tree.
Returns
-------
... | def function[node_equal, parameter[node1, node2]]:
constant[node_equal
High-level api: Evaluate whether two nodes are equal.
Parameters
----------
node1 : `Element`
A node in a model tree.
node2 : `Element`
A node in another model tree.
... | keyword[def] identifier[node_equal] ( identifier[node1] , identifier[node2] ):
literal[string]
keyword[if] identifier[ModelDiff] . identifier[node_less] ( identifier[node1] , identifier[node2] ) keyword[and] identifier[ModelDiff] . identifier[node_less] ( identifier[node2] , identifier[node1] ):... | def node_equal(node1, node2):
"""node_equal
High-level api: Evaluate whether two nodes are equal.
Parameters
----------
node1 : `Element`
A node in a model tree.
node2 : `Element`
A node in another model tree.
Returns
-------
... |
def stop(self):
"""Send a TX_DELETE message to cancel this task.
This will delete the entry for the transmission of the CAN-message
with the specified can_id CAN identifier. The message length for the command
TX_DELETE is {[bcm_msg_head]} (only the header).
"""
log.debug... | def function[stop, parameter[self]]:
constant[Send a TX_DELETE message to cancel this task.
This will delete the entry for the transmission of the CAN-message
with the specified can_id CAN identifier. The message length for the command
TX_DELETE is {[bcm_msg_head]} (only the header).
... | keyword[def] identifier[stop] ( identifier[self] ):
literal[string]
identifier[log] . identifier[debug] ( literal[string] )
identifier[stopframe] = identifier[build_bcm_tx_delete_header] ( identifier[self] . identifier[can_id_with_flags] , identifier[self] . identifier[flags] )
i... | def stop(self):
"""Send a TX_DELETE message to cancel this task.
This will delete the entry for the transmission of the CAN-message
with the specified can_id CAN identifier. The message length for the command
TX_DELETE is {[bcm_msg_head]} (only the header).
"""
log.debug('Stoppi... |
def GET_AUTH(self, courseid, scoreboardid): # pylint: disable=arguments-differ
""" GET request """
course = self.course_factory.get_course(courseid)
scoreboards = course.get_descriptor().get('scoreboard', [])
try:
scoreboardid = int(scoreboardid)
scoreboard_name... | def function[GET_AUTH, parameter[self, courseid, scoreboardid]]:
constant[ GET request ]
variable[course] assign[=] call[name[self].course_factory.get_course, parameter[name[courseid]]]
variable[scoreboards] assign[=] call[call[name[course].get_descriptor, parameter[]].get, parameter[constant[sc... | keyword[def] identifier[GET_AUTH] ( identifier[self] , identifier[courseid] , identifier[scoreboardid] ):
literal[string]
identifier[course] = identifier[self] . identifier[course_factory] . identifier[get_course] ( identifier[courseid] )
identifier[scoreboards] = identifier[course] . iden... | def GET_AUTH(self, courseid, scoreboardid): # pylint: disable=arguments-differ
' GET request '
course = self.course_factory.get_course(courseid)
scoreboards = course.get_descriptor().get('scoreboard', [])
try:
scoreboardid = int(scoreboardid)
scoreboard_name = scoreboards[scoreboardid][... |
def add_traces(self):
"""Add traces based on self.data."""
y_distance = self.parent.value('y_distance')
self.chan = []
self.chan_pos = []
self.chan_scale = []
row = 0
for one_grp in self.parent.channels.groups:
for one_chan in one_grp['chan_to_plot']:... | def function[add_traces, parameter[self]]:
constant[Add traces based on self.data.]
variable[y_distance] assign[=] call[name[self].parent.value, parameter[constant[y_distance]]]
name[self].chan assign[=] list[[]]
name[self].chan_pos assign[=] list[[]]
name[self].chan_scale assign... | keyword[def] identifier[add_traces] ( identifier[self] ):
literal[string]
identifier[y_distance] = identifier[self] . identifier[parent] . identifier[value] ( literal[string] )
identifier[self] . identifier[chan] =[]
identifier[self] . identifier[chan_pos] =[]
identifier[... | def add_traces(self):
"""Add traces based on self.data."""
y_distance = self.parent.value('y_distance')
self.chan = []
self.chan_pos = []
self.chan_scale = []
row = 0
for one_grp in self.parent.channels.groups:
for one_chan in one_grp['chan_to_plot']:
# channel name
... |
def SETNZ(cpu, dest):
"""
Sets byte if not zero.
:param cpu: current CPU.
:param dest: destination operand.
"""
dest.write(Operators.ITEBV(dest.size, cpu.ZF == False, 1, 0)) | def function[SETNZ, parameter[cpu, dest]]:
constant[
Sets byte if not zero.
:param cpu: current CPU.
:param dest: destination operand.
]
call[name[dest].write, parameter[call[name[Operators].ITEBV, parameter[name[dest].size, compare[name[cpu].ZF equal[==] constant[False]... | keyword[def] identifier[SETNZ] ( identifier[cpu] , identifier[dest] ):
literal[string]
identifier[dest] . identifier[write] ( identifier[Operators] . identifier[ITEBV] ( identifier[dest] . identifier[size] , identifier[cpu] . identifier[ZF] == keyword[False] , literal[int] , literal[int] )) | def SETNZ(cpu, dest):
"""
Sets byte if not zero.
:param cpu: current CPU.
:param dest: destination operand.
"""
dest.write(Operators.ITEBV(dest.size, cpu.ZF == False, 1, 0)) |
def changelog():
# type: () -> str
""" Print change log since last release. """
# Skip 'v' prefix
versions = [x for x in git.tags() if versioning.is_valid(x[1:])]
cmd = 'git log --format=%H'
if versions:
cmd += ' {}..HEAD'.format(versions[-1])
hashes = shell.run(cmd, capture=True).... | def function[changelog, parameter[]]:
constant[ Print change log since last release. ]
variable[versions] assign[=] <ast.ListComp object at 0x7da1b1052a70>
variable[cmd] assign[=] constant[git log --format=%H]
if name[versions] begin[:]
<ast.AugAssign object at 0x7da1b1052200>
... | keyword[def] identifier[changelog] ():
literal[string]
identifier[versions] =[ identifier[x] keyword[for] identifier[x] keyword[in] identifier[git] . identifier[tags] () keyword[if] identifier[versioning] . identifier[is_valid] ( identifier[x] [ literal[int] :])]
identifier[cmd] = literal[... | def changelog():
# type: () -> str
' Print change log since last release. '
# Skip 'v' prefix
versions = [x for x in git.tags() if versioning.is_valid(x[1:])]
cmd = 'git log --format=%H'
if versions:
cmd += ' {}..HEAD'.format(versions[-1]) # depends on [control=['if'], data=[]]
hash... |
def extract_names(sender):
"""Tries to extract sender's names from `From:` header.
It could extract not only the actual names but e.g.
the name of the company, parts of email, etc.
>>> extract_names('Sergey N. Obukhov <serobnic@mail.ru>')
['Sergey', 'Obukhov', 'serobnic']
>>> extract_names(''... | def function[extract_names, parameter[sender]]:
constant[Tries to extract sender's names from `From:` header.
It could extract not only the actual names but e.g.
the name of the company, parts of email, etc.
>>> extract_names('Sergey N. Obukhov <serobnic@mail.ru>')
['Sergey', 'Obukhov', 'sero... | keyword[def] identifier[extract_names] ( identifier[sender] ):
literal[string]
identifier[sender] = identifier[to_unicode] ( identifier[sender] , identifier[precise] = keyword[True] )
identifier[sender] = literal[string] . identifier[join] ([ identifier[char] keyword[if] identifier[char] . iden... | def extract_names(sender):
"""Tries to extract sender's names from `From:` header.
It could extract not only the actual names but e.g.
the name of the company, parts of email, etc.
>>> extract_names('Sergey N. Obukhov <serobnic@mail.ru>')
['Sergey', 'Obukhov', 'serobnic']
>>> extract_names(''... |
def process_selectors(self, index=0, flags=0):
"""
Process selectors.
We do our own selectors as BeautifulSoup4 has some annoying quirks,
and we don't really need to do nth selectors or siblings or
descendants etc.
"""
return self.parse_selectors(self.selector_i... | def function[process_selectors, parameter[self, index, flags]]:
constant[
Process selectors.
We do our own selectors as BeautifulSoup4 has some annoying quirks,
and we don't really need to do nth selectors or siblings or
descendants etc.
]
return[call[name[self].pars... | keyword[def] identifier[process_selectors] ( identifier[self] , identifier[index] = literal[int] , identifier[flags] = literal[int] ):
literal[string]
keyword[return] identifier[self] . identifier[parse_selectors] ( identifier[self] . identifier[selector_iter] ( identifier[self] . identifier[patt... | def process_selectors(self, index=0, flags=0):
"""
Process selectors.
We do our own selectors as BeautifulSoup4 has some annoying quirks,
and we don't really need to do nth selectors or siblings or
descendants etc.
"""
return self.parse_selectors(self.selector_iter(self.... |
def read_dbf(dbf_path, index = None, cols = False, incl_index = False):
"""
Read a dbf file as a pandas.DataFrame, optionally selecting the index
variable and which columns are to be loaded.
__author__ = "Dani Arribas-Bel <darribas@asu.edu> "
...
Arguments
---------
dbf_path : str
... | def function[read_dbf, parameter[dbf_path, index, cols, incl_index]]:
constant[
Read a dbf file as a pandas.DataFrame, optionally selecting the index
variable and which columns are to be loaded.
__author__ = "Dani Arribas-Bel <darribas@asu.edu> "
...
Arguments
---------
dbf_path ... | keyword[def] identifier[read_dbf] ( identifier[dbf_path] , identifier[index] = keyword[None] , identifier[cols] = keyword[False] , identifier[incl_index] = keyword[False] ):
literal[string]
identifier[db] = identifier[ps] . identifier[open] ( identifier[dbf_path] )
keyword[if] identifier[cols] :
... | def read_dbf(dbf_path, index=None, cols=False, incl_index=False):
"""
Read a dbf file as a pandas.DataFrame, optionally selecting the index
variable and which columns are to be loaded.
__author__ = "Dani Arribas-Bel <darribas@asu.edu> "
...
Arguments
---------
dbf_path : str
... |
def is_zip_file(models):
r'''
Ensure that a path is a zip file by:
- checking length is 1
- checking extension is '.zip'
'''
ext = os.path.splitext(models[0])[1]
return (len(models) == 1) and (ext == '.zip') | def function[is_zip_file, parameter[models]]:
constant[
Ensure that a path is a zip file by:
- checking length is 1
- checking extension is '.zip'
]
variable[ext] assign[=] call[call[name[os].path.splitext, parameter[call[name[models]][constant[0]]]]][constant[1]]
return[<ast.BoolO... | keyword[def] identifier[is_zip_file] ( identifier[models] ):
literal[string]
identifier[ext] = identifier[os] . identifier[path] . identifier[splitext] ( identifier[models] [ literal[int] ])[ literal[int] ]
keyword[return] ( identifier[len] ( identifier[models] )== literal[int] ) keyword[and] ( identi... | def is_zip_file(models):
"""
Ensure that a path is a zip file by:
- checking length is 1
- checking extension is '.zip'
"""
ext = os.path.splitext(models[0])[1]
return len(models) == 1 and ext == '.zip' |
def trapz_loglog(y, x, axis=-1, intervals=False):
"""
Integrate along the given axis using the composite trapezoidal rule in
loglog space.
Integrate `y` (`x`) along given axis in loglog space.
Parameters
----------
y : array_like
Input array to integrate.
x : array_like, option... | def function[trapz_loglog, parameter[y, x, axis, intervals]]:
constant[
Integrate along the given axis using the composite trapezoidal rule in
loglog space.
Integrate `y` (`x`) along given axis in loglog space.
Parameters
----------
y : array_like
Input array to integrate.
... | keyword[def] identifier[trapz_loglog] ( identifier[y] , identifier[x] , identifier[axis] =- literal[int] , identifier[intervals] = keyword[False] ):
literal[string]
keyword[try] :
identifier[y_unit] = identifier[y] . identifier[unit]
identifier[y] = identifier[y] . identifier[value]
... | def trapz_loglog(y, x, axis=-1, intervals=False):
"""
Integrate along the given axis using the composite trapezoidal rule in
loglog space.
Integrate `y` (`x`) along given axis in loglog space.
Parameters
----------
y : array_like
Input array to integrate.
x : array_like, option... |
def get_status(self, channel=Channel.CHANNEL_CH0):
"""
Returns the error status of a specific CAN channel.
:param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:return: Tuple with CAN and USB status (see structure :class:`Status`).
... | def function[get_status, parameter[self, channel]]:
constant[
Returns the error status of a specific CAN channel.
:param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:return: Tuple with CAN and USB status (see structure :class:`Statu... | keyword[def] identifier[get_status] ( identifier[self] , identifier[channel] = identifier[Channel] . identifier[CHANNEL_CH0] ):
literal[string]
identifier[status] = identifier[Status] ()
identifier[UcanGetStatusEx] ( identifier[self] . identifier[_handle] , identifier[channel] , identifier... | def get_status(self, channel=Channel.CHANNEL_CH0):
"""
Returns the error status of a specific CAN channel.
:param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:return: Tuple with CAN and USB status (see structure :class:`Status`).
... |
def check_sim_out(self):
'''check if we should send new servos to flightgear'''
now = time.time()
if now - self.last_sim_send_time < 0.02 or self.rc_channels_scaled is None:
return
self.last_sim_send_time = now
servos = []
for ch in range(1,9):
se... | def function[check_sim_out, parameter[self]]:
constant[check if we should send new servos to flightgear]
variable[now] assign[=] call[name[time].time, parameter[]]
if <ast.BoolOp object at 0x7da1b16d31c0> begin[:]
return[None]
name[self].last_sim_send_time assign[=] name[now]
... | keyword[def] identifier[check_sim_out] ( identifier[self] ):
literal[string]
identifier[now] = identifier[time] . identifier[time] ()
keyword[if] identifier[now] - identifier[self] . identifier[last_sim_send_time] < literal[int] keyword[or] identifier[self] . identifier[rc_channels_scal... | def check_sim_out(self):
"""check if we should send new servos to flightgear"""
now = time.time()
if now - self.last_sim_send_time < 0.02 or self.rc_channels_scaled is None:
return # depends on [control=['if'], data=[]]
self.last_sim_send_time = now
servos = []
for ch in range(1, 9):
... |
def _get_device(self):
"""
Get the device
"""
try:
device = {
"name": self._dev.name,
"isReachable": self._dev.isReachable,
"isTrusted": self._get_isTrusted(),
}
except Exception:
return None
... | def function[_get_device, parameter[self]]:
constant[
Get the device
]
<ast.Try object at 0x7da18bc72290>
return[name[device]] | keyword[def] identifier[_get_device] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[device] ={
literal[string] : identifier[self] . identifier[_dev] . identifier[name] ,
literal[string] : identifier[self] . identifier[_dev] . identifier[isReac... | def _get_device(self):
"""
Get the device
"""
try:
device = {'name': self._dev.name, 'isReachable': self._dev.isReachable, 'isTrusted': self._get_isTrusted()} # depends on [control=['try'], data=[]]
except Exception:
return None # depends on [control=['except'], data=[]]
... |
def notify(cls, user_or_email_, object_id=None, **filters):
"""Start notifying the given user or email address when this event
occurs and meets the criteria given in ``filters``.
Return the created (or the existing matching) Watch so you can call
:meth:`~tidings.models.Watch.activate()`... | def function[notify, parameter[cls, user_or_email_, object_id]]:
constant[Start notifying the given user or email address when this event
occurs and meets the criteria given in ``filters``.
Return the created (or the existing matching) Watch so you can call
:meth:`~tidings.models.Watch.... | keyword[def] identifier[notify] ( identifier[cls] , identifier[user_or_email_] , identifier[object_id] = keyword[None] ,** identifier[filters] ):
literal[string]
keyword[try] :
identifier[watch] = identifier[cls] . identifier[_watches_belonging_to_us... | def notify(cls, user_or_email_, object_id=None, **filters):
"""Start notifying the given user or email address when this event
occurs and meets the criteria given in ``filters``.
Return the created (or the existing matching) Watch so you can call
:meth:`~tidings.models.Watch.activate()` on ... |
def set_cached_value(self, *args, **kwargs):
"""
Sets the cached value
"""
key = self.get_cache_key(*args, **kwargs)
logger.debug(key)
return namedtuple('Settable', ['to'])(lambda value: self.cache.set(key, value)) | def function[set_cached_value, parameter[self]]:
constant[
Sets the cached value
]
variable[key] assign[=] call[name[self].get_cache_key, parameter[<ast.Starred object at 0x7da20c9905e0>]]
call[name[logger].debug, parameter[name[key]]]
return[call[call[name[namedtuple], param... | keyword[def] identifier[set_cached_value] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[key] = identifier[self] . identifier[get_cache_key] (* identifier[args] ,** identifier[kwargs] )
identifier[logger] . identifier[debug] ( identifier[key] )
... | def set_cached_value(self, *args, **kwargs):
"""
Sets the cached value
"""
key = self.get_cache_key(*args, **kwargs)
logger.debug(key)
return namedtuple('Settable', ['to'])(lambda value: self.cache.set(key, value)) |
def _set_apply_exp_traffic_class_map_name(self, v, load=False):
"""
Setter method for apply_exp_traffic_class_map_name, mapped from YANG variable /qos_mpls/map_apply/apply_exp_traffic_class_map_name (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_apply_exp_tr... | def function[_set_apply_exp_traffic_class_map_name, parameter[self, v, load]]:
constant[
Setter method for apply_exp_traffic_class_map_name, mapped from YANG variable /qos_mpls/map_apply/apply_exp_traffic_class_map_name (container)
If this variable is read-only (config: false) in the
source YANG fil... | keyword[def] identifier[_set_apply_exp_traffic_class_map_name] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
key... | def _set_apply_exp_traffic_class_map_name(self, v, load=False):
"""
Setter method for apply_exp_traffic_class_map_name, mapped from YANG variable /qos_mpls/map_apply/apply_exp_traffic_class_map_name (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_apply_exp_tr... |
def validate(self):
"""Validate the resource"""
if not self._resource.get('permissions'):
self.permissions = self.default_permissions
try:
# update _resource so have default values from the schema
self._resource = self.schema(self._resource)
except Mu... | def function[validate, parameter[self]]:
constant[Validate the resource]
if <ast.UnaryOp object at 0x7da1b1451660> begin[:]
name[self].permissions assign[=] name[self].default_permissions
<ast.Try object at 0x7da1b1451900>
<ast.Yield object at 0x7da1b1452680>
<ast.Yie... | keyword[def] identifier[validate] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_resource] . identifier[get] ( literal[string] ):
identifier[self] . identifier[permissions] = identifier[self] . identifier[default_permissions]
... | def validate(self):
"""Validate the resource"""
if not self._resource.get('permissions'):
self.permissions = self.default_permissions # depends on [control=['if'], data=[]]
try:
# update _resource so have default values from the schema
self._resource = self.schema(self._resource) #... |
def symmetry(self):
"""
Check whether a mesh has rotational symmetry.
Returns
-----------
symmetry: None No rotational symmetry
'radial' Symmetric around an axis
'spherical' Symmetric around a point
"""
symmetry, a... | def function[symmetry, parameter[self]]:
constant[
Check whether a mesh has rotational symmetry.
Returns
-----------
symmetry: None No rotational symmetry
'radial' Symmetric around an axis
'spherical' Symmetric around a point
... | keyword[def] identifier[symmetry] ( identifier[self] ):
literal[string]
identifier[symmetry] , identifier[axis] , identifier[section] = identifier[inertia] . identifier[radial_symmetry] ( identifier[self] )
identifier[self] . identifier[_cache] [ literal[string] ]= identifier[axis]
... | def symmetry(self):
"""
Check whether a mesh has rotational symmetry.
Returns
-----------
symmetry: None No rotational symmetry
'radial' Symmetric around an axis
'spherical' Symmetric around a point
"""
(symmetry, axis, se... |
def fit_size_distribution_component_models(self, model_names, model_objs, input_columns, output_columns):
"""
This calculates 2 principal components for the hail size distribution between the shape and scale parameters.
Separate machine learning models are fit to predict each component.
... | def function[fit_size_distribution_component_models, parameter[self, model_names, model_objs, input_columns, output_columns]]:
constant[
This calculates 2 principal components for the hail size distribution between the shape and scale parameters.
Separate machine learning models are fit to predi... | keyword[def] identifier[fit_size_distribution_component_models] ( identifier[self] , identifier[model_names] , identifier[model_objs] , identifier[input_columns] , identifier[output_columns] ):
literal[string]
identifier[groups] = identifier[np] . identifier[unique] ( identifier[self] . identifier[... | def fit_size_distribution_component_models(self, model_names, model_objs, input_columns, output_columns):
"""
This calculates 2 principal components for the hail size distribution between the shape and scale parameters.
Separate machine learning models are fit to predict each component.
Arg... |
def data_url(content, mimetype=None):
"""
Returns content encoded as base64 Data URI.
:param content: bytes or str or Path
:param mimetype: mimetype for
:return: str object (consisting only of ASCII, though)
.. seealso:: https://en.wikipedia.org/wiki/Data_URI_scheme
"""
if isinstance(c... | def function[data_url, parameter[content, mimetype]]:
constant[
Returns content encoded as base64 Data URI.
:param content: bytes or str or Path
:param mimetype: mimetype for
:return: str object (consisting only of ASCII, though)
.. seealso:: https://en.wikipedia.org/wiki/Data_URI_scheme
... | keyword[def] identifier[data_url] ( identifier[content] , identifier[mimetype] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[content] , identifier[pathlib] . identifier[Path] ):
keyword[if] keyword[not] identifier[mimetype] :
identifier[mimetype... | def data_url(content, mimetype=None):
"""
Returns content encoded as base64 Data URI.
:param content: bytes or str or Path
:param mimetype: mimetype for
:return: str object (consisting only of ASCII, though)
.. seealso:: https://en.wikipedia.org/wiki/Data_URI_scheme
"""
if isinstance(c... |
def methods(self, *args, **kwds):
"""
Request info of callable remote methods.
Arguments for :meth:`call` except for `name` can be applied to
this function too.
"""
self.callmanager.methods(self, *args, **kwds) | def function[methods, parameter[self]]:
constant[
Request info of callable remote methods.
Arguments for :meth:`call` except for `name` can be applied to
this function too.
]
call[name[self].callmanager.methods, parameter[name[self], <ast.Starred object at 0x7da2044c2a4... | keyword[def] identifier[methods] ( identifier[self] ,* identifier[args] ,** identifier[kwds] ):
literal[string]
identifier[self] . identifier[callmanager] . identifier[methods] ( identifier[self] ,* identifier[args] ,** identifier[kwds] ) | def methods(self, *args, **kwds):
"""
Request info of callable remote methods.
Arguments for :meth:`call` except for `name` can be applied to
this function too.
"""
self.callmanager.methods(self, *args, **kwds) |
def write(self, filename):
"""read a sparse matrix, loading row and column name files"""
if file_exists(filename):
return filename
out_files = [filename, filename + ".rownames", filename + ".colnames"]
with file_transaction(out_files) as tx_out_files:
with open(tx... | def function[write, parameter[self, filename]]:
constant[read a sparse matrix, loading row and column name files]
if call[name[file_exists], parameter[name[filename]]] begin[:]
return[name[filename]]
variable[out_files] assign[=] list[[<ast.Name object at 0x7da1b1896a10>, <ast.BinOp obje... | keyword[def] identifier[write] ( identifier[self] , identifier[filename] ):
literal[string]
keyword[if] identifier[file_exists] ( identifier[filename] ):
keyword[return] identifier[filename]
identifier[out_files] =[ identifier[filename] , identifier[filename] + literal[stri... | def write(self, filename):
"""read a sparse matrix, loading row and column name files"""
if file_exists(filename):
return filename # depends on [control=['if'], data=[]]
out_files = [filename, filename + '.rownames', filename + '.colnames']
with file_transaction(out_files) as tx_out_files:
... |
def ls(self, glob_str):
"""
Return just the filenames that match `glob_str` inside the store directory.
:param str glob_str: A glob string, i.e. 'state_*'
:return: list of matched keys
"""
path = os.path.join(self.uri, glob_str)
return [os.path.split(s)[1] for s ... | def function[ls, parameter[self, glob_str]]:
constant[
Return just the filenames that match `glob_str` inside the store directory.
:param str glob_str: A glob string, i.e. 'state_*'
:return: list of matched keys
]
variable[path] assign[=] call[name[os].path.join, paramet... | keyword[def] identifier[ls] ( identifier[self] , identifier[glob_str] ):
literal[string]
identifier[path] = identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[uri] , identifier[glob_str] )
keyword[return] [ identifier[os] . identifier[path] . identifier[sp... | def ls(self, glob_str):
"""
Return just the filenames that match `glob_str` inside the store directory.
:param str glob_str: A glob string, i.e. 'state_*'
:return: list of matched keys
"""
path = os.path.join(self.uri, glob_str)
return [os.path.split(s)[1] for s in glob.glob... |
def patch_namespaced_persistent_volume_claim(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_persistent_volume_claim # noqa: E501
partially update the specified PersistentVolumeClaim # noqa: E501
This method makes a synchronous HTTP request by default. To make an
... | def function[patch_namespaced_persistent_volume_claim, parameter[self, name, namespace, body]]:
constant[patch_namespaced_persistent_volume_claim # noqa: E501
partially update the specified PersistentVolumeClaim # noqa: E501
This method makes a synchronous HTTP request by default. To make an
... | keyword[def] identifier[patch_namespaced_persistent_volume_claim] ( identifier[self] , identifier[name] , identifier[namespace] , identifier[body] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[g... | def patch_namespaced_persistent_volume_claim(self, name, namespace, body, **kwargs): # noqa: E501
"patch_namespaced_persistent_volume_claim # noqa: E501\n\n partially update the specified PersistentVolumeClaim # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n ... |
def load_skel(self, file_name):
"""
Loads an ASF file into a skeleton structure.
:param file_name: The file name to load in.
"""
fid = open(file_name, 'r')
self.read_skel(fid)
fid.close()
self.name = file_name | def function[load_skel, parameter[self, file_name]]:
constant[
Loads an ASF file into a skeleton structure.
:param file_name: The file name to load in.
]
variable[fid] assign[=] call[name[open], parameter[name[file_name], constant[r]]]
call[name[self].read_skel, parame... | keyword[def] identifier[load_skel] ( identifier[self] , identifier[file_name] ):
literal[string]
identifier[fid] = identifier[open] ( identifier[file_name] , literal[string] )
identifier[self] . identifier[read_skel] ( identifier[fid] )
identifier[fid] . identifier[close] ()
... | def load_skel(self, file_name):
"""
Loads an ASF file into a skeleton structure.
:param file_name: The file name to load in.
"""
fid = open(file_name, 'r')
self.read_skel(fid)
fid.close()
self.name = file_name |
def create(cls, type):
""" Return the specified Filter """
if type == 0: return FilterDropShadow(id)
elif type == 1: return FilterBlur(id)
elif type == 2: return FilterGlow(id)
elif type == 3: return FilterBevel(id)
elif type == 4: return FilterGradientGlow(id)
el... | def function[create, parameter[cls, type]]:
constant[ Return the specified Filter ]
if compare[name[type] equal[==] constant[0]] begin[:]
return[call[name[FilterDropShadow], parameter[name[id]]]] | keyword[def] identifier[create] ( identifier[cls] , identifier[type] ):
literal[string]
keyword[if] identifier[type] == literal[int] : keyword[return] identifier[FilterDropShadow] ( identifier[id] )
keyword[elif] identifier[type] == literal[int] : keyword[return] identifier[FilterBlur]... | def create(cls, type):
""" Return the specified Filter """
if type == 0:
return FilterDropShadow(id) # depends on [control=['if'], data=[]]
elif type == 1:
return FilterBlur(id) # depends on [control=['if'], data=[]]
elif type == 2:
return FilterGlow(id) # depends on [control=... |
def push_pq(self, tokens):
""" Creates and Load object, populates it with data, finds its Bus and
adds it.
"""
logger.debug("Pushing PQ data: %s" % tokens)
bus = self.case.buses[tokens["bus_no"] - 1]
bus.p_demand = tokens["p"]
bus.q_demand = tokens["q"] | def function[push_pq, parameter[self, tokens]]:
constant[ Creates and Load object, populates it with data, finds its Bus and
adds it.
]
call[name[logger].debug, parameter[binary_operation[constant[Pushing PQ data: %s] <ast.Mod object at 0x7da2590d6920> name[tokens]]]]
variable[bu... | keyword[def] identifier[push_pq] ( identifier[self] , identifier[tokens] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] % identifier[tokens] )
identifier[bus] = identifier[self] . identifier[case] . identifier[buses] [ identifier[tokens] [ literal[string] ]- l... | def push_pq(self, tokens):
""" Creates and Load object, populates it with data, finds its Bus and
adds it.
"""
logger.debug('Pushing PQ data: %s' % tokens)
bus = self.case.buses[tokens['bus_no'] - 1]
bus.p_demand = tokens['p']
bus.q_demand = tokens['q'] |
def intersection(self, meta):
"""
Get the intersection between the meta data given and the meta data contained within the plates.
Since all of the streams have the same meta data keys (but differing values) we only need to consider
the first stream.
:param meta: The meta data to ... | def function[intersection, parameter[self, meta]]:
constant[
Get the intersection between the meta data given and the meta data contained within the plates.
Since all of the streams have the same meta data keys (but differing values) we only need to consider
the first stream.
:pa... | keyword[def] identifier[intersection] ( identifier[self] , identifier[meta] ):
literal[string]
identifier[keys] = identifier[self] . identifier[_streams] [ literal[int] ]. identifier[stream_id] . identifier[meta_data] . identifier[keys] ()
keyword[return] identifier[StreamId] ( identifier... | def intersection(self, meta):
"""
Get the intersection between the meta data given and the meta data contained within the plates.
Since all of the streams have the same meta data keys (but differing values) we only need to consider
the first stream.
:param meta: The meta data to comp... |
def register_options(cls, register):
"""Register options not tied to any particular task or subsystem."""
# The bootstrap options need to be registered on the post-bootstrap Options instance, so it
# won't choke on them on the command line, and also so we can access their values as regular
# global-scop... | def function[register_options, parameter[cls, register]]:
constant[Register options not tied to any particular task or subsystem.]
call[name[cls].register_bootstrap_options, parameter[name[register]]]
call[name[register], parameter[constant[-x], constant[--time]]]
call[name[register], pa... | keyword[def] identifier[register_options] ( identifier[cls] , identifier[register] ):
literal[string]
identifier[cls] . identifier[register_bootstrap_options] ( identifier[register] )
identifier[register] ( literal[string] , literal[string] , identifier[type] = identifier[bool] ,
... | def register_options(cls, register):
"""Register options not tied to any particular task or subsystem."""
# The bootstrap options need to be registered on the post-bootstrap Options instance, so it
# won't choke on them on the command line, and also so we can access their values as regular
# global-scop... |
def _init_vertical(self):
"""Create and grid the widgets for a vertical orientation."""
self.scale.grid(row=0, sticky='ns')
# showvalue
padx1, padx2 = 0, 0
pady1, pady2 = 0, 0
if self._showvalue:
self.label.configure(text=self._formatter.format(self._start))
... | def function[_init_vertical, parameter[self]]:
constant[Create and grid the widgets for a vertical orientation.]
call[name[self].scale.grid, parameter[]]
<ast.Tuple object at 0x7da1b2290880> assign[=] tuple[[<ast.Constant object at 0x7da1b2290940>, <ast.Constant object at 0x7da1b2290970>]]
... | keyword[def] identifier[_init_vertical] ( identifier[self] ):
literal[string]
identifier[self] . identifier[scale] . identifier[grid] ( identifier[row] = literal[int] , identifier[sticky] = literal[string] )
identifier[padx1] , identifier[padx2] = literal[int] , literal[int]
... | def _init_vertical(self):
"""Create and grid the widgets for a vertical orientation."""
self.scale.grid(row=0, sticky='ns')
# showvalue
(padx1, padx2) = (0, 0)
(pady1, pady2) = (0, 0)
if self._showvalue:
self.label.configure(text=self._formatter.format(self._start))
if self._labe... |
def parse_seconds(value):
'''
Parse string into Seconds instances.
Handled formats:
HH:MM:SS
HH:MM
SS
'''
svalue = str(value)
colons = svalue.count(':')
if colons == 2:
hours, minutes, seconds = [int(v) for v in svalue.split(':... | def function[parse_seconds, parameter[value]]:
constant[
Parse string into Seconds instances.
Handled formats:
HH:MM:SS
HH:MM
SS
]
variable[svalue] assign[=] call[name[str], parameter[name[value]]]
variable[colons] assign[=] call[name[svalue].coun... | keyword[def] identifier[parse_seconds] ( identifier[value] ):
literal[string]
identifier[svalue] = identifier[str] ( identifier[value] )
identifier[colons] = identifier[svalue] . identifier[count] ( literal[string] )
keyword[if] identifier[colons] == literal[int] :
i... | def parse_seconds(value):
"""
Parse string into Seconds instances.
Handled formats:
HH:MM:SS
HH:MM
SS
"""
svalue = str(value)
colons = svalue.count(':')
if colons == 2:
(hours, minutes, seconds) = [int(v) for v in svalue.split(':')] # depends on ... |
def write_config_file(self, f, comments):
"""This method write a sample file, with attributes, descriptions,
sample values, required flags, using the configuration object
properties.
"""
if self.conf_hidden:
return False
if comments:
f.write("\n")... | def function[write_config_file, parameter[self, f, comments]]:
constant[This method write a sample file, with attributes, descriptions,
sample values, required flags, using the configuration object
properties.
]
if name[self].conf_hidden begin[:]
return[constant[False]]
... | keyword[def] identifier[write_config_file] ( identifier[self] , identifier[f] , identifier[comments] ):
literal[string]
keyword[if] identifier[self] . identifier[conf_hidden] :
keyword[return] keyword[False]
keyword[if] identifier[comments] :
identifier[f] . ... | def write_config_file(self, f, comments):
"""This method write a sample file, with attributes, descriptions,
sample values, required flags, using the configuration object
properties.
"""
if self.conf_hidden:
return False # depends on [control=['if'], data=[]]
if comments:
... |
def color2idx(self, red, green, blue):
"""Get an Excel index from"""
xlwt_colors = [
(0, 0, 0), (255, 255, 255), (255, 0, 0), (0, 255, 0), (0, 0, 255),
(255, 255, 0), (255, 0, 255), (0, 255, 255), (0, 0, 0),
(255, 255, 255), (255, 0, 0), (0, 255, 0), (0, 0, 255),
... | def function[color2idx, parameter[self, red, green, blue]]:
constant[Get an Excel index from]
variable[xlwt_colors] assign[=] list[[<ast.Tuple object at 0x7da2046238e0>, <ast.Tuple object at 0x7da204621b40>, <ast.Tuple object at 0x7da204620c70>, <ast.Tuple object at 0x7da204623fa0>, <ast.Tuple object at... | keyword[def] identifier[color2idx] ( identifier[self] , identifier[red] , identifier[green] , identifier[blue] ):
literal[string]
identifier[xlwt_colors] =[
( literal[int] , literal[int] , literal[int] ),( literal[int] , literal[int] , literal[int] ),( literal[int] , literal[int] , literal... | def color2idx(self, red, green, blue):
"""Get an Excel index from"""
xlwt_colors = [(0, 0, 0), (255, 255, 255), (255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255), (0, 0, 0), (255, 255, 255), (255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255), (128... |
def _set_command_options(self, command_obj, option_dict=None):
"""
Set the options for 'command_obj' from 'option_dict'. Basically
this means copying elements of a dictionary ('option_dict') to
attributes of an instance ('command').
'command_obj' must be a Command instance. If... | def function[_set_command_options, parameter[self, command_obj, option_dict]]:
constant[
Set the options for 'command_obj' from 'option_dict'. Basically
this means copying elements of a dictionary ('option_dict') to
attributes of an instance ('command').
'command_obj' must be a... | keyword[def] identifier[_set_command_options] ( identifier[self] , identifier[command_obj] , identifier[option_dict] = keyword[None] ):
literal[string]
identifier[command_name] = identifier[command_obj] . identifier[get_command_name] ()
keyword[if] identifier[option_dict] keyword[is] ke... | def _set_command_options(self, command_obj, option_dict=None):
"""
Set the options for 'command_obj' from 'option_dict'. Basically
this means copying elements of a dictionary ('option_dict') to
attributes of an instance ('command').
'command_obj' must be a Command instance. If 'op... |
def _log_file_ind(self,inum):
"""
Information about available profile.data or log.data files.
Parameters
----------
inum : integer
Attempt to get number of inum's profile.data file.
inum_max: max number of profile.data or log.data files
availa... | def function[_log_file_ind, parameter[self, inum]]:
constant[
Information about available profile.data or log.data files.
Parameters
----------
inum : integer
Attempt to get number of inum's profile.data file.
inum_max: max number of profile.data or log.d... | keyword[def] identifier[_log_file_ind] ( identifier[self] , identifier[inum] ):
literal[string]
identifier[self] . identifier[_profiles_index] ()
keyword[if] identifier[inum] <= literal[int] :
identifier[print] ( literal[string] )
keyword[return]
iden... | def _log_file_ind(self, inum):
"""
Information about available profile.data or log.data files.
Parameters
----------
inum : integer
Attempt to get number of inum's profile.data file.
inum_max: max number of profile.data or log.data files
available... |
def addFeatureSet(self, featureSet):
"""
Adds the specified featureSet to this dataset.
"""
id_ = featureSet.getId()
self._featureSetIdMap[id_] = featureSet
self._featureSetIds.append(id_)
name = featureSet.getLocalId()
self._featureSetNameMap[name] = feat... | def function[addFeatureSet, parameter[self, featureSet]]:
constant[
Adds the specified featureSet to this dataset.
]
variable[id_] assign[=] call[name[featureSet].getId, parameter[]]
call[name[self]._featureSetIdMap][name[id_]] assign[=] name[featureSet]
call[name[self]._... | keyword[def] identifier[addFeatureSet] ( identifier[self] , identifier[featureSet] ):
literal[string]
identifier[id_] = identifier[featureSet] . identifier[getId] ()
identifier[self] . identifier[_featureSetIdMap] [ identifier[id_] ]= identifier[featureSet]
identifier[self] . ide... | def addFeatureSet(self, featureSet):
"""
Adds the specified featureSet to this dataset.
"""
id_ = featureSet.getId()
self._featureSetIdMap[id_] = featureSet
self._featureSetIds.append(id_)
name = featureSet.getLocalId()
self._featureSetNameMap[name] = featureSet |
def split_by_proportionally_distribute_labels(self, proportions={}, use_lengths=True):
"""
Split the corpus into subsets, so the occurrence of the labels is distributed amongst the
subsets according to the given proportions.
Args:
proportions (dict): A dictionary containing ... | def function[split_by_proportionally_distribute_labels, parameter[self, proportions, use_lengths]]:
constant[
Split the corpus into subsets, so the occurrence of the labels is distributed amongst the
subsets according to the given proportions.
Args:
proportions (dict): A dic... | keyword[def] identifier[split_by_proportionally_distribute_labels] ( identifier[self] , identifier[proportions] ={}, identifier[use_lengths] = keyword[True] ):
literal[string]
identifier[identifiers] ={}
keyword[for] identifier[utterance] keyword[in] identifier[self] . identifier[corp... | def split_by_proportionally_distribute_labels(self, proportions={}, use_lengths=True):
"""
Split the corpus into subsets, so the occurrence of the labels is distributed amongst the
subsets according to the given proportions.
Args:
proportions (dict): A dictionary containing the ... |
def isfile_strict(path):
"""Same as os.path.isfile() but does not swallow EACCES / EPERM
exceptions, see:
http://mail.python.org/pipermail/python-dev/2012-June/120787.html
"""
try:
st = os.stat(path)
except OSError:
err = sys.exc_info()[1]
if err.errno in (errno.EPERM, er... | def function[isfile_strict, parameter[path]]:
constant[Same as os.path.isfile() but does not swallow EACCES / EPERM
exceptions, see:
http://mail.python.org/pipermail/python-dev/2012-June/120787.html
]
<ast.Try object at 0x7da18f8137f0> | keyword[def] identifier[isfile_strict] ( identifier[path] ):
literal[string]
keyword[try] :
identifier[st] = identifier[os] . identifier[stat] ( identifier[path] )
keyword[except] identifier[OSError] :
identifier[err] = identifier[sys] . identifier[exc_info] ()[ literal[int] ]
... | def isfile_strict(path):
"""Same as os.path.isfile() but does not swallow EACCES / EPERM
exceptions, see:
http://mail.python.org/pipermail/python-dev/2012-June/120787.html
"""
try:
st = os.stat(path) # depends on [control=['try'], data=[]]
except OSError:
err = sys.exc_info()[1]... |
def contact_advertiser(self, name, email, contact_number, message):
"""
This method allows you to contact the advertiser of a listing.
:param name: Your name
:param email: Your email address.
:param contact_number: Your contact number.
:param message: Your message.
... | def function[contact_advertiser, parameter[self, name, email, contact_number, message]]:
constant[
This method allows you to contact the advertiser of a listing.
:param name: Your name
:param email: Your email address.
:param contact_number: Your contact number.
:param me... | keyword[def] identifier[contact_advertiser] ( identifier[self] , identifier[name] , identifier[email] , identifier[contact_number] , identifier[message] ):
literal[string]
identifier[req] = identifier[Request] ( identifier[debug] = identifier[self] . identifier[_debug] )
identifier[ad_se... | def contact_advertiser(self, name, email, contact_number, message):
"""
This method allows you to contact the advertiser of a listing.
:param name: Your name
:param email: Your email address.
:param contact_number: Your contact number.
:param message: Your message.
:r... |
def trunc_list(s: List) -> List:
"""Truncate lists to maximum length."""
if len(s) > max_list_size:
i = max_list_size // 2
j = i - 1
s = s[:i] + [ELLIPSIS] + s[-j:]
return s | def function[trunc_list, parameter[s]]:
constant[Truncate lists to maximum length.]
if compare[call[name[len], parameter[name[s]]] greater[>] name[max_list_size]] begin[:]
variable[i] assign[=] binary_operation[name[max_list_size] <ast.FloorDiv object at 0x7da2590d6bc0> constant[2]]
... | keyword[def] identifier[trunc_list] ( identifier[s] : identifier[List] )-> identifier[List] :
literal[string]
keyword[if] identifier[len] ( identifier[s] )> identifier[max_list_size] :
identifier[i] = identifier[max_list_size] // literal[int]
identifier[j] = identifier[i] - literal[int]... | def trunc_list(s: List) -> List:
"""Truncate lists to maximum length."""
if len(s) > max_list_size:
i = max_list_size // 2
j = i - 1
s = s[:i] + [ELLIPSIS] + s[-j:] # depends on [control=['if'], data=['max_list_size']]
return s |
def DeregisterPathSpec(cls, path_spec_type):
"""Deregisters a path specification.
Args:
path_spec_type (type): path specification type.
Raises:
KeyError: if path specification is not registered.
"""
type_indicator = path_spec_type.TYPE_INDICATOR
if type_indicator not in cls._path_s... | def function[DeregisterPathSpec, parameter[cls, path_spec_type]]:
constant[Deregisters a path specification.
Args:
path_spec_type (type): path specification type.
Raises:
KeyError: if path specification is not registered.
]
variable[type_indicator] assign[=] name[path_spec_type... | keyword[def] identifier[DeregisterPathSpec] ( identifier[cls] , identifier[path_spec_type] ):
literal[string]
identifier[type_indicator] = identifier[path_spec_type] . identifier[TYPE_INDICATOR]
keyword[if] identifier[type_indicator] keyword[not] keyword[in] identifier[cls] . identifier[_path_spe... | def DeregisterPathSpec(cls, path_spec_type):
"""Deregisters a path specification.
Args:
path_spec_type (type): path specification type.
Raises:
KeyError: if path specification is not registered.
"""
type_indicator = path_spec_type.TYPE_INDICATOR
if type_indicator not in cls._path_s... |
def compute_md5_for_data_asbase64(data):
# type: (obj) -> str
"""Compute MD5 hash for bits and encode as Base64
:param any data: data to compute MD5 for
:rtype: str
:return: MD5 for data
"""
hasher = blobxfer.util.new_md5_hasher()
hasher.update(data)
return blobxfer.util.base64_encod... | def function[compute_md5_for_data_asbase64, parameter[data]]:
constant[Compute MD5 hash for bits and encode as Base64
:param any data: data to compute MD5 for
:rtype: str
:return: MD5 for data
]
variable[hasher] assign[=] call[name[blobxfer].util.new_md5_hasher, parameter[]]
call... | keyword[def] identifier[compute_md5_for_data_asbase64] ( identifier[data] ):
literal[string]
identifier[hasher] = identifier[blobxfer] . identifier[util] . identifier[new_md5_hasher] ()
identifier[hasher] . identifier[update] ( identifier[data] )
keyword[return] identifier[blobxfer] . identifie... | def compute_md5_for_data_asbase64(data):
# type: (obj) -> str
'Compute MD5 hash for bits and encode as Base64\n :param any data: data to compute MD5 for\n :rtype: str\n :return: MD5 for data\n '
hasher = blobxfer.util.new_md5_hasher()
hasher.update(data)
return blobxfer.util.base64_encod... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.