code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def load_streets(self, filename):
"""
Load up all streets in lowercase for easier matching. The file should have one street per line, with no extra
characters. This isn't strictly required, but will vastly increase the accuracy.
"""
with open(filename, 'r') as f:
for ... | def function[load_streets, parameter[self, filename]]:
constant[
Load up all streets in lowercase for easier matching. The file should have one street per line, with no extra
characters. This isn't strictly required, but will vastly increase the accuracy.
]
with call[name[open], ... | keyword[def] identifier[load_streets] ( identifier[self] , identifier[filename] ):
literal[string]
keyword[with] identifier[open] ( identifier[filename] , literal[string] ) keyword[as] identifier[f] :
keyword[for] identifier[line] keyword[in] identifier[f] :
ident... | def load_streets(self, filename):
"""
Load up all streets in lowercase for easier matching. The file should have one street per line, with no extra
characters. This isn't strictly required, but will vastly increase the accuracy.
"""
with open(filename, 'r') as f:
for line in f:
... |
def _parse_args(args: List[str]) -> _UpdateArgumentsRunConfig:
"""
Parses the given CLI arguments to get a run configuration.
:param args: CLI arguments
:return: run configuration derived from the given CLI arguments
"""
parser = argparse.ArgumentParser(
prog="gitlab-update-variables", d... | def function[_parse_args, parameter[args]]:
constant[
Parses the given CLI arguments to get a run configuration.
:param args: CLI arguments
:return: run configuration derived from the given CLI arguments
]
variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
... | keyword[def] identifier[_parse_args] ( identifier[args] : identifier[List] [ identifier[str] ])-> identifier[_UpdateArgumentsRunConfig] :
literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] (
identifier[prog] = literal[string] , identifier[description] = literal[stri... | def _parse_args(args: List[str]) -> _UpdateArgumentsRunConfig:
"""
Parses the given CLI arguments to get a run configuration.
:param args: CLI arguments
:return: run configuration derived from the given CLI arguments
"""
parser = argparse.ArgumentParser(prog='gitlab-update-variables', descriptio... |
def voc_eval(detpath,
annopath,
imagesetfile,
classname,
cachedir,
ovthresh=0.5,
use_07_metric=True):
"""rec, prec, ap = voc_eval(detpath,
annopath,
imagesetfile,
... | def function[voc_eval, parameter[detpath, annopath, imagesetfile, classname, cachedir, ovthresh, use_07_metric]]:
constant[rec, prec, ap = voc_eval(detpath,
annopath,
imagesetfile,
classname,
[ovthresh],
... | keyword[def] identifier[voc_eval] ( identifier[detpath] ,
identifier[annopath] ,
identifier[imagesetfile] ,
identifier[classname] ,
identifier[cachedir] ,
identifier[ovthresh] = literal[int] ,
identifier[use_07_metric] = keyword[True] ):
literal[string]
keyword[if] keyword[n... | def voc_eval(detpath, annopath, imagesetfile, classname, cachedir, ovthresh=0.5, use_07_metric=True):
"""rec, prec, ap = voc_eval(detpath,
annopath,
imagesetfile,
classname,
[ovthresh],
... |
def _get_drive_resource(self, drive_name):
"""Gets the DiskDrive resource if exists.
:param drive_name: can be either "PhysicalDrives" or
"LogicalDrives".
:returns the list of drives.
:raises: IloCommandNotSupportedError if the given drive resource
doesn't exist... | def function[_get_drive_resource, parameter[self, drive_name]]:
constant[Gets the DiskDrive resource if exists.
:param drive_name: can be either "PhysicalDrives" or
"LogicalDrives".
:returns the list of drives.
:raises: IloCommandNotSupportedError if the given drive resourc... | keyword[def] identifier[_get_drive_resource] ( identifier[self] , identifier[drive_name] ):
literal[string]
identifier[disk_details_list] =[]
identifier[array_uri_links] = identifier[self] . identifier[_create_list_of_array_controllers] ()
keyword[for] identifier[array_link] key... | def _get_drive_resource(self, drive_name):
"""Gets the DiskDrive resource if exists.
:param drive_name: can be either "PhysicalDrives" or
"LogicalDrives".
:returns the list of drives.
:raises: IloCommandNotSupportedError if the given drive resource
doesn't exist.
... |
def check_conf_percentage_validity(conf_percentage):
"""
Ensures that `conf_percentage` is in (0, 100). Raises a helpful ValueError
if otherwise.
"""
msg = "conf_percentage MUST be a number between 0.0 and 100."
condition_1 = isinstance(conf_percentage, Number)
if not condition_1:
ra... | def function[check_conf_percentage_validity, parameter[conf_percentage]]:
constant[
Ensures that `conf_percentage` is in (0, 100). Raises a helpful ValueError
if otherwise.
]
variable[msg] assign[=] constant[conf_percentage MUST be a number between 0.0 and 100.]
variable[condition_1]... | keyword[def] identifier[check_conf_percentage_validity] ( identifier[conf_percentage] ):
literal[string]
identifier[msg] = literal[string]
identifier[condition_1] = identifier[isinstance] ( identifier[conf_percentage] , identifier[Number] )
keyword[if] keyword[not] identifier[condition_1] :
... | def check_conf_percentage_validity(conf_percentage):
"""
Ensures that `conf_percentage` is in (0, 100). Raises a helpful ValueError
if otherwise.
"""
msg = 'conf_percentage MUST be a number between 0.0 and 100.'
condition_1 = isinstance(conf_percentage, Number)
if not condition_1:
ra... |
def dict_merge(o, v):
'''
Recursively climbs through dictionaries and merges them together.
:param o:
The first dictionary
:param v:
The second dictionary
:returns:
A dictionary (who would have guessed?)
.. note::
Make sure `o` & `v` are indeed dictionaries,
... | def function[dict_merge, parameter[o, v]]:
constant[
Recursively climbs through dictionaries and merges them together.
:param o:
The first dictionary
:param v:
The second dictionary
:returns:
A dictionary (who would have guessed?)
.. note::
Make sure `o` & `... | keyword[def] identifier[dict_merge] ( identifier[o] , identifier[v] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[v] , identifier[dict] ):
keyword[return] identifier[v]
identifier[res] = identifier[_deepcopy] ( identifier[o] )
keyword[for] identifi... | def dict_merge(o, v):
"""
Recursively climbs through dictionaries and merges them together.
:param o:
The first dictionary
:param v:
The second dictionary
:returns:
A dictionary (who would have guessed?)
.. note::
Make sure `o` & `v` are indeed dictionaries,
... |
def adjustMinimumWidth( self ):
"""
Updates the minimum width for this menu based on the font metrics \
for its title (if its shown). This method is called automatically \
when the menu is shown.
"""
if not self.showTitle():
return
metrics = ... | def function[adjustMinimumWidth, parameter[self]]:
constant[
Updates the minimum width for this menu based on the font metrics for its title (if its shown). This method is called automatically when the menu is shown.
]
if <ast.UnaryOp object at 0x7da18f09df00> begin[:]
... | keyword[def] identifier[adjustMinimumWidth] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[showTitle] ():
keyword[return]
identifier[metrics] = identifier[QFontMetrics] ( identifier[self] . identifier[font] ())
identif... | def adjustMinimumWidth(self):
"""
Updates the minimum width for this menu based on the font metrics for its title (if its shown). This method is called automatically when the menu is shown.
"""
if not self.showTitle():
return # depends on [control=['if'], data=[]]
m... |
def dump_junit(self):
"""Returns a string containing XML mapped to the JUnit schema."""
testsuites = ElementTree.Element('testsuites', name='therapist', time=str(round(self.execution_time, 2)),
tests=str(self.count()), failures=str(self.count(status=Result.FAILUR... | def function[dump_junit, parameter[self]]:
constant[Returns a string containing XML mapped to the JUnit schema.]
variable[testsuites] assign[=] call[name[ElementTree].Element, parameter[constant[testsuites]]]
for taget[name[result]] in starred[name[self].objects] begin[:]
variabl... | keyword[def] identifier[dump_junit] ( identifier[self] ):
literal[string]
identifier[testsuites] = identifier[ElementTree] . identifier[Element] ( literal[string] , identifier[name] = literal[string] , identifier[time] = identifier[str] ( identifier[round] ( identifier[self] . identifier[execution_... | def dump_junit(self):
"""Returns a string containing XML mapped to the JUnit schema."""
testsuites = ElementTree.Element('testsuites', name='therapist', time=str(round(self.execution_time, 2)), tests=str(self.count()), failures=str(self.count(status=Result.FAILURE)), errors=str(self.count(status=Result.ERROR)))... |
def revnet_164_cifar():
"""Tiny hparams suitable for CIFAR/etc."""
hparams = revnet_cifar_base()
hparams.bottleneck = True
hparams.num_channels = [16, 32, 64]
hparams.num_layers_per_block = [8, 8, 8]
return hparams | def function[revnet_164_cifar, parameter[]]:
constant[Tiny hparams suitable for CIFAR/etc.]
variable[hparams] assign[=] call[name[revnet_cifar_base], parameter[]]
name[hparams].bottleneck assign[=] constant[True]
name[hparams].num_channels assign[=] list[[<ast.Constant object at 0x7da1b2... | keyword[def] identifier[revnet_164_cifar] ():
literal[string]
identifier[hparams] = identifier[revnet_cifar_base] ()
identifier[hparams] . identifier[bottleneck] = keyword[True]
identifier[hparams] . identifier[num_channels] =[ literal[int] , literal[int] , literal[int] ]
identifier[hparams] . identi... | def revnet_164_cifar():
"""Tiny hparams suitable for CIFAR/etc."""
hparams = revnet_cifar_base()
hparams.bottleneck = True
hparams.num_channels = [16, 32, 64]
hparams.num_layers_per_block = [8, 8, 8]
return hparams |
def _features_as_kv(self):
"""
Return features row as kv pairs so that they can be stored in memcache or redis and
used at serving layer
:return: a nested hash for each column
"""
self._data = self.get_data()
key_list = self.key()
values_list = self.values... | def function[_features_as_kv, parameter[self]]:
constant[
Return features row as kv pairs so that they can be stored in memcache or redis and
used at serving layer
:return: a nested hash for each column
]
name[self]._data assign[=] call[name[self].get_data, parameter[]]
... | keyword[def] identifier[_features_as_kv] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_data] = identifier[self] . identifier[get_data] ()
identifier[key_list] = identifier[self] . identifier[key] ()
identifier[values_list] = identifier[self] . identifier[val... | def _features_as_kv(self):
"""
Return features row as kv pairs so that they can be stored in memcache or redis and
used at serving layer
:return: a nested hash for each column
"""
self._data = self.get_data()
key_list = self.key()
values_list = self.values()
result = ... |
def linefeed(self):
"""Perform an index and, if :data:`~pyte.modes.LNM` is set, a
carriage return.
"""
self.index()
if mo.LNM in self.mode:
self.carriage_return() | def function[linefeed, parameter[self]]:
constant[Perform an index and, if :data:`~pyte.modes.LNM` is set, a
carriage return.
]
call[name[self].index, parameter[]]
if compare[name[mo].LNM in name[self].mode] begin[:]
call[name[self].carriage_return, parameter[]] | keyword[def] identifier[linefeed] ( identifier[self] ):
literal[string]
identifier[self] . identifier[index] ()
keyword[if] identifier[mo] . identifier[LNM] keyword[in] identifier[self] . identifier[mode] :
identifier[self] . identifier[carriage_return] () | def linefeed(self):
"""Perform an index and, if :data:`~pyte.modes.LNM` is set, a
carriage return.
"""
self.index()
if mo.LNM in self.mode:
self.carriage_return() # depends on [control=['if'], data=[]] |
def resize(self, dims):
"""Resize our drawing area to encompass a space defined by the
given dimensions.
"""
width, height = dims[:2]
self.dims = (width, height)
self.logger.debug("renderer reconfigured to %dx%d" % (
width, height))
# create cairo sur... | def function[resize, parameter[self, dims]]:
constant[Resize our drawing area to encompass a space defined by the
given dimensions.
]
<ast.Tuple object at 0x7da204960760> assign[=] call[name[dims]][<ast.Slice object at 0x7da204961e10>]
name[self].dims assign[=] tuple[[<ast.Name o... | keyword[def] identifier[resize] ( identifier[self] , identifier[dims] ):
literal[string]
identifier[width] , identifier[height] = identifier[dims] [: literal[int] ]
identifier[self] . identifier[dims] =( identifier[width] , identifier[height] )
identifier[self] . identifier[logger... | def resize(self, dims):
"""Resize our drawing area to encompass a space defined by the
given dimensions.
"""
(width, height) = dims[:2]
self.dims = (width, height)
self.logger.debug('renderer reconfigured to %dx%d' % (width, height))
# create cairo surface the size of the window
... |
def check_dependencies(req, indent=1, history=None):
"""
Given a setuptools package requirement (e.g. 'gryphon==2.42' or just
'gryphon'), print a tree of dependencies as they resolve in this
environment.
"""
# keep a history to avoid infinite loops
if history is None:
history = set()... | def function[check_dependencies, parameter[req, indent, history]]:
constant[
Given a setuptools package requirement (e.g. 'gryphon==2.42' or just
'gryphon'), print a tree of dependencies as they resolve in this
environment.
]
if compare[name[history] is constant[None]] begin[:]
... | keyword[def] identifier[check_dependencies] ( identifier[req] , identifier[indent] = literal[int] , identifier[history] = keyword[None] ):
literal[string]
keyword[if] identifier[history] keyword[is] keyword[None] :
identifier[history] = identifier[set] ()
keyword[if] identifier[req] ... | def check_dependencies(req, indent=1, history=None):
"""
Given a setuptools package requirement (e.g. 'gryphon==2.42' or just
'gryphon'), print a tree of dependencies as they resolve in this
environment.
"""
# keep a history to avoid infinite loops
if history is None:
history = set()... |
def revoke(self, paths: Union[str, Iterable[str]], users: Union[str, Iterable[str], User, Iterable[User]]):
"""
Revokes all access controls that are associated to the given path or collection of paths.
:param paths: the paths to remove access controls on
:param users: the users to revoke... | def function[revoke, parameter[self, paths, users]]:
constant[
Revokes all access controls that are associated to the given path or collection of paths.
:param paths: the paths to remove access controls on
:param users: the users to revoke access controls for. User may be in the represen... | keyword[def] identifier[revoke] ( identifier[self] , identifier[paths] : identifier[Union] [ identifier[str] , identifier[Iterable] [ identifier[str] ]], identifier[users] : identifier[Union] [ identifier[str] , identifier[Iterable] [ identifier[str] ], identifier[User] , identifier[Iterable] [ identifier[User] ]]):
... | def revoke(self, paths: Union[str, Iterable[str]], users: Union[str, Iterable[str], User, Iterable[User]]):
"""
Revokes all access controls that are associated to the given path or collection of paths.
:param paths: the paths to remove access controls on
:param users: the users to revoke acc... |
def job_success(self, job, queue, job_result):
"""
Called just after an execute call was successful.
job_result is the value returned by the callback, if any.
"""
job.queued.delete()
job.hmset(end=str(datetime.utcnow()), status=STATUSES.SUCCESS)
queue.success.rpus... | def function[job_success, parameter[self, job, queue, job_result]]:
constant[
Called just after an execute call was successful.
job_result is the value returned by the callback, if any.
]
call[name[job].queued.delete, parameter[]]
call[name[job].hmset, parameter[]]
... | keyword[def] identifier[job_success] ( identifier[self] , identifier[job] , identifier[queue] , identifier[job_result] ):
literal[string]
identifier[job] . identifier[queued] . identifier[delete] ()
identifier[job] . identifier[hmset] ( identifier[end] = identifier[str] ( identifier[dateti... | def job_success(self, job, queue, job_result):
"""
Called just after an execute call was successful.
job_result is the value returned by the callback, if any.
"""
job.queued.delete()
job.hmset(end=str(datetime.utcnow()), status=STATUSES.SUCCESS)
queue.success.rpush(job.ident)
... |
def lock_context(self, timeout='default', requested_key='exclusive'):
"""A context that locks
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to self.... | def function[lock_context, parameter[self, timeout, requested_key]]:
constant[A context that locks
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to ... | keyword[def] identifier[lock_context] ( identifier[self] , identifier[timeout] = literal[string] , identifier[requested_key] = literal[string] ):
literal[string]
keyword[if] identifier[requested_key] == literal[string] :
identifier[self] . identifier[lock_excl] ( identifier[timeout] )... | def lock_context(self, timeout='default', requested_key='exclusive'):
"""A context that locks
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to self.time... |
def validate(self, value):
"""validate function form OrValidator
Returns:
True if at least one of the validators
validate function return True
"""
errors = []
self._used_validator = []
for val in self._validators:
try:
... | def function[validate, parameter[self, value]]:
constant[validate function form OrValidator
Returns:
True if at least one of the validators
validate function return True
]
variable[errors] assign[=] list[[]]
name[self]._used_validator assign[=] list[[]]
... | keyword[def] identifier[validate] ( identifier[self] , identifier[value] ):
literal[string]
identifier[errors] =[]
identifier[self] . identifier[_used_validator] =[]
keyword[for] identifier[val] keyword[in] identifier[self] . identifier[_validators] :
keyword[try] ... | def validate(self, value):
"""validate function form OrValidator
Returns:
True if at least one of the validators
validate function return True
"""
errors = []
self._used_validator = []
for val in self._validators:
try:
val.validate(value)
... |
def _MergeByIdKeepNew(self):
"""Migrate all entities, discarding duplicates from the old/a schedule.
This method migrates all entities from the new/b schedule. It then migrates
entities in the old schedule where there isn't already an entity with the
same ID.
Unlike _MergeSameId this method migrat... | def function[_MergeByIdKeepNew, parameter[self]]:
constant[Migrate all entities, discarding duplicates from the old/a schedule.
This method migrates all entities from the new/b schedule. It then migrates
entities in the old schedule where there isn't already an entity with the
same ID.
Unlike ... | keyword[def] identifier[_MergeByIdKeepNew] ( identifier[self] ):
literal[string]
identifier[a_orig_migrated] ={}
identifier[b_orig_migrated] ={}
keyword[for] identifier[orig] keyword[in] identifier[self] . identifier[_GetIter] ( identifier[self] . identifier[feed_merger] . identifier[a_s... | def _MergeByIdKeepNew(self):
"""Migrate all entities, discarding duplicates from the old/a schedule.
This method migrates all entities from the new/b schedule. It then migrates
entities in the old schedule where there isn't already an entity with the
same ID.
Unlike _MergeSameId this method migrat... |
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Return a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit val... | def function[get_random_string, parameter[length, allowed_chars]]:
constant[
Return a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
]
if <ast.UnaryOp object at 0x7da18c4cc4c0> begin[... | keyword[def] identifier[get_random_string] ( identifier[length] = literal[int] ,
identifier[allowed_chars] = literal[string]
literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[using_sysrandom] :
identifier[random] . identifier[seed] (
... | def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Return a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
"""
if not using_... |
def wait(self, timeout=None, poll_interval=1.0):
"""
Wait for the upload to complete or to err out.
Will return the resulting Activity or raise an exception if the upload fails.
:param timeout: The max seconds to wait. Will raise TimeoutExceeded
exception if thi... | def function[wait, parameter[self, timeout, poll_interval]]:
constant[
Wait for the upload to complete or to err out.
Will return the resulting Activity or raise an exception if the upload fails.
:param timeout: The max seconds to wait. Will raise TimeoutExceeded
... | keyword[def] identifier[wait] ( identifier[self] , identifier[timeout] = keyword[None] , identifier[poll_interval] = literal[int] ):
literal[string]
identifier[start] = identifier[time] . identifier[time] ()
keyword[while] identifier[self] . identifier[activity_id] keyword[is] keyword[N... | def wait(self, timeout=None, poll_interval=1.0):
"""
Wait for the upload to complete or to err out.
Will return the resulting Activity or raise an exception if the upload fails.
:param timeout: The max seconds to wait. Will raise TimeoutExceeded
exception if this ti... |
def allocate_eip_address(domain=None, region=None, key=None, keyid=None, profile=None):
'''
Allocate a new Elastic IP address and associate it with your account.
domain
(string) Optional param - if set to exactly 'vpc', the address will be
allocated to the VPC. The default simply maps the ... | def function[allocate_eip_address, parameter[domain, region, key, keyid, profile]]:
constant[
Allocate a new Elastic IP address and associate it with your account.
domain
(string) Optional param - if set to exactly 'vpc', the address will be
allocated to the VPC. The default simply map... | keyword[def] identifier[allocate_eip_address] ( identifier[domain] = keyword[None] , identifier[region] = keyword[None] , identifier[key] = keyword[None] , identifier[keyid] = keyword[None] , identifier[profile] = keyword[None] ):
literal[string]
keyword[if] identifier[domain] keyword[and] identifier[do... | def allocate_eip_address(domain=None, region=None, key=None, keyid=None, profile=None):
"""
Allocate a new Elastic IP address and associate it with your account.
domain
(string) Optional param - if set to exactly 'vpc', the address will be
allocated to the VPC. The default simply maps the ... |
def getDjangoObjects(context):
"""
Returns a reference to the C{django_objects} on the context. If it doesn't
exist then it is created.
@rtype: Instance of L{DjangoReferenceCollection}
@since: 0.5
"""
c = context.extra
k = 'django_objects'
try:
return c[k]
except KeyErr... | def function[getDjangoObjects, parameter[context]]:
constant[
Returns a reference to the C{django_objects} on the context. If it doesn't
exist then it is created.
@rtype: Instance of L{DjangoReferenceCollection}
@since: 0.5
]
variable[c] assign[=] name[context].extra
variabl... | keyword[def] identifier[getDjangoObjects] ( identifier[context] ):
literal[string]
identifier[c] = identifier[context] . identifier[extra]
identifier[k] = literal[string]
keyword[try] :
keyword[return] identifier[c] [ identifier[k] ]
keyword[except] identifier[KeyError] :
... | def getDjangoObjects(context):
"""
Returns a reference to the C{django_objects} on the context. If it doesn't
exist then it is created.
@rtype: Instance of L{DjangoReferenceCollection}
@since: 0.5
"""
c = context.extra
k = 'django_objects'
try:
return c[k] # depends on [con... |
def _set_config(config):
"""Set gl configuration"""
pyglet_config = pyglet.gl.Config()
pyglet_config.red_size = config['red_size']
pyglet_config.green_size = config['green_size']
pyglet_config.blue_size = config['blue_size']
pyglet_config.alpha_size = config['alpha_size']
pyglet_config.acc... | def function[_set_config, parameter[config]]:
constant[Set gl configuration]
variable[pyglet_config] assign[=] call[name[pyglet].gl.Config, parameter[]]
name[pyglet_config].red_size assign[=] call[name[config]][constant[red_size]]
name[pyglet_config].green_size assign[=] call[name[config... | keyword[def] identifier[_set_config] ( identifier[config] ):
literal[string]
identifier[pyglet_config] = identifier[pyglet] . identifier[gl] . identifier[Config] ()
identifier[pyglet_config] . identifier[red_size] = identifier[config] [ literal[string] ]
identifier[pyglet_config] . identifier[gr... | def _set_config(config):
"""Set gl configuration"""
pyglet_config = pyglet.gl.Config()
pyglet_config.red_size = config['red_size']
pyglet_config.green_size = config['green_size']
pyglet_config.blue_size = config['blue_size']
pyglet_config.alpha_size = config['alpha_size']
pyglet_config.accum... |
def _music_lib_search(self, search, start, max_items):
"""Perform a music library search and extract search numbers.
You can get an overview of all the relevant search prefixes (like
'A:') and their meaning with the request:
.. code ::
response = device.contentDirectory.Brows... | def function[_music_lib_search, parameter[self, search, start, max_items]]:
constant[Perform a music library search and extract search numbers.
You can get an overview of all the relevant search prefixes (like
'A:') and their meaning with the request:
.. code ::
response = de... | keyword[def] identifier[_music_lib_search] ( identifier[self] , identifier[search] , identifier[start] , identifier[max_items] ):
literal[string]
identifier[response] = identifier[self] . identifier[contentDirectory] . identifier[Browse] ([
( literal[string] , identifier[search] ),
... | def _music_lib_search(self, search, start, max_items):
"""Perform a music library search and extract search numbers.
You can get an overview of all the relevant search prefixes (like
'A:') and their meaning with the request:
.. code ::
response = device.contentDirectory.Browse([
... |
def managed(name,
value=None,
host=DEFAULT_HOST,
port=DEFAULT_PORT,
time=DEFAULT_TIME,
min_compress_len=DEFAULT_MIN_COMPRESS_LEN):
'''
Manage a memcached key.
name
The key to manage
value
The value to set for that key
hos... | def function[managed, parameter[name, value, host, port, time, min_compress_len]]:
constant[
Manage a memcached key.
name
The key to manage
value
The value to set for that key
host
The memcached server IP address
port
The memcached server port
.. cod... | keyword[def] identifier[managed] ( identifier[name] ,
identifier[value] = keyword[None] ,
identifier[host] = identifier[DEFAULT_HOST] ,
identifier[port] = identifier[DEFAULT_PORT] ,
identifier[time] = identifier[DEFAULT_TIME] ,
identifier[min_compress_len] = identifier[DEFAULT_MIN_COMPRESS_LEN] ):
literal[s... | def managed(name, value=None, host=DEFAULT_HOST, port=DEFAULT_PORT, time=DEFAULT_TIME, min_compress_len=DEFAULT_MIN_COMPRESS_LEN):
"""
Manage a memcached key.
name
The key to manage
value
The value to set for that key
host
The memcached server IP address
port
... |
def user_role(name, rawtext, text, lineno, inliner, options=None, content=None):
"""Sphinx role for linking to a user profile. Defaults to linking to
Github profiles, but the profile URIS can be configured via the
``issues_user_uri`` config value.
Examples: ::
:user:`sloria`
Anchor text a... | def function[user_role, parameter[name, rawtext, text, lineno, inliner, options, content]]:
constant[Sphinx role for linking to a user profile. Defaults to linking to
Github profiles, but the profile URIS can be configured via the
``issues_user_uri`` config value.
Examples: ::
:user:`slori... | keyword[def] identifier[user_role] ( identifier[name] , identifier[rawtext] , identifier[text] , identifier[lineno] , identifier[inliner] , identifier[options] = keyword[None] , identifier[content] = keyword[None] ):
literal[string]
identifier[options] = identifier[options] keyword[or] {}
identifier[... | def user_role(name, rawtext, text, lineno, inliner, options=None, content=None):
"""Sphinx role for linking to a user profile. Defaults to linking to
Github profiles, but the profile URIS can be configured via the
``issues_user_uri`` config value.
Examples: ::
:user:`sloria`
Anchor text a... |
def query(self, variables, evidence=None, joint=True):
"""
Query method using belief propagation.
Parameters
----------
variables: list
list of variables for which you want to compute the probability
evidence: dict
a dict key, value pair as {var:... | def function[query, parameter[self, variables, evidence, joint]]:
constant[
Query method using belief propagation.
Parameters
----------
variables: list
list of variables for which you want to compute the probability
evidence: dict
a dict key, va... | keyword[def] identifier[query] ( identifier[self] , identifier[variables] , identifier[evidence] = keyword[None] , identifier[joint] = keyword[True] ):
literal[string]
keyword[return] identifier[self] . identifier[_query] ( identifier[variables] = identifier[variables] , identifier[operation] = li... | def query(self, variables, evidence=None, joint=True):
"""
Query method using belief propagation.
Parameters
----------
variables: list
list of variables for which you want to compute the probability
evidence: dict
a dict key, value pair as {var: sta... |
def _set_bundle_message(self, v, load=False):
"""
Setter method for bundle_message, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/rsvp/interface_refresh_reduction/bundle_message (container)
If this variable is read-only (config: false) in the
source YANG file, then _... | def function[_set_bundle_message, parameter[self, v, load]]:
constant[
Setter method for bundle_message, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/rsvp/interface_refresh_reduction/bundle_message (container)
If this variable is read-only (config: false) in the
... | keyword[def] identifier[_set_bundle_message] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
... | def _set_bundle_message(self, v, load=False):
"""
Setter method for bundle_message, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/rsvp/interface_refresh_reduction/bundle_message (container)
If this variable is read-only (config: false) in the
source YANG file, then _... |
def update_rwalk(self, blob):
"""Update the random walk proposal scale based on the current
number of accepted/rejected steps."""
self.scale = blob['scale']
accept, reject = blob['accept'], blob['reject']
facc = (1. * accept) / (accept + reject)
norm = max(self.facc, 1. ... | def function[update_rwalk, parameter[self, blob]]:
constant[Update the random walk proposal scale based on the current
number of accepted/rejected steps.]
name[self].scale assign[=] call[name[blob]][constant[scale]]
<ast.Tuple object at 0x7da1b1ecf070> assign[=] tuple[[<ast.Subscript obj... | keyword[def] identifier[update_rwalk] ( identifier[self] , identifier[blob] ):
literal[string]
identifier[self] . identifier[scale] = identifier[blob] [ literal[string] ]
identifier[accept] , identifier[reject] = identifier[blob] [ literal[string] ], identifier[blob] [ literal[string] ]
... | def update_rwalk(self, blob):
"""Update the random walk proposal scale based on the current
number of accepted/rejected steps."""
self.scale = blob['scale']
(accept, reject) = (blob['accept'], blob['reject'])
facc = 1.0 * accept / (accept + reject)
norm = max(self.facc, 1.0 - self.facc) * se... |
def patch(nml_path, nml_patch, out_path=None):
"""Create a new namelist based on an input namelist and reference dict.
>>> f90nml.patch('data.nml', nml_patch, 'patched_data.nml')
This function is equivalent to the ``read`` function of the ``Parser``
object with the patch output arguments.
>>> par... | def function[patch, parameter[nml_path, nml_patch, out_path]]:
constant[Create a new namelist based on an input namelist and reference dict.
>>> f90nml.patch('data.nml', nml_patch, 'patched_data.nml')
This function is equivalent to the ``read`` function of the ``Parser``
object with the patch outp... | keyword[def] identifier[patch] ( identifier[nml_path] , identifier[nml_patch] , identifier[out_path] = keyword[None] ):
literal[string]
identifier[parser] = identifier[Parser] ()
keyword[return] identifier[parser] . identifier[read] ( identifier[nml_path] , identifier[nml_patch] , identifier[out_pat... | def patch(nml_path, nml_patch, out_path=None):
"""Create a new namelist based on an input namelist and reference dict.
>>> f90nml.patch('data.nml', nml_patch, 'patched_data.nml')
This function is equivalent to the ``read`` function of the ``Parser``
object with the patch output arguments.
>>> par... |
def update_user_type(self):
"""Return either 'tutor' or 'student' based on which radio
button is selected.
"""
if self.rb_tutor.isChecked():
self.user_type = 'tutor'
elif self.rb_student.isChecked():
self.user_type = 'student'
self.accept() | def function[update_user_type, parameter[self]]:
constant[Return either 'tutor' or 'student' based on which radio
button is selected.
]
if call[name[self].rb_tutor.isChecked, parameter[]] begin[:]
name[self].user_type assign[=] constant[tutor]
call[name[self].acce... | keyword[def] identifier[update_user_type] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[rb_tutor] . identifier[isChecked] ():
identifier[self] . identifier[user_type] = literal[string]
keyword[elif] identifier[self] . identifier[rb_student]... | def update_user_type(self):
"""Return either 'tutor' or 'student' based on which radio
button is selected.
"""
if self.rb_tutor.isChecked():
self.user_type = 'tutor' # depends on [control=['if'], data=[]]
elif self.rb_student.isChecked():
self.user_type = 'student' # depend... |
def present(name, provider):
'''
Ensure the RackSpace queue exists.
name
Name of the Rackspace queue.
provider
Salt Cloud Provider
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
is_present = list(__salt__['cloud.action']('queues_exists', provider=pr... | def function[present, parameter[name, provider]]:
constant[
Ensure the RackSpace queue exists.
name
Name of the Rackspace queue.
provider
Salt Cloud Provider
]
variable[ret] assign[=] dictionary[[<ast.Constant object at 0x7da1b1c23460>, <ast.Constant object at 0x7da1b1c... | keyword[def] identifier[present] ( identifier[name] , identifier[provider] ):
literal[string]
identifier[ret] ={ literal[string] : identifier[name] , literal[string] : keyword[True] , literal[string] : literal[string] , literal[string] :{}}
identifier[is_present] = identifier[list] ( identifier[__sal... | def present(name, provider):
"""
Ensure the RackSpace queue exists.
name
Name of the Rackspace queue.
provider
Salt Cloud Provider
"""
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
is_present = list(__salt__['cloud.action']('queues_exists', provider=pro... |
def get_file(self, **kwargs):
"""
Return the FSEntry that matches parameters.
:param str file_uuid: UUID of the target FSEntry.
:param str label: structMap LABEL of the target FSEntry.
:param str type: structMap TYPE of the target FSEntry.
:returns: :class:`FSEntry` that... | def function[get_file, parameter[self]]:
constant[
Return the FSEntry that matches parameters.
:param str file_uuid: UUID of the target FSEntry.
:param str label: structMap LABEL of the target FSEntry.
:param str type: structMap TYPE of the target FSEntry.
:returns: :cla... | keyword[def] identifier[get_file] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[for] identifier[entry] keyword[in] identifier[self] . identifier[all_files] ():
keyword[if] identifier[all] ( identifier[value] == identifier[getattr] (... | def get_file(self, **kwargs):
"""
Return the FSEntry that matches parameters.
:param str file_uuid: UUID of the target FSEntry.
:param str label: structMap LABEL of the target FSEntry.
:param str type: structMap TYPE of the target FSEntry.
:returns: :class:`FSEntry` that mat... |
def count_jobs_to_dequeue(self):
""" Returns the number of jobs that can be dequeued right now from the queue. """
# timed ZSET
if self.is_timed:
return context.connections.redis.zcount(
self.redis_key,
"-inf",
time.time())
# ... | def function[count_jobs_to_dequeue, parameter[self]]:
constant[ Returns the number of jobs that can be dequeued right now from the queue. ]
if name[self].is_timed begin[:]
return[call[name[context].connections.redis.zcount, parameter[name[self].redis_key, constant[-inf], call[name[time].time, pa... | keyword[def] identifier[count_jobs_to_dequeue] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[is_timed] :
keyword[return] identifier[context] . identifier[connections] . identifier[redis] . identifier[zcount] (
identifier[self] ... | def count_jobs_to_dequeue(self):
""" Returns the number of jobs that can be dequeued right now from the queue. """
# timed ZSET
if self.is_timed:
return context.connections.redis.zcount(self.redis_key, '-inf', time.time()) # depends on [control=['if'], data=[]]
else:
# In all other case... |
def get_storage_location():
""" get the portal with the plone.api
"""
location = api.portal.getSite()
if location.get('bika_setup', False):
location = location['bika_setup']
return location | def function[get_storage_location, parameter[]]:
constant[ get the portal with the plone.api
]
variable[location] assign[=] call[name[api].portal.getSite, parameter[]]
if call[name[location].get, parameter[constant[bika_setup], constant[False]]] begin[:]
variable[location] as... | keyword[def] identifier[get_storage_location] ():
literal[string]
identifier[location] = identifier[api] . identifier[portal] . identifier[getSite] ()
keyword[if] identifier[location] . identifier[get] ( literal[string] , keyword[False] ):
identifier[location] = identifier[location] [ litera... | def get_storage_location():
""" get the portal with the plone.api
"""
location = api.portal.getSite()
if location.get('bika_setup', False):
location = location['bika_setup'] # depends on [control=['if'], data=[]]
return location |
def H13(self):
"Information measure of correlation 2."
# An imaginary result has been encountered once in the Matlab
# version. The reason is unclear.
return np.sqrt(1 - np.exp(-2 * (self.hxy2 - self.H9()))) | def function[H13, parameter[self]]:
constant[Information measure of correlation 2.]
return[call[name[np].sqrt, parameter[binary_operation[constant[1] - call[name[np].exp, parameter[binary_operation[<ast.UnaryOp object at 0x7da20c6c6b60> * binary_operation[name[self].hxy2 - call[name[self].H9, parameter[]]]]... | keyword[def] identifier[H13] ( identifier[self] ):
literal[string]
keyword[return] identifier[np] . identifier[sqrt] ( literal[int] - identifier[np] . identifier[exp] (- literal[int] *( identifier[self] . identifier[hxy2] - identifier[self] . identifier[H9] ()))) | def H13(self):
"""Information measure of correlation 2."""
# An imaginary result has been encountered once in the Matlab
# version. The reason is unclear.
return np.sqrt(1 - np.exp(-2 * (self.hxy2 - self.H9()))) |
def symmetric_difference(self, sig: Scope) -> Scope:
""" Create a new Set with values present in only one Set """
new = Scope(sig=self._hsig.values(), state=self.state)
new ^= sig
return new | def function[symmetric_difference, parameter[self, sig]]:
constant[ Create a new Set with values present in only one Set ]
variable[new] assign[=] call[name[Scope], parameter[]]
<ast.AugAssign object at 0x7da1b013d030>
return[name[new]] | keyword[def] identifier[symmetric_difference] ( identifier[self] , identifier[sig] : identifier[Scope] )-> identifier[Scope] :
literal[string]
identifier[new] = identifier[Scope] ( identifier[sig] = identifier[self] . identifier[_hsig] . identifier[values] (), identifier[state] = identifier[self] .... | def symmetric_difference(self, sig: Scope) -> Scope:
""" Create a new Set with values present in only one Set """
new = Scope(sig=self._hsig.values(), state=self.state)
new ^= sig
return new |
def implements(*interfaces):
"""Can be used in the class definition of `Component`
subclasses to declare the extension points that are extended.
"""
import sys
frame = sys._getframe(1)
locals_ = frame.f_locals
# Some sanity checks
msg = 'implements() can... | def function[implements, parameter[]]:
constant[Can be used in the class definition of `Component`
subclasses to declare the extension points that are extended.
]
import module[sys]
variable[frame] assign[=] call[name[sys]._getframe, parameter[constant[1]]]
variable[locals_] ... | keyword[def] identifier[implements] (* identifier[interfaces] ):
literal[string]
keyword[import] identifier[sys]
identifier[frame] = identifier[sys] . identifier[_getframe] ( literal[int] )
identifier[locals_] = identifier[frame] . identifier[f_locals]
ident... | def implements(*interfaces):
"""Can be used in the class definition of `Component`
subclasses to declare the extension points that are extended.
"""
import sys
frame = sys._getframe(1)
locals_ = frame.f_locals
# Some sanity checks
msg = 'implements() can only be used in a class d... |
def _leastUsedCell(cls, random, cells, connections):
"""
Gets the cell with the smallest number of segments.
Break ties randomly.
:param random: (Object)
Random number generator. Gets mutated.
:param cells: (list)
Indices of cells.
:param connections: (Object)
Connections instance... | def function[_leastUsedCell, parameter[cls, random, cells, connections]]:
constant[
Gets the cell with the smallest number of segments.
Break ties randomly.
:param random: (Object)
Random number generator. Gets mutated.
:param cells: (list)
Indices of cells.
:param connections: (O... | keyword[def] identifier[_leastUsedCell] ( identifier[cls] , identifier[random] , identifier[cells] , identifier[connections] ):
literal[string]
identifier[leastUsedCells] =[]
identifier[minNumSegments] = identifier[float] ( literal[string] )
keyword[for] identifier[cell] keyword[in] identifier... | def _leastUsedCell(cls, random, cells, connections):
"""
Gets the cell with the smallest number of segments.
Break ties randomly.
:param random: (Object)
Random number generator. Gets mutated.
:param cells: (list)
Indices of cells.
:param connections: (Object)
Connections instance... |
def primeSieve(k):
"""return a list with length k + 1, showing if list[i] == 1, i is a prime
else if list[i] == 0, i is a composite, if list[i] == -1, not defined"""
def isPrime(n):
"""return True is given number n is absolutely prime,
return False is otherwise."""
for i in range(2,... | def function[primeSieve, parameter[k]]:
constant[return a list with length k + 1, showing if list[i] == 1, i is a prime
else if list[i] == 0, i is a composite, if list[i] == -1, not defined]
def function[isPrime, parameter[n]]:
constant[return True is given number n is absolutely pri... | keyword[def] identifier[primeSieve] ( identifier[k] ):
literal[string]
keyword[def] identifier[isPrime] ( identifier[n] ):
literal[string]
keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , identifier[int] ( identifier[n] ** literal[int] )+ literal[int] ):
... | def primeSieve(k):
"""return a list with length k + 1, showing if list[i] == 1, i is a prime
else if list[i] == 0, i is a composite, if list[i] == -1, not defined"""
def isPrime(n):
"""return True is given number n is absolutely prime,
return False is otherwise."""
for i in range(2,... |
def get_from_geo(self, lat, lng, distance, skip_cache=False):
"""
Calls `postcodes.get_from_geo` but checks the correctness of
all arguments, and by default utilises a local cache.
:param skip_cache: optional argument specifying whether to skip
the cache and... | def function[get_from_geo, parameter[self, lat, lng, distance, skip_cache]]:
constant[
Calls `postcodes.get_from_geo` but checks the correctness of
all arguments, and by default utilises a local cache.
:param skip_cache: optional argument specifying whether to skip
... | keyword[def] identifier[get_from_geo] ( identifier[self] , identifier[lat] , identifier[lng] , identifier[distance] , identifier[skip_cache] = keyword[False] ):
literal[string]
identifier[lat] , identifier[lng] , identifier[distance] = identifier[float] ( identifier[lat] ), identifier[floa... | def get_from_geo(self, lat, lng, distance, skip_cache=False):
"""
Calls `postcodes.get_from_geo` but checks the correctness of
all arguments, and by default utilises a local cache.
:param skip_cache: optional argument specifying whether to skip
the cache and mak... |
def ParseNotificationcenterRow(
self, parser_mediator, query, row, **unused_kwargs):
"""Parses a message row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
... | def function[ParseNotificationcenterRow, parameter[self, parser_mediator, query, row]]:
constant[Parses a message row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row... | keyword[def] identifier[ParseNotificationcenterRow] (
identifier[self] , identifier[parser_mediator] , identifier[query] , identifier[row] ,** identifier[unused_kwargs] ):
literal[string]
identifier[query_hash] = identifier[hash] ( identifier[query] )
identifier[event_data] = identifier[MacNotificat... | def ParseNotificationcenterRow(self, parser_mediator, query, row, **unused_kwargs):
"""Parses a message row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (s... |
async def write_request(
self, method: constants.HttpRequestMethod, *,
uri: str="/", authority: Optional[str]=None,
scheme: Optional[str]=None,
headers: Optional[_HeaderType]=None) -> \
"writers.HttpRequestWriter":
"""
Send next request to the server.
... | <ast.AsyncFunctionDef object at 0x7da18c4cc490> | keyword[async] keyword[def] identifier[write_request] (
identifier[self] , identifier[method] : identifier[constants] . identifier[HttpRequestMethod] ,*,
identifier[uri] : identifier[str] = literal[string] , identifier[authority] : identifier[Optional] [ identifier[str] ]= keyword[None] ,
identifier[scheme] : ide... | async def write_request(self, method: constants.HttpRequestMethod, *, uri: str='/', authority: Optional[str]=None, scheme: Optional[str]=None, headers: Optional[_HeaderType]=None) -> 'writers.HttpRequestWriter':
"""
Send next request to the server.
"""
return await self._delegate.write_request(m... |
def create_label(self, label, doc=None):
"""
Create a new label
Arguments:
doc --- first document on which the label must be added (required
for now)
"""
label = copy.copy(label)
assert(label not in self.labels.values())
self.label... | def function[create_label, parameter[self, label, doc]]:
constant[
Create a new label
Arguments:
doc --- first document on which the label must be added (required
for now)
]
variable[label] assign[=] call[name[copy].copy, parameter[name[label]]]
... | keyword[def] identifier[create_label] ( identifier[self] , identifier[label] , identifier[doc] = keyword[None] ):
literal[string]
identifier[label] = identifier[copy] . identifier[copy] ( identifier[label] )
keyword[assert] ( identifier[label] keyword[not] keyword[in] identifier[self] .... | def create_label(self, label, doc=None):
"""
Create a new label
Arguments:
doc --- first document on which the label must be added (required
for now)
"""
label = copy.copy(label)
assert label not in self.labels.values()
self.labels[label.name] = l... |
def morphDataLists(fromList, toList, stepList):
'''
Iteratively morph fromList into toList using the values 0 to 1 in stepList
stepList: a value of 0 means no change and a value of 1 means a complete
change to the other value
'''
# If there are more than 1 pitch value, then we align the da... | def function[morphDataLists, parameter[fromList, toList, stepList]]:
constant[
Iteratively morph fromList into toList using the values 0 to 1 in stepList
stepList: a value of 0 means no change and a value of 1 means a complete
change to the other value
]
<ast.Tuple object at 0x7da1b... | keyword[def] identifier[morphDataLists] ( identifier[fromList] , identifier[toList] , identifier[stepList] ):
literal[string]
identifier[fromListRel] , identifier[fromStartTime] , identifier[fromEndTime] = identifier[_makeTimingRelative] ( identifier[fromList] )
... | def morphDataLists(fromList, toList, stepList):
"""
Iteratively morph fromList into toList using the values 0 to 1 in stepList
stepList: a value of 0 means no change and a value of 1 means a complete
change to the other value
"""
# If there are more than 1 pitch value, then we align the dat... |
def received(self, limit=None):
"""
Returns all the events that have been received (excluding sent events), until a limit if defined
Args:
limit (int, optional): the max length of the events to return (Default value = None)
Returns:
list: a list of received events
... | def function[received, parameter[self, limit]]:
constant[
Returns all the events that have been received (excluding sent events), until a limit if defined
Args:
limit (int, optional): the max length of the events to return (Default value = None)
Returns:
list: a lis... | keyword[def] identifier[received] ( identifier[self] , identifier[limit] = keyword[None] ):
literal[string]
keyword[return] identifier[list] ( identifier[itertools] . identifier[islice] (( identifier[itertools] . identifier[filterfalse] ( keyword[lambda] identifier[x] : identifier[x] [ literal[in... | def received(self, limit=None):
"""
Returns all the events that have been received (excluding sent events), until a limit if defined
Args:
limit (int, optional): the max length of the events to return (Default value = None)
Returns:
list: a list of received events
... |
def ParseApplicationUsageRow(
self, parser_mediator, query, row, **unused_kwargs):
"""Parses an application usage row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the r... | def function[ParseApplicationUsageRow, parameter[self, parser_mediator, query, row]]:
constant[Parses an application usage row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that create... | keyword[def] identifier[ParseApplicationUsageRow] (
identifier[self] , identifier[parser_mediator] , identifier[query] , identifier[row] ,** identifier[unused_kwargs] ):
literal[string]
identifier[query_hash] = identifier[hash] ( identifier[query] )
identifier[application_name] = identifie... | def ParseApplicationUsageRow(self, parser_mediator, query, row, **unused_kwargs):
"""Parses an application usage row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
... |
def freeze():
"""Combine all dependencies for the Agent's static environment."""
echo_waiting('Verifying collected packages...')
catalog, errors = make_catalog()
if errors:
for error in errors:
echo_failure(error)
abort()
static_file = get_agent_requirements()
echo_... | def function[freeze, parameter[]]:
constant[Combine all dependencies for the Agent's static environment.]
call[name[echo_waiting], parameter[constant[Verifying collected packages...]]]
<ast.Tuple object at 0x7da20c6e7220> assign[=] call[name[make_catalog], parameter[]]
if name[errors] be... | keyword[def] identifier[freeze] ():
literal[string]
identifier[echo_waiting] ( literal[string] )
identifier[catalog] , identifier[errors] = identifier[make_catalog] ()
keyword[if] identifier[errors] :
keyword[for] identifier[error] keyword[in] identifier[errors] :
identi... | def freeze():
"""Combine all dependencies for the Agent's static environment."""
echo_waiting('Verifying collected packages...')
(catalog, errors) = make_catalog()
if errors:
for error in errors:
echo_failure(error) # depends on [control=['for'], data=['error']]
abort() # d... |
def severity(self):
"""Retrieves the severity for the incident/incidents from the
output response
Returns:
severity(namedtuple): List of named tuples of severity for the
incident/incidents
"""
resource_list = self.traffic_incident()
severity = nam... | def function[severity, parameter[self]]:
constant[Retrieves the severity for the incident/incidents from the
output response
Returns:
severity(namedtuple): List of named tuples of severity for the
incident/incidents
]
variable[resource_list] assign[=] cal... | keyword[def] identifier[severity] ( identifier[self] ):
literal[string]
identifier[resource_list] = identifier[self] . identifier[traffic_incident] ()
identifier[severity] = identifier[namedtuple] ( literal[string] , literal[string] )
keyword[if] identifier[len] ( identifier[reso... | def severity(self):
"""Retrieves the severity for the incident/incidents from the
output response
Returns:
severity(namedtuple): List of named tuples of severity for the
incident/incidents
"""
resource_list = self.traffic_incident()
severity = namedtuple('sev... |
def self_edge_filter(_: BELGraph, source: BaseEntity, target: BaseEntity, __: str) -> bool:
"""Check if the source and target nodes are the same."""
return source == target | def function[self_edge_filter, parameter[_, source, target, __]]:
constant[Check if the source and target nodes are the same.]
return[compare[name[source] equal[==] name[target]]] | keyword[def] identifier[self_edge_filter] ( identifier[_] : identifier[BELGraph] , identifier[source] : identifier[BaseEntity] , identifier[target] : identifier[BaseEntity] , identifier[__] : identifier[str] )-> identifier[bool] :
literal[string]
keyword[return] identifier[source] == identifier[target] | def self_edge_filter(_: BELGraph, source: BaseEntity, target: BaseEntity, __: str) -> bool:
"""Check if the source and target nodes are the same."""
return source == target |
def find_page_location(command, specified_platform):
"""Find the command man page in the pages directory."""
repo_directory = get_config()['repo_directory']
default_platform = get_config()['platform']
command_platform = (
specified_platform if specified_platform else default_platform)
with ... | def function[find_page_location, parameter[command, specified_platform]]:
constant[Find the command man page in the pages directory.]
variable[repo_directory] assign[=] call[call[name[get_config], parameter[]]][constant[repo_directory]]
variable[default_platform] assign[=] call[call[name[get_con... | keyword[def] identifier[find_page_location] ( identifier[command] , identifier[specified_platform] ):
literal[string]
identifier[repo_directory] = identifier[get_config] ()[ literal[string] ]
identifier[default_platform] = identifier[get_config] ()[ literal[string] ]
identifier[command_platform] ... | def find_page_location(command, specified_platform):
"""Find the command man page in the pages directory."""
repo_directory = get_config()['repo_directory']
default_platform = get_config()['platform']
command_platform = specified_platform if specified_platform else default_platform
with io.open(path... |
def is_gesture(self):
"""Macro to check if this event is
a :class:`~libinput.event.GestureEvent`.
"""
if self in {type(self).GESTURE_SWIPE_BEGIN, type(self).GESTURE_SWIPE_END,
type(self).GESTURE_SWIPE_UPDATE, type(self).GESTURE_PINCH_BEGIN,
type(self).GESTURE_PINCH_UPDATE, type(self).GESTURE_PINCH_END}:
... | def function[is_gesture, parameter[self]]:
constant[Macro to check if this event is
a :class:`~libinput.event.GestureEvent`.
]
if compare[name[self] in <ast.Set object at 0x7da18f00ffa0>] begin[:]
return[constant[True]] | keyword[def] identifier[is_gesture] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] keyword[in] { identifier[type] ( identifier[self] ). identifier[GESTURE_SWIPE_BEGIN] , identifier[type] ( identifier[self] ). identifier[GESTURE_SWIPE_END] ,
identifier[type] ( identifier[self] ). ident... | def is_gesture(self):
"""Macro to check if this event is
a :class:`~libinput.event.GestureEvent`.
"""
if self in {type(self).GESTURE_SWIPE_BEGIN, type(self).GESTURE_SWIPE_END, type(self).GESTURE_SWIPE_UPDATE, type(self).GESTURE_PINCH_BEGIN, type(self).GESTURE_PINCH_UPDATE, type(self).GESTURE_PINCH_END}:
... |
def flatten(self, lst=None):
"""syntax.flatten(token_stream) - compile period tokens
This turns a stream of tokens into p-code for the trivial
stack machine that evaluates period expressions in in_period.
"""
tree = []
uops = [] # accumulated unary ... | def function[flatten, parameter[self, lst]]:
constant[syntax.flatten(token_stream) - compile period tokens
This turns a stream of tokens into p-code for the trivial
stack machine that evaluates period expressions in in_period.
]
variable[tree] assign[=] list[[]]
variable... | keyword[def] identifier[flatten] ( identifier[self] , identifier[lst] = keyword[None] ):
literal[string]
identifier[tree] =[]
identifier[uops] =[]
identifier[s] = identifier[Stack] ()
identifier[group_len] = literal[int]
keyword[for] identifier[item] keyword[i... | def flatten(self, lst=None):
"""syntax.flatten(token_stream) - compile period tokens
This turns a stream of tokens into p-code for the trivial
stack machine that evaluates period expressions in in_period.
"""
tree = []
uops = [] # accumulated unary operations
s = Stack()
gr... |
def constructor_args(class_, *args, **kwargs):
"""
Return (args, kwargs) matching the function signature
:param callable: callable to inspect
:type callable: Callable
:param args:
:type args:
:param kwargs:
:type kwargs:
:return: (args, kwargs) matching the function signature
:r... | def function[constructor_args, parameter[class_]]:
constant[
Return (args, kwargs) matching the function signature
:param callable: callable to inspect
:type callable: Callable
:param args:
:type args:
:param kwargs:
:type kwargs:
:return: (args, kwargs) matching the function si... | keyword[def] identifier[constructor_args] ( identifier[class_] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[argspec] = identifier[getargspec] ( identifier[_constructor] ( identifier[class_] ))
keyword[return] identifier[argspec_args] ( identifier[argspec] , keyword[True] ,... | def constructor_args(class_, *args, **kwargs):
"""
Return (args, kwargs) matching the function signature
:param callable: callable to inspect
:type callable: Callable
:param args:
:type args:
:param kwargs:
:type kwargs:
:return: (args, kwargs) matching the function signature
:r... |
def _get_trendline(self,date0=None,date1=None,on=None,kind='trend',to_strfmt='%Y-%m-%d',from_strfmt='%d%b%y',**kwargs):
"""
Returns a trendline (line), support or resistance
Parameters:
date0 : string
Trendline starting date
date1 : string
Trendline end date
on : string
Indicate the data... | def function[_get_trendline, parameter[self, date0, date1, on, kind, to_strfmt, from_strfmt]]:
constant[
Returns a trendline (line), support or resistance
Parameters:
date0 : string
Trendline starting date
date1 : string
Trendline end date
on : string
Indicate the data series in wh... | keyword[def] identifier[_get_trendline] ( identifier[self] , identifier[date0] = keyword[None] , identifier[date1] = keyword[None] , identifier[on] = keyword[None] , identifier[kind] = literal[string] , identifier[to_strfmt] = literal[string] , identifier[from_strfmt] = literal[string] ,** identifier[kwargs] ):
li... | def _get_trendline(self, date0=None, date1=None, on=None, kind='trend', to_strfmt='%Y-%m-%d', from_strfmt='%d%b%y', **kwargs):
"""
Returns a trendline (line), support or resistance
Parameters:
date0 : string
Trendline starting date
date1 : string
Trendline end date
on : string
Indicate... |
def _read_stream(self, stream):
"""
Read in the pod stream
"""
data = yaml.safe_load_all(stream=stream)
obj = self._find_convertable_object(data)
pod = self.pod_types[obj['kind']](obj)
return obj, pod.get('containers'), self.ingest_volumes_param(pod.get('volumes',... | def function[_read_stream, parameter[self, stream]]:
constant[
Read in the pod stream
]
variable[data] assign[=] call[name[yaml].safe_load_all, parameter[]]
variable[obj] assign[=] call[name[self]._find_convertable_object, parameter[name[data]]]
variable[pod] assign[=] ca... | keyword[def] identifier[_read_stream] ( identifier[self] , identifier[stream] ):
literal[string]
identifier[data] = identifier[yaml] . identifier[safe_load_all] ( identifier[stream] = identifier[stream] )
identifier[obj] = identifier[self] . identifier[_find_convertable_object] ( identifie... | def _read_stream(self, stream):
"""
Read in the pod stream
"""
data = yaml.safe_load_all(stream=stream)
obj = self._find_convertable_object(data)
pod = self.pod_types[obj['kind']](obj)
return (obj, pod.get('containers'), self.ingest_volumes_param(pod.get('volumes', []))) |
def sg_print(tensor_list):
r"""Simple tensor printing function for debugging.
Prints the value, shape, and data type of each tensor in the list.
Args:
tensor_list: A list/tuple of tensors or a single tensor.
Returns:
The value of the tensors.
For example,
```p... | def function[sg_print, parameter[tensor_list]]:
constant[Simple tensor printing function for debugging.
Prints the value, shape, and data type of each tensor in the list.
Args:
tensor_list: A list/tuple of tensors or a single tensor.
Returns:
The value of the tensors.
... | keyword[def] identifier[sg_print] ( identifier[tensor_list] ):
literal[string]
keyword[if] identifier[type] ( identifier[tensor_list] ) keyword[is] keyword[not] identifier[list] keyword[and] identifier[type] ( identifier[tensor_list] ) keyword[is] keyword[not] identifier[tuple] :
ident... | def sg_print(tensor_list):
"""Simple tensor printing function for debugging.
Prints the value, shape, and data type of each tensor in the list.
Args:
tensor_list: A list/tuple of tensors or a single tensor.
Returns:
The value of the tensors.
For example,
```py... |
def root_block(template_name=DEFAULT_TEMPLATE_NAME):
"""A decorator that is used to define that the decorated block function
will be at the root of the block template hierarchy. In the usual case
this will be the HTML skeleton of the document, unless the template is used
to serve partial HTML rendering... | def function[root_block, parameter[template_name]]:
constant[A decorator that is used to define that the decorated block function
will be at the root of the block template hierarchy. In the usual case
this will be the HTML skeleton of the document, unless the template is used
to serve partial HTML ... | keyword[def] identifier[root_block] ( identifier[template_name] = identifier[DEFAULT_TEMPLATE_NAME] ):
literal[string]
keyword[def] identifier[decorator] ( identifier[block_func] ):
identifier[block] = identifier[RootBlock] ( identifier[block_func] , identifier[template_name] )
keyword[r... | def root_block(template_name=DEFAULT_TEMPLATE_NAME):
"""A decorator that is used to define that the decorated block function
will be at the root of the block template hierarchy. In the usual case
this will be the HTML skeleton of the document, unless the template is used
to serve partial HTML rendering... |
def make_tree(statement, filename="<aexec>", symbol="single", local={}):
"""Helper for *aexec*."""
# Create tree
tree = ast.parse(CORO_CODE, filename, symbol)
# Check expression statement
if isinstance(statement, ast.Expr):
tree.body[0].body[0].value.elts[0] = statement.value
else:
... | def function[make_tree, parameter[statement, filename, symbol, local]]:
constant[Helper for *aexec*.]
variable[tree] assign[=] call[name[ast].parse, parameter[name[CORO_CODE], name[filename], name[symbol]]]
if call[name[isinstance], parameter[name[statement], name[ast].Expr]] begin[:]
... | keyword[def] identifier[make_tree] ( identifier[statement] , identifier[filename] = literal[string] , identifier[symbol] = literal[string] , identifier[local] ={}):
literal[string]
identifier[tree] = identifier[ast] . identifier[parse] ( identifier[CORO_CODE] , identifier[filename] , identifier[symbol... | def make_tree(statement, filename='<aexec>', symbol='single', local={}):
"""Helper for *aexec*."""
# Create tree
tree = ast.parse(CORO_CODE, filename, symbol)
# Check expression statement
if isinstance(statement, ast.Expr):
tree.body[0].body[0].value.elts[0] = statement.value # depends on [... |
def register_model(self, model):
"""
Register ``model`` to this group
:param model: model name
:return: None
"""
assert isinstance(model, str)
if model not in self.all_models:
self.all_models.append(model) | def function[register_model, parameter[self, model]]:
constant[
Register ``model`` to this group
:param model: model name
:return: None
]
assert[call[name[isinstance], parameter[name[model], name[str]]]]
if compare[name[model] <ast.NotIn object at 0x7da2590d7190> nam... | keyword[def] identifier[register_model] ( identifier[self] , identifier[model] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[model] , identifier[str] )
keyword[if] identifier[model] keyword[not] keyword[in] identifier[self] . identifier[all_models] :
... | def register_model(self, model):
"""
Register ``model`` to this group
:param model: model name
:return: None
"""
assert isinstance(model, str)
if model not in self.all_models:
self.all_models.append(model) # depends on [control=['if'], data=['model']] |
def get_deleted_objects(self, request, queryset):
"""
Find all objects related to instances of ``queryset`` that should also be deleted.
Returns
- to_delete - a nested list of strings suitable for display in the template with the ``unordered_list`` filter.
- model_count ... | def function[get_deleted_objects, parameter[self, request, queryset]]:
constant[
Find all objects related to instances of ``queryset`` that should also be deleted.
Returns
- to_delete - a nested list of strings suitable for display in the template with the ``unordered_list`` filter.... | keyword[def] identifier[get_deleted_objects] ( identifier[self] , identifier[request] , identifier[queryset] ):
literal[string]
identifier[collector] = identifier[NestedObjects] ( identifier[using] = identifier[queryset] . identifier[db] )
identifier[collector] . identifier[collect] ( iden... | def get_deleted_objects(self, request, queryset):
"""
Find all objects related to instances of ``queryset`` that should also be deleted.
Returns
- to_delete - a nested list of strings suitable for display in the template with the ``unordered_list`` filter.
- model_count - st... |
def get_residual_norms(H, self_adjoint=False):
'''Compute relative residual norms from Hessenberg matrix.
It is assumed that the initial guess is chosen as zero.'''
H = H.copy()
n_, n = H.shape
y = numpy.eye(n_, 1, dtype=H.dtype)
resnorms = [1.]
for i in range(n_-1):
G = Givens(H[i:... | def function[get_residual_norms, parameter[H, self_adjoint]]:
constant[Compute relative residual norms from Hessenberg matrix.
It is assumed that the initial guess is chosen as zero.]
variable[H] assign[=] call[name[H].copy, parameter[]]
<ast.Tuple object at 0x7da1b26279a0> assign[=] name[H... | keyword[def] identifier[get_residual_norms] ( identifier[H] , identifier[self_adjoint] = keyword[False] ):
literal[string]
identifier[H] = identifier[H] . identifier[copy] ()
identifier[n_] , identifier[n] = identifier[H] . identifier[shape]
identifier[y] = identifier[numpy] . identifier[eye] ( ... | def get_residual_norms(H, self_adjoint=False):
"""Compute relative residual norms from Hessenberg matrix.
It is assumed that the initial guess is chosen as zero."""
H = H.copy()
(n_, n) = H.shape
y = numpy.eye(n_, 1, dtype=H.dtype)
resnorms = [1.0]
for i in range(n_ - 1):
G = Givens... |
def outline(self, level=logging.INFO, message=""):
"""Print an outline of the actions the plan is going to take.
The outline will represent the rough ordering of the steps that will be
taken.
Args:
level (int, optional): a valid log level that should be used to log
... | def function[outline, parameter[self, level, message]]:
constant[Print an outline of the actions the plan is going to take.
The outline will represent the rough ordering of the steps that will be
taken.
Args:
level (int, optional): a valid log level that should be used to log... | keyword[def] identifier[outline] ( identifier[self] , identifier[level] = identifier[logging] . identifier[INFO] , identifier[message] = literal[string] ):
literal[string]
identifier[steps] = literal[int]
identifier[logger] . identifier[log] ( identifier[level] , literal[string] , identif... | def outline(self, level=logging.INFO, message=''):
"""Print an outline of the actions the plan is going to take.
The outline will represent the rough ordering of the steps that will be
taken.
Args:
level (int, optional): a valid log level that should be used to log
... |
def merge_config(template, config, list_identifiers=None):
"""
Merges ``config`` on top of ``template``.
Conflicting keys are handled in the following way:
* simple values (eg: ``str``, ``int``, ``float``, ecc) in ``config`` will
overwrite the ones in ``template``
* values of type ``list`` i... | def function[merge_config, parameter[template, config, list_identifiers]]:
constant[
Merges ``config`` on top of ``template``.
Conflicting keys are handled in the following way:
* simple values (eg: ``str``, ``int``, ``float``, ecc) in ``config`` will
overwrite the ones in ``template``
*... | keyword[def] identifier[merge_config] ( identifier[template] , identifier[config] , identifier[list_identifiers] = keyword[None] ):
literal[string]
identifier[result] = identifier[template] . identifier[copy] ()
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[config] . ident... | def merge_config(template, config, list_identifiers=None):
"""
Merges ``config`` on top of ``template``.
Conflicting keys are handled in the following way:
* simple values (eg: ``str``, ``int``, ``float``, ecc) in ``config`` will
overwrite the ones in ``template``
* values of type ``list`` i... |
def get_way(self, way_id, resolve_missing=False):
"""
Get a way by its ID.
:param way_id: The way ID
:type way_id: Integer
:param resolve_missing: Query the Overpass API if the way is missing in the result set.
:return: The way
:rtype: overpy.Way
:raises ... | def function[get_way, parameter[self, way_id, resolve_missing]]:
constant[
Get a way by its ID.
:param way_id: The way ID
:type way_id: Integer
:param resolve_missing: Query the Overpass API if the way is missing in the result set.
:return: The way
:rtype: overpy... | keyword[def] identifier[get_way] ( identifier[self] , identifier[way_id] , identifier[resolve_missing] = keyword[False] ):
literal[string]
identifier[ways] = identifier[self] . identifier[get_ways] ( identifier[way_id] = identifier[way_id] )
keyword[if] identifier[len] ( identifier[ways] ... | def get_way(self, way_id, resolve_missing=False):
"""
Get a way by its ID.
:param way_id: The way ID
:type way_id: Integer
:param resolve_missing: Query the Overpass API if the way is missing in the result set.
:return: The way
:rtype: overpy.Way
:raises over... |
async def SetVolumeInfo(self, volumes):
'''
volumes : typing.Sequence[~Volume]
Returns -> typing.Sequence[~ErrorResult]
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='StorageProvisioner',
request='SetVolumeInfo',
... | <ast.AsyncFunctionDef object at 0x7da18dc06080> | keyword[async] keyword[def] identifier[SetVolumeInfo] ( identifier[self] , identifier[volumes] ):
literal[string]
identifier[_params] = identifier[dict] ()
identifier[msg] = identifier[dict] ( identifier[type] = literal[string] ,
identifier[request] = literal[string] ,
... | async def SetVolumeInfo(self, volumes):
"""
volumes : typing.Sequence[~Volume]
Returns -> typing.Sequence[~ErrorResult]
"""
# map input types to rpc msg
_params = dict()
msg = dict(type='StorageProvisioner', request='SetVolumeInfo', version=4, params=_params)
_params['volumes... |
def Close(self):
"""Closes the connection to TimeSketch Elasticsearch database.
Sends the remaining events for indexing and removes the processing status on
the Timesketch search index object.
"""
super(TimesketchOutputModule, self).Close()
with self._timesketch.app_context():
search_ind... | def function[Close, parameter[self]]:
constant[Closes the connection to TimeSketch Elasticsearch database.
Sends the remaining events for indexing and removes the processing status on
the Timesketch search index object.
]
call[call[name[super], parameter[name[TimesketchOutputModule], name[s... | keyword[def] identifier[Close] ( identifier[self] ):
literal[string]
identifier[super] ( identifier[TimesketchOutputModule] , identifier[self] ). identifier[Close] ()
keyword[with] identifier[self] . identifier[_timesketch] . identifier[app_context] ():
identifier[search_index] = identifier[t... | def Close(self):
"""Closes the connection to TimeSketch Elasticsearch database.
Sends the remaining events for indexing and removes the processing status on
the Timesketch search index object.
"""
super(TimesketchOutputModule, self).Close()
with self._timesketch.app_context():
search_in... |
def _get_scaled_image(self, resource):
"""
Get scaled watermark image
:param resource: Image.Image
:return: Image.Image
"""
image = self._get_image()
original_width, original_height = resource.size
k = image.size[0] / float(image.size[1])
if imag... | def function[_get_scaled_image, parameter[self, resource]]:
constant[
Get scaled watermark image
:param resource: Image.Image
:return: Image.Image
]
variable[image] assign[=] call[name[self]._get_image, parameter[]]
<ast.Tuple object at 0x7da1b142a4d0> assign[=] n... | keyword[def] identifier[_get_scaled_image] ( identifier[self] , identifier[resource] ):
literal[string]
identifier[image] = identifier[self] . identifier[_get_image] ()
identifier[original_width] , identifier[original_height] = identifier[resource] . identifier[size]
identifier[... | def _get_scaled_image(self, resource):
"""
Get scaled watermark image
:param resource: Image.Image
:return: Image.Image
"""
image = self._get_image()
(original_width, original_height) = resource.size
k = image.size[0] / float(image.size[1])
if image.size[0] >= image.s... |
def gregorian_to_julian(day):
"""Convert a datetime.date object to its corresponding Julian day.
:param day: The datetime.date to convert to a Julian day
:returns: A Julian day, as an integer
"""
before_march = 1 if day.month < MARCH else 0
#
# Number of months since March
#
month_... | def function[gregorian_to_julian, parameter[day]]:
constant[Convert a datetime.date object to its corresponding Julian day.
:param day: The datetime.date to convert to a Julian day
:returns: A Julian day, as an integer
]
variable[before_march] assign[=] <ast.IfExp object at 0x7da20c6a9a80>
... | keyword[def] identifier[gregorian_to_julian] ( identifier[day] ):
literal[string]
identifier[before_march] = literal[int] keyword[if] identifier[day] . identifier[month] < identifier[MARCH] keyword[else] literal[int]
identifier[month_index] = identifier[day] . identifier[month] + ... | def gregorian_to_julian(day):
"""Convert a datetime.date object to its corresponding Julian day.
:param day: The datetime.date to convert to a Julian day
:returns: A Julian day, as an integer
"""
before_march = 1 if day.month < MARCH else 0
#
# Number of months since March
#
month_i... |
def copy_obj(obj):
''' does a deepcopy of an object, but does not copy a class
i.e.
x = {"key":[<classInstance1>,<classInstance2>,<classInstance3>]}
y = copy_obj(x)
y --> {"key":[<classInstance1>,<classInstance2>,<classInstance3>]}
del y['key'][0]
y --> {"key":[<class... | def function[copy_obj, parameter[obj]]:
constant[ does a deepcopy of an object, but does not copy a class
i.e.
x = {"key":[<classInstance1>,<classInstance2>,<classInstance3>]}
y = copy_obj(x)
y --> {"key":[<classInstance1>,<classInstance2>,<classInstance3>]}
del y['key'][... | keyword[def] identifier[copy_obj] ( identifier[obj] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[obj] , identifier[dict] ):
identifier[return_obj] ={}
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[obj] . identifier[items] ():
... | def copy_obj(obj):
""" does a deepcopy of an object, but does not copy a class
i.e.
x = {"key":[<classInstance1>,<classInstance2>,<classInstance3>]}
y = copy_obj(x)
y --> {"key":[<classInstance1>,<classInstance2>,<classInstance3>]}
del y['key'][0]
y --> {"key":[<class... |
def _analyze_case(model_dir, bench_dir, config):
""" Runs all of the verification checks on a particular case """
bundle = livvkit.verification_model_module
model_out = functions.find_file(model_dir, "*"+config["output_ext"])
bench_out = functions.find_file(bench_dir, "*"+config["output_ext"])
model... | def function[_analyze_case, parameter[model_dir, bench_dir, config]]:
constant[ Runs all of the verification checks on a particular case ]
variable[bundle] assign[=] name[livvkit].verification_model_module
variable[model_out] assign[=] call[name[functions].find_file, parameter[name[model_dir], b... | keyword[def] identifier[_analyze_case] ( identifier[model_dir] , identifier[bench_dir] , identifier[config] ):
literal[string]
identifier[bundle] = identifier[livvkit] . identifier[verification_model_module]
identifier[model_out] = identifier[functions] . identifier[find_file] ( identifier[model_dir]... | def _analyze_case(model_dir, bench_dir, config):
""" Runs all of the verification checks on a particular case """
bundle = livvkit.verification_model_module
model_out = functions.find_file(model_dir, '*' + config['output_ext'])
bench_out = functions.find_file(bench_dir, '*' + config['output_ext'])
m... |
def stop(self):
"""Stop consuming the stream and shutdown the background thread."""
with self._operational_lock:
self._bidi_rpc.close()
if self._thread is not None:
# Resume the thread to wake it up in case it is sleeping.
self.resume()
... | def function[stop, parameter[self]]:
constant[Stop consuming the stream and shutdown the background thread.]
with name[self]._operational_lock begin[:]
call[name[self]._bidi_rpc.close, parameter[]]
if compare[name[self]._thread is_not constant[None]] begin[:]
... | keyword[def] identifier[stop] ( identifier[self] ):
literal[string]
keyword[with] identifier[self] . identifier[_operational_lock] :
identifier[self] . identifier[_bidi_rpc] . identifier[close] ()
keyword[if] identifier[self] . identifier[_thread] keyword[is] keyword[... | def stop(self):
"""Stop consuming the stream and shutdown the background thread."""
with self._operational_lock:
self._bidi_rpc.close()
if self._thread is not None:
# Resume the thread to wake it up in case it is sleeping.
self.resume()
self._thread.join() # ... |
def get_station_year_text(WMO, WBAN, year):
'''Basic method to download data from the GSOD database, given a
station identifier and year.
Parameters
----------
WMO : int or None
World Meteorological Organization (WMO) identifiers, [-]
WBAN : int or None
Weather Bureau Army Na... | def function[get_station_year_text, parameter[WMO, WBAN, year]]:
constant[Basic method to download data from the GSOD database, given a
station identifier and year.
Parameters
----------
WMO : int or None
World Meteorological Organization (WMO) identifiers, [-]
WBAN : int or None... | keyword[def] identifier[get_station_year_text] ( identifier[WMO] , identifier[WBAN] , identifier[year] ):
literal[string]
keyword[if] identifier[WMO] keyword[is] keyword[None] :
identifier[WMO] = literal[int]
keyword[if] identifier[WBAN] keyword[is] keyword[None] :
identifier[... | def get_station_year_text(WMO, WBAN, year):
"""Basic method to download data from the GSOD database, given a
station identifier and year.
Parameters
----------
WMO : int or None
World Meteorological Organization (WMO) identifiers, [-]
WBAN : int or None
Weather Bureau Army Na... |
def update_launch_config(self, scaling_group, server_name=None, image=None,
flavor=None, disk_config=None, metadata=None, personality=None,
networks=None, load_balancers=None, key_name=None, config_drive=False,
user_data=None):
"""
Updates the server launch configurat... | def function[update_launch_config, parameter[self, scaling_group, server_name, image, flavor, disk_config, metadata, personality, networks, load_balancers, key_name, config_drive, user_data]]:
constant[
Updates the server launch configuration for an existing scaling group.
One or more of the ava... | keyword[def] identifier[update_launch_config] ( identifier[self] , identifier[scaling_group] , identifier[server_name] = keyword[None] , identifier[image] = keyword[None] ,
identifier[flavor] = keyword[None] , identifier[disk_config] = keyword[None] , identifier[metadata] = keyword[None] , identifier[personality] = ... | def update_launch_config(self, scaling_group, server_name=None, image=None, flavor=None, disk_config=None, metadata=None, personality=None, networks=None, load_balancers=None, key_name=None, config_drive=False, user_data=None):
"""
Updates the server launch configuration for an existing scaling group.
... |
def folderName(self, folder):
"""gets/set the current folder"""
if folder == "" or\
folder == "/":
self._currentURL = self._url
self._services = None
self._description = None
self._folderName = None
self._webEncrypted = None
... | def function[folderName, parameter[self, folder]]:
constant[gets/set the current folder]
if <ast.BoolOp object at 0x7da18dc9bd60> begin[:]
name[self]._currentURL assign[=] name[self]._url
name[self]._services assign[=] constant[None]
name[self]._descriptio... | keyword[def] identifier[folderName] ( identifier[self] , identifier[folder] ):
literal[string]
keyword[if] identifier[folder] == literal[string] keyword[or] identifier[folder] == literal[string] :
identifier[self] . identifier[_currentURL] = identifier[self] . identifier[_url]
... | def folderName(self, folder):
"""gets/set the current folder"""
if folder == '' or folder == '/':
self._currentURL = self._url
self._services = None
self._description = None
self._folderName = None
self._webEncrypted = None
self.__init()
self._folderName =... |
async def stepper_config(self, steps_per_revolution, stepper_pins):
"""
Configure stepper motor prior to operation.
This is a FirmataPlus feature.
:param steps_per_revolution: number of steps per motor revolution
:param stepper_pins: a list of control pin numbers - either 4 or ... | <ast.AsyncFunctionDef object at 0x7da207f026e0> | keyword[async] keyword[def] identifier[stepper_config] ( identifier[self] , identifier[steps_per_revolution] , identifier[stepper_pins] ):
literal[string]
identifier[data] =[ identifier[PrivateConstants] . identifier[STEPPER_CONFIGURE] , identifier[steps_per_revolution] & literal[int] ,
( ... | async def stepper_config(self, steps_per_revolution, stepper_pins):
"""
Configure stepper motor prior to operation.
This is a FirmataPlus feature.
:param steps_per_revolution: number of steps per motor revolution
:param stepper_pins: a list of control pin numbers - either 4 or 2
... |
def poke_array(self, store, name, elemtype, elements, container, visited, _stack):
"""abstract method"""
raise NotImplementedError | def function[poke_array, parameter[self, store, name, elemtype, elements, container, visited, _stack]]:
constant[abstract method]
<ast.Raise object at 0x7da1b1463c70> | keyword[def] identifier[poke_array] ( identifier[self] , identifier[store] , identifier[name] , identifier[elemtype] , identifier[elements] , identifier[container] , identifier[visited] , identifier[_stack] ):
literal[string]
keyword[raise] identifier[NotImplementedError] | def poke_array(self, store, name, elemtype, elements, container, visited, _stack):
"""abstract method"""
raise NotImplementedError |
def get_hash_statements_dict(self):
"""Return a dict of Statements keyed by hashes."""
res = {stmt_hash: stmts_from_json([stmt])[0]
for stmt_hash, stmt in self.__statement_jsons.items()}
return res | def function[get_hash_statements_dict, parameter[self]]:
constant[Return a dict of Statements keyed by hashes.]
variable[res] assign[=] <ast.DictComp object at 0x7da20c6e7850>
return[name[res]] | keyword[def] identifier[get_hash_statements_dict] ( identifier[self] ):
literal[string]
identifier[res] ={ identifier[stmt_hash] : identifier[stmts_from_json] ([ identifier[stmt] ])[ literal[int] ]
keyword[for] identifier[stmt_hash] , identifier[stmt] keyword[in] identifier[self] . iden... | def get_hash_statements_dict(self):
"""Return a dict of Statements keyed by hashes."""
res = {stmt_hash: stmts_from_json([stmt])[0] for (stmt_hash, stmt) in self.__statement_jsons.items()}
return res |
def unlink(self, func):
'''
Remove a callback function previously added with link()
Example:
base.unlink( callback )
'''
if func in self._syn_links:
self._syn_links.remove(func) | def function[unlink, parameter[self, func]]:
constant[
Remove a callback function previously added with link()
Example:
base.unlink( callback )
]
if compare[name[func] in name[self]._syn_links] begin[:]
call[name[self]._syn_links.remove, parameter[n... | keyword[def] identifier[unlink] ( identifier[self] , identifier[func] ):
literal[string]
keyword[if] identifier[func] keyword[in] identifier[self] . identifier[_syn_links] :
identifier[self] . identifier[_syn_links] . identifier[remove] ( identifier[func] ) | def unlink(self, func):
"""
Remove a callback function previously added with link()
Example:
base.unlink( callback )
"""
if func in self._syn_links:
self._syn_links.remove(func) # depends on [control=['if'], data=['func']] |
def models(cls, api_version=DEFAULT_API_VERSION):
"""Module depends on the API version:
* 2015-06-01: :mod:`v2015_06_01.models<azure.mgmt.authorization.v2015_06_01.models>`
* 2015-07-01: :mod:`v2015_07_01.models<azure.mgmt.authorization.v2015_07_01.models>`
* 2018-01-01-preview... | def function[models, parameter[cls, api_version]]:
constant[Module depends on the API version:
* 2015-06-01: :mod:`v2015_06_01.models<azure.mgmt.authorization.v2015_06_01.models>`
* 2015-07-01: :mod:`v2015_07_01.models<azure.mgmt.authorization.v2015_07_01.models>`
* 2018-01-01-... | keyword[def] identifier[models] ( identifier[cls] , identifier[api_version] = identifier[DEFAULT_API_VERSION] ):
literal[string]
keyword[if] identifier[api_version] == literal[string] :
keyword[from] . identifier[v2015_06_01] keyword[import] identifier[models]
keyword[... | def models(cls, api_version=DEFAULT_API_VERSION):
"""Module depends on the API version:
* 2015-06-01: :mod:`v2015_06_01.models<azure.mgmt.authorization.v2015_06_01.models>`
* 2015-07-01: :mod:`v2015_07_01.models<azure.mgmt.authorization.v2015_07_01.models>`
* 2018-01-01-preview: :m... |
def setup(self):
"""Setup."""
self.normalize = self.config['normalize'].upper()
self.convert_encoding = self.config['convert_encoding'].lower()
self.errors = self.config['errors'].lower()
if self.convert_encoding:
self.convert_encoding = codecs.lookup(
... | def function[setup, parameter[self]]:
constant[Setup.]
name[self].normalize assign[=] call[call[name[self].config][constant[normalize]].upper, parameter[]]
name[self].convert_encoding assign[=] call[call[name[self].config][constant[convert_encoding]].lower, parameter[]]
name[self].errors... | keyword[def] identifier[setup] ( identifier[self] ):
literal[string]
identifier[self] . identifier[normalize] = identifier[self] . identifier[config] [ literal[string] ]. identifier[upper] ()
identifier[self] . identifier[convert_encoding] = identifier[self] . identifier[config] [ literal... | def setup(self):
"""Setup."""
self.normalize = self.config['normalize'].upper()
self.convert_encoding = self.config['convert_encoding'].lower()
self.errors = self.config['errors'].lower()
if self.convert_encoding:
self.convert_encoding = codecs.lookup(filters.PYTHON_ENCODING_NAMES.get(self.d... |
def get_close_matches(word, possibilities, n=3, cutoff=0.6):
"""Use SequenceMatcher to return list of the best "good enough" matches.
word is a sequence for which close matches are desired (typically a
string).
possibilities is a list of sequences against which to match word
(typically a list of s... | def function[get_close_matches, parameter[word, possibilities, n, cutoff]]:
constant[Use SequenceMatcher to return list of the best "good enough" matches.
word is a sequence for which close matches are desired (typically a
string).
possibilities is a list of sequences against which to match word
... | keyword[def] identifier[get_close_matches] ( identifier[word] , identifier[possibilities] , identifier[n] = literal[int] , identifier[cutoff] = literal[int] ):
literal[string]
keyword[if] keyword[not] identifier[n] > literal[int] :
keyword[raise] identifier[ValueError] ( literal[string] %( ide... | def get_close_matches(word, possibilities, n=3, cutoff=0.6):
"""Use SequenceMatcher to return list of the best "good enough" matches.
word is a sequence for which close matches are desired (typically a
string).
possibilities is a list of sequences against which to match word
(typically a list of s... |
def make_reader_task(self, stream, callback):
"""
Create a reader executor task for a stream.
"""
return self.loop.create_task(self.executor_wrapper(background_reader, stream, self.loop, callback)) | def function[make_reader_task, parameter[self, stream, callback]]:
constant[
Create a reader executor task for a stream.
]
return[call[name[self].loop.create_task, parameter[call[name[self].executor_wrapper, parameter[name[background_reader], name[stream], name[self].loop, name[callback]]]]]... | keyword[def] identifier[make_reader_task] ( identifier[self] , identifier[stream] , identifier[callback] ):
literal[string]
keyword[return] identifier[self] . identifier[loop] . identifier[create_task] ( identifier[self] . identifier[executor_wrapper] ( identifier[background_reader] , identifier[... | def make_reader_task(self, stream, callback):
"""
Create a reader executor task for a stream.
"""
return self.loop.create_task(self.executor_wrapper(background_reader, stream, self.loop, callback)) |
def value(self, value):
"""
set the value
"""
# for the indep direction we also allow a string which points to one
# of the other available dimensions
# TODO: support c, fc, ec?
if isinstance(value, common.basestring) and value in ['x', 'y', 'z']:
# we... | def function[value, parameter[self, value]]:
constant[
set the value
]
if <ast.BoolOp object at 0x7da2041d9d50> begin[:]
name[self]._value assign[=] call[name[str], parameter[name[value]]]
variable[dimension] assign[=] name[value]
name[self... | keyword[def] identifier[value] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[value] , identifier[common] . identifier[basestring] ) keyword[and] identifier[value] keyword[in] [ literal[string] , literal[string... | def value(self, value):
"""
set the value
"""
# for the indep direction we also allow a string which points to one
# of the other available dimensions
# TODO: support c, fc, ec?
if isinstance(value, common.basestring) and value in ['x', 'y', 'z']:
# we'll cast just to get rid... |
def _get_photos(session, user_or_group_id):
"""
https://vk.com/dev/photos.getAll
"""
response = session.fetch_items("photos.getAll", Photo.from_json, count=200, owner_id=user_or_group_id)
return response | def function[_get_photos, parameter[session, user_or_group_id]]:
constant[
https://vk.com/dev/photos.getAll
]
variable[response] assign[=] call[name[session].fetch_items, parameter[constant[photos.getAll], name[Photo].from_json]]
return[name[response]] | keyword[def] identifier[_get_photos] ( identifier[session] , identifier[user_or_group_id] ):
literal[string]
identifier[response] = identifier[session] . identifier[fetch_items] ( literal[string] , identifier[Photo] . identifier[from_json] , identifier[count] = literal[int] , identifier[owner_id] =... | def _get_photos(session, user_or_group_id):
"""
https://vk.com/dev/photos.getAll
"""
response = session.fetch_items('photos.getAll', Photo.from_json, count=200, owner_id=user_or_group_id)
return response |
def gpg_key(value):
"""
test if value points to a known gpg key
and return that key as a gpg key object.
"""
try:
return crypto.get_key(value)
except GPGProblem as e:
raise ValidateError(str(e)) | def function[gpg_key, parameter[value]]:
constant[
test if value points to a known gpg key
and return that key as a gpg key object.
]
<ast.Try object at 0x7da1b0795720> | keyword[def] identifier[gpg_key] ( identifier[value] ):
literal[string]
keyword[try] :
keyword[return] identifier[crypto] . identifier[get_key] ( identifier[value] )
keyword[except] identifier[GPGProblem] keyword[as] identifier[e] :
keyword[raise] identifier[ValidateError] ( ide... | def gpg_key(value):
"""
test if value points to a known gpg key
and return that key as a gpg key object.
"""
try:
return crypto.get_key(value) # depends on [control=['try'], data=[]]
except GPGProblem as e:
raise ValidateError(str(e)) # depends on [control=['except'], data=['e'... |
def unpack_kinesis_event(kinesis_event, deserializer=None, unpacker=None,
embed_timestamp=False):
"""Extracts events (a list of dicts) from a Kinesis event."""
records = kinesis_event["Records"]
events = []
shard_ids = set()
for rec in records:
data = rec["kinesis"][... | def function[unpack_kinesis_event, parameter[kinesis_event, deserializer, unpacker, embed_timestamp]]:
constant[Extracts events (a list of dicts) from a Kinesis event.]
variable[records] assign[=] call[name[kinesis_event]][constant[Records]]
variable[events] assign[=] list[[]]
variable[s... | keyword[def] identifier[unpack_kinesis_event] ( identifier[kinesis_event] , identifier[deserializer] = keyword[None] , identifier[unpacker] = keyword[None] ,
identifier[embed_timestamp] = keyword[False] ):
literal[string]
identifier[records] = identifier[kinesis_event] [ literal[string] ]
identifier[... | def unpack_kinesis_event(kinesis_event, deserializer=None, unpacker=None, embed_timestamp=False):
"""Extracts events (a list of dicts) from a Kinesis event."""
records = kinesis_event['Records']
events = []
shard_ids = set()
for rec in records:
data = rec['kinesis']['data']
try:
... |
def solve(guess_a, guess_b, power, solver='scipy'):
""" Constructs a pyneqsys.symbolic.SymbolicSys instance and returns from its ``solve`` method. """
# The problem is 2 dimensional so we need 2 symbols
x = sp.symbols('x:2', real=True)
# There is a user specified parameter ``p`` in this problem:
p =... | def function[solve, parameter[guess_a, guess_b, power, solver]]:
constant[ Constructs a pyneqsys.symbolic.SymbolicSys instance and returns from its ``solve`` method. ]
variable[x] assign[=] call[name[sp].symbols, parameter[constant[x:2]]]
variable[p] assign[=] call[name[sp].Symbol, parameter[con... | keyword[def] identifier[solve] ( identifier[guess_a] , identifier[guess_b] , identifier[power] , identifier[solver] = literal[string] ):
literal[string]
identifier[x] = identifier[sp] . identifier[symbols] ( literal[string] , identifier[real] = keyword[True] )
identifier[p] = identifier[sp] ... | def solve(guess_a, guess_b, power, solver='scipy'):
""" Constructs a pyneqsys.symbolic.SymbolicSys instance and returns from its ``solve`` method. """
# The problem is 2 dimensional so we need 2 symbols
x = sp.symbols('x:2', real=True)
# There is a user specified parameter ``p`` in this problem:
p =... |
def discharge_token(self, username):
"""Discharge token for a user.
Raise a ServerError if an error occurs in the request process.
@param username The logged in user.
@return The resulting base64 encoded discharged token.
"""
url = '{}discharge-token-for-user?username={... | def function[discharge_token, parameter[self, username]]:
constant[Discharge token for a user.
Raise a ServerError if an error occurs in the request process.
@param username The logged in user.
@return The resulting base64 encoded discharged token.
]
variable[url] assig... | keyword[def] identifier[discharge_token] ( identifier[self] , identifier[username] ):
literal[string]
identifier[url] = literal[string] . identifier[format] (
identifier[self] . identifier[url] , identifier[quote] ( identifier[username] ))
identifier[logging] . identifier[debug] (... | def discharge_token(self, username):
"""Discharge token for a user.
Raise a ServerError if an error occurs in the request process.
@param username The logged in user.
@return The resulting base64 encoded discharged token.
"""
url = '{}discharge-token-for-user?username={}'.forma... |
def power_status_send(self, Vcc, Vservo, flags, force_mavlink1=False):
'''
Power supply status
Vcc : 5V rail voltage in millivolts (uint16_t)
Vservo : servo rail voltage in millivolts (uint16_t)
fla... | def function[power_status_send, parameter[self, Vcc, Vservo, flags, force_mavlink1]]:
constant[
Power supply status
Vcc : 5V rail voltage in millivolts (uint16_t)
Vservo : servo rail voltage in millivolts (uint16_t)
... | keyword[def] identifier[power_status_send] ( identifier[self] , identifier[Vcc] , identifier[Vservo] , identifier[flags] , identifier[force_mavlink1] = keyword[False] ):
literal[string]
keyword[return] identifier[self] . identifier[send] ( identifier[self] . identifier[power_status... | def power_status_send(self, Vcc, Vservo, flags, force_mavlink1=False):
"""
Power supply status
Vcc : 5V rail voltage in millivolts (uint16_t)
Vservo : servo rail voltage in millivolts (uint16_t)
flags ... |
def get_block_sysfee(self, height, id=None, endpoint=None):
"""
Get the system fee of a block by height. This is used in calculating gas claims
Args:
height: (int) height of the block to lookup
id: (int, optional) id to use for response tracking
endpoint: (RP... | def function[get_block_sysfee, parameter[self, height, id, endpoint]]:
constant[
Get the system fee of a block by height. This is used in calculating gas claims
Args:
height: (int) height of the block to lookup
id: (int, optional) id to use for response tracking
... | keyword[def] identifier[get_block_sysfee] ( identifier[self] , identifier[height] , identifier[id] = keyword[None] , identifier[endpoint] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[_call_endpoint] ( identifier[GET_BLOCK_SYS_FEE] , identifier[params] =[ identif... | def get_block_sysfee(self, height, id=None, endpoint=None):
"""
Get the system fee of a block by height. This is used in calculating gas claims
Args:
height: (int) height of the block to lookup
id: (int, optional) id to use for response tracking
endpoint: (RPCEnd... |
def get_tag_html(tag_id):
"""
Returns the Django HTML to load the tag library and render the tag.
Args:
tag_id (str): The tag id for the to return the HTML for.
"""
tag_data = get_lazy_tag_data(tag_id)
tag = tag_data['tag']
args = tag_data['args']
kwargs = tag_data['kwargs']
... | def function[get_tag_html, parameter[tag_id]]:
constant[
Returns the Django HTML to load the tag library and render the tag.
Args:
tag_id (str): The tag id for the to return the HTML for.
]
variable[tag_data] assign[=] call[name[get_lazy_tag_data], parameter[name[tag_id]]]
v... | keyword[def] identifier[get_tag_html] ( identifier[tag_id] ):
literal[string]
identifier[tag_data] = identifier[get_lazy_tag_data] ( identifier[tag_id] )
identifier[tag] = identifier[tag_data] [ literal[string] ]
identifier[args] = identifier[tag_data] [ literal[string] ]
identifier[kwargs] ... | def get_tag_html(tag_id):
"""
Returns the Django HTML to load the tag library and render the tag.
Args:
tag_id (str): The tag id for the to return the HTML for.
"""
tag_data = get_lazy_tag_data(tag_id)
tag = tag_data['tag']
args = tag_data['args']
kwargs = tag_data['kwargs']
... |
def update(self, *names: str) -> 'ListTree':
"""Add all the mailbox names to the tree, filling in any missing nodes.
Args:
names: The names of the mailboxes.
"""
for name in names:
parts = name.split(self._delimiter)
self._root.add(*parts)
re... | def function[update, parameter[self]]:
constant[Add all the mailbox names to the tree, filling in any missing nodes.
Args:
names: The names of the mailboxes.
]
for taget[name[name]] in starred[name[names]] begin[:]
variable[parts] assign[=] call[name[name].s... | keyword[def] identifier[update] ( identifier[self] ,* identifier[names] : identifier[str] )-> literal[string] :
literal[string]
keyword[for] identifier[name] keyword[in] identifier[names] :
identifier[parts] = identifier[name] . identifier[split] ( identifier[self] . identifier[_del... | def update(self, *names: str) -> 'ListTree':
"""Add all the mailbox names to the tree, filling in any missing nodes.
Args:
names: The names of the mailboxes.
"""
for name in names:
parts = name.split(self._delimiter)
self._root.add(*parts) # depends on [control=['f... |
def unpack_apply_message(bufs, g=None, copy=True):
"""Unpack f,args,kwargs from buffers packed by pack_apply_message().
Returns: original f,args,kwargs
"""
bufs = list(bufs) # allow us to pop
assert len(bufs) >= 2, "not enough buffers!"
pf = buffer_to_bytes_py2(bufs.pop(0))
f = uncan(pickl... | def function[unpack_apply_message, parameter[bufs, g, copy]]:
constant[Unpack f,args,kwargs from buffers packed by pack_apply_message().
Returns: original f,args,kwargs
]
variable[bufs] assign[=] call[name[list], parameter[name[bufs]]]
assert[compare[call[name[len], parameter[name[bufs]]] g... | keyword[def] identifier[unpack_apply_message] ( identifier[bufs] , identifier[g] = keyword[None] , identifier[copy] = keyword[True] ):
literal[string]
identifier[bufs] = identifier[list] ( identifier[bufs] )
keyword[assert] identifier[len] ( identifier[bufs] )>= literal[int] , literal[string]
i... | def unpack_apply_message(bufs, g=None, copy=True):
"""Unpack f,args,kwargs from buffers packed by pack_apply_message().
Returns: original f,args,kwargs
"""
bufs = list(bufs) # allow us to pop
assert len(bufs) >= 2, 'not enough buffers!'
pf = buffer_to_bytes_py2(bufs.pop(0))
f = uncan(pickl... |
def signal_to_exception(sig: signal.Signals) -> SignalException:
"""
Convert a ``signal.Signals`` to a ``SignalException``.
This allows for natural, pythonic signal handing with the use of try-except blocks.
.. code-block:: python
import signal
import zproc
zproc.signal_to_ex... | def function[signal_to_exception, parameter[sig]]:
constant[
Convert a ``signal.Signals`` to a ``SignalException``.
This allows for natural, pythonic signal handing with the use of try-except blocks.
.. code-block:: python
import signal
import zproc
zproc.signal_to_except... | keyword[def] identifier[signal_to_exception] ( identifier[sig] : identifier[signal] . identifier[Signals] )-> identifier[SignalException] :
literal[string]
identifier[signal] . identifier[signal] ( identifier[sig] , identifier[_sig_exc_handler] )
keyword[return] identifier[SignalException] ( identifi... | def signal_to_exception(sig: signal.Signals) -> SignalException:
"""
Convert a ``signal.Signals`` to a ``SignalException``.
This allows for natural, pythonic signal handing with the use of try-except blocks.
.. code-block:: python
import signal
import zproc
zproc.signal_to_ex... |
def get_kline(self, symbol, period, size=150, _async=False):
"""
获取KLine
:param symbol
:param period: 可选值:{1min, 5min, 15min, 30min, 60min, 1day, 1mon, 1week, 1year }
:param size: 可选值: [1,2000]
:return:
"""
params = {'symbol': symbol, 'period': period, 'si... | def function[get_kline, parameter[self, symbol, period, size, _async]]:
constant[
获取KLine
:param symbol
:param period: 可选值:{1min, 5min, 15min, 30min, 60min, 1day, 1mon, 1week, 1year }
:param size: 可选值: [1,2000]
:return:
]
variable[params] assign[=] diction... | keyword[def] identifier[get_kline] ( identifier[self] , identifier[symbol] , identifier[period] , identifier[size] = literal[int] , identifier[_async] = keyword[False] ):
literal[string]
identifier[params] ={ literal[string] : identifier[symbol] , literal[string] : identifier[period] , literal[stri... | def get_kline(self, symbol, period, size=150, _async=False):
"""
获取KLine
:param symbol
:param period: 可选值:{1min, 5min, 15min, 30min, 60min, 1day, 1mon, 1week, 1year }
:param size: 可选值: [1,2000]
:return:
"""
params = {'symbol': symbol, 'period': period, 'size': siz... |
def from_call(cls, call_node):
"""Get a CallSite object from the given Call node."""
callcontext = contextmod.CallContext(call_node.args, call_node.keywords)
return cls(callcontext) | def function[from_call, parameter[cls, call_node]]:
constant[Get a CallSite object from the given Call node.]
variable[callcontext] assign[=] call[name[contextmod].CallContext, parameter[name[call_node].args, name[call_node].keywords]]
return[call[name[cls], parameter[name[callcontext]]]] | keyword[def] identifier[from_call] ( identifier[cls] , identifier[call_node] ):
literal[string]
identifier[callcontext] = identifier[contextmod] . identifier[CallContext] ( identifier[call_node] . identifier[args] , identifier[call_node] . identifier[keywords] )
keyword[return] identifier... | def from_call(cls, call_node):
"""Get a CallSite object from the given Call node."""
callcontext = contextmod.CallContext(call_node.args, call_node.keywords)
return cls(callcontext) |
def from_csv(cls, csv_file):
"""
Not implemented. Will provide a route from CSV file.
"""
try:
param_dict = csv.DictReader(csv_file)
return cls(param_dict)
except:
raise NotImplementedError | def function[from_csv, parameter[cls, csv_file]]:
constant[
Not implemented. Will provide a route from CSV file.
]
<ast.Try object at 0x7da1b23ec1c0> | keyword[def] identifier[from_csv] ( identifier[cls] , identifier[csv_file] ):
literal[string]
keyword[try] :
identifier[param_dict] = identifier[csv] . identifier[DictReader] ( identifier[csv_file] )
keyword[return] identifier[cls] ( identifier[param_dict] )
keyw... | def from_csv(cls, csv_file):
"""
Not implemented. Will provide a route from CSV file.
"""
try:
param_dict = csv.DictReader(csv_file)
return cls(param_dict) # depends on [control=['try'], data=[]]
except:
raise NotImplementedError # depends on [control=['except'], da... |
def create_error_response(self, in_response_to, destination, info,
sign=False, issuer=None, sign_alg=None,
digest_alg=None, **kwargs):
""" Create a error response.
:param in_response_to: The identifier of the message this is a response
... | def function[create_error_response, parameter[self, in_response_to, destination, info, sign, issuer, sign_alg, digest_alg]]:
constant[ Create a error response.
:param in_response_to: The identifier of the message this is a response
to.
:param destination: The intended recipient of t... | keyword[def] identifier[create_error_response] ( identifier[self] , identifier[in_response_to] , identifier[destination] , identifier[info] ,
identifier[sign] = keyword[False] , identifier[issuer] = keyword[None] , identifier[sign_alg] = keyword[None] ,
identifier[digest_alg] = keyword[None] ,** identifier[kwargs] ... | def create_error_response(self, in_response_to, destination, info, sign=False, issuer=None, sign_alg=None, digest_alg=None, **kwargs):
""" Create a error response.
:param in_response_to: The identifier of the message this is a response
to.
:param destination: The intended recipient of t... |
def _releaseModifierKeys(self, modifiers):
"""Release given modifier keys (provided in list form).
Parameters: modifiers list
Returns: Unsigned int representing flags to set
"""
modFlags = self._releaseModifiers(modifiers)
# Post the queued keypresses:
self._post... | def function[_releaseModifierKeys, parameter[self, modifiers]]:
constant[Release given modifier keys (provided in list form).
Parameters: modifiers list
Returns: Unsigned int representing flags to set
]
variable[modFlags] assign[=] call[name[self]._releaseModifiers, parameter[na... | keyword[def] identifier[_releaseModifierKeys] ( identifier[self] , identifier[modifiers] ):
literal[string]
identifier[modFlags] = identifier[self] . identifier[_releaseModifiers] ( identifier[modifiers] )
identifier[self] . identifier[_postQueuedEvents] ()
keyword[return... | def _releaseModifierKeys(self, modifiers):
"""Release given modifier keys (provided in list form).
Parameters: modifiers list
Returns: Unsigned int representing flags to set
"""
modFlags = self._releaseModifiers(modifiers)
# Post the queued keypresses:
self._postQueuedEvents()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.