_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q14900 | CopyBuilder.get_items | train | def get_items(self, source=None, target=None, crit=None):
"""Copy records from source to target collection.
:param source: Input collection
:type source: QueryEngine
:param target: Output collection
:type target: QueryEngine
:param crit: Filter criteria, e.g. "{ 'flag': ... | python | {
"resource": ""
} |
q14901 | parse_fn_docstring | train | def parse_fn_docstring(fn):
"""Get parameter and return types from function's docstring.
Docstrings must use this format::
:param foo: What is foo
:type foo: int
:return: What is returned
:rtype: double
:return: A map of names, each with keys 'type' and 'desc'.
:rtype: tup... | python | {
"resource": ""
} |
q14902 | merge_tasks | train | def merge_tasks(core_collections, sandbox_collections, id_prefix, new_tasks, batch_size=100, wipe=False):
"""Merge core and sandbox collections into a temporary collection in the sandbox.
:param core_collections: Core collection info
:type core_collections: Collections
:param sandbox_collections: Sandb... | python | {
"resource": ""
} |
q14903 | alphadump | train | def alphadump(d, indent=2, depth=0):
"""Dump a dict to a str,
with keys in alphabetical order.
"""
sep = '\n' + ' ' * depth * indent
return ''.join(
("{}: {}{}".format(
k,
alphadump(d[k], depth=depth+1) if isinstance(d[k], dict)
else str(d[k]),
... | python | {
"resource": ""
} |
q14904 | HasExamples.validate_examples | train | def validate_examples(self, fail_fn):
"""Check the examples against the schema.
:param fail_fn: Pass failure messages to this function
:type fail_fn: function(str)
"""
for collection, doc in self.examples():
_log.debug("validating example in collection {}".format(col... | python | {
"resource": ""
} |
q14905 | Builder.run | train | def run(self, user_kw=None, build_kw=None):
"""Run the builder.
:param user_kw: keywords from user
:type user_kw: dict
:param build_kw: internal settings
:type build_kw: dict
:return: Number of items processed
:rtype: int
"""
user_kw = {} if user_... | python | {
"resource": ""
} |
q14906 | Builder.connect | train | def connect(self, config):
"""Connect to database with given configuration, which may be a dict or
a path to a pymatgen-db configuration.
"""
if isinstance(config, str):
conn = dbutil.get_database(config_file=config)
elif isinstance(config, dict):
conn = d... | python | {
"resource": ""
} |
q14907 | Builder._build | train | def _build(self, items, chunk_size=10000):
"""Build the output, in chunks.
:return: Number of items processed
:rtype: int
"""
_log.debug("_build, chunk_size={:d}".format(chunk_size))
n, i = 0, 0
for i, item in enumerate(items):
if i == 0:
... | python | {
"resource": ""
} |
q14908 | Builder._run_parallel_multiprocess | train | def _run_parallel_multiprocess(self):
"""Run processes from queue
"""
_log.debug("run.parallel.multiprocess.start")
processes = []
ProcRunner.instance = self
for i in range(self._ncores):
self._status.running(i)
proc = multiprocessing.Process(targe... | python | {
"resource": ""
} |
q14909 | Builder._run | train | def _run(self, index):
"""Run method for one thread or process
Just pull an item off the queue and process it,
until the queue is empty.
:param index: Sequential index of this process or thread
:type index: int
"""
while 1:
try:
item =... | python | {
"resource": ""
} |
q14910 | csv_dict | train | def csv_dict(d):
"""Format dict to a string with comma-separated values.
"""
if len(d) == 0:
return "{}"
return "{" + ', '.join(["'{}': {}".format(k, quotable(v))
for k, v in d.items()]) + "}" | python | {
"resource": ""
} |
q14911 | kvp_dict | train | def kvp_dict(d):
"""Format dict to key=value pairs.
"""
return ', '.join(
["{}={}".format(k, quotable(v)) for k, v in d.items()]) | python | {
"resource": ""
} |
q14912 | MaxValueBuilder.get_items | train | def get_items(self, source=None, target=None):
"""Get all records from source collection to add to target.
:param source: Input collection
:type source: QueryEngine
:param target: Output collection
:type target: QueryEngine
"""
self._groups = self.shared_dict()
... | python | {
"resource": ""
} |
q14913 | MaxValueBuilder.process_item | train | def process_item(self, item):
"""Calculate new maximum value for each group,
for "new" items only.
"""
group, value = item['group'], item['value']
if group in self._groups:
cur_val = self._groups[group]
self._groups[group] = max(cur_val, value)
els... | python | {
"resource": ""
} |
q14914 | MaxValueBuilder.finalize | train | def finalize(self, errs):
"""Update target collection with calculated maximum values.
"""
for group, value in self._groups.items():
doc = {'group': group, 'value': value}
self._target_coll.update({'group': group}, doc, upsert=True)
return True | python | {
"resource": ""
} |
q14915 | Projection.add | train | def add(self, field, op=None, val=None):
"""Update report fields to include new one, if it doesn't already.
:param field: The field to include
:type field: Field
:param op: Operation
:type op: ConstraintOperator
:return: None
"""
if field.has_subfield():
... | python | {
"resource": ""
} |
q14916 | Projection.to_mongo | train | def to_mongo(self):
"""Translate projection to MongoDB query form.
:return: Dictionary to put into a MongoDB JSON query
:rtype: dict
"""
d = copy.copy(self._fields)
for k, v in self._slices.items():
d[k] = {'$slice': v}
return d | python | {
"resource": ""
} |
q14917 | ConstraintViolationGroup.add_violations | train | def add_violations(self, violations, record=None):
"""Add constraint violations and associated record.
:param violations: List of violations
:type violations: list(ConstraintViolation)
:param record: Associated record
:type record: dict
:rtype: None
"""
r... | python | {
"resource": ""
} |
q14918 | ConstraintSpec._add_complex_section | train | def _add_complex_section(self, item):
"""Add a section that has a filter and set of constraints
:raise: ValueError if filter or constraints is missing
"""
# extract filter and constraints
try:
fltr = item[self.FILTER_SECT]
except KeyError:
raise V... | python | {
"resource": ""
} |
q14919 | Validator.validate | train | def validate(self, coll, constraint_spec, subject='collection'):
"""Validation of a collection.
This is a generator that yields ConstraintViolationGroups.
:param coll: Mongo collection
:type coll: pymongo.Collection
:param constraint_spec: Constraint specification
:type... | python | {
"resource": ""
} |
q14920 | Validator._validate_section | train | def _validate_section(self, subject, coll, parts):
"""Validate one section of a spec.
:param subject: Name of subject
:type subject: str
:param coll: The collection to validate
:type coll: pymongo.Collection
:param parts: Section parts
:type parts: Validator.Sect... | python | {
"resource": ""
} |
q14921 | Validator._get_violations | train | def _get_violations(self, query, record):
"""Reverse-engineer the query to figure out why a record was selected.
:param query: MongoDB query
:type query: MongQuery
:param record: Record in question
:type record: dict
:return: Reasons why bad
:rtype: list(Constrai... | python | {
"resource": ""
} |
q14922 | Validator._build | train | def _build(self, constraint_spec):
"""Generate queries to execute.
Sets instance variables so that Mongo query strings, etc. can now
be extracted from the object.
:param constraint_spec: Constraint specification
:type constraint_spec: ConstraintSpec
"""
self._se... | python | {
"resource": ""
} |
q14923 | Validator._process_constraint_expressions | train | def _process_constraint_expressions(self, expr_list, conflict_check=True, rev=True):
"""Create and return constraints from expressions in expr_list.
:param expr_list: The expressions
:conflict_check: If True, check for conflicting expressions within each field
:return: Constraints group... | python | {
"resource": ""
} |
q14924 | Validator._is_python | train | def _is_python(self, constraint_list):
"""Check whether constraint is an import of Python code.
:param constraint_list: List of raw constraints from YAML file
:type constraint_list: list(str)
:return: True if this refers to an import of code, False otherwise
:raises: ValidatorSy... | python | {
"resource": ""
} |
q14925 | Validator.set_aliases | train | def set_aliases(self, new_value):
"Set aliases and wrap errors in ValueError"
try:
self.aliases = new_value
except Exception as err:
raise ValueError("invalid value: {}".format(err)) | python | {
"resource": ""
} |
q14926 | Sampler.sample | train | def sample(self, cursor):
"""Extract records randomly from the database.
Continue until the target proportion of the items have been
extracted, or until `min_items` if this is larger.
If `max_items` is non-negative, do not extract more than these.
This function is a generator, y... | python | {
"resource": ""
} |
q14927 | available_backends | train | def available_backends():
"""Lists the currently available backend types"""
print 'The following LiveSync agents are available:'
for name, backend in current_plugin.backend_classes.iteritems():
print cformat(' - %{white!}{}%{reset}: {} ({})').format(name, backend.title, backend.description) | python | {
"resource": ""
} |
q14928 | agents | train | def agents():
"""Lists the currently active agents"""
print 'The following LiveSync agents are active:'
agent_list = LiveSyncAgent.find().order_by(LiveSyncAgent.backend_name, db.func.lower(LiveSyncAgent.name)).all()
table_data = [['ID', 'Name', 'Backend', 'Initial Export', 'Queue']]
for agent in age... | python | {
"resource": ""
} |
q14929 | initial_export | train | def initial_export(agent_id, force):
"""Performs the initial data export for an agent"""
agent = LiveSyncAgent.find_first(id=agent_id)
if agent is None:
print 'No such agent'
return
if agent.backend is None:
print cformat('Cannot run agent %{red!}{}%{reset} (backend not found)').... | python | {
"resource": ""
} |
q14930 | run | train | def run(agent_id, force=False):
"""Runs the livesync agent"""
if agent_id is None:
agent_list = LiveSyncAgent.find_all()
else:
agent = LiveSyncAgent.find_first(id=agent_id)
if agent is None:
print 'No such agent'
return
agent_list = [agent]
for ag... | python | {
"resource": ""
} |
q14931 | Task._serialize_inputs | train | def _serialize_inputs(inputs):
"""Serialize task input dictionary"""
serialized_inputs = {}
for input_id, input_value in inputs.items():
if isinstance(input_value, list):
serialized_list = Task._serialize_input_list(input_value)
serialized_inputs[input... | python | {
"resource": ""
} |
q14932 | Task._serialize_input_list | train | def _serialize_input_list(input_value):
"""Recursively serialize task input list"""
input_list = []
for item in input_value:
if isinstance(item, list):
input_list.append(Task._serialize_input_list(item))
else:
if isinstance(item, File):
... | python | {
"resource": ""
} |
q14933 | PiwikQueryReportEventGraphBase.get_result | train | def get_result(self):
"""Perform the call and return the graph data
:return: Encoded PNG graph data string to be inserted in a `src`
atribute of a HTML img tag.
"""
png = self.call()
if png is None:
return
if png.startswith('GD extension must... | python | {
"resource": ""
} |
q14934 | Chatroom.server | train | def server(self):
"""The server name of the chatroom.
Usually the default one unless a custom one is set.
"""
from indico_chat.plugin import ChatPlugin
return self.custom_server or ChatPlugin.settings.get('muc_server') | python | {
"resource": ""
} |
q14935 | ChatroomEventAssociation.find_for_event | train | def find_for_event(cls, event, include_hidden=False, **kwargs):
"""Returns a Query that retrieves the chatrooms for an event
:param event: an indico event (with a numeric ID)
:param include_hidden: if hidden chatrooms should be included, too
:param kwargs: extra kwargs to pass to ``find... | python | {
"resource": ""
} |
q14936 | ChatroomEventAssociation.delete | train | def delete(self, reason=''):
"""Deletes the event chatroom and if necessary the chatroom, too.
:param reason: reason for the deletion
:return: True if the associated chatroom was also
deleted, otherwise False
"""
db.session.delete(self)
db.session.flush(... | python | {
"resource": ""
} |
q14937 | obj_deref | train | def obj_deref(ref):
"""Returns the object identified by `ref`"""
from indico_livesync.models.queue import EntryType
if ref['type'] == EntryType.category:
return Category.get_one(ref['category_id'])
elif ref['type'] == EntryType.event:
return Event.get_one(ref['event_id'])
elif ref['t... | python | {
"resource": ""
} |
q14938 | clean_old_entries | train | def clean_old_entries():
"""Deletes obsolete entries from the queues"""
from indico_livesync.plugin import LiveSyncPlugin
from indico_livesync.models.queue import LiveSyncQueueEntry
queue_entry_ttl = LiveSyncPlugin.settings.get('queue_entry_ttl')
if not queue_entry_ttl:
return
expire_th... | python | {
"resource": ""
} |
q14939 | get_excluded_categories | train | def get_excluded_categories():
"""Get excluded category IDs."""
from indico_livesync.plugin import LiveSyncPlugin
return {int(x['id']) for x in LiveSyncPlugin.settings.get('excluded_categories')} | python | {
"resource": ""
} |
q14940 | compound_id | train | def compound_id(obj):
"""Generate a hierarchical compound ID, separated by dots."""
if isinstance(obj, (Category, Session)):
raise TypeError('Compound IDs are not supported for this entry type')
elif isinstance(obj, Event):
return unicode(obj.id)
elif isinstance(obj, Contribution):
... | python | {
"resource": ""
} |
q14941 | track_download_request | train | def track_download_request(download_url, download_title):
"""Track a download in Piwik"""
from indico_piwik.plugin import PiwikPlugin
if not download_url:
raise ValueError("download_url can't be empty")
if not download_title:
raise ValueError("download_title can't be empty")
reques... | python | {
"resource": ""
} |
q14942 | LiveSyncAgent.backend | train | def backend(self):
"""Returns the backend class"""
from indico_livesync.plugin import LiveSyncPlugin
return LiveSyncPlugin.instance.backend_classes.get(self.backend_name) | python | {
"resource": ""
} |
q14943 | notify_created | train | def notify_created(room, event, user):
"""Notifies about the creation of a chatroom.
:param room: the chatroom
:param event: the event
:param user: the user performing the action
"""
tpl = get_plugin_template_module('emails/created.txt', chatroom=room, event=event, user=user)
_send(event, t... | python | {
"resource": ""
} |
q14944 | notify_attached | train | def notify_attached(room, event, user):
"""Notifies about an existing chatroom being attached to an event.
:param room: the chatroom
:param event: the event
:param user: the user performing the action
"""
tpl = get_plugin_template_module('emails/attached.txt', chatroom=room, event=event, user=u... | python | {
"resource": ""
} |
q14945 | notify_modified | train | def notify_modified(room, event, user):
"""Notifies about the modification of a chatroom.
:param room: the chatroom
:param event: the event
:param user: the user performing the action
"""
tpl = get_plugin_template_module('emails/modified.txt', chatroom=room, event=event, user=user)
_send(ev... | python | {
"resource": ""
} |
q14946 | notify_deleted | train | def notify_deleted(room, event, user, room_deleted):
"""Notifies about the deletion of a chatroom.
:param room: the chatroom
:param event: the event
:param user: the user performing the action; `None` if due to event deletion
:param room_deleted: if the room has been deleted from the jabber server
... | python | {
"resource": ""
} |
q14947 | UPartedFile.get_parts | train | def get_parts(self):
"""
Partitions the file and saves the parts to be uploaded
in memory.
"""
parts = []
start_byte = 0
for i in range(1, self.total + 1):
end_byte = start_byte + self.part_size
if end_byte >= self.file_size - 1:
... | python | {
"resource": ""
} |
q14948 | Upload._verify_part_number | train | def _verify_part_number(self):
"""
Verifies that the total number of parts is smaller then 10^5 which
is the maximum number of parts.
"""
total = int(math.ceil(self._file_size / self._part_size))
if total > PartSize.MAXIMUM_TOTAL_PARTS:
self._status = Transfer... | python | {
"resource": ""
} |
q14949 | Upload._verify_part_size | train | def _verify_part_size(self):
"""
Verifies that the part size is smaller then the maximum part size
which is 5GB.
"""
if self._part_size > PartSize.MAXIMUM_UPLOAD_SIZE:
self._status = TransferState.FAILED
raise SbgError('Part size = {}b. Maximum part size i... | python | {
"resource": ""
} |
q14950 | Upload._verify_file_size | train | def _verify_file_size(self):
"""
Verifies that the file is smaller then 5TB which is the maximum
that is allowed for upload.
"""
if self._file_size > PartSize.MAXIMUM_OBJECT_SIZE:
self._status = TransferState.FAILED
raise SbgError('File size = {}b. Maximum... | python | {
"resource": ""
} |
q14951 | Upload._initialize_upload | train | def _initialize_upload(self):
"""
Initialized the upload on the API server by submitting the information
about the project, the file name, file size and the part size that is
going to be used during multipart upload.
"""
init_data = {
'name': self._file_name,... | python | {
"resource": ""
} |
q14952 | Upload._finalize_upload | train | def _finalize_upload(self):
"""
Finalizes the upload on the API server.
"""
from sevenbridges.models.file import File
try:
response = self._api.post(
self._URL['upload_complete'].format(upload_id=self._upload_id)
).json()
self._... | python | {
"resource": ""
} |
q14953 | Upload._abort_upload | train | def _abort_upload(self):
"""
Aborts the upload on the API server.
"""
try:
self._api.delete(
self._URL['upload_info'].format(upload_id=self._upload_id)
)
except SbgError as e:
self._status = TransferState.FAILED
rais... | python | {
"resource": ""
} |
q14954 | Upload.add_callback | train | def add_callback(self, callback=None, errorback=None):
"""
Adds a callback that will be called when the upload
finishes successfully or when error is raised.
"""
self._callback = callback
self._errorback = errorback | python | {
"resource": ""
} |
q14955 | process_records | train | def process_records(records):
"""Converts queue entries into object changes.
:param records: an iterable containing `LiveSyncQueueEntry` objects
:return: a dict mapping object references to `SimpleChange` bitsets
"""
changes = defaultdict(int)
cascaded_update_records = set()
cascaded_delete... | python | {
"resource": ""
} |
q14956 | _process_cascaded_category_contents | train | def _process_cascaded_category_contents(records):
"""
Travel from categories to subcontributions, flattening the whole event structure.
Yields everything that it finds (except for elements whose protection has changed
but are not inheriting their protection settings from anywhere).
:param records:... | python | {
"resource": ""
} |
q14957 | VidyoPlugin.create_room | train | def create_room(self, vc_room, event):
"""Create a new Vidyo room for an event, given a VC room.
In order to create the Vidyo room, the function will try to do so with
all the available identities of the user based on the authenticators
defined in Vidyo plugin's settings, in that order.... | python | {
"resource": ""
} |
q14958 | LiveSyncQueueEntry.object | train | def object(self):
"""Return the changed object."""
if self.type == EntryType.category:
return self.category
elif self.type == EntryType.event:
return self.event
elif self.type == EntryType.session:
return self.session
elif self.type == EntryTyp... | python | {
"resource": ""
} |
q14959 | LiveSyncQueueEntry.object_ref | train | def object_ref(self):
"""Return the reference of the changed object."""
return ImmutableDict(type=self.type, category_id=self.category_id, event_id=self.event_id,
session_id=self.session_id, contrib_id=self.contrib_id, subcontrib_id=self.subcontrib_id) | python | {
"resource": ""
} |
q14960 | LiveSyncQueueEntry.create | train | def create(cls, changes, ref, excluded_categories=set()):
"""Create a new change in all queues.
:param changes: the change types, an iterable containing
:class:`ChangeType`
:param ref: the object reference (returned by `obj_ref`)
of the changed ob... | python | {
"resource": ""
} |
q14961 | decompose_code | train | def decompose_code(code):
"""
Decomposes a MARC "code" into tag, ind1, ind2, subcode
"""
code = "%-6s" % code
ind1 = code[3:4]
if ind1 == " ": ind1 = "_"
ind2 = code[4:5]
if ind2 == " ": ind2 = "_"
subcode = code[5:6]
if subcode == " ": subcode = None
return (code[0:3], ind1,... | python | {
"resource": ""
} |
q14962 | InvenioConnector._init_browser | train | def _init_browser(self):
"""
Ovveride this method with the appropriate way to prepare a logged in
browser.
"""
self.browser = mechanize.Browser()
self.browser.set_handle_robots(False)
self.browser.open(self.server_url + "/youraccount/login")
self.browser.s... | python | {
"resource": ""
} |
q14963 | InvenioConnector.get_record | train | def get_record(self, recid, read_cache=True):
"""
Returns the record with given recid
"""
if recid in self.cached_records or not read_cache:
return self.cached_records[recid]
else:
return self.search(p="recid:" + str(recid)) | python | {
"resource": ""
} |
q14964 | InvenioConnector.upload_marcxml | train | def upload_marcxml(self, marcxml, mode):
"""
Uploads a record to the server
Parameters:
marcxml - *str* the XML to upload.
mode - *str* the mode to use for the upload.
"-i" insert new records
"-r" replace existing records
... | python | {
"resource": ""
} |
q14965 | InvenioConnector._validate_server_url | train | def _validate_server_url(self):
"""Validates self.server_url"""
try:
request = requests.head(self.server_url)
if request.status_code >= 400:
raise InvenioConnectorServerError(
"Unexpected status code '%d' accessing URL: %s"
... | python | {
"resource": ""
} |
q14966 | PiwikQueryReportEventMetricReferrers.get_result | train | def get_result(self):
"""Perform the call and return a list of referrers"""
result = get_json_from_remote_server(self.call)
referrers = list(result)
for referrer in referrers:
referrer['sum_visit_length'] = stringify_seconds(referrer['sum_visit_length'])
return sorted... | python | {
"resource": ""
} |
q14967 | PiwikQueryReportEventMetricPeakDateAndVisitors.get_result | train | def get_result(self):
"""Perform the call and return the peak date and how many users"""
result = get_json_from_remote_server(self.call)
if result:
date, value = max(result.iteritems(), key=itemgetter(1))
return {'date': date, 'users': value}
else:
ret... | python | {
"resource": ""
} |
q14968 | PiwikRequest.call | train | def call(self, default_response=None, **query_params):
"""Perform a query to the Piwik server and return the response.
:param default_response: Return value in case the query fails
:param query_params: Dictionary with the parameters of the query
"""
query_url = self.get_query_ur... | python | {
"resource": ""
} |
q14969 | PiwikRequest.get_query | train | def get_query(self, query_params=None):
"""Return a query string"""
if query_params is None:
query_params = {}
query = ''
query_params['idSite'] = self.site_id
if self.api_token is not None:
query_params['token_auth'] = self.api_token
for key, valu... | python | {
"resource": ""
} |
q14970 | PiwikRequest._perform_call | train | def _perform_call(self, query_url, default_response=None, timeout=10):
"""Returns the raw results from the API"""
try:
response = requests.get(query_url, timeout=timeout)
except socket.timeout:
current_plugin.logger.warning("Timeout contacting Piwik server")
r... | python | {
"resource": ""
} |
q14971 | Uploader.run | train | def run(self, records):
"""Runs the batch upload
:param records: an iterable containing queue entries
"""
self_name = type(self).__name__
for i, batch in enumerate(grouper(records, self.BATCH_SIZE, skip_missing=True), 1):
self.logger.info('%s processing batch %d', se... | python | {
"resource": ""
} |
q14972 | Uploader.run_initial | train | def run_initial(self, events):
"""Runs the initial batch upload
:param events: an iterable containing events
"""
self_name = type(self).__name__
for i, batch in enumerate(grouper(events, self.INITIAL_BATCH_SIZE, skip_missing=True), 1):
self.logger.debug('%s processin... | python | {
"resource": ""
} |
q14973 | Uploader.processed_records | train | def processed_records(self, records):
"""Executed after successfully uploading a batch of records from the queue.
:param records: a list of queue entries
"""
for record in records:
self.logger.debug('Marking as processed: %s', record)
record.processed = True
... | python | {
"resource": ""
} |
q14974 | cli | train | def cli():
"""Migrate data to S3.
Use the `copy` subcommand to copy data to S3. This can be done
safely while Indico is running. At the end it will show you what
you need to add to your `indico.conf`.
Once you updated your config with the new storage backends, you
can use the `apply` subcomman... | python | {
"resource": ""
} |
q14975 | DeconzSession.start | train | def start(self) -> None:
"""Connect websocket to deCONZ."""
if self.config:
self.websocket = self.ws_client(
self.loop, self.session, self.host,
self.config.websocketport, self.async_session_handler)
self.websocket.start()
else:
... | python | {
"resource": ""
} |
q14976 | DeconzSession.async_load_parameters | train | async def async_load_parameters(self) -> bool:
"""Load deCONZ parameters.
Returns lists of indices of which devices was added.
"""
data = await self.async_get_state('')
_LOGGER.debug(pformat(data))
config = data.get('config', {})
groups = data.get('groups', {})... | python | {
"resource": ""
} |
q14977 | DeconzSession.async_put_state | train | async def async_put_state(self, field: str, data: dict) -> dict:
"""Set state of object in deCONZ.
Field is a string representing a specific device in deCONZ
e.g. field='/lights/1/state'.
Data is a json object with what data you want to alter
e.g. data={'on': True}.
See ... | python | {
"resource": ""
} |
q14978 | DeconzSession.async_get_state | train | async def async_get_state(self, field: str) -> dict:
"""Get state of object in deCONZ.
Field is a string representing an API endpoint or lower
e.g. field='/lights'.
See Dresden Elektroniks REST API documentation for details:
http://dresden-elektronik.github.io/deconz-rest-doc/re... | python | {
"resource": ""
} |
q14979 | DeconzSession.async_session_handler | train | def async_session_handler(self, signal: str) -> None:
"""Signalling from websocket.
data - new data available for processing.
state - network state has changed.
"""
if signal == 'data':
self.async_event_handler(self.websocket.data)
elif signal == 'state... | python | {
"resource": ""
} |
q14980 | DeconzSession.async_event_handler | train | def async_event_handler(self, event: dict) -> None:
"""Receive event from websocket and identifies where the event belong.
{
"t": "event",
"e": "changed",
"r": "sensors",
"id": "12",
"state": { "buttonevent": 2002 }
}
"""
... | python | {
"resource": ""
} |
q14981 | DeconzSession.update_group_color | train | def update_group_color(self, lights: list) -> None:
"""Update group colors based on light states.
deCONZ group updates don't contain any information about the current
state of the lights in the group. This method updates the color
properties of the group to the current color of the ligh... | python | {
"resource": ""
} |
q14982 | async_get_api_key | train | async def async_get_api_key(session, host, port, username=None, password=None, **kwargs):
"""Get a new API key for devicetype."""
url = 'http://{host}:{port}/api'.format(host=host, port=str(port))
auth = None
if username and password:
auth = aiohttp.BasicAuth(username, password=password)
d... | python | {
"resource": ""
} |
q14983 | async_delete_api_key | train | async def async_delete_api_key(session, host, port, api_key):
"""Delete API key from deCONZ."""
url = 'http://{host}:{port}/api/{api_key}/config/whitelist/{api_key}'.format(
host=host, port=str(port), api_key=api_key)
response = await async_request(session.delete, url)
_LOGGER.info(response) | python | {
"resource": ""
} |
q14984 | async_delete_all_keys | train | async def async_delete_all_keys(session, host, port, api_key, api_keys=[]):
"""Delete all API keys except for the ones provided to the method."""
url = 'http://{}:{}/api/{}/config'.format(host, str(port), api_key)
response = await async_request(session.get, url)
api_keys.append(api_key)
for key in... | python | {
"resource": ""
} |
q14985 | async_get_bridgeid | train | async def async_get_bridgeid(session, host, port, api_key, **kwargs):
"""Get bridge id for bridge."""
url = 'http://{}:{}/api/{}/config'.format(host, str(port), api_key)
response = await async_request(session.get, url)
bridgeid = response['bridgeid']
_LOGGER.info("Bridge id: %s", bridgeid)
ret... | python | {
"resource": ""
} |
q14986 | async_discovery | train | async def async_discovery(session):
"""Find bridges allowing gateway discovery."""
bridges = []
response = await async_request(session.get, URL_DISCOVER)
if not response:
_LOGGER.info("No discoverable bridges available.")
return bridges
for bridge in response:
bridges.appen... | python | {
"resource": ""
} |
q14987 | AIOWSClient.retry | train | def retry(self):
"""Retry to connect to deCONZ."""
self.state = STATE_STARTING
self.loop.call_later(RETRY_TIMER, self.start)
_LOGGER.debug('Reconnecting to deCONZ in %i.', RETRY_TIMER) | python | {
"resource": ""
} |
q14988 | WSClient.stop | train | def stop(self):
"""Close websocket connection."""
self.state = STATE_STOPPED
if self.transport:
self.transport.close() | python | {
"resource": ""
} |
q14989 | WSClient.connection_made | train | def connection_made(self, transport):
"""Do the websocket handshake.
According to https://tools.ietf.org/html/rfc6455
"""
randomness = os.urandom(16)
key = base64encode(randomness).decode('utf-8').strip()
self.transport = transport
message = "GET / HTTP/1.1\r\n"
... | python | {
"resource": ""
} |
q14990 | WSClient.data_received | train | def data_received(self, data):
"""Data received over websocket.
First received data will allways be handshake accepting connection.
We need to check how big the header is so we can send event data
as a proper json object.
"""
if self.state == STATE_STARTING:
... | python | {
"resource": ""
} |
q14991 | WSClient.get_payload | train | def get_payload(self, data):
"""Parse length of payload and return it."""
start = 2
length = ord(data[1:2])
if length == 126:
# Payload information are an extra 2 bytes.
start = 4
length, = unpack(">H", data[2:4])
elif length == 127:
... | python | {
"resource": ""
} |
q14992 | notify_owner | train | def notify_owner(plugin, vc_room):
"""Notifies about the deletion of a Vidyo room from the Vidyo server."""
user = vc_room.vidyo_extension.owned_by_user
tpl = get_plugin_template_module('emails/remote_deleted.html', plugin=plugin, vc_room=vc_room, event=None,
vc_room_eve... | python | {
"resource": ""
} |
q14993 | rooms | train | def rooms(status=None):
"""Lists all Vidyo rooms"""
room_query = VCRoom.find(type='vidyo')
table_data = [['ID', 'Name', 'Status', 'Vidyo ID', 'Extension']]
if status:
room_query = room_query.filter(VCRoom.status == VCRoomStatus.get(status))
for room in room_query:
table_data.appen... | python | {
"resource": ""
} |
q14994 | render_engine_or_search_template | train | def render_engine_or_search_template(template_name, **context):
"""Renders a template from the engine plugin or the search plugin
If the template is available in the engine plugin, it's taken
from there, otherwise the template from this plugin is used.
:param template_name: name of the template
:p... | python | {
"resource": ""
} |
q14995 | iter_user_identities | train | def iter_user_identities(user):
"""Iterates over all existing user identities that can be used with Vidyo"""
from indico_vc_vidyo.plugin import VidyoPlugin
providers = authenticators_re.split(VidyoPlugin.settings.get('authenticators'))
done = set()
for provider in providers:
for _, identifie... | python | {
"resource": ""
} |
q14996 | get_user_from_identifier | train | def get_user_from_identifier(settings, identifier):
"""Get an actual User object from an identifier"""
providers = list(auth.strip() for auth in settings.get('authenticators').split(','))
identities = Identity.find_all(Identity.provider.in_(providers), Identity.identifier == identifier)
if identities:
... | python | {
"resource": ""
} |
q14997 | update_room_from_obj | train | def update_room_from_obj(settings, vc_room, room_obj):
"""Updates a VCRoom DB object using a SOAP room object returned by the API"""
vc_room.name = room_obj.name
if room_obj.ownerName != vc_room.data['owner_identity']:
owner = get_user_from_identifier(settings, room_obj.ownerName) or User.get_system... | python | {
"resource": ""
} |
q14998 | pack_ip | train | def pack_ip(ipstr):
"""Converts an ip address given in dotted notation to a four byte
string in network byte order.
>>> len(pack_ip("127.0.0.1"))
4
>>> pack_ip("foo")
Traceback (most recent call last):
...
ValueError: given ip address has an invalid number of dots
@type ipstr: str
@rtype: bytes
@raises Val... | python | {
"resource": ""
} |
q14999 | unpack_ip | train | def unpack_ip(fourbytes):
"""Converts an ip address given in a four byte string in network
byte order to a string in dotted notation.
>>> unpack_ip(b"dead")
'100.101.97.100'
>>> unpack_ip(b"alive")
Traceback (most recent call last):
...
ValueError: given buffer is not exactly four bytes long
@type fourbytes:... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.