sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def uuidify(val):
"""Takes an integer and transforms it to a UUID format.
returns: UUID formatted version of input.
"""
if uuidutils.is_uuid_like(val):
return val
else:
try:
int_val = int(val, 16)
except ValueError:
with excutils.save_and_reraise_exce... | Takes an integer and transforms it to a UUID format.
returns: UUID formatted version of input. | entailment |
def _ensure_format(rule, attribute, res_dict):
"""Verifies that attribute in res_dict is properly formatted.
Since, in the .ini-files, lists are specified as ':' separated text and
UUID values can be plain integers we need to transform any such values
into proper format. Empty strings are converted to ... | Verifies that attribute in res_dict is properly formatted.
Since, in the .ini-files, lists are specified as ':' separated text and
UUID values can be plain integers we need to transform any such values
into proper format. Empty strings are converted to None if validator
specifies that None value is acc... | entailment |
def obtain_hosting_device_credentials_from_config():
"""Obtains credentials from config file and stores them in memory.
To be called before hosting device templates defined in the config file
are created.
"""
cred_dict = get_specific_config('cisco_hosting_device_credential')
attr_info = {
... | Obtains credentials from config file and stores them in memory.
To be called before hosting device templates defined in the config file
are created. | entailment |
def get_resources(cls):
"""Returns Ext Resources."""
plural_mappings = resource_helper.build_plural_mappings(
{}, RESOURCE_ATTRIBUTE_MAP)
if NEUTRON_VERSION.version[0] <= NEUTRON_NEWTON_VERSION.version[0]:
attr.PLURALS.update(plural_mappings)
return resource_helpe... | Returns Ext Resources. | entailment |
def get_routertypes(self, context, filters=None, fields=None,
sorts=None, limit=None, marker=None,
page_reverse=False):
"""Lists defined router types."""
pass | Lists defined router types. | entailment |
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
set_mysql_engine()
engine = session.create_engine(neutron_config.database.connection)
connection = engine.connect()
context.co... | Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context. | entailment |
def has_role(self, role):
'''
Check whether the Launch Paramters set the role.
'''
return self.roles and any([re.search(role, our_role, re.I)
for our_role in self.roles]) | Check whether the Launch Paramters set the role. | entailment |
def username(self, default=None):
'''
Return the full, given, or family name if set.
'''
if self.lis_person_name_given:
return self.lis_person_name_given
elif self.lis_person_name_family:
return self.lis_person_name_family
elif self.lis_person_name... | Return the full, given, or family name if set. | entailment |
def post_replace_result(self, score, outcome_opts=defaultdict(lambda:None), result_data=None):
'''
POSTs the given score to the Tool Consumer with a replaceResult.
Returns OutcomeResponse object and stores it in self.outcome_request
OPTIONAL:
result_data must be a dictionar... | POSTs the given score to the Tool Consumer with a replaceResult.
Returns OutcomeResponse object and stores it in self.outcome_request
OPTIONAL:
result_data must be a dictionary
Note: ONLY ONE of these values can be in the dict at a time,
due to the Canvas specificat... | entailment |
def build_return_url(self):
'''
If the Tool Consumer sent a return URL, add any set messages to the
URL.
'''
if not self.launch_presentation_return_url:
return None
lti_message_fields = ['lti_errormsg', 'lti_errorlog',
'lti_msg',... | If the Tool Consumer sent a return URL, add any set messages to the
URL. | entailment |
def success_redirect(self, msg='', log=''):
'''
Shortcut for redirecting Django view to LTI Consumer with messages
'''
from django.shortcuts import redirect
self.lti_msg = msg
self.lti_log = log
return redirect(self.build_return_url()) | Shortcut for redirecting Django view to LTI Consumer with messages | entailment |
def error_redirect(self, errormsg='', errorlog=''):
'''
Shortcut for redirecting Django view to LTI Consumer with errors
'''
from django.shortcuts import redirect
self.lti_errormsg = errormsg
self.lti_errorlog = errorlog
return redirect(self.build_return_url()) | Shortcut for redirecting Django view to LTI Consumer with errors | entailment |
def _notify_thing_lid_change(self, from_lid, to_lid):
"""Used by Thing instances to indicate that a rename operation has happened"""
try:
with self.__private_things:
self.__private_things[to_lid] = self.__private_things.pop(from_lid)
except KeyError:
logge... | Used by Thing instances to indicate that a rename operation has happened | entailment |
def register_catchall_feeddata(self, callback, callback_parsed=None):
"""
Registers a callback that is called for all feeddata your Thing receives
`Example`
#!python
def feeddata_callback(data):
print(data)
...
client.register_cat... | Registers a callback that is called for all feeddata your Thing receives
`Example`
#!python
def feeddata_callback(data):
print(data)
...
client.register_catchall_feeddata(feeddata_callback)
`callback` (required) the function name that yo... | entailment |
def register_catchall_controlreq(self, callback, callback_parsed=None):
"""
Registers a callback that is called for all control requests received by your Thing
`Example`
#!python
def controlreq_callback(data):
print(data)
...
clie... | Registers a callback that is called for all control requests received by your Thing
`Example`
#!python
def controlreq_callback(data):
print(data)
...
client.register_catchall_controlreq(controlreq_callback)
`callback` (required) the func... | entailment |
def register_callback_created(self, func, serialised=True):
"""
Register a callback for resource creation. This will be called when any *new* resource
is created within your agent. If `serialised` is not set, the callbacks might arrive
in a different order to they were requested.
... | Register a callback for resource creation. This will be called when any *new* resource
is created within your agent. If `serialised` is not set, the callbacks might arrive
in a different order to they were requested.
The payload passed to your callback is an OrderedDict with the following key... | entailment |
def register_callback_duplicate(self, func, serialised=True):
"""
Register a callback for resource creation but where the resource already exists in Iotic Space.
In this case the existing reference is passed to you.
If `serialised` is not set, the callbacks might arrive in a different or... | Register a callback for resource creation but where the resource already exists in Iotic Space.
In this case the existing reference is passed to you.
If `serialised` is not set, the callbacks might arrive in a different order to they were requested.
The payload passed to your callback is an Ord... | entailment |
def register_callback_renamed(self, func, serialised=True):
"""
Register a callback for resource rename. This will be called when any resource
is renamed within your agent.
If `serialised` is not set, the callbacks might arrive in a different order to they were requested.
The p... | Register a callback for resource rename. This will be called when any resource
is renamed within your agent.
If `serialised` is not set, the callbacks might arrive in a different order to they were requested.
The payload passed to your callback is an OrderedDict with the following keys
... | entailment |
def register_callback_deleted(self, func, serialised=True):
"""
Register a callback for resource deletion. This will be called when any resource
is deleted within your agent.
If `serialised` is not set, the callbacks might arrive in a different order to they were requested.
The... | Register a callback for resource deletion. This will be called when any resource
is deleted within your agent.
If `serialised` is not set, the callbacks might arrive in a different order to they were requested.
The payload passed to your callback is an OrderedDict with the following keys
... | entailment |
def register_callback_reassigned(self, func, serialised=True):
"""
Register a callback for resource reassignment. This will be called when any resource
is reassigned to or from your agent.
If `serialised` is not set, the callbacks might arrive in a different order to they were requested... | Register a callback for resource reassignment. This will be called when any resource
is reassigned to or from your agent.
If `serialised` is not set, the callbacks might arrive in a different order to they were requested.
The payload passed to your callback is an OrderedDict with the following... | entailment |
def register_callback_subscribed(self, callback):
"""
Register a callback for new subscription. This gets called whenever one of *your* things subscribes to something
else.
`Note` it is not called when whenever something else subscribes to your thing.
The payload passed to your... | Register a callback for new subscription. This gets called whenever one of *your* things subscribes to something
else.
`Note` it is not called when whenever something else subscribes to your thing.
The payload passed to your callback is either a
[RemoteControl](RemotePoint.m.html#Iotic... | entailment |
def simulate_feeddata(self, feedid, data, mime=None, time=None):
"""Simulate the last feeddata received for given feedid
Calls the registered callback for the feed with the last recieved feed data. Allows you to test your code
without having to wait for the remote thing to share again.
... | Simulate the last feeddata received for given feedid
Calls the registered callback for the feed with the last recieved feed data. Allows you to test your code
without having to wait for the remote thing to share again.
`feedid` (required) (string) local id of your Feed
`data` (optional... | entailment |
def confirm_tell(self, data, success):
"""Confirm that you've done as you were told. Call this from your control callback to confirm action.
Used when you are advertising a control and you want to tell the remote requestor that you have
done what they asked you to.
`Example:` this is a... | Confirm that you've done as you were told. Call this from your control callback to confirm action.
Used when you are advertising a control and you want to tell the remote requestor that you have
done what they asked you to.
`Example:` this is a minimal example to show the idea. Note - no Exce... | entailment |
def save_config(self):
"""Save the config, update the seqnum & default language
"""
self.__config.set('agent', 'seqnum', self.__client.get_seqnum())
self.__config.set('agent', 'lang', self.__client.default_lang)
self.__config.save() | Save the config, update the seqnum & default language | entailment |
def _get_point_data_handler_for(self, point):
"""Used by point instances and data callbacks"""
with self.__point_data_handlers:
try:
return self.__point_data_handlers[point]
except KeyError:
return self.__point_data_handlers.setdefault(point, Point... | Used by point instances and data callbacks | entailment |
def _parsed_callback_wrapper(self, callback_parsed, callback_plain, foc, data):
"""Used to by register_catchall_*data() and Thing class (follow, create_point) to present point data as an
object."""
# used by PointDataObjectHandler as reference
if foc == R_FEED:
point_ref = da... | Used to by register_catchall_*data() and Thing class (follow, create_point) to present point data as an
object. | entailment |
def _wait_and_except_if_failed(self, event, timeout=None):
"""Combines waiting for event and call to `_except_if_failed`. If timeout is not specified the configured
sync_timeout is used.
"""
event.wait(timeout or self.__sync_timeout)
self._except_if_failed(event) | Combines waiting for event and call to `_except_if_failed`. If timeout is not specified the configured
sync_timeout is used. | entailment |
def _except_if_failed(cls, event):
"""Raises an IOTException from the given event if it was not successful. Assumes timeout success flag on event
has not been set yet."""
if event.success is None:
raise IOTSyncTimeout('Requested timed out', event)
if not event.success:
... | Raises an IOTException from the given event if it was not successful. Assumes timeout success flag on event
has not been set yet. | entailment |
def list(self, all_my_agents=False, limit=500, offset=0):
"""List `all` the things created by this client on this or all your agents
Returns QAPI list function payload
Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
if there is a communications pr... | List `all` the things created by this client on this or all your agents
Returns QAPI list function payload
Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
if there is a communications problem between you and the infrastructure
`all_my_agents` (op... | entailment |
def get_thing(self, lid):
"""Get the details of a newly created Thing. This only applies to asynchronous creation of Things and the
new Thing instance can only be retrieved once.
Returns a [Thing](Thing.m.html#IoticAgent.IOT.Thing.Thing) object,
which corresponds to the Thing with the g... | Get the details of a newly created Thing. This only applies to asynchronous creation of Things and the
new Thing instance can only be retrieved once.
Returns a [Thing](Thing.m.html#IoticAgent.IOT.Thing.Thing) object,
which corresponds to the Thing with the given local id (nickname)
Rai... | entailment |
def create_thing(self, lid):
"""Create a new Thing with a local id (lid).
Returns a [Thing](Thing.m.html#IoticAgent.IOT.Thing.Thing) object if successful
or if the Thing already exists
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing... | Create a new Thing with a local id (lid).
Returns a [Thing](Thing.m.html#IoticAgent.IOT.Thing.Thing) object if successful
or if the Thing already exists
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing the error if the infrastructure detects... | entailment |
def delete_thing(self, lid):
"""Delete a Thing
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing the error if the infrastructure detects a problem
Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
i... | Delete a Thing
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing the error if the infrastructure detects a problem
Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
if there is a communications problem betw... | entailment |
def search(self, text=None, lang=None, location=None, unit=None, limit=50, offset=0, reduced=False, local=None,
scope=SearchScope.PUBLIC):
"""Search the Iotic Space for public Things with metadata matching the search parameters:
text, lang(uage), location, unit, limit, offset. Note that o... | Search the Iotic Space for public Things with metadata matching the search parameters:
text, lang(uage), location, unit, limit, offset. Note that only things which have at least one point defined can
be found.
Returns dict of results as below (first with reduced=False, second with reduced=True)... | entailment |
def search_reduced(self, text=None, lang=None, location=None, unit=None, limit=100, offset=0, local=None,
scope=SearchScope.PUBLIC):
"""Shorthand for [search()](#IoticAgent.IOT.Client.Client.search) with `reduced=True`"""
return self.search(text, lang, location, unit, limit, offse... | Shorthand for [search()](#IoticAgent.IOT.Client.Client.search) with `reduced=True` | entailment |
def search_located(self, text=None, lang=None, location=None, unit=None, limit=100, offset=0, local=None,
scope=SearchScope.PUBLIC):
"""See [search()](#IoticAgent.IOT.Client.Client.search) for general documentation. Provides a thing-only
result set comprised only of things which h... | See [search()](#IoticAgent.IOT.Client.Client.search) for general documentation. Provides a thing-only
result set comprised only of things which have a location set, e.g.:
#!python
{
# Keyed by thing id
'2b2d8b068e404861b19f9e060877e002':
... | entailment |
def describe(self, guid_or_resource, lang=None, local=None, scope=DescribeScope.AUTO):
"""Describe returns the public (or local) description of a Thing or Point
Returns the description dict (see below for Thing example) if available, otherwise `None`
#!python
{
... | Describe returns the public (or local) description of a Thing or Point
Returns the description dict (see below for Thing example) if available, otherwise `None`
#!python
{
"type": "Entity",
"meta": {
"long": 0.716356,
... | entailment |
def from_post_request(post_request):
'''
Convenience method for creating a new OutcomeRequest from a request
object.
post_request is assumed to be a Django HttpRequest object
'''
request = OutcomeRequest()
request.post_request = post_request
request.proce... | Convenience method for creating a new OutcomeRequest from a request
object.
post_request is assumed to be a Django HttpRequest object | entailment |
def post_replace_result(self, score, result_data=None):
'''
POSTs the given score to the Tool Consumer with a replaceResult.
OPTIONAL:
result_data must be a dictionary
Note: ONLY ONE of these values can be in the dict at a time,
due to the Canvas specificatio... | POSTs the given score to the Tool Consumer with a replaceResult.
OPTIONAL:
result_data must be a dictionary
Note: ONLY ONE of these values can be in the dict at a time,
due to the Canvas specification.
'text' : str text
'url' : str url | entailment |
def post_outcome_request(self):
'''
POST an OAuth signed request to the Tool Consumer.
'''
if not self.has_required_attributes():
raise InvalidLTIConfigError(
'OutcomeRequest does not have all required attributes')
consumer = oauth2.Consumer(key=self.... | POST an OAuth signed request to the Tool Consumer. | entailment |
def process_xml(self, xml):
'''
Parse Outcome Request data from XML.
'''
root = objectify.fromstring(xml)
self.message_identifier = str(
root.imsx_POXHeader.imsx_POXRequestHeaderInfo.
imsx_messageIdentifier)
try:
result = root.imsx_POXB... | Parse Outcome Request data from XML. | entailment |
def _setup_transport(self):
"""Wrap the socket in an SSL object."""
if hasattr(self, 'sslopts'):
self.sock = ssl.wrap_socket(self.sock, **self.sslopts)
elif hasattr(self, 'sslctx'):
self.sock = self.sslctx.wrap_socket(self.sock,
... | Wrap the socket in an SSL object. | entailment |
def _shutdown_transport(self):
"""Unwrap a Python 2.6 SSL socket, so we can call shutdown()"""
if self.sock is not None:
try:
unwrap = self.sock.unwrap
except AttributeError:
return
try:
self.sock = unwrap()
... | Unwrap a Python 2.6 SSL socket, so we can call shutdown() | entailment |
def _file_loc(self):
"""_file_loc helper returns a possible config filename.
EG /tmp/stuff/fish.py -> /tmp/stuff/fish.ini
"""
if self.__fname is None:
f = os.path.splitext(os.path.basename(argv[0]))[0] + '.ini'
cwd = os.getcwd()
# todo: prefer script p... | _file_loc helper returns a possible config filename.
EG /tmp/stuff/fish.py -> /tmp/stuff/fish.ini | entailment |
def setup_logging(self):
"""Setup logging module based on known modules in the config file
"""
logging.getLogger('amqp').setLevel(str_to_logging(self.get('logging', 'amqp')))
logging.getLogger('rdflib').setLevel(str_to_logging(self.get('logging', 'rdflib'))) | Setup logging module based on known modules in the config file | entailment |
def save(self, filename=None):
"""Write config to file."""
if self.__fname is None and filename is None:
raise ValueError('Config loaded from string, no filename specified')
conf = self.__config
cpa = dict_to_cp(conf)
with open(self.__fname if filename is None else fi... | Write config to file. | entailment |
def get(self, section, val):
"""Get a setting or the default
`Returns` The current value of the setting `val` or the default, or `None` if not found
`section` (mandatory) (string) the section name in the config E.g. `"agent"`
`val` (mandatory) (string) the section name in the config E... | Get a setting or the default
`Returns` The current value of the setting `val` or the default, or `None` if not found
`section` (mandatory) (string) the section name in the config E.g. `"agent"`
`val` (mandatory) (string) the section name in the config E.g. `"host"` | entailment |
def set(self, section, val, data):
"""Add a setting to the config
`section` (mandatory) (string) the section name in the config E.g. `"agent"`
`val` (mandatory) (string) the section name in the config E.g. `"host"`
`data` (mandatory) (as appropriate) the new value for the `val`
... | Add a setting to the config
`section` (mandatory) (string) the section name in the config E.g. `"agent"`
`val` (mandatory) (string) the section name in the config E.g. `"host"`
`data` (mandatory) (as appropriate) the new value for the `val` | entailment |
def update(self, section, val, data):
"""Add a setting to the config, but if same as default or None then no action.
This saves the .save writing the defaults
`section` (mandatory) (string) the section name in the config E.g. `"agent"`
`val` (mandatory) (string) the section name in the... | Add a setting to the config, but if same as default or None then no action.
This saves the .save writing the defaults
`section` (mandatory) (string) the section name in the config E.g. `"agent"`
`val` (mandatory) (string) the section name in the config E.g. `"host"`
`data` (mandatory)... | entailment |
def get_location(self):
"""Gets the current geo location of your Thing
Returns tuple of `(lat, lon)` in `float` or `(None, None)` if location is not set for this Thing
"""
lat = None
lon = None
# note: always picks from first triple
for _, _, o in self._graph.tri... | Gets the current geo location of your Thing
Returns tuple of `(lat, lon)` in `float` or `(None, None)` if location is not set for this Thing | entailment |
def delete_location(self):
"""Deletes all the `geo:lat` and `geo:long` metadata properties on your Thing
"""
# normally this should only remove one triple each
for s, p, o in self._graph.triples((None, GEO_NS.lat, None)):
self._graph.remove((s, p, o))
for s, p, o in s... | Deletes all the `geo:lat` and `geo:long` metadata properties on your Thing | entailment |
def start(self):
"""start connection threads, blocks until started
"""
if not (self.__recv_thread or self.__send_thread):
self.__end.clear()
self.__send_ready.clear()
self.__recv_ready.clear()
timeout = self.__socket_timeout + 1
ignore_... | start connection threads, blocks until started | entailment |
def is_alive(self):
"""Helper function to show if send & recv Threads are running
"""
if self.__send_ready.is_set() and self.__recv_ready.is_set():
if self.__send_thread is not None and self.__recv_thread is not None:
return self.__send_thread.is_alive() and self.__re... | Helper function to show if send & recv Threads are running | entailment |
def stop(self):
"""disconnect, blocks until stopped
"""
self.__end.set()
if self.__recv_thread:
self.__recv_thread.join()
self.__recv_thread = None
if self.__send_thread:
self.__send_thread.join()
self.__send_thread = None | disconnect, blocks until stopped | entailment |
def send(self, body, content_type='application/ubjson', timeout=5):
"""timeout indicates amount of time to wait for sending thread to be ready. set to larger than zero to wait
(in seconds, fractional) or None to block.
"""
if self.__send_ready.wait(timeout):
try:
... | timeout indicates amount of time to wait for sending thread to be ready. set to larger than zero to wait
(in seconds, fractional) or None to block. | entailment |
def __get_ssl_context(cls, sslca=None):
"""Make an SSLConext for this Python version using public or sslca
"""
if ((version_info[0] == 2 and (version_info[1] >= 7 and version_info[2] >= 5)) or
(version_info[0] == 3 and version_info[1] >= 4)):
logger.debug('SSL method ... | Make an SSLConext for this Python version using public or sslca | entailment |
def __recv_cb(self, msg):
"""Calls user-provided callback and marks message for Ack regardless of success
"""
try:
self.__msg_callback(msg)
except:
logger.exception("AmqpLink.__recv_cb exception calling msg_callback")
finally:
# only works if a... | Calls user-provided callback and marks message for Ack regardless of success | entailment |
def __recv_run(self): # pylint: disable=too-many-branches,too-many-statements
"""Main receive thread/loop
"""
while not self.__end.is_set():
self.__unacked = 0
self.__last_id = None
try:
self.__recv_ready.clear() # Ensure event is cleared fo... | Main receive thread/loop | entailment |
def __recv_log_set_exc_and_wait(self, msg, level=None, wait_seconds=CONN_RETRY_DELAY_SECONDS):
"""Equivalent to __send_log_set_exc_and_wait but for receiver thread"""
logger.log(
((logging.DEBUG if self.__recv_exc else logging.ERROR) if level is None else level),
msg,
... | Equivalent to __send_log_set_exc_and_wait but for receiver thread | entailment |
def __recv_exc_clear(self, log_if_exc_set=None):
"""Equivalent to __send_exc_clear"""
if not (log_if_exc_set is None or self.__recv_exc is None):
logger.info(log_if_exc_set)
self.__recv_exc = None | Equivalent to __send_exc_clear | entailment |
def __send_run(self):
"""Send request thread
"""
while not self.__end.is_set():
try:
with Connection(userid=self.__prefix + self.__epid,
password=self.__passwd,
virtual_host=self.__vhost,
... | Send request thread | entailment |
def __send_log_set_exc_and_wait(self, msg, level=None, wait_seconds=CONN_RETRY_DELAY_SECONDS):
"""To be called in exception context only.
msg - message to log
level - logging level. If not specified, ERROR unless it is a repeated failure in which case DEBUG. If
specified, the given leve... | To be called in exception context only.
msg - message to log
level - logging level. If not specified, ERROR unless it is a repeated failure in which case DEBUG. If
specified, the given level will always be used.
wait_seconds - how long to pause for (so retry is not triggered immediately... | entailment |
def __send_exc_clear(self, log_if_exc_set=None):
"""Clear send exception and time. If exception was previously was set, optionally log log_if_exc_set at INFO
level.
"""
if not (log_if_exc_set is None or self.__send_exc is None):
logger.info(log_if_exc_set)
self.__send... | Clear send exception and time. If exception was previously was set, optionally log log_if_exc_set at INFO
level. | entailment |
def valid_mimetype(type_, allow_none=True):
"""Checks for validity of given type, optionally allowing for a None value. Note: Unknown idx/NUMBER notation, where
NUMBER is not a known shorthand mapping, will be rejected, i.e. type_ is valid if it
1) is an ASCII-only string between 1 & 64 characters lo... | Checks for validity of given type, optionally allowing for a None value. Note: Unknown idx/NUMBER notation, where
NUMBER is not a known shorthand mapping, will be rejected, i.e. type_ is valid if it
1) is an ASCII-only string between 1 & 64 characters long
2a) does not begin with "idx/" OR
... | entailment |
def expand_idx_mimetype(type_):
"""Returns long equivalent of type_, if available, otherwise type_ itself. Does not raise exceptions"""
if isinstance(type_, unicode_type):
match = __IDX_PATTERN.match(type_)
return __IDX_MAPPING.get(match.group(1), type_) if match else type_
else:
ret... | Returns long equivalent of type_, if available, otherwise type_ itself. Does not raise exceptions | entailment |
def throttle(self):
"""Uses time.monotonic() (or time.sleep() if not available) to limit to the desired rate. Should be called once
per iteration of action which is to be throttled. Returns None unless a custom wait_cmd was specified in the
constructor in which case its return value is used if a... | Uses time.monotonic() (or time.sleep() if not available) to limit to the desired rate. Should be called once
per iteration of action which is to be throttled. Returns None unless a custom wait_cmd was specified in the
constructor in which case its return value is used if a wait was required. | entailment |
def decode_sent_msg(pref, message, pretty=False):
"""decode_sent_msg: Return a string of the decoded message
"""
newline = "\n" if pretty else " "
indent = " " if pretty else ""
start = newline + indent
out = []
out.append("%s%s{%sSEQNUM: %d," % (pref, newline, start, message[Const.W_SEQ... | decode_sent_msg: Return a string of the decoded message | entailment |
def decode_rcvd_msg(pref, message, seqnum, pretty=False):
"""decode_rcvd_msg: Return string of received message expanding short codes, optionally with newlines and indent
"""
newline = "\n" if pretty else " "
indent = " " if pretty else ""
start = newline + indent
out = []
out.append("%s... | decode_rcvd_msg: Return string of received message expanding short codes, optionally with newlines and indent | entailment |
def _long_to_bytes(self, long_value):
"""
Turns a long value into its byte string equivalent.
:param long_value: the long value to be returned as a byte string
:return: a byte string equivalent of a long value
"""
_byte_string = b''
pack = struct.pack
whil... | Turns a long value into its byte string equivalent.
:param long_value: the long value to be returned as a byte string
:return: a byte string equivalent of a long value | entailment |
def restore_event(self, requestId):
"""restore an event based on the requestId.
For example if the user app had to shutdown with pending requests.
The user can rebuild the Events they were waiting for based on the requestId(s).
"""
with self.__requests:
if requestId ... | restore an event based on the requestId.
For example if the user app had to shutdown with pending requests.
The user can rebuild the Events they were waiting for based on the requestId(s). | entailment |
def __add_callback(self, type_, func, serialised_if_crud=True):
"""sync_if_crud indicates whether to serialise this callback (applies only to CRUD)"""
Validation.callable_check(func)
with self.__callbacks:
self.__callbacks[type_].append((func, serialised_if_crud)) | sync_if_crud indicates whether to serialise this callback (applies only to CRUD) | entailment |
def register_callback_created(self, func, serialised=True):
"""Register a callback function to receive QAPI Unsolicited (resource) CREATED. The
callback receives a single argument - the inner message. If `serialised` is not set,
the callbacks might arrive out-of-order (e.g. created point before ... | Register a callback function to receive QAPI Unsolicited (resource) CREATED. The
callback receives a single argument - the inner message. If `serialised` is not set,
the callbacks might arrive out-of-order (e.g. created point before created thing). | entailment |
def register_callback_duplicate(self, func, serialised=True):
"""Register a callback function to receive QAPI Unsolicited (resource) DUPLICATE. The
callback receives a single argument - the inner message. If `serialised` is not set,
the callbacks might arrive out-of-order.
"""
se... | Register a callback function to receive QAPI Unsolicited (resource) DUPLICATE. The
callback receives a single argument - the inner message. If `serialised` is not set,
the callbacks might arrive out-of-order. | entailment |
def register_callback_renamed(self, func, serialised=True):
"""Register a callback function to receive QAPI Unsolicited (resource) RENAMED. The
callback receives a single argument - the inner message. If `serialised` is not set,
the callbacks might arrive out-of-order.
"""
self._... | Register a callback function to receive QAPI Unsolicited (resource) RENAMED. The
callback receives a single argument - the inner message. If `serialised` is not set,
the callbacks might arrive out-of-order. | entailment |
def register_callback_deleted(self, func, serialised=True):
"""Register a callback function to receive QAPI Unsolicited (resource) DELETED. The
callback receives a single argument - the inner message. If `serialised` is not set,
the callbacks might arrive out-of-order.
"""
self._... | Register a callback function to receive QAPI Unsolicited (resource) DELETED. The
callback receives a single argument - the inner message. If `serialised` is not set,
the callbacks might arrive out-of-order. | entailment |
def register_callback_reassigned(self, func, serialised=True):
"""Register a callback function to receive QAPI Unsolicited (entity) REASSIGNED. The
callback receives a single argument - the inner message. If `serialised` is not set,
the callbacks might arrive out-of-order.
"""
se... | Register a callback function to receive QAPI Unsolicited (entity) REASSIGNED. The
callback receives a single argument - the inner message. If `serialised` is not set,
the callbacks might arrive out-of-order. | entailment |
def simulate_feeddata(self, feedid, data, mime=None, time=None):
"""Send feed data"""
# Separate public method since internal one does not require parameter checks
feedid = Validation.guid_check_convert(feedid)
mime = Validation.mime_check_convert(mime, allow_none=True)
Validatio... | Send feed data | entailment |
def start(self): # noqa (complexity)
"""Start the send & recv Threads.
Start can be delayed to EG restore requestIds before attaching to the QAPI
Note: This function waits for/blocks until amqplink connect(s) and the current
sequence number has been obtained from the container (wi... | Start the send & recv Threads.
Start can be delayed to EG restore requestIds before attaching to the QAPI
Note: This function waits for/blocks until amqplink connect(s) and the current
sequence number has been obtained from the container (within 5 seconds) | entailment |
def stop(self):
"""Stop the Client, disconnect from queue
"""
if self.__end.is_set():
return
self.__end.set()
self.__send_retry_requests_timer.cancel()
self.__threadpool.stop()
self.__crud_threadpool.stop()
self.__amqplink.stop()
self._... | Stop the Client, disconnect from queue | entailment |
def set_compression(self, comp=COMP_DEFAULT, size=COMP_SIZE):
"""Override compression method (defined by container) and threshold"""
if comp not in COMPRESSORS:
if comp == COMP_LZ4F:
raise ValueError('lz4f compression not available, required lz4framed')
else:
... | Override compression method (defined by container) and threshold | entailment |
def _request(self, resource, rtype, action=None, payload=None, offset=None, limit=None, requestId=None,
is_crud=False):
"""_request amqp queue publish helper
return: RequestEvent object or None for failed to publish
"""
end = self.__end
if end.is_set():
... | _request amqp queue publish helper
return: RequestEvent object or None for failed to publish | entailment |
def __send_ready_cb(self, last_send_failure_time):
"""Callback from AmqpLink on send transport readiness. (Only ever comes from a single thread.)"""
logger.debug('Readiness notification (last failed=%s)', last_send_failure_time)
# It is possible for multiple timers to be scheduled (if multiple t... | Callback from AmqpLink on send transport readiness. (Only ever comes from a single thread.) | entailment |
def __send_retry_requests(self, last_send_failure_time):
"""Called via Timer from __send_ready to resend requests which might not have been sent due to transport
failure. This can happen since the current transport implementation does not received acknowledgements
for sent messages."""
... | Called via Timer from __send_ready to resend requests which might not have been sent due to transport
failure. This can happen since the current transport implementation does not received acknowledgements
for sent messages. | entailment |
def request_entity_create(self, lid, epId=None):
"""request entity create: lid = local name to user
If epId=None (default), the current agent/EP is chosen
If epId=False, no agent is assigned
If epId=guid, said agent is chosen
"""
lid = Validation.lid_check_convert(lid)
... | request entity create: lid = local name to user
If epId=None (default), the current agent/EP is chosen
If epId=False, no agent is assigned
If epId=guid, said agent is chosen | entailment |
def request_entity_reassign(self, lid, nepId=None):
"""request entity to be reassigned to given ep/agent
If nepId=None (default), the current agent/EP is chosen
If nepId=False, no agent is assigned
If nepId=guid, said agent is chosen
"""
lid = Validation.lid_check_convert... | request entity to be reassigned to given ep/agent
If nepId=None (default), the current agent/EP is chosen
If nepId=False, no agent is assigned
If nepId=guid, said agent is chosen | entailment |
def request_point_create(self, foc, lid, pid, control_cb=None, save_recent=0):
"""request point create: feed or control, lid and pid point lid
"""
Validation.foc_check(foc)
lid = Validation.lid_check_convert(lid)
pid = Validation.pid_check_convert(pid)
save_recent = valid... | request point create: feed or control, lid and pid point lid | entailment |
def __point_data_to_bytes(self, data, mime=None): # pylint: disable=too-many-branches
"""Returns tuple of mime type & data. Auto encodes unicode strings (to utf8) and
dictionaries (to ubjson) depending on client setting."""
if mime is None:
if self.__auto_encode_decode:
... | Returns tuple of mime type & data. Auto encodes unicode strings (to utf8) and
dictionaries (to ubjson) depending on client setting. | entailment |
def __bytes_to_share_data(self, payload):
"""Attempt to auto-decode data"""
rbytes = payload[P_DATA]
mime = payload[P_MIME]
if mime is None or not self.__auto_encode_decode:
return rbytes, mime
mime = expand_idx_mimetype(mime).lower()
try:
if mime... | Attempt to auto-decode data | entailment |
def __new_request_id(self):
"""requestId follows form "pre num" where pre is some random ascii prefix EG 6 chars long
and num is an ever increasing number (self.__reqnum). MUST be called within self.__requests lock
"""
while True:
# Since seqnum wraps on 2^64 at most, this sh... | requestId follows form "pre num" where pre is some random ascii prefix EG 6 chars long
and num is an ever increasing number (self.__reqnum). MUST be called within self.__requests lock | entailment |
def __make_hash(cls, innermsg, token, seqnum):
"""return the hash for this innermsg, token, seqnum
return digest bytes
"""
hobj = hmacNew(token, digestmod=hashfunc)
hobj.update(innermsg)
hobj.update(cls.__byte_packer(seqnum))
return hobj.digest() | return the hash for this innermsg, token, seqnum
return digest bytes | entailment |
def __check_hash(self, message):
"""return true/false if hash is good
message = dict
"""
return message[W_HASH] == self.__make_hash(message[W_MESSAGE], self.__token, message[W_SEQ]) | return true/false if hash is good
message = dict | entailment |
def __make_innermsg(resource, rtype, ref, action=None, payload=None, limit=None):
"""return innermsg chunk (dict)
"""
if action is not None and not isinstance(action, (tuple, list)):
raise TypeError('action must be None/tuple/list')
p = {M_RESOURCE: resource,
M_T... | return innermsg chunk (dict) | entailment |
def __request_except(self, requestId, exc, set_and_forget=True):
"""Set exception (if not None) for the given request and (optionally) remove from internal cache & setting its
event"""
try:
with self.__requests:
if set_and_forget:
req = self.__r... | Set exception (if not None) for the given request and (optionally) remove from internal cache & setting its
event | entailment |
def __request_mark_sent(self, requestId):
"""Set send time & clear exception from request if set, ignoring non-existent requests"""
with self.__requests:
try:
req = self.__requests[requestId]
except KeyError:
# request might have had a response alr... | Set send time & clear exception from request if set, ignoring non-existent requests | entailment |
def __publish(self, qmsg):
"""Returns True unless sending failed (at which point an exception will have been set in the request)"""
with self.__seqnum_lock:
seqnum = self.__seqnum
self.__seqnum = (self.__seqnum + 1) % _SEQ_WRAP_SIZE
#
innermsg = ubjdumpb(qmsg.inne... | Returns True unless sending failed (at which point an exception will have been set in the request) | entailment |
def __fire_callback(self, type_, *args, **kwargs):
"""Returns True if at least one callback was called"""
called = False
plain_submit = self.__threadpool.submit
with self.__callbacks:
submit = self.__crud_threadpool.submit if type_ in _CB_CRUD_TYPES else plain_submit
... | Returns True if at least one callback was called | entailment |
def __validate_decode_msg(self, message): # noqa (complexity) pylint: disable=too-many-return-statements,too-many-branches
"""Decodes wrapper, check hash & seq, decodes body. Returns body or None, if validation / unpack failed"""
try:
if not _CONTENT_TYPE_PATTERN.match(message.content_type)... | Decodes wrapper, check hash & seq, decodes body. Returns body or None, if validation / unpack failed | entailment |
def __dispatch_msg(self, message):
"""Verify the signature and update RequestEvents / perform callbacks
Note messages with an invalid wrapper, invalid hash, invalid sequence number or unexpected clientRef
will be sent to debug_bad callback.
"""
msg = self.__validate_decode_msg(m... | Verify the signature and update RequestEvents / perform callbacks
Note messages with an invalid wrapper, invalid hash, invalid sequence number or unexpected clientRef
will be sent to debug_bad callback. | entailment |
def __handle_known_solicited(self, msg):
"""returns True if message has been handled as a solicited response"""
with self.__requests:
try:
req = self.__requests[msg[M_CLIENTREF]]
except KeyError:
return False
if self.__handle_low_seq_r... | returns True if message has been handled as a solicited response | entailment |
def __clear_references(self, request, remove_request=True):
"""Remove any internal references to the given request"""
# remove request itself
if remove_request:
with self.__requests:
self.__requests.pop(request.id_)
# remove request type specific references
... | Remove any internal references to the given request | entailment |
def __update_existing(self, msg, req):
"""Propagate changes based on type of message. MUST be called within self.__requests lock. Performs additional
actions when solicited messages arrive."""
req._messages.append(msg)
payload = msg[M_PAYLOAD]
if msg[M_TYPE] in _RSP_TYPE_CREA... | Propagate changes based on type of message. MUST be called within self.__requests lock. Performs additional
actions when solicited messages arrive. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.