_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q18200 | Facts.load_facts | train | def load_facts(self, facts):
"""Load a set of facts into the CLIPS data base.
The C equivalent of the CLIPS load-facts command.
Facts can be loaded from a string or from a text file.
"""
facts = facts.encode()
if os.path.exists(facts):
ret = lib.EnvLoadFac... | python | {
"resource": ""
} |
q18201 | Facts.save_facts | train | def save_facts(self, path, mode=SaveMode.LOCAL_SAVE):
"""Save the facts in the system to the specified file.
The Python equivalent of the CLIPS save-facts command.
"""
ret = lib.EnvSaveFacts(self._env, path.encode(), mode)
if ret == -1:
raise CLIPSError(self._env)
... | python | {
"resource": ""
} |
q18202 | Fact.asserted | train | def asserted(self):
"""True if the fact has been asserted within CLIPS."""
# https://sourceforge.net/p/clipsrules/discussion/776945/thread/4f04bb9e/
if self.index == 0:
return False
return bool(lib.EnvFactExistp(self._env, self._fact)) | python | {
"resource": ""
} |
q18203 | Fact.template | train | def template(self):
"""The associated Template."""
return Template(
self._env, lib.EnvFactDeftemplate(self._env, self._fact)) | python | {
"resource": ""
} |
q18204 | Fact.assertit | train | def assertit(self):
"""Assert the fact within the CLIPS environment."""
if self.asserted:
raise RuntimeError("Fact already asserted")
lib.EnvAssignFactSlotDefaults(self._env, self._fact)
if lib.EnvAssert(self._env, self._fact) == ffi.NULL:
raise CLIPSError(self.... | python | {
"resource": ""
} |
q18205 | Fact.retract | train | def retract(self):
"""Retract the fact from the CLIPS environment."""
if lib.EnvRetract(self._env, self._fact) != 1:
raise CLIPSError(self._env) | python | {
"resource": ""
} |
q18206 | ImpliedFact.append | train | def append(self, value):
"""Append an element to the fact."""
if self.asserted:
raise RuntimeError("Fact already asserted")
self._multifield.append(value) | python | {
"resource": ""
} |
q18207 | ImpliedFact.extend | train | def extend(self, values):
"""Append multiple elements to the fact."""
if self.asserted:
raise RuntimeError("Fact already asserted")
self._multifield.extend(values) | python | {
"resource": ""
} |
q18208 | ImpliedFact.assertit | train | def assertit(self):
"""Assert the fact within CLIPS."""
data = clips.data.DataObject(self._env)
data.value = list(self._multifield)
if lib.EnvPutFactSlot(
self._env, self._fact, ffi.NULL, data.byref) != 1:
raise CLIPSError(self._env)
super(ImpliedFac... | python | {
"resource": ""
} |
q18209 | TemplateFact.update | train | def update(self, sequence=None, **mapping):
"""Add multiple elements to the fact."""
if sequence is not None:
if isinstance(sequence, dict):
for slot in sequence:
self[slot] = sequence[slot]
else:
for slot, value in sequence:
... | python | {
"resource": ""
} |
q18210 | Template.name | train | def name(self):
"""Template name."""
return ffi.string(
lib.EnvGetDeftemplateName(self._env, self._tpl)).decode() | python | {
"resource": ""
} |
q18211 | Template.module | train | def module(self):
"""The module in which the Template is defined.
Python equivalent of the CLIPS deftemplate-module command.
"""
modname = ffi.string(lib.EnvDeftemplateModule(self._env, self._tpl))
defmodule = lib.EnvFindDefmodule(self._env, modname)
return Module(self... | python | {
"resource": ""
} |
q18212 | Template.watch | train | def watch(self, flag):
"""Whether or not the Template is being watched."""
lib.EnvSetDeftemplateWatch(self._env, int(flag), self._tpl) | python | {
"resource": ""
} |
q18213 | Template.slots | train | def slots(self):
"""Iterate over the Slots of the Template."""
if self.implied:
return ()
data = clips.data.DataObject(self._env)
lib.EnvDeftemplateSlotNames(self._env, self._tpl, data.byref)
return tuple(
TemplateSlot(self._env, self._tpl, n.encode()) ... | python | {
"resource": ""
} |
q18214 | Template.new_fact | train | def new_fact(self):
"""Create a new Fact from this template."""
fact = lib.EnvCreateFact(self._env, self._tpl)
if fact == ffi.NULL:
raise CLIPSError(self._env)
return new_fact(self._env, fact) | python | {
"resource": ""
} |
q18215 | Template.undefine | train | def undefine(self):
"""Undefine the Template.
Python equivalent of the CLIPS undeftemplate command.
The object becomes unusable after this method has been called.
"""
if lib.EnvUndeftemplate(self._env, self._tpl) != 1:
raise CLIPSError(self._env) | python | {
"resource": ""
} |
q18216 | TemplateSlot.multifield | train | def multifield(self):
"""True if the slot is a multifield slot."""
return bool(lib.EnvDeftemplateSlotMultiP(
self._env, self._tpl, self._name)) | python | {
"resource": ""
} |
q18217 | TemplateSlot.default_type | train | def default_type(self):
"""The default value type for this Slot.
The Python equivalent of the CLIPS deftemplate-slot-defaultp function.
"""
return TemplateSlotDefaultType(
lib.EnvDeftemplateSlotDefaultP(self._env, self._tpl, self._name)) | python | {
"resource": ""
} |
q18218 | Classes.instances_changed | train | def instances_changed(self):
"""True if any instance has changed."""
value = bool(lib.EnvGetInstancesChanged(self._env))
lib.EnvSetInstancesChanged(self._env, int(False))
return value | python | {
"resource": ""
} |
q18219 | Classes.classes | train | def classes(self):
"""Iterate over the defined Classes."""
defclass = lib.EnvGetNextDefclass(self._env, ffi.NULL)
while defclass != ffi.NULL:
yield Class(self._env, defclass)
defclass = lib.EnvGetNextDefclass(self._env, defclass) | python | {
"resource": ""
} |
q18220 | Classes.find_class | train | def find_class(self, name):
"""Find the Class by its name."""
defclass = lib.EnvFindDefclass(self._env, name.encode())
if defclass == ffi.NULL:
raise LookupError("Class '%s' not found" % name)
return Class(self._env, defclass) | python | {
"resource": ""
} |
q18221 | Classes.instances | train | def instances(self):
"""Iterate over the defined Instancees."""
definstance = lib.EnvGetNextInstance(self._env, ffi.NULL)
while definstance != ffi.NULL:
yield Instance(self._env, definstance)
definstance = lib.EnvGetNextInstance(self._env, definstance) | python | {
"resource": ""
} |
q18222 | Classes.find_instance | train | def find_instance(self, name, module=None):
"""Find the Instance by its name."""
module = module if module is not None else ffi.NULL
definstance = lib.EnvFindInstance(self._env, module, name.encode(), 1)
if definstance == ffi.NULL:
raise LookupError("Instance '%s' not found" ... | python | {
"resource": ""
} |
q18223 | Classes.load_instances | train | def load_instances(self, instances):
"""Load a set of instances into the CLIPS data base.
The C equivalent of the CLIPS load-instances command.
Instances can be loaded from a string,
from a file or from a binary file.
"""
instances = instances.encode()
if os.p... | python | {
"resource": ""
} |
q18224 | Classes.restore_instances | train | def restore_instances(self, instances):
"""Restore a set of instances into the CLIPS data base.
The Python equivalent of the CLIPS restore-instances command.
Instances can be passed as a set of strings or as a file.
"""
instances = instances.encode()
if os.path.exists... | python | {
"resource": ""
} |
q18225 | Classes.save_instances | train | def save_instances(self, path, binary=False, mode=SaveMode.LOCAL_SAVE):
"""Save the instances in the system to the specified file.
If binary is True, the instances will be saved in binary format.
The Python equivalent of the CLIPS save-instances command.
"""
if binary:
... | python | {
"resource": ""
} |
q18226 | Classes.make_instance | train | def make_instance(self, command):
"""Create and initialize an instance of a user-defined class.
command must be a string in the form:
(<instance-name> of <class-name> <slot-override>*)
<slot-override> :== (<slot-name> <constant>*)
Python equivalent of the CLIPS make-instance c... | python | {
"resource": ""
} |
q18227 | Class.name | train | def name(self):
"""Class name."""
return ffi.string(lib.EnvGetDefclassName(self._env, self._cls)).decode() | python | {
"resource": ""
} |
q18228 | Class.module | train | def module(self):
"""The module in which the Class is defined.
Python equivalent of the CLIPS defglobal-module command.
"""
modname = ffi.string(lib.EnvDefclassModule(self._env, self._cls))
defmodule = lib.EnvFindDefmodule(self._env, modname)
return Module(self._env, d... | python | {
"resource": ""
} |
q18229 | Class.watch_instances | train | def watch_instances(self, flag):
"""Whether or not the Class Instances are being watched."""
lib.EnvSetDefclassWatchInstances(self._env, int(flag), self._cls) | python | {
"resource": ""
} |
q18230 | Class.watch_slots | train | def watch_slots(self, flag):
"""Whether or not the Class Slots are being watched."""
lib.EnvSetDefclassWatchSlots(self._env, int(flag), self._cls) | python | {
"resource": ""
} |
q18231 | Class.new_instance | train | def new_instance(self, name):
"""Create a new raw instance from this Class.
No slot overrides or class default initializations
are performed for the instance.
This function bypasses message-passing.
"""
ist = lib.EnvCreateRawInstance(self._env, self._cls, name.encode()... | python | {
"resource": ""
} |
q18232 | Class.find_message_handler | train | def find_message_handler(self, handler_name, handler_type='primary'):
"""Returns the MessageHandler given its name and type for this class."""
ret = lib.EnvFindDefmessageHandler(
self._env, self._cls, handler_name.encode(), handler_type.encode())
if ret == 0:
raise CLIPSE... | python | {
"resource": ""
} |
q18233 | Class.subclass | train | def subclass(self, klass):
"""True if the Class is a subclass of the given one."""
return bool(lib.EnvSubclassP(self._env, self._cls, klass._cls)) | python | {
"resource": ""
} |
q18234 | Class.superclass | train | def superclass(self, klass):
"""True if the Class is a superclass of the given one."""
return bool(lib.EnvSuperclassP(self._env, self._cls, klass._cls)) | python | {
"resource": ""
} |
q18235 | Class.slots | train | def slots(self, inherited=False):
"""Iterate over the Slots of the class."""
data = clips.data.DataObject(self._env)
lib.EnvClassSlots(self._env, self._cls, data.byref, int(inherited))
return (ClassSlot(self._env, self._cls, n.encode()) for n in data.value) | python | {
"resource": ""
} |
q18236 | Class.instances | train | def instances(self):
"""Iterate over the instances of the class."""
ist = lib.EnvGetNextInstanceInClass(self._env, self._cls, ffi.NULL)
while ist != ffi.NULL:
yield Instance(self._env, ist)
ist = lib.EnvGetNextInstanceInClass(self._env, self._cls, ist) | python | {
"resource": ""
} |
q18237 | Class.subclasses | train | def subclasses(self, inherited=False):
"""Iterate over the subclasses of the class.
This function is the Python equivalent
of the CLIPS class-subclasses command.
"""
data = clips.data.DataObject(self._env)
lib.EnvClassSubclasses(self._env, self._cls, data.byref, int(in... | python | {
"resource": ""
} |
q18238 | Class.superclasses | train | def superclasses(self, inherited=False):
"""Iterate over the superclasses of the class.
This function is the Python equivalent
of the CLIPS class-superclasses command.
"""
data = clips.data.DataObject(self._env)
lib.EnvClassSuperclasses(
self._env, self._cl... | python | {
"resource": ""
} |
q18239 | Class.message_handlers | train | def message_handlers(self):
"""Iterate over the message handlers of the class."""
index = lib.EnvGetNextDefmessageHandler(self._env, self._cls, 0)
while index != 0:
yield MessageHandler(self._env, self._cls, index)
index = lib.EnvGetNextDefmessageHandler(self._env, self... | python | {
"resource": ""
} |
q18240 | Class.undefine | train | def undefine(self):
"""Undefine the Class.
Python equivalent of the CLIPS undefclass command.
The object becomes unusable after this method has been called.
"""
if lib.EnvUndefclass(self._env, self._cls) != 1:
raise CLIPSError(self._env)
self._env = None | python | {
"resource": ""
} |
q18241 | FortranReader.include | train | def include(self):
"""
If the next line is an include statement, inserts the contents
of the included file into the pending buffer.
"""
if len(self.pending) == 0 or not self.pending[0].startswith('include '):
return
name = self.pending.pop(0)[8:].strip()[1:-1]... | python | {
"resource": ""
} |
q18242 | GraphData.register | train | def register(self,obj,cls=type(None),hist={}):
"""
Takes a FortranObject and adds it to the appropriate list, if
not already present.
"""
#~ ident = getattr(obj,'ident',obj)
if is_submodule(obj,cls):
if obj not in self.submodules: self.submodules[obj] = Submod... | python | {
"resource": ""
} |
q18243 | GraphData.get_node | train | def get_node(self,obj,cls=type(None),hist={}):
"""
Returns the node corresponding to obj. If does not already exist
then it will create it.
"""
#~ ident = getattr(obj,'ident',obj)
if obj in self.modules and is_module(obj,cls):
return self.modules[obj]
... | python | {
"resource": ""
} |
q18244 | FortranGraph.add_to_graph | train | def add_to_graph(self, nodes, edges, nesting):
"""
Adds nodes and edges to the graph as long as the maximum number
of nodes is not exceeded.
All edges are expected to have a reference to an entry in nodes.
If the list of nodes is not added in the first hop due to graph
si... | python | {
"resource": ""
} |
q18245 | ModuleGraph.add_nodes | train | def add_nodes(self, nodes, nesting=1):
"""
Adds nodes and edges for generating the graph showing the relationship
between modules and submodules listed in nodes.
"""
hopNodes = set() # nodes in this hop
hopEdges = [] # edges in this hop
# get nodes and edges ... | python | {
"resource": ""
} |
q18246 | FileGraph.add_nodes | train | def add_nodes(self, nodes, nesting=1):
"""
Adds edges showing dependencies between source files listed in
the nodes.
"""
hopNodes = set() # nodes in this hop
hopEdges = [] # edges in this hop
# get nodes and edges for this hop
for i, n in zip(range(le... | python | {
"resource": ""
} |
q18247 | CallGraph.add_nodes | train | def add_nodes(self, nodes, nesting=1):
"""
Adds edges indicating the call-tree for the procedures listed in
the nodes.
"""
hopNodes = set() # nodes in this hop
hopEdges = [] # edges in this hop
# get nodes and edges for this hop
for i, n in zip(range(... | python | {
"resource": ""
} |
q18248 | DefaultObjectPolicy.exception | train | def exception(self, url, exception):
'''What to return when there's an exception.'''
return (time.time() + self.ttl, self.factory(url)) | python | {
"resource": ""
} |
q18249 | parse_date | train | def parse_date(string):
'''Return a timestamp for the provided datestring, described by RFC 7231.'''
parsed = email.utils.parsedate_tz(string)
if parsed is None:
raise ValueError("Invalid time.")
parsed = list(parsed)
# Default time zone is GMT/UTC
parsed[9] = 0 if parsed[9] is None else... | python | {
"resource": ""
} |
q18250 | HeaderWithDefaultPolicy.ttl | train | def ttl(self, response):
'''Get the ttl from headers.'''
# If max-age is specified in Cache-Control, use it and ignore any
# Expires header, as per RFC2616 Sec. 13.2.4.
cache_control = response.headers.get('cache-control')
if cache_control is not None:
for directive i... | python | {
"resource": ""
} |
q18251 | ExpiringObject.get | train | def get(self):
'''Get the wrapped object.'''
if (self.obj is None) or (time.time() >= self.expires):
with self.lock:
self.expires, self.obj = self.factory()
if isinstance(self.obj, BaseException):
self.exception = self.obj
e... | python | {
"resource": ""
} |
q18252 | BaseCache.get | train | def get(self, url):
'''Get the entity that corresponds to URL.'''
robots_url = Robots.robots_url(url)
if robots_url not in self.cache:
self.cache[robots_url] = ExpiringObject(partial(self.factory, robots_url))
return self.cache[robots_url].get() | python | {
"resource": ""
} |
q18253 | RobotsCache.allowed | train | def allowed(self, url, agent):
'''Return true if the provided URL is allowed to agent.'''
return self.get(url).allowed(url, agent) | python | {
"resource": ""
} |
q18254 | timer | train | def timer(name, count):
'''Time this block.'''
start = time.time()
try:
yield count
finally:
duration = time.time() - start
print(name)
print('=' * 10)
print('Total: %s' % duration)
print(' Avg: %s' % (duration / count))
print(' Rate: %s' % (count... | python | {
"resource": ""
} |
q18255 | add_command_arguments | train | def add_command_arguments(parser):
"""
Additional command line arguments for the behave management command
"""
parser.add_argument(
'--noinput',
'--no-input',
action='store_const',
const=False,
dest='interactive',
help='Tells Django to NOT prompt the user ... | python | {
"resource": ""
} |
q18256 | add_behave_arguments | train | def add_behave_arguments(parser): # noqa
"""
Additional command line arguments extracted directly from behave
"""
# Option strings that conflict with Django
conflicts = [
'--no-color',
'--version',
'-c',
'-k',
'-v',
'-S',
'--simple',
]
... | python | {
"resource": ""
} |
q18257 | Command.add_arguments | train | def add_arguments(self, parser):
"""
Add behave's and our command line arguments to the command
"""
parser.usage = "%(prog)s [options] [ [DIR|FILE|FILE:LINE] ]+"
parser.description = """\
Run a number of feature tests with behave."""
add_command_arguments(parser)... | python | {
"resource": ""
} |
q18258 | Command.get_behave_args | train | def get_behave_args(self, argv=sys.argv):
"""
Get a list of those command line arguments specified with the
management command that are meant as arguments for running behave.
"""
parser = BehaveArgsHelper().create_parser('manage.py', 'behave')
args, unknown = parser.parse... | python | {
"resource": ""
} |
q18259 | load_registered_fixtures | train | def load_registered_fixtures(context):
"""
Apply fixtures that are registered with the @fixtures decorator.
"""
# -- SELECT STEP REGISTRY:
# HINT: Newer behave versions use runner.step_registry
# to be able to support multiple runners, each with its own step_registry.
runner = context._runne... | python | {
"resource": ""
} |
q18260 | BehaveHooksMixin.patch_context | train | def patch_context(self, context):
"""
Patches the context to add utility functions
Sets up the base_url, and the get_url() utility function.
"""
context.__class__ = PatchedContext
# Simply setting __class__ directly doesn't work
# because behave.runner.Context.__... | python | {
"resource": ""
} |
q18261 | BehaveHooksMixin.setup_fixtures | train | def setup_fixtures(self, context):
"""
Sets up fixtures
"""
if getattr(context, 'fixtures', None):
context.test.fixtures = copy(context.fixtures)
if getattr(context, 'reset_sequences', None):
context.test.reset_sequences = context.reset_sequences
... | python | {
"resource": ""
} |
q18262 | DenonAVR.exec_appcommand_post | train | def exec_appcommand_post(self, attribute_list):
"""
Prepare and execute a HTTP POST call to AppCommand.xml end point.
Returns XML ElementTree on success and None on fail.
"""
# Prepare POST XML body for AppCommand.xml
post_root = ET.Element("tx")
for attribute i... | python | {
"resource": ""
} |
q18263 | DenonAVR.get_status_xml | train | def get_status_xml(self, command, suppress_errors=False):
"""Get status XML via HTTP and return it as XML ElementTree."""
# Get XML structure via HTTP get
res = requests.get("http://{host}:{port}{command}".format(
host=self._host, port=self._receiver_port, command=command),
... | python | {
"resource": ""
} |
q18264 | DenonAVR.send_get_command | train | def send_get_command(self, command):
"""Send command via HTTP get to receiver."""
# Send commands via HTTP get
res = requests.get("http://{host}:{port}{command}".format(
host=self._host, port=self._receiver_port, command=command),
timeout=self.timeout)
... | python | {
"resource": ""
} |
q18265 | DenonAVR.send_post_command | train | def send_post_command(self, command, body):
"""Send command via HTTP post to receiver."""
# Send commands via HTTP post
res = requests.post("http://{host}:{port}{command}".format(
host=self._host, port=self._receiver_port, command=command),
data=body, time... | python | {
"resource": ""
} |
q18266 | DenonAVR.create_zones | train | def create_zones(self, add_zones):
"""Create instances of additional zones for the receiver."""
for zone, zname in add_zones.items():
# Name either set explicitly or name of Main Zone with suffix
zonename = "{} {}".format(self._name, zone) if (
zname is None) else... | python | {
"resource": ""
} |
q18267 | DenonAVR._update_input_func_list | train | def _update_input_func_list(self):
"""
Update sources list from receiver.
Internal method which updates sources list of receiver after getting
sources and potential renaming information from receiver.
"""
# Get all sources and renaming information from receiver
#... | python | {
"resource": ""
} |
q18268 | DenonAVR._get_receiver_name | train | def _get_receiver_name(self):
"""Get name of receiver from web interface if not set."""
# If name is not set yet, get it from Main Zone URL
if self._name is None and self._urls.mainzone is not None:
name_tag = {"FriendlyName": None}
try:
root = self.get_st... | python | {
"resource": ""
} |
q18269 | DenonAVR._get_zone_name | train | def _get_zone_name(self):
"""Get receivers zone name if not set yet."""
if self._name is None:
# Collect tags for AppCommand.xml call
tags = ["GetZoneName"]
# Execute call
root = self.exec_appcommand_post(tags)
# Check result
if roo... | python | {
"resource": ""
} |
q18270 | DenonAVR._get_receiver_sources | train | def _get_receiver_sources(self):
"""
Get sources list from receiver.
Internal method which queries device via HTTP to get the receiver's
input sources.
This method also determines the type of the receiver
(avr, avr-x, avr-x-2016).
"""
# Test if receiver i... | python | {
"resource": ""
} |
q18271 | DenonAVR._get_status_from_xml_tags | train | def _get_status_from_xml_tags(self, root, relevant_tags):
"""
Get relevant status tags from XML structure with this internal method.
Status is saved to internal attributes.
Return dictionary of tags not found in XML.
"""
for child in root:
if child.tag not in... | python | {
"resource": ""
} |
q18272 | DenonAVR.set_input_func | train | def set_input_func(self, input_func):
"""
Set input_func of device.
Valid values depend on the device and should be taken from
"input_func_list".
Return "True" on success and "False" on fail.
"""
# For selection of sources other names then at receiving sources
... | python | {
"resource": ""
} |
q18273 | DenonAVR._set_all_zone_stereo | train | def _set_all_zone_stereo(self, zst_on):
"""
Set All Zone Stereo option on the device.
Calls command to activate/deactivate the mode
Return "True" when successfully sent.
"""
command_url = self._urls.command_set_all_zone_stereo
if zst_on:
command_url +... | python | {
"resource": ""
} |
q18274 | DenonAVR.set_sound_mode | train | def set_sound_mode(self, sound_mode):
"""
Set sound_mode of device.
Valid values depend on the device and should be taken from
"sound_mode_list".
Return "True" on success and "False" on fail.
"""
if sound_mode == ALL_ZONE_STEREO:
if self._set_all_zone... | python | {
"resource": ""
} |
q18275 | DenonAVR.set_sound_mode_dict | train | def set_sound_mode_dict(self, sound_mode_dict):
"""Set the matching dictionary used to match the raw sound mode."""
error_msg = ("Syntax of sound mode dictionary not valid, "
"use: OrderedDict([('COMMAND', ['VALUE1','VALUE2'])])")
if isinstance(sound_mode_dict, dict):
... | python | {
"resource": ""
} |
q18276 | DenonAVR.construct_sm_match_dict | train | def construct_sm_match_dict(self):
"""
Construct the sm_match_dict.
Reverse the key value structure. The sm_match_dict is bigger,
but allows for direct matching using a dictionary key access.
The sound_mode_dict is uses externally to set this dictionary
because that has ... | python | {
"resource": ""
} |
q18277 | DenonAVR.match_sound_mode | train | def match_sound_mode(self, sound_mode_raw):
"""Match the raw_sound_mode to its corresponding sound_mode."""
try:
sound_mode = self._sm_match_dict[sound_mode_raw.upper()]
return sound_mode
except KeyError:
smr_up = sound_mode_raw.upper()
self._sound... | python | {
"resource": ""
} |
q18278 | DenonAVR.toggle_play_pause | train | def toggle_play_pause(self):
"""Toggle play pause media player."""
# Use Play/Pause button only for sources which support NETAUDIO
if (self._state == STATE_PLAYING and
self._input_func in self._netaudio_func_list):
return self._pause()
elif self._input_func in... | python | {
"resource": ""
} |
q18279 | DenonAVR._play | train | def _play(self):
"""Send play command to receiver command via HTTP post."""
# Use pause command only for sources which support NETAUDIO
if self._input_func in self._netaudio_func_list:
body = {"cmd0": "PutNetAudioCommand/CurEnter",
"cmd1": "aspMainZone_WebUpdateSt... | python | {
"resource": ""
} |
q18280 | DenonAVR._pause | train | def _pause(self):
"""Send pause command to receiver command via HTTP post."""
# Use pause command only for sources which support NETAUDIO
if self._input_func in self._netaudio_func_list:
body = {"cmd0": "PutNetAudioCommand/CurEnter",
"cmd1": "aspMainZone_WebUpdate... | python | {
"resource": ""
} |
q18281 | DenonAVR.previous_track | train | def previous_track(self):
"""Send previous track command to receiver command via HTTP post."""
# Use previous track button only for sources which support NETAUDIO
if self._input_func in self._netaudio_func_list:
body = {"cmd0": "PutNetAudioCommand/CurUp",
"cmd1": ... | python | {
"resource": ""
} |
q18282 | DenonAVR.volume_up | train | def volume_up(self):
"""Volume up receiver via HTTP get command."""
try:
return bool(self.send_get_command(self._urls.command_volume_up))
except requests.exceptions.RequestException:
_LOGGER.error("Connection error: volume up command not sent.")
return False | python | {
"resource": ""
} |
q18283 | DenonAVR.volume_down | train | def volume_down(self):
"""Volume down receiver via HTTP get command."""
try:
return bool(self.send_get_command(self._urls.command_volume_down))
except requests.exceptions.RequestException:
_LOGGER.error("Connection error: volume down command not sent.")
return... | python | {
"resource": ""
} |
q18284 | DenonAVR.set_volume | train | def set_volume(self, volume):
"""
Set receiver volume via HTTP get command.
Volume is send in a format like -50.0.
Minimum is -80.0, maximum at 18.0
"""
if volume < -80 or volume > 18:
raise ValueError("Invalid volume")
try:
return bool(s... | python | {
"resource": ""
} |
q18285 | DenonAVR.mute | train | def mute(self, mute):
"""Mute receiver via HTTP get command."""
try:
if mute:
if self.send_get_command(self._urls.command_mute_on):
self._mute = STATE_ON
return True
else:
return False
els... | python | {
"resource": ""
} |
q18286 | DenonAVRZones.sound_mode | train | def sound_mode(self):
"""Return the matched current sound mode as a string."""
sound_mode_matched = self._parent_avr.match_sound_mode(
self._parent_avr.sound_mode_raw)
return sound_mode_matched | python | {
"resource": ""
} |
q18287 | identify_denonavr_receivers | train | def identify_denonavr_receivers():
"""
Identify DenonAVR using SSDP and SCPD queries.
Returns a list of dictionaries which includes all discovered Denon AVR
devices with keys "host", "modelName", "friendlyName", "presentationURL".
"""
# Sending SSDP broadcast message to get devices
devices ... | python | {
"resource": ""
} |
q18288 | send_ssdp_broadcast | train | def send_ssdp_broadcast():
"""
Send SSDP broadcast message to discover UPnP devices.
Returns a list of dictionaries with "address" (IP, PORT) and "URL"
of SCPD XML for all discovered devices.
"""
# Send up to three different broadcast messages
for i, ssdp_query in enumerate(SSDP_QUERIES):
... | python | {
"resource": ""
} |
q18289 | evaluate_scpd_xml | train | def evaluate_scpd_xml(url):
"""
Get and evaluate SCPD XML to identified URLs.
Returns dictionary with keys "host", "modelName", "friendlyName" and
"presentationURL" if a Denon AVR device was found and "False" if not.
"""
# Get SCPD XML via HTTP GET
try:
res = requests.get(url, timeo... | python | {
"resource": ""
} |
q18290 | init_all_receivers | train | def init_all_receivers():
"""
Initialize all discovered Denon AVR receivers in LAN zone.
Returns a list of created Denon AVR instances.
By default SSDP broadcasts are sent up to 3 times with a 2 seconds timeout.
"""
receivers = discover()
init_receivers = []
for receiver in receivers:
... | python | {
"resource": ""
} |
q18291 | parse_auto_sub | train | def parse_auto_sub(text):
'''
Parses webvtt and returns timestamps for words and lines
Tested on automatically generated subtitles from YouTube
'''
pat = r'<(\d\d:\d\d:\d\d(\.\d+)?)>'
out = []
lines = []
data = text.split('\n')
data = [d for d in data if re.search(r'\d\d:\d\d:\d\d'... | python | {
"resource": ""
} |
q18292 | Timecode.tc_to_frames | train | def tc_to_frames(self, timecode):
"""Converts the given timecode to frames
"""
hours, minutes, seconds, frames = map(int, timecode.split(':'))
ffps = float(self._framerate)
if self.drop_frame:
# Number of drop frames is 6% of framerate rounded to nearest
... | python | {
"resource": ""
} |
q18293 | Timecode.frames_to_tc | train | def frames_to_tc(self, frames):
"""Converts frames back to timecode
:returns str: the string representation of the current time code
"""
if frames == 0:
return 0, 0, 0, 0
ffps = float(self._framerate)
if self.drop_frame:
# Number of frames to d... | python | {
"resource": ""
} |
q18294 | make_edl | train | def make_edl(timestamps, name):
'''Converts an array of ordered timestamps into an EDL string'''
fpses = {}
out = "TITLE: {}\nFCM: NON-DROP FRAME\n\n".format(name)
rec_in = 0
for index, timestamp in enumerate(timestamps):
if timestamp['file'] not in fpses:
fpses[timestamp['fi... | python | {
"resource": ""
} |
q18295 | convert_timespan | train | def convert_timespan(timespan):
"""Convert an srt timespan into a start and end timestamp."""
start, end = timespan.split('-->')
start = convert_timestamp(start)
end = convert_timestamp(end)
return start, end | python | {
"resource": ""
} |
q18296 | convert_timestamp | train | def convert_timestamp(timestamp):
"""Convert an srt timestamp into seconds."""
timestamp = timestamp.strip()
chunk, millis = timestamp.split(',')
hours, minutes, seconds = chunk.split(':')
hours = int(hours)
minutes = int(minutes)
seconds = int(seconds)
seconds = seconds + hours * 60 * 6... | python | {
"resource": ""
} |
q18297 | clean_srt | train | def clean_srt(srt):
"""Remove damaging line breaks and numbers from srt files and return a
dictionary.
"""
with open(srt, 'r') as f:
text = f.read()
text = re.sub(r'^\d+[\n\r]', '', text, flags=re.MULTILINE)
lines = text.splitlines()
output = OrderedDict()
key = ''
for line ... | python | {
"resource": ""
} |
q18298 | cleanup_log_files | train | def cleanup_log_files(outputfile):
"""Search for and remove temp log files found in the output directory."""
d = os.path.dirname(os.path.abspath(outputfile))
logfiles = [f for f in os.listdir(d) if f.endswith('ogg.log')]
for f in logfiles:
os.remove(f) | python | {
"resource": ""
} |
q18299 | demo_supercut | train | def demo_supercut(composition, padding):
"""Print out timespans to be cut followed by the line number in the srt."""
for i, c in enumerate(composition):
line = c['line']
start = c['start']
end = c['end']
if i > 0 and composition[i - 1]['file'] == c['file'] and start < composition... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.