INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Fetch an image if it isn't already present.
This works like ``docker pull`` and will pull the tag ``latest`` if no tag
is specified in the image name. | def fetch_image(client, name):
"""
Fetch an image if it isn't already present.
This works like ``docker pull`` and will pull the tag ``latest`` if no tag
is specified in the image name.
"""
try:
image = client.images.get(name)
except docker.errors.ImageNotFound:
name, tag = ... |
Get both the model and ID of an object that could be an ID or a model.
:param id_or_model:
The object that could be an ID string or a model object.
:param model_collection:
The collection to which the model belongs. | def _get_id_and_model(self, id_or_model):
"""
Get both the model and ID of an object that could be an ID or a model.
:param id_or_model:
The object that could be an ID string or a model object.
:param model_collection:
The collection to which the model belongs.
... |
Create an instance of this resource type. | def create(self, name, *args, **kwargs):
"""
Create an instance of this resource type.
"""
resource_name = self._resource_name(name)
log.info(
"Creating {} '{}'...".format(self._model_name, resource_name))
resource = self.collection.create(*args, name=resource... |
Remove an instance of this resource type. | def remove(self, resource, **kwargs):
"""
Remove an instance of this resource type.
"""
log.info(
"Removing {} '{}'...".format(self._model_name, resource.name))
resource.remove(**kwargs)
self._ids.remove(resource.id) |
Create a new container.
:param name:
The name for the container. This will be prefixed with the
namespace.
:param image:
The image tag or image object to create the container from.
:param network:
The network to connect the container to. The conta... | def create(self, name, image, fetch_image=False, network=None, volumes={},
**kwargs):
"""
Create a new container.
:param name:
The name for the container. This will be prefixed with the
namespace.
:param image:
The image tag or image ob... |
Remove a container.
:param container: The container to remove.
:param force:
Whether to force the removal of the container, even if it is
running. Note that this defaults to True, unlike the Docker
default.
:param volumes:
Whether to remove any vo... | def remove(self, container, force=True, volumes=True):
"""
Remove a container.
:param container: The container to remove.
:param force:
Whether to force the removal of the container, even if it is
running. Note that this defaults to True, unlike the Docker
... |
Get the default bridge network that containers are connected to if no
other network options are specified.
:param create:
Whether or not to create the network if it doesn't already exist. | def get_default(self, create=True):
"""
Get the default bridge network that containers are connected to if no
other network options are specified.
:param create:
Whether or not to create the network if it doesn't already exist.
"""
if self._default_network is... |
Create a new network.
:param name:
The name for the network. This will be prefixed with the namespace.
:param check_duplicate:
Whether or not to check for networks with the same name. Docker
allows the creation of multiple networks with the same name (unlike
... | def create(self, name, check_duplicate=True, **kwargs):
"""
Create a new network.
:param name:
The name for the network. This will be prefixed with the namespace.
:param check_duplicate:
Whether or not to check for networks with the same name. Docker
... |
Get the helper for a given type of Docker model. For use by resource
definitions. | def _helper_for_model(self, model_type):
"""
Get the helper for a given type of Docker model. For use by resource
definitions.
"""
if model_type is models.containers.Container:
return self.containers
if model_type is models.images.Image:
return sel... |
Clean up all resources when we're done with them. | def teardown(self):
"""
Clean up all resources when we're done with them.
"""
self.containers._teardown()
self.networks._teardown()
self.volumes._teardown()
# We need to close the underlying APIClient explicitly to avoid
# ResourceWarnings from unclosed H... |
Execute a ``redis-cli`` command inside a running container.
:param command: the command to run
:param args: a list of args for the command
:param db: the db number to query (default ``0``)
:param redis_cli_opts: a list of extra options to pass to ``redis-cli``
:returns: a tuple ... | def exec_redis_cli(self, command, args=[], db=0, redis_cli_opts=[]):
"""
Execute a ``redis-cli`` command inside a running container.
:param command: the command to run
:param args: a list of args for the command
:param db: the db number to query (default ``0``)
:param re... |
Run the ``KEYS`` command and return the list of matching keys.
:param pattern: the pattern to filter keys by (default ``*``)
:param db: the db number to query (default ``0``) | def list_keys(self, pattern='*', db=0):
"""
Run the ``KEYS`` command and return the list of matching keys.
:param pattern: the pattern to filter keys by (default ``*``)
:param db: the db number to query (default ``0``)
"""
lines = output_lines(self.exec_redis_cli('KEYS',... |
uses thread_init as a decorator-style | def threaded(system, func, *args, **kwargs):
""" uses thread_init as a decorator-style """
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
if system.raven_client:
system.raven_client.captureException(... |
List the processes running inside a container.
We use an exec rather than `container.top()` because we want to run 'ps'
inside the container. This is because we want to get PIDs and usernames in
the container's namespaces. `container.top()` uses 'ps' from outside the
container in the host's namespaces. ... | def list_container_processes(container):
"""
List the processes running inside a container.
We use an exec rather than `container.top()` because we want to run 'ps'
inside the container. This is because we want to get PIDs and usernames in
the container's namespaces. `container.top()` uses 'ps' from... |
Build a tree structure from a list of PsRow objects.
:param ps_rows: a list of PsRow objects
:return: a PsTree object | def build_process_tree(ps_rows):
"""
Build a tree structure from a list of PsRow objects.
:param ps_rows: a list of PsRow objects
:return: a PsTree object
"""
ps_tree = None
for row in ps_rows:
if row.ppid == 0:
if ps_tree is not None:
raise PsException("T... |
Посмотреть баланс основного счёта. | def cmd_balance():
"""
Посмотреть баланс основного счёта.
"""
r = rocket.operations.cool_feed.get(params={"per_page": 1})
r = handle_error(r)
j = r.json()
template = "".join([
click.style("{rur} {code}, ", fg="green", bold=True),
"{miles} рокетрублей"])
click.echo(templa... |
Return ``True`` if the expected matchers are matched in the expected
order, otherwise ``False``. | def match(self, item):
"""
Return ``True`` if the expected matchers are matched in the expected
order, otherwise ``False``.
"""
if self._position == len(self._matchers):
raise RuntimeError('Matcher exhausted, no more matchers to use')
matcher = self._matchers... |
Return an args string for the repr. | def args_str(self):
"""
Return an args string for the repr.
"""
matched = [str(m) for m in self._matchers[:self._position]]
unmatched = [str(m) for m in self._matchers[self._position:]]
return 'matched=[{}], unmatched=[{}]'.format(
', '.join(matched), ', '.joi... |
Return ``True`` if the expected matchers are matched in any order,
otherwise ``False``. | def match(self, item):
"""
Return ``True`` if the expected matchers are matched in any order,
otherwise ``False``.
"""
if not self._unused_matchers:
raise RuntimeError('Matcher exhausted, no more matchers to use')
for matcher in self._unused_matchers:
... |
Return an args string for the repr. | def args_str(self):
"""
Return an args string for the repr.
"""
matched = [str(m) for m in self._used_matchers]
unmatched = [str(m) for m in self._unused_matchers]
return 'matched=[{}], unmatched=[{}]'.format(
', '.join(matched), ', '.join(unmatched)) |
Primary method for wavelet analysis and subsequent deconvolution.
INPUTS:
subregion (default=None): Size, in pixels, of the central region to be analyzed and deconvolved.
scale_count (default=None): Maximum scale to be considered - maximum scale considered during
... | def moresane(self, subregion=None, scale_count=None, sigma_level=4, loop_gain=0.1, tolerance=0.75, accuracy=1e-6,
major_loop_miter=100, minor_loop_miter=30, all_on_gpu=False, decom_mode="ser", core_count=1,
conv_device='cpu', conv_mode='linear', extraction_mode='cpu', enforce_positivit... |
Extension of the MORESANE algorithm. This takes a scale-by-scale approach, attempting to remove all sources
at the lower scales before moving onto the higher ones. At each step the algorithm may return to previous
scales to remove the sources uncovered by the deconvolution.
INPUTS:
star... | def moresane_by_scale(self, start_scale=1, stop_scale=20, subregion=None, sigma_level=4, loop_gain=0.1,
tolerance=0.75, accuracy=1e-6, major_loop_miter=100, minor_loop_miter=30, all_on_gpu=False,
decom_mode="ser", core_count=1, conv_device='cpu', conv_mode='linear', e... |
This method constructs the restoring beam and then adds the convolution to the residual. | def restore(self):
"""
This method constructs the restoring beam and then adds the convolution to the residual.
"""
clean_beam, beam_params = beam_fit(self.psf_data, self.cdelt1, self.cdelt2)
if np.all(np.array(self.psf_data_shape)==2*np.array(self.dirty_data_shape)):
... |
This method tries to ensure that the input data has the correct dimensions.
INPUTS:
input_hdr (no default) Header from which data shape is to be extracted. | def handle_input(self, input_hdr):
"""
This method tries to ensure that the input data has the correct dimensions.
INPUTS:
input_hdr (no default) Header from which data shape is to be extracted.
"""
input_slice = input_hdr['NAXIS']*[0]
for i in range(input... |
This method simply saves the model components and the residual.
INPUTS:
data (no default) Data which is to be saved.
name (no default) File name for new .fits file. Will overwrite. | def save_fits(self, data, name):
"""
This method simply saves the model components and the residual.
INPUTS:
data (no default) Data which is to be saved.
name (no default) File name for new .fits file. Will overwrite.
"""
data = data.reshape(1, 1, dat... |
Convenience function which creates a logger for the module.
INPUTS:
level (default="INFO"): Minimum log level for logged/streamed messages.
OUTPUTS:
logger Logger for the function. NOTE: Must be bound to variable named logger. | def make_logger(self, level="INFO"):
"""
Convenience function which creates a logger for the module.
INPUTS:
level (default="INFO"): Minimum log level for logged/streamed messages.
OUTPUTS:
logger Logger for the function. NOTE: Must be bound to ... |
List actuators, programs or sensors (what is string) | def ls(self, what):
"""List actuators, programs or sensors (what is string)"""
for i in getattr(self.system, what):
self.logger.info('%s: %s: %s', i.__class__.__name__, i, i.status)
return True |
Print Automate help if no parameter is given. Otherwise,
act as pydoc.help() | def help(self, *args, **kwargs):
"""Print Automate help if no parameter is given. Otherwise,
act as pydoc.help()"""
if len(args) > 0 or len(kwargs) > 0:
import pydoc
pydoc.help(*args, **kwargs)
else:
hstr = helpstr
for i in hstr.split("... |
Start Text UI main loop | def text_ui(self):
"""
Start Text UI main loop
"""
self.logger.info("Starting command line interface")
self.help()
try:
self.ipython_ui()
except ImportError:
self.fallback_ui()
self.system.cleanup() |
Prepare headers for http communication.
Return dict of header to be used in requests.
Args:
.. versionadded:: 0.3.2
**additional_headers**: (optional) Additional headers
to be used with request
Returns:
Headers dict. Key and values are s... | def _prepare_headers(self, additional_headers=None, **kwargs):
"""Prepare headers for http communication.
Return dict of header to be used in requests.
Args:
.. versionadded:: 0.3.2
**additional_headers**: (optional) Additional headers
to be used wit... |
Returns response to http HEAD
on provided url | def head(self, url, *args, **kwargs):
"""Returns response to http HEAD
on provided url
"""
res = self._conn.head(url, headers=self._prepare_headers(**kwargs))
if res.status_code == 200:
return res
return None |
Gets data from url as text
Returns content under the provided url as text
Args:
**url**: address of the wanted data
.. versionadded:: 0.3.2
**additional_headers**: (optional) Additional headers
to be used with request
Returns:
... | def get_data(self, url, *args, **kwargs):
"""Gets data from url as text
Returns content under the provided url as text
Args:
**url**: address of the wanted data
.. versionadded:: 0.3.2
**additional_headers**: (optional) Additional headers
... |
Gets data from url as bytes
Returns content under the provided url as bytes
ie. for binary data
Args:
**url**: address of the wanted data
.. versionadded:: 0.3.2
**additional_headers**: (optional) Additional headers
to be used with reque... | def get_raw_data(self, url, *args, **kwargs):
"""Gets data from url as bytes
Returns content under the provided url as bytes
ie. for binary data
Args:
**url**: address of the wanted data
.. versionadded:: 0.3.2
**additional_headers**: (optional)... |
Uploads file to provided url.
Returns contents as text
Args:
**url**: address where to upload file
**filename**: Name of the uploaded file
**file_stream**: file like object to upload
.. versionadded:: 0.3.2
**additional_headers**: (opt... | def post_file(self, url, filename, file_stream, *args, **kwargs):
"""Uploads file to provided url.
Returns contents as text
Args:
**url**: address where to upload file
**filename**: Name of the uploaded file
**file_stream**: file like object to upload
... |
Deletes data under provided url
Returns status as boolean.
Args:
**url**: address of file to be deleted
.. versionadded:: 0.3.2
**additional_headers**: (optional) Additional headers
to be used with request
Returns:
Boolean. ... | def delete_data(self, url, *args, **kwargs):
"""Deletes data under provided url
Returns status as boolean.
Args:
**url**: address of file to be deleted
.. versionadded:: 0.3.2
**additional_headers**: (optional) Additional headers
to be u... |
Показывает последние операции в ленте. | def cmd_feed():
"""
Показывает последние операции в ленте.
"""
r = rocket.operations.cool_feed.get()
r = handle_error(r)
j = r.json()
lines = []
for date, operations in sorted(list(j["dates"].items())):
lines += [[
click.style("===== %s =====" % date, fg="blue", bol... |
Перевести деньги на номер карты. | def cmd_transfer(recipient, amount):
"""
Перевести деньги на номер карты.
"""
r = rocket.card2card.transfer.post(params={
"source_card": recipient,
"amount": amount
})
r = handle_error(r)
j = r.json()
if j["status"] == "approved":
template = "".join([
... |
Given a collection of Unicode diacritics, return a function that takes a
Unicode character and returns the member of the collection the character
has (or None). | def extract_diacritic(*diacritics):
"""
Given a collection of Unicode diacritics, return a function that takes a
Unicode character and returns the member of the collection the character
has (or None).
"""
def _(ch):
decomposed_form = unicodedata.normalize("NFD", ch)
for diacritic... |
Add the given breathing to the given (possibly accented) character. | def add_breathing(ch, breathing):
"""
Add the given breathing to the given (possibly accented) character.
"""
decomposed = unicodedata.normalize("NFD", ch)
if len(decomposed) > 1 and decomposed[1] == LONG:
return unicodedata.normalize(
"NFC", decomposed[0:2] + breathing + decompo... |
Given a collection of Unicode diacritics, return a function that takes a
string and returns the string without those diacritics. | def remove_diacritic(*diacritics):
"""
Given a collection of Unicode diacritics, return a function that takes a
string and returns the string without those diacritics.
"""
def _(text):
return unicodedata.normalize("NFC", "".join(
ch
for ch in unicodedata.normalize("NF... |
Change digital Pin value (boolean). Also PWM supported(float) | def change_digital(self, pin_nr, value):
""" Change digital Pin value (boolean). Also PWM supported(float)"""
if not self._board:
return
with self._lock:
self._act_digital[pin_nr].pin.write(value) |
Recursively merge all input dicts into a single dict. | def deep_merge(*dicts):
"""
Recursively merge all input dicts into a single dict.
"""
result = {}
for d in dicts:
if not isinstance(d, dict):
raise Exception('Can only deep_merge dicts, got {}'.format(d))
for k, v in d.items():
# Whenever the value is a dict, ... |
Create an instance of this resource definition.
Only one instance may exist at any given time. | def create(self, **kwargs):
"""
Create an instance of this resource definition.
Only one instance may exist at any given time.
"""
if self.created:
raise RuntimeError(
'{} already created.'.format(self.__model_type__.__name__))
kwargs = self.... |
Remove an instance of this resource definition. | def remove(self, **kwargs):
"""
Remove an instance of this resource definition.
"""
self.helper.remove(self.inner(), **kwargs)
self._inner = None |
Setup this resource so that is ready to be used in a test. If the
resource has already been created, this call does nothing.
For most resources, this just involves creating the resource in Docker.
:param helper:
The resource helper to use, if one was not provided when this
... | def setup(self, helper=None, **create_kwargs):
"""
Setup this resource so that is ready to be used in a test. If the
resource has already been created, this call does nothing.
For most resources, this just involves creating the resource in Docker.
:param helper:
The... |
.. todo::
Document this. | def set_helper(self, helper):
"""
.. todo::
Document this.
"""
# We don't want to "unset" in this method.
if helper is None:
return
# Get the right kind of helper if given a DockerHelper
if isinstance(helper, DockerHelper):
he... |
A decorator to inject this container into a function as a test fixture. | def as_fixture(self, name=None):
"""
A decorator to inject this container into a function as a test fixture.
"""
if name is None:
name = self.name
def deco(f):
@functools.wraps(f)
def wrapper(*args, **kw):
with self:
... |
:returns: the underlying Docker model object | def inner(self):
"""
:returns: the underlying Docker model object
"""
if not self.created:
raise RuntimeError(
'{} not created yet.'.format(self.__model_type__.__name__))
return self._inner |
Creates the container, starts it, and waits for it to completely start.
:param helper:
The resource helper to use, if one was not provided when this
container definition was created.
:param **run_kwargs: Keyword arguments passed to :meth:`.run`.
:returns:
Th... | def setup(self, helper=None, **run_kwargs):
"""
Creates the container, starts it, and waits for it to completely start.
:param helper:
The resource helper to use, if one was not provided when this
container definition was created.
:param **run_kwargs: Keyword arg... |
Stop and remove the container if it exists. | def teardown(self):
"""
Stop and remove the container if it exists.
"""
while self._http_clients:
self._http_clients.pop().close()
if self.created:
self.halt() |
Get the container's current status from Docker.
If the container does not exist (before creation and after removal),
the status is ``None``. | def status(self):
"""
Get the container's current status from Docker.
If the container does not exist (before creation and after removal),
the status is ``None``.
"""
if not self.created:
return None
self.inner().reload()
return self.inner().s... |
Stop the container. The container must have been created.
:param timeout:
Timeout in seconds to wait for the container to stop before sending
a ``SIGKILL``. Default: 5 (half the Docker default) | def stop(self, timeout=5):
"""
Stop the container. The container must have been created.
:param timeout:
Timeout in seconds to wait for the container to stop before sending
a ``SIGKILL``. Default: 5 (half the Docker default)
"""
self.inner().stop(timeout=... |
Create the container and start it. Similar to ``docker run``.
:param fetch_image:
Whether to try pull the image if it's not found. The behaviour here
is similar to ``docker run`` and this parameter defaults to
``True``.
:param **kwargs: Keyword arguments passed to :m... | def run(self, fetch_image=True, **kwargs):
"""
Create the container and start it. Similar to ``docker run``.
:param fetch_image:
Whether to try pull the image if it's not found. The behaviour here
is similar to ``docker run`` and this parameter defaults to
``... |
Wait for the container to start.
By default this will wait for the log lines matching the patterns
passed in the ``wait_patterns`` parameter of the constructor using an
UnorderedMatcher. For more advanced checks for container startup, this
method should be overridden. | def wait_for_start(self):
"""
Wait for the container to start.
By default this will wait for the log lines matching the patterns
passed in the ``wait_patterns`` parameter of the constructor using an
UnorderedMatcher. For more advanced checks for container startup, this
m... |
:param container_port: The container port.
:param proto: The protocol ('tcp' or 'udp').
:param index: The index of the mapping entry to return.
:returns: A tuple of the interface IP and port on the host. | def get_host_port(self, container_port, proto='tcp', index=0):
"""
:param container_port: The container port.
:param proto: The protocol ('tcp' or 'udp').
:param index: The index of the mapping entry to return.
:returns: A tuple of the interface IP and port on the host.
"... |
Get the first mapping of the first (lowest) container port that has a
mapping. Useful when a container publishes only one port.
Note that unlike the Docker API, which sorts ports lexicographically
(e.g. ``90/tcp`` > ``8000/tcp``), we sort ports numerically so that the
lowest port is alw... | def get_first_host_port(self):
"""
Get the first mapping of the first (lowest) container port that has a
mapping. Useful when a container publishes only one port.
Note that unlike the Docker API, which sorts ports lexicographically
(e.g. ``90/tcp`` > ``8000/tcp``), we sort ports... |
Get container logs.
This method does not support streaming, use :meth:`stream_logs` for
that. | def get_logs(self, stdout=True, stderr=True, timestamps=False, tail='all',
since=None):
"""
Get container logs.
This method does not support streaming, use :meth:`stream_logs` for
that.
"""
return self.inner().logs(
stdout=stdout, stderr=stde... |
Stream container output. | def stream_logs(self, stdout=True, stderr=True, tail='all', timeout=10.0):
"""
Stream container output.
"""
return stream_logs(
self.inner(), stdout=stdout, stderr=stderr, tail=tail,
timeout=timeout) |
Wait for logs matching the given matcher. | def wait_for_logs_matching(self, matcher, timeout=10, encoding='utf-8',
**logs_kwargs):
"""
Wait for logs matching the given matcher.
"""
wait_for_logs_matching(
self.inner(), matcher, timeout=timeout, encoding=encoding,
**logs_kwarg... |
Construct an HTTP client for this container. | def http_client(self, port=None):
"""
Construct an HTTP client for this container.
"""
# Local import to avoid potential circularity.
from seaworthy.client import ContainerHttpClient
client = ContainerHttpClient.for_container(self, container_port=port)
self._http_... |
Войти в приложение с помощью SMS. | def cmd_register(phone):
"""
Войти в приложение с помощью SMS.
"""
if phone is None:
phone = click.prompt("Номер телефона")
r = rocket.devices.register.post(data={"phone": phone})
r = handle_error(r)
id = r.json()["sms_verification"]["id"]
code = click.prompt("Введите код из SM... |
Create the module's index. | def create_autosummary_file(modules, opts):
# type: (List[unicode], Any, unicode) -> None
"""Create the module's index."""
lines = [
'API Reference',
'=============',
'',
'.. autosummary::',
' :template: api_module.rst',
' :toctree: {}'.format(opts.destdir... |
Look for every file in the directory tree and create the corresponding
ReST files. | def recurse_tree(rootpath, excludes, opts):
# type: (unicode, List[unicode], Any) -> List[unicode]
"""
Look for every file in the directory tree and create the corresponding
ReST files.
"""
if INITPY in os.listdir(rootpath):
path_prefix = path.sep.join(rootpath.split(path.sep)[:-1])
... |
Parse and check the command line arguments. | def main(argv=sys.argv):
# type: (List[str]) -> int
"""Parse and check the command line arguments."""
parser = optparse.OptionParser(
usage="""\
usage: %prog [options] -o <output_path> <module_path> [exclude_pattern, ...]
Look recursively in <module_path> for Python modules and packages and create
... |
Запускает интерпретатор Python с подключенной обёрткой API Рокетбанка. | def cmd_repl():
"""
Запускает интерпретатор Python с подключенной обёрткой API Рокетбанка.
"""
import code
import rlcompleter # noqa
import readline
import sys
readline.parse_and_bind("tab: complete")
shell = code.InteractiveConsole({
"rocket": rocket,
})
shell.inte... |
Get the authorization URL to redirect the user | def get_authorization_url(self):
"""Get the authorization URL to redirect the user"""
url = self._get_oauth_url('authenticate')
query = {
'client_id': self._client_id,
'response_type': 'code',
'redirect_uri': self.callback
}
query_str = self.ur... |
Prepare and dispatch a trait change event to a listener. | def _dispatch_change_event(self, object, trait_name, old, new, handler):
""" Prepare and dispatch a trait change event to a listener. """
# Extract the arguments needed from the handler.
args = self.argument_transform(object, trait_name, old, new)
# Send a description of the event to the change event ... |
After user has authorized the request token, get access token
with user supplied verifier. | def get_access_token(self, verifier=None):
"""
After user has authorized the request token, get access token
with user supplied verifier.
"""
try:
url = self._get_oauth_url('access_token')
#build request
query = {
'client_id': ... |
Split `value` into value and "exponent-of-10", where "exponent-of-10" is a
multiple of 3. This corresponds to SI prefixes.
Returns tuple, where the second value is the "exponent-of-10" and the first
value is `value` divided by the "exponent-of-10".
Args
----
value : int, float
Input v... | def split(value, precision=1):
'''
Split `value` into value and "exponent-of-10", where "exponent-of-10" is a
multiple of 3. This corresponds to SI prefixes.
Returns tuple, where the second value is the "exponent-of-10" and the first
value is `value` divided by the "exponent-of-10".
Args
... |
Args:
expof10 : Exponent of a power of 10 associated with a SI unit
character.
Returns:
str : One of the characters in "yzafpnum kMGTPEZY". | def prefix(expof10):
'''
Args:
expof10 : Exponent of a power of 10 associated with a SI unit
character.
Returns:
str : One of the characters in "yzafpnum kMGTPEZY".
'''
prefix_levels = (len(SI_PREFIX_UNITS) - 1) // 2
si_level = expof10 // 3
if abs(si_level) > ... |
Format value to string with SI prefix, using the specified precision.
Parameters
----------
value : int, float
Input value.
precision : int
Number of digits after decimal place to include.
format_str : str or unicode
Format string where ``{prefix}`` and ``{value}`` represent... | def si_format(value, precision=1, format_str=u'{value} {prefix}',
exp_format_str=u'{value}e{expof10}'):
'''
Format value to string with SI prefix, using the specified precision.
Parameters
----------
value : int, float
Input value.
precision : int
Number of digits ... |
Parse a value expressed using SI prefix units to a floating point number.
Parameters
----------
value : str or unicode
Value expressed using SI prefix units (as returned by :func:`si_format`
function).
.. versionchanged:: 1.0
Use unicode string for SI unit to support micro (i.... | def si_parse(value):
'''
Parse a value expressed using SI prefix units to a floating point number.
Parameters
----------
value : str or unicode
Value expressed using SI prefix units (as returned by :func:`si_format`
function).
.. versionchanged:: 1.0
Use unicode string... |
Set sensor ``name`` status to ``status``. | def set_status(self, name, status):
"""
Set sensor ``name`` status to ``status``.
"""
getattr(self.system, name).status = status
return True |
Set statuses from a dictionary of format ``{name: status}`` | def set_object_status(self, statusdict):
"""
Set statuses from a dictionary of format ``{name: status}``
"""
for name, value in statusdict.items():
getattr(self.system, name).status = value
return True |
Toggle boolean-valued sensor status between ``True`` and ``False``. | def toggle_object_status(self, objname):
"""
Toggle boolean-valued sensor status between ``True`` and ``False``.
"""
o = getattr(self.system, objname)
o.status = not o.status
self.system.flush()
return o.status |
Get sensors as a dictionary of format ``{name: status}`` | def get_sensors(self):
"""
Get sensors as a dictionary of format ``{name: status}``
"""
return {i.name: i.status for i in self.system.sensors} |
Get sensors with defined tag as a dictionary of format ``{name: status}`` | def get_websensors(self):
"""
Get sensors with defined tag as a dictionary of format ``{name: status}``
"""
return {i.name: i.status for i in self.system.sensors if self.tag & i.tags} |
Get actuators as a dictionary of format ``{name: status}`` | def get_actuators(self):
"""
Get actuators as a dictionary of format ``{name: status}``
"""
return {i.name: i.status for i in self.system.actuators} |
Return recent log entries as a string. | def log(self):
"""
Return recent log entries as a string.
"""
logserv = self.system.request_service('LogStoreService')
return logserv.lastlog(html=False) |
Посмотреть список тарифов. | def cmd_tariffs():
"""
Посмотреть список тарифов.
"""
r = rocket.tariffs.get()
r = handle_error(r)
for tariff in r.json():
click.echo("- {name} <{url}>".format(
name=click.style(tariff["name"], fg="green", bold=True),
url=tariff["url"])) |
Load system from a dump, if dump file exists, or create a new system if it does not exist. | def load_or_create(cls, filename=None, no_input=False, create_new=False, **kwargs):
"""
Load system from a dump, if dump file exists, or create a new system if it does not exist.
"""
parser = argparse.ArgumentParser()
parser.add_argument('--no_input', action='store_true')
... |
Save state of the system to a dump file :attr:`System.filename` | def save_state(self):
"""
Save state of the system to a dump file :attr:`System.filename`
"""
if not self.filename:
self.logger.error('Filename not specified. Could not save state')
return
self.logger.debug('Saving system state to %s', self.filename)
... |
A read-only property that gives the namespace of the system for evaluating commands. | def cmd_namespace(self):
"""
A read-only property that gives the namespace of the system for evaluating commands.
"""
import automate
ns = dict(list(automate.__dict__.items()) + list(self.namespace.items()))
return ns |
Give unique name for an Sensor/Program/Actuator object | def get_unique_name(self, obj, name='', name_from_system=''):
"""
Give unique name for an Sensor/Program/Actuator object
"""
ns = self.namespace
newname = name
if not newname:
newname = name_from_system
if not newname:
newname = u"Name... |
A property that gives a dictionary that contains services as values and their names as keys. | def services_by_name(self):
"""
A property that gives a dictionary that contains services as values and their names as keys.
"""
srvs = defaultdict(list)
for i in self.services:
srvs[i.__class__.__name__].append(i)
return srvs |
Give SystemObject instance corresponding to the name | def name_to_system_object(self, name):
"""
Give SystemObject instance corresponding to the name
"""
if isinstance(name, str):
if self.allow_name_referencing:
name = name
else:
raise NameError('System.allow_name_referencing is se... |
Get Callable for specified string (for GUI-based editing) | def eval_in_system_namespace(self, exec_str):
"""
Get Callable for specified string (for GUI-based editing)
"""
ns = self.cmd_namespace
try:
return eval(exec_str, ns)
except Exception as e:
self.logger.warning('Could not execute %s, gave error ... |
Register function in the system namespace. Called by Services. | def register_service_functions(self, *funcs):
"""
Register function in the system namespace. Called by Services.
"""
for func in funcs:
self.namespace[func.__name__] = func |
Register service into the system. Called by Services. | def register_service(self, service):
"""
Register service into the system. Called by Services.
"""
if service not in self.services:
self.services.append(service) |
Used by Sensors/Actuators/other services that need to use other services for their
operations. | def request_service(self, type, id=0):
"""
Used by Sensors/Actuators/other services that need to use other services for their
operations.
"""
srvs = self.services_by_name.get(type)
if not srvs:
return
ser = srvs[id]
if not ser.system:... |
Execute commands in automate namespace | def cmd_exec(self, cmd):
"""
Execute commands in automate namespace
"""
if not cmd:
return
ns = self.cmd_namespace
import copy
rval = True
nscopy = copy.copy(ns)
try:
r = eval(cmd, ns)
if isinstance(r, Syste... |
Clean up before quitting | def cleanup(self):
"""
Clean up before quitting
"""
self.pre_exit_trigger = True
self.logger.info("Shutting down %s, please wait a moment.", self.name)
for t in threading.enumerate():
if isinstance(t, TimerClass):
t.cancel()
self.... |
This function parses in values from command line, allowing for user control from the system terminal. | def handle_parser():
"""
This function parses in values from command line, allowing for user control from the system terminal.
"""
parser = argparse.ArgumentParser(description="Runs the pymoresane deconvolution algorithm with the specified "
"arguments. I... |
Writes PUML from the system. If filename is given, stores result in the file.
Otherwise returns result as a string. | def write_puml(self, filename=''):
"""
Writes PUML from the system. If filename is given, stores result in the file.
Otherwise returns result as a string.
"""
def get_type(o):
type = 'program'
if isinstance(o, AbstractSensor):
type ... |
Returns PUML from the system as a SVG image. Requires plantuml library. | def write_svg(self):
"""
Returns PUML from the system as a SVG image. Requires plantuml library.
"""
import plantuml
puml = self.write_puml()
server = plantuml.PlantUML(url=self.url)
svg = server.processes(puml)
return svg |
Calculate the median kneighbor distance.
Find the distance between a set of random datapoints and
their kth nearest neighbours. This is a heuristic for setting the
kernel length scale. | def median_kneighbour_distance(X, k=5):
"""
Calculate the median kneighbor distance.
Find the distance between a set of random datapoints and
their kth nearest neighbours. This is a heuristic for setting the
kernel length scale.
"""
N_all = X.shape[0]
k = min(k, N_all)
N_subset = mi... |
Calculate centiles of distances between random pairs in a dataset.
This an alternative to the median kNN distance for setting the kernel
length scale. | def pair_distance_centile(X, centile, max_pairs=5000):
"""
Calculate centiles of distances between random pairs in a dataset.
This an alternative to the median kNN distance for setting the kernel
length scale.
"""
N = X.shape[0]
n_pairs = min(max_pairs, N**2)
# randorder1 = np.random.pe... |
Fit the inlier model given training data.
This function attempts to choose reasonable defaults for parameters
sigma and rho if none are specified, which could then be adjusted
to improve performance.
Parameters
----------
X : array
Examples of inlier data, o... | def fit(self, X, y=None):
"""
Fit the inlier model given training data.
This function attempts to choose reasonable defaults for parameters
sigma and rho if none are specified, which could then be adjusted
to improve performance.
Parameters
----------
X ... |
Assign classes to test data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns
-------
y_predicted : array
A vector of length N containing assigned classes. If n... | def predict(self, X):
"""
Assign classes to test data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns
-------
y_predicted : array
A vector of ... |
Calculate posterior probabilities of test data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns:
-------
y_prob : array
An array of dimension N times n_inlier_... | def predict_proba(self, X):
"""
Calculate posterior probabilities of test data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns:
-------
y_prob : array
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.