_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
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
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 """
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 """
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
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(
python
{ "resource": "" }
q12905
ConnectAPI.get_webhook
train
def get_webhook(self): """Get the current callback URL if it exists. :return: The currently set 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
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
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
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:
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
python
{ "resource": "" }
q12911
ChannelSubscription.ensure_started
train
def ensure_started(self): """Idempotent channel start""" if self.active: 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()
python
{ "resource": "" }
q12913
BillingAPI.get_quota_remaining
train
def get_quota_remaining(self): """Get the remaining value""" api = self._get_api(billing.DefaultApi) 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)
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 []
python
{ "resource": "" }
q12916
BillingAPI._month_converter
train
def _month_converter(self, date_time): """Returns Billing API format YYYY-DD""" if not 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
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:
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
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:
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('*'):
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:
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}
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
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
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,))
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
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
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
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
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)
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') )
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.
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 """
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
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
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
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.
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 """
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
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
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 """
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
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
python
{ "resource": "" }
q12945
Query.filter
train
def filter(self): """Get the query of this Query. The device query :return: The query of this Query.
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:
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',
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
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 #
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. """
python
{ "resource": "" }
q12951
force_ascii_values
train
def force_ascii_values(data): """Ensures each value is ascii-only""" return {
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)
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.
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.
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:
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",
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')
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:
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:
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
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
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
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
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
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
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
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
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)
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
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
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
python
{ "resource": "" }
q12972
AccountManagementAPI.get_account
train
def get_account(self): """Get details of the current account. :returns: an account object. :rtype: Account
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.
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:
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 """
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.
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.
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 #
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,
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
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:
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(
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:
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.
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
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:
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")
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)
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
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)
python
{ "resource": "" }
q12991
Certificate.type
train
def type(self): """Certificate type. :return: The type of the certificate. :rtype: CertificateType """ if self._device_mode == 1
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,
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:
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
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.
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)
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)
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
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
python
{ "resource": "" }