code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def print_start_command(self, command):
'''Set print command
Args:
command: the type of command you desire.
Returns:
None
Raises:
RuntimeError: Command too long.
'''
size = len(command)
if size > 20:
raise R... | def function[print_start_command, parameter[self, command]]:
constant[Set print command
Args:
command: the type of command you desire.
Returns:
None
Raises:
RuntimeError: Command too long.
]
variable[size] assign[=] call[name[l... | keyword[def] identifier[print_start_command] ( identifier[self] , identifier[command] ):
literal[string]
identifier[size] = identifier[len] ( identifier[command] )
keyword[if] identifier[size] > literal[int] :
keyword[raise] identifier[RuntimeError] ( literal[string] )
... | def print_start_command(self, command):
"""Set print command
Args:
command: the type of command you desire.
Returns:
None
Raises:
RuntimeError: Command too long.
"""
size = len(command)
if size > 20:
raise RuntimeError('Com... |
def _api_call(self, endpoint, model=None, method=None, data=None, filters=None):
"""
Makes a call to the linode api. Data should only be given if the method is
POST or PUT, and should be a dictionary
"""
if not self.token:
raise RuntimeError("You do not have an API t... | def function[_api_call, parameter[self, endpoint, model, method, data, filters]]:
constant[
Makes a call to the linode api. Data should only be given if the method is
POST or PUT, and should be a dictionary
]
if <ast.UnaryOp object at 0x7da18dc98670> begin[:]
<ast.Raise ... | keyword[def] identifier[_api_call] ( identifier[self] , identifier[endpoint] , identifier[model] = keyword[None] , identifier[method] = keyword[None] , identifier[data] = keyword[None] , identifier[filters] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[... | def _api_call(self, endpoint, model=None, method=None, data=None, filters=None):
"""
Makes a call to the linode api. Data should only be given if the method is
POST or PUT, and should be a dictionary
"""
if not self.token:
raise RuntimeError('You do not have an API token!') # d... |
def after_event(self, event):
"""Ensure all lines on a screen have proper width (:attr:`columns`).
Extra characters are truncated, missing characters are filled
with whitespace.
:param str event: event name, for example ``"linefeed"``.
"""
if event in ["prev_page", "nex... | def function[after_event, parameter[self, event]]:
constant[Ensure all lines on a screen have proper width (:attr:`columns`).
Extra characters are truncated, missing characters are filled
with whitespace.
:param str event: event name, for example ``"linefeed"``.
]
if co... | keyword[def] identifier[after_event] ( identifier[self] , identifier[event] ):
literal[string]
keyword[if] identifier[event] keyword[in] [ literal[string] , literal[string] ]:
keyword[for] identifier[line] keyword[in] identifier[self] . identifier[buffer] . identifier[values] ():
... | def after_event(self, event):
"""Ensure all lines on a screen have proper width (:attr:`columns`).
Extra characters are truncated, missing characters are filled
with whitespace.
:param str event: event name, for example ``"linefeed"``.
"""
if event in ['prev_page', 'next_page']... |
def get_bucket(bucket_name, include_created=None, flags=FLAGS.ALL ^ FLAGS.CREATED_DATE, **conn):
"""
Orchestrates all the calls required to fully build out an S3 bucket in the following format:
{
"Arn": ...,
"Name": ...,
"Region": ...,
"Owner": ...,
"Grants": ...... | def function[get_bucket, parameter[bucket_name, include_created, flags]]:
constant[
Orchestrates all the calls required to fully build out an S3 bucket in the following format:
{
"Arn": ...,
"Name": ...,
"Region": ...,
"Owner": ...,
"Grants": ...,
"Gr... | keyword[def] identifier[get_bucket] ( identifier[bucket_name] , identifier[include_created] = keyword[None] , identifier[flags] = identifier[FLAGS] . identifier[ALL] ^ identifier[FLAGS] . identifier[CREATED_DATE] ,** identifier[conn] ):
literal[string]
keyword[if] identifier[type] ( identifier[include_cre... | def get_bucket(bucket_name, include_created=None, flags=FLAGS.ALL ^ FLAGS.CREATED_DATE, **conn):
"""
Orchestrates all the calls required to fully build out an S3 bucket in the following format:
{
"Arn": ...,
"Name": ...,
"Region": ...,
"Owner": ...,
"Grants": ...... |
def hosts(self, **kwargs):
"""
Convenience wrapper around listHosts(...) for this channel ID.
:param **kwargs: keyword arguments to the listHosts RPC.
:returns: deferred that when fired returns a list of hosts (dicts).
"""
kwargs['channelID'] = self.id
return sel... | def function[hosts, parameter[self]]:
constant[
Convenience wrapper around listHosts(...) for this channel ID.
:param **kwargs: keyword arguments to the listHosts RPC.
:returns: deferred that when fired returns a list of hosts (dicts).
]
call[name[kwargs]][constant[chann... | keyword[def] identifier[hosts] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= identifier[self] . identifier[id]
keyword[return] identifier[self] . identifier[connection] . identifier[listHosts] (** identifier[kwargs] ) | def hosts(self, **kwargs):
"""
Convenience wrapper around listHosts(...) for this channel ID.
:param **kwargs: keyword arguments to the listHosts RPC.
:returns: deferred that when fired returns a list of hosts (dicts).
"""
kwargs['channelID'] = self.id
return self.connection... |
def normalize_object_slot(self, value=_nothing, prop=None, obj=None):
"""This hook wraps ``normalize_slot``, and performs clean-ups which
require access to the object the slot is in as well as the value.
"""
if value is not _nothing and hasattr(prop, "compare_as"):
method, na... | def function[normalize_object_slot, parameter[self, value, prop, obj]]:
constant[This hook wraps ``normalize_slot``, and performs clean-ups which
require access to the object the slot is in as well as the value.
]
if <ast.BoolOp object at 0x7da20c6c78e0> begin[:]
<ast.Tup... | keyword[def] identifier[normalize_object_slot] ( identifier[self] , identifier[value] = identifier[_nothing] , identifier[prop] = keyword[None] , identifier[obj] = keyword[None] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[not] identifier[_nothing] keyword[and] identif... | def normalize_object_slot(self, value=_nothing, prop=None, obj=None):
"""This hook wraps ``normalize_slot``, and performs clean-ups which
require access to the object the slot is in as well as the value.
"""
if value is not _nothing and hasattr(prop, 'compare_as'):
(method, nargs) = geta... |
def pts_shift(pts=[], shift=[0.0, 0.0]):
'''Return given points shifted in N dimensions.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isins... | def function[pts_shift, parameter[pts, shift]]:
constant[Return given points shifted in N dimensions.
]
assert[<ast.BoolOp object at 0x7da2054a5810>]
variable[l_pt_prev] assign[=] constant[None]
for taget[name[pt]] in starred[name[pts]] begin[:]
assert[call[name[isinstance], para... | keyword[def] identifier[pts_shift] ( identifier[pts] =[], identifier[shift] =[ literal[int] , literal[int] ]):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[pts] , identifier[list] ) keyword[and] identifier[len] ( identifier[pts] )> literal[int]
identifier[l_pt_prev] = keyword... | def pts_shift(pts=[], shift=[0.0, 0.0]):
"""Return given points shifted in N dimensions.
"""
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isins... |
def get_groups_of_user(self, user_id, **kwargs): # noqa: E501
"""Get groups of the user. # noqa: E501
An endpoint for retrieving groups of the user. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/users/{user-id}/groups -H 'Authorization: Bearer API_KEY'` # noqa: E501
This ... | def function[get_groups_of_user, parameter[self, user_id]]:
constant[Get groups of the user. # noqa: E501
An endpoint for retrieving groups of the user. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/users/{user-id}/groups -H 'Authorization: Bearer API_KEY'` # noqa: E501
Th... | keyword[def] identifier[get_groups_of_user] ( identifier[self] , identifier[user_id] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] identif... | def get_groups_of_user(self, user_id, **kwargs): # noqa: E501
"Get groups of the user. # noqa: E501\n\n An endpoint for retrieving groups of the user. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/users/{user-id}/groups -H 'Authorization: Bearer API_KEY'` # noqa: E501\n This met... |
def _decompose_from_posterior_marginals(
model, posterior_means, posterior_covs, parameter_samples):
"""Utility method to decompose a joint posterior into components.
Args:
model: `tfp.sts.Sum` instance defining an additive STS model.
posterior_means: float `Tensor` of shape `concat(
[[num_poster... | def function[_decompose_from_posterior_marginals, parameter[model, posterior_means, posterior_covs, parameter_samples]]:
constant[Utility method to decompose a joint posterior into components.
Args:
model: `tfp.sts.Sum` instance defining an additive STS model.
posterior_means: float `Tensor` of shape... | keyword[def] identifier[_decompose_from_posterior_marginals] (
identifier[model] , identifier[posterior_means] , identifier[posterior_covs] , identifier[parameter_samples] ):
literal[string]
keyword[try] :
identifier[model] . identifier[components]
keyword[except] identifier[AttributeError] :
... | def _decompose_from_posterior_marginals(model, posterior_means, posterior_covs, parameter_samples):
"""Utility method to decompose a joint posterior into components.
Args:
model: `tfp.sts.Sum` instance defining an additive STS model.
posterior_means: float `Tensor` of shape `concat(
[[num_posterior... |
def make_simple():
"""
Create a L{SimpleAuthenticator} instance using values read from coilmq configuration.
@return: The configured L{SimpleAuthenticator}
@rtype: L{SimpleAuthenticator}
@raise ConfigError: If there is a configuration error.
"""
authfile = config.get('coilmq', 'auth.simple.... | def function[make_simple, parameter[]]:
constant[
Create a L{SimpleAuthenticator} instance using values read from coilmq configuration.
@return: The configured L{SimpleAuthenticator}
@rtype: L{SimpleAuthenticator}
@raise ConfigError: If there is a configuration error.
]
variable[aut... | keyword[def] identifier[make_simple] ():
literal[string]
identifier[authfile] = identifier[config] . identifier[get] ( literal[string] , literal[string] )
keyword[if] keyword[not] identifier[authfile] :
keyword[raise] identifier[ConfigError] ( literal[string] )
identifier[sa] = identi... | def make_simple():
"""
Create a L{SimpleAuthenticator} instance using values read from coilmq configuration.
@return: The configured L{SimpleAuthenticator}
@rtype: L{SimpleAuthenticator}
@raise ConfigError: If there is a configuration error.
"""
authfile = config.get('coilmq', 'auth.simple.... |
def netconf_state_sessions_session_login_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
netconf_state = ET.SubElement(config, "netconf-state", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring")
sessions = ET.SubElement(netconf_state, "ses... | def function[netconf_state_sessions_session_login_time, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[netconf_state] assign[=] call[name[ET].SubElement, parameter[name[config], constant[netconf-sta... | keyword[def] identifier[netconf_state_sessions_session_login_time] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[netconf_state] = identifier[ET] . identifier[SubElement] ( identifier[con... | def netconf_state_sessions_session_login_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
netconf_state = ET.SubElement(config, 'netconf-state', xmlns='urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring')
sessions = ET.SubElement(netconf_state, 'sessions')
sess... |
def NewFromContent(cls,
content,
urn,
chunk_size=1024,
token=None,
private_key=None,
public_key=None):
"""Alternate constructor for GRRSignedBlob.
Creates a GRRSignedBlob from a content... | def function[NewFromContent, parameter[cls, content, urn, chunk_size, token, private_key, public_key]]:
constant[Alternate constructor for GRRSignedBlob.
Creates a GRRSignedBlob from a content string by chunking it and signing
each chunk.
Args:
content: The data to stored in the GRRSignedBlo... | keyword[def] identifier[NewFromContent] ( identifier[cls] ,
identifier[content] ,
identifier[urn] ,
identifier[chunk_size] = literal[int] ,
identifier[token] = keyword[None] ,
identifier[private_key] = keyword[None] ,
identifier[public_key] = keyword[None] ):
literal[string]
identifier[aff4] . identi... | def NewFromContent(cls, content, urn, chunk_size=1024, token=None, private_key=None, public_key=None):
"""Alternate constructor for GRRSignedBlob.
Creates a GRRSignedBlob from a content string by chunking it and signing
each chunk.
Args:
content: The data to stored in the GRRSignedBlob.
ur... |
def get_cameras_rules(self):
"""Return the camera rules."""
resource = "rules"
rules_event = self.publish_and_get_event(resource)
if rules_event:
return rules_event.get('properties')
return None | def function[get_cameras_rules, parameter[self]]:
constant[Return the camera rules.]
variable[resource] assign[=] constant[rules]
variable[rules_event] assign[=] call[name[self].publish_and_get_event, parameter[name[resource]]]
if name[rules_event] begin[:]
return[call[name[rules... | keyword[def] identifier[get_cameras_rules] ( identifier[self] ):
literal[string]
identifier[resource] = literal[string]
identifier[rules_event] = identifier[self] . identifier[publish_and_get_event] ( identifier[resource] )
keyword[if] identifier[rules_event] :
keyw... | def get_cameras_rules(self):
"""Return the camera rules."""
resource = 'rules'
rules_event = self.publish_and_get_event(resource)
if rules_event:
return rules_event.get('properties') # depends on [control=['if'], data=[]]
return None |
def get_symm_bands(self, structure, efermi, kpt_line=None,
labels_dict=None):
"""
Function useful to read bands from Boltztrap output and get a
BandStructureSymmLine object comparable with that one from a DFT
calculation (if the same kpt_line is provide... | def function[get_symm_bands, parameter[self, structure, efermi, kpt_line, labels_dict]]:
constant[
Function useful to read bands from Boltztrap output and get a
BandStructureSymmLine object comparable with that one from a DFT
calculation (if the same kpt_line is provided). De... | keyword[def] identifier[get_symm_bands] ( identifier[self] , identifier[structure] , identifier[efermi] , identifier[kpt_line] = keyword[None] ,
identifier[labels_dict] = keyword[None] ):
literal[string]
keyword[try] :
keyword[if] identifier[kpt_line] keyword[is] keyword[None] :
... | def get_symm_bands(self, structure, efermi, kpt_line=None, labels_dict=None):
"""
Function useful to read bands from Boltztrap output and get a
BandStructureSymmLine object comparable with that one from a DFT
calculation (if the same kpt_line is provided). Default kpt_line
... |
def s3am_upload(job, fpath, s3_dir, num_cores=1, s3_key_path=None):
"""
Uploads a file to s3 via S3AM
S3AM binary must be on the PATH to use this function
For SSE-C encryption: provide a path to a 32-byte file
:param toil.job.Job job: Toil job that is calling this function
:param str fpath: Pat... | def function[s3am_upload, parameter[job, fpath, s3_dir, num_cores, s3_key_path]]:
constant[
Uploads a file to s3 via S3AM
S3AM binary must be on the PATH to use this function
For SSE-C encryption: provide a path to a 32-byte file
:param toil.job.Job job: Toil job that is calling this function
... | keyword[def] identifier[s3am_upload] ( identifier[job] , identifier[fpath] , identifier[s3_dir] , identifier[num_cores] = literal[int] , identifier[s3_key_path] = keyword[None] ):
literal[string]
identifier[require] ( identifier[s3_dir] . identifier[startswith] ( literal[string] ), literal[string] , identi... | def s3am_upload(job, fpath, s3_dir, num_cores=1, s3_key_path=None):
"""
Uploads a file to s3 via S3AM
S3AM binary must be on the PATH to use this function
For SSE-C encryption: provide a path to a 32-byte file
:param toil.job.Job job: Toil job that is calling this function
:param str fpath: Pat... |
def tag_and_stem(self, text, cache=None):
"""
Given some text, return a sequence of (stem, pos, text) triples as
appropriate for the reader. `pos` can be as general or specific as
necessary (for example, it might label all parts of speech, or it might
only distinguish function wo... | def function[tag_and_stem, parameter[self, text, cache]]:
constant[
Given some text, return a sequence of (stem, pos, text) triples as
appropriate for the reader. `pos` can be as general or specific as
necessary (for example, it might label all parts of speech, or it might
only d... | keyword[def] identifier[tag_and_stem] ( identifier[self] , identifier[text] , identifier[cache] = keyword[None] ):
literal[string]
identifier[analysis] = identifier[self] . identifier[analyze] ( identifier[text] )
identifier[triples] =[]
keyword[for] identifier[record] keyword[... | def tag_and_stem(self, text, cache=None):
"""
Given some text, return a sequence of (stem, pos, text) triples as
appropriate for the reader. `pos` can be as general or specific as
necessary (for example, it might label all parts of speech, or it might
only distinguish function words ... |
def get_seqprop_subsequence_from_structchain_property(self,
property_key, property_value, condition,
seqprop=None, structprop=None, chain_id=None,
... | def function[get_seqprop_subsequence_from_structchain_property, parameter[self, property_key, property_value, condition, seqprop, structprop, chain_id, use_representatives, return_resnums]]:
constant[Get a subsequence as a new SeqProp object given a certain property you want to find in the
given StructP... | keyword[def] identifier[get_seqprop_subsequence_from_structchain_property] ( identifier[self] ,
identifier[property_key] , identifier[property_value] , identifier[condition] ,
identifier[seqprop] = keyword[None] , identifier[structprop] = keyword[None] , identifier[chain_id] = keyword[None] ,
identifier[use_repres... | def get_seqprop_subsequence_from_structchain_property(self, property_key, property_value, condition, seqprop=None, structprop=None, chain_id=None, use_representatives=False, return_resnums=False):
"""Get a subsequence as a new SeqProp object given a certain property you want to find in the
given StructProp'... |
def is_terminal(self):
"""True if this result will stop the test."""
return (self.raised_exception or self.is_timeout or
self.phase_result == openhtf.PhaseResult.STOP) | def function[is_terminal, parameter[self]]:
constant[True if this result will stop the test.]
return[<ast.BoolOp object at 0x7da1b18c28f0>] | keyword[def] identifier[is_terminal] ( identifier[self] ):
literal[string]
keyword[return] ( identifier[self] . identifier[raised_exception] keyword[or] identifier[self] . identifier[is_timeout] keyword[or]
identifier[self] . identifier[phase_result] == identifier[openhtf] . identifier[PhaseResult... | def is_terminal(self):
"""True if this result will stop the test."""
return self.raised_exception or self.is_timeout or self.phase_result == openhtf.PhaseResult.STOP |
def setParams(self,params):
""" set params """
start = 0
for i in range(self.n_terms):
n_effects = self.B[i].size
self.B[i] = np.reshape(params[start:start+n_effects],self.B[i].shape, order='F')
start += n_effects | def function[setParams, parameter[self, params]]:
constant[ set params ]
variable[start] assign[=] constant[0]
for taget[name[i]] in starred[call[name[range], parameter[name[self].n_terms]]] begin[:]
variable[n_effects] assign[=] call[name[self].B][name[i]].size
c... | keyword[def] identifier[setParams] ( identifier[self] , identifier[params] ):
literal[string]
identifier[start] = literal[int]
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[self] . identifier[n_terms] ):
identifier[n_effects] = identifier[self] . id... | def setParams(self, params):
""" set params """
start = 0
for i in range(self.n_terms):
n_effects = self.B[i].size
self.B[i] = np.reshape(params[start:start + n_effects], self.B[i].shape, order='F')
start += n_effects # depends on [control=['for'], data=['i']] |
def create_data_item_from_data_and_metadata(self, data_and_metadata: DataAndMetadata.DataAndMetadata, title: str=None) -> DataItem:
"""Create a data item in the library from the data and metadata.
.. versionadded:: 1.0
.. deprecated:: 1.1
Use :py:meth:`~nion.swift.Facade.Library.crea... | def function[create_data_item_from_data_and_metadata, parameter[self, data_and_metadata, title]]:
constant[Create a data item in the library from the data and metadata.
.. versionadded:: 1.0
.. deprecated:: 1.1
Use :py:meth:`~nion.swift.Facade.Library.create_data_item_from_data_and_m... | keyword[def] identifier[create_data_item_from_data_and_metadata] ( identifier[self] , identifier[data_and_metadata] : identifier[DataAndMetadata] . identifier[DataAndMetadata] , identifier[title] : identifier[str] = keyword[None] )-> identifier[DataItem] :
literal[string]
identifier[data_item] = id... | def create_data_item_from_data_and_metadata(self, data_and_metadata: DataAndMetadata.DataAndMetadata, title: str=None) -> DataItem:
"""Create a data item in the library from the data and metadata.
.. versionadded:: 1.0
.. deprecated:: 1.1
Use :py:meth:`~nion.swift.Facade.Library.create_d... |
async def get(self, key, *, dc=None, watch=None, consistency=None):
"""Returns the specified key
Parameters:
key (str): Key to fetch
watch (Blocking): Do a blocking query
consistency (Consistency): Force consistency
Returns:
ObjectMeta: where valu... | <ast.AsyncFunctionDef object at 0x7da18c4ce3e0> | keyword[async] keyword[def] identifier[get] ( identifier[self] , identifier[key] ,*, identifier[dc] = keyword[None] , identifier[watch] = keyword[None] , identifier[consistency] = keyword[None] ):
literal[string]
identifier[response] = keyword[await] identifier[self] . identifier[_read] ( identif... | async def get(self, key, *, dc=None, watch=None, consistency=None):
"""Returns the specified key
Parameters:
key (str): Key to fetch
watch (Blocking): Do a blocking query
consistency (Consistency): Force consistency
Returns:
ObjectMeta: where value is... |
def get(self):
"""
Constructs a WorkflowRealTimeStatisticsContext
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsContext
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeSta... | def function[get, parameter[self]]:
constant[
Constructs a WorkflowRealTimeStatisticsContext
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsContext
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_sta... | keyword[def] identifier[get] ( identifier[self] ):
literal[string]
keyword[return] identifier[WorkflowRealTimeStatisticsContext] (
identifier[self] . identifier[_version] ,
identifier[workspace_sid] = identifier[self] . identifier[_solution] [ literal[string] ],
identifi... | def get(self):
"""
Constructs a WorkflowRealTimeStatisticsContext
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsContext
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatist... |
def output_for_skipping_run_set(self, runSet, reason=None):
'''
This function writes a simple message to terminal and logfile,
when a run set is skipped.
There is no message about skipping a run set in the xml-file.
'''
# print to terminal
util.printOut("\nSkippi... | def function[output_for_skipping_run_set, parameter[self, runSet, reason]]:
constant[
This function writes a simple message to terminal and logfile,
when a run set is skipped.
There is no message about skipping a run set in the xml-file.
]
call[name[util].printOut, parame... | keyword[def] identifier[output_for_skipping_run_set] ( identifier[self] , identifier[runSet] , identifier[reason] = keyword[None] ):
literal[string]
identifier[util] . identifier[printOut] ( literal[string] +
( literal[string] + identifier[runSet] . identifier[name] + literal[stri... | def output_for_skipping_run_set(self, runSet, reason=None):
"""
This function writes a simple message to terminal and logfile,
when a run set is skipped.
There is no message about skipping a run set in the xml-file.
"""
# print to terminal
util.printOut('\nSkipping run set' +... |
def mark_rewrite(self, *names):
"""Mark import names as needing to be re-written.
The named module or package as well as any nested modules will
be re-written on import.
"""
already_imported = set(names).intersection(set(sys.modules))
if already_imported:
for... | def function[mark_rewrite, parameter[self]]:
constant[Mark import names as needing to be re-written.
The named module or package as well as any nested modules will
be re-written on import.
]
variable[already_imported] assign[=] call[call[name[set], parameter[name[names]]].inters... | keyword[def] identifier[mark_rewrite] ( identifier[self] ,* identifier[names] ):
literal[string]
identifier[already_imported] = identifier[set] ( identifier[names] ). identifier[intersection] ( identifier[set] ( identifier[sys] . identifier[modules] ))
keyword[if] identifier[already_impor... | def mark_rewrite(self, *names):
"""Mark import names as needing to be re-written.
The named module or package as well as any nested modules will
be re-written on import.
"""
already_imported = set(names).intersection(set(sys.modules))
if already_imported:
for name in already... |
def known(self, object):
""" get the type specified in the object's metadata """
try:
md = object.__metadata__
known = md.sxtype
return known
except:
pass | def function[known, parameter[self, object]]:
constant[ get the type specified in the object's metadata ]
<ast.Try object at 0x7da2041dafb0> | keyword[def] identifier[known] ( identifier[self] , identifier[object] ):
literal[string]
keyword[try] :
identifier[md] = identifier[object] . identifier[__metadata__]
identifier[known] = identifier[md] . identifier[sxtype]
keyword[return] identifier[known]... | def known(self, object):
""" get the type specified in the object's metadata """
try:
md = object.__metadata__
known = md.sxtype
return known # depends on [control=['try'], data=[]]
except:
pass # depends on [control=['except'], data=[]] |
def _match_show(self, show):
"""Match a query for a specific show/list of shows"""
if self.show:
return match_list(self.show, show)
else:
return True | def function[_match_show, parameter[self, show]]:
constant[Match a query for a specific show/list of shows]
if name[self].show begin[:]
return[call[name[match_list], parameter[name[self].show, name[show]]]] | keyword[def] identifier[_match_show] ( identifier[self] , identifier[show] ):
literal[string]
keyword[if] identifier[self] . identifier[show] :
keyword[return] identifier[match_list] ( identifier[self] . identifier[show] , identifier[show] )
keyword[else] :
keyw... | def _match_show(self, show):
"""Match a query for a specific show/list of shows"""
if self.show:
return match_list(self.show, show) # depends on [control=['if'], data=[]]
else:
return True |
def cmd_oreoled(self, args):
'''send LED pattern as override, using OreoLED conventions'''
if len(args) < 4:
print("Usage: oreoled LEDNUM RED GREEN BLUE <RATE>")
return
lednum = int(args[0])
pattern = [0] * 24
pattern[0] = ord('R')
pattern[1] = ord... | def function[cmd_oreoled, parameter[self, args]]:
constant[send LED pattern as override, using OreoLED conventions]
if compare[call[name[len], parameter[name[args]]] less[<] constant[4]] begin[:]
call[name[print], parameter[constant[Usage: oreoled LEDNUM RED GREEN BLUE <RATE>]]]
... | keyword[def] identifier[cmd_oreoled] ( identifier[self] , identifier[args] ):
literal[string]
keyword[if] identifier[len] ( identifier[args] )< literal[int] :
identifier[print] ( literal[string] )
keyword[return]
identifier[lednum] = identifier[int] ( identifier... | def cmd_oreoled(self, args):
"""send LED pattern as override, using OreoLED conventions"""
if len(args) < 4:
print('Usage: oreoled LEDNUM RED GREEN BLUE <RATE>')
return # depends on [control=['if'], data=[]]
lednum = int(args[0])
pattern = [0] * 24
pattern[0] = ord('R')
pattern[... |
def require_int(self, key: str) -> int:
"""
Returns a configuration value, as an int, by its given key. If it doesn't exist, or the
configuration value is not a legal int, an error is thrown.
:param str key: The requested configuration key.
:return: The configuration key's valu... | def function[require_int, parameter[self, key]]:
constant[
Returns a configuration value, as an int, by its given key. If it doesn't exist, or the
configuration value is not a legal int, an error is thrown.
:param str key: The requested configuration key.
:return: The configura... | keyword[def] identifier[require_int] ( identifier[self] , identifier[key] : identifier[str] )-> identifier[int] :
literal[string]
identifier[v] = identifier[self] . identifier[get_int] ( identifier[key] )
keyword[if] identifier[v] keyword[is] keyword[None] :
keyword[raise] ... | def require_int(self, key: str) -> int:
"""
Returns a configuration value, as an int, by its given key. If it doesn't exist, or the
configuration value is not a legal int, an error is thrown.
:param str key: The requested configuration key.
:return: The configuration key's value.
... |
def inject(self, filename, content):
""" add the injection content to the dictionary """
# ensure content always has one trailing newline
content = _unicode(content).rstrip() + "\n"
if filename not in self.inject_dict:
self.inject_dict[filename] = ""
self.inject_dict[... | def function[inject, parameter[self, filename, content]]:
constant[ add the injection content to the dictionary ]
variable[content] assign[=] binary_operation[call[call[name[_unicode], parameter[name[content]]].rstrip, parameter[]] + constant[
]]
if compare[name[filename] <ast.NotIn object at 0x... | keyword[def] identifier[inject] ( identifier[self] , identifier[filename] , identifier[content] ):
literal[string]
identifier[content] = identifier[_unicode] ( identifier[content] ). identifier[rstrip] ()+ literal[string]
keyword[if] identifier[filename] keyword[not] keyword[i... | def inject(self, filename, content):
""" add the injection content to the dictionary """
# ensure content always has one trailing newline
content = _unicode(content).rstrip() + '\n'
if filename not in self.inject_dict:
self.inject_dict[filename] = '' # depends on [control=['if'], data=['filenam... |
def get_payload(self):
"""Return Payload."""
payload = bytes([self.node_id])
payload += string_to_bytes(self.name, 64)
payload += bytes([self.order >> 8 & 255, self.order & 255])
payload += bytes([self.placement])
payload += bytes([self.node_variation.value])
retu... | def function[get_payload, parameter[self]]:
constant[Return Payload.]
variable[payload] assign[=] call[name[bytes], parameter[list[[<ast.Attribute object at 0x7da1b26ac400>]]]]
<ast.AugAssign object at 0x7da1b26adb70>
<ast.AugAssign object at 0x7da1b26ad8d0>
<ast.AugAssign object at 0x7da1b2... | keyword[def] identifier[get_payload] ( identifier[self] ):
literal[string]
identifier[payload] = identifier[bytes] ([ identifier[self] . identifier[node_id] ])
identifier[payload] += identifier[string_to_bytes] ( identifier[self] . identifier[name] , literal[int] )
identifier[payl... | def get_payload(self):
"""Return Payload."""
payload = bytes([self.node_id])
payload += string_to_bytes(self.name, 64)
payload += bytes([self.order >> 8 & 255, self.order & 255])
payload += bytes([self.placement])
payload += bytes([self.node_variation.value])
return payload |
def transform_y(self, tfms:TfmList=None, **kwargs):
"Set `tfms` to be applied to the targets only."
_check_kwargs(self.y, tfms, **kwargs)
self.tfm_y=True
if tfms is None:
self.tfms_y = list(filter(lambda t: t.use_on_y, listify(self.tfms)))
self.tfmargs_y = {**self... | def function[transform_y, parameter[self, tfms]]:
constant[Set `tfms` to be applied to the targets only.]
call[name[_check_kwargs], parameter[name[self].y, name[tfms]]]
name[self].tfm_y assign[=] constant[True]
if compare[name[tfms] is constant[None]] begin[:]
name[self].... | keyword[def] identifier[transform_y] ( identifier[self] , identifier[tfms] : identifier[TfmList] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[_check_kwargs] ( identifier[self] . identifier[y] , identifier[tfms] ,** identifier[kwargs] )
identifier[self] . identifier[... | def transform_y(self, tfms: TfmList=None, **kwargs):
"""Set `tfms` to be applied to the targets only."""
_check_kwargs(self.y, tfms, **kwargs)
self.tfm_y = True
if tfms is None:
self.tfms_y = list(filter(lambda t: t.use_on_y, listify(self.tfms)))
self.tfmargs_y = {**self.tfmargs, **kwarg... |
def guess_depth(packages):
"""
Guess the optimal depth to use for the given list of arguments.
Args:
packages (list of str): list of packages.
Returns:
int: guessed depth to use.
"""
if len(packages) == 1:
return packages[0].count('.') + 2
return min(p.count('.') fo... | def function[guess_depth, parameter[packages]]:
constant[
Guess the optimal depth to use for the given list of arguments.
Args:
packages (list of str): list of packages.
Returns:
int: guessed depth to use.
]
if compare[call[name[len], parameter[name[packages]]] equal[==... | keyword[def] identifier[guess_depth] ( identifier[packages] ):
literal[string]
keyword[if] identifier[len] ( identifier[packages] )== literal[int] :
keyword[return] identifier[packages] [ literal[int] ]. identifier[count] ( literal[string] )+ literal[int]
keyword[return] identifier[min] (... | def guess_depth(packages):
"""
Guess the optimal depth to use for the given list of arguments.
Args:
packages (list of str): list of packages.
Returns:
int: guessed depth to use.
"""
if len(packages) == 1:
return packages[0].count('.') + 2 # depends on [control=['if'],... |
def _modu16(ins):
''' Reminder of div. 2 16bit unsigned integers. The result is pushed onto the stack.
Optimizations:
* If 2nd operand is 1 => Return 0
* If 2nd operand = 2^n => do AND (2^n - 1)
'''
op1, op2 = tuple(ins.quad[2:])
if is_int(op2):
op2 = int16(op2)
... | def function[_modu16, parameter[ins]]:
constant[ Reminder of div. 2 16bit unsigned integers. The result is pushed onto the stack.
Optimizations:
* If 2nd operand is 1 => Return 0
* If 2nd operand = 2^n => do AND (2^n - 1)
]
<ast.Tuple object at 0x7da1b06165f0> assign[=] ca... | keyword[def] identifier[_modu16] ( identifier[ins] ):
literal[string]
identifier[op1] , identifier[op2] = identifier[tuple] ( identifier[ins] . identifier[quad] [ literal[int] :])
keyword[if] identifier[is_int] ( identifier[op2] ):
identifier[op2] = identifier[int16] ( identifier[op2] )
... | def _modu16(ins):
""" Reminder of div. 2 16bit unsigned integers. The result is pushed onto the stack.
Optimizations:
* If 2nd operand is 1 => Return 0
* If 2nd operand = 2^n => do AND (2^n - 1)
"""
(op1, op2) = tuple(ins.quad[2:])
if is_int(op2):
op2 = int16(op2)
... |
def getHostDetailsByIndex(self, index, lanInterfaceId=1, timeout=1):
"""Execute GetGenericHostEntry action to get detailed information's of a connected host.
:param index: the index of the host
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to w... | def function[getHostDetailsByIndex, parameter[self, index, lanInterfaceId, timeout]]:
constant[Execute GetGenericHostEntry action to get detailed information's of a connected host.
:param index: the index of the host
:param int lanInterfaceId: the id of the LAN interface
:param float ti... | keyword[def] identifier[getHostDetailsByIndex] ( identifier[self] , identifier[index] , identifier[lanInterfaceId] = literal[int] , identifier[timeout] = literal[int] ):
literal[string]
identifier[namespace] = identifier[Lan] . identifier[getServiceType] ( literal[string] )+ identifier[str] ( ident... | def getHostDetailsByIndex(self, index, lanInterfaceId=1, timeout=1):
"""Execute GetGenericHostEntry action to get detailed information's of a connected host.
:param index: the index of the host
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to wait ... |
def K(self, X, X2, target):
"""Compute the covariance matrix between X and X2."""
if X2 is None: X2 = X
# i1 = X[:,1]
# i2 = X2[:,1]
# X = X[:,0].reshape(-1,1)
# X2 = X2[:,0].reshape(-1,1)
dist = np.abs(X - X2.T)
ly=1/self.lengthscaleY
lu=np.s... | def function[K, parameter[self, X, X2, target]]:
constant[Compute the covariance matrix between X and X2.]
if compare[name[X2] is constant[None]] begin[:]
variable[X2] assign[=] name[X]
variable[dist] assign[=] call[name[np].abs, parameter[binary_operation[name[X] - name[X2].T]]]... | keyword[def] identifier[K] ( identifier[self] , identifier[X] , identifier[X2] , identifier[target] ):
literal[string]
keyword[if] identifier[X2] keyword[is] keyword[None] : identifier[X2] = identifier[X]
identifier[dist] = identifier[np] . identifie... | def K(self, X, X2, target):
"""Compute the covariance matrix between X and X2."""
if X2 is None:
X2 = X # depends on [control=['if'], data=['X2']]
# i1 = X[:,1]
# i2 = X2[:,1]
# X = X[:,0].reshape(-1,1)
# X2 = X2[:,0].reshape(-1,1)
dist = np.abs(X - X2.T)
ly = 1 / self.lengthsca... |
def addJunctionPos(shape, fromPos, toPos):
"""Extends shape with the given positions in case they differ from the
existing endpoints. assumes that shape and positions have the same dimensionality"""
result = list(shape)
if fromPos != shape[0]:
result = [fromPos] + result
if toPos != shape[-1... | def function[addJunctionPos, parameter[shape, fromPos, toPos]]:
constant[Extends shape with the given positions in case they differ from the
existing endpoints. assumes that shape and positions have the same dimensionality]
variable[result] assign[=] call[name[list], parameter[name[shape]]]
... | keyword[def] identifier[addJunctionPos] ( identifier[shape] , identifier[fromPos] , identifier[toPos] ):
literal[string]
identifier[result] = identifier[list] ( identifier[shape] )
keyword[if] identifier[fromPos] != identifier[shape] [ literal[int] ]:
identifier[result] =[ identifier[fromPos... | def addJunctionPos(shape, fromPos, toPos):
"""Extends shape with the given positions in case they differ from the
existing endpoints. assumes that shape and positions have the same dimensionality"""
result = list(shape)
if fromPos != shape[0]:
result = [fromPos] + result # depends on [control=[... |
def template_stack(name=None, profile=None):
'''
Return template a specific stack (heat stack-template)
name
Name of the stack
profile
Profile to use
CLI Example:
.. code-block:: bash
salt '*' heat.template_stack name=mystack profile=openstack1
'''
h_client =... | def function[template_stack, parameter[name, profile]]:
constant[
Return template a specific stack (heat stack-template)
name
Name of the stack
profile
Profile to use
CLI Example:
.. code-block:: bash
salt '*' heat.template_stack name=mystack profile=openstack1
... | keyword[def] identifier[template_stack] ( identifier[name] = keyword[None] , identifier[profile] = keyword[None] ):
literal[string]
identifier[h_client] = identifier[_auth] ( identifier[profile] )
keyword[if] keyword[not] identifier[name] :
keyword[return] {
literal[string] : keyw... | def template_stack(name=None, profile=None):
"""
Return template a specific stack (heat stack-template)
name
Name of the stack
profile
Profile to use
CLI Example:
.. code-block:: bash
salt '*' heat.template_stack name=mystack profile=openstack1
"""
h_client =... |
def dfa_projection(dfa: dict, symbols_to_remove: set) -> dict:
""" Returns a NFA that reads the language recognized by the
input DFA where all the symbols in **symbols_to_project**
are projected out of the alphabet.
Projection in a DFA is the operation that existentially
removes from a word all occ... | def function[dfa_projection, parameter[dfa, symbols_to_remove]]:
constant[ Returns a NFA that reads the language recognized by the
input DFA where all the symbols in **symbols_to_project**
are projected out of the alphabet.
Projection in a DFA is the operation that existentially
removes from a ... | keyword[def] identifier[dfa_projection] ( identifier[dfa] : identifier[dict] , identifier[symbols_to_remove] : identifier[set] )-> identifier[dict] :
literal[string]
identifier[nfa] ={
literal[string] : identifier[dfa] [ literal[string] ]. identifier[difference] ( identifier[symbols_to_remove] ),
... | def dfa_projection(dfa: dict, symbols_to_remove: set) -> dict:
""" Returns a NFA that reads the language recognized by the
input DFA where all the symbols in **symbols_to_project**
are projected out of the alphabet.
Projection in a DFA is the operation that existentially
removes from a word all occ... |
def spread_stats(stats, spreader=False):
"""Iterates all descendant statistics under the given root statistics.
When ``spreader=True``, each iteration yields a descendant statistics and
`spread()` function together. You should call `spread()` if you want to
spread the yielded statistics also.
"""... | def function[spread_stats, parameter[stats, spreader]]:
constant[Iterates all descendant statistics under the given root statistics.
When ``spreader=True``, each iteration yields a descendant statistics and
`spread()` function together. You should call `spread()` if you want to
spread the yielded ... | keyword[def] identifier[spread_stats] ( identifier[stats] , identifier[spreader] = keyword[False] ):
literal[string]
identifier[spread] = identifier[spread_t] () keyword[if] identifier[spreader] keyword[else] keyword[True]
identifier[descendants] = identifier[deque] ( identifier[stats] )
keyw... | def spread_stats(stats, spreader=False):
"""Iterates all descendant statistics under the given root statistics.
When ``spreader=True``, each iteration yields a descendant statistics and
`spread()` function together. You should call `spread()` if you want to
spread the yielded statistics also.
"""... |
def send_confirmation(self, message, success=True):
"""Send success or error message to configured confirmation
:param str message: Body message to send
:param bool success: Device executed successfully to personalize message
:return: None
"""
message = message.strip()
... | def function[send_confirmation, parameter[self, message, success]]:
constant[Send success or error message to configured confirmation
:param str message: Body message to send
:param bool success: Device executed successfully to personalize message
:return: None
]
variabl... | keyword[def] identifier[send_confirmation] ( identifier[self] , identifier[message] , identifier[success] = keyword[True] ):
literal[string]
identifier[message] = identifier[message] . identifier[strip] ()
keyword[if] keyword[not] identifier[self] . identifier[confirmation] :
... | def send_confirmation(self, message, success=True):
"""Send success or error message to configured confirmation
:param str message: Body message to send
:param bool success: Device executed successfully to personalize message
:return: None
"""
message = message.strip()
if no... |
def get_config():
"""Read the configfile and return config dict.
Returns
-------
dict
Dictionary with the content of the configpath file.
"""
configpath = get_configpath()
if not configpath.exists():
raise IOError("Config file {} not found.".format(str(configpath)))
else... | def function[get_config, parameter[]]:
constant[Read the configfile and return config dict.
Returns
-------
dict
Dictionary with the content of the configpath file.
]
variable[configpath] assign[=] call[name[get_configpath], parameter[]]
if <ast.UnaryOp object at 0x7da1b... | keyword[def] identifier[get_config] ():
literal[string]
identifier[configpath] = identifier[get_configpath] ()
keyword[if] keyword[not] identifier[configpath] . identifier[exists] ():
keyword[raise] identifier[IOError] ( literal[string] . identifier[format] ( identifier[str] ( identifier[c... | def get_config():
"""Read the configfile and return config dict.
Returns
-------
dict
Dictionary with the content of the configpath file.
"""
configpath = get_configpath()
if not configpath.exists():
raise IOError('Config file {} not found.'.format(str(configpath))) # depen... |
def save(self, filename='saved.ol.p'):
"""
Save model to pickle file
"""
import dill as pickle
sv = {
# 'feature_function': self.feature_function,
'cl': self.cl
}
pickle.dump(sv, open(filename, "wb")) | def function[save, parameter[self, filename]]:
constant[
Save model to pickle file
]
import module[dill] as alias[pickle]
variable[sv] assign[=] dictionary[[<ast.Constant object at 0x7da1b23710f0>], [<ast.Attribute object at 0x7da1b2373430>]]
call[name[pickle].dump, parameter... | keyword[def] identifier[save] ( identifier[self] , identifier[filename] = literal[string] ):
literal[string]
keyword[import] identifier[dill] keyword[as] identifier[pickle]
identifier[sv] ={
literal[string] : identifier[self] . identifier[cl]
}
iden... | def save(self, filename='saved.ol.p'):
"""
Save model to pickle file
"""
import dill as pickle
# 'feature_function': self.feature_function,
sv = {'cl': self.cl}
pickle.dump(sv, open(filename, 'wb')) |
def enable_support_autoupload(self, **kwargs):
"""Set Spanning Tree state.
Args:
enabled (bool): Is Autoupload enabled? (True, False).
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
... | def function[enable_support_autoupload, parameter[self]]:
constant[Set Spanning Tree state.
Args:
enabled (bool): Is Autoupload enabled? (True, False).
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback... | keyword[def] identifier[enable_support_autoupload] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[enabled] = identifier[kwargs] . identifier[pop] ( literal[string] )
identifier[callback] = identifier[kwargs] . identifier[pop] ( literal[string] , identifier[self] . ... | def enable_support_autoupload(self, **kwargs):
"""Set Spanning Tree state.
Args:
enabled (bool): Is Autoupload enabled? (True, False).
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
... |
def set_nest_transactions_with_savepoints(self, nest_transactions_with_savepoints):
"""Sets if nested transactions should use savepoints.
:param nest_transactions_with_savepoints: `True` or `False`
"""
if self._transaction_nesting_level > 0:
raise DBALConnectionError.may_not... | def function[set_nest_transactions_with_savepoints, parameter[self, nest_transactions_with_savepoints]]:
constant[Sets if nested transactions should use savepoints.
:param nest_transactions_with_savepoints: `True` or `False`
]
if compare[name[self]._transaction_nesting_level greater[>] ... | keyword[def] identifier[set_nest_transactions_with_savepoints] ( identifier[self] , identifier[nest_transactions_with_savepoints] ):
literal[string]
keyword[if] identifier[self] . identifier[_transaction_nesting_level] > literal[int] :
keyword[raise] identifier[DBALConnectionError] .... | def set_nest_transactions_with_savepoints(self, nest_transactions_with_savepoints):
"""Sets if nested transactions should use savepoints.
:param nest_transactions_with_savepoints: `True` or `False`
"""
if self._transaction_nesting_level > 0:
raise DBALConnectionError.may_not_alter_neste... |
def transpose(self, *axes):
"""
Transpose just the keys of a BoltArraySpark, returning a
new BoltArraySpark.
Parameters
----------
axes : tuple
New proposed axes.
"""
new = argpack(axes)
old = range(self.ndim)
istransposeable(... | def function[transpose, parameter[self]]:
constant[
Transpose just the keys of a BoltArraySpark, returning a
new BoltArraySpark.
Parameters
----------
axes : tuple
New proposed axes.
]
variable[new] assign[=] call[name[argpack], parameter[nam... | keyword[def] identifier[transpose] ( identifier[self] ,* identifier[axes] ):
literal[string]
identifier[new] = identifier[argpack] ( identifier[axes] )
identifier[old] = identifier[range] ( identifier[self] . identifier[ndim] )
identifier[istransposeable] ( identifier[new] , ident... | def transpose(self, *axes):
"""
Transpose just the keys of a BoltArraySpark, returning a
new BoltArraySpark.
Parameters
----------
axes : tuple
New proposed axes.
"""
new = argpack(axes)
old = range(self.ndim)
istransposeable(new, old)
if... |
def _set_rstp(self, v, load=False):
"""
Setter method for rstp, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/rstp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_rstp is considered as a private
method. Backe... | def function[_set_rstp, parameter[self, v, load]]:
constant[
Setter method for rstp, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/rstp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_rstp is considered as a ... | keyword[def] identifier[_set_rstp] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
identifie... | def _set_rstp(self, v, load=False):
"""
Setter method for rstp, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/rstp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_rstp is considered as a private
method. Backe... |
def find_all_hid_devices():
"Finds all HID devices connected to the system"
#
# From DDK documentation (finding and Opening HID collection):
# After a user-mode application is loaded, it does the following sequence
# of operations:
#
# * Calls HidD_GetHidGuid to obtain the system-de... | def function[find_all_hid_devices, parameter[]]:
constant[Finds all HID devices connected to the system]
variable[guid] assign[=] call[name[winapi].GetHidGuid, parameter[]]
variable[results] assign[=] list[[]]
variable[required_size] assign[=] call[name[DWORD], parameter[]]
varia... | keyword[def] identifier[find_all_hid_devices] ():
literal[string]
identifier[guid] = identifier[winapi] . identifier[GetHidGuid] ()
identifier[resu... | def find_all_hid_devices():
"""Finds all HID devices connected to the system""" #
# From DDK documentation (finding and Opening HID collection):
# After a user-mode application is loaded, it does the following sequence
# of operations:
#
# * Calls HidD_GetHidGuid to obtain the system-defined ... |
def unmarshall_key(self, key):
"""
Unmarshalls a Crash key read from the database.
@type key: str or buffer
@param key: Key to convert.
@rtype: L{Crash} key.
@return: Converted key.
"""
key = str(key)
if self.escapeKeys:
key = key.d... | def function[unmarshall_key, parameter[self, key]]:
constant[
Unmarshalls a Crash key read from the database.
@type key: str or buffer
@param key: Key to convert.
@rtype: L{Crash} key.
@return: Converted key.
]
variable[key] assign[=] call[name[str], p... | keyword[def] identifier[unmarshall_key] ( identifier[self] , identifier[key] ):
literal[string]
identifier[key] = identifier[str] ( identifier[key] )
keyword[if] identifier[self] . identifier[escapeKeys] :
identifier[key] = identifier[key] . identifier[decode] ( literal[strin... | def unmarshall_key(self, key):
"""
Unmarshalls a Crash key read from the database.
@type key: str or buffer
@param key: Key to convert.
@rtype: L{Crash} key.
@return: Converted key.
"""
key = str(key)
if self.escapeKeys:
key = key.decode('hex') # ... |
def update_key_bundle(key_bundle, diff):
"""
Apply a diff specification to a KeyBundle.
The keys that are to be added are added.
The keys that should be deleted are marked as inactive.
:param key_bundle: The original KeyBundle
:param diff: The difference specification
:return: An updated ke... | def function[update_key_bundle, parameter[key_bundle, diff]]:
constant[
Apply a diff specification to a KeyBundle.
The keys that are to be added are added.
The keys that should be deleted are marked as inactive.
:param key_bundle: The original KeyBundle
:param diff: The difference specifica... | keyword[def] identifier[update_key_bundle] ( identifier[key_bundle] , identifier[diff] ):
literal[string]
keyword[try] :
identifier[_add] = identifier[diff] [ literal[string] ]
keyword[except] identifier[KeyError] :
keyword[pass]
keyword[else] :
identifier[key_bundle]... | def update_key_bundle(key_bundle, diff):
"""
Apply a diff specification to a KeyBundle.
The keys that are to be added are added.
The keys that should be deleted are marked as inactive.
:param key_bundle: The original KeyBundle
:param diff: The difference specification
:return: An updated ke... |
def resolve_relation_type_config(value):
"""Resolve the relation type to config object.
Resolve relation type from string (e.g.: serialization) or int (db value)
to the full config object.
"""
relation_types = current_app.config['PIDRELATIONS_RELATION_TYPES']
if isinstance(value, six.string_ty... | def function[resolve_relation_type_config, parameter[value]]:
constant[Resolve the relation type to config object.
Resolve relation type from string (e.g.: serialization) or int (db value)
to the full config object.
]
variable[relation_types] assign[=] call[name[current_app].config][consta... | keyword[def] identifier[resolve_relation_type_config] ( identifier[value] ):
literal[string]
identifier[relation_types] = identifier[current_app] . identifier[config] [ literal[string] ]
keyword[if] identifier[isinstance] ( identifier[value] , identifier[six] . identifier[string_types] ):
ke... | def resolve_relation_type_config(value):
"""Resolve the relation type to config object.
Resolve relation type from string (e.g.: serialization) or int (db value)
to the full config object.
"""
relation_types = current_app.config['PIDRELATIONS_RELATION_TYPES']
if isinstance(value, six.string_ty... |
def main(
lang='deu', n=900, epochs=50, batch_size=64, num_neurons=256,
encoder_input_data=None,
decoder_input_data=None,
decoder_target_data=None,
checkpoint_dir=os.path.join(BIGDATA_PATH, 'checkpoints'),
):
""" Train an LSTM encoder-decoder squence-to-sequence model... | def function[main, parameter[lang, n, epochs, batch_size, num_neurons, encoder_input_data, decoder_input_data, decoder_target_data, checkpoint_dir]]:
constant[ Train an LSTM encoder-decoder squence-to-sequence model on Anki flashcards for international translation
>>> model = main('spa', n=400, epochs=3, b... | keyword[def] identifier[main] (
identifier[lang] = literal[string] , identifier[n] = literal[int] , identifier[epochs] = literal[int] , identifier[batch_size] = literal[int] , identifier[num_neurons] = literal[int] ,
identifier[encoder_input_data] = keyword[None] ,
identifier[decoder_input_data] = keyword[None] ,
... | def main(lang='deu', n=900, epochs=50, batch_size=64, num_neurons=256, encoder_input_data=None, decoder_input_data=None, decoder_target_data=None, checkpoint_dir=os.path.join(BIGDATA_PATH, 'checkpoints')):
""" Train an LSTM encoder-decoder squence-to-sequence model on Anki flashcards for international translation
... |
def tree_structures_for(self, prefix, current_oid, parent_oids, prefixes):
"""
Return the entries for this commit, the entries of the parent commits,
and the difference between the two (current_files - parent_files)
"""
if prefix and prefixes and prefix not in prefixes:
... | def function[tree_structures_for, parameter[self, prefix, current_oid, parent_oids, prefixes]]:
constant[
Return the entries for this commit, the entries of the parent commits,
and the difference between the two (current_files - parent_files)
]
if <ast.BoolOp object at 0x7da1b15f... | keyword[def] identifier[tree_structures_for] ( identifier[self] , identifier[prefix] , identifier[current_oid] , identifier[parent_oids] , identifier[prefixes] ):
literal[string]
keyword[if] identifier[prefix] keyword[and] identifier[prefixes] keyword[and] identifier[prefix] keyword[not] key... | def tree_structures_for(self, prefix, current_oid, parent_oids, prefixes):
"""
Return the entries for this commit, the entries of the parent commits,
and the difference between the two (current_files - parent_files)
"""
if prefix and prefixes and (prefix not in prefixes):
return ... |
def ordering(self, type):
"""
Get the attribute ordering defined in the specified
XSD type information.
@param type: An XSD type object.
@type type: SchemaObject
@return: An ordered list of attribute names.
@rtype: list
"""
result = []
for ... | def function[ordering, parameter[self, type]]:
constant[
Get the attribute ordering defined in the specified
XSD type information.
@param type: An XSD type object.
@type type: SchemaObject
@return: An ordered list of attribute names.
@rtype: list
]
... | keyword[def] identifier[ordering] ( identifier[self] , identifier[type] ):
literal[string]
identifier[result] =[]
keyword[for] identifier[child] , identifier[ancestry] keyword[in] identifier[type] . identifier[resolve] ():
identifier[name] = identifier[child] . identifier[n... | def ordering(self, type):
"""
Get the attribute ordering defined in the specified
XSD type information.
@param type: An XSD type object.
@type type: SchemaObject
@return: An ordered list of attribute names.
@rtype: list
"""
result = []
for (child, ance... |
def collection(name, child_names=None, child_source=None,
child_view=None, child_model=None, child_label=None,
child_desc=None, child_meta=None,
label=None, desc=None, meta=None, model_meta=None):
"""
Annotate a dynamic collection of sub-models.
@param name: ... | def function[collection, parameter[name, child_names, child_source, child_view, child_model, child_label, child_desc, child_meta, label, desc, meta, model_meta]]:
constant[
Annotate a dynamic collection of sub-models.
@param name: name of the collection model containing the sub-models
@type... | keyword[def] identifier[collection] ( identifier[name] , identifier[child_names] = keyword[None] , identifier[child_source] = keyword[None] ,
identifier[child_view] = keyword[None] , identifier[child_model] = keyword[None] , identifier[child_label] = keyword[None] ,
identifier[child_desc] = keyword[None] , identifi... | def collection(name, child_names=None, child_source=None, child_view=None, child_model=None, child_label=None, child_desc=None, child_meta=None, label=None, desc=None, meta=None, model_meta=None):
"""
Annotate a dynamic collection of sub-models.
@param name: name of the collection model containing ... |
def calculate_dependencies():
"""Calculate test dependencies
First do a topological sorting based on the dependencies.
Then sort the different dependency groups based on priorities.
"""
order = []
for g in toposort(merge_dicts(dependencies, soft_dependencies)):
... | def function[calculate_dependencies, parameter[]]:
constant[Calculate test dependencies
First do a topological sorting based on the dependencies.
Then sort the different dependency groups based on priorities.
]
variable[order] assign[=] list[[]]
for taget[name[g]] in star... | keyword[def] identifier[calculate_dependencies] ():
literal[string]
identifier[order] =[]
keyword[for] identifier[g] keyword[in] identifier[toposort] ( identifier[merge_dicts] ( identifier[dependencies] , identifier[soft_dependencies] )):
keyword[for] identifier[t] keywor... | def calculate_dependencies():
"""Calculate test dependencies
First do a topological sorting based on the dependencies.
Then sort the different dependency groups based on priorities.
"""
order = []
for g in toposort(merge_dicts(dependencies, soft_dependencies)):
for t in sorte... |
def get_block_height(block_hash, coin_symbol='btc', api_key=None):
'''
Takes a block_hash and returns the block_height
'''
return get_block_overview(block_representation=block_hash,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['height'] | def function[get_block_height, parameter[block_hash, coin_symbol, api_key]]:
constant[
Takes a block_hash and returns the block_height
]
return[call[call[name[get_block_overview], parameter[]]][constant[height]]] | keyword[def] identifier[get_block_height] ( identifier[block_hash] , identifier[coin_symbol] = literal[string] , identifier[api_key] = keyword[None] ):
literal[string]
keyword[return] identifier[get_block_overview] ( identifier[block_representation] = identifier[block_hash] ,
identifier[coin_symbol] ... | def get_block_height(block_hash, coin_symbol='btc', api_key=None):
"""
Takes a block_hash and returns the block_height
"""
return get_block_overview(block_representation=block_hash, coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['height'] |
def set(self, value):
"""Sets value"""
self._value = self._setter(self._node, value, self._value) if self._setter else value | def function[set, parameter[self, value]]:
constant[Sets value]
name[self]._value assign[=] <ast.IfExp object at 0x7da18f722200> | keyword[def] identifier[set] ( identifier[self] , identifier[value] ):
literal[string]
identifier[self] . identifier[_value] = identifier[self] . identifier[_setter] ( identifier[self] . identifier[_node] , identifier[value] , identifier[self] . identifier[_value] ) keyword[if] identifier[self] . ... | def set(self, value):
"""Sets value"""
self._value = self._setter(self._node, value, self._value) if self._setter else value |
def find_uuid(self, obj, column_name):
""" Find uuid.
Parameters
----------
obj : ???
the object returned by the MDAL Query
column_name : str
input point returned from MDAL Query
Returns
-------
str
th... | def function[find_uuid, parameter[self, obj, column_name]]:
constant[ Find uuid.
Parameters
----------
obj : ???
the object returned by the MDAL Query
column_name : str
input point returned from MDAL Query
Returns
-------
... | keyword[def] identifier[find_uuid] ( identifier[self] , identifier[obj] , identifier[column_name] ):
literal[string]
identifier[keys] = identifier[obj] . identifier[context] . identifier[keys] ()
keyword[for] identifier[i] keyword[in] identifier[keys] :
keyword[if] ident... | def find_uuid(self, obj, column_name):
""" Find uuid.
Parameters
----------
obj : ???
the object returned by the MDAL Query
column_name : str
input point returned from MDAL Query
Returns
-------
str
the uu... |
def get_thumbnail_name(self, thumbnail_options, transparent=False,
high_resolution=False):
"""
A version of ``Thumbnailer.get_thumbnail_name`` that produces a
reproducible thumbnail name that can be converted back to the original
filename.
"""
p... | def function[get_thumbnail_name, parameter[self, thumbnail_options, transparent, high_resolution]]:
constant[
A version of ``Thumbnailer.get_thumbnail_name`` that produces a
reproducible thumbnail name that can be converted back to the original
filename.
]
<ast.Tuple obje... | keyword[def] identifier[get_thumbnail_name] ( identifier[self] , identifier[thumbnail_options] , identifier[transparent] = keyword[False] ,
identifier[high_resolution] = keyword[False] ):
literal[string]
identifier[path] , identifier[source_filename] = identifier[os] . identifier[path] . identifie... | def get_thumbnail_name(self, thumbnail_options, transparent=False, high_resolution=False):
"""
A version of ``Thumbnailer.get_thumbnail_name`` that produces a
reproducible thumbnail name that can be converted back to the original
filename.
"""
(path, source_filename) = os.path.sp... |
def bfd(self, **kwargs):
"""Configure BFD for BGP globally.
Args:
rbridge_id (str): Rbridge to configure. (1, 225, etc)
tx (str): BFD transmit interval in milliseconds (300, 500, etc)
rx (str): BFD receive interval in milliseconds (300, 500, etc)
multipl... | def function[bfd, parameter[self]]:
constant[Configure BFD for BGP globally.
Args:
rbridge_id (str): Rbridge to configure. (1, 225, etc)
tx (str): BFD transmit interval in milliseconds (300, 500, etc)
rx (str): BFD receive interval in milliseconds (300, 500, etc)
... | keyword[def] identifier[bfd] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= identifier[kwargs] . identifier[pop] ( literal[string] )
identifier[kwargs] [ literal[string] ]= identifier[kwargs] . identifier[pop] ( literal[string] )
... | def bfd(self, **kwargs):
"""Configure BFD for BGP globally.
Args:
rbridge_id (str): Rbridge to configure. (1, 225, etc)
tx (str): BFD transmit interval in milliseconds (300, 500, etc)
rx (str): BFD receive interval in milliseconds (300, 500, etc)
multiplier ... |
def do_check(self, params):
"""
\x1b[1mNAME\x1b[0m
check - Checks that a path is at a given version (only works within a transaction)
\x1b[1mSYNOPSIS\x1b[0m
check <path> <version>
\x1b[1mEXAMPLES\x1b[0m
> txn 'create /foo "start"' 'check /foo 0' 'set /foo "end"' 'rm /foo 1'
""... | def function[do_check, parameter[self, params]]:
constant[
[1mNAME[0m
check - Checks that a path is at a given version (only works within a transaction)
[1mSYNOPSIS[0m
check <path> <version>
[1mEXAMPLES[0m
> txn 'create /foo "start"' 'check /foo 0' 'set /foo "end"' 'rm /foo 1'
... | keyword[def] identifier[do_check] ( identifier[self] , identifier[params] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[in_transaction] :
keyword[return]
identifier[self] . identifier[client_context] . identifier[check] ( identifier[params] . id... | def do_check(self, params):
"""
\x1b[1mNAME\x1b[0m
check - Checks that a path is at a given version (only works within a transaction)
\x1b[1mSYNOPSIS\x1b[0m
check <path> <version>
\x1b[1mEXAMPLES\x1b[0m
> txn 'create /foo "start"' 'check /foo 0' 'set /foo "end"' 'rm /foo 1'
"""
... |
def process(self):
"""
Calls the process endpoint for all locales of the asset.
API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/assets/asset-processing
"""
for locale in self._fields.keys():
self._client._put(
... | def function[process, parameter[self]]:
constant[
Calls the process endpoint for all locales of the asset.
API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/assets/asset-processing
]
for taget[name[locale]] in starred[call[na... | keyword[def] identifier[process] ( identifier[self] ):
literal[string]
keyword[for] identifier[locale] keyword[in] identifier[self] . identifier[_fields] . identifier[keys] ():
identifier[self] . identifier[_client] . identifier[_put] (
literal[string] . identifier[for... | def process(self):
"""
Calls the process endpoint for all locales of the asset.
API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/assets/asset-processing
"""
for locale in self._fields.keys():
self._client._put('{0}/files/{1}... |
def aligner_from_header(in_bam):
"""Identify aligner from the BAM header; handling pre-aligned inputs.
"""
from bcbio.pipeline.alignment import TOOLS
with pysam.Samfile(in_bam, "rb") as bamfile:
for pg in bamfile.header.get("PG", []):
for ka in TOOLS.keys():
if pg.get... | def function[aligner_from_header, parameter[in_bam]]:
constant[Identify aligner from the BAM header; handling pre-aligned inputs.
]
from relative_module[bcbio.pipeline.alignment] import module[TOOLS]
with call[name[pysam].Samfile, parameter[name[in_bam], constant[rb]]] begin[:]
f... | keyword[def] identifier[aligner_from_header] ( identifier[in_bam] ):
literal[string]
keyword[from] identifier[bcbio] . identifier[pipeline] . identifier[alignment] keyword[import] identifier[TOOLS]
keyword[with] identifier[pysam] . identifier[Samfile] ( identifier[in_bam] , literal[string] ) keyw... | def aligner_from_header(in_bam):
"""Identify aligner from the BAM header; handling pre-aligned inputs.
"""
from bcbio.pipeline.alignment import TOOLS
with pysam.Samfile(in_bam, 'rb') as bamfile:
for pg in bamfile.header.get('PG', []):
for ka in TOOLS.keys():
if pg.get... |
def list_directors(self, service_id, version_number):
"""List the directors for a particular service and version."""
content = self._fetch("/service/%s/version/%d/director" % (service_id, version_number))
return map(lambda x: FastlyDirector(self, x), content) | def function[list_directors, parameter[self, service_id, version_number]]:
constant[List the directors for a particular service and version.]
variable[content] assign[=] call[name[self]._fetch, parameter[binary_operation[constant[/service/%s/version/%d/director] <ast.Mod object at 0x7da2590d6920> tuple[... | keyword[def] identifier[list_directors] ( identifier[self] , identifier[service_id] , identifier[version_number] ):
literal[string]
identifier[content] = identifier[self] . identifier[_fetch] ( literal[string] %( identifier[service_id] , identifier[version_number] ))
keyword[return] identifier[map] ( keywo... | def list_directors(self, service_id, version_number):
"""List the directors for a particular service and version."""
content = self._fetch('/service/%s/version/%d/director' % (service_id, version_number))
return map(lambda x: FastlyDirector(self, x), content) |
def _sentence_to_interstitial_spacing(self):
"""Fix common spacing errors caused by LaTeX's habit
of using an inter-sentence space after any full stop."""
not_sentence_end_chars = [' ']
abbreviations = ['i.e.', 'e.g.', ' v.',
' w.', ' wh.']
titles = ['Prof.', 'Mr.', ... | def function[_sentence_to_interstitial_spacing, parameter[self]]:
constant[Fix common spacing errors caused by LaTeX's habit
of using an inter-sentence space after any full stop.]
variable[not_sentence_end_chars] assign[=] list[[<ast.Constant object at 0x7da2054a42e0>]]
variable[abbrevia... | keyword[def] identifier[_sentence_to_interstitial_spacing] ( identifier[self] ):
literal[string]
identifier[not_sentence_end_chars] =[ literal[string] ]
identifier[abbreviations] =[ literal[string] , literal[string] , literal[string] ,
literal[string] , literal[string] ]
... | def _sentence_to_interstitial_spacing(self):
"""Fix common spacing errors caused by LaTeX's habit
of using an inter-sentence space after any full stop."""
not_sentence_end_chars = [' ']
abbreviations = ['i.e.', 'e.g.', ' v.', ' w.', ' wh.']
titles = ['Prof.', 'Mr.', 'Mrs.', 'Messrs.', 'Mmes.', '... |
def bivnorm (sx, sy, cxy):
"""Given the parameters of a Gaussian bivariate distribution, compute the
correct normalization for the equivalent 2D Gaussian. It's 1 / (2 pi sqrt
(sx**2 sy**2 - cxy**2). This function adds a lot of sanity checking.
Inputs:
* sx: standard deviation (not variance) of x v... | def function[bivnorm, parameter[sx, sy, cxy]]:
constant[Given the parameters of a Gaussian bivariate distribution, compute the
correct normalization for the equivalent 2D Gaussian. It's 1 / (2 pi sqrt
(sx**2 sy**2 - cxy**2). This function adds a lot of sanity checking.
Inputs:
* sx: standard d... | keyword[def] identifier[bivnorm] ( identifier[sx] , identifier[sy] , identifier[cxy] ):
literal[string]
identifier[_bivcheck] ( identifier[sx] , identifier[sy] , identifier[cxy] )
keyword[from] identifier[numpy] keyword[import] identifier[pi] , identifier[sqrt]
identifier[t] =( identifier[sx... | def bivnorm(sx, sy, cxy):
"""Given the parameters of a Gaussian bivariate distribution, compute the
correct normalization for the equivalent 2D Gaussian. It's 1 / (2 pi sqrt
(sx**2 sy**2 - cxy**2). This function adds a lot of sanity checking.
Inputs:
* sx: standard deviation (not variance) of x va... |
def do_rmpostfix(self, arg):
"""Removes a postfix function from a variable. See 'postfix'."""
altered = False
if arg in self.curargs["functions"]:
del self.curargs["functions"][arg]
altered = True
elif arg == "*":
for varname in list(self.curargs["func... | def function[do_rmpostfix, parameter[self, arg]]:
constant[Removes a postfix function from a variable. See 'postfix'.]
variable[altered] assign[=] constant[False]
if compare[name[arg] in call[name[self].curargs][constant[functions]]] begin[:]
<ast.Delete object at 0x7da1b2547910>
... | keyword[def] identifier[do_rmpostfix] ( identifier[self] , identifier[arg] ):
literal[string]
identifier[altered] = keyword[False]
keyword[if] identifier[arg] keyword[in] identifier[self] . identifier[curargs] [ literal[string] ]:
keyword[del] identifier[self] . identifie... | def do_rmpostfix(self, arg):
"""Removes a postfix function from a variable. See 'postfix'."""
altered = False
if arg in self.curargs['functions']:
del self.curargs['functions'][arg]
altered = True # depends on [control=['if'], data=['arg']]
elif arg == '*':
for varname in list(s... |
def _make_dict_elems(build_instr, builders):
"""
Return a list of keys and a list of values for the dictionary literal
generated by ``build_instr``.
"""
keys = []
values = []
for _ in range(build_instr.arg):
popped = builders.pop()
if not isinstance(popped, instrs.STORE_MAP):... | def function[_make_dict_elems, parameter[build_instr, builders]]:
constant[
Return a list of keys and a list of values for the dictionary literal
generated by ``build_instr``.
]
variable[keys] assign[=] list[[]]
variable[values] assign[=] list[[]]
for taget[name[_]] in starre... | keyword[def] identifier[_make_dict_elems] ( identifier[build_instr] , identifier[builders] ):
literal[string]
identifier[keys] =[]
identifier[values] =[]
keyword[for] identifier[_] keyword[in] identifier[range] ( identifier[build_instr] . identifier[arg] ):
identifier[popped] = identi... | def _make_dict_elems(build_instr, builders):
"""
Return a list of keys and a list of values for the dictionary literal
generated by ``build_instr``.
"""
keys = []
values = []
for _ in range(build_instr.arg):
popped = builders.pop()
if not isinstance(popped, instrs.STORE_MAP):... |
def pack_multiple(messages):
"""
Converts a list of SMB2CreateEABuffer structures and packs them as a
bytes object used when setting to the SMB2CreateContextRequest
buffer_data field. This should be used as it would calculate the
correct next_entry_offset field value for each buf... | def function[pack_multiple, parameter[messages]]:
constant[
Converts a list of SMB2CreateEABuffer structures and packs them as a
bytes object used when setting to the SMB2CreateContextRequest
buffer_data field. This should be used as it would calculate the
correct next_entry_offs... | keyword[def] identifier[pack_multiple] ( identifier[messages] ):
literal[string]
identifier[data] = literal[string]
identifier[msg_count] = identifier[len] ( identifier[messages] )
keyword[for] identifier[i] , identifier[msg] keyword[in] identifier[enumerate] ( identifier[mess... | def pack_multiple(messages):
"""
Converts a list of SMB2CreateEABuffer structures and packs them as a
bytes object used when setting to the SMB2CreateContextRequest
buffer_data field. This should be used as it would calculate the
correct next_entry_offset field value for each buffer ... |
def add_val(self, val):
"""add value in form of dict"""
if not isinstance(val, type({})):
raise ValueError(type({}))
self.read()
self.config.update(val)
self.save() | def function[add_val, parameter[self, val]]:
constant[add value in form of dict]
if <ast.UnaryOp object at 0x7da1b0eb8400> begin[:]
<ast.Raise object at 0x7da1b0eb8f70>
call[name[self].read, parameter[]]
call[name[self].config.update, parameter[name[val]]]
call[name[self]... | keyword[def] identifier[add_val] ( identifier[self] , identifier[val] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[val] , identifier[type] ({})):
keyword[raise] identifier[ValueError] ( identifier[type] ({}))
identifier[self] . identifier[... | def add_val(self, val):
"""add value in form of dict"""
if not isinstance(val, type({})):
raise ValueError(type({})) # depends on [control=['if'], data=[]]
self.read()
self.config.update(val)
self.save() |
def request_password_reset(email):
'''Trigger Parse\'s Password Process. Return True/False
indicate success/failure on the request'''
url = '/'.join([API_ROOT, 'requestPasswordReset'])
try:
User.POST(url, email=email)
return True
except ParseError:
... | def function[request_password_reset, parameter[email]]:
constant[Trigger Parse's Password Process. Return True/False
indicate success/failure on the request]
variable[url] assign[=] call[constant[/].join, parameter[list[[<ast.Name object at 0x7da1b0577700>, <ast.Constant object at 0x7da1b05771f0... | keyword[def] identifier[request_password_reset] ( identifier[email] ):
literal[string]
identifier[url] = literal[string] . identifier[join] ([ identifier[API_ROOT] , literal[string] ])
keyword[try] :
identifier[User] . identifier[POST] ( identifier[url] , identifier[email] = ... | def request_password_reset(email):
"""Trigger Parse's Password Process. Return True/False
indicate success/failure on the request"""
url = '/'.join([API_ROOT, 'requestPasswordReset'])
try:
User.POST(url, email=email)
return True # depends on [control=['try'], data=[]]
except Par... |
def is_possible_type(
self, abstract_type: GraphQLAbstractType, possible_type: GraphQLObjectType
) -> bool:
"""Check whether a concrete type is possible for an abstract type."""
possible_type_map = self._possible_type_map
try:
possible_type_names = possible_type_map[abstr... | def function[is_possible_type, parameter[self, abstract_type, possible_type]]:
constant[Check whether a concrete type is possible for an abstract type.]
variable[possible_type_map] assign[=] name[self]._possible_type_map
<ast.Try object at 0x7da1b1d80130>
return[compare[name[possible_type].name ... | keyword[def] identifier[is_possible_type] (
identifier[self] , identifier[abstract_type] : identifier[GraphQLAbstractType] , identifier[possible_type] : identifier[GraphQLObjectType]
)-> identifier[bool] :
literal[string]
identifier[possible_type_map] = identifier[self] . identifier[_possible_typ... | def is_possible_type(self, abstract_type: GraphQLAbstractType, possible_type: GraphQLObjectType) -> bool:
"""Check whether a concrete type is possible for an abstract type."""
possible_type_map = self._possible_type_map
try:
possible_type_names = possible_type_map[abstract_type.name] # depends on [... |
def layer_depth( lat, lon, layerID="LID-BOTTOM"):
"""Returns layer depth at lat / lon (degrees)
where lat/lon may be arrays (of equal size).
Depths are returned in metres.
"""
## Must wrap longitude from 0 to 360 ...
lon1 = np.array(lon)%360.0
lat1 = np.array(lat)
# ## Must wrap longi... | def function[layer_depth, parameter[lat, lon, layerID]]:
constant[Returns layer depth at lat / lon (degrees)
where lat/lon may be arrays (of equal size).
Depths are returned in metres.
]
variable[lon1] assign[=] binary_operation[call[name[np].array, parameter[name[lon]]] <ast.Mod object at 0... | keyword[def] identifier[layer_depth] ( identifier[lat] , identifier[lon] , identifier[layerID] = literal[string] ):
literal[string]
identifier[lon1] = identifier[np] . identifier[array] ( identifier[lon] )% literal[int]
identifier[lat1] = identifier[np] . identifier[array] ( identifier[lat] )
... | def layer_depth(lat, lon, layerID='LID-BOTTOM'):
"""Returns layer depth at lat / lon (degrees)
where lat/lon may be arrays (of equal size).
Depths are returned in metres.
"""
## Must wrap longitude from 0 to 360 ...
lon1 = np.array(lon) % 360.0
lat1 = np.array(lat)
# ## Must wrap longitu... |
def find_suitable_encoding(self, char):
"""The order of our search is a specific one:
1. code pages that we already tried before; there is a good
chance they might work again, reducing the search space,
and by re-using already used encodings we might also
reduce the num... | def function[find_suitable_encoding, parameter[self, char]]:
constant[The order of our search is a specific one:
1. code pages that we already tried before; there is a good
chance they might work again, reducing the search space,
and by re-using already used encodings we might als... | keyword[def] identifier[find_suitable_encoding] ( identifier[self] , identifier[char] ):
literal[string]
identifier[sorted_encodings] = identifier[sorted] (
identifier[self] . identifier[codepages] . identifier[items] (),
identifier[key] = identifier[self] . identifier[__encoding_... | def find_suitable_encoding(self, char):
"""The order of our search is a specific one:
1. code pages that we already tried before; there is a good
chance they might work again, reducing the search space,
and by re-using already used encodings we might also
reduce the number ... |
def train(self, category, text):
"""
Trains a category with a sample of text
:param category: the name of the category we want to train
:type category: str
:param text: the text we want to train the category with
:type text: str
"""
try:
bayes... | def function[train, parameter[self, category, text]]:
constant[
Trains a category with a sample of text
:param category: the name of the category we want to train
:type category: str
:param text: the text we want to train the category with
:type text: str
]
<... | keyword[def] identifier[train] ( identifier[self] , identifier[category] , identifier[text] ):
literal[string]
keyword[try] :
identifier[bayes_category] = identifier[self] . identifier[categories] . identifier[get_category] ( identifier[category] )
keyword[except] identifier[... | def train(self, category, text):
"""
Trains a category with a sample of text
:param category: the name of the category we want to train
:type category: str
:param text: the text we want to train the category with
:type text: str
"""
try:
bayes_category = ... |
def load(filename):
''' Open and return the supplied json file '''
global _DICTIONARY
try:
json_file = filename + '.json'
with open(os.path.join(_DEFAULT_DIR, json_file), 'rb') as f:
_DICTIONARY = json.load(f)
except IOError:
raise IOError('Language file not found. Make sure that your ',
... | def function[load, parameter[filename]]:
constant[ Open and return the supplied json file ]
<ast.Global object at 0x7da18eb57880>
<ast.Try object at 0x7da18eb56320> | keyword[def] identifier[load] ( identifier[filename] ):
literal[string]
keyword[global] identifier[_DICTIONARY]
keyword[try] :
identifier[json_file] = identifier[filename] + literal[string]
keyword[with] identifier[open] ( identifier[os] . identifier[path] . identifier[join] ( identifier[_DEFA... | def load(filename):
""" Open and return the supplied json file """
global _DICTIONARY
try:
json_file = filename + '.json'
with open(os.path.join(_DEFAULT_DIR, json_file), 'rb') as f:
_DICTIONARY = json.load(f) # depends on [control=['with'], data=['f']] # depends on [control=['... |
def keep_form_with_max_profit(self, forms=None):
"""
This converts the dataframe, which shows all profitable forms,
to the form with the greatest profit, so that more profitable
forms outcompete less profitable forms.
Parameters
----------
forms: list of strings
... | def function[keep_form_with_max_profit, parameter[self, forms]]:
constant[
This converts the dataframe, which shows all profitable forms,
to the form with the greatest profit, so that more profitable
forms outcompete less profitable forms.
Parameters
----------
f... | keyword[def] identifier[keep_form_with_max_profit] ( identifier[self] , identifier[forms] = keyword[None] ):
literal[string]
identifier[f] = identifier[self] . identifier[feasibility]
keyword[if] identifier[forms] keyword[is] keyword[not] keyword[None] :
identifier[f] = ... | def keep_form_with_max_profit(self, forms=None):
"""
This converts the dataframe, which shows all profitable forms,
to the form with the greatest profit, so that more profitable
forms outcompete less profitable forms.
Parameters
----------
forms: list of strings
... |
def p_exprs(p):
"""
exprs : expr
| exprs COMMA expr
"""
if len(p) == 2:
p[0] = node.expr_list([p[1]])
elif len(p) == 4:
p[0] = p[1]
p[0].append(p[3])
else:
assert (0)
assert isinstance(p[0], node.expr_list) | def function[p_exprs, parameter[p]]:
constant[
exprs : expr
| exprs COMMA expr
]
if compare[call[name[len], parameter[name[p]]] equal[==] constant[2]] begin[:]
call[name[p]][constant[0]] assign[=] call[name[node].expr_list, parameter[list[[<ast.Subscript object at 0x7da... | keyword[def] identifier[p_exprs] ( identifier[p] ):
literal[string]
keyword[if] identifier[len] ( identifier[p] )== literal[int] :
identifier[p] [ literal[int] ]= identifier[node] . identifier[expr_list] ([ identifier[p] [ literal[int] ]])
keyword[elif] identifier[len] ( identifier[p] )== l... | def p_exprs(p):
"""
exprs : expr
| exprs COMMA expr
"""
if len(p) == 2:
p[0] = node.expr_list([p[1]]) # depends on [control=['if'], data=[]]
elif len(p) == 4:
p[0] = p[1]
p[0].append(p[3]) # depends on [control=['if'], data=[]]
else:
assert 0
asser... |
def iterator(self):
"""
If search has occurred and no ordering has occurred, decorate
each result with the number of search terms so that it can be
sorted by the number of occurrence of terms.
In the case of search fields that span model relationships, we
cannot accurate... | def function[iterator, parameter[self]]:
constant[
If search has occurred and no ordering has occurred, decorate
each result with the number of search terms so that it can be
sorted by the number of occurrence of terms.
In the case of search fields that span model relationships,... | keyword[def] identifier[iterator] ( identifier[self] ):
literal[string]
identifier[results] = identifier[super] ( identifier[SearchableQuerySet] , identifier[self] ). identifier[iterator] ()
keyword[if] identifier[self] . identifier[_search_terms] keyword[and] keyword[not] identifier[s... | def iterator(self):
"""
If search has occurred and no ordering has occurred, decorate
each result with the number of search terms so that it can be
sorted by the number of occurrence of terms.
In the case of search fields that span model relationships, we
cannot accurately m... |
def is_clicked(self, MouseStateType):
"""
Did the user depress and release the button to signify a click?
MouseStateType is the button to query. Values found under StateTypes.py
"""
return self.previous_mouse_state.query_state(MouseStateType) and (
not self.current_mouse_... | def function[is_clicked, parameter[self, MouseStateType]]:
constant[
Did the user depress and release the button to signify a click?
MouseStateType is the button to query. Values found under StateTypes.py
]
return[<ast.BoolOp object at 0x7da18f722b00>] | keyword[def] identifier[is_clicked] ( identifier[self] , identifier[MouseStateType] ):
literal[string]
keyword[return] identifier[self] . identifier[previous_mouse_state] . identifier[query_state] ( identifier[MouseStateType] ) keyword[and] (
keyword[not] identifier[self] . identifier[cu... | def is_clicked(self, MouseStateType):
"""
Did the user depress and release the button to signify a click?
MouseStateType is the button to query. Values found under StateTypes.py
"""
return self.previous_mouse_state.query_state(MouseStateType) and (not self.current_mouse_state.query_state... |
def get_file_mode_for_writing(context):
"""Get file mode for writing from tar['format'].
This should return w:, w:gz, w:bz2 or w:xz. If user specified something
wacky in tar.Format, that's their business.
"""
format = context['tar'].get('format', None)
# slightly weird double-check because fals... | def function[get_file_mode_for_writing, parameter[context]]:
constant[Get file mode for writing from tar['format'].
This should return w:, w:gz, w:bz2 or w:xz. If user specified something
wacky in tar.Format, that's their business.
]
variable[format] assign[=] call[call[name[context]][const... | keyword[def] identifier[get_file_mode_for_writing] ( identifier[context] ):
literal[string]
identifier[format] = identifier[context] [ literal[string] ]. identifier[get] ( literal[string] , keyword[None] )
keyword[if] identifier[format] keyword[or] identifier[format] == literal[strin... | def get_file_mode_for_writing(context):
"""Get file mode for writing from tar['format'].
This should return w:, w:gz, w:bz2 or w:xz. If user specified something
wacky in tar.Format, that's their business.
"""
format = context['tar'].get('format', None)
# slightly weird double-check because fals... |
def _verify_cert(self, sock: ssl.SSLSocket):
'''Check if certificate matches hostname.'''
# Based on tornado.iostream.SSLIOStream
# Needed for older OpenSSL (<0.9.8f) versions
verify_mode = self._ssl_context.verify_mode
assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED,
... | def function[_verify_cert, parameter[self, sock]]:
constant[Check if certificate matches hostname.]
variable[verify_mode] assign[=] name[self]._ssl_context.verify_mode
assert[compare[name[verify_mode] in tuple[[<ast.Attribute object at 0x7da20eb294b0>, <ast.Attribute object at 0x7da2041d9840>, <ast.... | keyword[def] identifier[_verify_cert] ( identifier[self] , identifier[sock] : identifier[ssl] . identifier[SSLSocket] ):
literal[string]
identifier[verify_mode] = identifier[self] . identifier[_ssl_context] . identifier[verify_mode]
keyword[assert] identifier[verify_mo... | def _verify_cert(self, sock: ssl.SSLSocket):
"""Check if certificate matches hostname."""
# Based on tornado.iostream.SSLIOStream
# Needed for older OpenSSL (<0.9.8f) versions
verify_mode = self._ssl_context.verify_mode
assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED, ssl.CERT_OPTIONAL), 'Un... |
def deny(cls, action, **kwargs):
"""Deny the given action need.
:param action: The action to deny.
:returns: A :class:`invenio_access.models.ActionNeedMixin` instance.
"""
return cls.create(action, exclude=True, **kwargs) | def function[deny, parameter[cls, action]]:
constant[Deny the given action need.
:param action: The action to deny.
:returns: A :class:`invenio_access.models.ActionNeedMixin` instance.
]
return[call[name[cls].create, parameter[name[action]]]] | keyword[def] identifier[deny] ( identifier[cls] , identifier[action] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[cls] . identifier[create] ( identifier[action] , identifier[exclude] = keyword[True] ,** identifier[kwargs] ) | def deny(cls, action, **kwargs):
"""Deny the given action need.
:param action: The action to deny.
:returns: A :class:`invenio_access.models.ActionNeedMixin` instance.
"""
return cls.create(action, exclude=True, **kwargs) |
def get_kvlayer_stream_item_by_doc_id(client, doc_id):
'''Retrieve :class:`streamcorpus.StreamItem`s from :mod:`kvlayer`.
Namely, it returns an iterator over all documents with the given
docid. The docid should be an md5 hash of the document's abs_url.
:param client: kvlayer client object
:type cl... | def function[get_kvlayer_stream_item_by_doc_id, parameter[client, doc_id]]:
constant[Retrieve :class:`streamcorpus.StreamItem`s from :mod:`kvlayer`.
Namely, it returns an iterator over all documents with the given
docid. The docid should be an md5 hash of the document's abs_url.
:param client: kvl... | keyword[def] identifier[get_kvlayer_stream_item_by_doc_id] ( identifier[client] , identifier[doc_id] ):
literal[string]
keyword[if] identifier[client] keyword[is] keyword[None] :
identifier[client] = identifier[kvlayer] . identifier[client] ()
identifier[client] . identifier[setup_name... | def get_kvlayer_stream_item_by_doc_id(client, doc_id):
"""Retrieve :class:`streamcorpus.StreamItem`s from :mod:`kvlayer`.
Namely, it returns an iterator over all documents with the given
docid. The docid should be an md5 hash of the document's abs_url.
:param client: kvlayer client object
:type cl... |
def attach_binary(self, content, filename):
"""
Attaches given binary data.
:param bytes content: Binary data to be attached.
:param str filename:
:return: None.
"""
content_type = guess_content_type(filename)
payload = {"Name": filename, "Content": b64en... | def function[attach_binary, parameter[self, content, filename]]:
constant[
Attaches given binary data.
:param bytes content: Binary data to be attached.
:param str filename:
:return: None.
]
variable[content_type] assign[=] call[name[guess_content_type], paramete... | keyword[def] identifier[attach_binary] ( identifier[self] , identifier[content] , identifier[filename] ):
literal[string]
identifier[content_type] = identifier[guess_content_type] ( identifier[filename] )
identifier[payload] ={ literal[string] : identifier[filename] , literal[string] : ide... | def attach_binary(self, content, filename):
"""
Attaches given binary data.
:param bytes content: Binary data to be attached.
:param str filename:
:return: None.
"""
content_type = guess_content_type(filename)
payload = {'Name': filename, 'Content': b64encode(content... |
def new_table_graphicFrame(cls, id_, name, rows, cols, x, y, cx, cy):
"""
Return a ``<p:graphicFrame>`` element tree populated with a table
element.
"""
graphicFrame = cls.new_graphicFrame(id_, name, x, y, cx, cy)
graphicFrame.graphic.graphicData.uri = GRAPHIC_DATA_URI_TA... | def function[new_table_graphicFrame, parameter[cls, id_, name, rows, cols, x, y, cx, cy]]:
constant[
Return a ``<p:graphicFrame>`` element tree populated with a table
element.
]
variable[graphicFrame] assign[=] call[name[cls].new_graphicFrame, parameter[name[id_], name[name], nam... | keyword[def] identifier[new_table_graphicFrame] ( identifier[cls] , identifier[id_] , identifier[name] , identifier[rows] , identifier[cols] , identifier[x] , identifier[y] , identifier[cx] , identifier[cy] ):
literal[string]
identifier[graphicFrame] = identifier[cls] . identifier[new_graphicFrame]... | def new_table_graphicFrame(cls, id_, name, rows, cols, x, y, cx, cy):
"""
Return a ``<p:graphicFrame>`` element tree populated with a table
element.
"""
graphicFrame = cls.new_graphicFrame(id_, name, x, y, cx, cy)
graphicFrame.graphic.graphicData.uri = GRAPHIC_DATA_URI_TABLE
grap... |
def parse_device(lines):
"""Parse all the lines of a device block.
A device block is composed of a header line with the name of the device and
at least one extra line describing the device and its status. The extra
lines have a varying format depending on the status and personality of the
device (... | def function[parse_device, parameter[lines]]:
constant[Parse all the lines of a device block.
A device block is composed of a header line with the name of the device and
at least one extra line describing the device and its status. The extra
lines have a varying format depending on the status and ... | keyword[def] identifier[parse_device] ( identifier[lines] ):
literal[string]
identifier[name] , identifier[status_line] , identifier[device] = identifier[parse_device_header] ( identifier[lines] . identifier[pop] ( literal[int] ))
keyword[if] keyword[not] identifier[status_line] :
... | def parse_device(lines):
"""Parse all the lines of a device block.
A device block is composed of a header line with the name of the device and
at least one extra line describing the device and its status. The extra
lines have a varying format depending on the status and personality of the
device (... |
def catch_result(task_func):
"""Catch printed result from Celery Task and return it in task response
"""
@functools.wraps(task_func, assigned=available_attrs(task_func))
def dec(*args, **kwargs):
# inicialize
orig_stdout = sys.stdout
sys.stdout = content = StringIO()
tas... | def function[catch_result, parameter[task_func]]:
constant[Catch printed result from Celery Task and return it in task response
]
def function[dec, parameter[]]:
variable[orig_stdout] assign[=] name[sys].stdout
name[sys].stdout assign[=] call[name[StringIO], parameter... | keyword[def] identifier[catch_result] ( identifier[task_func] ):
literal[string]
@ identifier[functools] . identifier[wraps] ( identifier[task_func] , identifier[assigned] = identifier[available_attrs] ( identifier[task_func] ))
keyword[def] identifier[dec] (* identifier[args] ,** identifier[kwargs] ... | def catch_result(task_func):
"""Catch printed result from Celery Task and return it in task response
"""
@functools.wraps(task_func, assigned=available_attrs(task_func))
def dec(*args, **kwargs):
# inicialize
orig_stdout = sys.stdout
sys.stdout = content = StringIO()
tas... |
def _direct_render(self, name, attrs):
"""Render the widget the old way - using field_template or output_format."""
context = {
'image': self.image_url(),
'name': name,
'key': self._key,
'id': u'%s_%s' % (self.id_prefix, attrs.get('id')) if self.id_prefix ... | def function[_direct_render, parameter[self, name, attrs]]:
constant[Render the widget the old way - using field_template or output_format.]
variable[context] assign[=] dictionary[[<ast.Constant object at 0x7da2041db0a0>, <ast.Constant object at 0x7da2041da620>, <ast.Constant object at 0x7da2041dba60>, ... | keyword[def] identifier[_direct_render] ( identifier[self] , identifier[name] , identifier[attrs] ):
literal[string]
identifier[context] ={
literal[string] : identifier[self] . identifier[image_url] (),
literal[string] : identifier[name] ,
literal[string] : identifier[sel... | def _direct_render(self, name, attrs):
"""Render the widget the old way - using field_template or output_format."""
context = {'image': self.image_url(), 'name': name, 'key': self._key, 'id': u'%s_%s' % (self.id_prefix, attrs.get('id')) if self.id_prefix else attrs.get('id'), 'audio': self.audio_url()}
self... |
def post(self, request, *args, **kwargs):
""" Handles POST requests. """
self.init_attachment_cache()
# Stores a boolean indicating if we are considering a preview
self.preview = 'preview' in self.request.POST
# Initializes the forms
post_form_class = self.get_post_form... | def function[post, parameter[self, request]]:
constant[ Handles POST requests. ]
call[name[self].init_attachment_cache, parameter[]]
name[self].preview assign[=] compare[constant[preview] in name[self].request.POST]
variable[post_form_class] assign[=] call[name[self].get_post_form_class,... | keyword[def] identifier[post] ( identifier[self] , identifier[request] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[init_attachment_cache] ()
identifier[self] . identifier[preview] = literal[string] keyword[in] identifier[self] . i... | def post(self, request, *args, **kwargs):
""" Handles POST requests. """
self.init_attachment_cache()
# Stores a boolean indicating if we are considering a preview
self.preview = 'preview' in self.request.POST
# Initializes the forms
post_form_class = self.get_post_form_class()
post_form = s... |
def get_complexes(self):
"""Extract INDRA Complex Statements from the BioPAX model.
This method searches for org.biopax.paxtools.model.level3.Complex
objects which represent molecular complexes. It doesn't reuse
BioPAX Pattern's org.biopax.paxtools.pattern.PatternBox.inComplexWith
... | def function[get_complexes, parameter[self]]:
constant[Extract INDRA Complex Statements from the BioPAX model.
This method searches for org.biopax.paxtools.model.level3.Complex
objects which represent molecular complexes. It doesn't reuse
BioPAX Pattern's org.biopax.paxtools.pattern.Pat... | keyword[def] identifier[get_complexes] ( identifier[self] ):
literal[string]
keyword[for] identifier[obj] keyword[in] identifier[self] . identifier[model] . identifier[getObjects] (). identifier[toArray] ():
identifier[bpe] = identifier[_cast_biopax_element] ( identifier[obj] )
... | def get_complexes(self):
"""Extract INDRA Complex Statements from the BioPAX model.
This method searches for org.biopax.paxtools.model.level3.Complex
objects which represent molecular complexes. It doesn't reuse
BioPAX Pattern's org.biopax.paxtools.pattern.PatternBox.inComplexWith
q... |
def as_partition(self, **kwargs):
"""Return a PartitionName based on this name."""
return PartitionName(**dict(list(self.dict.items()) + list(kwargs.items()))) | def function[as_partition, parameter[self]]:
constant[Return a PartitionName based on this name.]
return[call[name[PartitionName], parameter[]]] | keyword[def] identifier[as_partition] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[PartitionName] (** identifier[dict] ( identifier[list] ( identifier[self] . identifier[dict] . identifier[items] ())+ identifier[list] ( identifier[kwargs] . identifier[it... | def as_partition(self, **kwargs):
"""Return a PartitionName based on this name."""
return PartitionName(**dict(list(self.dict.items()) + list(kwargs.items()))) |
def _get_slot(self):
"Returns the next coordinates for a preview"
x = y = 10
for k, p in self.previews.items():
y += p.height() + self.padding
return x, y | def function[_get_slot, parameter[self]]:
constant[Returns the next coordinates for a preview]
variable[x] assign[=] constant[10]
for taget[tuple[[<ast.Name object at 0x7da1b17ce4d0>, <ast.Name object at 0x7da1b17cddb0>]]] in starred[call[name[self].previews.items, parameter[]]] begin[:]
... | keyword[def] identifier[_get_slot] ( identifier[self] ):
literal[string]
identifier[x] = identifier[y] = literal[int]
keyword[for] identifier[k] , identifier[p] keyword[in] identifier[self] . identifier[previews] . identifier[items] ():
identifier[y] += identifier[p] . id... | def _get_slot(self):
"""Returns the next coordinates for a preview"""
x = y = 10
for (k, p) in self.previews.items():
y += p.height() + self.padding # depends on [control=['for'], data=[]]
return (x, y) |
def render(self, *args, **kwargs):
"""Renders the element and all his childrens."""
# args kwargs API provided for last minute content injection
# self._reverse_mro_func('pre_render')
pretty = kwargs.pop("pretty", False)
if pretty and self._stable != "pretty":
self._s... | def function[render, parameter[self]]:
constant[Renders the element and all his childrens.]
variable[pretty] assign[=] call[name[kwargs].pop, parameter[constant[pretty], constant[False]]]
if <ast.BoolOp object at 0x7da1b0f3a4d0> begin[:]
name[self]._stable assign[=] constant[Fals... | keyword[def] identifier[render] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[pretty] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[False] )
keyword[if] identifier[pretty] keyword[and] identifier[self] ... | def render(self, *args, **kwargs):
"""Renders the element and all his childrens."""
# args kwargs API provided for last minute content injection
# self._reverse_mro_func('pre_render')
pretty = kwargs.pop('pretty', False)
if pretty and self._stable != 'pretty':
self._stable = False # depends... |
def _compute_mean(self, C, rup, rjb):
"""
Compute mean value according to equation 30, page 1021.
"""
mean = (C['c1'] +
self._compute_magnitude_term(C, rup) +
self._compute_distance_term(C, rup, rjb))
return mean | def function[_compute_mean, parameter[self, C, rup, rjb]]:
constant[
Compute mean value according to equation 30, page 1021.
]
variable[mean] assign[=] binary_operation[binary_operation[call[name[C]][constant[c1]] + call[name[self]._compute_magnitude_term, parameter[name[C], name[rup]]]]... | keyword[def] identifier[_compute_mean] ( identifier[self] , identifier[C] , identifier[rup] , identifier[rjb] ):
literal[string]
identifier[mean] =( identifier[C] [ literal[string] ]+
identifier[self] . identifier[_compute_magnitude_term] ( identifier[C] , identifier[rup] )+
ident... | def _compute_mean(self, C, rup, rjb):
"""
Compute mean value according to equation 30, page 1021.
"""
mean = C['c1'] + self._compute_magnitude_term(C, rup) + self._compute_distance_term(C, rup, rjb)
return mean |
def import_locations(self, osm_file):
"""Import OSM data files.
``import_locations()`` returns a list of ``Node`` and ``Way`` objects.
It expects data files conforming to the `OpenStreetMap 0.5 DTD`_, which
is XML such as::
<?xml version="1.0" encoding="UTF-8"?>
... | def function[import_locations, parameter[self, osm_file]]:
constant[Import OSM data files.
``import_locations()`` returns a list of ``Node`` and ``Way`` objects.
It expects data files conforming to the `OpenStreetMap 0.5 DTD`_, which
is XML such as::
<?xml version="1.0" en... | keyword[def] identifier[import_locations] ( identifier[self] , identifier[osm_file] ):
literal[string]
identifier[self] . identifier[_osm_file] = identifier[osm_file]
identifier[data] = identifier[utils] . identifier[prepare_xml_read] ( identifier[osm_file] , identifier[objectify] = keywo... | def import_locations(self, osm_file):
"""Import OSM data files.
``import_locations()`` returns a list of ``Node`` and ``Way`` objects.
It expects data files conforming to the `OpenStreetMap 0.5 DTD`_, which
is XML such as::
<?xml version="1.0" encoding="UTF-8"?>
<o... |
def get_HDX_code_from_location(location, locations=None, configuration=None):
# type: (str, Optional[List[Dict]], Optional[Configuration]) -> Optional[str]
"""Get HDX code for location
Args:
location (str): Location for which to get HDX code
locations (Optional[List[Dict... | def function[get_HDX_code_from_location, parameter[location, locations, configuration]]:
constant[Get HDX code for location
Args:
location (str): Location for which to get HDX code
locations (Optional[List[Dict]]): Valid locations list. Defaults to list downloaded from HDX.
... | keyword[def] identifier[get_HDX_code_from_location] ( identifier[location] , identifier[locations] = keyword[None] , identifier[configuration] = keyword[None] ):
literal[string]
keyword[if] identifier[locations] keyword[is] keyword[None] :
identifier[locations] = identifier[Locatio... | def get_HDX_code_from_location(location, locations=None, configuration=None):
# type: (str, Optional[List[Dict]], Optional[Configuration]) -> Optional[str]
'Get HDX code for location\n\n Args:\n location (str): Location for which to get HDX code\n locations (Optional[List[Dict]]): V... |
def download_image(url: str = '', save_path: str = '',
unverified_ctx: bool = False) -> Union[None, str]:
"""Download image and save in current directory on local machine.
:param url: URL to image.
:param save_path: Saving path.
:param unverified_ctx: Create unverified context.
:... | def function[download_image, parameter[url, save_path, unverified_ctx]]:
constant[Download image and save in current directory on local machine.
:param url: URL to image.
:param save_path: Saving path.
:param unverified_ctx: Create unverified context.
:return: Path to downloaded image.
:rty... | keyword[def] identifier[download_image] ( identifier[url] : identifier[str] = literal[string] , identifier[save_path] : identifier[str] = literal[string] ,
identifier[unverified_ctx] : identifier[bool] = keyword[False] )-> identifier[Union] [ keyword[None] , identifier[str] ]:
literal[string]
keyword[if] ... | def download_image(url: str='', save_path: str='', unverified_ctx: bool=False) -> Union[None, str]:
"""Download image and save in current directory on local machine.
:param url: URL to image.
:param save_path: Saving path.
:param unverified_ctx: Create unverified context.
:return: Path to downloade... |
def signature_split(signatures: bytes, pos: int) -> Tuple[int, int, int]:
"""
:param signatures: signatures in form of {bytes32 r}{bytes32 s}{uint8 v}
:param pos: position of the signature
:return: Tuple with v, r, s
"""
signature_pos = 65 * pos
v = signatures[64 + signature_pos]
r = int... | def function[signature_split, parameter[signatures, pos]]:
constant[
:param signatures: signatures in form of {bytes32 r}{bytes32 s}{uint8 v}
:param pos: position of the signature
:return: Tuple with v, r, s
]
variable[signature_pos] assign[=] binary_operation[constant[65] * name[pos]]
... | keyword[def] identifier[signature_split] ( identifier[signatures] : identifier[bytes] , identifier[pos] : identifier[int] )-> identifier[Tuple] [ identifier[int] , identifier[int] , identifier[int] ]:
literal[string]
identifier[signature_pos] = literal[int] * identifier[pos]
identifier[v] = identifie... | def signature_split(signatures: bytes, pos: int) -> Tuple[int, int, int]:
"""
:param signatures: signatures in form of {bytes32 r}{bytes32 s}{uint8 v}
:param pos: position of the signature
:return: Tuple with v, r, s
"""
signature_pos = 65 * pos
v = signatures[64 + signature_pos]
r = int... |
def roc_auc(logits, labels, weights_fn=None):
"""Calculate ROC AUC.
Requires binary classes.
Args:
logits: Tensor of size [batch_size, 1, 1, num_classes]
labels: Tensor of size [batch_size, 1, 1, num_classes]
weights_fn: Function that takes in labels and weighs examples (unused)
Returns:
ROC A... | def function[roc_auc, parameter[logits, labels, weights_fn]]:
constant[Calculate ROC AUC.
Requires binary classes.
Args:
logits: Tensor of size [batch_size, 1, 1, num_classes]
labels: Tensor of size [batch_size, 1, 1, num_classes]
weights_fn: Function that takes in labels and weighs examples (... | keyword[def] identifier[roc_auc] ( identifier[logits] , identifier[labels] , identifier[weights_fn] = keyword[None] ):
literal[string]
keyword[del] identifier[weights_fn]
keyword[with] identifier[tf] . identifier[variable_scope] ( literal[string] , identifier[values] =[ identifier[logits] , identifier[la... | def roc_auc(logits, labels, weights_fn=None):
"""Calculate ROC AUC.
Requires binary classes.
Args:
logits: Tensor of size [batch_size, 1, 1, num_classes]
labels: Tensor of size [batch_size, 1, 1, num_classes]
weights_fn: Function that takes in labels and weighs examples (unused)
Returns:
ROC... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.