_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q276000 | Meter.extractHolidayDate | test | def extractHolidayDate(self, setting_holiday):
""" Read a single holiday date from meter buffer.
Args:
setting_holiday (int): Holiday from 0-19 or in range(Extents.Holidays)
Returns:
tuple: Holiday tuple, elements are strings.
=============== =============... | python | {
"resource": ""
} |
q276001 | Meter.readSettings | test | 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... | python | {
"resource": ""
} |
q276002 | Meter.writeCmdMsg | test | 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 | python | {
"resource": ""
} |
q276003 | Meter.serialCmdPwdAuth | test | 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... | python | {
"resource": ""
} |
q276004 | V3Meter.updateObservers | test | 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())) | python | {
"resource": ""
} |
q276005 | V4Meter.initLcdLookup | test | 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... | python | {
"resource": ""
} |
q276006 | V4Meter.request | test | 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... | python | {
"resource": ""
} |
q276007 | V4Meter.requestA | test | 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... | python | {
"resource": ""
} |
q276008 | V4Meter.requestB | test | 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... | python | {
"resource": ""
} |
q276009 | V4Meter.makeAB | test | 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 ... | python | {
"resource": ""
} |
q276010 | V4Meter.calculateFields | test | 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... | python | {
"resource": ""
} |
q276011 | V4Meter.setLCDCmd | test | 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... | python | {
"resource": ""
} |
q276012 | V4Meter.setRelay | test | 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... | python | {
"resource": ""
} |
q276013 | V4Meter.serialPostEnd | test | 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()))
... | python | {
"resource": ""
} |
q276014 | V4Meter.setPulseInputRatio | test | 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:... | python | {
"resource": ""
} |
q276015 | V4Meter.setZeroResettableKWH | test | 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")
... | python | {
"resource": ""
} |
q276016 | V4Meter.setLCD | test | 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
... | python | {
"resource": ""
} |
q276017 | iterate_fields | test | 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... | python | {
"resource": ""
} |
q276018 | iterate_schema | test | 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... | python | {
"resource": ""
} |
q276019 | paragraphs | test | 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... | python | {
"resource": ""
} |
q276020 | text | test | 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.
"""
... | python | {
"resource": ""
} |
q276021 | FormatterMixin.statistics | test | 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))) | python | {
"resource": ""
} |
q276022 | Colored.color | test | 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"],
) | python | {
"resource": ""
} |
q276023 | DotsFormatter.show | test | def show(self, text):
"""
Write the text to the stream and flush immediately.
"""
self.stream.write(text)
self.stream.flush() | python | {
"resource": ""
} |
q276024 | DotsFormatter.result_summary | test | 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),
) | python | {
"resource": ""
} |
q276025 | parse | test | 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... | python | {
"resource": ""
} |
q276026 | setup | test | 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... | python | {
"resource": ""
} |
q276027 | run | test | 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... | python | {
"resource": ""
} |
q276028 | transform | test | 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 | python | {
"resource": ""
} |
q276029 | ExampleTransformer.transform_describe | test | 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
... | python | {
"resource": ""
} |
q276030 | ExampleTransformer.transform_describe_body | test | 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... | python | {
"resource": ""
} |
q276031 | ExampleTransformer.transform_example | test | 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... | python | {
"resource": ""
} |
q276032 | ExampleTransformer.transform_example_body | test | 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... | python | {
"resource": ""
} |
q276033 | ExampleTransformer.takes_only_self | test | 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=[],
) | python | {
"resource": ""
} |
q276034 | ExampleLoader.register | test | def register(cls):
"""
Register the path hook.
"""
cls._finder = FileFinder.path_hook((cls, [cls.suffix]))
sys.path_hooks.append(cls._finder) | python | {
"resource": ""
} |
q276035 | ExampleLoader.source_to_code | test | 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) | python | {
"resource": ""
} |
q276036 | apply_argument_parser | test | 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 | python | {
"resource": ""
} |
q276037 | load_by_name | test | 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) | python | {
"resource": ""
} |
q276038 | load_from_path | test | 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... | python | {
"resource": ""
} |
q276039 | discover | test | 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... | python | {
"resource": ""
} |
q276040 | checker | test | 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... | python | {
"resource": ""
} |
q276041 | messages | test | 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
... | python | {
"resource": ""
} |
q276042 | add | test | 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... | python | {
"resource": ""
} |
q276043 | remove | test | 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() | python | {
"resource": ""
} |
q276044 | restart | test | 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) | python | {
"resource": ""
} |
q276045 | call | test | 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... | python | {
"resource": ""
} |
q276046 | get | test | 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... | python | {
"resource": ""
} |
q276047 | makeService | test | 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... | python | {
"resource": ""
} |
q276048 | Nodelist.refresh_session | test | 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:
... | python | {
"resource": ""
} |
q276049 | Nodelist.remove_expired_nodes | test | 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... | python | {
"resource": ""
} |
q276050 | Nodelist.remove_node | test | 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) | python | {
"resource": ""
} |
q276051 | Nodelist.get_last_updated | test | 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... | python | {
"resource": ""
} |
q276052 | Nodelist.get_all_nodes | test | 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)
... | python | {
"resource": ""
} |
q276053 | Reference.refresh_session | test | 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... | python | {
"resource": ""
} |
q276054 | Reference.increment_times_modified | test | 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_... | python | {
"resource": ""
} |
q276055 | Reference.dereference | test | 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. ... | python | {
"resource": ""
} |
q276056 | delimit | test | 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... | python | {
"resource": ""
} |
q276057 | check | test | 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.... | python | {
"resource": ""
} |
q276058 | Status.merge | test | 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... | python | {
"resource": ""
} |
q276059 | exists | test | 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... | python | {
"resource": ""
} |
q276060 | get | test | 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__)
... | python | {
"resource": ""
} |
q276061 | constant | test | 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):
... | python | {
"resource": ""
} |
q276062 | splat | test | 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 ... | python | {
"resource": ""
} |
q276063 | unsplat | test | 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... | python | {
"resource": ""
} |
q276064 | runProcess | test | 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... | python | {
"resource": ""
} |
q276065 | makeService | test | 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... | python | {
"resource": ""
} |
q276066 | completely_parse_reader | test | 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... | python | {
"resource": ""
} |
q276067 | lit | test | 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 ... | python | {
"resource": ""
} |
q276068 | opt | test | 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... | python | {
"resource": ""
} |
q276069 | rep1 | test | 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... | python | {
"resource": ""
} |
q276070 | rep | test | 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... | python | {
"resource": ""
} |
q276071 | rep1sep | test | 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,... | python | {
"resource": ""
} |
q276072 | repsep | test | 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... | python | {
"resource": ""
} |
q276073 | check | test | 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... | python | {
"resource": ""
} |
q276074 | State.close | test | 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 | python | {
"resource": ""
} |
q276075 | State.check | test | 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() | python | {
"resource": ""
} |
q276076 | maybeAddHeart | test | 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... | python | {
"resource": ""
} |
q276077 | wrapHeart | test | def wrapHeart(service):
"""Wrap a service in a MultiService with a heart"""
master = taservice.MultiService()
service.setServiceParent(master)
maybeAddHeart(master)
return master | python | {
"resource": ""
} |
q276078 | freeze_from_checkpoint | test | def freeze_from_checkpoint(input_checkpoint, output_file_path, output_node_names):
"""Freeze and shrink the graph based on a checkpoint and the output node names."""
check_input_checkpoint(input_checkpoint)
output_node_names = output_node_names_string_as_list(output_node_names)
with tf.Session() as se... | python | {
"resource": ""
} |
q276079 | freeze | test | def freeze(sess, output_file_path, output_node_names):
"""Freeze and shrink the graph based on a session and the output node names."""
with TemporaryDirectory() as temp_dir_name:
checkpoint_path = os.path.join(temp_dir_name, 'model.ckpt')
tf.train.Saver().save(sess, checkpoint_path)
fre... | python | {
"resource": ""
} |
q276080 | save_graph_only | test | def save_graph_only(sess, output_file_path, output_node_names, as_text=False):
"""Save a small version of the graph based on a session and the output node names."""
for node in sess.graph_def.node:
node.device = ''
graph_def = graph_util.extract_sub_graph(sess.graph_def, output_node_names)
outpu... | python | {
"resource": ""
} |
q276081 | save_graph_only_from_checkpoint | test | def save_graph_only_from_checkpoint(input_checkpoint, output_file_path, output_node_names, as_text=False):
"""Save a small version of the graph based on a checkpoint and the output node names."""
check_input_checkpoint(input_checkpoint)
output_node_names = output_node_names_string_as_list(output_node_names... | python | {
"resource": ""
} |
q276082 | save_weights_from_checkpoint | test | def save_weights_from_checkpoint(input_checkpoint, output_path, conv_var_names=None, conv_transpose_var_names=None):
"""Save the weights of the trainable variables given a checkpoint, each one in a different file in output_path."""
check_input_checkpoint(input_checkpoint)
with tf.Session() as sess:
... | python | {
"resource": ""
} |
q276083 | restore_from_checkpoint | test | def restore_from_checkpoint(sess, input_checkpoint):
"""Return a TensorFlow saver from a checkpoint containing the metagraph."""
saver = tf.train.import_meta_graph('{}.meta'.format(input_checkpoint))
saver.restore(sess, input_checkpoint)
return saver | python | {
"resource": ""
} |
q276084 | BaseNode.parse | test | def parse(cls, parser, token):
"""
Parse the tag, instantiate the class.
:type parser: django.template.base.Parser
:type token: django.template.base.Token
"""
tag_name, args, kwargs = parse_token_kwargs(
parser, token,
allowed_kwargs=cls.allowed_k... | python | {
"resource": ""
} |
q276085 | BaseNode.render_tag | test | def render_tag(self, context, *tag_args, **tag_kwargs):
"""
Render the tag, with all arguments resolved to their actual values.
"""
raise NotImplementedError("{0}.render_tag() is not implemented!".format(self.__class__.__name__)) | python | {
"resource": ""
} |
q276086 | BaseNode.validate_args | test | def validate_args(cls, tag_name, *args, **kwargs):
"""
Validate the syntax of the template tag.
"""
if cls.min_args is not None and len(args) < cls.min_args:
if cls.min_args == 1:
raise TemplateSyntaxError("'{0}' tag requires at least {1} argument".format(tag_... | python | {
"resource": ""
} |
q276087 | BaseInclusionNode.get_context_data | test | def get_context_data(self, parent_context, *tag_args, **tag_kwargs):
"""
Return the context data for the included template.
"""
raise NotImplementedError("{0}.get_context_data() is not implemented.".format(self.__class__.__name__)) | python | {
"resource": ""
} |
q276088 | BaseAssignmentOrInclusionNode.parse | test | def parse(cls, parser, token):
"""
Parse the "as var" syntax.
"""
bits, as_var = parse_as_var(parser, token)
tag_name, args, kwargs = parse_token_kwargs(parser, bits, ('template',) + cls.allowed_kwargs, compile_args=cls.compile_args, compile_kwargs=cls.compile_kwargs)
# ... | python | {
"resource": ""
} |
q276089 | BaseAssignmentOrInclusionNode.get_context_data | test | def get_context_data(self, parent_context, *tag_args, **tag_kwargs):
"""
Return the context data for the inclusion tag.
Returns ``{'value': self.get_value(parent_context, *tag_args, **tag_kwargs)}`` by default.
"""
if 'template' not in self.allowed_kwargs:
# The over... | python | {
"resource": ""
} |
q276090 | caffe_to_tensorflow_session | test | def caffe_to_tensorflow_session(caffe_def_path, caffemodel_path, inputs, graph_name='Graph',
conversion_out_dir_path=None, use_padding_same=False):
"""Create a TensorFlow Session from a Caffe model."""
try:
# noinspection PyUnresolvedReferences
from caffeflow impo... | python | {
"resource": ""
} |
q276091 | freeze | test | def freeze(caffe_def_path, caffemodel_path, inputs, output_file_path, output_node_names, graph_name='Graph',
conversion_out_dir_path=None, checkpoint_out_path=None, use_padding_same=False):
"""Freeze and shrink the graph based on a Caffe model, the input tensors and the output node names."""
with caf... | python | {
"resource": ""
} |
q276092 | save_graph_only | test | def save_graph_only(caffe_def_path, caffemodel_path, inputs, output_file_path, output_node_names, graph_name='Graph',
use_padding_same=False):
"""Save a small version of the graph based on a Caffe model, the input tensors and the output node names."""
with caffe_to_tensorflow_session(caffe_d... | python | {
"resource": ""
} |
q276093 | make_rows | test | def make_rows(num_columns, seq):
"""
Make a sequence into rows of num_columns columns.
>>> tuple(make_rows(2, [1, 2, 3, 4, 5]))
((1, 4), (2, 5), (3, None))
>>> tuple(make_rows(3, [1, 2, 3, 4, 5]))
((1, 3, 5), (2, 4, None))
"""
# calculate the minimum number of rows necessary to fit the list in
# num_columns C... | python | {
"resource": ""
} |
q276094 | grouper_nofill_str | test | def grouper_nofill_str(n, iterable):
"""
Take a sequence and break it up into chunks of the specified size.
The last chunk may be smaller than size.
This works very similar to grouper_nofill, except
it works with strings as well.
>>> tuple(grouper_nofill_str(3, 'foobarbaz'))
('foo', 'bar', 'baz')
You can sti... | python | {
"resource": ""
} |
q276095 | every_other | test | def every_other(iterable):
"""
Yield every other item from the iterable
>>> ' '.join(every_other('abcdefg'))
'a c e g'
"""
items = iter(iterable)
while True:
try:
yield next(items)
next(items)
except StopIteration:
return | python | {
"resource": ""
} |
q276096 | remove_duplicates | test | def remove_duplicates(iterable, key=None):
"""
Given an iterable with items that may come in as sequential duplicates,
remove those duplicates.
Unlike unique_justseen, this function does not remove triplicates.
>>> ' '.join(remove_duplicates('abcaabbccaaabbbcccbcbc'))
'a b c a b c a a b b c c b c b c'
>>> ' '.... | python | {
"resource": ""
} |
q276097 | peek | test | def peek(iterable):
"""
Get the next value from an iterable, but also return an iterable
that will subsequently return that value and the rest of the
original iterable.
>>> l = iter([1,2,3])
>>> val, l = peek(l)
>>> val
1
>>> list(l)
[1, 2, 3]
"""
peeker, original = itertools.tee(iterable)
return next(pee... | python | {
"resource": ""
} |
q276098 | takewhile_peek | test | def takewhile_peek(predicate, iterable):
"""
Like takewhile, but takes a peekable iterable and doesn't
consume the non-matching item.
>>> items = Peekable(range(10))
>>> is_small = lambda n: n < 4
>>> small_items = takewhile_peek(is_small, items)
>>> list(small_items)
[0, 1, 2, 3]
>>> list(items)
[4, 5, 6... | python | {
"resource": ""
} |
q276099 | partition_items | test | def partition_items(count, bin_size):
"""
Given the total number of items, determine the number of items that
can be added to each bin with a limit on the bin size.
So if you want to partition 11 items into groups of 3, you'll want
three of three and one of two.
>>> partition_items(11, 3)
[3, 3, 3, 2]
But if... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.