_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 75
19.8k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q12900
|
ConnectAPI.delete_subscriptions
|
train
|
def delete_subscriptions(self):
"""Remove all subscriptions.
Warning: This could be slow for large numbers of connected devices.
If possible, explicitly delete subscriptions known to have been created.
:returns: None
"""
warnings.warn('This could be slow for large numbers of connected devices.'
'If possible, explicitly delete subscriptions known to have been created.')
for device in self.list_connected_devices():
try:
self.delete_device_subscriptions(device_id=device.id)
except CloudApiException as e:
LOG.warning('failed to remove subscription for %s: %s', device.id, e)
continue
|
python
|
{
"resource": ""
}
|
q12901
|
ConnectAPI.list_presubscriptions
|
train
|
def list_presubscriptions(self, **kwargs):
"""Get a list of pre-subscription data
:returns: a list of `Presubscription` objects
:rtype: list of mbed_cloud.presubscription.Presubscription
"""
api = self._get_api(mds.SubscriptionsApi)
resp = api.get_pre_subscriptions(**kwargs)
return [Presubscription(p) for p in resp]
|
python
|
{
"resource": ""
}
|
q12902
|
ConnectAPI.list_device_subscriptions
|
train
|
def list_device_subscriptions(self, device_id, **kwargs):
"""Lists all subscribed resources from a single device
:param device_id: ID of the device (Required)
:returns: a list of subscribed resources
:rtype: list of str
"""
api = self._get_api(mds.SubscriptionsApi)
resp = api.get_endpoint_subscriptions(device_id, **kwargs)
return resp.split("\n")
|
python
|
{
"resource": ""
}
|
q12903
|
ConnectAPI.delete_device_subscriptions
|
train
|
def delete_device_subscriptions(self, device_id):
"""Removes a device's subscriptions
:param device_id: ID of the device (Required)
:returns: None
"""
api = self._get_api(mds.SubscriptionsApi)
return api.delete_endpoint_subscriptions(device_id)
|
python
|
{
"resource": ""
}
|
q12904
|
ConnectAPI.notify_webhook_received
|
train
|
def notify_webhook_received(self, payload):
"""Callback function for triggering notification channel handlers.
Use this in conjunction with a webserver to complete the loop when using
webhooks as the notification channel.
:param str payload: the encoded payload, as sent by the notification channel
"""
class PayloadContainer: # noqa
# bodge to give attribute lookup
data = payload
notification = self._get_api(mds.NotificationsApi).api_client.deserialize(
PayloadContainer, mds.NotificationMessage.__name__
)
handle_channel_message(
db=self._db,
queues=self._queues,
b64decode=self.b64decode,
notification_object=notification
)
|
python
|
{
"resource": ""
}
|
q12905
|
ConnectAPI.get_webhook
|
train
|
def get_webhook(self):
"""Get the current callback URL if it exists.
:return: The currently set webhook
"""
api = self._get_api(mds.NotificationsApi)
return Webhook(api.get_webhook())
|
python
|
{
"resource": ""
}
|
q12906
|
ConnectAPI.update_webhook
|
train
|
def update_webhook(self, url, headers=None):
"""Register new webhook for incoming subscriptions.
If a webhook is already set, this will do an overwrite.
:param str url: the URL with listening webhook (Required)
:param dict headers: K/V dict with additional headers to send with request
:return: void
"""
headers = headers or {}
api = self._get_api(mds.NotificationsApi)
# Delete notifications channel
api.delete_long_poll_channel()
# Send the request to register the webhook
webhook_obj = WebhookData(url=url, headers=headers)
api.register_webhook(webhook_obj)
return
|
python
|
{
"resource": ""
}
|
q12907
|
ConnectAPI.list_metrics
|
train
|
def list_metrics(self, include=None, interval="1d", **kwargs):
"""Get statistics.
:param list[str] include: List of fields included in response.
None, or an empty list will return all fields.
Fields: transactions, successful_api_calls, failed_api_calls, successful_handshakes,
pending_bootstraps, successful_bootstraps, failed_bootstraps, registrations,
updated_registrations, expired_registrations, deleted_registrations
:param str interval: Group data by this interval in days, weeks or hours.
Sample values: 2h, 3w, 4d.
:param datetime start: Fetch the data with timestamp greater than or equal to this value.
The parameter is not mandatory, if the period is specified.
:param datetime end: Fetch the data with timestamp less than this value.
The parameter is not mandatory, if the period is specified.
:param str period: Period. Fetch the data for the period in days, weeks or hours.
Sample values: 2h, 3w, 4d.
The parameter is not mandatory, if the start and end time are specified
:param int limit: The number of devices to retrieve
:param str order: The ordering direction, ascending (asc) or descending (desc)
:param str after: Get metrics after/starting at given metric ID
:returns: a list of :py:class:`Metric` objects
:rtype: PaginatedResponse
"""
self._verify_arguments(interval, kwargs)
include = Metric._map_includes(include)
kwargs.update(dict(include=include, interval=interval))
api = self._get_api(statistics.StatisticsApi)
return PaginatedResponse(api.get_metrics, lwrap_type=Metric, **kwargs)
|
python
|
{
"resource": ""
}
|
q12908
|
EnrollmentId.enrollment_identity
|
train
|
def enrollment_identity(self, enrollment_identity):
"""
Sets the enrollment_identity of this EnrollmentId.
Enrollment identity.
:param enrollment_identity: The enrollment_identity of this EnrollmentId.
:type: str
"""
if enrollment_identity is None:
raise ValueError("Invalid value for `enrollment_identity`, must not be `None`")
if enrollment_identity is not None and not re.search('^A-[A-Za-z0-9:]{95}$', enrollment_identity):
raise ValueError("Invalid value for `enrollment_identity`, must be a follow pattern or equal to `/^A-[A-Za-z0-9:]{95}$/`")
self._enrollment_identity = enrollment_identity
|
python
|
{
"resource": ""
}
|
q12909
|
ChannelSubscription._filter_optional_keys
|
train
|
def _filter_optional_keys(self, data):
"""Filtering for this channel, based on key-value matching"""
for filter_key, filter_value in (self._optional_filters or {}).items():
data_value = data.get(filter_key)
LOG.debug(
'optional keys filter %s: %s (%s)',
filter_key, filter_value, data_value
)
if data_value is None or data_value != filter_value:
LOG.debug(
'optional keys filter rejecting %s: %s (%s)',
filter_key, filter_value, data_value
)
return False
return True
|
python
|
{
"resource": ""
}
|
q12910
|
ChannelSubscription._configure
|
train
|
def _configure(self, manager, connect_api_instance, observer_params):
"""Configure behind-the-scenes settings for the channel
These are required in addition to the parameters provided
on instantiation
"""
self._manager = manager
self._api = connect_api_instance
self._observer_params = self._observer_params or {}
self._observer_params.update(observer_params)
|
python
|
{
"resource": ""
}
|
q12911
|
ChannelSubscription.ensure_started
|
train
|
def ensure_started(self):
"""Idempotent channel start"""
if self.active:
return self
self._observer = self._observer_class(**self._observer_params)
self.start()
self._active = True
return self
|
python
|
{
"resource": ""
}
|
q12912
|
ChannelSubscription.ensure_stopped
|
train
|
def ensure_stopped(self):
"""Idempotent channel stop"""
if not self.active:
return self
self.stop()
self.observer.cancel()
self._manager.remove_routes(self, self.get_routing_keys())
self._active = False
return self
|
python
|
{
"resource": ""
}
|
q12913
|
BillingAPI.get_quota_remaining
|
train
|
def get_quota_remaining(self):
"""Get the remaining value"""
api = self._get_api(billing.DefaultApi)
quota = api.get_service_package_quota()
return None if quota is None else int(quota.quota)
|
python
|
{
"resource": ""
}
|
q12914
|
BillingAPI.get_quota_history
|
train
|
def get_quota_history(self, **kwargs):
"""Get quota usage history"""
kwargs = self._verify_sort_options(kwargs)
kwargs = self._verify_filters(kwargs, ServicePackage)
api = self._get_api(billing.DefaultApi)
return PaginatedResponse(
api.get_service_package_quota_history,
lwrap_type=QuotaHistory,
**kwargs
)
|
python
|
{
"resource": ""
}
|
q12915
|
BillingAPI.get_service_packages
|
train
|
def get_service_packages(self):
"""Get all service packages"""
api = self._get_api(billing.DefaultApi)
package_response = api.get_service_packages()
packages = []
for state in PACKAGE_STATES:
# iterate states in order
items = getattr(package_response, state) or []
for item in ensure_listable(items):
params = item.to_dict()
params['state'] = state
packages.append(ServicePackage(params))
return packages
|
python
|
{
"resource": ""
}
|
q12916
|
BillingAPI._month_converter
|
train
|
def _month_converter(self, date_time):
"""Returns Billing API format YYYY-DD"""
if not date_time:
date_time = datetime.datetime.utcnow()
if isinstance(date_time, datetime.datetime):
date_time = '%s-%02d' % (date_time.year, date_time.month)
return date_time
|
python
|
{
"resource": ""
}
|
q12917
|
BillingAPI._filepath_converter
|
train
|
def _filepath_converter(self, user_path, file_name):
"""Logic for obtaining a file path
:param user_path: a path as provided by the user. perhaps a file or directory?
:param file_name: the name of the remote file
:return:
"""
path = user_path or os.path.join(os.getcwd(), 'billing_reports', os.path.sep)
dir_specified = path.endswith(os.sep)
if dir_specified:
path = os.path.join(path, file_name)
path = os.path.abspath(path)
directory = os.path.dirname(path)
if not os.path.isdir(directory):
os.makedirs(directory)
if os.path.exists(path):
raise IOError('SDK will not write into an existing path: %r' % path)
return path
|
python
|
{
"resource": ""
}
|
q12918
|
BillingAPI.get_report_overview
|
train
|
def get_report_overview(self, month, file_path):
"""Downloads a report overview
:param month: month as datetime instance, or string in YYYY-MM format
:type month: str or datetime
:param str file_path: location to store output file
:return: outcome
:rtype: True or None
"""
api = self._get_api(billing.DefaultApi)
month = self._month_converter(month)
response = api.get_billing_report(month=month)
if file_path and response:
content = api.api_client.sanitize_for_serialization(response.to_dict())
with open(file_path, 'w') as fh:
fh.write(
json.dumps(
content,
sort_keys=True,
indent=2,
)
)
return response
|
python
|
{
"resource": ""
}
|
q12919
|
BillingAPI.get_report_firmware_updates
|
train
|
def get_report_firmware_updates(self, month=None, file_path=None):
"""Downloads a report of the firmware updates
:param str file_path: [optional] location to store output file
:param month: [default: utcnow] month as datetime instance, or string in YYYY-MM format
:type month: str or datetime
:return: The report structure
:rtype: dict
"""
api = self._get_api(billing.DefaultApi)
month = self._month_converter(month)
response = api.get_billing_report_firmware_updates(month=month)
download_url = response.url
file_path = self._filepath_converter(file_path, response.filename)
if file_path:
urllib.request.urlretrieve(download_url, file_path)
return response
|
python
|
{
"resource": ""
}
|
q12920
|
DeviceEventData.event_type
|
train
|
def event_type(self, event_type):
"""
Sets the event_type of this DeviceEventData.
Event code
:param event_type: The event_type of this DeviceEventData.
:type: str
"""
if event_type is not None and len(event_type) > 100:
raise ValueError("Invalid value for `event_type`, length must be less than or equal to `100`")
self._event_type = event_type
|
python
|
{
"resource": ""
}
|
q12921
|
ResourceValues._pattern_match
|
train
|
def _pattern_match(self, item, pattern):
"""Determine whether the item supplied is matched by the pattern."""
if pattern.endswith('*'):
return item.startswith(pattern[:-1])
else:
return item == pattern
|
python
|
{
"resource": ""
}
|
q12922
|
ResourceValues.stop
|
train
|
def stop(self):
"""Stop the channel"""
self._presubs.remove(self._sdk_presub_params)
if self._immediacy == FirstValue.on_value_update:
self._unsubscribe_all_matching()
super(ResourceValues, self).stop()
|
python
|
{
"resource": ""
}
|
q12923
|
PreSubscriptionRegistry.load_from_cloud
|
train
|
def load_from_cloud(self):
"""Sync - read"""
self.current = [
{k: v for k, v in p.to_dict().items() if v is not None}
for p in self.api.list_presubscriptions()
]
|
python
|
{
"resource": ""
}
|
q12924
|
PreSubscriptionRegistry.add
|
train
|
def add(self, items):
"""Add entry to global presubs list"""
with _presub_lock:
self.load_from_cloud()
for entry in utils.ensure_listable(items):
# add new entries, but only if they're unique
if entry not in self.current:
self.current.append(entry)
self.save_to_cloud()
|
python
|
{
"resource": ""
}
|
q12925
|
PreSubscriptionRegistry.remove
|
train
|
def remove(self, items):
"""Remove entry from global presubs list"""
with _presub_lock:
self.load_from_cloud()
for entry in utils.ensure_listable(items):
# remove all matching entries
while entry in self.current:
self.current.remove(entry)
self.save_to_cloud()
|
python
|
{
"resource": ""
}
|
q12926
|
force_utc
|
train
|
def force_utc(time, name='field', precision=6):
"""Appending 'Z' to isoformatted time - explicit timezone is required for most APIs"""
if not isinstance(time, datetime.datetime):
raise CloudValueError("%s should be of type datetime" % (name,))
clip = 6 - precision
timestring = time.isoformat()
if clip:
timestring = timestring[:-clip]
return timestring + "Z"
|
python
|
{
"resource": ""
}
|
q12927
|
catch_exceptions
|
train
|
def catch_exceptions(*exceptions):
"""Catch all exceptions provided as arguments, and raise CloudApiException instead."""
def wrap(fn):
@functools.wraps(fn)
def wrapped_f(*args, **kwargs):
try:
return fn(*args, **kwargs)
except exceptions:
t, value, traceback = sys.exc_info()
# If any resource does not exist, return None instead of raising
if str(value.status) == '404':
return None
e = CloudApiException(str(value), value.reason, value.status)
raise_(CloudApiException, e, traceback)
return wrapped_f
return wrap
|
python
|
{
"resource": ""
}
|
q12928
|
DeviceDataPostRequest.endpoint_name
|
train
|
def endpoint_name(self, endpoint_name):
"""
Sets the endpoint_name of this DeviceDataPostRequest.
The endpoint name given to the device.
:param endpoint_name: The endpoint_name of this DeviceDataPostRequest.
:type: str
"""
if endpoint_name is not None and len(endpoint_name) > 64:
raise ValueError("Invalid value for `endpoint_name`, length must be less than or equal to `64`")
self._endpoint_name = endpoint_name
|
python
|
{
"resource": ""
}
|
q12929
|
DeviceDataPostRequest.firmware_checksum
|
train
|
def firmware_checksum(self, firmware_checksum):
"""
Sets the firmware_checksum of this DeviceDataPostRequest.
The SHA256 checksum of the current firmware image.
:param firmware_checksum: The firmware_checksum of this DeviceDataPostRequest.
:type: str
"""
if firmware_checksum is not None and len(firmware_checksum) > 64:
raise ValueError("Invalid value for `firmware_checksum`, length must be less than or equal to `64`")
self._firmware_checksum = firmware_checksum
|
python
|
{
"resource": ""
}
|
q12930
|
DeviceDataPostRequest.serial_number
|
train
|
def serial_number(self, serial_number):
"""
Sets the serial_number of this DeviceDataPostRequest.
The serial number of the device.
:param serial_number: The serial_number of this DeviceDataPostRequest.
:type: str
"""
if serial_number is not None and len(serial_number) > 64:
raise ValueError("Invalid value for `serial_number`, length must be less than or equal to `64`")
self._serial_number = serial_number
|
python
|
{
"resource": ""
}
|
q12931
|
DeviceDataPostRequest.vendor_id
|
train
|
def vendor_id(self, vendor_id):
"""
Sets the vendor_id of this DeviceDataPostRequest.
The device vendor ID.
:param vendor_id: The vendor_id of this DeviceDataPostRequest.
:type: str
"""
if vendor_id is not None and len(vendor_id) > 255:
raise ValueError("Invalid value for `vendor_id`, length must be less than or equal to `255`")
self._vendor_id = vendor_id
|
python
|
{
"resource": ""
}
|
q12932
|
main
|
train
|
def main():
"""Collects results from CI run"""
source_files = (
('integration', r'results/results.xml'),
('unittests', r'results/unittests.xml'),
('coverage', r'results/coverage.xml')
)
parsed = {k: ElementTree.parse(v).getroot().attrib for k, v in source_files}
with open(r'results/summary.json', 'w') as fh:
json.dump(parsed, fh)
|
python
|
{
"resource": ""
}
|
q12933
|
DeviceDirectoryAPI.list_devices
|
train
|
def list_devices(self, **kwargs):
"""List devices in the device catalog.
Example usage, listing all registered devices in the catalog:
.. code-block:: python
filters = { 'state': {'$eq': 'registered' } }
devices = api.list_devices(order='asc', filters=filters)
for idx, d in enumerate(devices):
print(idx, d.id)
:param int limit: The number of devices to retrieve.
:param str order: The ordering direction, ascending (asc) or
descending (desc)
:param str after: Get devices after/starting at given `device_id`
:param filters: Dictionary of filters to apply.
:returns: a list of :py:class:`Device` objects registered in the catalog.
:rtype: PaginatedResponse
"""
kwargs = self._verify_sort_options(kwargs)
kwargs = self._verify_filters(kwargs, Device, True)
api = self._get_api(device_directory.DefaultApi)
return PaginatedResponse(api.device_list, lwrap_type=Device, **kwargs)
|
python
|
{
"resource": ""
}
|
q12934
|
DeviceDirectoryAPI.get_device
|
train
|
def get_device(self, device_id):
"""Get device details from catalog.
:param str device_id: the ID of the device to retrieve (Required)
:returns: device object matching the `device_id`.
:rtype: Device
"""
api = self._get_api(device_directory.DefaultApi)
return Device(api.device_retrieve(device_id))
|
python
|
{
"resource": ""
}
|
q12935
|
DeviceDirectoryAPI.update_device
|
train
|
def update_device(self, device_id, **kwargs):
"""Update existing device in catalog.
.. code-block:: python
existing_device = api.get_device(...)
updated_device = api.update_device(
existing_device.id,
certificate_fingerprint = "something new"
)
:param str device_id: The ID of the device to update (Required)
:param obj custom_attributes: Up to 5 custom JSON attributes
:param str description: The description of the device
:param str name: The name of the device
:param str alias: The alias of the device
:param str device_type: The endpoint type of the device - e.g. if the device is a gateway
:param str host_gateway: The endpoint_name of the host gateway, if appropriate
:param str certificate_fingerprint: Fingerprint of the device certificate
:param str certificate_issuer_id: ID of the issuer of the certificate
:returns: the updated device object
:rtype: Device
"""
api = self._get_api(device_directory.DefaultApi)
device = Device._create_request_map(kwargs)
body = DeviceDataPostRequest(**device)
return Device(api.device_update(device_id, body))
|
python
|
{
"resource": ""
}
|
q12936
|
DeviceDirectoryAPI.add_device
|
train
|
def add_device(self, **kwargs):
"""Add a new device to catalog.
.. code-block:: python
device = {
"mechanism": "connector",
"certificate_fingerprint": "<certificate>",
"name": "New device name",
"certificate_issuer_id": "<id>"
}
resp = api.add_device(**device)
print(resp.created_at)
:param str certificate_fingerprint: Fingerprint of the device certificate
:param str certificate_issuer_id: ID of the issuer of the certificate
:param str name: The name of the device
:param str account_id: The owning Identity and Access Managment (IAM) account ID
:param obj custom_attributes: Up to 5 custom JSON attributes
:param str description: The description of the device
:param str device_class: Class of the device
:param str id: The ID of the device
:param str manifest_url: URL for the current device manifest
:param str mechanism: The ID of the channel used to communicate with the device
:param str mechanism_url: The address of the connector to use
:param str serial_number: The serial number of the device
:param str state: The current state of the device
:param int trust_class: The device trust class
:param str vendor_id: The device vendor ID
:param str alias: The alias of the device
:parama str device_type: The endpoint type of the device - e.g. if the device is a gateway
:param str host_gateway: The endpoint_name of the host gateway, if appropriate
:param datetime bootstrap_certificate_expiration:
:param datetime connector_certificate_expiration: Expiration date of the certificate
used to connect to connector server
:param int device_execution_mode: The device class
:param str firmware_checksum: The SHA256 checksum of the current firmware image
:param datetime manifest_timestamp: The timestamp of the current manifest version
:return: the newly created device object.
:rtype: Device
"""
api = self._get_api(device_directory.DefaultApi)
device = Device._create_request_map(kwargs)
device = DeviceData(**device)
return Device(api.device_create(device))
|
python
|
{
"resource": ""
}
|
q12937
|
DeviceDirectoryAPI.delete_device
|
train
|
def delete_device(self, device_id):
"""Delete device from catalog.
:param str device_id: ID of device in catalog to delete (Required)
:return: void
"""
api = self._get_api(device_directory.DefaultApi)
return api.device_destroy(id=device_id)
|
python
|
{
"resource": ""
}
|
q12938
|
DeviceDirectoryAPI.list_queries
|
train
|
def list_queries(self, **kwargs):
"""List queries in device query service.
:param int limit: The number of devices to retrieve.
:param str order: The ordering direction, ascending (asc) or
descending (desc)
:param str after: Get devices after/starting at given `device_id`
:param filters: Dictionary of filters to apply.
:returns: a list of :py:class:`Query` objects.
:rtype: PaginatedResponse
"""
kwargs = self._verify_sort_options(kwargs)
kwargs = self._verify_filters(kwargs, Query, True)
api = self._get_api(device_directory.DefaultApi)
return PaginatedResponse(api.device_query_list, lwrap_type=Query, **kwargs)
|
python
|
{
"resource": ""
}
|
q12939
|
DeviceDirectoryAPI.add_query
|
train
|
def add_query(self, name, filter, **kwargs):
"""Add a new query to device query service.
.. code-block:: python
f = api.add_query(
name = "Query name",
filter = {
"device_id": {"$eq": "01234"},
custom_attributes = {
"foo": {"$eq": "bar"}
}
}
)
print(f.created_at)
:param str name: Name of query (Required)
:param dict filter: Filter properties to apply (Required)
:param return: The newly created query object.
:return: the newly created query object
:rtype: Query
"""
# Ensure we have the correct types and get the new query object
filter_obj = filters.legacy_filter_formatter(
dict(filter=filter),
Device._get_attributes_map()
) if filter else None
query_map = Query._create_request_map(kwargs)
# Create the DeviceQuery object
f = DeviceQuery(name=name, query=filter_obj['filter'], **query_map)
api = self._get_api(device_directory.DefaultApi)
return Query(api.device_query_create(f))
|
python
|
{
"resource": ""
}
|
q12940
|
DeviceDirectoryAPI.update_query
|
train
|
def update_query(self, query_id, name=None, filter=None, **kwargs):
"""Update existing query in device query service.
.. code-block:: python
q = api.get_query(...)
q.filter["custom_attributes"]["foo"] = {
"$eq": "bar"
}
new_q = api.update_query(
query_id = q.id,
name = "new name",
filter = q.filter
)
:param str query_id: Existing query ID to update (Required)
:param str name: name of query
:param dict filter: query properties to apply
:return: the newly updated query object.
:rtype: Query
"""
# Get urlencoded query attribute
filter_obj = filters.legacy_filter_formatter(
dict(filter=filter),
Device._get_attributes_map()
) if filter else None
query_map = Query._create_request_map(kwargs)
# The filter option is optional on update but DeviceQueryPostPutRequest sets it None, which is invalid.
# Manually create a resource body without the filter parameter if only the name is provided.
if filter is None:
body = {"name": name}
else:
body = DeviceQueryPostPutRequest(name=name, query=filter_obj['filter'], **query_map)
api = self._get_api(device_directory.DefaultApi)
return Query(api.device_query_update(query_id, body))
|
python
|
{
"resource": ""
}
|
q12941
|
DeviceDirectoryAPI.delete_query
|
train
|
def delete_query(self, query_id):
"""Delete query in device query service.
:param int query_id: ID of the query to delete (Required)
:return: void
"""
api = self._get_api(device_directory.DefaultApi)
api.device_query_destroy(query_id)
return
|
python
|
{
"resource": ""
}
|
q12942
|
DeviceDirectoryAPI.get_query
|
train
|
def get_query(self, query_id):
"""Get query in device query service.
:param int query_id: ID of the query to get (Required)
:returns: device query object
:rtype: Query
"""
api = self._get_api(device_directory.DefaultApi)
return Query(api.device_query_retrieve(query_id))
|
python
|
{
"resource": ""
}
|
q12943
|
DeviceDirectoryAPI.list_device_events
|
train
|
def list_device_events(self, **kwargs):
"""List all device logs.
:param int limit: The number of logs to retrieve.
:param str order: The ordering direction, ascending (asc) or
descending (desc)
:param str after: Get logs after/starting at given `device_event_id`
:param dict filters: Dictionary of filters to apply.
:return: list of :py:class:`DeviceEvent` objects
:rtype: PaginatedResponse
"""
kwargs = self._verify_sort_options(kwargs)
kwargs = self._verify_filters(kwargs, DeviceEvent, True)
api = self._get_api(device_directory.DefaultApi)
return PaginatedResponse(api.device_log_list, lwrap_type=DeviceEvent, **kwargs)
|
python
|
{
"resource": ""
}
|
q12944
|
DeviceDirectoryAPI.get_device_event
|
train
|
def get_device_event(self, device_event_id):
"""Get device event with provided ID.
:param int device_event_id: id of the event to get (Required)
:rtype: DeviceEvent
"""
api = self._get_api(device_directory.DefaultApi)
return DeviceEvent(api.device_log_retrieve(device_event_id))
|
python
|
{
"resource": ""
}
|
q12945
|
Query.filter
|
train
|
def filter(self):
"""Get the query of this Query.
The device query
:return: The query of this Query.
:rtype: dict
"""
if isinstance(self._filter, str):
return self._decode_query(self._filter)
return self._filter
|
python
|
{
"resource": ""
}
|
q12946
|
get_metadata
|
train
|
def get_metadata(item):
"""Get metadata information from the distribution.
Depending on the package this may either be in METADATA or PKG-INFO
:param item: pkg_resources WorkingSet item
:returns: metadata resource as list of non-blank non-comment lines
"""
for metadata_key in ('METADATA', 'PKG-INFO'):
try:
metadata_lines = item.get_metadata_lines(metadata_key)
break
except (KeyError, IOError):
# The package will be shown in the report without any license information
# if a metadata key is not found.
metadata_lines = []
return metadata_lines
|
python
|
{
"resource": ""
}
|
q12947
|
license_cleanup
|
train
|
def license_cleanup(text):
"""Tidy up a license string
e.g. "::OSI:: mit software license" -> "MIT"
"""
if not text:
return None
text = text.rsplit(':', 1)[-1]
replacements = [
'licenses',
'license',
'licences',
'licence',
'software',
',',
]
for replacement in replacements:
text = text.replace(replacement, '')
text = text.strip().upper()
text = text.replace(' ', '_')
text = text.replace('-', '_')
if any(trigger.upper() in text for trigger in BAD_LICENSES):
return None
return text
|
python
|
{
"resource": ""
}
|
q12948
|
get_package_info_from_line
|
train
|
def get_package_info_from_line(tpip_pkg, line):
"""Given a line of text from metadata, extract semantic info"""
lower_line = line.lower()
try:
metadata_key, metadata_value = lower_line.split(':', 1)
except ValueError:
return
metadata_key = metadata_key.strip()
metadata_value = metadata_value.strip()
if metadata_value == 'unknown':
return
# extract exact matches
if metadata_key in TPIP_FIELD_MAPPINGS:
tpip_pkg[TPIP_FIELD_MAPPINGS[metadata_key]] = metadata_value
return
if metadata_key.startswith('version') and not tpip_pkg.get('PkgVersion'):
# ... but if not, we'll use whatever we find
tpip_pkg['PkgVersion'] = metadata_value
return
# Handle british and american spelling of licence/license
if 'licen' in lower_line:
if metadata_key.startswith('classifier') or '::' in metadata_value:
license = lower_line.rsplit(':')[-1].strip().lower()
license = license_cleanup(license)
if license:
tpip_pkg.setdefault('PkgLicenses', []).append(license)
|
python
|
{
"resource": ""
}
|
q12949
|
process_metadata
|
train
|
def process_metadata(pkg_name, metadata_lines):
"""Create a dictionary containing the relevant fields.
The following is an example of the generated dictionary:
:Example:
{
'name': 'six',
'version': '1.11.0',
'repository': 'pypi.python.org/pypi/six',
'licence': 'MIT',
'classifier': 'MIT License'
}
:param str pkg_name: name of the package
:param metadata_lines: metadata resource as list of non-blank non-comment lines
:returns: Dictionary of each of the fields
:rtype: Dict[str, str]
"""
# Initialise a dictionary with all the fields to report on.
tpip_pkg = dict(
PkgName=pkg_name,
PkgType='python package',
PkgMgrURL='https://pypi.org/project/%s/' % pkg_name,
)
# Extract the metadata into a list for each field as there may be multiple
# entries for each one.
for line in metadata_lines:
get_package_info_from_line(tpip_pkg, line)
# condense PkgAuthorEmail into the Originator field
if 'PkgAuthorEmail' in tpip_pkg:
tpip_pkg['PkgOriginator'] = '%s <%s>' % (
tpip_pkg['PkgOriginator'],
tpip_pkg.pop('PkgAuthorEmail')
)
explicit_license = license_cleanup(tpip_pkg.get('PkgLicense'))
license_candidates = tpip_pkg.pop('PkgLicenses', [])
if explicit_license:
tpip_pkg['PkgLicense'] = explicit_license
else:
tpip_pkg['PkgLicense'] = ' '.join(set(license_candidates))
return tpip_pkg
|
python
|
{
"resource": ""
}
|
q12950
|
write_csv_file
|
train
|
def write_csv_file(output_filename, tpip_pkgs):
"""Write the TPIP report out to a CSV file.
:param str output_filename: filename for CSV.
:param List tpip_pkgs: a list of dictionaries compatible with DictWriter.
"""
dirname = os.path.dirname(os.path.abspath(os.path.expanduser(output_filename)))
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
with open(output_filename, 'w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=FIELDNAMES)
writer.writeheader()
writer.writerows(tpip_pkgs)
|
python
|
{
"resource": ""
}
|
q12951
|
force_ascii_values
|
train
|
def force_ascii_values(data):
"""Ensures each value is ascii-only"""
return {
k: v.encode('utf8').decode('ascii', 'backslashreplace')
for k, v in data.items()
}
|
python
|
{
"resource": ""
}
|
q12952
|
main
|
train
|
def main():
"""Generate a TPIP report."""
parser = argparse.ArgumentParser(description='Generate a TPIP report as a CSV file.')
parser.add_argument('output_filename', type=str, metavar='output-file',
help='the output path and filename', nargs='?')
parser.add_argument('--only', type=str, help='only parse this package')
args = parser.parse_args()
output_path = os.path.abspath(args.output_filename) if args.output_filename else None
skips = []
tpip_pkgs = []
for pkg_name, pkg_item in sorted(pkg_resources.working_set.by_key.items()):
if args.only and args.only not in pkg_name.lower():
continue
if pkg_name in EXCLUDED_PACKAGES:
skips.append(pkg_name)
continue
metadata_lines = get_metadata(pkg_item)
tpip_pkg = process_metadata(pkg_name, metadata_lines)
tpip_pkgs.append(force_ascii_values(tpip_pkg))
print(json.dumps(tpip_pkgs, indent=2, sort_keys=True))
print('Parsed %s packages\nOutput to CSV: `%s`\nIgnored packages: %s' % (
len(tpip_pkgs),
output_path,
', '.join(skips),
))
output_path and write_csv_file(output_path, tpip_pkgs)
|
python
|
{
"resource": ""
}
|
q12953
|
ServicePackageMetadata.remaining_quota
|
train
|
def remaining_quota(self, remaining_quota):
"""
Sets the remaining_quota of this ServicePackageMetadata.
Current available service package quota.
:param remaining_quota: The remaining_quota of this ServicePackageMetadata.
:type: int
"""
if remaining_quota is None:
raise ValueError("Invalid value for `remaining_quota`, must not be `None`")
if remaining_quota is not None and remaining_quota < 0:
raise ValueError("Invalid value for `remaining_quota`, must be a value greater than or equal to `0`")
self._remaining_quota = remaining_quota
|
python
|
{
"resource": ""
}
|
q12954
|
ServicePackageMetadata.reserved_quota
|
train
|
def reserved_quota(self, reserved_quota):
"""
Sets the reserved_quota of this ServicePackageMetadata.
Sum of all open reservations for this account.
:param reserved_quota: The reserved_quota of this ServicePackageMetadata.
:type: int
"""
if reserved_quota is None:
raise ValueError("Invalid value for `reserved_quota`, must not be `None`")
if reserved_quota is not None and reserved_quota < 0:
raise ValueError("Invalid value for `reserved_quota`, must be a value greater than or equal to `0`")
self._reserved_quota = reserved_quota
|
python
|
{
"resource": ""
}
|
q12955
|
UpdateCampaignPutRequest.root_manifest_id
|
train
|
def root_manifest_id(self, root_manifest_id):
"""
Sets the root_manifest_id of this UpdateCampaignPutRequest.
:param root_manifest_id: The root_manifest_id of this UpdateCampaignPutRequest.
:type: str
"""
if root_manifest_id is not None and len(root_manifest_id) > 32:
raise ValueError("Invalid value for `root_manifest_id`, length must be less than or equal to `32`")
self._root_manifest_id = root_manifest_id
|
python
|
{
"resource": ""
}
|
q12956
|
UpdateCampaignPutRequest.state
|
train
|
def state(self, state):
"""
Sets the state of this UpdateCampaignPutRequest.
The state of the campaign
:param state: The state of this UpdateCampaignPutRequest.
:type: str
"""
allowed_values = ["draft", "scheduled", "allocatingquota", "allocatedquota", "quotaallocationfailed", "checkingmanifest", "checkedmanifest", "devicefetch", "devicecopy", "devicecheck", "publishing", "deploying", "deployed", "manifestremoved", "expired", "stopping", "autostopped", "userstopped", "conflict"]
if state not in allowed_values:
raise ValueError(
"Invalid value for `state` ({0}), must be one of {1}"
.format(state, allowed_values)
)
self._state = state
|
python
|
{
"resource": ""
}
|
q12957
|
Observer.notify
|
train
|
def notify(self, data):
"""Notify this observer that data has arrived"""
LOG.debug('notify received: %s', data)
self._notify_count += 1
if self._cancelled:
LOG.debug('notify skipping due to `cancelled`')
return self
if self._once_done and self._once:
LOG.debug('notify skipping due to `once`')
return self
with self._lock:
try:
# notify next consumer immediately
self._waitables.get_nowait().put_nowait(data)
LOG.debug('found a consumer, notifying')
except queue.Empty:
# store the notification
try:
self._notifications.put_nowait(data)
LOG.debug('no consumers, queueing data')
except queue.Full:
LOG.warning('notification queue full - discarding new data')
# callbacks are sent straight away
# bombproofing should be handled by individual callbacks
for callback in self._callbacks:
LOG.debug('callback: %s', callback)
callback(data)
self._once_done = True
return self
|
python
|
{
"resource": ""
}
|
q12958
|
Observer.cancel
|
train
|
def cancel(self):
"""Cancels the observer
No more notifications will be passed on
"""
LOG.debug('cancelling %s', self)
self._cancelled = True
self.clear_callbacks() # not strictly necessary, but may release references
while True:
try:
self._waitables.get_nowait().put_nowait(self.sentinel)
except queue.Empty:
break
|
python
|
{
"resource": ""
}
|
q12959
|
CfsslAuthCredentials.hmac_hex_key
|
train
|
def hmac_hex_key(self, hmac_hex_key):
"""
Sets the hmac_hex_key of this CfsslAuthCredentials.
The key that is used to compute the HMAC of the request using the HMAC-SHA-256 algorithm. Must contain an even number of hexadecimal characters.
:param hmac_hex_key: The hmac_hex_key of this CfsslAuthCredentials.
:type: str
"""
if hmac_hex_key is None:
raise ValueError("Invalid value for `hmac_hex_key`, must not be `None`")
if hmac_hex_key is not None and len(hmac_hex_key) > 64:
raise ValueError("Invalid value for `hmac_hex_key`, length must be less than or equal to `64`")
if hmac_hex_key is not None and not re.search('^([a-fA-F0-9][a-fA-F0-9]){1,32}$', hmac_hex_key):
raise ValueError("Invalid value for `hmac_hex_key`, must be a follow pattern or equal to `/^([a-fA-F0-9][a-fA-F0-9]){1,32}$/`")
self._hmac_hex_key = hmac_hex_key
|
python
|
{
"resource": ""
}
|
q12960
|
DeviceQueryPostPutRequest.name
|
train
|
def name(self, name):
"""
Sets the name of this DeviceQueryPostPutRequest.
The name of the query.
:param name: The name of this DeviceQueryPostPutRequest.
:type: str
"""
if name is None:
raise ValueError("Invalid value for `name`, must not be `None`")
if name is not None and len(name) > 200:
raise ValueError("Invalid value for `name`, length must be less than or equal to `200`")
self._name = name
|
python
|
{
"resource": ""
}
|
q12961
|
DeviceQueryPostPutRequest.query
|
train
|
def query(self, query):
"""
Sets the query of this DeviceQueryPostPutRequest.
The device query.
:param query: The query of this DeviceQueryPostPutRequest.
:type: str
"""
if query is None:
raise ValueError("Invalid value for `query`, must not be `None`")
if query is not None and len(query) > 1000:
raise ValueError("Invalid value for `query`, length must be less than or equal to `1000`")
self._query = query
|
python
|
{
"resource": ""
}
|
q12962
|
AccountManagementAPI.list_api_keys
|
train
|
def list_api_keys(self, **kwargs):
"""List the API keys registered in the organisation.
List api keys Example:
.. code-block:: python
account_management_api = AccountManagementAPI()
# List api keys
api_keys_paginated_response = account_management_api.list_api_keys()
# get single api key
api_keys_paginated_response.data[0]
:param int limit: Number of API keys to get
:param str after: Entity ID after which to start fetching
:param str order: Order of the records to return (asc|desc)
:param dict filters: Dictionary of filters to apply: str owner (eq)
:returns: a list of :class:`ApiKey` objects
:rtype: PaginatedResponse
:raises: ApiException
"""
kwargs = self._verify_sort_options(kwargs)
kwargs = self._verify_filters(kwargs, ApiKey)
api = self._get_api(iam.DeveloperApi)
# Return the data array
return PaginatedResponse(api.get_all_api_keys, lwrap_type=ApiKey, **kwargs)
|
python
|
{
"resource": ""
}
|
q12963
|
AccountManagementAPI.get_api_key
|
train
|
def get_api_key(self, api_key_id):
"""Get API key details for key registered in organisation.
:param str api_key_id: The ID of the API key to be updated (Required)
:returns: API key object
:rtype: ApiKey
"""
api = self._get_api(iam.DeveloperApi)
return ApiKey(api.get_api_key(api_key_id))
|
python
|
{
"resource": ""
}
|
q12964
|
AccountManagementAPI.delete_api_key
|
train
|
def delete_api_key(self, api_key_id):
"""Delete an API key registered in the organisation.
:param str api_key_id: The ID of the API key (Required)
:returns: void
"""
api = self._get_api(iam.DeveloperApi)
api.delete_api_key(api_key_id)
return
|
python
|
{
"resource": ""
}
|
q12965
|
AccountManagementAPI.add_api_key
|
train
|
def add_api_key(self, name, **kwargs):
"""Create new API key registered to organisation.
:param str name: The name of the API key (Required)
:param list groups: List of group IDs (`str`)
:param str owner: User ID owning the API key
:param str status: The status of the API key. Values: ACTIVE, INACTIVE
:returns: Newly created API key object
:rtype: ApiKey
"""
api = self._get_api(iam.DeveloperApi)
kwargs.update({'name': name})
api_key = ApiKey._create_request_map(kwargs)
body = iam.ApiKeyInfoReq(**api_key)
return ApiKey(api.create_api_key(body))
|
python
|
{
"resource": ""
}
|
q12966
|
AccountManagementAPI.update_api_key
|
train
|
def update_api_key(self, api_key_id, **kwargs):
"""Update API key.
:param str api_key_id: The ID of the API key to be updated (Required)
:param str name: The name of the API key
:param str owner: User ID owning the API key
:param str status: The status of the API key. Values: ACTIVE, INACTIVE
:returns: Newly created API key object
:rtype: ApiKey
"""
api = self._get_api(iam.DeveloperApi)
apikey = ApiKey._create_request_map(kwargs)
body = iam.ApiKeyUpdateReq(**apikey)
return ApiKey(api.update_api_key(api_key_id, body))
|
python
|
{
"resource": ""
}
|
q12967
|
AccountManagementAPI.list_users
|
train
|
def list_users(self, **kwargs):
"""List all users in organisation.
:param int limit: The number of users to retrieve
:param str order: The ordering direction, ascending (asc) or descending (desc)
:param str after: Get users after/starting at given user ID
:param dict filters: Dictionary of filters to apply: str status (eq)
:returns: a list of :py:class:`User` objects
:rtype: PaginatedResponse
"""
kwargs = self._verify_sort_options(kwargs)
kwargs = self._verify_filters(kwargs, User)
api = self._get_api(iam.AccountAdminApi)
return PaginatedResponse(api.get_all_users, lwrap_type=User, **kwargs)
|
python
|
{
"resource": ""
}
|
q12968
|
AccountManagementAPI.get_user
|
train
|
def get_user(self, user_id):
"""Get user details of specified user.
:param str user_id: the ID of the user to get (Required)
:returns: the user object with details about the user.
:rtype: User
"""
api = self._get_api(iam.AccountAdminApi)
return User(api.get_user(user_id))
|
python
|
{
"resource": ""
}
|
q12969
|
AccountManagementAPI.update_user
|
train
|
def update_user(self, user_id, **kwargs):
"""Update user properties of specified user.
:param str user_id: The ID of the user to update (Required)
:param str username: The unique username of the user
:param str email: The unique email of the user
:param str full_name: The full name of the user
:param str password: The password string of the user.
:param str phone_number: Phone number of the user
:param bool terms_accepted: Is 'General Terms & Conditions' accepted
:param bool marketing_accepted: Is receiving marketing information accepted?
:returns: the updated user object
:rtype: User
"""
api = self._get_api(iam.AccountAdminApi)
user = User._create_request_map(kwargs)
body = iam.UserUpdateReq(**user)
return User(api.update_user(user_id, body))
|
python
|
{
"resource": ""
}
|
q12970
|
AccountManagementAPI.delete_user
|
train
|
def delete_user(self, user_id):
"""Delete user specified user.
:param str user_id: the ID of the user to delete (Required)
:returns: void
"""
api = self._get_api(iam.AccountAdminApi)
api.delete_user(user_id)
return
|
python
|
{
"resource": ""
}
|
q12971
|
AccountManagementAPI.add_user
|
train
|
def add_user(self, username, email, **kwargs):
"""Create a new user with provided details.
Add user example:
.. code-block:: python
account_management_api = AccountManagementAPI()
# Add user
user = {
"username": "test_user",
"email": "test@gmail.com",
"phone_number": "0123456789"
}
new_user = account_management_api.add_user(**user)
:param str username: The unique username of the user (Required)
:param str email: The unique email of the user (Required)
:param str full_name: The full name of the user
:param list groups: List of group IDs (`str`) which this user belongs to
:param str password: The password string of the user
:param str phone_number: Phone number of the user
:param bool terms_accepted: 'General Terms & Conditions' have been accepted
:param bool marketing_accepted: Marketing Information opt-in
:returns: the new user object
:rtype: User
"""
api = self._get_api(iam.AccountAdminApi)
kwargs.update({'username': username, 'email': email})
user = User._create_request_map(kwargs)
body = iam.UserUpdateReq(**user)
return User(api.create_user(body))
|
python
|
{
"resource": ""
}
|
q12972
|
AccountManagementAPI.get_account
|
train
|
def get_account(self):
"""Get details of the current account.
:returns: an account object.
:rtype: Account
"""
api = self._get_api(iam.DeveloperApi)
return Account(api.get_my_account_info(include="limits, policies"))
|
python
|
{
"resource": ""
}
|
q12973
|
AccountManagementAPI.update_account
|
train
|
def update_account(self, **kwargs):
"""Update details of account associated with current API key.
:param str address_line1: Postal address line 1.
:param str address_line2: Postal address line 2.
:param str city: The city part of the postal address.
:param str display_name: The display name for the account.
:param str country: The country part of the postal address.
:param str company: The name of the company.
:param str state: The state part of the postal address.
:param str contact: The name of the contact person for this account.
:param str postal_code: The postal code part of the postal address.
:param str parent_id: The ID of the parent account.
:param str phone_number: The phone number of the company.
:param str email: Email address for this account.
:param list[str] aliases: List of aliases
:returns: an account object.
:rtype: Account
"""
api = self._get_api(iam.AccountAdminApi)
account = Account._create_request_map(kwargs)
body = AccountUpdateReq(**account)
return Account(api.update_my_account(body))
|
python
|
{
"resource": ""
}
|
q12974
|
AccountManagementAPI.list_groups
|
train
|
def list_groups(self, **kwargs):
"""List all groups in organisation.
:param int limit: The number of groups to retrieve
:param str order: The ordering direction, ascending (asc) or descending (desc)
:param str after: Get groups after/starting at given group ID
:returns: a list of :py:class:`Group` objects.
:rtype: PaginatedResponse
"""
kwargs = self._verify_sort_options(kwargs)
api = self._get_api(iam.DeveloperApi)
return PaginatedResponse(api.get_all_groups, lwrap_type=Group, **kwargs)
|
python
|
{
"resource": ""
}
|
q12975
|
AccountManagementAPI.get_group
|
train
|
def get_group(self, group_id):
"""Get details of the group.
:param str group_id: The group ID (Required)
:returns: :py:class:`Group` object.
:rtype: Group
"""
api = self._get_api(iam.DeveloperApi)
return Group(api.get_group_summary(group_id))
|
python
|
{
"resource": ""
}
|
q12976
|
AccountManagementAPI.list_group_users
|
train
|
def list_group_users(self, group_id, **kwargs):
"""List users of a group.
:param str group_id: The group ID (Required)
:param int limit: The number of users to retrieve
:param str order: The ordering direction, ascending (asc) or descending (desc)
:param str after: Get API keys after/starting at given user ID
:returns: a list of :py:class:`User` objects.
:rtype: PaginatedResponse
"""
kwargs["group_id"] = group_id
kwargs = self._verify_sort_options(kwargs)
api = self._get_api(iam.AccountAdminApi)
return PaginatedResponse(api.get_users_of_group, lwrap_type=User, **kwargs)
|
python
|
{
"resource": ""
}
|
q12977
|
AccountManagementAPI.list_group_api_keys
|
train
|
def list_group_api_keys(self, group_id, **kwargs):
"""List API keys of a group.
:param str group_id: The group ID (Required)
:param int limit: The number of api keys to retrieve.
:param str order: The ordering direction, ascending (asc) or descending (desc).
:param str after: Get API keys after/starting at given api key ID.
:returns: a list of :py:class:`ApiKey` objects.
:rtype: PaginatedResponse
"""
kwargs["group_id"] = group_id
kwargs = self._verify_sort_options(kwargs)
api = self._get_api(iam.DeveloperApi)
return PaginatedResponse(api.get_api_keys_of_group, lwrap_type=ApiKey, **kwargs)
|
python
|
{
"resource": ""
}
|
q12978
|
AsyncWrapper.defer
|
train
|
def defer(self, *args, **kwargs):
"""Call the function and immediately return an asynchronous object.
The calling code will need to check for the result at a later time using:
In Python 2/3 using ThreadPools - an AsyncResult
(https://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.AsyncResult)
In Python 3 using Asyncio - a Future
(https://docs.python.org/3/library/asyncio-task.html#future)
:param args:
:param kwargs:
:return:
"""
LOG.debug(
'%s on %s (awaitable %s async %s provider %s)',
'deferring',
self._func,
self._is_awaitable,
self._is_asyncio_provider,
self._concurrency_provider
)
if self._blocked:
raise RuntimeError('Already activated this deferred call by blocking on it')
with self._lock:
if not self._deferable:
func_partial = functools.partial(self._func, *args, **kwargs)
# we are either:
# - pure asyncio
# - asyncio but with blocking function
# - not asyncio, use threadpool
self._deferable = (
# pure asyncio
asyncio.ensure_future(func_partial(), loop=self._concurrency_provider)
if self._is_awaitable else (
# asyncio blocked
self._concurrency_provider.run_in_executor(
func=func_partial,
executor=None
)
if self._is_asyncio_provider else (
# not asyncio
self._concurrency_provider.apply_async(func_partial)
)
)
)
return self._deferable
|
python
|
{
"resource": ""
}
|
q12979
|
AsyncWrapper.block
|
train
|
def block(self, *args, **kwargs):
"""Call the wrapped function, and wait for the result in a blocking fashion
Returns the result of the function call.
:param args:
:param kwargs:
:return: result of function call
"""
LOG.debug(
'%s on %s (awaitable %s async %s provider %s)',
'blocking',
self._func,
self._is_awaitable,
self._is_asyncio_provider,
self._concurrency_provider
)
if self._deferable:
raise RuntimeError('Already activated this call by deferring it')
with self._lock:
if not hasattr(self, '_result'):
try:
self._result = (
self._concurrency_provider.run_until_complete(self.defer(*args, **kwargs))
if self._is_asyncio_provider else self._func(*args, **kwargs)
)
except queue.Empty:
raise CloudTimeoutError("No data received after %.1f seconds." % kwargs.get("timeout", 0))
self._blocked = True
return self._result
|
python
|
{
"resource": ""
}
|
q12980
|
EnrollmentIdentities.after
|
train
|
def after(self, after):
"""
Sets the after of this EnrollmentIdentities.
ID
:param after: The after of this EnrollmentIdentities.
:type: str
"""
if after is None:
raise ValueError("Invalid value for `after`, must not be `None`")
if after is not None and not re.search('^[A-Za-z0-9]{32}', after):
raise ValueError("Invalid value for `after`, must be a follow pattern or equal to `/^[A-Za-z0-9]{32}/`")
self._after = after
|
python
|
{
"resource": ""
}
|
q12981
|
EnrollmentIdentities.order
|
train
|
def order(self, order):
"""
Sets the order of this EnrollmentIdentities.
:param order: The order of this EnrollmentIdentities.
:type: str
"""
if order is None:
raise ValueError("Invalid value for `order`, must not be `None`")
allowed_values = ["ASC", "DESC"]
if order not in allowed_values:
raise ValueError(
"Invalid value for `order` ({0}), must be one of {1}"
.format(order, allowed_values)
)
self._order = order
|
python
|
{
"resource": ""
}
|
q12982
|
UpdateCampaign.health_indicator
|
train
|
def health_indicator(self, health_indicator):
"""
Sets the health_indicator of this UpdateCampaign.
An indication to the condition of the campaign.
:param health_indicator: The health_indicator of this UpdateCampaign.
:type: str
"""
allowed_values = ["ok", "warning", "error"]
if health_indicator not in allowed_values:
raise ValueError(
"Invalid value for `health_indicator` ({0}), must be one of {1}"
.format(health_indicator, allowed_values)
)
self._health_indicator = health_indicator
|
python
|
{
"resource": ""
}
|
q12983
|
ServicePackageQuota.quota
|
train
|
def quota(self, quota):
"""
Sets the quota of this ServicePackageQuota.
Available quota for the service package.
:param quota: The quota of this ServicePackageQuota.
:type: int
"""
if quota is None:
raise ValueError("Invalid value for `quota`, must not be `None`")
if quota is not None and quota < 0:
raise ValueError("Invalid value for `quota`, must be a value greater than or equal to `0`")
self._quota = quota
|
python
|
{
"resource": ""
}
|
q12984
|
EnrollmentIdentity.enrolled_device_id
|
train
|
def enrolled_device_id(self, enrolled_device_id):
"""
Sets the enrolled_device_id of this EnrollmentIdentity.
The ID of the device in the Device Directory once it has been registered.
:param enrolled_device_id: The enrolled_device_id of this EnrollmentIdentity.
:type: str
"""
if enrolled_device_id is None:
raise ValueError("Invalid value for `enrolled_device_id`, must not be `None`")
if enrolled_device_id is not None and not re.search('^[A-Za-z0-9]{32}', enrolled_device_id):
raise ValueError("Invalid value for `enrolled_device_id`, must be a follow pattern or equal to `/^[A-Za-z0-9]{32}/`")
self._enrolled_device_id = enrolled_device_id
|
python
|
{
"resource": ""
}
|
q12985
|
main
|
train
|
def main(news_dir=None):
"""Checks for existence of a new newsfile"""
if news_dir is None:
from generate_news import news_dir
news_dir = os.path.abspath(news_dir)
# assume the name of the remote alias is just 'origin'
remote_alias = 'origin'
# figure out what the 'default branch' for the origin is
origin_stats = subprocess.check_output(
['git', 'remote', 'show', remote_alias],
cwd=news_dir
).decode()
# the output of the git command looks like:
# ' HEAD branch: master'
origin_branch = 'master' # unless we prove otherwise
for line in origin_stats.splitlines():
if 'head branch:' in line.lower():
origin_branch = line.split(':', 1)[-1].strip()
break
origin = '%s/%s' % (remote_alias, origin_branch)
# figure out the current branch
current_branch = subprocess.check_output(
['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
cwd=news_dir
).decode().strip()
print(':: Finding news in `%s` to add to remote `%s`' % (current_branch, origin))
diff_command = ['git', 'diff', '%s...%s' % (origin, current_branch), '--name-status', news_dir]
file_diff = subprocess.check_output(
diff_command,
cwd=news_dir
).decode()
# the output of the git command looks like:
# 'A docs/news/789.feature'
# [optional] ensure we have an addition, rather than just modify/delete
added_news = [line for line in file_diff.splitlines() if line.lower().strip().startswith('a')]
# pass or fail
if not added_news:
print(
'! Error: Uh-oh, did not find any news files!\n'
'! Please add a news file to `%s`\n'
'+ File diff:\n%s\n'
'{} Git diff command:\n`%s`\n' % (
news_dir,
file_diff.strip(),
subprocess.list2cmdline(diff_command)
)
)
exit(1) # exit with an error status, no need for a traceback
print(':: %s new files in `%s`' % (len(added_news), news_dir))
|
python
|
{
"resource": ""
}
|
q12986
|
CampaignDeviceMetadata.deployment_state
|
train
|
def deployment_state(self, deployment_state):
"""
Sets the deployment_state of this CampaignDeviceMetadata.
The state of the update campaign on the device
:param deployment_state: The deployment_state of this CampaignDeviceMetadata.
:type: str
"""
allowed_values = ["pending", "updated_connector_channel", "failed_connector_channel_update", "deployed", "manifestremoved", "deregistered"]
if deployment_state not in allowed_values:
raise ValueError(
"Invalid value for `deployment_state` ({0}), must be one of {1}"
.format(deployment_state, allowed_values)
)
self._deployment_state = deployment_state
|
python
|
{
"resource": ""
}
|
q12987
|
CertificatesAPI.list_certificates
|
train
|
def list_certificates(self, **kwargs):
"""List certificates registered to organisation.
Currently returns partially populated certificates. To obtain the full certificate object:
`[get_certificate(certificate_id=cert['id']) for cert in list_certificates]`
:param int limit: The number of certificates to retrieve.
:param str order: The ordering direction, ascending (asc) or
descending (desc).
:param str after: Get certificates after/starting at given `certificate_id`.
:param dict filters: Dictionary of filters to apply: type (eq), expire (eq), owner (eq)
:return: list of :py:class:`Certificate` objects
:rtype: Certificate
"""
kwargs = self._verify_sort_options(kwargs)
kwargs = self._verify_filters(kwargs, Certificate)
if "service__eq" in kwargs:
if kwargs["service__eq"] == CertificateType.bootstrap:
pass
elif kwargs["service__eq"] == CertificateType.developer:
kwargs["device_execution_mode__eq"] = 1
kwargs.pop("service__eq")
elif kwargs["service__eq"] == CertificateType.lwm2m:
pass
else:
raise CloudValueError(
"Incorrect value for CertificateType filter: %s" % (kwargs["service__eq"])
)
owner = kwargs.pop('owner_id__eq', None)
if owner is not None:
kwargs['owner__eq'] = owner
api = self._get_api(iam.DeveloperApi)
return PaginatedResponse(api.get_all_certificates, lwrap_type=Certificate, **kwargs)
|
python
|
{
"resource": ""
}
|
q12988
|
CertificatesAPI.get_certificate
|
train
|
def get_certificate(self, certificate_id):
"""Get certificate by id.
:param str certificate_id: The certificate id (Required)
:returns: Certificate object
:rtype: Certificate
"""
api = self._get_api(iam.DeveloperApi)
certificate = Certificate(api.get_certificate(certificate_id))
self._extend_certificate(certificate)
return certificate
|
python
|
{
"resource": ""
}
|
q12989
|
CertificatesAPI.add_certificate
|
train
|
def add_certificate(self, name, type, certificate_data, signature=None, **kwargs):
"""Add a new BYOC certificate.
:param str name: name of the certificate (Required)
:param str type: type of the certificate. Values: lwm2m or bootstrap (Required)
:param str certificate_data: X509.v3 trusted certificate in PEM format. (Required)
:param str signature: This parameter has been DEPRECATED in the API and does not need to
be provided.
:param str status: Status of the certificate.
Allowed values: "ACTIVE" | "INACTIVE".
:param str description: Human readable description of this certificate,
not longer than 500 characters.
:returns: Certificate object
:rtype: Certificate
"""
kwargs.update({'name': name})
kwargs.update({'type': type})
api = self._get_api(iam.AccountAdminApi)
kwargs.update({'certificate_data': certificate_data})
certificate = Certificate._create_request_map(kwargs)
if not certificate.get('enrollment_mode') and signature:
certificate.update({'signature': signature})
body = iam.TrustedCertificateReq(**certificate)
prod_cert = api.add_certificate(body)
return self.get_certificate(prod_cert.id)
|
python
|
{
"resource": ""
}
|
q12990
|
CertificatesAPI.add_developer_certificate
|
train
|
def add_developer_certificate(self, name, **kwargs):
"""Add a new developer certificate.
:param str name: name of the certificate (Required)
:param str description: Human readable description of this certificate,
not longer than 500 characters.
:returns: Certificate object
:rtype: Certificate
"""
kwargs['name'] = name
api = self._get_api(cert.DeveloperCertificateApi)
certificate = Certificate._create_request_map(kwargs)
# just pull the fields we care about
subset = cert.DeveloperCertificateRequestData.attribute_map
certificate = {k: v for k, v in certificate.items() if k in subset}
body = cert.DeveloperCertificateRequestData(**certificate)
dev_cert = api.create_developer_certificate(self.auth, body)
return self.get_certificate(dev_cert.id)
|
python
|
{
"resource": ""
}
|
q12991
|
Certificate.type
|
train
|
def type(self):
"""Certificate type.
:return: The type of the certificate.
:rtype: CertificateType
"""
if self._device_mode == 1 or self._type == CertificateType.developer:
return CertificateType.developer
elif self._type == CertificateType.bootstrap:
return CertificateType.bootstrap
else:
return CertificateType.lwm2m
|
python
|
{
"resource": ""
}
|
q12992
|
handle_channel_message
|
train
|
def handle_channel_message(db, queues, b64decode, notification_object):
"""Handler for notification channels
Given a NotificationMessage object, update internal state, notify
any subscribers and resolve async deferred tasks.
:param db:
:param queues:
:param b64decode:
:param notification_object:
:return:
"""
for notification in getattr(notification_object, 'notifications') or []:
# Ensure we have subscribed for the path we received a notification for
subscriber_queue = queues[notification.ep].get(notification.path)
if subscriber_queue is None:
LOG.debug(
"Ignoring notification on %s (%s) as no subscription is registered",
notification.ep,
notification.path
)
break
payload = tlv.decode(
payload=notification.payload,
content_type=notification.ct,
decode_b64=b64decode
)
subscriber_queue.put(payload)
for response in getattr(notification_object, 'async_responses') or []:
payload = tlv.decode(
payload=response.payload,
content_type=response.ct,
decode_b64=b64decode
)
db.update({response.id: dict(
payload=payload,
error=response.error,
status_code=response.status
)})
|
python
|
{
"resource": ""
}
|
q12993
|
AsyncConsumer.value
|
train
|
def value(self):
"""Get the value of the finished async request, if it is available.
:raises CloudUnhandledError: When not checking value of `error` or `is_done` first
:return: the payload value
:rtype: str
"""
status_code, error_msg, payload = self.check_error()
if not self._status_ok(status_code) and not payload:
raise CloudUnhandledError("Attempted to decode async request which returned an error.",
reason=error_msg,
status=status_code)
return self.db[self.async_id]["payload"]
|
python
|
{
"resource": ""
}
|
q12994
|
NotificationsThread.run
|
train
|
def run(self):
"""Thread main loop"""
retries = 0
try:
while not self._stopping:
try:
data = self.notifications_api.long_poll_notifications()
except mds.rest.ApiException as e:
# An HTTP 410 can be raised when stopping so don't log anything
if not self._stopping:
backoff = 2 ** retries - random.randint(int(retries / 2), retries)
LOG.error('Notification long poll failed with exception (retry in %d seconds):\n%s', backoff, e)
retries += 1
# Backoff for an increasing amount of time until we have tried 10 times, then reset the backoff.
if retries >= 10:
retries = 0
time.sleep(backoff)
else:
handle_channel_message(
db=self.db,
queues=self.queues,
b64decode=self._b64decode,
notification_object=data
)
if self.subscription_manager:
self.subscription_manager.notify(data.to_dict())
finally:
self._stopped.set()
|
python
|
{
"resource": ""
}
|
q12995
|
CreateCertificateIssuerConfig.certificate_issuer_id
|
train
|
def certificate_issuer_id(self, certificate_issuer_id):
"""
Sets the certificate_issuer_id of this CreateCertificateIssuerConfig.
The ID of the certificate issuer.
:param certificate_issuer_id: The certificate_issuer_id of this CreateCertificateIssuerConfig.
:type: str
"""
if certificate_issuer_id is None:
raise ValueError("Invalid value for `certificate_issuer_id`, must not be `None`")
if certificate_issuer_id is not None and len(certificate_issuer_id) > 32:
raise ValueError("Invalid value for `certificate_issuer_id`, length must be less than or equal to `32`")
self._certificate_issuer_id = certificate_issuer_id
|
python
|
{
"resource": ""
}
|
q12996
|
my_application
|
train
|
def my_application(api):
"""An example application.
- Registers a webhook with mbed cloud services
- Requests the value of a resource
- Prints the value when it arrives
"""
device = api.list_connected_devices().first()
print('using device #', device.id)
api.delete_device_subscriptions(device.id)
try:
print('setting webhook url to:', ngrok_url)
api.update_webhook(ngrok_url)
print('requesting resource value for:', resource_path)
deferred = api.get_resource_value_async(device_id=device.id, resource_path=resource_path)
print('waiting for async #', deferred.async_id)
result = deferred.wait(15)
print('webhook sent us this payload value:', repr(result))
return result
except Exception:
print(traceback.format_exc())
finally:
api.delete_webhook()
print("Deregistered and unsubscribed from all resources. Exiting.")
exit(1)
|
python
|
{
"resource": ""
}
|
q12997
|
webhook_handler
|
train
|
def webhook_handler(request):
"""Receives the webhook from mbed cloud services
Passes the raw http body directly to mbed sdk, to notify that a webhook was received
"""
body = request.stream.read().decode('utf8')
print('webhook handler saw:', body)
api.notify_webhook_received(payload=body)
# nb. protected references are not part of the API.
# this is just to demonstrate that the asyncid is stored
print('key store contains:', api._db.keys())
|
python
|
{
"resource": ""
}
|
q12998
|
start_sequence
|
train
|
def start_sequence():
"""Start the demo sequence
We must start this thread in the same process as the webserver to be certain
we are sharing the api instance in memory.
(ideally in future the async id database will be capable of being more than
just a dictionary)
"""
print('getting started!...')
t = threading.Thread(target=my_application, kwargs=dict(api=api))
t.daemon = True
t.start()
return 'ok, starting webhook to: %s' % (ngrok_url,)
|
python
|
{
"resource": ""
}
|
q12999
|
new_preload
|
train
|
def new_preload():
"""Job running prior to builds - fetches TestRunner image"""
testrunner_image = get_testrunner_image()
local_image = testrunner_image.rsplit(':')[-2].rsplit('/')[-1]
version_file = 'testrunner_version.txt'
template = yaml.safe_load(f"""
machine:
image: 'circleci/classic:201710-02'
steps:
- run:
name: AWS login
command: |-
login="$(aws ecr get-login --no-include-email)"
${{login}}
- run:
name: Pull TestRunner Image
command: docker pull {testrunner_image}
- run:
name: Make cache directory
command: mkdir -p {cache_dir}
- run:
name: Obtain Testrunner Version
command: echo $(docker run {testrunner_image} python -m trunner --version) > {cache_dir}/{version_file}
- run:
name: Export docker image layer cache
command: docker save -o {cache_dir}/{testrunner_cache} {testrunner_image}
- persist_to_workspace: # workspace is used later in this same build
root: {cache_dir}
paths: '{testrunner_cache}'
- persist_to_workspace: # workspace is used later in this same build
root: {cache_dir}
paths: '{version_file}'
- store_artifacts:
path: {version_file}
""")
return 'preload', template
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.