INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
extract holiday and weekend: class: ~ekmmeters. Schedule from meter object buffer. | def extractHolidayWeekendSchedules(self):
""" extract holiday and weekend :class:`~ekmmeters.Schedule` from meter object buffer.
Returns:
tuple: Holiday and weekend :class:`~ekmmeters.Schedule` values, as strings.
======= ======================================
Holid... |
Recommended call to read all meter settings at once. | def readSettings(self):
"""Recommended call to read all meter settings at once.
Returns:
bool: True if all subsequent serial calls completed with ACK.
"""
success = (self.readHolidayDates() and
self.readMonthTariffs(ReadMonths.kWh) and
s... |
Internal method to set the command result string. | def writeCmdMsg(self, msg):
""" Internal method to set the command result string.
Args:
msg (str): Message built during command.
"""
ekm_log("(writeCmdMsg | " + self.getContext() + ") " + msg)
self.m_command_msg = msg |
Password step of set commands | def serialCmdPwdAuth(self, password_str):
""" Password step of set commands
This method is normally called within another serial command, so it
does not issue a termination string. Any default password is set
in the caller parameter list, never here.
Args:
password... |
Initialize: class: ~ekmmeters. SerialBlock for V3 read. | def initWorkFormat(self):
""" Initialize :class:`~ekmmeters.SerialBlock` for V3 read. """
self.m_blk_a["reserved_10"] = [1, FieldType.Hex, ScaleType.No, "", 0, False, False]
self.m_blk_a[Field.Model] = [2, FieldType.Hex, ScaleType.No, "", 0, False, True]
self.m_blk_a[Field.Firmware] = [1... |
Required request () override for v3 and standard method to read meter. | def request(self, send_terminator = False):
"""Required request() override for v3 and standard method to read meter.
Args:
send_terminator (bool): Send termination string at end of read.
Returns:
bool: CRC request flag result from most recent read
"""
se... |
Strip reserved and CRC for m_req: class: ~ekmmeters. SerialBlock. | def makeReturnFormat(self):
""" Strip reserved and CRC for m_req :class:`~ekmmeters.SerialBlock`. """
for fld in self.m_blk_a:
compare_fld = fld.upper()
if not "RESERVED" in compare_fld and not "CRC" in compare_fld:
self.m_req[fld] = self.m_blk_a[fld]
pass |
Insert to: class: ~ekmmeters. MeterDB subclass. | def insert(self, meter_db):
""" Insert to :class:`~ekmmeters.MeterDB` subclass.
Please note MeterDB subclassing is only for simplest-case.
Args:
meter_db (MeterDB): Instance of subclass of MeterDB.
"""
if meter_db:
meter_db.dbInsert(self.m_req, self.m_r... |
Fire update method in all attached observers in order of attachment. | def updateObservers(self):
""" Fire update method in all attached observers in order of attachment. """
for observer in self.m_observers:
try:
observer.update(self.m_req)
except:
ekm_log(traceback.format_exc(sys.exc_info())) |
Return: class: ~ekmmeters. Field content scaled and formatted. | def getField(self, fld_name):
""" Return :class:`~ekmmeters.Field` content, scaled and formatted.
Args:
fld_name (str): A :class:`~ekmmeters.Field` value which is on your meter.
Returns:
str: String value (scaled if numeric) for the field.
"""
result = "... |
Initialize A read: class: ~ekmmeters. SerialBlock. | def initFormatA(self):
""" Initialize A read :class:`~ekmmeters.SerialBlock`."""
self.m_blk_a["reserved_1"] = [1, FieldType.Hex, ScaleType.No, "", 0, False, False]
self.m_blk_a[Field.Model] = [2, FieldType.Hex, ScaleType.No, "", 0, False, True]
self.m_blk_a[Field.Firmware] = [1, FieldTyp... |
Initialize B read: class: ~ekmmeters. SerialBlock. | def initFormatB(self):
""" Initialize B read :class:`~ekmmeters.SerialBlock`."""
self.m_blk_b["reserved_5"] = [1, FieldType.Hex, ScaleType.No, "", 0, False, False]
self.m_blk_b[Field.Model] = [2, FieldType.Hex, ScaleType.No, "", 0, False, True]
self.m_blk_b[Field.Firmware] = [1, FieldTyp... |
Initialize lookup table for string input of LCD fields | def initLcdLookup(self):
""" Initialize lookup table for string input of LCD fields """
self.m_lcd_lookup["kWh_Tot"] = LCDItems.kWh_Tot
self.m_lcd_lookup["Rev_kWh_Tot"] = LCDItems.Rev_kWh_Tot
self.m_lcd_lookup["RMS_Volts_Ln_1"] = LCDItems.RMS_Volts_Ln_1
self.m_lcd_lookup["RMS_Vol... |
Combined A and B read for V4 meter. | def request(self, send_terminator = False):
""" Combined A and B read for V4 meter.
Args:
send_terminator (bool): Send termination string at end of read.
Returns:
bool: True on completion.
"""
try:
retA = self.requestA()
retB = se... |
Issue an A read on V4 meter. | def requestA(self):
"""Issue an A read on V4 meter.
Returns:
bool: True if CRC match at end of call.
"""
work_context = self.getContext()
self.setContext("request[v4A]")
self.m_serial_port.write("2f3f".decode("hex") + self.m_meter_address + "3030210d0a".decod... |
Issue a B read on V4 meter. | def requestB(self):
""" Issue a B read on V4 meter.
Returns:
bool: True if CRC match at end of call.
"""
work_context = self.getContext()
self.setContext("request[v4B]")
self.m_serial_port.write("2f3f".decode("hex") + self.m_meter_address + "3031210d0a".decod... |
Munge A and B reads into single serial block with only unique fields. | def makeAB(self):
""" Munge A and B reads into single serial block with only unique fields."""
for fld in self.m_blk_a:
compare_fld = fld.upper()
if not "RESERVED" in compare_fld and not "CRC" in compare_fld:
self.m_req[fld] = self.m_blk_a[fld]
for fld in ... |
Write calculated fields for read buffer. | def calculateFields(self):
"""Write calculated fields for read buffer."""
pf1 = self.m_blk_b[Field.Cos_Theta_Ln_1][MeterData.StringValue]
pf2 = self.m_blk_b[Field.Cos_Theta_Ln_2][MeterData.StringValue]
pf3 = self.m_blk_b[Field.Cos_Theta_Ln_3][MeterData.StringValue]
pf1_int = sel... |
Single call wrapper for LCD set. | def setLCDCmd(self, display_list, password="00000000"):
""" Single call wrapper for LCD set."
Wraps :func:`~ekmmeters.V4Meter.setLcd` and associated init and add methods.
Args:
display_list (list): List composed of :class:`~ekmmeters.LCDItems`
password (str): Optional p... |
Serial call to set relay. | def setRelay(self, seconds, relay, status, password="00000000"):
"""Serial call to set relay.
Args:
seconds (int): Seconds to hold, ero is hold forever. See :class:`~ekmmeters.RelayInterval`.
relay (int): Selected relay, see :class:`~ekmmeters.Relay`.
status (int): S... |
Send termination string to implicit current meter. | def serialPostEnd(self):
""" Send termination string to implicit current meter."""
ekm_log("Termination string sent (" + self.m_context + ")")
try:
self.m_serial_port.write("0142300375".decode("hex"))
except:
ekm_log(traceback.format_exc(sys.exc_info()))
... |
Serial call to set pulse input ratio on a line. | def setPulseInputRatio(self, line_in, new_cnst, password="00000000"):
"""Serial call to set pulse input ratio on a line.
Args:
line_in (int): Member of :class:`~ekmmeters.Pulse`
new_cnst (int): New pulse input ratio
password (str): Optional password
Returns:... |
Serial call to zero resettable kWh registers. | def setZeroResettableKWH(self, password="00000000"):
""" Serial call to zero resettable kWh registers.
Args:
password (str): Optional password.
Returns:
bool: True on completion and ACK.
"""
result = False
self.setContext("setZeroResettableKWH")
... |
Serial call to set LCD using meter object bufer. | def setLCD(self, password="00000000"):
""" Serial call to set LCD using meter object bufer.
Used with :func:`~ekmmeters.V4Meter.addLcdItem`.
Args:
password (str): Optional password
Returns:
bool: True on completion and ACK.
"""
result = False
... |
Recursively iterate over all DictField sub - fields. | def iterate_fields(fields, schema):
"""Recursively iterate over all DictField sub-fields.
:param fields: Field instance (e.g. input)
:type fields: dict
:param schema: Schema instance (e.g. input_schema)
:type schema: dict
"""
schema_dict = {val['name']: val for val in schema}
for field... |
Recursively iterate over all schema sub - fields. | def iterate_schema(fields, schema, path=None):
"""Recursively iterate over all schema sub-fields.
:param fields: Field instance (e.g. input)
:type fields: dict
:param schema: Schema instance (e.g. input_schema)
:type schema: dict
:path schema: Field path
:path schema: string
"""
fo... |
Random paragraphs. | def paragraphs(quantity=2, separator='\n\n', wrap_start='', wrap_end='',
html=False, sentences_quantity=3, as_list=False):
"""Random paragraphs."""
if html:
wrap_start = '<p>'
wrap_end = '</p>'
separator = '\n\n'
result = []
for i in xrange(0, quantity):
r... |
Random text. | def text(length=None, at_least=10, at_most=15, lowercase=True,
uppercase=True, digits=True, spaces=True, punctuation=False):
"""
Random text.
If `length` is present the text will be exactly this chars long. Else the
text will be something between `at_least` and `at_most` chars long.
"""
... |
Add arguments to the parser for collection in app. args. | def add_arguments(cls, parser):
"""Add arguments to the parser for collection in app.args.
Args:
parser:
`argparse.ArgumentParser`. Parser.
Arguments added here are server on
self.args.
"""
parser.add_argument(
'-c... |
Applies task numbers to an issue. | def apply_tasks_to_issue(self, issue, tasks, issue_body=None):
"""Applies task numbers to an issue."""
issue_body = issue_body or issue.body
task_numbers = transport.format_task_numbers_with_links(tasks)
if task_numbers:
new_body = transport.ASANA_SECTION_RE.sub('', issue_bod... |
Creates a local map of github labels/ milestones to asana tags. | def sync_labels(self, repo):
"""Creates a local map of github labels/milestones to asana tags."""
logging.info("syncing new github.com labels to tags")
# create label tag map
ltm = self.app.data.get("label-tag-map", {})
# loop over labels, if they don't have tags, make them
... |
Return output for the combined time and result summary statistics. | def statistics(self, elapsed, result):
"""
Return output for the combined time and result summary statistics.
"""
return "\n".join((self.timing(elapsed), self.result_summary(result))) |
Color some text in the given ANSI color. | def color(self, color, text):
"""
Color some text in the given ANSI color.
"""
return "{escape}{text}{reset}".format(
escape=self.ANSI[color], text=text, reset=self.ANSI["reset"],
) |
Write the text to the stream and flush immediately. | def show(self, text):
"""
Write the text to the stream and flush immediately.
"""
self.stream.write(text)
self.stream.flush() |
Return a summary of the results. | def result_summary(self, result):
"""
Return a summary of the results.
"""
return "{} examples, {} errors, {} failures\n".format(
result.testsRun, len(result.errors), len(result.failures),
) |
Parse some arguments using the parser. | def parse(argv=None):
"""
Parse some arguments using the parser.
"""
if argv is None:
argv = sys.argv[1:]
# Evade http://bugs.python.org/issue9253
if not argv or argv[0] not in {"run", "transform"}:
argv = ["run"] + argv
arguments = _clean(_parser.parse_args(argv))
re... |
Setup the environment for an example run. | def setup(config):
"""
Setup the environment for an example run.
"""
formatter = config.Formatter()
if config.verbose:
formatter = result.Verbose(formatter)
if config.color:
formatter = result.Colored(formatter)
current_result = result.ExampleResult(formatter)
ivoire... |
Time to run. | def run(config):
"""
Time to run.
"""
setup(config)
if config.exitfirst:
ivoire.current_result.failfast = True
ivoire.current_result.startTestRun()
for spec in config.specs:
try:
load_by_name(spec)
except Exception:
ivoire.current_result.a... |
Run in transform mode. | def transform(config):
"""
Run in transform mode.
"""
if transform_possible:
ExampleLoader.register()
args, sys.argv[1:] = sys.argv[1:], config.args
try:
return runpy.run_path(config.runner, run_name="__main__")
finally:
sys.argv[1:] = args |
with describe ( thing ) as it:... | def visit_With(self, node):
"""
with describe(thing) as it:
...
|
v
class TestThing(TestCase):
...
"""
withitem, = node.items
context = withitem.context_expr
if context.func.id == "describe":
descr... |
Transform a describe node into a TestCase. | def transform_describe(self, node, describes, context_variable):
"""
Transform a describe node into a ``TestCase``.
``node`` is the node object.
``describes`` is the name of the object being described.
``context_variable`` is the name bound in the context manager (usually
... |
Transform the body of an ExampleGroup. | def transform_describe_body(self, body, group_var):
"""
Transform the body of an ``ExampleGroup``.
``body`` is the body.
``group_var`` is the name bound to the example group in the context
manager (usually "it").
"""
for node in body:
withitem, = no... |
Transform an example node into a test method. | def transform_example(self, node, name, context_variable, group_variable):
"""
Transform an example node into a test method.
Returns the unchanged node if it wasn't an ``Example``.
``node`` is the node object.
``name`` is the name of the example being described.
``conte... |
Transform the body of an Example into the body of a method. | def transform_example_body(self, body, context_variable):
"""
Transform the body of an ``Example`` into the body of a method.
Replaces instances of ``context_variable`` to refer to ``self``.
``body`` is the body.
``context_variable`` is the name bound in the surrounding context... |
Return an argument list node that takes only self. | def takes_only_self(self):
"""
Return an argument list node that takes only ``self``.
"""
return ast.arguments(
args=[ast.arg(arg="self")],
defaults=[],
kw_defaults=[],
kwonlyargs=[],
) |
Register the path hook. | def register(cls):
"""
Register the path hook.
"""
cls._finder = FileFinder.path_hook((cls, [cls.suffix]))
sys.path_hooks.append(cls._finder) |
Transform the source code then return the code object. | def source_to_code(self, source_bytes, source_path):
"""
Transform the source code, then return the code object.
"""
node = ast.parse(source_bytes)
transformed = ExampleTransformer().transform(node)
return compile(transformed, source_path, "exec", dont_inherit=True) |
Apply the argument parser. | def apply_argument_parser(argumentsParser, options=None):
""" Apply the argument parser. """
if options is not None:
args = argumentsParser.parse_args(options)
else:
args = argumentsParser.parse_args()
return args |
Load a spec from either a file path or a fully qualified name. | def load_by_name(name):
"""
Load a spec from either a file path or a fully qualified name.
"""
if os.path.exists(name):
load_from_path(name)
else:
__import__(name) |
Load a spec from a given path discovering specs if a directory is given. | def load_from_path(path):
"""
Load a spec from a given path, discovering specs if a directory is given.
"""
if os.path.isdir(path):
paths = discover(path)
else:
paths = [path]
for path in paths:
name = os.path.basename(os.path.splitext(path)[0])
imp.load_source... |
Discover all of the specs recursively inside path. | def discover(path, filter_specs=filter_specs):
"""
Discover all of the specs recursively inside ``path``.
Successively yields the (full) relative paths to each spec.
"""
for dirpath, _, filenames in os.walk(path):
for spec in filter_specs(filenames):
yield os.path.join(dirpath... |
Construct a function that checks a directory for process configuration | def checker(location, receiver):
"""Construct a function that checks a directory for process configuration
The function checks for additions or removals
of JSON process configuration files and calls the appropriate receiver
methods.
:param location: string, the directory to monitor
:param rece... |
Construct a function that checks a directory for messages | def messages(location, receiver):
"""Construct a function that checks a directory for messages
The function checks for new messages and
calls the appropriate method on the receiver. Sent messages are
deleted.
:param location: string, the directory to monitor
:param receiver: IEventReceiver
... |
Add a process. | def add(places, name, cmd, args, env=None, uid=None, gid=None, extras=None,
env_inherit=None):
"""Add a process.
:param places: a Places instance
:param name: string, the logical name of the process
:param cmd: string, executable
:param args: list of strings, command-line arguments
:par... |
Remove a process | def remove(places, name):
"""Remove a process
:params places: a Places instance
:params name: string, the logical name of the process
:returns: None
"""
config = filepath.FilePath(places.config)
fle = config.child(name)
fle.remove() |
Restart a process | def restart(places, name):
"""Restart a process
:params places: a Places instance
:params name: string, the logical name of the process
:returns: None
"""
content = _dumps(dict(type='RESTART', name=name))
_addMessage(places, content) |
Call results. func on the attributes of results | def call(results):
"""Call results.func on the attributes of results
:params result: dictionary-like object
:returns: None
"""
results = vars(results)
places = Places(config=results.pop('config'),
messages=results.pop('messages'))
func = results.pop('func')
func(plac... |
Return a service which monitors processes based on directory contents | def get(config, messages, freq, pidDir=None, reactor=None):
"""Return a service which monitors processes based on directory contents
Construct and return a service that, when started, will run processes
based on the contents of the 'config' directory, restarting them
if file contents change and stoppin... |
Return a service based on parsed command - line options | def makeService(opt):
"""Return a service based on parsed command-line options
:param opt: dict-like object. Relevant keys are config, messages,
pid, frequency, threshold, killtime, minrestartdelay
and maxrestartdelay
:returns: service, {twisted.application.interfaces.IServi... |
Adds or refreshes a particular node in the nodelist attributing the current time with the node_id. | def refresh_session(self, node_id=None):
"""
Adds or refreshes a particular node in the nodelist, attributing the
current time with the node_id.
:param string node_id: optional, the connection id of the node whose
session should be refreshed
"""
if not node_id:
... |
Detects connections that have held a reference for longer than its process_ttl without refreshing its session. This function does not actually removed them from the hash. ( See remove_expired_nodes. ) | def find_expired_nodes(self, node_ids=None):
"""
Detects connections that have held a reference for longer than its
process_ttl without refreshing its session. This function does not
actually removed them from the hash. (See remove_expired_nodes.)
:param list node_ids: optional,... |
Removes all expired nodes from the nodelist. If a set of node_ids is passed in those ids are checked to ensure they haven t been refreshed prior to a lock being acquired. | def remove_expired_nodes(self, node_ids=None):
"""
Removes all expired nodes from the nodelist. If a set of node_ids is
passed in, those ids are checked to ensure they haven't been refreshed
prior to a lock being acquired.
Should only be run with a lock.
:param list no... |
Removes a particular node from the nodelist. | def remove_node(self, node_id=None):
"""
Removes a particular node from the nodelist.
:param string node_id: optional, the process id of the node to remove
"""
if not node_id:
node_id = self.conn.id
self.conn.client.hdel(self.nodelist_key, node_id) |
Returns the time a particular node has been last refreshed. | def get_last_updated(self, node_id=None):
"""
Returns the time a particular node has been last refreshed.
:param string node_id: optional, the connection id of the node to retrieve
:rtype: int
:returns: Returns a unix timestamp if it exists, otherwise None
"""
i... |
Returns all nodes in the hash with the time they were last refreshed as a dictionary. | def get_all_nodes(self):
"""
Returns all nodes in the hash with the time they were last refreshed
as a dictionary.
:rtype: dict(string, int)
:returns: A dictionary of strings and corresponding timestamps
"""
nodes = self.conn.client.hgetall(self.nodelist_key)
... |
Update the session for this node. Specifically ; lock on the reflist then update the time this node acquired the reference. | def refresh_session(self):
"""
Update the session for this node. Specifically; lock on the reflist,
then update the time this node acquired the reference.
This method should only be called while the reference is locked.
"""
expired_nodes = self.nodelist.find_expired_nod... |
Increments the number of times this resource has been modified by all processes. | def increment_times_modified(self):
"""
Increments the number of times this resource has been modified by all
processes.
"""
rc = self.conn.client.incr(self.times_modified_key)
self.conn.client.pexpire(self.times_modified_key,
phonon.s_to_... |
: returns: The total number of times increment_times_modified has been called for this resource by all processes.: rtype: int | def get_times_modified(self):
"""
:returns: The total number of times increment_times_modified has been called for this resource by all processes.
:rtype: int
"""
times_modified = self.conn.client.get(self.times_modified_key)
if times_modified is None:
return ... |
: returns: The total number of elements in the reference list.: rtype: int | def count(self):
"""
:returns: The total number of elements in the reference list.
:rtype: int
"""
references = self.conn.client.get(self.refcount_key)
if references is None:
return 0
return int(references) |
This method should only be called while the reference is locked. | def dereference(self, callback=None, args=None, kwargs=None):
"""
This method should only be called while the reference is locked.
Decrements the reference count for the resource. If this process holds
the only reference at the time we finish dereferencing it; True is
returned. ... |
Returns a list of tokens interleaved with the delimiter. | def delimit(values, delimiter=', '):
"Returns a list of tokens interleaved with the delimiter."
toks = []
if not values:
return toks
if not isinstance(delimiter, (list, tuple)):
delimiter = [delimiter]
last = len(values) - 1
for i, value in enumerate(values):
toks.app... |
check which processes need to be restarted | def check(path, start, now):
"""check which processes need to be restarted
:params path: a twisted.python.filepath.FilePath with configurations
:params start: when the checker started running
:params now: current time
:returns: list of strings
"""
return [child.basename() for child in path.... |
Parse configuration | def parseConfig(opt):
"""Parse configuration
:params opt: dict-like object with config and messages keys
:returns: restarter, path
"""
places = ctllib.Places(config=opt['config'], messages=opt['messages'])
restarter = functools.partial(ctllib.restart, places)
path = filepath.FilePath(opt['c... |
Make a service | def makeService(opt):
"""Make a service
:params opt: dictionary-like object with 'freq', 'config' and 'messages'
:returns: twisted.application.internet.TimerService that at opt['freq']
checks for stale processes in opt['config'], and sends
restart messages through opt['messages'... |
Generate a basic error to include the current state. | def expected_error(self, expected: str) -> str:
"""Generate a basic error to include the current state.
A parser can supply only a representation of what it is expecting to
this method and the reader will provide the context, including the index
to the error.
Args:
... |
Generate an error to indicate that infinite recursion was encountered. | def recursion_error(self, repeated_parser: str):
"""Generate an error to indicate that infinite recursion was encountered.
A parser can supply a representation of itself to this method and the
reader will supply the context, including the location where the
parser stalled.
Args... |
Generate a basic error to include the current state. | def expected_error(self, expected: str) -> str:
"""Generate a basic error to include the current state.
A parser can supply only a representation of what it is expecting to
this method and the reader will provide the context, including the line
and character positions.
Args:
... |
Generate an error to indicate that infinite recursion was encountered. | def recursion_error(self, repeated_parser: str):
"""Generate an error to indicate that infinite recursion was encountered.
A parser can supply a representation of itself to this method and the
reader will supply the context, including the location where the
parser stalled.
Args... |
Merge the failure message from another status into this one. | def merge(self, status: 'Status[Input, Output]') -> 'Status[Input, Output]':
"""Merge the failure message from another status into this one.
Whichever status represents parsing that has gone the farthest is
retained. If both statuses have gone the same distance, then the
expected values... |
Query to test if a value exists. | def exists(value):
"Query to test if a value exists."
if not isinstance(value, Token):
raise TypeError('value must be a token')
if not hasattr(value, 'identifier'):
raise TypeError('value must support an identifier')
if not value.identifier:
value = value.__class__(**value.__di... |
Query to get the value. | def get(value):
"Query to get the value."
if not isinstance(value, Token):
raise TypeError('value must be a token')
if not hasattr(value, 'identifier'):
raise TypeError('value must support an identifier')
if not value.identifier:
value = value.__class__(**value.__dict__)
... |
Produce a function that always returns a supplied value. | def constant(x: A) -> Callable[..., A]:
"""Produce a function that always returns a supplied value.
Args:
x: Any object.
Returns:
A function that accepts any number of positional and keyword arguments, discards them, and returns ``x``.
"""
def constanted(*args, **kwargs):
... |
Convert a function taking multiple arguments into a function taking a single iterable argument. | def splat(f: Callable[..., A]) -> Callable[[Iterable], A]:
"""Convert a function taking multiple arguments into a function taking a single iterable argument.
Args:
f: Any function
Returns:
A function that accepts a single iterable argument. Each element of this iterable argument is passed ... |
Convert a function taking a single iterable argument into a function taking multiple arguments. | def unsplat(f: Callable[[Iterable], A]) -> Callable[..., A]:
"""Convert a function taking a single iterable argument into a function taking multiple arguments.
Args:
f: Any function taking a single iterable argument
Returns:
A function that accepts multiple arguments. Each argument of this... |
Run a process return a deferred that fires when it is done | def runProcess(args, timeout, grace, reactor):
"""Run a process, return a deferred that fires when it is done
:params args: Process arguments
:params timeout: Time before terminating process
:params grace: Time before killing process after terminating it
:params reactor: IReactorProcess and IReacto... |
Make scheduler service | def makeService(opts):
"""Make scheduler service
:params opts: dict-like object.
keys: frequency, args, timeout, grace
"""
ser = tainternet.TimerService(opts['frequency'], runProcess, opts['args'],
opts['timeout'], opts['grace'], tireactor)
ret = service.Mul... |
Consume reader and return Success only on complete consumption. | def completely_parse_reader(parser: Parser[Input, Output], reader: Reader[Input]) -> Result[Output]:
"""Consume reader and return Success only on complete consumption.
This is a helper function for ``parse`` methods, which return ``Success``
when the input is completely consumed and ``Failure`` with an app... |
Match a literal sequence. | def lit(literal: Sequence[Input], *literals: Sequence[Sequence[Input]]) -> Parser:
"""Match a literal sequence.
In the `TextParsers`` context, this matches the literal string
provided. In the ``GeneralParsers`` context, this matches a sequence of
input.
If multiple literals are provided, they are ... |
Optionally match a parser. | def opt(parser: Union[Parser, Sequence[Input]]) -> OptionalParser:
"""Optionally match a parser.
An ``OptionalParser`` attempts to match ``parser``. If it succeeds, it
returns a list of length one with the value returned by the parser as the
only element. If it fails, it returns an empty list.
Arg... |
Match a parser one or more times repeatedly. | def rep1(parser: Union[Parser, Sequence[Input]]) -> RepeatedOnceParser:
"""Match a parser one or more times repeatedly.
This matches ``parser`` multiple times in a row. If it matches as least
once, it returns a list of values from each time ``parser`` matched. If it
does not match ``parser`` at all, it... |
Match a parser zero or more times repeatedly. | def rep(parser: Union[Parser, Sequence[Input]]) -> RepeatedParser:
"""Match a parser zero or more times repeatedly.
This matches ``parser`` multiple times in a row. A list is returned
containing the value from each match. If there are no matches, an empty list
is returned.
Args:
parser: Pa... |
Match a parser one or more times separated by another parser. | def rep1sep(parser: Union[Parser, Sequence[Input]], separator: Union[Parser, Sequence[Input]]) \
-> RepeatedOnceSeparatedParser:
"""Match a parser one or more times separated by another parser.
This matches repeated sequences of ``parser`` separated by ``separator``.
If there is at least one match,... |
Match a parser zero or more times separated by another parser. | def repsep(parser: Union[Parser, Sequence[Input]], separator: Union[Parser, Sequence[Input]]) \
-> RepeatedSeparatedParser:
"""Match a parser zero or more times separated by another parser.
This matches repeated sequences of ``parser`` separated by ``separator``. A
list is returned containing the v... |
Check all processes | def check(settings, states, location):
"""Check all processes"""
children = {child.basename(): child for child in location.children()}
last = set(states)
current = set(children)
gone = last - current
added = current - last
for name in gone:
states[name].close()
del states[nam... |
Make a service | def makeService(opt):
"""Make a service
:params opt: dictionary-like object with 'freq', 'config' and 'messages'
:returns: twisted.application.internet.TimerService that at opt['freq']
checks for stale processes in opt['config'], and sends
restart messages through opt['messages'... |
Discard data and cancel all calls. | def close(self):
"""Discard data and cancel all calls.
Instance cannot be reused after closing.
"""
if self.closed:
raise ValueError("Cannot close a closed state")
if self.call is not None:
self.call.cancel()
self.closed = True |
Check the state of HTTP | def check(self):
"""Check the state of HTTP"""
if self.closed:
raise ValueError("Cannot check a closed state")
self._maybeReset()
if self.url is None:
return False
return self._maybeCheck() |
Make a service | def makeService():
"""Make a service
:returns: an IService
"""
configJSON = os.environ.get('NCOLONY_CONFIG')
if configJSON is None:
return None
config = json.loads(configJSON)
params = config.get('ncolony.beatcheck')
if params is None:
return None
myFilePath = filepa... |
Add a heart to a service collection | def maybeAddHeart(master):
"""Add a heart to a service collection
Add a heart to a service.IServiceCollector if
the heart is not None.
:params master: a service.IServiceCollector
"""
heartSer = makeService()
if heartSer is None:
return
heartSer.setName('heart')
heartSer.set... |
Wrap a service in a MultiService with a heart | def wrapHeart(service):
"""Wrap a service in a MultiService with a heart"""
master = taservice.MultiService()
service.setServiceParent(master)
maybeAddHeart(master)
return master |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.