code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
self.send(command + '\r')
return self.expect_prompt(consume) | def execute(self, command, consume=True) | Sends the given data to the remote host (with a newline appended)
and waits for a prompt in the response. The prompt attempts to use
a sane default that works with many devices running Unix, IOS,
IOS-XR, or Junos and others. If that fails, a custom prompt may
also be defined using the se... | 6.775596 | 7.865004 | 0.861487 |
while True:
try:
result = self._waitfor(prompt)
except DriverReplacedException:
continue # retry
return result | def waitfor(self, prompt) | Monitors the data received from the remote host and waits until
the response matches the given prompt.
Once a match has been found, the buffer containing incoming data
is NOT changed. In other words, consecutive calls to this function
will always work, e.g.::
conn.waitfor('m... | 8.165363 | 12.607833 | 0.647642 |
while True:
try:
result = self._expect(prompt)
except DriverReplacedException:
continue # retry
return result | def expect(self, prompt) | Like waitfor(), but also removes the matched string from the buffer
containing the incoming data. In other words, the following may not
alway complete::
conn.expect('myprompt>')
conn.expect('myprompt>') # timeout
Returns the index of the regular expression that matched.... | 9.439586 | 12.758564 | 0.739863 |
if consume:
result = self.expect(self.get_prompt())
else:
self._dbg(1, "DO NOT CONSUME PROMPT!")
result = self.waitfor(self.get_prompt())
# We skip the first line because it contains the echo of the command
# sent.
self._dbg(5, "Check... | def expect_prompt(self, consume=True) | Monitors the data received from the remote host and waits for a
prompt in the response. The prompt attempts to use
a sane default that works with many devices running Unix, IOS,
IOS-XR, or Junos and others. If that fails, a custom prompt may
also be defined using the set_prompt() method.... | 4.981421 | 4.74966 | 1.048795 |
self.buffer.add_monitor(pattern, partial(callback, self), limit) | def add_monitor(self, pattern, callback, limit=80) | Calls the given function whenever the given pattern matches the
incoming data.
.. HINT::
If you want to catch all incoming data regardless of a
pattern, use the Protocol.data_received_event event instead.
Arguments passed to the callback are the protocol instance, the
... | 7.502758 | 11.239036 | 0.667562 |
def _wrapped(job, *args, **kwargs):
job_id = id(job)
to_parent = job.data['pipe']
host = job.data['host']
# Create a protocol adapter.
mkaccount = partial(_account_factory, to_parent, host)
pargs = {'account_factory': mkaccount,
'stdout': ... | def _prepare_connection(func) | A decorator that unpacks the host and connection from the job argument
and passes them as separate arguments to the wrapped function. | 4.181403 | 4.110487 | 1.017252 |
child = _PipeHandler(self.account_manager)
self.pipe_handlers[id(child)] = child
child.start()
return child.to_parent | def _create_pipe(self) | Creates a new pipe and returns the child end of the connection.
To request an account from the pipe, use::
pipe = queue._create_pipe()
# Let the account manager choose an account.
pipe.send(('acquire-account-for-host', host))
account = pipe.recv()
..... | 9.860322 | 6.454923 | 1.527566 |
self._dbg(2, 'Waiting for the queue to finish.')
self.workqueue.wait_until_done()
for child in list(self.pipe_handlers.values()):
child.join()
self._del_status_bar()
self._print_status_bar()
gc.collect() | def join(self) | Waits until all jobs are completed. | 9.572633 | 7.923719 | 1.208098 |
if not force:
self.join()
self._dbg(2, 'Shutting down queue...')
self.workqueue.shutdown(True)
self._dbg(2, 'Queue shut down.')
self._del_status_bar() | def shutdown(self, force=False) | Stop executing any further jobs. If the force argument is True,
the function does not wait until any queued jobs are completed but
stops immediately.
After emptying the queue it is restarted, so you may still call run()
after using this method.
:type force: bool
:param... | 7.842403 | 8.954217 | 0.875833 |
try:
if not force:
self.join()
finally:
self._dbg(2, 'Destroying queue...')
self.workqueue.destroy()
self.account_manager.reset()
self.completed = 0
self.total = 0
self.failed = 0
sel... | def destroy(self, force=False) | Like shutdown(), but also removes all accounts, hosts, etc., and
does not restart the queue. In other words, the queue can no longer
be used after calling this method.
:type force: bool
:param force: Whether to wait until all jobs were processed. | 5.747964 | 5.079363 | 1.131631 |
self._dbg(2, 'Resetting queue...')
self.account_manager.reset()
self.workqueue.shutdown(True)
self.completed = 0
self.total = 0
self.failed = 0
self.status_bar_length = 0
self._dbg(2, 'Queue reset.')
self._del_status_bar() | def reset(self) | Remove all accounts, hosts, etc. | 6.449563 | 5.710743 | 1.129374 |
return self._run(hosts, function, self.workqueue.enqueue, attempts) | def run(self, hosts, function, attempts=1) | Add the given function to a queue, and call it once for each host
according to the threading options.
Use decorators.bind() if you also want to pass additional
arguments to the callback function.
Returns an object that represents the queued task, and that may be
passed to is_com... | 9.894024 | 15.474791 | 0.639364 |
return self._run(hosts,
function,
self.workqueue.enqueue_or_ignore,
attempts) | def run_or_ignore(self, hosts, function, attempts=1) | Like run(), but only appends hosts that are not already in the
queue.
:type hosts: string|list(string)|Host|list(Host)
:param hosts: A hostname or Host object, or a list of them.
:type function: function
:param function: The function to execute.
:type attempts: int
... | 7.514676 | 11.050659 | 0.680021 |
return self._run(hosts,
function,
self.workqueue.priority_enqueue,
False,
attempts) | def priority_run(self, hosts, function, attempts=1) | Like run(), but adds the task to the front of the queue.
:type hosts: string|list(string)|Host|list(Host)
:param hosts: A hostname or Host object, or a list of them.
:type function: function
:param function: The function to execute.
:type attempts: int
:param attempts... | 8.002048 | 12.264682 | 0.652446 |
return self._run(hosts,
function,
self.workqueue.priority_enqueue_or_raise,
False,
attempts) | def priority_run_or_raise(self, hosts, function, attempts=1) | Like priority_run(), but if a host is already in the queue, the
existing host is moved to the top of the queue instead of enqueuing
the new one.
:type hosts: string|list(string)|Host|list(Host)
:param hosts: A hostname or Host object, or a list of them.
:type function: functio... | 7.391005 | 9.285846 | 0.795943 |
return self._run(hosts,
function,
self.workqueue.priority_enqueue,
True,
attempts) | def force_run(self, hosts, function, attempts=1) | Like priority_run(), but starts the task immediately even if that
max_threads is exceeded.
:type hosts: string|list(string)|Host|list(Host)
:param hosts: A hostname or Host object, or a list of them.
:type function: function
:param function: The function to execute.
:t... | 10.987137 | 12.598451 | 0.872102 |
self.total += 1
task = Task(self.workqueue)
job_id = self.workqueue.enqueue(function, name, attempts)
if job_id is not None:
task.add_job_id(job_id)
self._dbg(2, 'Function enqueued.')
return task | def enqueue(self, function, name=None, attempts=1) | Places the given function in the queue and calls it as soon
as a thread is available. To pass additional arguments to the
callback, use Python's functools.partial().
:type function: function
:param function: The function to execute.
:type name: string
:param name: A na... | 5.237683 | 5.69069 | 0.920395 |
try:
index = int(index[0])
except IndexError:
raise ValueError('index variable is required')
except ValueError:
raise ValueError('index is not an integer')
try:
return [source[index]]
except IndexError:
raise ValueError('no such item in the list') | def get(scope, source, index) | Returns a copy of the list item with the given index.
It is an error if an item with teh given index does not exist.
:type source: string
:param source: A list of strings.
:type index: string
:param index: A list of strings.
:rtype: string
:return: The cleaned up list of strings. | 3.499927 | 3.670142 | 0.953622 |
process = Popen(command[0],
shell=True,
stdin=PIPE,
stdout=PIPE,
stderr=STDOUT,
close_fds=True)
scope.define(__response__=process.stdout.read())
return True | def execute(scope, command) | Executes the given command locally.
:type command: string
:param command: A shell command. | 4.415292 | 5.5237 | 0.799336 |
if value is None:
return
if key in self.info:
old_confidence, old_value = self.info.get(key)
if old_confidence >= confidence:
return
self.info[key] = (confidence, value) | def set(self, key, value, confidence=100) | Defines the given value with the given confidence, unless the same
value is already defined with a higher confidence level. | 2.641137 | 2.420066 | 1.091349 |
for item in regex_list:
if hasattr(item, '__call__'):
self.set(key, *item(string))
else:
regex, value, confidence = item
if regex.search(string):
self.set(key, value, confidence) | def set_from_match(self, key, regex_list, string) | Given a list of functions or three-tuples (regex, value, confidence),
this function walks through them and checks whether any of the
items in the list matches the given string.
If the list item is a function, it must have the following
signature::
func(string) : (string, int... | 3.149477 | 2.537163 | 1.241338 |
if key not in self.info:
return None
conf, value = self.info.get(key)
if conf >= confidence:
return value
return None | def get(self, key, confidence=0) | Returns the info with the given key, if it has at least the given
confidence. Returns None otherwise. | 3.58077 | 2.85045 | 1.256212 |
def decorated(*inner_args, **inner_kwargs):
kwargs.update(inner_kwargs)
return function(*(inner_args + args), **kwargs)
copy_labels(function, decorated)
return decorated | def bind(function, *args, **kwargs) | Wraps the given function such that when it is called, the given arguments
are passed in addition to the connection argument.
:type function: function
:param function: The function that's ought to be wrapped.
:type args: list
:param args: Passed on to the called function.
:type kwargs: dict
... | 3.723978 | 5.143423 | 0.724027 |
def decorated(job, host, conn, *args, **kwargs):
os = conn.guess_os()
func = map.get(os)
if func is None:
raise Exception('No handler for %s found.' % os)
return func(job, host, conn, *args, **kwargs)
return decorated | def os_function_mapper(map) | When called with an open connection, this function uses the
conn.guess_os() function to guess the operating system
of the connected host.
It then uses the given map to look up a function name that corresponds
to the operating system, and calls it. Example::
def ios_xr(job, host, conn):
... | 3.665 | 2.548639 | 1.438022 |
def decorator(function):
def decorated(job, host, conn, *args, **kwargs):
failed = 0
while True:
try:
if only_authenticate:
conn.authenticate(flush=flush)
else:
conn.login(flu... | def _decorate(flush=True, attempts=1, only_authenticate=False) | Wraps the given function such that conn.login() or conn.authenticate() is
executed.
Doing the real work for autologin and autoauthenticate to minimize code
duplication.
:type flush: bool
:param flush: Whether to flush the last prompt from the buffer.
:type attempts: int
:param attempts: T... | 3.068224 | 3.064545 | 1.001201 |
filenames = glob.glob('*[0-9][0-9][0-9]*{}'.format(extension))
return [ProblemFile(file) for file in filenames] | def problem_glob(extension='.py') | Returns ProblemFile objects for all valid problem files | 4.343687 | 3.432436 | 1.265482 |
if timespan >= 60.0:
# Format time greater than one minute in a human-readable format
# Idea from http://snipplr.com/view/5713/
def _format_long_time(time):
suffixes = ('d', 'h', 'm', 's')
lengths = (24*60*60, 60*60, 60, 1)
for suffix, length in zip... | def human_time(timespan, precision=3) | Formats the timespan in a human readable format | 2.603289 | 2.61454 | 0.995697 |
try:
cpu_usr = end[0] - start[0]
cpu_sys = end[1] - start[1]
except TypeError:
# `clock()[1] == None` so subtraction results in a TypeError
return 'Time elapsed: {}'.format(human_time(cpu_usr))
else:
times = (human_time(x) for x in (cpu_usr, cpu_sys, cpu_usr + ... | def format_time(start, end) | Returns string with relevant time information formatted properly | 5.242653 | 5.214347 | 1.005428 |
return BASE_NAME.format(prefix, self.num, suffix, extension) | def filename(self, prefix='', suffix='', extension='.py') | Returns filename padded with leading zeros | 10.927979 | 10.288557 | 1.062149 |
file_glob = glob.glob(BASE_NAME.format('*', self.num, '*', '.*'))
# Sort globbed files by tuple (filename, extension)
return sorted(file_glob, key=lambda f: os.path.splitext(f)) | def glob(self) | Returns a sorted glob of files belonging to a given problem | 8.391771 | 7.3434 | 1.142764 |
with open(os.path.join(EULER_DATA, 'resources.json')) as data_file:
data = json.load(data_file)
problem_num = str(self.num)
if problem_num in data:
files = data[problem_num]
# Ensure a list of files is returned
return files if isinstanc... | def resources(self) | Returns a list of resources related to the problem (or None) | 4.069951 | 3.403391 | 1.195852 |
if not os.path.isdir('resources'):
os.mkdir('resources')
resource_dir = os.path.join(os.getcwd(), 'resources', '')
copied_resources = []
for resource in self.resources:
src = os.path.join(EULER_DATA, 'resources', resource)
if os.path.isfile(... | def copy_resources(self) | Copies the relevant resources to a resources subdirectory | 2.80626 | 2.657732 | 1.055885 |
num = self.num
solution_file = os.path.join(EULER_DATA, 'solutions.txt')
solution_line = linecache.getline(solution_file, num)
try:
answer = solution_line.split('. ')[1].strip()
except IndexError:
answer = None
if answer:
re... | def solution(self) | Returns the answer to a given problem | 4.559518 | 4.305327 | 1.059041 |
def _problem_iter(problem_num):
problem_file = os.path.join(EULER_DATA, 'problems.txt')
with open(problem_file) as f:
is_problem = False
last_line = ''
for line in f:
if line.strip() == 'Problem %i' % problem_... | def text(self) | Parses problems.txt and returns problem text | 3.800548 | 3.511314 | 1.082372 |
# Define solution before echoing in case solution does not exist
solution = click.style(Problem(num).solution, bold=True)
click.confirm("View answer to problem %i?" % num, abort=True)
click.echo("The answer to problem {} is {}.".format(num, solution)) | def cheat(num) | View the answer to a problem. | 9.456609 | 7.849786 | 1.204696 |
p = Problem(num)
problem_text = p.text
msg = "Generate file for problem %i?" % num
click.confirm(msg, default=prompt_default, abort=True)
# Allow skipped problem files to be recreated
if p.glob:
filename = str(p.file)
msg = '"{}" already exists. Overwrite?'.format(filenam... | def generate(num, prompt_default=True) | Generates Python file for a problem. | 4.349226 | 4.067303 | 1.069315 |
# Define problem_text before echoing in case problem does not exist
problem_text = Problem(num).text
click.secho("Project Euler Problem %i" % num, bold=True)
click.echo(problem_text) | def preview(num) | Prints the text of a problem. | 10.785984 | 9.273178 | 1.163138 |
click.echo("Current problem is problem %i." % num)
generate(num + 1, prompt_default=False)
Problem(num).file.change_suffix('-skipped') | def skip(num) | Generates Python file for the next problem. | 25.898985 | 18.872099 | 1.372343 |
p = Problem(num)
filename = filename or p.filename()
if not os.path.isfile(filename):
# Attempt to verify the first problem file matched by glob
if p.glob:
filename = str(p.file)
else:
click.secho('No file found for problem %i.' % p.num, fg='red')
... | def verify(num, filename=None, exit=True) | Verifies the solution to a problem. | 4.279765 | 4.159884 | 1.028818 |
# Define various problem statuses
keys = ('correct', 'incorrect', 'error', 'skipped', 'missing')
symbols = ('C', 'I', 'E', 'S', '.')
colours = ('green', 'red', 'yellow', 'cyan', 'white')
status = OrderedDict(
(key, click.style(symbol, fg=colour, bold=True))
for key, symbol, co... | def verify_all(num) | Verifies all problem files in the current directory and
prints an overview of the status of each problem. | 4.330664 | 4.153478 | 1.04266 |
euler_functions = cheat, generate, preview, skip, verify, verify_all
# Reverse functions to print help page options in alphabetical order
for option in reversed(euler_functions):
name, docstring = option.__name__, option.__doc__
kwargs = {'flag_value': option, 'help': docstring}
... | def euler_options(fn) | Decorator to link CLI options with their appropriate functions | 7.534934 | 7.01301 | 1.074422 |
# No problem given (or given option ignores the problem argument)
if problem == 0 or option in {skip, verify_all}:
# Determine the highest problem number in the current directory
files = problem_glob()
problem = max(file.num for file in files) if files else 0
# No Project E... | def main(option, problem) | Python-based Project Euler command line tool. | 8.068006 | 8.108301 | 0.99503 |
if args:
LOG.debug("args: %s" % str(args))
if kwargs:
LOG.debug("kwargs: %s" % str(kwargs))
try:
self._server.start()
self._server.proxyInit()
return True
except Exception as err:
LOG.critical("Failed to sta... | def start(self, *args, **kwargs) | Start the server thread if it wasn't created with autostart = True. | 3.129369 | 3.102875 | 1.008539 |
if args:
LOG.debug("args: %s" % str(args))
if kwargs:
LOG.debug("kwargs: %s" % str(kwargs))
try:
self._server.stop()
self._server = None
# Device-storage clear
self.devices.clear()
self.devices_all.clea... | def stop(self, *args, **kwargs) | Stop the server thread. | 3.643628 | 3.515683 | 1.036393 |
if self._server is not None:
return self._server.getSystemVariable(remote, name) | def getSystemVariable(self, remote, name) | Get single system variable from CCU / Homegear | 4.138834 | 4.165806 | 0.993525 |
if self._server is not None:
return self._server.deleteSystemVariable(remote, name) | def deleteSystemVariable(self, remote, name) | Delete a system variable from CCU / Homegear | 3.972191 | 4.452857 | 0.892054 |
if self._server is not None:
return self._server.setSystemVariable(remote, name, value) | def setSystemVariable(self, remote, name, value) | Set a system variable on CCU / Homegear | 3.509069 | 3.725778 | 0.941835 |
if self._server is not None:
return self._server.setInstallMode(remote, on, t, mode, address) | def setInstallMode(self, remote, on=True, t=60, mode=1, address=None) | Activate or deactivate installmode on CCU / Homegear | 3.139735 | 3.291096 | 0.954009 |
if self._server is not None:
return self._server.getAllMetadata(remote, address) | def getAllMetadata(self, remote, address) | Get all metadata of device | 4.428295 | 4.481161 | 0.988203 |
if self._server is not None:
# pylint: disable=E1121
return self._server.getAllMetadata(remote, address, key) | def getMetadata(self, remote, address, key) | Get metadata of device | 5.077655 | 4.935849 | 1.02873 |
if self._server is not None:
# pylint: disable=E1121
return self._server.getAllMetadata(remote, address, key, value) | def setMetadata(self, remote, address, key, value) | Set metadata of device | 5.166449 | 5.419097 | 0.953378 |
if self._server is not None:
# pylint: disable=E1121
return self._server.deleteMetadata(remote, address, key) | def deleteMetadata(self, remote, address, key) | Delete metadata of device | 3.974434 | 4.12992 | 0.962351 |
if self._server is not None:
return self._server.putParamset(remote, address, paramset, value) | def putParamset(self, remote, address, paramset, value) | Set paramsets manually | 3.017649 | 3.067502 | 0.983748 |
# Get the color from homematic. In general this is just the hue parameter.
hm_color = self.getCachedOrUpdatedValue("COLOR", channel=self._color_channel)
if hm_color >= 200:
# 200 is a special case (white), so we have a saturation of 0.
# Larger values are undefi... | def get_hs_color(self) | Return the color of the light as HSV color without the "value" component for the brightness.
Returns (hue, saturation) tuple with values in range of 0-1, representing the H and S component of the
HSV color system. | 11.261121 | 9.967656 | 1.129766 |
self.turn_off_effect()
if saturation < 0.1: # Special case (white)
hm_color = 200
else:
hm_color = int(round(max(min(hue, 1), 0) * 199))
self.setValue(key="COLOR", channel=self._color_channel, value=hm_color) | def set_hs_color(self, hue: float, saturation: float) | Set a fixed color and also turn off effects in order to see the color.
:param hue: Hue component (range 0-1)
:param saturation: Saturation component (range 0-1). Yields white for values near 0, other values are
interpreted as 100% saturation.
The input values are the components of ... | 6.699022 | 6.518687 | 1.027664 |
effect_value = self.getCachedOrUpdatedValue("PROGRAM", channel=self._effect_channel)
try:
return self._light_effect_list[effect_value]
except IndexError:
LOG.error("Unexpected color effect returned by CCU")
return "Unknown" | def get_effect(self) -> str | Return the current color change program of the light. | 14.938404 | 10.391086 | 1.437617 |
try:
effect_index = self._light_effect_list.index(effect_name)
except ValueError:
LOG.error("Trying to set unknown light effect")
return False
return self.setValue(key="PROGRAM", channel=self._effect_channel, value=effect_index) | def set_effect(self, effect_name: str) | Sets the color change program of the light. | 6.481349 | 5.260895 | 1.231986 |
credentials = ''
if username is None:
return credentials
if username is not None:
if ':' in username:
return credentials
credentials += username
if credentials and password is not None:
credentials += ":%s" % password
return "%s@" % credentials | def make_http_credentials(username=None, password=None) | Build auth part for api_url. | 3.958515 | 3.707673 | 1.067655 |
credentials = make_http_credentials(username, password)
scheme = 'http'
if not path:
path = ''
if path and not path.startswith('/'):
path = "/%s" % path
if ssl:
scheme += 's'
return "%s://%s%s:%i%s" % (scheme, credentials, host, port, path) | def build_api_url(host=REMOTES['default']['ip'],
port=REMOTES['default']['port'],
path=REMOTES['default']['path'],
username=None,
password=None,
ssl=False) | Build API URL from components. | 3.044144 | 3.157381 | 0.964136 |
global WORKING
WORKING = True
remote = interface_id.split('-')[-1]
LOG.debug(
"RPCFunctions.createDeviceObjects: iterating interface_id = %s" % (remote, ))
# First create parent object
for dev in self._devices_raw[remote]:
if not dev['PARE... | def createDeviceObjects(self, interface_id) | Transform the raw device descriptions into instances of devicetypes.generic.HMDevice or availabe subclass. | 2.961842 | 2.898009 | 1.022026 |
LOG.debug("RPCFunctions.error: interface_id = %s, errorcode = %i, message = %s" % (
interface_id, int(errorcode), str(msg)))
if self.systemcallback:
self.systemcallback('error', interface_id, errorcode, msg)
return True | def error(self, interface_id, errorcode, msg) | When some error occurs the CCU / Homegear will send it's error message here | 4.288979 | 4.398615 | 0.975075 |
LOG.debug("RPCFunctions.saveDevices: devicefile: %s, _devices_raw: %s" % (
self.devicefile, str(self._devices_raw[remote])))
if self.devicefile:
try:
with open(self.devicefile, 'w') as df:
df.write(json.dumps(self._devices_raw[remote])... | def saveDevices(self, remote) | We save known devices into a json-file so we don't have to work through the whole list of devices the CCU / Homegear presents us | 3.180217 | 3.168874 | 1.003579 |
LOG.debug("RPCFunctions.event: interface_id = %s, address = %s, value_key = %s, value = %s" % (
interface_id, address, value_key.upper(), str(value)))
self.devices_all[interface_id.split(
'-')[-1]][address].event(interface_id, value_key.upper(), value)
if self.ev... | def event(self, interface_id, address, value_key, value) | If a device emits some sort event, we will handle it here. | 3.266316 | 3.10838 | 1.05081 |
LOG.debug("RPCFunctions.listDevices: interface_id = %s, _devices_raw = %s" % (
interface_id, str(self._devices_raw)))
remote = interface_id.split('-')[-1]
if remote not in self._devices_raw:
self._devices_raw[remote] = []
if self.systemcallback:
... | def listDevices(self, interface_id) | The CCU / Homegear asks for devices known to our XML-RPC server. We respond to that request using this method. | 3.952434 | 3.937009 | 1.003918 |
LOG.debug("RPCFunctions.newDevices: interface_id = %s, dev_descriptions = %s" % (
interface_id, str(dev_descriptions)))
remote = interface_id.split('-')[-1]
if remote not in self._devices_raw:
self._devices_raw[remote] = []
if remote not in self._devices_... | def newDevices(self, interface_id, dev_descriptions) | The CCU / Homegear informs us about newly added devices. We react on that and add those devices as well. | 2.93447 | 2.935207 | 0.999749 |
LOG.debug("RPCFunctions.deleteDevices: interface_id = %s, addresses = %s" % (
interface_id, str(addresses)))
# TODO: remove known device objects as well
remote = interface_id.split('-')[-1]
self._devices_raw[remote] = [device for device in self._devices_raw[
... | def deleteDevices(self, interface_id, addresses) | The CCU / Homegear informs us about removed devices. We react on that and remove those devices as well. | 5.472089 | 5.320801 | 1.028433 |
with self.lock:
parent = xmlrpc.client.ServerProxy
# pylint: disable=E1101
return parent._ServerProxy__request(self, *args, **kwargs) | def __request(self, *args, **kwargs) | Call method on server side | 5.473078 | 5.087612 | 1.075766 |
# Call init() with local XML RPC config and interface_id (the name of
# the receiver) to receive events. XML RPC server has to be running.
for interface_id, proxy in self.proxies.items():
if proxy._skipinit:
continue
if proxy._callbackip and proxy... | def proxyInit(self) | To receive events the proxy has to tell the CCU / Homegear where to send the events. For that we call the init-method. | 4.678587 | 4.490756 | 1.041826 |
stopped = []
for interface_id, proxy in self.proxies.items():
if interface_id in self.failed_inits:
LOG.warning("ServerThread.stop: Not performing de-init for %s" % interface_id)
continue
if proxy._callbackip and proxy._callbackport:
... | def stop(self) | To stop the server we de-init from the CCU / Homegear, then shut down our XML-RPC server. | 3.755166 | 3.48266 | 1.078247 |
if data['type'] == 'LOGIC':
return data['name'], data['value'] == 'true'
elif data['type'] == 'NUMBER':
return data['name'], float(data['value'])
elif data['type'] == 'LIST':
return data['name'], int(data['value'])
else:
return dat... | def parseCCUSysVar(self, data) | Helper to parse type of system variables of CCU | 2.365262 | 2.35002 | 1.006486 |
session = False
try:
params = {"username": self.remotes[remote][
'username'], "password": self.remotes[remote]['password']}
response = self._rpcfunctions.jsonRpcPost(
self.remotes[remote]['ip'], self.remotes[remote].get('jsonport', DEFAULT... | def jsonRpcLogin(self, remote) | Login to CCU and return session | 4.155441 | 4.068149 | 1.021457 |
logout = False
try:
params = {"_session_id_": session}
response = self._rpcfunctions.jsonRpcPost(
self.remotes[remote]['ip'], self.remotes[remote].get('jsonport', DEFAULT_JSONPORT), "Session.logout", params)
if response['error'] is None and re... | def jsonRpcLogout(self, remote, session) | Logout of CCU | 5.520819 | 5.626939 | 0.981141 |
variables = {}
if self.remotes[remote]['username'] and self.remotes[remote]['password']:
LOG.debug(
"ServerThread.getAllSystemVariables: Getting all System variables via JSON-RPC")
session = self.jsonRpcLogin(remote)
if not session:
... | def getAllSystemVariables(self, remote) | Get all system variables from CCU / Homegear | 3.944904 | 3.789227 | 1.041084 |
var = None
if self.remotes[remote]['username'] and self.remotes[remote]['password']:
LOG.debug(
"ServerThread.getSystemVariable: Getting System variable via JSON-RPC")
session = self.jsonRpcLogin(remote)
if not session:
return
... | def getSystemVariable(self, remote, name) | Get single system variable from CCU / Homegear | 3.807494 | 3.7867 | 1.005491 |
if self.remotes[remote]['username'] and self.remotes[remote]['password']:
LOG.debug(
"ServerThread.setSystemVariable: Setting System variable via JSON-RPC")
session = self.jsonRpcLogin(remote)
if not session:
return
try:
... | def setSystemVariable(self, remote, name, value) | Set a system variable on CCU / Homegear | 2.865275 | 2.907077 | 0.985621 |
try:
return self.proxies["%s-%s" % (self._interface_id, remote)].getServiceMessages()
except Exception as err:
LOG.debug("ServerThread.getServiceMessages: Exception: %s" % str(err)) | def getServiceMessages(self, remote) | Get service messages from CCU / Homegear | 6.392394 | 6.555017 | 0.975191 |
try:
args = [on]
if on and t:
args.append(t)
if address:
args.append(address)
else:
args.append(mode)
return self.proxies["%s-%s" % (self._interface_id, remote)].setInstallMode(*... | def setInstallMode(self, remote, on=True, t=60, mode=1, address=None) | Activate or deactivate installmode on CCU / Homegear | 4.585223 | 4.780379 | 0.959176 |
try:
return self.proxies["%s-%s" % (self._interface_id, remote)].getAllMetadata(address)
except Exception as err:
LOG.debug("ServerThread.getAllMetadata: Exception: %s" % str(err)) | def getAllMetadata(self, remote, address) | Get all metadata of device | 6.207148 | 6.506536 | 0.953986 |
try:
return self.proxies["%s-%s" % (self._interface_id, remote)].setMetadata(address, key, value)
except Exception as err:
LOG.debug("ServerThread.setMetadata: Exception: %s" % str(err)) | def setMetadata(self, remote, address, key, value) | Set metadata of device | 5.498408 | 5.874935 | 0.93591 |
try:
return self.proxies["%s-%s" % (self._interface_id, remote)].deleteMetadata(address, key)
except Exception as err:
LOG.debug("ServerThread.deleteMetadata: Exception: %s" % str(err)) | def deleteMetadata(self, remote, address, key) | Delete metadata of device | 5.929313 | 6.310308 | 0.939623 |
try:
self.proxies["%s-%s" % (self._interface_id, remote)].ping("%s-%s" % (self._interface_id, remote))
except Exception as err:
LOG.warning("ServerThread.ping: Exception: %s" % str(err)) | def ping(self, remote) | Send ping to CCU/Homegear to generate PONG event | 5.608125 | 5.210025 | 1.07641 |
rdict = self.remotes.get(remote)
if not rdict:
return False
if rdict.get('type') != BACKEND_HOMEGEAR:
return False
try:
interface_id = "%s-%s" % (self._interface_id, remote)
return self.proxies[interface_id].clientServerInitialized... | def homegearCheckInit(self, remote) | Check if proxy is still initialized | 5.187469 | 4.917534 | 1.054892 |
try:
return self.proxies["%s-%s" % (self._interface_id, remote)].putParamset(address, paramset, value)
except Exception as err:
LOG.debug("ServerThread.putParamset: Exception: %s" % str(err)) | def putParamset(self, remote, address, paramset, value) | Set paramsets manually | 4.864731 | 5.003531 | 0.97226 |
try:
onoff = bool(onoff)
except Exception as err:
LOG.debug("HelperActorState.set_state: Exception %s" % (err,))
return False
self.writeNodeData("STATE", onoff, channel) | def set_state(self, onoff, channel=None) | Turn state on/off | 7.944035 | 8.058569 | 0.985787 |
try:
position = float(position)
except Exception as err:
LOG.debug("HelperLevel.set_level: Exception %s" % (err,))
return False
self.writeNodeData("LEVEL", position, channel) | def set_level(self, position, channel=None) | Seek a specific value by specifying a float() from 0.0 to 1.0. | 7.84626 | 7.220794 | 1.08662 |
try:
position = float(position)
except Exception as err:
LOG.debug("HelperActorBlindTilt.set_level_2: Exception %s" % (err,))
return False
level = self.getWriteData("LEVEL", channel)
self.writeNodeData("LEVEL_2", position, channel)
... | def set_cover_tilt_position(self, position, channel=None) | Seek a specific value by specifying a float() from 0.0 to 1.0. | 9.309401 | 9.351502 | 0.995498 |
try:
ontime = float(ontime)
except Exception as err:
LOG.debug("SwitchPowermeter.set_ontime: Exception %s" % (err,))
return False
self.actionNodeData("ON_TIME", ontime) | def set_ontime(self, ontime) | Set duration th switch stays on when toggled. | 7.566016 | 7.166175 | 1.055796 |
LOG.info(
"HMGeneric.event: address=%s, interface_id=%s, key=%s, value=%s"
% (self._ADDRESS, interface_id, key, value))
self._VALUES[key] = value # Cache the value
for callback in self._eventcallbacks:
LOG.debug("HMGeneric.event: Using callback %s... | def event(self, interface_id, key, value) | Handle the event received by server. | 4.243492 | 4.167161 | 1.018317 |
try:
self._PARAMSET_DESCRIPTIONS[paramset] = self._proxy.getParamsetDescription(self._ADDRESS, paramset)
except Exception as err:
LOG.error("HMGeneric.getParamsetDescription: Exception: " + str(err))
return False | def getParamsetDescription(self, paramset) | Descriptions for paramsets are available to determine what can be don with the device. | 6.699501 | 6.003196 | 1.115989 |
try:
if paramset:
if self._proxy:
returnset = self._proxy.getParamset(self._ADDRESS, paramset)
if returnset:
self._paramsets[paramset] = returnset
if self.PARAMSETS:
... | def updateParamset(self, paramset) | Devices should not update their own paramsets. They rely on the state of the server.
Hence we pull the specified paramset. | 4.430854 | 4.116646 | 1.076326 |
try:
for ps in self._PARAMSETS:
self.updateParamset(ps)
return True
except Exception as err:
LOG.error("HMGeneric.updateParamsets: Exception: " + str(err))
return False | def updateParamsets(self) | Devices should update their own paramsets. They rely on the state of the server. Hence we pull all paramsets. | 5.681743 | 5.145294 | 1.10426 |
try:
if paramset in self._PARAMSETS and data:
self._proxy.putParamset(self._ADDRESS, paramset, data)
# We update all paramsets to at least have a temporarily accurate state for the device.
# This might not be true for tasks that take long to c... | def putParamset(self, paramset, data={}) | Some devices act upon changes to paramsets.
A "putted" paramset must not contain all keys available in the specified paramset,
just the ones which are writable and should be changed. | 10.553376 | 9.943285 | 1.061357 |
try:
return self._VALUES[key]
except KeyError:
return self.getValue(key) | def getCachedOrUpdatedValue(self, key) | Gets the device's value with the given key.
If the key is not found in the cache, the value is queried from the host. | 4.722265 | 5.738872 | 0.822856 |
LOG.debug("HMGeneric.setValue: address = '%s', key = '%s' value = '%s'" % (self._ADDRESS, key, value))
try:
self._proxy.setValue(self._ADDRESS, key, value)
return True
except Exception as err:
LOG.error("HMGeneric.setValue: %s on %s Exception: %s", ke... | def setValue(self, key, value) | Some devices allow to directly set values to perform a specific task. | 4.456363 | 4.190911 | 1.06334 |
LOG.debug("HMGeneric.getValue: address = '%s', key = '%s'" % (self._ADDRESS, key))
try:
returnvalue = self._proxy.getValue(self._ADDRESS, key)
self._VALUES[key] = returnvalue
return returnvalue
except Exception as err:
LOG.warning("HMGener... | def getValue(self, key) | Some devices allow to directly get values for specific parameters. | 5.257188 | 4.913586 | 1.069929 |
if channel:
return self._hmchannels[channel].getCachedOrUpdatedValue(key)
try:
return self._VALUES[key]
except KeyError:
value = self._VALUES[key] = self.getValue(key)
return value | def getCachedOrUpdatedValue(self, key, channel=None) | Gets the channel's value with the given key.
If the key is not found in the cache, the value is queried from the host.
If 'channel' is given, the respective channel's value is returned. | 4.12174 | 4.625749 | 0.891043 |
if self._VALUES.get(PARAM_UNREACH, False):
return True
else:
for device in self._hmchannels.values():
if device.UNREACH:
return True
return False | def UNREACH(self) | Returns true if the device or any children is not reachable | 8.679077 | 7.065465 | 1.22838 |
return self._getNodeData(name, self._ATTRIBUTENODE, channel) | def getAttributeData(self, name, channel=None) | Returns a attribut | 12.344096 | 14.206456 | 0.868907 |
return self._getNodeData(name, self._BINARYNODE, channel) | def getBinaryData(self, name, channel=None) | Returns a binary node | 13.230759 | 10.40585 | 1.271473 |
return self._getNodeData(name, self._SENSORNODE, channel) | def getSensorData(self, name, channel=None) | Returns a sensor node | 12.563524 | 11.555659 | 1.087218 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.