code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def get_current_waypoints(boatd=None):
'''
Get the current set of waypoints active from boatd.
:returns: The current waypoints
:rtype: List of Points
'''
if boatd is None:
boatd = Boatd()
content = boatd.get('/waypoints')
return [Point(*coords) for coords in content.get('waypo... | def function[get_current_waypoints, parameter[boatd]]:
constant[
Get the current set of waypoints active from boatd.
:returns: The current waypoints
:rtype: List of Points
]
if compare[name[boatd] is constant[None]] begin[:]
variable[boatd] assign[=] call[name[Boatd], pa... | keyword[def] identifier[get_current_waypoints] ( identifier[boatd] = keyword[None] ):
literal[string]
keyword[if] identifier[boatd] keyword[is] keyword[None] :
identifier[boatd] = identifier[Boatd] ()
identifier[content] = identifier[boatd] . identifier[get] ( literal[string] )
keyw... | def get_current_waypoints(boatd=None):
"""
Get the current set of waypoints active from boatd.
:returns: The current waypoints
:rtype: List of Points
"""
if boatd is None:
boatd = Boatd() # depends on [control=['if'], data=['boatd']]
content = boatd.get('/waypoints')
return [Po... |
def log_stats(self):
"""Print statistics into log."""
logging.info('Validation statistics: ')
for k, v in iteritems(self.stats):
logging.info('%s - %d valid out of %d total submissions',
k, v[0], v[0] + v[1]) | def function[log_stats, parameter[self]]:
constant[Print statistics into log.]
call[name[logging].info, parameter[constant[Validation statistics: ]]]
for taget[tuple[[<ast.Name object at 0x7da1b1fc8610>, <ast.Name object at 0x7da1b1fca230>]]] in starred[call[name[iteritems], parameter[name[self]... | keyword[def] identifier[log_stats] ( identifier[self] ):
literal[string]
identifier[logging] . identifier[info] ( literal[string] )
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[iteritems] ( identifier[self] . identifier[stats] ):
identifier[logging] . identifier[info] ( ... | def log_stats(self):
"""Print statistics into log."""
logging.info('Validation statistics: ')
for (k, v) in iteritems(self.stats):
logging.info('%s - %d valid out of %d total submissions', k, v[0], v[0] + v[1]) # depends on [control=['for'], data=[]] |
def list_certificate_signing_request(self, **kwargs):
"""
list or watch objects of kind CertificateSigningRequest
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_certificate_signing_re... | def function[list_certificate_signing_request, parameter[self]]:
constant[
list or watch objects of kind CertificateSigningRequest
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_certi... | keyword[def] identifier[list_certificate_signing_request] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] identifier[self... | def list_certificate_signing_request(self, **kwargs):
"""
list or watch objects of kind CertificateSigningRequest
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_certificate_signing_reques... |
def get_default_api_key(self, email, password):
"""
Get the default API key for a user.
:param email: The email of the user.
:type email: string
:param password: The user's password.
:type password: string
:returns: API key to confirm that it was fetched successf... | def function[get_default_api_key, parameter[self, email, password]]:
constant[
Get the default API key for a user.
:param email: The email of the user.
:type email: string
:param password: The user's password.
:type password: string
:returns: API key to confirm t... | keyword[def] identifier[get_default_api_key] ( identifier[self] , identifier[email] , identifier[password] ):
literal[string]
identifier[parameters] = identifier[dict] ()
identifier[parameters] [ literal[string] ]= identifier[email]
identifier[parameters] [ literal[string] ]= ide... | def get_default_api_key(self, email, password):
"""
Get the default API key for a user.
:param email: The email of the user.
:type email: string
:param password: The user's password.
:type password: string
:returns: API key to confirm that it was fetched successfully... |
def _read_data(self, fp_, header):
"""Read data block"""
nlines = int(header["block2"]['number_of_lines'][0])
ncols = int(header["block2"]['number_of_columns'][0])
return da.from_array(np.memmap(self.filename, offset=fp_.tell(),
dtype='<u2', shape=(... | def function[_read_data, parameter[self, fp_, header]]:
constant[Read data block]
variable[nlines] assign[=] call[name[int], parameter[call[call[call[name[header]][constant[block2]]][constant[number_of_lines]]][constant[0]]]]
variable[ncols] assign[=] call[name[int], parameter[call[call[call[nam... | keyword[def] identifier[_read_data] ( identifier[self] , identifier[fp_] , identifier[header] ):
literal[string]
identifier[nlines] = identifier[int] ( identifier[header] [ literal[string] ][ literal[string] ][ literal[int] ])
identifier[ncols] = identifier[int] ( identifier[header] [ lite... | def _read_data(self, fp_, header):
"""Read data block"""
nlines = int(header['block2']['number_of_lines'][0])
ncols = int(header['block2']['number_of_columns'][0])
return da.from_array(np.memmap(self.filename, offset=fp_.tell(), dtype='<u2', shape=(nlines, ncols), mode='r'), chunks=CHUNK_SIZE) |
def Save(self, filename, env):
"""
Saves all the options in the given file. This file can
then be used to load the options next run. This can be used
to create an option cache file.
filename - Name of the file to save into
env - the environment get the option values fr... | def function[Save, parameter[self, filename, env]]:
constant[
Saves all the options in the given file. This file can
then be used to load the options next run. This can be used
to create an option cache file.
filename - Name of the file to save into
env - the environme... | keyword[def] identifier[Save] ( identifier[self] , identifier[filename] , identifier[env] ):
literal[string]
keyword[try] :
identifier[fh] = identifier[open] ( identifier[filename] , literal[string] )
keyword[try] :
... | def Save(self, filename, env):
"""
Saves all the options in the given file. This file can
then be used to load the options next run. This can be used
to create an option cache file.
filename - Name of the file to save into
env - the environment get the option values from
... |
def sbytes2ilines(stream, encoding="utf8", closer=None):
"""
CONVERT A STREAM (with read() method) OF (ARBITRARY-SIZED) byte BLOCKS
TO A LINE (CR-DELIMITED) GENERATOR
"""
def read():
try:
while True:
bytes_ = stream.read(4096)
if not bytes_:
... | def function[sbytes2ilines, parameter[stream, encoding, closer]]:
constant[
CONVERT A STREAM (with read() method) OF (ARBITRARY-SIZED) byte BLOCKS
TO A LINE (CR-DELIMITED) GENERATOR
]
def function[read, parameter[]]:
<ast.Try object at 0x7da1b0a3bf40>
return[call[name[ibytes2ilin... | keyword[def] identifier[sbytes2ilines] ( identifier[stream] , identifier[encoding] = literal[string] , identifier[closer] = keyword[None] ):
literal[string]
keyword[def] identifier[read] ():
keyword[try] :
keyword[while] keyword[True] :
identifier[bytes_] = identifi... | def sbytes2ilines(stream, encoding='utf8', closer=None):
"""
CONVERT A STREAM (with read() method) OF (ARBITRARY-SIZED) byte BLOCKS
TO A LINE (CR-DELIMITED) GENERATOR
"""
def read():
try:
while True:
bytes_ = stream.read(4096)
if not bytes_:
... |
def named_module(name):
"""Returns a module given its name."""
module = __import__(name)
packages = name.split(".")[1:]
m = module
for p in packages:
m = getattr(m, p)
return m | def function[named_module, parameter[name]]:
constant[Returns a module given its name.]
variable[module] assign[=] call[name[__import__], parameter[name[name]]]
variable[packages] assign[=] call[call[name[name].split, parameter[constant[.]]]][<ast.Slice object at 0x7da1b09ed120>]
variabl... | keyword[def] identifier[named_module] ( identifier[name] ):
literal[string]
identifier[module] = identifier[__import__] ( identifier[name] )
identifier[packages] = identifier[name] . identifier[split] ( literal[string] )[ literal[int] :]
identifier[m] = identifier[module]
keyword[for] iden... | def named_module(name):
"""Returns a module given its name."""
module = __import__(name)
packages = name.split('.')[1:]
m = module
for p in packages:
m = getattr(m, p) # depends on [control=['for'], data=['p']]
return m |
def setup_splittable_dax_generated(workflow, input_tables, out_dir, tags):
'''
Function for setting up the splitting jobs as part of the workflow.
Parameters
-----------
workflow : pycbc.workflow.core.Workflow
The Workflow instance that the jobs will be added to.
input_tables : pycbc.wo... | def function[setup_splittable_dax_generated, parameter[workflow, input_tables, out_dir, tags]]:
constant[
Function for setting up the splitting jobs as part of the workflow.
Parameters
-----------
workflow : pycbc.workflow.core.Workflow
The Workflow instance that the jobs will be added ... | keyword[def] identifier[setup_splittable_dax_generated] ( identifier[workflow] , identifier[input_tables] , identifier[out_dir] , identifier[tags] ):
literal[string]
identifier[cp] = identifier[workflow] . identifier[cp]
keyword[try] :
identifier[num_splits] = identifier[cp] . identifi... | def setup_splittable_dax_generated(workflow, input_tables, out_dir, tags):
"""
Function for setting up the splitting jobs as part of the workflow.
Parameters
-----------
workflow : pycbc.workflow.core.Workflow
The Workflow instance that the jobs will be added to.
input_tables : pycbc.wo... |
def os_packages(metadata):
""" Installs operating system dependent packages """
family = metadata[0]
release = metadata[1]
#
if 'Amazon' in family and '2' not in release:
stdout_message('Identified Amazon Linux 1 os distro')
commands = [
'sudo yum -y update', 'sudo yum -y... | def function[os_packages, parameter[metadata]]:
constant[ Installs operating system dependent packages ]
variable[family] assign[=] call[name[metadata]][constant[0]]
variable[release] assign[=] call[name[metadata]][constant[1]]
if <ast.BoolOp object at 0x7da18f00caf0> begin[:]
... | keyword[def] identifier[os_packages] ( identifier[metadata] ):
literal[string]
identifier[family] = identifier[metadata] [ literal[int] ]
identifier[release] = identifier[metadata] [ literal[int] ]
keyword[if] literal[string] keyword[in] identifier[family] keyword[and] literal[string] ... | def os_packages(metadata):
""" Installs operating system dependent packages """
family = metadata[0]
release = metadata[1]
#
if 'Amazon' in family and '2' not in release:
stdout_message('Identified Amazon Linux 1 os distro')
commands = ['sudo yum -y update', 'sudo yum -y groupinstall... |
def set_volume(self, volume):
"""Set volume."""
for data in self._group.get('clients'):
client = self._server.client(data.get('id'))
yield from client.set_volume(volume, update_group=False)
client.update_volume({
'volume': {
'percen... | def function[set_volume, parameter[self, volume]]:
constant[Set volume.]
for taget[name[data]] in starred[call[name[self]._group.get, parameter[constant[clients]]]] begin[:]
variable[client] assign[=] call[name[self]._server.client, parameter[call[name[data].get, parameter[constant[id]]]... | keyword[def] identifier[set_volume] ( identifier[self] , identifier[volume] ):
literal[string]
keyword[for] identifier[data] keyword[in] identifier[self] . identifier[_group] . identifier[get] ( literal[string] ):
identifier[client] = identifier[self] . identifier[_server] . identif... | def set_volume(self, volume):
"""Set volume."""
for data in self._group.get('clients'):
client = self._server.client(data.get('id'))
yield from client.set_volume(volume, update_group=False)
client.update_volume({'volume': {'percent': volume, 'muted': client.muted}}) # depends on [contro... |
def get_id(test):
"""
Return the id of the given test, formatted as expected by nose.
:param test: a nose.case.Test instance
:return:
"""
test_id = test.id()
module_length = len(test.test.__module__)
return test_id[:module_length] + ":" + test_id[module_length + 1:] | def function[get_id, parameter[test]]:
constant[
Return the id of the given test, formatted as expected by nose.
:param test: a nose.case.Test instance
:return:
]
variable[test_id] assign[=] call[name[test].id, parameter[]]
variable[module_length] assign[=] call[name[len], parame... | keyword[def] identifier[get_id] ( identifier[test] ):
literal[string]
identifier[test_id] = identifier[test] . identifier[id] ()
identifier[module_length] = identifier[len] ( identifier[test] . identifier[test] . identifier[__module__] )
keyword[return] identifier[test_id] [: identifier[module_l... | def get_id(test):
"""
Return the id of the given test, formatted as expected by nose.
:param test: a nose.case.Test instance
:return:
"""
test_id = test.id()
module_length = len(test.test.__module__)
return test_id[:module_length] + ':' + test_id[module_length + 1:] |
def estimate(phenotype, G=None, K=None, covariates=None, overdispersion=True):
"""Estimate the so-called narrow-sense heritability.
It supports Bernoulli and Binomial phenotypes (see `outcome_type`).
The user must specifiy only one of the parameters G, K, and QS for
defining the genetic background.
... | def function[estimate, parameter[phenotype, G, K, covariates, overdispersion]]:
constant[Estimate the so-called narrow-sense heritability.
It supports Bernoulli and Binomial phenotypes (see `outcome_type`).
The user must specifiy only one of the parameters G, K, and QS for
defining the genetic back... | keyword[def] identifier[estimate] ( identifier[phenotype] , identifier[G] = keyword[None] , identifier[K] = keyword[None] , identifier[covariates] = keyword[None] , identifier[overdispersion] = keyword[True] ):
literal[string]
identifier[logger] = identifier[logging] . identifier[getLogger] ( identifier[__... | def estimate(phenotype, G=None, K=None, covariates=None, overdispersion=True):
"""Estimate the so-called narrow-sense heritability.
It supports Bernoulli and Binomial phenotypes (see `outcome_type`).
The user must specifiy only one of the parameters G, K, and QS for
defining the genetic background.
... |
def prefix(prefix):
"""Returns a dictionary of all environment variables starting with
the given prefix, lower cased and stripped.
"""
d = {}
e = lower_dict(environ.copy())
prefix = prefix.lower()
for k, v in e.items():
try:
if k.startswith(prefix):
k =... | def function[prefix, parameter[prefix]]:
constant[Returns a dictionary of all environment variables starting with
the given prefix, lower cased and stripped.
]
variable[d] assign[=] dictionary[[], []]
variable[e] assign[=] call[name[lower_dict], parameter[call[name[environ].copy, paramet... | keyword[def] identifier[prefix] ( identifier[prefix] ):
literal[string]
identifier[d] ={}
identifier[e] = identifier[lower_dict] ( identifier[environ] . identifier[copy] ())
identifier[prefix] = identifier[prefix] . identifier[lower] ()
keyword[for] identifier[k] , identifier[v] keyword... | def prefix(prefix):
"""Returns a dictionary of all environment variables starting with
the given prefix, lower cased and stripped.
"""
d = {}
e = lower_dict(environ.copy())
prefix = prefix.lower()
for (k, v) in e.items():
try:
if k.startswith(prefix):
k = ... |
def _from_dict(cls, _dict):
"""Initialize a Face object from a json dictionary."""
args = {}
if 'age' in _dict:
args['age'] = FaceAge._from_dict(_dict.get('age'))
if 'gender' in _dict:
args['gender'] = FaceGender._from_dict(_dict.get('gender'))
if 'face_lo... | def function[_from_dict, parameter[cls, _dict]]:
constant[Initialize a Face object from a json dictionary.]
variable[args] assign[=] dictionary[[], []]
if compare[constant[age] in name[_dict]] begin[:]
call[name[args]][constant[age]] assign[=] call[name[FaceAge]._from_dict, param... | keyword[def] identifier[_from_dict] ( identifier[cls] , identifier[_dict] ):
literal[string]
identifier[args] ={}
keyword[if] literal[string] keyword[in] identifier[_dict] :
identifier[args] [ literal[string] ]= identifier[FaceAge] . identifier[_from_dict] ( identifier[_dic... | def _from_dict(cls, _dict):
"""Initialize a Face object from a json dictionary."""
args = {}
if 'age' in _dict:
args['age'] = FaceAge._from_dict(_dict.get('age')) # depends on [control=['if'], data=['_dict']]
if 'gender' in _dict:
args['gender'] = FaceGender._from_dict(_dict.get('gender... |
def _fill_lookup_prop(self, testsuites_properties):
"""Fills the polarion-lookup-method property."""
if not self._lookup_prop:
raise Dump2PolarionException("Failed to set the 'polarion-lookup-method' property")
etree.SubElement(
testsuites_properties,
"proper... | def function[_fill_lookup_prop, parameter[self, testsuites_properties]]:
constant[Fills the polarion-lookup-method property.]
if <ast.UnaryOp object at 0x7da1b23d6080> begin[:]
<ast.Raise object at 0x7da1b23d62c0>
call[name[etree].SubElement, parameter[name[testsuites_properties], consta... | keyword[def] identifier[_fill_lookup_prop] ( identifier[self] , identifier[testsuites_properties] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_lookup_prop] :
keyword[raise] identifier[Dump2PolarionException] ( literal[string] )
identifier[etre... | def _fill_lookup_prop(self, testsuites_properties):
"""Fills the polarion-lookup-method property."""
if not self._lookup_prop:
raise Dump2PolarionException("Failed to set the 'polarion-lookup-method' property") # depends on [control=['if'], data=[]]
etree.SubElement(testsuites_properties, 'property... |
def _update_from_raw_data(self, raw_data, data_type_id=None, name=None,
description=None):
"""
Upload already serialized raw data and replace the existing dataset.
Parameters
----------
raw_data: bytes
Dataset contents to upload.
... | def function[_update_from_raw_data, parameter[self, raw_data, data_type_id, name, description]]:
constant[
Upload already serialized raw data and replace the existing dataset.
Parameters
----------
raw_data: bytes
Dataset contents to upload.
data_type_id : st... | keyword[def] identifier[_update_from_raw_data] ( identifier[self] , identifier[raw_data] , identifier[data_type_id] = keyword[None] , identifier[name] = keyword[None] ,
identifier[description] = keyword[None] ):
literal[string]
identifier[_not_none] ( literal[string] , identifier[raw_data] )
... | def _update_from_raw_data(self, raw_data, data_type_id=None, name=None, description=None):
"""
Upload already serialized raw data and replace the existing dataset.
Parameters
----------
raw_data: bytes
Dataset contents to upload.
data_type_id : str
Se... |
def config(self, configlet=None, plane='sdr', **attributes):
"""Configure the device.
This method applies configuration to the device.
Args:
configlet (text): The configuration template.
plane (text): sdr or admin
attributes (dict): The dictionary of attribu... | def function[config, parameter[self, configlet, plane]]:
constant[Configure the device.
This method applies configuration to the device.
Args:
configlet (text): The configuration template.
plane (text): sdr or admin
attributes (dict): The dictionary of attri... | keyword[def] identifier[config] ( identifier[self] , identifier[configlet] = keyword[None] , identifier[plane] = literal[string] ,** identifier[attributes] ):
literal[string]
identifier[begin] = identifier[time] . identifier[time] ()
identifier[label] = identifier[self] . identifier[_chain... | def config(self, configlet=None, plane='sdr', **attributes):
"""Configure the device.
This method applies configuration to the device.
Args:
configlet (text): The configuration template.
plane (text): sdr or admin
attributes (dict): The dictionary of attributes ... |
def begin_group(self, indent=0, open=''):
"""
Begin a group. If you want support for python < 2.5 which doesn't has
the with statement this is the preferred way:
p.begin_group(1, '{')
...
p.end_group(1, '}')
The python 2.5 expression would be this:
... | def function[begin_group, parameter[self, indent, open]]:
constant[
Begin a group. If you want support for python < 2.5 which doesn't has
the with statement this is the preferred way:
p.begin_group(1, '{')
...
p.end_group(1, '}')
The python 2.5 expr... | keyword[def] identifier[begin_group] ( identifier[self] , identifier[indent] = literal[int] , identifier[open] = literal[string] ):
literal[string]
keyword[if] identifier[open] :
identifier[self] . identifier[text] ( identifier[open] )
identifier[group] = identifier[Group] ( ... | def begin_group(self, indent=0, open=''):
"""
Begin a group. If you want support for python < 2.5 which doesn't has
the with statement this is the preferred way:
p.begin_group(1, '{')
...
p.end_group(1, '}')
The python 2.5 expression would be this:
... |
def new_plugin(self, config, *args, **kwargs):
"""
instantiate a plugin
creates the object, stores it in _instance
"""
typ = None
obj = None
# if type is defined, create a new instance
if 'type' in config:
typ = config['type']
# singl... | def function[new_plugin, parameter[self, config]]:
constant[
instantiate a plugin
creates the object, stores it in _instance
]
variable[typ] assign[=] constant[None]
variable[obj] assign[=] constant[None]
if compare[constant[type] in name[config]] begin[:]
... | keyword[def] identifier[new_plugin] ( identifier[self] , identifier[config] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[typ] = keyword[None]
identifier[obj] = keyword[None]
keyword[if] literal[string] keyword[in] identifier[config] :
... | def new_plugin(self, config, *args, **kwargs):
"""
instantiate a plugin
creates the object, stores it in _instance
"""
typ = None
obj = None
# if type is defined, create a new instance
if 'type' in config:
typ = config['type'] # depends on [control=['if'], data=['con... |
def encode_max_segments_accepted(arg):
"""Encode the maximum number of segments the device will accept, Section
20.1.2.4, and if the device says it can only accept one segment it shouldn't
say that it supports segmentation!"""
# unspecified
if not arg:
return 0
if arg > 64:
retu... | def function[encode_max_segments_accepted, parameter[arg]]:
constant[Encode the maximum number of segments the device will accept, Section
20.1.2.4, and if the device says it can only accept one segment it shouldn't
say that it supports segmentation!]
if <ast.UnaryOp object at 0x7da1b26adcf0> be... | keyword[def] identifier[encode_max_segments_accepted] ( identifier[arg] ):
literal[string]
keyword[if] keyword[not] identifier[arg] :
keyword[return] literal[int]
keyword[if] identifier[arg] > literal[int] :
keyword[return] literal[int]
keyword[for] ident... | def encode_max_segments_accepted(arg):
"""Encode the maximum number of segments the device will accept, Section
20.1.2.4, and if the device says it can only accept one segment it shouldn't
say that it supports segmentation!"""
# unspecified
if not arg:
return 0 # depends on [control=['if'],... |
def flatten_urls(self, urls):
"""
Function flatten urls for route grouping feature of glim.
Args
----
urls (dict): a dict of url definitions.
current_key (unknown type): a dict or a string marking the
current key that is used for recursive calls.
... | def function[flatten_urls, parameter[self, urls]]:
constant[
Function flatten urls for route grouping feature of glim.
Args
----
urls (dict): a dict of url definitions.
current_key (unknown type): a dict or a string marking the
current key that is used fo... | keyword[def] identifier[flatten_urls] ( identifier[self] , identifier[urls] ):
literal[string]
identifier[available_methods] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ]
identifier[ruleset] =[]
key... | def flatten_urls(self, urls):
"""
Function flatten urls for route grouping feature of glim.
Args
----
urls (dict): a dict of url definitions.
current_key (unknown type): a dict or a string marking the
current key that is used for recursive calls.
ru... |
def default_styles():
"""Generate default ODF styles."""
styles = {}
def _add_style(name, **kwargs):
styles[name] = _create_style(name, **kwargs)
_add_style('heading-1',
family='paragraph',
fontsize='24pt',
fontweight='bold',
)
_... | def function[default_styles, parameter[]]:
constant[Generate default ODF styles.]
variable[styles] assign[=] dictionary[[], []]
def function[_add_style, parameter[name]]:
call[name[styles]][name[name]] assign[=] call[name[_create_style], parameter[name[name]]]
call[name[_... | keyword[def] identifier[default_styles] ():
literal[string]
identifier[styles] ={}
keyword[def] identifier[_add_style] ( identifier[name] ,** identifier[kwargs] ):
identifier[styles] [ identifier[name] ]= identifier[_create_style] ( identifier[name] ,** identifier[kwargs] )
identifie... | def default_styles():
"""Generate default ODF styles."""
styles = {}
def _add_style(name, **kwargs):
styles[name] = _create_style(name, **kwargs)
_add_style('heading-1', family='paragraph', fontsize='24pt', fontweight='bold')
_add_style('heading-2', family='paragraph', fontsize='22pt', font... |
def patch(
self,
id,
name=None,
description=None,
whitelisted_container_task_types=None,
whitelisted_executable_task_types=None,
):
"""Partially updates a task whitelist on the saltant server.
Args:
id (int): The ID of the task whitelist.
... | def function[patch, parameter[self, id, name, description, whitelisted_container_task_types, whitelisted_executable_task_types]]:
constant[Partially updates a task whitelist on the saltant server.
Args:
id (int): The ID of the task whitelist.
name (str, optional): The name of th... | keyword[def] identifier[patch] (
identifier[self] ,
identifier[id] ,
identifier[name] = keyword[None] ,
identifier[description] = keyword[None] ,
identifier[whitelisted_container_task_types] = keyword[None] ,
identifier[whitelisted_executable_task_types] = keyword[None] ,
):
literal[string]
... | def patch(self, id, name=None, description=None, whitelisted_container_task_types=None, whitelisted_executable_task_types=None):
"""Partially updates a task whitelist on the saltant server.
Args:
id (int): The ID of the task whitelist.
name (str, optional): The name of the task whit... |
def get_relations(self, database, schema):
"""Case-insensitively yield all relations matching the given schema.
:param str schema: The case-insensitive schema name to list from.
:return List[BaseRelation]: The list of relations with the given
schema
"""
schema = _low... | def function[get_relations, parameter[self, database, schema]]:
constant[Case-insensitively yield all relations matching the given schema.
:param str schema: The case-insensitive schema name to list from.
:return List[BaseRelation]: The list of relations with the given
schema
... | keyword[def] identifier[get_relations] ( identifier[self] , identifier[database] , identifier[schema] ):
literal[string]
identifier[schema] = identifier[_lower] ( identifier[schema] )
keyword[with] identifier[self] . identifier[lock] :
identifier[results] =[
iden... | def get_relations(self, database, schema):
"""Case-insensitively yield all relations matching the given schema.
:param str schema: The case-insensitive schema name to list from.
:return List[BaseRelation]: The list of relations with the given
schema
"""
schema = _lower(schem... |
def t_B_SEQUENCE_COMPACT_START(self, t):
r"""
\-\ + (?= -\ )
# ^ ^ sequence indicator
| \-\ + (?= [\{\[]\ | [^:\n]*:\s )
# ^ ^ ^^^ map indicator
# ^ ^ flow indicator
"""
indent_status, curr_depth, n... | def function[t_B_SEQUENCE_COMPACT_START, parameter[self, t]]:
constant[
\-\ + (?= -\ )
# ^ ^ sequence indicator
| \-\ + (?= [\{\[]\ | [^:\n]*:\s )
# ^ ^ ^^^ map indicator
# ^ ^ flow indicator
]
<ast.... | keyword[def] identifier[t_B_SEQUENCE_COMPACT_START] ( identifier[self] , identifier[t] ):
literal[string]
identifier[indent_status] , identifier[curr_depth] , identifier[next_depth] = identifier[self] . identifier[get_indent_status] ( identifier[t] )
keyword[if] identifier[indent_status... | def t_B_SEQUENCE_COMPACT_START(self, t):
"""
\\-\\ + (?= -\\ )
# ^ ^ sequence indicator
| \\-\\ + (?= [\\{\\[]\\ | [^:\\n]*:\\s )
# ^ ^ ^^^ map indicator
# ^ ^ flow indicator
"""
(indent_status, curr_depth, ... |
def delete(uid):
'''
Delete by uid
'''
q_u1 = TabPostHist.delete().where(TabPostHist.post_id == uid)
q_u1.execute()
q_u2 = TabRel.delete().where(TabRel.post_f_id == uid or TabRel.post_t_id == uid)
q_u2.execute()
q_u3 = TabCollect.delete().where(TabCollect... | def function[delete, parameter[uid]]:
constant[
Delete by uid
]
variable[q_u1] assign[=] call[call[name[TabPostHist].delete, parameter[]].where, parameter[compare[name[TabPostHist].post_id equal[==] name[uid]]]]
call[name[q_u1].execute, parameter[]]
variable[q_u2] assign[... | keyword[def] identifier[delete] ( identifier[uid] ):
literal[string]
identifier[q_u1] = identifier[TabPostHist] . identifier[delete] (). identifier[where] ( identifier[TabPostHist] . identifier[post_id] == identifier[uid] )
identifier[q_u1] . identifier[execute] ()
identifier[q_u... | def delete(uid):
"""
Delete by uid
"""
q_u1 = TabPostHist.delete().where(TabPostHist.post_id == uid)
q_u1.execute()
q_u2 = TabRel.delete().where(TabRel.post_f_id == uid or TabRel.post_t_id == uid)
q_u2.execute()
q_u3 = TabCollect.delete().where(TabCollect.post_id == uid)
q_u3... |
def cancel(self, tid, session):
'''taobao.logistics.online.cancel 取消物流订单接口
调此接口取消发货的订单,重新选择物流公司发货。前提是物流公司未揽收货物。对未发货和已经被物流公司揽收的物流订单,是不能取消的。'''
request = TOPRequest('taobao.logistics.online.cancel')
request['tid'] = tid
self.create(self.execute(request, session), fields = ... | def function[cancel, parameter[self, tid, session]]:
constant[taobao.logistics.online.cancel 取消物流订单接口
调此接口取消发货的订单,重新选择物流公司发货。前提是物流公司未揽收货物。对未发货和已经被物流公司揽收的物流订单,是不能取消的。]
variable[request] assign[=] call[name[TOPRequest], parameter[constant[taobao.logistics.online.cancel]]]
call[nam... | keyword[def] identifier[cancel] ( identifier[self] , identifier[tid] , identifier[session] ):
literal[string]
identifier[request] = identifier[TOPRequest] ( literal[string] )
identifier[request] [ literal[string] ]= identifier[tid]
identifier[self] . identifier[create] ( identifi... | def cancel(self, tid, session):
"""taobao.logistics.online.cancel 取消物流订单接口
调此接口取消发货的订单,重新选择物流公司发货。前提是物流公司未揽收货物。对未发货和已经被物流公司揽收的物流订单,是不能取消的。"""
request = TOPRequest('taobao.logistics.online.cancel')
request['tid'] = tid
self.create(self.execute(request, session), fields=['is_success', 'mo... |
def convolutional_layer_series(initial_size, layer_sequence):
""" Execute a series of convolutional layer transformations to the size number """
size = initial_size
for filter_size, padding, stride in layer_sequence:
size = convolution_size_equation(size, filter_size, padding, stride)
return s... | def function[convolutional_layer_series, parameter[initial_size, layer_sequence]]:
constant[ Execute a series of convolutional layer transformations to the size number ]
variable[size] assign[=] name[initial_size]
for taget[tuple[[<ast.Name object at 0x7da18bcca590>, <ast.Name object at 0x7da18b... | keyword[def] identifier[convolutional_layer_series] ( identifier[initial_size] , identifier[layer_sequence] ):
literal[string]
identifier[size] = identifier[initial_size]
keyword[for] identifier[filter_size] , identifier[padding] , identifier[stride] keyword[in] identifier[layer_sequence] :
... | def convolutional_layer_series(initial_size, layer_sequence):
""" Execute a series of convolutional layer transformations to the size number """
size = initial_size
for (filter_size, padding, stride) in layer_sequence:
size = convolution_size_equation(size, filter_size, padding, stride) # depends o... |
def get_body_region(defined):
"""Return the start and end offsets of function body"""
scope = defined.get_scope()
pymodule = defined.get_module()
lines = pymodule.lines
node = defined.get_ast()
start_line = node.lineno
if defined.get_doc() is None:
start_line = node.body[0].lineno
... | def function[get_body_region, parameter[defined]]:
constant[Return the start and end offsets of function body]
variable[scope] assign[=] call[name[defined].get_scope, parameter[]]
variable[pymodule] assign[=] call[name[defined].get_module, parameter[]]
variable[lines] assign[=] name[pymo... | keyword[def] identifier[get_body_region] ( identifier[defined] ):
literal[string]
identifier[scope] = identifier[defined] . identifier[get_scope] ()
identifier[pymodule] = identifier[defined] . identifier[get_module] ()
identifier[lines] = identifier[pymodule] . identifier[lines]
identifier... | def get_body_region(defined):
"""Return the start and end offsets of function body"""
scope = defined.get_scope()
pymodule = defined.get_module()
lines = pymodule.lines
node = defined.get_ast()
start_line = node.lineno
if defined.get_doc() is None:
start_line = node.body[0].lineno #... |
def getTemplates(self, workitems, template_folder=None,
template_names=None, keep=False, encoding="UTF-8"):
"""Get templates from a group of to-be-copied :class:`Workitems` and
write them to files named after the names in `template_names`
respectively.
:param workit... | def function[getTemplates, parameter[self, workitems, template_folder, template_names, keep, encoding]]:
constant[Get templates from a group of to-be-copied :class:`Workitems` and
write them to files named after the names in `template_names`
respectively.
:param workitems: a :class:`lis... | keyword[def] identifier[getTemplates] ( identifier[self] , identifier[workitems] , identifier[template_folder] = keyword[None] ,
identifier[template_names] = keyword[None] , identifier[keep] = keyword[False] , identifier[encoding] = literal[string] ):
literal[string]
keyword[if] ( keyword[not] i... | def getTemplates(self, workitems, template_folder=None, template_names=None, keep=False, encoding='UTF-8'):
"""Get templates from a group of to-be-copied :class:`Workitems` and
write them to files named after the names in `template_names`
respectively.
:param workitems: a :class:`list`/:cla... |
def set_contents_from_file(self, fp, headers=None, replace=True,
cb=None, num_cb=10, policy=None, md5=None,
res_upload_handler=None, size=None):
"""
Store an object in GS using the name of the Key object as the
key in GS and the conte... | def function[set_contents_from_file, parameter[self, fp, headers, replace, cb, num_cb, policy, md5, res_upload_handler, size]]:
constant[
Store an object in GS using the name of the Key object as the
key in GS and the contents of the file pointed to by 'fp' as the
contents.
:typ... | keyword[def] identifier[set_contents_from_file] ( identifier[self] , identifier[fp] , identifier[headers] = keyword[None] , identifier[replace] = keyword[True] ,
identifier[cb] = keyword[None] , identifier[num_cb] = literal[int] , identifier[policy] = keyword[None] , identifier[md5] = keyword[None] ,
identifier[res... | def set_contents_from_file(self, fp, headers=None, replace=True, cb=None, num_cb=10, policy=None, md5=None, res_upload_handler=None, size=None):
"""
Store an object in GS using the name of the Key object as the
key in GS and the contents of the file pointed to by 'fp' as the
contents.
... |
def sentinel2_toa_cloud_mask(input_img):
"""Extract cloud mask from the Sentinel 2 TOA QA60 band
Parameters
----------
input_img : ee.Image
Image from the COPERNICUS/S2 collection with a QA60 band.
Returns
-------
ee.Image
Notes
-----
Output image is structured to be a... | def function[sentinel2_toa_cloud_mask, parameter[input_img]]:
constant[Extract cloud mask from the Sentinel 2 TOA QA60 band
Parameters
----------
input_img : ee.Image
Image from the COPERNICUS/S2 collection with a QA60 band.
Returns
-------
ee.Image
Notes
-----
Out... | keyword[def] identifier[sentinel2_toa_cloud_mask] ( identifier[input_img] ):
literal[string]
identifier[qa_img] = identifier[input_img] . identifier[select] ([ literal[string] ])
identifier[cloud_mask] = identifier[qa_img] . identifier[rightShift] ( literal[int] ). identifier[bitwiseAnd] ( literal[int... | def sentinel2_toa_cloud_mask(input_img):
"""Extract cloud mask from the Sentinel 2 TOA QA60 band
Parameters
----------
input_img : ee.Image
Image from the COPERNICUS/S2 collection with a QA60 band.
Returns
-------
ee.Image
Notes
-----
Output image is structured to be a... |
def get_grade_entry(self, grade_entry_id):
"""Gets the ``GradeEntry`` specified by its ``Id``.
arg: grade_entry_id (osid.id.Id): ``Id`` of the
``GradeEntry``
return: (osid.grading.GradeEntry) - the grade entry
raise: NotFound - ``grade_entry_id`` not found
ra... | def function[get_grade_entry, parameter[self, grade_entry_id]]:
constant[Gets the ``GradeEntry`` specified by its ``Id``.
arg: grade_entry_id (osid.id.Id): ``Id`` of the
``GradeEntry``
return: (osid.grading.GradeEntry) - the grade entry
raise: NotFound - ``grade_entr... | keyword[def] identifier[get_grade_entry] ( identifier[self] , identifier[grade_entry_id] ):
literal[string]
identifier[collection] = identifier[JSONClientValidated] ( literal[string] ,
identifier[collection] = literal[string] ,
identifier[runtime] = iden... | def get_grade_entry(self, grade_entry_id):
"""Gets the ``GradeEntry`` specified by its ``Id``.
arg: grade_entry_id (osid.id.Id): ``Id`` of the
``GradeEntry``
return: (osid.grading.GradeEntry) - the grade entry
raise: NotFound - ``grade_entry_id`` not found
raise:... |
def prepare_files(self, finder):
"""
Prepare process. Create temp directories, download and/or unpack files.
"""
from pip.index import Link
unnamed = list(self.unnamed_requirements)
reqs = list(self.requirements.values())
while reqs or unnamed:
if unn... | def function[prepare_files, parameter[self, finder]]:
constant[
Prepare process. Create temp directories, download and/or unpack files.
]
from relative_module[pip.index] import module[Link]
variable[unnamed] assign[=] call[name[list], parameter[name[self].unnamed_requirements]]
... | keyword[def] identifier[prepare_files] ( identifier[self] , identifier[finder] ):
literal[string]
keyword[from] identifier[pip] . identifier[index] keyword[import] identifier[Link]
identifier[unnamed] = identifier[list] ( identifier[self] . identifier[unnamed_requirements] )
... | def prepare_files(self, finder):
"""
Prepare process. Create temp directories, download and/or unpack files.
"""
from pip.index import Link
unnamed = list(self.unnamed_requirements)
reqs = list(self.requirements.values())
while reqs or unnamed:
if unnamed:
req_to_... |
def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split):
"""Generate samples of the encoded frames with possible extra data.
By default this function just encodes the numpy array returned as "frame"
from `self.generate_samples` into a PNG image. Override this function to
get other encoding... | def function[generate_encoded_samples, parameter[self, data_dir, tmp_dir, dataset_split]]:
constant[Generate samples of the encoded frames with possible extra data.
By default this function just encodes the numpy array returned as "frame"
from `self.generate_samples` into a PNG image. Override this fun... | keyword[def] identifier[generate_encoded_samples] ( identifier[self] , identifier[data_dir] , identifier[tmp_dir] , identifier[dataset_split] ):
literal[string]
identifier[writer] = keyword[None]
keyword[with] identifier[tf] . identifier[Graph] (). identifier[as_default] ():
identifier[image... | def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split):
"""Generate samples of the encoded frames with possible extra data.
By default this function just encodes the numpy array returned as "frame"
from `self.generate_samples` into a PNG image. Override this function to
get other encoding... |
def compile_rename_column(self, blueprint, command, connection):
"""
Compile a rename column command.
:param blueprint: The blueprint
:type blueprint: Blueprint
:param command: The command
:type command: Fluent
:param connection: The connection
:type co... | def function[compile_rename_column, parameter[self, blueprint, command, connection]]:
constant[
Compile a rename column command.
:param blueprint: The blueprint
:type blueprint: Blueprint
:param command: The command
:type command: Fluent
:param connection: The ... | keyword[def] identifier[compile_rename_column] ( identifier[self] , identifier[blueprint] , identifier[command] , identifier[connection] ):
literal[string]
identifier[table] = identifier[self] . identifier[get_table_prefix] ()+ identifier[blueprint] . identifier[get_table] ()
identifier[c... | def compile_rename_column(self, blueprint, command, connection):
"""
Compile a rename column command.
:param blueprint: The blueprint
:type blueprint: Blueprint
:param command: The command
:type command: Fluent
:param connection: The connection
:type connec... |
def remove_timezone(cls, timestr):
"""Completely remove timezone information, if any.
:return: the new string if timezone was found, `None` otherwise
"""
if re.match(r".*[\-+]?\d{2}:\d{2}$", timestr):
return re.sub(
r"(.*)(\s[\+-]?\d\d:\d\d)$",
... | def function[remove_timezone, parameter[cls, timestr]]:
constant[Completely remove timezone information, if any.
:return: the new string if timezone was found, `None` otherwise
]
if call[name[re].match, parameter[constant[.*[\-+]?\d{2}:\d{2}$], name[timestr]]] begin[:]
return[ca... | keyword[def] identifier[remove_timezone] ( identifier[cls] , identifier[timestr] ):
literal[string]
keyword[if] identifier[re] . identifier[match] ( literal[string] , identifier[timestr] ):
keyword[return] identifier[re] . identifier[sub] (
literal[string] ,
... | def remove_timezone(cls, timestr):
"""Completely remove timezone information, if any.
:return: the new string if timezone was found, `None` otherwise
"""
if re.match('.*[\\-+]?\\d{2}:\\d{2}$', timestr):
return re.sub('(.*)(\\s[\\+-]?\\d\\d:\\d\\d)$', '\\1', timestr) # depends on [contr... |
def imread(filename, masked = False):
"""Convenience function that uses the QImage_ constructor to read an
image from the given file and return an `rgb_view` of the result.
This is intentionally similar to scipy.ndimage.imread (which uses
PIL), scipy.misc.imread, or matplotlib.pyplot.imread (using PIL
... | def function[imread, parameter[filename, masked]]:
constant[Convenience function that uses the QImage_ constructor to read an
image from the given file and return an `rgb_view` of the result.
This is intentionally similar to scipy.ndimage.imread (which uses
PIL), scipy.misc.imread, or matplotlib.pyp... | keyword[def] identifier[imread] ( identifier[filename] , identifier[masked] = keyword[False] ):
literal[string]
identifier[qImage] = identifier[_qt] . identifier[QImage] ( identifier[filename] )
keyword[if] identifier[qImage] . identifier[isNull] ():
keyword[raise] identifier[IOError] ( li... | def imread(filename, masked=False):
"""Convenience function that uses the QImage_ constructor to read an
image from the given file and return an `rgb_view` of the result.
This is intentionally similar to scipy.ndimage.imread (which uses
PIL), scipy.misc.imread, or matplotlib.pyplot.imread (using PIL
... |
def setup(self):
"""
We need to use socket._fileobject Because SSL.Connection
doesn't have a 'dup'. Not exactly sure WHY this is, but
this is backed up by comments in socket.py and SSL/connection.c
"""
self.connection = self.request # for doPOST
self.rfile = sock... | def function[setup, parameter[self]]:
constant[
We need to use socket._fileobject Because SSL.Connection
doesn't have a 'dup'. Not exactly sure WHY this is, but
this is backed up by comments in socket.py and SSL/connection.c
]
name[self].connection assign[=] name[self].re... | keyword[def] identifier[setup] ( identifier[self] ):
literal[string]
identifier[self] . identifier[connection] = identifier[self] . identifier[request]
identifier[self] . identifier[rfile] = identifier[socket] . identifier[_fileobject] ( identifier[self] . identifier[request] , literal[st... | def setup(self):
"""
We need to use socket._fileobject Because SSL.Connection
doesn't have a 'dup'. Not exactly sure WHY this is, but
this is backed up by comments in socket.py and SSL/connection.c
"""
self.connection = self.request # for doPOST
self.rfile = socket._fileobje... |
def add_rect(img, box, color=None, thickness=1):
"""
Draws a bounding box inside the image.
:param img: Input image
:param box: Box object that defines the bounding box.
:param color: Color of the box
:param thickness: Thickness of line
:return: Rectangle added image
"""
if color is... | def function[add_rect, parameter[img, box, color, thickness]]:
constant[
Draws a bounding box inside the image.
:param img: Input image
:param box: Box object that defines the bounding box.
:param color: Color of the box
:param thickness: Thickness of line
:return: Rectangle added image... | keyword[def] identifier[add_rect] ( identifier[img] , identifier[box] , identifier[color] = keyword[None] , identifier[thickness] = literal[int] ):
literal[string]
keyword[if] identifier[color] keyword[is] keyword[None] :
identifier[color] = identifier[COL_GRAY]
identifier[box] = identif... | def add_rect(img, box, color=None, thickness=1):
"""
Draws a bounding box inside the image.
:param img: Input image
:param box: Box object that defines the bounding box.
:param color: Color of the box
:param thickness: Thickness of line
:return: Rectangle added image
"""
if color is... |
def reset_attr_by_path(self, field_path):
"""
It restores original values for fields looked up by field path.
Field path is dot-formatted string path: ``parent_field.child_field``.
:param field_path: field path. It allows ``*`` as wildcard.
:type field_path: str
"""
... | def function[reset_attr_by_path, parameter[self, field_path]]:
constant[
It restores original values for fields looked up by field path.
Field path is dot-formatted string path: ``parent_field.child_field``.
:param field_path: field path. It allows ``*`` as wildcard.
:type field... | keyword[def] identifier[reset_attr_by_path] ( identifier[self] , identifier[field_path] ):
literal[string]
identifier[fields] , identifier[next_field] = identifier[self] . identifier[_get_fields_by_path] ( identifier[field_path] )
keyword[for] identifier[field] keyword[in] identifier[fi... | def reset_attr_by_path(self, field_path):
"""
It restores original values for fields looked up by field path.
Field path is dot-formatted string path: ``parent_field.child_field``.
:param field_path: field path. It allows ``*`` as wildcard.
:type field_path: str
"""
(fie... |
def _find_executable_task_instances(self, simple_dag_bag, states, session=None):
"""
Finds TIs that are ready for execution with respect to pool limits,
dag concurrency, executor state, and priority.
:param simple_dag_bag: TaskInstances associated with DAGs in the
simple_dag... | def function[_find_executable_task_instances, parameter[self, simple_dag_bag, states, session]]:
constant[
Finds TIs that are ready for execution with respect to pool limits,
dag concurrency, executor state, and priority.
:param simple_dag_bag: TaskInstances associated with DAGs in the
... | keyword[def] identifier[_find_executable_task_instances] ( identifier[self] , identifier[simple_dag_bag] , identifier[states] , identifier[session] = keyword[None] ):
literal[string]
identifier[executable_tis] =[]
identifier[TI] = identifier[models] . identifier... | def _find_executable_task_instances(self, simple_dag_bag, states, session=None):
"""
Finds TIs that are ready for execution with respect to pool limits,
dag concurrency, executor state, and priority.
:param simple_dag_bag: TaskInstances associated with DAGs in the
simple_dag_bag... |
def move_edge_target(self, edge_id, node_a):
"""Moves an edge so that it targets node_a."""
# Grab the edge
edge = self.get_edge(edge_id)
# Alter the vertices
edge['vertices'] = (edge['vertices'][0], node_a) | def function[move_edge_target, parameter[self, edge_id, node_a]]:
constant[Moves an edge so that it targets node_a.]
variable[edge] assign[=] call[name[self].get_edge, parameter[name[edge_id]]]
call[name[edge]][constant[vertices]] assign[=] tuple[[<ast.Subscript object at 0x7da1b28f3c10>, <ast.N... | keyword[def] identifier[move_edge_target] ( identifier[self] , identifier[edge_id] , identifier[node_a] ):
literal[string]
identifier[edge] = identifier[self] . identifier[get_edge] ( identifier[edge_id] )
identifier[edge] [ literal[string] ]=( identifier[edge] [ literal... | def move_edge_target(self, edge_id, node_a):
"""Moves an edge so that it targets node_a."""
# Grab the edge
edge = self.get_edge(edge_id)
# Alter the vertices
edge['vertices'] = (edge['vertices'][0], node_a) |
def defaults(self):
"""Return the defaults, with their values interpolated (with the
defaults dict itself)
Mainly to support defaults using values such as %(here)s
"""
defaults = ConfigParser.defaults(self).copy()
for key, val in iteritems(defaults):
defaults... | def function[defaults, parameter[self]]:
constant[Return the defaults, with their values interpolated (with the
defaults dict itself)
Mainly to support defaults using values such as %(here)s
]
variable[defaults] assign[=] call[call[name[ConfigParser].defaults, parameter[name[sel... | keyword[def] identifier[defaults] ( identifier[self] ):
literal[string]
identifier[defaults] = identifier[ConfigParser] . identifier[defaults] ( identifier[self] ). identifier[copy] ()
keyword[for] identifier[key] , identifier[val] keyword[in] identifier[iteritems] ( identifier[defaults... | def defaults(self):
"""Return the defaults, with their values interpolated (with the
defaults dict itself)
Mainly to support defaults using values such as %(here)s
"""
defaults = ConfigParser.defaults(self).copy()
for (key, val) in iteritems(defaults):
defaults[key] = self.g... |
def transition_cycle(n_states, prob):
'''Construct a cyclic transition matrix over `n_states`.
The transition matrix will have the following properties:
- `transition[i, i] = p`
- `transition[i, i + 1] = (1 - p)`
This type of transition matrix is appropriate for state spaces
with cycl... | def function[transition_cycle, parameter[n_states, prob]]:
constant[Construct a cyclic transition matrix over `n_states`.
The transition matrix will have the following properties:
- `transition[i, i] = p`
- `transition[i, i + 1] = (1 - p)`
This type of transition matrix is appropriate... | keyword[def] identifier[transition_cycle] ( identifier[n_states] , identifier[prob] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[n_states] , identifier[int] ) keyword[or] identifier[n_states] <= literal[int] :
keyword[raise] identifier[ParameterError] ( lite... | def transition_cycle(n_states, prob):
"""Construct a cyclic transition matrix over `n_states`.
The transition matrix will have the following properties:
- `transition[i, i] = p`
- `transition[i, i + 1] = (1 - p)`
This type of transition matrix is appropriate for state spaces
with cycl... |
def timeit(func):
"""
Decorator that logs the cost time of a function.
"""
@wraps(func)
def wrapped_func(*args, **kwargs):
start = timer()
result = func(*args, **kwargs)
cost = timer() - start
logger.debug('<method: %s> finished in %2.2f sec' % (func.__name__, cost... | def function[timeit, parameter[func]]:
constant[
Decorator that logs the cost time of a function.
]
def function[wrapped_func, parameter[]]:
variable[start] assign[=] call[name[timer], parameter[]]
variable[result] assign[=] call[name[func], parameter[<ast.Starred... | keyword[def] identifier[timeit] ( identifier[func] ):
literal[string]
@ identifier[wraps] ( identifier[func] )
keyword[def] identifier[wrapped_func] (* identifier[args] ,** identifier[kwargs] ):
identifier[start] = identifier[timer] ()
identifier[result] = identifier[func] (* identif... | def timeit(func):
"""
Decorator that logs the cost time of a function.
"""
@wraps(func)
def wrapped_func(*args, **kwargs):
start = timer()
result = func(*args, **kwargs)
cost = timer() - start
logger.debug('<method: %s> finished in %2.2f sec' % (func.__name__, cost))... |
def verify_integrity(self):
"""Verifies that all required functions been injected."""
if not self.__integrity_check:
if not self.__appid:
raise Exception('U2F_APPID was not defined! Please define it in configuration file.')
if self.__facets_enabled and not len(se... | def function[verify_integrity, parameter[self]]:
constant[Verifies that all required functions been injected.]
if <ast.UnaryOp object at 0x7da20e9b0fd0> begin[:]
if <ast.UnaryOp object at 0x7da20e9b1ab0> begin[:]
<ast.Raise object at 0x7da20e9b1f30>
if <ast.Bo... | keyword[def] identifier[verify_integrity] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[__integrity_check] :
keyword[if] keyword[not] identifier[self] . identifier[__appid] :
keyword[raise] identifier[Exception] ( lit... | def verify_integrity(self):
"""Verifies that all required functions been injected."""
if not self.__integrity_check:
if not self.__appid:
raise Exception('U2F_APPID was not defined! Please define it in configuration file.') # depends on [control=['if'], data=[]]
if self.__facets_ena... |
def replace_coord(arr, old_dim, new_dim, new_coord):
"""Replace a coordinate with new one; new and old must have same shape."""
new_arr = arr.rename({old_dim: new_dim})
new_arr[new_dim] = new_coord
return new_arr | def function[replace_coord, parameter[arr, old_dim, new_dim, new_coord]]:
constant[Replace a coordinate with new one; new and old must have same shape.]
variable[new_arr] assign[=] call[name[arr].rename, parameter[dictionary[[<ast.Name object at 0x7da1b0464880>], [<ast.Name object at 0x7da1b0464850>]]]]... | keyword[def] identifier[replace_coord] ( identifier[arr] , identifier[old_dim] , identifier[new_dim] , identifier[new_coord] ):
literal[string]
identifier[new_arr] = identifier[arr] . identifier[rename] ({ identifier[old_dim] : identifier[new_dim] })
identifier[new_arr] [ identifier[new_dim] ]= identi... | def replace_coord(arr, old_dim, new_dim, new_coord):
"""Replace a coordinate with new one; new and old must have same shape."""
new_arr = arr.rename({old_dim: new_dim})
new_arr[new_dim] = new_coord
return new_arr |
def _display_stream(normalized_data, stream):
"""
print stream message from docker-py stream.
"""
try:
stream.write(normalized_data['stream'])
except UnicodeEncodeError:
stream.write(normalized_data['stream'].encode("utf-8")) | def function[_display_stream, parameter[normalized_data, stream]]:
constant[
print stream message from docker-py stream.
]
<ast.Try object at 0x7da18f813730> | keyword[def] identifier[_display_stream] ( identifier[normalized_data] , identifier[stream] ):
literal[string]
keyword[try] :
identifier[stream] . identifier[write] ( identifier[normalized_data] [ literal[string] ])
keyword[except] identifier[UnicodeEncodeError] :
identifier[stream]... | def _display_stream(normalized_data, stream):
"""
print stream message from docker-py stream.
"""
try:
stream.write(normalized_data['stream']) # depends on [control=['try'], data=[]]
except UnicodeEncodeError:
stream.write(normalized_data['stream'].encode('utf-8')) # depends on [co... |
def formMarkup(self, realm, return_to=None, immediate=False,
form_tag_attrs=None):
"""Get html for a form to submit this request to the IDP.
@param form_tag_attrs: Dictionary of attributes to be added to
the form tag. 'accept-charset' and 'enctype' have defaults
that... | def function[formMarkup, parameter[self, realm, return_to, immediate, form_tag_attrs]]:
constant[Get html for a form to submit this request to the IDP.
@param form_tag_attrs: Dictionary of attributes to be added to
the form tag. 'accept-charset' and 'enctype' have defaults
that ... | keyword[def] identifier[formMarkup] ( identifier[self] , identifier[realm] , identifier[return_to] = keyword[None] , identifier[immediate] = keyword[False] ,
identifier[form_tag_attrs] = keyword[None] ):
literal[string]
identifier[message] = identifier[self] . identifier[getMessage] ( identifier[r... | def formMarkup(self, realm, return_to=None, immediate=False, form_tag_attrs=None):
"""Get html for a form to submit this request to the IDP.
@param form_tag_attrs: Dictionary of attributes to be added to
the form tag. 'accept-charset' and 'enctype' have defaults
that can be overridd... |
def _parse_extra(self, fp):
""" Parse and store the config comments and create maps for dot notion lookup """
comment = ''
section = ''
fp.seek(0)
for line in fp:
line = line.rstrip()
if not line:
if comment:
comment ... | def function[_parse_extra, parameter[self, fp]]:
constant[ Parse and store the config comments and create maps for dot notion lookup ]
variable[comment] assign[=] constant[]
variable[section] assign[=] constant[]
call[name[fp].seek, parameter[constant[0]]]
for taget[name[line]] i... | keyword[def] identifier[_parse_extra] ( identifier[self] , identifier[fp] ):
literal[string]
identifier[comment] = literal[string]
identifier[section] = literal[string]
identifier[fp] . identifier[seek] ( literal[int] )
keyword[for] identifier[line] keyword[in] ide... | def _parse_extra(self, fp):
""" Parse and store the config comments and create maps for dot notion lookup """
comment = ''
section = ''
fp.seek(0)
for line in fp:
line = line.rstrip()
if not line:
if comment:
comment += '\n' # depends on [control=['if'], ... |
def set_trial_config(experiment_config, port, config_file_name):
'''set trial configuration'''
request_data = dict()
request_data['trial_config'] = experiment_config['trial']
response = rest_put(cluster_metadata_url(port), json.dumps(request_data), REST_TIME_OUT)
if check_response(response):
... | def function[set_trial_config, parameter[experiment_config, port, config_file_name]]:
constant[set trial configuration]
variable[request_data] assign[=] call[name[dict], parameter[]]
call[name[request_data]][constant[trial_config]] assign[=] call[name[experiment_config]][constant[trial]]
... | keyword[def] identifier[set_trial_config] ( identifier[experiment_config] , identifier[port] , identifier[config_file_name] ):
literal[string]
identifier[request_data] = identifier[dict] ()
identifier[request_data] [ literal[string] ]= identifier[experiment_config] [ literal[string] ]
identifier[... | def set_trial_config(experiment_config, port, config_file_name):
"""set trial configuration"""
request_data = dict()
request_data['trial_config'] = experiment_config['trial']
response = rest_put(cluster_metadata_url(port), json.dumps(request_data), REST_TIME_OUT)
if check_response(response):
... |
def to_numpy(self, dtype=None, copy=False):
"""Convert the DataFrame to a NumPy array.
Args:
dtype: The dtype to pass to numpy.asarray()
copy: Whether to ensure that the returned value is a not a view on another
array.
Returns:
A num... | def function[to_numpy, parameter[self, dtype, copy]]:
constant[Convert the DataFrame to a NumPy array.
Args:
dtype: The dtype to pass to numpy.asarray()
copy: Whether to ensure that the returned value is a not a view on another
array.
Returns:
... | keyword[def] identifier[to_numpy] ( identifier[self] , identifier[dtype] = keyword[None] , identifier[copy] = keyword[False] ):
literal[string]
keyword[return] identifier[self] . identifier[_default_to_pandas] ( literal[string] , identifier[dtype] = identifier[dtype] , identifier[copy] = identif... | def to_numpy(self, dtype=None, copy=False):
"""Convert the DataFrame to a NumPy array.
Args:
dtype: The dtype to pass to numpy.asarray()
copy: Whether to ensure that the returned value is a not a view on another
array.
Returns:
A numpy array.
... |
def delete(self, key: str) -> None:
"""
Deletes a setting from this object's storage.
The write to the database is performed immediately and the cache in the cache backend is flushed.
The cache within this object will be updated correctly.
"""
if key in self._wri... | def function[delete, parameter[self, key]]:
constant[
Deletes a setting from this object's storage.
The write to the database is performed immediately and the cache in the cache backend is flushed.
The cache within this object will be updated correctly.
]
if comp... | keyword[def] identifier[delete] ( identifier[self] , identifier[key] : identifier[str] )-> keyword[None] :
literal[string]
keyword[if] identifier[key] keyword[in] identifier[self] . identifier[_write_cache] ():
identifier[self] . identifier[_write_cache] ()[ identifier[key] ]. ident... | def delete(self, key: str) -> None:
"""
Deletes a setting from this object's storage.
The write to the database is performed immediately and the cache in the cache backend is flushed.
The cache within this object will be updated correctly.
"""
if key in self._write_cache... |
def abort(self, frame):
"""
Handles ABORT command: Rolls back specified transaction.
"""
if not frame.transaction:
raise ProtocolError("Missing transaction for ABORT command.")
if not frame.transaction in self.engine.transactions:
raise ProtocolError("Inv... | def function[abort, parameter[self, frame]]:
constant[
Handles ABORT command: Rolls back specified transaction.
]
if <ast.UnaryOp object at 0x7da1b19383d0> begin[:]
<ast.Raise object at 0x7da1b193ada0>
if <ast.UnaryOp object at 0x7da1b193ab60> begin[:]
<ast.Raise ... | keyword[def] identifier[abort] ( identifier[self] , identifier[frame] ):
literal[string]
keyword[if] keyword[not] identifier[frame] . identifier[transaction] :
keyword[raise] identifier[ProtocolError] ( literal[string] )
keyword[if] keyword[not] identifier[frame] . ident... | def abort(self, frame):
"""
Handles ABORT command: Rolls back specified transaction.
"""
if not frame.transaction:
raise ProtocolError('Missing transaction for ABORT command.') # depends on [control=['if'], data=[]]
if not frame.transaction in self.engine.transactions:
raise... |
def find_file(self, path, saltenv, back=None):
'''
Find the path and return the fnd structure, this structure is passed
to other backend interfaces.
'''
path = salt.utils.stringutils.to_unicode(path)
saltenv = salt.utils.stringutils.to_unicode(saltenv)
back = self... | def function[find_file, parameter[self, path, saltenv, back]]:
constant[
Find the path and return the fnd structure, this structure is passed
to other backend interfaces.
]
variable[path] assign[=] call[name[salt].utils.stringutils.to_unicode, parameter[name[path]]]
varia... | keyword[def] identifier[find_file] ( identifier[self] , identifier[path] , identifier[saltenv] , identifier[back] = keyword[None] ):
literal[string]
identifier[path] = identifier[salt] . identifier[utils] . identifier[stringutils] . identifier[to_unicode] ( identifier[path] )
identifier[sa... | def find_file(self, path, saltenv, back=None):
"""
Find the path and return the fnd structure, this structure is passed
to other backend interfaces.
"""
path = salt.utils.stringutils.to_unicode(path)
saltenv = salt.utils.stringutils.to_unicode(saltenv)
back = self.backends(back)
... |
async def send_and_receive(self, message,
generate_identifier=True, timeout=5):
"""Send a message and wait for a response."""
await self._connect_and_encrypt()
# Some messages will respond with the same identifier as used in the
# corresponding request. Ot... | <ast.AsyncFunctionDef object at 0x7da2054a5540> | keyword[async] keyword[def] identifier[send_and_receive] ( identifier[self] , identifier[message] ,
identifier[generate_identifier] = keyword[True] , identifier[timeout] = literal[int] ):
literal[string]
keyword[await] identifier[self] . identifier[_connect_and_encrypt] ()
... | async def send_and_receive(self, message, generate_identifier=True, timeout=5):
"""Send a message and wait for a response."""
await self._connect_and_encrypt()
# Some messages will respond with the same identifier as used in the
# corresponding request. Others will not and one example is the crypto
... |
def works(self, ids = None, query = None, filter = None, offset = None,
limit = None, sample = None, sort = None,
order = None, facet = None, select = None, cursor = None,
cursor_max = 5000, **kwargs):
'''
Search Crossref works
:param ids: [Array] DOIs ... | def function[works, parameter[self, ids, query, filter, offset, limit, sample, sort, order, facet, select, cursor, cursor_max]]:
constant[
Search Crossref works
:param ids: [Array] DOIs (digital object identifier) or other identifiers
:param query: [String] A query string
:param... | keyword[def] identifier[works] ( identifier[self] , identifier[ids] = keyword[None] , identifier[query] = keyword[None] , identifier[filter] = keyword[None] , identifier[offset] = keyword[None] ,
identifier[limit] = keyword[None] , identifier[sample] = keyword[None] , identifier[sort] = keyword[None] ,
identifier[o... | def works(self, ids=None, query=None, filter=None, offset=None, limit=None, sample=None, sort=None, order=None, facet=None, select=None, cursor=None, cursor_max=5000, **kwargs):
"""
Search Crossref works
:param ids: [Array] DOIs (digital object identifier) or other identifiers
:param query:... |
def del_rules(cls, *names, attr=None):
"""Delete algebraic rules used by :meth:`create`
Remove the rules with the given `names`, or all rules if no names are
given
Args:
names (str): Names of rules to delete
attr (None or str): Name of the class attribute from w... | def function[del_rules, parameter[cls]]:
constant[Delete algebraic rules used by :meth:`create`
Remove the rules with the given `names`, or all rules if no names are
given
Args:
names (str): Names of rules to delete
attr (None or str): Name of the class attribut... | keyword[def] identifier[del_rules] ( identifier[cls] ,* identifier[names] , identifier[attr] = keyword[None] ):
literal[string]
keyword[if] identifier[attr] keyword[is] keyword[None] :
identifier[attr] = identifier[cls] . identifier[_rules_attr] ()
keyword[if] identifier[l... | def del_rules(cls, *names, attr=None):
"""Delete algebraic rules used by :meth:`create`
Remove the rules with the given `names`, or all rules if no names are
given
Args:
names (str): Names of rules to delete
attr (None or str): Name of the class attribute from which... |
def dictfetchone(cursor: Cursor) -> Optional[Dict[str, Any]]:
"""
Return the next row from a cursor as an :class:`OrderedDict`, or ``None``.
"""
columns = get_fieldnames_from_cursor(cursor)
row = cursor.fetchone()
if not row:
return None
return OrderedDict(zip(columns, row)) | def function[dictfetchone, parameter[cursor]]:
constant[
Return the next row from a cursor as an :class:`OrderedDict`, or ``None``.
]
variable[columns] assign[=] call[name[get_fieldnames_from_cursor], parameter[name[cursor]]]
variable[row] assign[=] call[name[cursor].fetchone, parameter[... | keyword[def] identifier[dictfetchone] ( identifier[cursor] : identifier[Cursor] )-> identifier[Optional] [ identifier[Dict] [ identifier[str] , identifier[Any] ]]:
literal[string]
identifier[columns] = identifier[get_fieldnames_from_cursor] ( identifier[cursor] )
identifier[row] = identifier[cursor] .... | def dictfetchone(cursor: Cursor) -> Optional[Dict[str, Any]]:
"""
Return the next row from a cursor as an :class:`OrderedDict`, or ``None``.
"""
columns = get_fieldnames_from_cursor(cursor)
row = cursor.fetchone()
if not row:
return None # depends on [control=['if'], data=[]]
return... |
def _prepare_row(task, full, summary):
"""return a dict with the task's info (more if "full" is set)."""
# Would like to include the Job ID in the default set of columns, but
# it is a long value and would leave little room for status and update time.
row_spec = collections.namedtuple('row_spec',
... | def function[_prepare_row, parameter[task, full, summary]]:
constant[return a dict with the task's info (more if "full" is set).]
variable[row_spec] assign[=] call[name[collections].namedtuple, parameter[constant[row_spec], list[[<ast.Constant object at 0x7da1b0127070>, <ast.Constant object at 0x7da1b01... | keyword[def] identifier[_prepare_row] ( identifier[task] , identifier[full] , identifier[summary] ):
literal[string]
identifier[row_spec] = identifier[collections] . identifier[namedtuple] ( literal[string] ,
[ literal[string] , literal[string] , literal[string] ])
identifier[default_columns] ... | def _prepare_row(task, full, summary):
"""return a dict with the task's info (more if "full" is set)."""
# Would like to include the Job ID in the default set of columns, but
# it is a long value and would leave little room for status and update time.
row_spec = collections.namedtuple('row_spec', ['key'... |
def ensure_state(default_getter, exc_class, default_msg=None):
"""Create a decorator factory function."""
def decorator(getter=default_getter, msg=default_msg):
def ensure_decorator(f):
@wraps(f)
def inner(self, *args, **kwargs):
if not getter(self):
... | def function[ensure_state, parameter[default_getter, exc_class, default_msg]]:
constant[Create a decorator factory function.]
def function[decorator, parameter[getter, msg]]:
def function[ensure_decorator, parameter[f]]:
def function[inner, parameter[self]]:
... | keyword[def] identifier[ensure_state] ( identifier[default_getter] , identifier[exc_class] , identifier[default_msg] = keyword[None] ):
literal[string]
keyword[def] identifier[decorator] ( identifier[getter] = identifier[default_getter] , identifier[msg] = identifier[default_msg] ):
keyword[def] ... | def ensure_state(default_getter, exc_class, default_msg=None):
"""Create a decorator factory function."""
def decorator(getter=default_getter, msg=default_msg):
def ensure_decorator(f):
@wraps(f)
def inner(self, *args, **kwargs):
if not getter(self):
... |
def is_installed_extension(name,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
runas=None):
'''
Test if a specific extension is... | def function[is_installed_extension, parameter[name, user, host, port, maintenance_db, password, runas]]:
constant[
Test if a specific extension is installed
CLI Example:
.. code-block:: bash
salt '*' postgres.is_installed_extension
]
variable[installed_ext] assign[=] call[na... | keyword[def] identifier[is_installed_extension] ( identifier[name] ,
identifier[user] = keyword[None] ,
identifier[host] = keyword[None] ,
identifier[port] = keyword[None] ,
identifier[maintenance_db] = keyword[None] ,
identifier[password] = keyword[None] ,
identifier[runas] = keyword[None] ):
literal[stri... | def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None):
"""
Test if a specific extension is installed
CLI Example:
.. code-block:: bash
salt '*' postgres.is_installed_extension
"""
installed_ext = get_installed_extension(name... |
def remove_not_allowed_in_console():
'''This function should be called from the console, when it starts.
Some transformers are not allowed in the console and they could have
been loaded prior to the console being activated. We effectively remove them
and print an information message specific to that tr... | def function[remove_not_allowed_in_console, parameter[]]:
constant[This function should be called from the console, when it starts.
Some transformers are not allowed in the console and they could have
been loaded prior to the console being activated. We effectively remove them
and print an informat... | keyword[def] identifier[remove_not_allowed_in_console] ():
literal[string]
identifier[not_allowed_in_console] =[]
keyword[if] identifier[CONSOLE_ACTIVE] :
keyword[for] identifier[name] keyword[in] identifier[transformers] :
identifier[tr_module] = identifier[import_transforme... | def remove_not_allowed_in_console():
"""This function should be called from the console, when it starts.
Some transformers are not allowed in the console and they could have
been loaded prior to the console being activated. We effectively remove them
and print an information message specific to that tr... |
def get_options(server):
"""Retrieve the available HTTP verbs"""
try:
response = requests.options(
server, allow_redirects=False, verify=False, timeout=5)
except (requests.exceptions.ConnectionError,
requests.exceptions.MissingSchema):
return "Server {} is not availab... | def function[get_options, parameter[server]]:
constant[Retrieve the available HTTP verbs]
<ast.Try object at 0x7da1b2261c90>
<ast.Try object at 0x7da1b2263d30> | keyword[def] identifier[get_options] ( identifier[server] ):
literal[string]
keyword[try] :
identifier[response] = identifier[requests] . identifier[options] (
identifier[server] , identifier[allow_redirects] = keyword[False] , identifier[verify] = keyword[False] , identifier[timeout] = l... | def get_options(server):
"""Retrieve the available HTTP verbs"""
try:
response = requests.options(server, allow_redirects=False, verify=False, timeout=5) # depends on [control=['try'], data=[]]
except (requests.exceptions.ConnectionError, requests.exceptions.MissingSchema):
return 'Server {... |
def _Rforce(self,R,phi=0.,t=0.):
"""
NAME:
_Rforce
PURPOSE:
evaluate the radial force for this potential
INPUT:
R - Galactocentric cylindrical radius
phi - azimuth
t - time
OUTPUT:
the radial force
HISTORY:... | def function[_Rforce, parameter[self, R, phi, t]]:
constant[
NAME:
_Rforce
PURPOSE:
evaluate the radial force for this potential
INPUT:
R - Galactocentric cylindrical radius
phi - azimuth
t - time
OUTPUT:
the radia... | keyword[def] identifier[_Rforce] ( identifier[self] , identifier[R] , identifier[phi] = literal[int] , identifier[t] = literal[int] ):
literal[string]
keyword[return] identifier[self] . identifier[_A] * identifier[math] . identifier[exp] (-( identifier[t] - identifier[self] . identifier[_to] )** l... | def _Rforce(self, R, phi=0.0, t=0.0):
"""
NAME:
_Rforce
PURPOSE:
evaluate the radial force for this potential
INPUT:
R - Galactocentric cylindrical radius
phi - azimuth
t - time
OUTPUT:
the radial force
HISTORY... |
def _process_response(self, response):
"""Parse response"""
forward_raw = False
content_type = response.headers['Content-Type']
if content_type != 'application/json':
logger.debug("headers: %s", response.headers)
# API BUG: text/xml content-type with json payload... | def function[_process_response, parameter[self, response]]:
constant[Parse response]
variable[forward_raw] assign[=] constant[False]
variable[content_type] assign[=] call[name[response].headers][constant[Content-Type]]
if compare[name[content_type] not_equal[!=] constant[application/json... | keyword[def] identifier[_process_response] ( identifier[self] , identifier[response] ):
literal[string]
identifier[forward_raw] = keyword[False]
identifier[content_type] = identifier[response] . identifier[headers] [ literal[string] ]
keyword[if] identifier[content_type] != lit... | def _process_response(self, response):
"""Parse response"""
forward_raw = False
content_type = response.headers['Content-Type']
if content_type != 'application/json':
logger.debug('headers: %s', response.headers)
# API BUG: text/xml content-type with json payload
# http://forum.m... |
def reset_tree(self):
"""
Resets the current tree to empty.
"""
self.tree = {}
self.tree['leaves'] = []
self.tree['levels'] = []
self.tree['is_ready'] = False | def function[reset_tree, parameter[self]]:
constant[
Resets the current tree to empty.
]
name[self].tree assign[=] dictionary[[], []]
call[name[self].tree][constant[leaves]] assign[=] list[[]]
call[name[self].tree][constant[levels]] assign[=] list[[]]
call[name[se... | keyword[def] identifier[reset_tree] ( identifier[self] ):
literal[string]
identifier[self] . identifier[tree] ={}
identifier[self] . identifier[tree] [ literal[string] ]=[]
identifier[self] . identifier[tree] [ literal[string] ]=[]
identifier[self] . identifier[tree] [ li... | def reset_tree(self):
"""
Resets the current tree to empty.
"""
self.tree = {}
self.tree['leaves'] = []
self.tree['levels'] = []
self.tree['is_ready'] = False |
def new_annot(self):
"""Action: create a new file for annotations."""
if self.parent.info.filename is None:
msg = 'No dataset loaded'
self.parent.statusBar().showMessage(msg)
lg.debug(msg)
return
filename = splitext(self.parent.info.filename)[0] +... | def function[new_annot, parameter[self]]:
constant[Action: create a new file for annotations.]
if compare[name[self].parent.info.filename is constant[None]] begin[:]
variable[msg] assign[=] constant[No dataset loaded]
call[call[name[self].parent.statusBar, parameter[]].sh... | keyword[def] identifier[new_annot] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[parent] . identifier[info] . identifier[filename] keyword[is] keyword[None] :
identifier[msg] = literal[string]
identifier[self] . identifier[parent] . id... | def new_annot(self):
"""Action: create a new file for annotations."""
if self.parent.info.filename is None:
msg = 'No dataset loaded'
self.parent.statusBar().showMessage(msg)
lg.debug(msg)
return # depends on [control=['if'], data=[]]
filename = splitext(self.parent.info.fil... |
def list_default_storage_policy_of_datastore(datastore, service_instance=None):
'''
Returns a list of datastores assign the the storage policies.
datastore
Name of the datastore to assign.
The datastore needs to be visible to the VMware entity the proxy
points to.
service_insta... | def function[list_default_storage_policy_of_datastore, parameter[datastore, service_instance]]:
constant[
Returns a list of datastores assign the the storage policies.
datastore
Name of the datastore to assign.
The datastore needs to be visible to the VMware entity the proxy
poi... | keyword[def] identifier[list_default_storage_policy_of_datastore] ( identifier[datastore] , identifier[service_instance] = keyword[None] ):
literal[string]
identifier[log] . identifier[trace] ( literal[string] , identifier[datastore] )
identifier[target_ref] = identifier[_get_proxy_target] ( iden... | def list_default_storage_policy_of_datastore(datastore, service_instance=None):
"""
Returns a list of datastores assign the the storage policies.
datastore
Name of the datastore to assign.
The datastore needs to be visible to the VMware entity the proxy
points to.
service_insta... |
def _cleanSessions(self):
"""
Clean expired sesisons.
"""
tooOld = extime.Time() - timedelta(seconds=PERSISTENT_SESSION_LIFETIME)
self.store.query(
PersistentSession,
PersistentSession.lastUsed < tooOld).deleteFromStore()
self._lastClean = self._cl... | def function[_cleanSessions, parameter[self]]:
constant[
Clean expired sesisons.
]
variable[tooOld] assign[=] binary_operation[call[name[extime].Time, parameter[]] - call[name[timedelta], parameter[]]]
call[call[name[self].store.query, parameter[name[PersistentSession], compare[n... | keyword[def] identifier[_cleanSessions] ( identifier[self] ):
literal[string]
identifier[tooOld] = identifier[extime] . identifier[Time] ()- identifier[timedelta] ( identifier[seconds] = identifier[PERSISTENT_SESSION_LIFETIME] )
identifier[self] . identifier[store] . identifier[query] (
... | def _cleanSessions(self):
"""
Clean expired sesisons.
"""
tooOld = extime.Time() - timedelta(seconds=PERSISTENT_SESSION_LIFETIME)
self.store.query(PersistentSession, PersistentSession.lastUsed < tooOld).deleteFromStore()
self._lastClean = self._clock.seconds() |
def update_data_disk(self, service_name, deployment_name, role_name, lun,
host_caching=None, media_link=None, updated_lun=None,
disk_label=None, disk_name=None,
logical_disk_size_in_gb=None):
'''
Updates the specified data disk a... | def function[update_data_disk, parameter[self, service_name, deployment_name, role_name, lun, host_caching, media_link, updated_lun, disk_label, disk_name, logical_disk_size_in_gb]]:
constant[
Updates the specified data disk attached to the specified virtual
machine.
service_name:
... | keyword[def] identifier[update_data_disk] ( identifier[self] , identifier[service_name] , identifier[deployment_name] , identifier[role_name] , identifier[lun] ,
identifier[host_caching] = keyword[None] , identifier[media_link] = keyword[None] , identifier[updated_lun] = keyword[None] ,
identifier[disk_label] = key... | def update_data_disk(self, service_name, deployment_name, role_name, lun, host_caching=None, media_link=None, updated_lun=None, disk_label=None, disk_name=None, logical_disk_size_in_gb=None):
"""
Updates the specified data disk attached to the specified virtual
machine.
service_name:
... |
def sign(self, data, entropy=None, hashfunc=None, sigencode=sigencode_string, k=None):
"""
hashfunc= should behave like hashlib.sha1 . The output length of the
hash (in bytes) must not be longer than the length of the curve order
(rounded up to the nearest byte), so using SHA256 with nis... | def function[sign, parameter[self, data, entropy, hashfunc, sigencode, k]]:
constant[
hashfunc= should behave like hashlib.sha1 . The output length of the
hash (in bytes) must not be longer than the length of the curve order
(rounded up to the nearest byte), so using SHA256 with nist256p... | keyword[def] identifier[sign] ( identifier[self] , identifier[data] , identifier[entropy] = keyword[None] , identifier[hashfunc] = keyword[None] , identifier[sigencode] = identifier[sigencode_string] , identifier[k] = keyword[None] ):
literal[string]
identifier[hashfunc] = identifier[hashfunc] ke... | def sign(self, data, entropy=None, hashfunc=None, sigencode=sigencode_string, k=None):
"""
hashfunc= should behave like hashlib.sha1 . The output length of the
hash (in bytes) must not be longer than the length of the curve order
(rounded up to the nearest byte), so using SHA256 with nist256... |
def resample_dataset(dataset, destination_area, **kwargs):
"""Resample *dataset* and return the resampled version.
Args:
dataset (xarray.DataArray): Data to be resampled.
destination_area: The destination onto which to project the data,
either a full blown area definition or a string ... | def function[resample_dataset, parameter[dataset, destination_area]]:
constant[Resample *dataset* and return the resampled version.
Args:
dataset (xarray.DataArray): Data to be resampled.
destination_area: The destination onto which to project the data,
either a full blown area de... | keyword[def] identifier[resample_dataset] ( identifier[dataset] , identifier[destination_area] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[source_area] = identifier[dataset] . identifier[attrs] [ literal[string] ]
keyword[except] identifier[KeyError] :
i... | def resample_dataset(dataset, destination_area, **kwargs):
"""Resample *dataset* and return the resampled version.
Args:
dataset (xarray.DataArray): Data to be resampled.
destination_area: The destination onto which to project the data,
either a full blown area definition or a string ... |
def Y_dist(self, new_y_distance):
"""Use preset values for the distance between lines."""
self.parent.value('y_distance', new_y_distance)
self.parent.traces.display() | def function[Y_dist, parameter[self, new_y_distance]]:
constant[Use preset values for the distance between lines.]
call[name[self].parent.value, parameter[constant[y_distance], name[new_y_distance]]]
call[name[self].parent.traces.display, parameter[]] | keyword[def] identifier[Y_dist] ( identifier[self] , identifier[new_y_distance] ):
literal[string]
identifier[self] . identifier[parent] . identifier[value] ( literal[string] , identifier[new_y_distance] )
identifier[self] . identifier[parent] . identifier[traces] . identifier[display] () | def Y_dist(self, new_y_distance):
"""Use preset values for the distance between lines."""
self.parent.value('y_distance', new_y_distance)
self.parent.traces.display() |
def get_stub(self, number, arch, abi_list=()):
"""
Pretty much the intersection of SimLibrary.get_stub() and SimSyscallLibrary.get().
:param number: The syscall number
:param arch: The architecture being worked with, as either a string name or an archinfo.Arch
:param... | def function[get_stub, parameter[self, number, arch, abi_list]]:
constant[
Pretty much the intersection of SimLibrary.get_stub() and SimSyscallLibrary.get().
:param number: The syscall number
:param arch: The architecture being worked with, as either a string name or an arch... | keyword[def] identifier[get_stub] ( identifier[self] , identifier[number] , identifier[arch] , identifier[abi_list] =()):
literal[string]
identifier[name] , identifier[arch] , identifier[abi] = identifier[self] . identifier[_canonicalize] ( identifier[number] , identifier[arch] , identifier[abi_lis... | def get_stub(self, number, arch, abi_list=()):
"""
Pretty much the intersection of SimLibrary.get_stub() and SimSyscallLibrary.get().
:param number: The syscall number
:param arch: The architecture being worked with, as either a string name or an archinfo.Arch
:param abi... |
def unregister_plotter(identifier, sorter=True, plot_func=True):
"""
Unregister a :class:`psyplot.plotter.Plotter` for the projects
Parameters
----------
identifier: str
Name of the attribute that is used to filter for the instances
belonging to this plotter or to create plots with ... | def function[unregister_plotter, parameter[identifier, sorter, plot_func]]:
constant[
Unregister a :class:`psyplot.plotter.Plotter` for the projects
Parameters
----------
identifier: str
Name of the attribute that is used to filter for the instances
belonging to this plotter or ... | keyword[def] identifier[unregister_plotter] ( identifier[identifier] , identifier[sorter] = keyword[True] , identifier[plot_func] = keyword[True] ):
literal[string]
identifier[d] = identifier[registered_plotters] . identifier[get] ( identifier[identifier] ,{})
keyword[if] identifier[sorter] keyword[... | def unregister_plotter(identifier, sorter=True, plot_func=True):
"""
Unregister a :class:`psyplot.plotter.Plotter` for the projects
Parameters
----------
identifier: str
Name of the attribute that is used to filter for the instances
belonging to this plotter or to create plots with ... |
def download(self, name, ids, datas=None, context=None):
"""Download a report from the server and return it as a remote file.
For instance, to download the "Quotation / Order" report of sale orders
identified by the IDs ``[2, 3]``:
.. doctest::
:options: +SKIP
>... | def function[download, parameter[self, name, ids, datas, context]]:
constant[Download a report from the server and return it as a remote file.
For instance, to download the "Quotation / Order" report of sale orders
identified by the IDs ``[2, 3]``:
.. doctest::
:options: +SK... | keyword[def] identifier[download] ( identifier[self] , identifier[name] , identifier[ids] , identifier[datas] = keyword[None] , identifier[context] = keyword[None] ):
literal[string]
keyword[if] identifier[context] keyword[is] keyword[None] :
identifier[context] = identifier[self] .... | def download(self, name, ids, datas=None, context=None):
"""Download a report from the server and return it as a remote file.
For instance, to download the "Quotation / Order" report of sale orders
identified by the IDs ``[2, 3]``:
.. doctest::
:options: +SKIP
>>> r... |
def reply_audio(
self,
audio: str,
quote: bool = None,
caption: str = "",
parse_mode: str = "",
duration: int = 0,
performer: str = None,
title: str = None,
thumb: str = None,
disable_notification: bool = None,
reply_to_message_id: ... | def function[reply_audio, parameter[self, audio, quote, caption, parse_mode, duration, performer, title, thumb, disable_notification, reply_to_message_id, reply_markup, progress, progress_args]]:
constant[Bound method *reply_audio* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.... | keyword[def] identifier[reply_audio] (
identifier[self] ,
identifier[audio] : identifier[str] ,
identifier[quote] : identifier[bool] = keyword[None] ,
identifier[caption] : identifier[str] = literal[string] ,
identifier[parse_mode] : identifier[str] = literal[string] ,
identifier[duration] : identifier[int] = l... | def reply_audio(self, audio: str, quote: bool=None, caption: str='', parse_mode: str='', duration: int=0, performer: str=None, title: str=None, thumb: str=None, disable_notification: bool=None, reply_to_message_id: int=None, reply_markup: Union['pyrogram.InlineKeyboardMarkup', 'pyrogram.ReplyKeyboardMarkup', 'pyrogram.... |
def json_unicode_to_utf8(data):
"""Change all strings in a JSON structure to UTF-8."""
if isinstance(data, unicode):
return data.encode('utf-8')
elif isinstance(data, dict):
newdict = {}
for key in data:
newdict[json_unicode_to_utf8(
key)] = json_unicode_t... | def function[json_unicode_to_utf8, parameter[data]]:
constant[Change all strings in a JSON structure to UTF-8.]
if call[name[isinstance], parameter[name[data], name[unicode]]] begin[:]
return[call[name[data].encode, parameter[constant[utf-8]]]] | keyword[def] identifier[json_unicode_to_utf8] ( identifier[data] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[data] , identifier[unicode] ):
keyword[return] identifier[data] . identifier[encode] ( literal[string] )
keyword[elif] identifier[isinstance] ( identifier[dat... | def json_unicode_to_utf8(data):
"""Change all strings in a JSON structure to UTF-8."""
if isinstance(data, unicode):
return data.encode('utf-8') # depends on [control=['if'], data=[]]
elif isinstance(data, dict):
newdict = {}
for key in data:
newdict[json_unicode_to_utf8... |
def kline_echarts(self, code=None):
def kline_formater(param):
return param.name + ':' + vars(param)
"""plot the market_data"""
if code is None:
path_name = '.' + os.sep + 'QA_' + self.type + \
'_codepackage_' + self.if_fq + '.html'
kline = K... | def function[kline_echarts, parameter[self, code]]:
def function[kline_formater, parameter[param]]:
return[binary_operation[binary_operation[name[param].name + constant[:]] + call[name[vars], parameter[name[param]]]]]
constant[plot the market_data]
if compare[name[code] is constant[None]... | keyword[def] identifier[kline_echarts] ( identifier[self] , identifier[code] = keyword[None] ):
keyword[def] identifier[kline_formater] ( identifier[param] ):
keyword[return] identifier[param] . identifier[name] + literal[string] + identifier[vars] ( identifier[param] )
literal[stri... | def kline_echarts(self, code=None):
def kline_formater(param):
return param.name + ':' + vars(param)
'plot the market_data'
if code is None:
path_name = '.' + os.sep + 'QA_' + self.type + '_codepackage_' + self.if_fq + '.html'
kline = Kline('CodePackage_' + self.if_fq + '_' + self.t... |
def _histogram(self, which, mu, sigma, data):
"""plot a histogram. For internal use only"""
weights = np.ones_like(data)/len(data) # make bar heights sum to 100%
n, bins, patches = plt.hist(data, bins=25, weights=weights, facecolor='blue', alpha=0.5)
plt.title(r'%s %s: $\mu=%.2f$, $\si... | def function[_histogram, parameter[self, which, mu, sigma, data]]:
constant[plot a histogram. For internal use only]
variable[weights] assign[=] binary_operation[call[name[np].ones_like, parameter[name[data]]] / call[name[len], parameter[name[data]]]]
<ast.Tuple object at 0x7da20c990070> assign[... | keyword[def] identifier[_histogram] ( identifier[self] , identifier[which] , identifier[mu] , identifier[sigma] , identifier[data] ):
literal[string]
identifier[weights] = identifier[np] . identifier[ones_like] ( identifier[data] )/ identifier[len] ( identifier[data] )
identifier[n] , ide... | def _histogram(self, which, mu, sigma, data):
"""plot a histogram. For internal use only"""
weights = np.ones_like(data) / len(data) # make bar heights sum to 100%
(n, bins, patches) = plt.hist(data, bins=25, weights=weights, facecolor='blue', alpha=0.5)
plt.title('%s %s: $\\mu=%.2f$, $\\sigma=%.2f$' %... |
def build_on_condition(self, runnable, regime, on_condition):
"""
Build OnCondition event handler code.
@param on_condition: OnCondition event handler object
@type on_condition: lems.model.dynamics.OnCondition
@return: Generated OnCondition code
@rtype: list(string)
... | def function[build_on_condition, parameter[self, runnable, regime, on_condition]]:
constant[
Build OnCondition event handler code.
@param on_condition: OnCondition event handler object
@type on_condition: lems.model.dynamics.OnCondition
@return: Generated OnCondition code
... | keyword[def] identifier[build_on_condition] ( identifier[self] , identifier[runnable] , identifier[regime] , identifier[on_condition] ):
literal[string]
identifier[on_condition_code] =[]
identifier[on_condition_code] +=[ literal[string] . identifier[format] ( identifier[self] . identifie... | def build_on_condition(self, runnable, regime, on_condition):
"""
Build OnCondition event handler code.
@param on_condition: OnCondition event handler object
@type on_condition: lems.model.dynamics.OnCondition
@return: Generated OnCondition code
@rtype: list(string)
... |
def match(self, **kwargs):
"""
Traverse relationships with properties matching the given parameters.
e.g: `.match(price__lt=10)`
:param kwargs: see `NodeSet.filter()` for syntax
:return: self
"""
if kwargs:
if self.definition.get('model') is None... | def function[match, parameter[self]]:
constant[
Traverse relationships with properties matching the given parameters.
e.g: `.match(price__lt=10)`
:param kwargs: see `NodeSet.filter()` for syntax
:return: self
]
if name[kwargs] begin[:]
if com... | keyword[def] identifier[match] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[kwargs] :
keyword[if] identifier[self] . identifier[definition] . identifier[get] ( literal[string] ) keyword[is] keyword[None] :
keyword[raise] ident... | def match(self, **kwargs):
"""
Traverse relationships with properties matching the given parameters.
e.g: `.match(price__lt=10)`
:param kwargs: see `NodeSet.filter()` for syntax
:return: self
"""
if kwargs:
if self.definition.get('model') is None:
... |
def PCO_protocol_dispatcher(s):
"""Choose the correct PCO element."""
proto_num = orb(s[0]) * 256 + orb(s[1])
cls = PCO_PROTOCOL_CLASSES.get(proto_num, Raw)
return cls(s) | def function[PCO_protocol_dispatcher, parameter[s]]:
constant[Choose the correct PCO element.]
variable[proto_num] assign[=] binary_operation[binary_operation[call[name[orb], parameter[call[name[s]][constant[0]]]] * constant[256]] + call[name[orb], parameter[call[name[s]][constant[1]]]]]
variabl... | keyword[def] identifier[PCO_protocol_dispatcher] ( identifier[s] ):
literal[string]
identifier[proto_num] = identifier[orb] ( identifier[s] [ literal[int] ])* literal[int] + identifier[orb] ( identifier[s] [ literal[int] ])
identifier[cls] = identifier[PCO_PROTOCOL_CLASSES] . identifier[get] ( identif... | def PCO_protocol_dispatcher(s):
"""Choose the correct PCO element."""
proto_num = orb(s[0]) * 256 + orb(s[1])
cls = PCO_PROTOCOL_CLASSES.get(proto_num, Raw)
return cls(s) |
def get_bcbio_timings(path):
"""Fetch timing information from a bcbio log file."""
with open(path, 'r') as file_handle:
steps = {}
for line in file_handle:
matches = re.search(r'^\[([^\]]+)\] ([^:]+: .*)', line)
if not matches:
continue
tstamp... | def function[get_bcbio_timings, parameter[path]]:
constant[Fetch timing information from a bcbio log file.]
with call[name[open], parameter[name[path], constant[r]]] begin[:]
variable[steps] assign[=] dictionary[[], []]
for taget[name[line]] in starred[name[file_handle]] ... | keyword[def] identifier[get_bcbio_timings] ( identifier[path] ):
literal[string]
keyword[with] identifier[open] ( identifier[path] , literal[string] ) keyword[as] identifier[file_handle] :
identifier[steps] ={}
keyword[for] identifier[line] keyword[in] identifier[file_handle] :
... | def get_bcbio_timings(path):
"""Fetch timing information from a bcbio log file."""
with open(path, 'r') as file_handle:
steps = {}
for line in file_handle:
matches = re.search('^\\[([^\\]]+)\\] ([^:]+: .*)', line)
if not matches:
continue # depends on [co... |
def port_profile_global_port_profile_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
port_profile_global = ET.SubElement(config, "port-profile-global", xmlns="urn:brocade.com:mgmt:brocade-port-profile")
port_profile = ET.SubElement(port_profile_glob... | def function[port_profile_global_port_profile_name, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[port_profile_global] assign[=] call[name[ET].SubElement, parameter[name[config], constant[port-prof... | keyword[def] identifier[port_profile_global_port_profile_name] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[port_profile_global] = identifier[ET] . identifier[SubElement] ( identifier[c... | def port_profile_global_port_profile_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
port_profile_global = ET.SubElement(config, 'port-profile-global', xmlns='urn:brocade.com:mgmt:brocade-port-profile')
port_profile = ET.SubElement(port_profile_global, 'port-profil... |
def sg_rnn(tensor, opt):
r"""Applies a simple rnn.
Args:
tensor: A 3-D `Tensor` (automatically passed by decorator).
opt:
in_dim: A positive `integer`. The size of input dimension.
dim: A positive `integer`. The size of output dimension.
bias: Boolean. If True, biases ar... | def function[sg_rnn, parameter[tensor, opt]]:
constant[Applies a simple rnn.
Args:
tensor: A 3-D `Tensor` (automatically passed by decorator).
opt:
in_dim: A positive `integer`. The size of input dimension.
dim: A positive `integer`. The size of output dimension.
bia... | keyword[def] identifier[sg_rnn] ( identifier[tensor] , identifier[opt] ):
literal[string]
identifier[ln] = keyword[lambda] identifier[v] : identifier[_ln_rnn] ( identifier[v] , identifier[gamma] , identifier[beta] ) keyword[if] identifier[opt] . identifier[ln] keyword[else] identifier[v]
... | def sg_rnn(tensor, opt):
"""Applies a simple rnn.
Args:
tensor: A 3-D `Tensor` (automatically passed by decorator).
opt:
in_dim: A positive `integer`. The size of input dimension.
dim: A positive `integer`. The size of output dimension.
bias: Boolean. If True, biases are... |
def get_publisher(self, publisher_id):
"""GetPublisher.
Get a specific service hooks publisher.
:param str publisher_id: ID for a publisher.
:rtype: :class:`<Publisher> <azure.devops.v5_0.service_hooks.models.Publisher>`
"""
route_values = {}
if publisher_id is no... | def function[get_publisher, parameter[self, publisher_id]]:
constant[GetPublisher.
Get a specific service hooks publisher.
:param str publisher_id: ID for a publisher.
:rtype: :class:`<Publisher> <azure.devops.v5_0.service_hooks.models.Publisher>`
]
variable[route_values]... | keyword[def] identifier[get_publisher] ( identifier[self] , identifier[publisher_id] ):
literal[string]
identifier[route_values] ={}
keyword[if] identifier[publisher_id] keyword[is] keyword[not] keyword[None] :
identifier[route_values] [ literal[string] ]= identifier[self]... | def get_publisher(self, publisher_id):
"""GetPublisher.
Get a specific service hooks publisher.
:param str publisher_id: ID for a publisher.
:rtype: :class:`<Publisher> <azure.devops.v5_0.service_hooks.models.Publisher>`
"""
route_values = {}
if publisher_id is not None:
... |
def format(self, data: Iterable[_FormatArg]) -> bytes:
"""String interpolation into the format string.
Args:
data: The data interpolated into the format string.
Examples:
::
BytesFormat(b'Hello, %b!') % b'World'
BytesFormat(b'%b, %b!') %... | def function[format, parameter[self, data]]:
constant[String interpolation into the format string.
Args:
data: The data interpolated into the format string.
Examples:
::
BytesFormat(b'Hello, %b!') % b'World'
BytesFormat(b'%b, %b!') % (b'... | keyword[def] identifier[format] ( identifier[self] , identifier[data] : identifier[Iterable] [ identifier[_FormatArg] ])-> identifier[bytes] :
literal[string]
identifier[fix_arg] = identifier[self] . identifier[_fix_format_arg]
keyword[return] identifier[self] . identifier[how] % identif... | def format(self, data: Iterable[_FormatArg]) -> bytes:
"""String interpolation into the format string.
Args:
data: The data interpolated into the format string.
Examples:
::
BytesFormat(b'Hello, %b!') % b'World'
BytesFormat(b'%b, %b!') % (b'... |
def make_shell_context(self) -> dict:
"""Create a context for interactive shell usage.
The :attr:`shell_context_processors` can be used to add
additional context.
"""
context = {'app': self, 'g': g}
for processor in self.shell_context_processors:
context.upda... | def function[make_shell_context, parameter[self]]:
constant[Create a context for interactive shell usage.
The :attr:`shell_context_processors` can be used to add
additional context.
]
variable[context] assign[=] dictionary[[<ast.Constant object at 0x7da18bc734f0>, <ast.Constant ... | keyword[def] identifier[make_shell_context] ( identifier[self] )-> identifier[dict] :
literal[string]
identifier[context] ={ literal[string] : identifier[self] , literal[string] : identifier[g] }
keyword[for] identifier[processor] keyword[in] identifier[self] . identifier[shell_context_... | def make_shell_context(self) -> dict:
"""Create a context for interactive shell usage.
The :attr:`shell_context_processors` can be used to add
additional context.
"""
context = {'app': self, 'g': g}
for processor in self.shell_context_processors:
context.update(processor()) ... |
def del_permission_role(self, role, perm_view):
"""
Remove permission-ViewMenu object to Role
:param role:
The role object
:param perm_view:
The PermissionViewMenu object
"""
if perm_view in role.permissions:
try:
... | def function[del_permission_role, parameter[self, role, perm_view]]:
constant[
Remove permission-ViewMenu object to Role
:param role:
The role object
:param perm_view:
The PermissionViewMenu object
]
if compare[name[perm_view] ... | keyword[def] identifier[del_permission_role] ( identifier[self] , identifier[role] , identifier[perm_view] ):
literal[string]
keyword[if] identifier[perm_view] keyword[in] identifier[role] . identifier[permissions] :
keyword[try] :
identifier[role] . identifier[perm... | def del_permission_role(self, role, perm_view):
"""
Remove permission-ViewMenu object to Role
:param role:
The role object
:param perm_view:
The PermissionViewMenu object
"""
if perm_view in role.permissions:
try:
r... |
def prebuild_arch(self, arch):
'''Run any pre-build tasks for the Recipe. By default, this checks if
any prebuild_archname methods exist for the archname of the current
architecture, and runs them if so.'''
prebuild = "prebuild_{}".format(arch.arch.replace('-', '_'))
if hasattr(s... | def function[prebuild_arch, parameter[self, arch]]:
constant[Run any pre-build tasks for the Recipe. By default, this checks if
any prebuild_archname methods exist for the archname of the current
architecture, and runs them if so.]
variable[prebuild] assign[=] call[constant[prebuild_{}].... | keyword[def] identifier[prebuild_arch] ( identifier[self] , identifier[arch] ):
literal[string]
identifier[prebuild] = literal[string] . identifier[format] ( identifier[arch] . identifier[arch] . identifier[replace] ( literal[string] , literal[string] ))
keyword[if] identifier[hasattr] ( ... | def prebuild_arch(self, arch):
"""Run any pre-build tasks for the Recipe. By default, this checks if
any prebuild_archname methods exist for the archname of the current
architecture, and runs them if so."""
prebuild = 'prebuild_{}'.format(arch.arch.replace('-', '_'))
if hasattr(self, prebuil... |
def discrete(self, *args):
"""
Set fields to be discrete.
:rtype: DataFrame
:Example:
>>> # Table schema is create table test(f1 double, f2 string)
>>> # Original continuity: f1=CONTINUOUS, f2=CONTINUOUS
>>> # Now we want to set ``f1`` and ``f2`` into continuou... | def function[discrete, parameter[self]]:
constant[
Set fields to be discrete.
:rtype: DataFrame
:Example:
>>> # Table schema is create table test(f1 double, f2 string)
>>> # Original continuity: f1=CONTINUOUS, f2=CONTINUOUS
>>> # Now we want to set ``f1`` and `... | keyword[def] identifier[discrete] ( identifier[self] ,* identifier[args] ):
literal[string]
identifier[new_df] = identifier[copy_df] ( identifier[self] )
identifier[fields] = identifier[_render_field_set] ( identifier[args] )
identifier[self] . identifier[_assert_ml_fields_valid] ... | def discrete(self, *args):
"""
Set fields to be discrete.
:rtype: DataFrame
:Example:
>>> # Table schema is create table test(f1 double, f2 string)
>>> # Original continuity: f1=CONTINUOUS, f2=CONTINUOUS
>>> # Now we want to set ``f1`` and ``f2`` into continuous
... |
def build_model(self, token_encoder_model, sentence_encoder_model,
trainable_embeddings=True, output_activation='softmax'):
"""Builds a model that first encodes all words within sentences using `token_encoder_model`, followed by
`sentence_encoder_model`.
Args:
to... | def function[build_model, parameter[self, token_encoder_model, sentence_encoder_model, trainable_embeddings, output_activation]]:
constant[Builds a model that first encodes all words within sentences using `token_encoder_model`, followed by
`sentence_encoder_model`.
Args:
token_enco... | keyword[def] identifier[build_model] ( identifier[self] , identifier[token_encoder_model] , identifier[sentence_encoder_model] ,
identifier[trainable_embeddings] = keyword[True] , identifier[output_activation] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] (... | def build_model(self, token_encoder_model, sentence_encoder_model, trainable_embeddings=True, output_activation='softmax'):
"""Builds a model that first encodes all words within sentences using `token_encoder_model`, followed by
`sentence_encoder_model`.
Args:
token_encoder_model: An in... |
def pyquil_to_image(program: pyquil.Program) -> PIL.Image: # pragma: no cover
"""Returns an image of a pyquil circuit.
See circuit_to_latex() for more details.
"""
circ = pyquil_to_circuit(program)
latex = circuit_to_latex(circ)
img = render_latex(latex)
return img | def function[pyquil_to_image, parameter[program]]:
constant[Returns an image of a pyquil circuit.
See circuit_to_latex() for more details.
]
variable[circ] assign[=] call[name[pyquil_to_circuit], parameter[name[program]]]
variable[latex] assign[=] call[name[circuit_to_latex], parameter[... | keyword[def] identifier[pyquil_to_image] ( identifier[program] : identifier[pyquil] . identifier[Program] )-> identifier[PIL] . identifier[Image] :
literal[string]
identifier[circ] = identifier[pyquil_to_circuit] ( identifier[program] )
identifier[latex] = identifier[circuit_to_latex] ( identifier[cir... | def pyquil_to_image(program: pyquil.Program) -> PIL.Image: # pragma: no cover
'Returns an image of a pyquil circuit.\n\n See circuit_to_latex() for more details.\n '
circ = pyquil_to_circuit(program)
latex = circuit_to_latex(circ)
img = render_latex(latex)
return img |
def append_child ( self, object, child ):
""" Appends a child to the object's children.
"""
if isinstance( child, Subgraph ):
object.subgraphs.append( child )
elif isinstance( child, Cluster ):
object.clusters.append( child )
elif isinstance( child, Node... | def function[append_child, parameter[self, object, child]]:
constant[ Appends a child to the object's children.
]
if call[name[isinstance], parameter[name[child], name[Subgraph]]] begin[:]
call[name[object].subgraphs.append, parameter[name[child]]] | keyword[def] identifier[append_child] ( identifier[self] , identifier[object] , identifier[child] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[child] , identifier[Subgraph] ):
identifier[object] . identifier[subgraphs] . identifier[append] ( identifier[child] )
... | def append_child(self, object, child):
""" Appends a child to the object's children.
"""
if isinstance(child, Subgraph):
object.subgraphs.append(child) # depends on [control=['if'], data=[]]
elif isinstance(child, Cluster):
object.clusters.append(child) # depends on [control=['if']... |
def ArcTan(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
Takes the inverse tan of a vertex, Arctan(vertex)
:param input_vertex: the vertex
"""
return Double(context.jvm_view().ArcTanVertex, label, cast_to_double_vertex(input_vertex)) | def function[ArcTan, parameter[input_vertex, label]]:
constant[
Takes the inverse tan of a vertex, Arctan(vertex)
:param input_vertex: the vertex
]
return[call[name[Double], parameter[call[name[context].jvm_view, parameter[]].ArcTanVertex, name[label], call[name[cast_to_double_vertex], para... | keyword[def] identifier[ArcTan] ( identifier[input_vertex] : identifier[vertex_constructor_param_types] , identifier[label] : identifier[Optional] [ identifier[str] ]= keyword[None] )-> identifier[Vertex] :
literal[string]
keyword[return] identifier[Double] ( identifier[context] . identifier[jvm_view] ().... | def ArcTan(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
Takes the inverse tan of a vertex, Arctan(vertex)
:param input_vertex: the vertex
"""
return Double(context.jvm_view().ArcTanVertex, label, cast_to_double_vertex(input_vertex)) |
def from_text(cls, filename, **kwargs):
'''
Create a constellation by reading a catalog in from a text file,
as long as it's formated as in to_text() with identifiers, coordinates, magnitudes.
Parameters
----------
filename : str
The filename to read in.
... | def function[from_text, parameter[cls, filename]]:
constant[
Create a constellation by reading a catalog in from a text file,
as long as it's formated as in to_text() with identifiers, coordinates, magnitudes.
Parameters
----------
filename : str
The filename... | keyword[def] identifier[from_text] ( identifier[cls] , identifier[filename] ,** identifier[kwargs] ):
literal[string]
identifier[t] = identifier[ascii] . identifier[read] ( identifier[filename] ,** identifier[kwargs] )
literal[string]
identifier[this] = ident... | def from_text(cls, filename, **kwargs):
"""
Create a constellation by reading a catalog in from a text file,
as long as it's formated as in to_text() with identifiers, coordinates, magnitudes.
Parameters
----------
filename : str
The filename to read in.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.