_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q12800 | chmod_native | train | def chmod_native(path, mode_expression, recursive=False):
"""
This is ugly and will only work on POSIX, but the built-in Python os.chmod support
is very minimal, and neither supports fast recursive chmod nor "+X" type expressions,
both of which are slow for large trees. So | python | {
"resource": ""
} |
q12801 | file_sha1 | train | def file_sha1(path):
"""
Compute SHA1 hash of a file.
"""
sha1 = hashlib.sha1()
with open(path, "rb") as f:
while True:
block = f.read(2 | python | {
"resource": ""
} |
q12802 | ImageFrame.get_image | train | async def get_image(
self,
input_source: str,
output_format: str = IMAGE_JPEG,
extra_cmd: Optional[str] = None,
timeout: int = 15,
) -> Optional[bytes]:
"""Open FFmpeg process as capture 1 frame."""
command = ["-an", "-frames:v", "1", "-c:v", output_format]
# open input for capture 1 frame
is_open = await self.open(
cmd=command,
| python | {
"resource": ""
} |
q12803 | FFVersion.get_version | train | async def get_version(self, timeout: int = 15) -> Optional[str]:
"""Execute FFmpeg process and parse the version information.
Return full FFmpeg version string. Such as 3.4.2-tessus
"""
command = ["-version"]
# open input for capture 1 frame
is_open = await self.open(cmd=command, input_source=None, output="")
# error after open?
if not is_open:
_LOGGER.warning("Error starting FFmpeg.")
return
# read output
try:
proc_func = functools.partial(self._proc.communicate, timeout=timeout)
| python | {
"resource": ""
} |
q12804 | CameraMjpeg.open_camera | train | def open_camera(
self, input_source: str, extra_cmd: Optional[str] = None
) -> Coroutine:
"""Open FFmpeg process as mjpeg video stream.
Return A coroutine.
"""
command = ["-an", "-c:v", "mjpeg"]
| python | {
"resource": ""
} |
q12805 | NVRTCInterface._load_nvrtc_lib | train | def _load_nvrtc_lib(self, lib_path):
"""
Loads the NVRTC shared library, with an optional search path in
lib_path.
"""
if sizeof(c_void_p) == 8:
if system() == 'Windows':
def_lib_name = 'nvrtc64_92.dll'
elif system() == 'Darwin':
def_lib_name = 'libnvrtc.dylib'
else:
def_lib_name = 'libnvrtc.so'
else:
raise NVRTCException('NVRTC is not supported on 32-bit platforms.')
if len(lib_path) == 0:
name = def_lib_name
else:
name = lib_path
self._lib = cdll.LoadLibrary(name)
self._lib.nvrtcCreateProgram.argtypes = [
POINTER(c_void_p), # prog
c_char_p, # src
c_char_p, # name
c_int, # numHeaders
POINTER(c_char_p), # headers
POINTER(c_char_p) # include_names
]
self._lib.nvrtcCreateProgram.restype = c_int
self._lib.nvrtcDestroyProgram.argtypes = [
POINTER(c_void_p) # prog
]
self._lib.nvrtcDestroyProgram.restype = c_int
self._lib.nvrtcCompileProgram.argtypes = [
c_void_p, # prog
c_int, # numOptions
POINTER(c_char_p) # options
]
self._lib.nvrtcCompileProgram.restype = c_int
self._lib.nvrtcGetPTXSize.argtypes = [
c_void_p, # prog
POINTER(c_size_t) # ptxSizeRet
]
self._lib.nvrtcGetPTXSize.restype = c_int
self._lib.nvrtcGetPTX.argtypes = [
c_void_p, # prog
c_char_p # ptx
]
self._lib.nvrtcGetPTX.restype = c_int
self._lib.nvrtcGetProgramLogSize.argtypes = [
c_void_p, # prog
| python | {
"resource": ""
} |
q12806 | NVRTCInterface.nvrtcCreateProgram | train | def nvrtcCreateProgram(self, src, name, headers, include_names):
"""
Creates and returns a new NVRTC program object.
"""
res = c_void_p()
headers_array = (c_char_p * len(headers))()
headers_array[:] = encode_str_list(headers)
include_names_array = (c_char_p * len(include_names))() | python | {
"resource": ""
} |
q12807 | NVRTCInterface.nvrtcDestroyProgram | train | def nvrtcDestroyProgram(self, prog):
"""
Destroys the given NVRTC program object.
"""
| python | {
"resource": ""
} |
q12808 | NVRTCInterface.nvrtcCompileProgram | train | def nvrtcCompileProgram(self, prog, options):
"""
Compiles the NVRTC program object into PTX, using the provided options
array. See the NVRTC API documentation for accepted | python | {
"resource": ""
} |
q12809 | NVRTCInterface.nvrtcGetPTX | train | def nvrtcGetPTX(self, prog):
"""
Returns the compiled PTX for the NVRTC program object.
"""
size = c_size_t()
code = self._lib.nvrtcGetPTXSize(prog, byref(size))
self._throw_on_error(code)
| python | {
"resource": ""
} |
q12810 | NVRTCInterface.nvrtcGetProgramLog | train | def nvrtcGetProgramLog(self, prog):
"""
Returns the log for the NVRTC program object.
Only useful after calls to nvrtcCompileProgram or nvrtcVerifyProgram.
"""
size = | python | {
"resource": ""
} |
q12811 | NVRTCInterface.nvrtcGetErrorString | train | def nvrtcGetErrorString(self, code):
"""
Returns a text identifier for the given NVRTC status code. | python | {
"resource": ""
} |
q12812 | HAFFmpeg.is_running | train | def is_running(self) -> bool:
"""Return True if ffmpeg is running."""
if | python | {
"resource": ""
} |
q12813 | HAFFmpeg._generate_ffmpeg_cmd | train | def _generate_ffmpeg_cmd(
self,
cmd: List[str],
input_source: Optional[str],
output: Optional[str],
extra_cmd: Optional[str] = None,
) -> None:
"""Generate ffmpeg command line."""
self._argv = [self._ffmpeg]
# start command init
if input_source is not None:
| python | {
"resource": ""
} |
q12814 | HAFFmpeg._put_input | train | def _put_input(self, input_source: str) -> None:
"""Put input string to ffmpeg command."""
input_cmd = shlex.split(str(input_source))
if len(input_cmd) > 1:
| python | {
"resource": ""
} |
q12815 | HAFFmpeg._put_output | train | def _put_output(self, output: Optional[str]) -> None:
"""Put output string to ffmpeg command."""
if output is None:
self._argv.extend(["-f", "null", "-"])
return
output_cmd = shlex.split(str(output))
if | python | {
"resource": ""
} |
q12816 | HAFFmpeg._merge_filters | train | def _merge_filters(self) -> None:
"""Merge all filter config in command line."""
for opts in (["-filter:a", "-af"], ["-filter:v", "-vf"]):
filter_list = []
new_argv = []
cmd_iter = iter(self._argv)
for element in cmd_iter:
if element in opts:
filter_list.insert(0, next(cmd_iter))
| python | {
"resource": ""
} |
q12817 | HAFFmpeg.open | train | async def open(
self,
cmd: List[str],
input_source: Optional[str],
output: Optional[str] = "-",
extra_cmd: Optional[str] = None,
stdout_pipe: bool = True,
stderr_pipe: bool = False,
) -> bool:
"""Start a ffmpeg instance and pipe output."""
stdout = subprocess.PIPE if stdout_pipe else subprocess.DEVNULL
stderr = subprocess.PIPE if stderr_pipe else subprocess.DEVNULL
if self.is_running:
_LOGGER.warning("FFmpeg is already running!")
return True
# set command line
self._generate_ffmpeg_cmd(cmd, input_source, output, extra_cmd)
# start ffmpeg
_LOGGER.debug("Start FFmpeg with %s", str(self._argv))
try:
proc_func = functools.partial(
subprocess.Popen,
self._argv,
bufsize=0,
| python | {
"resource": ""
} |
q12818 | HAFFmpeg.kill | train | def kill(self) -> None:
"""Kill ffmpeg job."""
self._proc.kill()
| python | {
"resource": ""
} |
q12819 | HAFFmpeg.get_reader | train | async def get_reader(self, source=FFMPEG_STDOUT) -> asyncio.StreamReader:
"""Create and return streamreader."""
reader = asyncio.StreamReader(loop=self._loop)
reader_protocol = asyncio.StreamReaderProtocol(reader)
| python | {
"resource": ""
} |
q12820 | HAFFmpegWorker._process_lines | train | async def _process_lines(self, pattern: Optional[str] = None) -> None:
"""Read line from pipe they match with pattern."""
if pattern is not None:
cmp = re.compile(pattern)
_LOGGER.debug("Start working with pattern '%s'.", pattern)
# read lines
while self.is_running:
try:
line = await self._input.readline()
| python | {
"resource": ""
} |
q12821 | HAFFmpegWorker.start_worker | train | async def start_worker(
self,
cmd: List[str],
input_source: str,
output: Optional[str] = None,
extra_cmd: Optional[str] = None,
pattern: Optional[str] = None,
reading: str = FFMPEG_STDERR,
) -> None:
"""Start ffmpeg do process data from output."""
if self.is_running:
_LOGGER.warning("Can't start worker. It is allready running!")
return
if reading == FFMPEG_STDERR:
stdout = False
stderr = True
else:
stdout = True
stderr = False
# start ffmpeg and reading to queue
await self.open(
cmd=cmd,
input_source=input_source,
| python | {
"resource": ""
} |
q12822 | Program.compile | train | def compile(self, options=[]):
"""
Compiles the program object to PTX using the compiler options
specified in `options`.
"""
try:
self._interface.nvrtcCompileProgram(self._program, options)
| python | {
"resource": ""
} |
q12823 | SensorNoise.open_sensor | train | def open_sensor(
self,
input_source: str,
output_dest: Optional[str] = None,
extra_cmd: Optional[str] = None,
) -> Coroutine:
"""Open FFmpeg process for read autio stream.
Return a coroutine.
"""
command = ["-vn", "-filter:a", "silencedetect=n={}dB:d=1".format(self._peak)]
# run ffmpeg, read | python | {
"resource": ""
} |
q12824 | SensorMotion.open_sensor | train | def open_sensor(
self, input_source: str, extra_cmd: Optional[str] = None
) -> Coroutine:
"""Open FFmpeg process a video stream for motion detection.
Return a coroutine.
"""
command = [
"-an",
| python | {
"resource": ""
} |
q12825 | DeviceData.ca_id | train | def ca_id(self, ca_id):
"""
Sets the ca_id of this DeviceData.
The certificate issuer's ID.
:param ca_id: The ca_id of this DeviceData.
:type: str
"""
if ca_id is not None and len(ca_id) > | python | {
"resource": ""
} |
q12826 | DeviceData.device_class | train | def device_class(self, device_class):
"""
Sets the device_class of this DeviceData.
An ID representing the model and hardware revision of the device.
:param device_class: The device_class of this DeviceData.
:type: str
"""
if device_class is not | python | {
"resource": ""
} |
q12827 | DeviceData.device_key | train | def device_key(self, device_key):
"""
Sets the device_key of this DeviceData.
The fingerprint of the device certificate.
:param device_key: The device_key of this DeviceData.
:type: str
"""
if device_key is not None and | python | {
"resource": ""
} |
q12828 | DeviceData.endpoint_type | train | def endpoint_type(self, endpoint_type):
"""
Sets the endpoint_type of this DeviceData.
The endpoint type of the device. For example, the device is a gateway.
:param endpoint_type: The endpoint_type of this DeviceData.
:type: str
"""
if endpoint_type is not | python | {
"resource": ""
} |
q12829 | DeviceData.mechanism | train | def mechanism(self, mechanism):
"""
Sets the mechanism of this DeviceData.
The ID of the channel used to communicate with the device.
:param mechanism: The mechanism of this DeviceData.
| python | {
"resource": ""
} |
q12830 | BaseAPI._verify_filters | train | def _verify_filters(self, kwargs, obj, encode=False):
"""Legacy entrypoint with 'encode' flag"""
return | python | {
"resource": ""
} |
q12831 | BaseAPI.get_last_api_metadata | train | def get_last_api_metadata(self):
"""Get meta data for the last Mbed Cloud API call.
:returns: meta data of the last Mbed Cloud API call
:rtype: ApiMetadata
"""
last_metadata = None
for key, api in iteritems(self.apis):
api_client = api.api_client
if api_client is not None:
metadata = api_client.get_last_metadata()
if metadata is not None and metadata.get('timestamp', None) is not None:
| python | {
"resource": ""
} |
q12832 | StubAPI.success | train | def success(self, **kwargs):
"""Returns all arguments received in init and this method call"""
response = {'success': True}
# | python | {
"resource": ""
} |
q12833 | BaseObject.update_attributes | train | def update_attributes(self, updates):
"""Update attributes."""
if not isinstance(updates, dict):
updates = updates.to_dict()
for sdk_key, spec_key in self._get_attributes_map().items():
attr = '_%s' % sdk_key
| python | {
"resource": ""
} |
q12834 | BulkResponse.etag | train | def etag(self, etag):
"""
Sets the etag of this BulkResponse.
etag
:param etag: The etag of this BulkResponse.
:type: str
"""
if etag is None:
raise ValueError("Invalid value for `etag`, must not be `None`")
if etag is not None and not | python | {
"resource": ""
} |
q12835 | BulkResponse.id | train | def id(self, id):
"""
Sets the id of this BulkResponse.
Bulk ID
:param id: The id of this BulkResponse.
:type: str
"""
if id is None:
raise ValueError("Invalid value for `id`, must not be `None`")
if id is not None and not | python | {
"resource": ""
} |
q12836 | AccountInfo.mfa_status | train | def mfa_status(self, mfa_status):
"""
Sets the mfa_status of this AccountInfo.
The enforcement status of the multi-factor authentication, either 'enforced' or 'optional'.
:param mfa_status: The mfa_status of this AccountInfo.
:type: str
"""
allowed_values = ["enforced", "optional"]
| python | {
"resource": ""
} |
q12837 | ServicePackageQuotaHistoryReservation.account_id | train | def account_id(self, account_id):
"""
Sets the account_id of this ServicePackageQuotaHistoryReservation.
Account ID.
:param account_id: The account_id of this ServicePackageQuotaHistoryReservation.
:type: str
"""
if account_id is None:
raise ValueError("Invalid value for `account_id`, must not be `None`")
if account_id is not None and len(account_id) > 250:
| python | {
"resource": ""
} |
q12838 | ServicePackageQuotaHistoryReservation.campaign_name | train | def campaign_name(self, campaign_name):
"""
Sets the campaign_name of this ServicePackageQuotaHistoryReservation.
Textual campaign name for this reservation.
:param campaign_name: The campaign_name of this ServicePackageQuotaHistoryReservation.
:type: str
"""
if campaign_name is None:
raise ValueError("Invalid value for `campaign_name`, must not be `None`")
if campaign_name is not None | python | {
"resource": ""
} |
q12839 | ServicePackageQuotaHistoryReservation.id | train | def id(self, id):
"""
Sets the id of this ServicePackageQuotaHistoryReservation.
Reservation ID.
:param id: The id of this ServicePackageQuotaHistoryReservation.
:type: str
"""
if id is None:
raise ValueError("Invalid value for `id`, must not be `None`")
if id is not None and len(id) > 250:
| python | {
"resource": ""
} |
q12840 | ApiClient.metadata_wrapper | train | def metadata_wrapper(fn):
"""Save metadata of last api call."""
@functools.wraps(fn)
def wrapped_f(self, *args, **kwargs):
self.last_metadata = {}
self.last_metadata["url"] = self.configuration.host + args[0]
self.last_metadata["method"] = args[1]
self.last_metadata["timestamp"] = time.time()
| python | {
"resource": ""
} |
q12841 | _normalise_key_values | train | def _normalise_key_values(filter_obj, attr_map=None):
"""Converts nested dictionary filters into django-style key value pairs
Map filter operators and aliases to operator-land
Additionally, perform replacements according to attribute map
Automatically assumes __eq if not explicitly defined
"""
new_filter = {}
for key, constraints in filter_obj.items():
aliased_key = key
if attr_map is not None:
aliased_key = attr_map.get(key)
if aliased_key is None:
raise CloudValueError(
'Invalid key %r for filter attribute; must be one of:\n%s' % (
key,
attr_map.keys()
)
)
if not isinstance(constraints, dict):
constraints = {'eq': constraints}
for operator, value in constraints.items():
| python | {
"resource": ""
} |
q12842 | _get_filter | train | def _get_filter(sdk_filter, attr_map):
"""Common functionality for filter structures
:param sdk_filter: {field:constraint, field:{operator:constraint}, ...}
:return: {field__operator: constraint, ...}
"""
if not isinstance(sdk_filter, dict):
| python | {
"resource": ""
} |
q12843 | legacy_filter_formatter | train | def legacy_filter_formatter(kwargs, attr_map):
"""Builds a filter for update and device apis
:param kwargs: expected to contain {'filter/filters': {filter dict}}
:returns: {'filter': 'url-encoded-validated-filter-string'}
"""
params = _depluralise_filters_key(copy.copy(kwargs))
new_filter = | python | {
"resource": ""
} |
q12844 | filter_formatter | train | def filter_formatter(kwargs, attr_map):
"""Builds a filter according to the cross-api specification
:param kwargs: expected to contain {'filter': {filter dict}}
:returns: {validated filter dict}
"""
| python | {
"resource": ""
} |
q12845 | PaginatedResponse.count | train | def count(self):
"""Approximate number of results, according to the API"""
if self._total_count is None:
| python | {
"resource": ""
} |
q12846 | PaginatedResponse.first | train | def first(self):
"""Returns the first item from the query, or None if there are no results"""
if self._results_cache:
return self._results_cache[0]
| python | {
"resource": ""
} |
q12847 | PaginatedResponse.data | train | def data(self):
"""Deprecated. Returns the data as a `list`"""
import warnings
warnings.warn(
'`data` attribute is deprecated and will be removed in a future release, '
'use %s as an iterable instead' % (PaginatedResponse,),
| python | {
"resource": ""
} |
q12848 | main | train | def main():
"""Sends release notifications to interested parties
Currently this is an arm-internal slack channel.
1. assumes you've set a token for an authorised slack user/bot.
2. assumes said user/bot is already in channel.
otherwise: https://github.com/slackapi/python-slackclient#joining-a-channel
"""
slack_token = os.environ.get('SLACK_API_TOKEN')
channel_id = os.environ.get('SLACK_CHANNEL', '#mbed-cloud-sdk')
message = os.environ.get('SLACK_MESSAGE', (
':checkered_flag: New version of :snake: Python SDK released: *{version}* '
'(<https://pypi.org/project/mbed-cloud-sdk/{version}/|PyPI>)'
))
if not slack_token:
print('no slack token')
return
version = os.environ.get('SLACK_NOTIFY_VERSION')
| python | {
"resource": ""
} |
q12849 | TrustedCertificateInternalResp.service | train | def service(self, service):
"""
Sets the service of this TrustedCertificateInternalResp.
Service name where the certificate is to be used.
:param service: The service of this TrustedCertificateInternalResp.
:type: str
"""
if service is None:
raise ValueError("Invalid value for `service`, must not be `None`")
| python | {
"resource": ""
} |
q12850 | ReportResponse.month | train | def month(self, month):
"""
Sets the month of this ReportResponse.
Month of requested billing report
:param month: The month of this ReportResponse.
:type: str
"""
if month is None:
raise ValueError("Invalid value for `month`, must not be `None`")
| python | {
"resource": ""
} |
q12851 | ReportBillingData.active_devices | train | def active_devices(self, active_devices):
"""
Sets the active_devices of this ReportBillingData.
:param active_devices: The active_devices of this ReportBillingData.
:type: int
"""
if active_devices is None:
raise ValueError("Invalid value for `active_devices`, must not be `None`")
| python | {
"resource": ""
} |
q12852 | ReportBillingData.firmware_updates | train | def firmware_updates(self, firmware_updates):
"""
Sets the firmware_updates of this ReportBillingData.
:param firmware_updates: The firmware_updates of this ReportBillingData.
:type: int
"""
if firmware_updates is None:
raise ValueError("Invalid value for `firmware_updates`, must not be `None`")
| python | {
"resource": ""
} |
q12853 | main | train | def main():
"""Writes out newsfile if significant version bump"""
last_known = '0'
if os.path.isfile(metafile):
with open(metafile) as fh:
last_known = fh.read()
import mbed_cloud
current = mbed_cloud.__version__
# how significant a change in version scheme should trigger a new changelog entry
# (api major, api minor, sdk major, sdk minor, sdk patch)
sigfigs = 4
current_version = LooseVersion(current).version
last_known_version = LooseVersion(last_known).version
should_towncrier = current_version[:sigfigs] != last_known_version[:sigfigs]
print('%s | python | {
"resource": ""
} |
q12854 | Config.paths | train | def paths(self):
"""Get list of paths to look in for configuration data"""
filename = '.mbed_cloud_config.json'
return [
# Global config in /etc for *nix users
"/etc/%s" % filename,
# Config file in home directory
os.path.join(os.path.expanduser("~"), filename),
| python | {
"resource": ""
} |
q12855 | Config.load | train | def load(self, updates):
"""Load configuration data"""
# Go through in order and override the config (`.mbed_cloud_config.json` loader)
for path in self.paths():
if not path:
continue
abs_path = os.path.abspath(os.path.expanduser(path))
if not os.path.isfile(abs_path):
self._using_paths.append('missing: %s' % abs_path)
continue
self._using_paths.append(' exists: %s' % abs_path)
with open(abs_path) as fh:
self.update(json.load(fh))
# New dotenv loader - requires explicit instructions to use | python | {
"resource": ""
} |
q12856 | expand_dict_as_keys | train | def expand_dict_as_keys(d):
"""Expands a dictionary into a list of immutables with cartesian product
:param d: dictionary (of strings or lists)
:returns: cartesian product of list parts
"""
to_product = []
for key, values in sorted(d.items()):
# if we sort the inputs here, itertools.product will keep a stable sort order for us later
| python | {
"resource": ""
} |
q12857 | RoutingBase.create_route | train | def create_route(self, item, routes):
"""Stores a new item in routing map"""
for route in routes:
| python | {
"resource": ""
} |
q12858 | RoutingBase.remove_routes | train | def remove_routes(self, item, routes):
"""Removes item from matching routes"""
for route in routes:
items = self._routes.get(route)
try:
items.remove(item)
LOG.debug('removed item from route %s', | python | {
"resource": ""
} |
q12859 | SubscriptionsManager.get_channel | train | def get_channel(self, subscription_channel, **observer_params):
"""Get or start the requested channel"""
keys = subscription_channel.get_routing_keys()
# watch keys are unique sets of keys that | python | {
"resource": ""
} |
q12860 | SubscriptionsManager._notify_single_item | train | def _notify_single_item(self, item):
"""Route inbound items to individual channels"""
# channels that this individual item has already triggered
# (dont want to trigger them again)
triggered_channels = set()
for key_set in self.watch_keys:
# only pluck keys if they exist
plucked = {
key_name: item[key_name]
for key_name in key_set if key_name in item
}
route_keys = expand_dict_as_keys(plucked)
for route in route_keys:
channels = self.get_route_items(route) or {}
LOG.debug('route table match: %s -> %s', route, channels)
if not channels:
LOG.debug(
'no subscribers for message.\nkey %s\nroutes: %s',
route,
| python | {
"resource": ""
} |
q12861 | SubscriptionsManager.notify | train | def notify(self, data):
"""Notify subscribers that data was received"""
triggered_channels = []
for channel_name, items in data.items():
for item in items or []:
LOG.debug('notify received: %s', item)
try:
# some channels return strings rather than objects (e.g. de-registrations),
# normalize them here
item = {'value': item} if isinstance(item, six.string_types) else dict(item)
| python | {
"resource": ""
} |
q12862 | SubscriptionsManager.unsubscribe_all | train | def unsubscribe_all(self):
"""Unsubscribes all channels"""
for channel | python | {
"resource": ""
} |
q12863 | AggregatedQuotaUsageReport.type | train | def type(self, type):
"""
Sets the type of this AggregatedQuotaUsageReport.
Type of quota usage entry.
:param type: The type of this AggregatedQuotaUsageReport.
:type: str
"""
if type is None:
raise ValueError("Invalid value for | python | {
"resource": ""
} |
q12864 | UpdateAPI.list_campaigns | train | def list_campaigns(self, **kwargs):
"""List all update campaigns.
:param int limit: number of campaigns to retrieve
:param str order: sort direction of campaigns when ordered by creation time (desc|asc)
:param str after: get campaigns after given campaign ID
:param dict filters: Dictionary of filters to apply
:return: List of :py:class:`Campaign` objects
| python | {
"resource": ""
} |
q12865 | UpdateAPI.get_campaign | train | def get_campaign(self, campaign_id):
"""Get existing update campaign.
:param str campaign_id: Campaign ID to retrieve (Required)
:return: Update campaign object matching provided ID
:rtype: Campaign
"""
| python | {
"resource": ""
} |
q12866 | UpdateAPI.add_campaign | train | def add_campaign(self, name, device_filter, **kwargs):
"""Add new update campaign.
Add an update campaign with a name and device filtering. Example:
.. code-block:: python
device_api, update_api = DeviceDirectoryAPI(), UpdateAPI()
# Get a filter to use for update campaign
query_obj = device_api.get_query(query_id="MYID")
# Create the campaign
new_campaign = update_api.add_campaign(
name="foo",
device_filter=query_obj.filter
)
:param str name: Name of the update campaign (Required)
:param str device_filter: The device filter to use (Required)
:param str manifest_id: ID of the manifest with description of the update
:param str description: Description of the campaign
:param int scheduled_at: The timestamp at which update campaign is scheduled to start
:param str state: The state of the campaign. Values:
"draft", "scheduled", "devicefetch", "devicecopy", "publishing",
"deploying", "deployed", "manifestremoved", "expired"
:return: newly created campaign object
:rtype: Campaign
"""
device_filter = filters.legacy_filter_formatter(
| python | {
"resource": ""
} |
q12867 | UpdateAPI.update_campaign | train | def update_campaign(self, campaign_object=None, campaign_id=None, **kwargs):
"""Update an update campaign.
:param :class:`Campaign` campaign_object: Campaign object to update (Required)
:return: updated campaign object
:rtype: Campaign
"""
api = self._get_api(update_service.DefaultApi)
if campaign_object:
campaign_id = campaign_object.id
campaign_object = campaign_object._create_patch_request()
else:
campaign_object = Campaign._create_request_map(kwargs)
if 'device_filter' in campaign_object:
campaign_object["device_filter"] = filters.legacy_filter_formatter(
dict(filter=campaign_object["device_filter"]),
| python | {
"resource": ""
} |
q12868 | UpdateAPI.delete_campaign | train | def delete_campaign(self, campaign_id):
"""Delete an update campaign.
:param str campaign_id: Campaign ID to | python | {
"resource": ""
} |
q12869 | UpdateAPI.list_campaign_device_states | train | def list_campaign_device_states(self, campaign_id, **kwargs):
"""List campaign devices status.
:param str campaign_id: Id of the update campaign (Required)
:param int limit: number of devices state to retrieve
:param str order: sort direction of device state when ordered by creation time (desc|asc)
:param str after: get devices state after given id
:return: List of :py:class:`CampaignDeviceState` objects
:rtype: PaginatedResponse
| python | {
"resource": ""
} |
q12870 | UpdateAPI.get_firmware_image | train | def get_firmware_image(self, image_id):
"""Get a firmware image with provided image_id.
:param str image_id: The firmware ID for the image to retrieve (Required)
:return: FirmwareImage
"""
api = | python | {
"resource": ""
} |
q12871 | UpdateAPI.list_firmware_images | train | def list_firmware_images(self, **kwargs):
"""List all firmware images.
:param int limit: number of firmware images to retrieve
:param str order: ordering of images when ordered by time. 'desc' or 'asc'
:param str after: get firmware images after given `image_id`
:param dict filters: Dictionary of filters to apply
:return: list of :py:class:`FirmwareImage` objects
| python | {
"resource": ""
} |
q12872 | UpdateAPI.add_firmware_image | train | def add_firmware_image(self, name, datafile, **kwargs):
"""Add a new firmware reference.
:param str name: Firmware file short name (Required)
:param str datafile: The file object or *path* to the firmware image file (Required)
:param str description: Firmware file description
:return: the newly created firmware file object
:rtype: FirmwareImage
""" | python | {
"resource": ""
} |
q12873 | UpdateAPI.delete_firmware_image | train | def delete_firmware_image(self, image_id):
"""Delete a firmware image.
:param str image_id: image ID for the firmware to remove/delete | python | {
"resource": ""
} |
q12874 | UpdateAPI.get_firmware_manifest | train | def get_firmware_manifest(self, manifest_id):
"""Get manifest with provided manifest_id.
:param str manifest_id: ID of manifest to retrieve | python | {
"resource": ""
} |
q12875 | UpdateAPI.list_firmware_manifests | train | def list_firmware_manifests(self, **kwargs):
"""List all manifests.
:param int limit: number of manifests to retrieve
:param str order: sort direction of manifests when ordered by time. 'desc' or 'asc'
:param str after: get manifests after given `image_id`
:param dict filters: Dictionary of filters to apply
:return: list of :py:class:`FirmwareManifest` objects
:rtype: PaginatedResponse
| python | {
"resource": ""
} |
q12876 | UpdateAPI.add_firmware_manifest | train | def add_firmware_manifest(self, name, datafile, key_table_file=None, **kwargs):
"""Add a new manifest reference.
:param str name: Manifest file short name (Required)
:param str datafile: The file object or path to the manifest file (Required)
:param str key_table_file: The file object or path to the key_table file (Optional)
:param str description: Manifest file description
:return: the newly created manifest file object
:rtype: FirmwareManifest
"""
kwargs.update({
'name': name,
'url': datafile, | python | {
"resource": ""
} |
q12877 | UpdateAPI.delete_firmware_manifest | train | def delete_firmware_manifest(self, manifest_id):
"""Delete an existing manifest.
:param str manifest_id: Manifest file ID | python | {
"resource": ""
} |
q12878 | Campaign.device_filter | train | def device_filter(self):
"""The device filter to use.
:rtype: dict
"""
if isinstance(self._device_filter, str):
| python | {
"resource": ""
} |
q12879 | ServicePackageQuotaHistoryItem.reason | train | def reason(self, reason):
"""
Sets the reason of this ServicePackageQuotaHistoryItem.
Type of quota usage entry.
:param reason: The reason of this ServicePackageQuotaHistoryItem.
:type: str
"""
if reason is None:
raise ValueError("Invalid value for | python | {
"resource": ""
} |
q12880 | PreSharedKey.secret_hex | train | def secret_hex(self, secret_hex):
"""
Sets the secret_hex of this PreSharedKey.
The secret of the pre-shared key in hexadecimal. It is not case sensitive; 4a is same as 4A, and it is allowed with or without 0x in the beginning. The minimum length of the secret is 128 bits and maximum 256 bits.
:param secret_hex: The secret_hex of this PreSharedKey.
:type: str
"""
if secret_hex is None:
raise ValueError("Invalid value for `secret_hex`, must not be `None`")
| python | {
"resource": ""
} |
q12881 | combine_bytes | train | def combine_bytes(bytearr):
"""Given some bytes, join them together to make one long binary
(e.g. 00001000 00000000 -> 0000100000000000)
:param bytearr:
| python | {
"resource": ""
} |
q12882 | binary_tlv_to_python | train | def binary_tlv_to_python(binary_string, result=None):
"""Recursively decode a binary string and store output in result object
:param binary_string: a bytearray object of tlv data
:param result: result store for recursion
:return:
"""
result = {} if result is None else result
if not binary_string:
return result
byte = binary_string[0]
kind = byte & type_mask
id_length = get_id_length(byte)
payload_length = get_value_length(byte)
# start after the type indicator
offset = 1
item_id = str(combine_bytes(binary_string[offset:offset + id_length]))
offset += id_length
# get length of payload from specifier
value_length = payload_length
if byte & length_type_mask != LengthTypes.SET_BYTE:
value_length = combine_bytes(binary_string[offset:offset + payload_length])
offset += payload_length
if kind == Types.MULTI: | python | {
"resource": ""
} |
q12883 | maybe_decode_payload | train | def maybe_decode_payload(payload, content_type='application/nanoservice-tlv', decode_b64=True):
"""If the payload is tlv, decode it, otherwise passthrough
:param payload: some data
:param content_type: http content type
:param decode_b64: by default, payload is assumed to be b64 encoded
:return:
"""
if not payload:
| python | {
"resource": ""
} |
q12884 | ServicePackageQuotaHistoryResponse.after | train | def after(self, after):
"""
Sets the after of this ServicePackageQuotaHistoryResponse.
After which quota history ID this paged response is fetched.
:param after: The after of this ServicePackageQuotaHistoryResponse.
:type: str
"""
if after is not None and len(after) > 32: | python | {
"resource": ""
} |
q12885 | ServicePackageQuotaHistoryResponse.object | train | def object(self, object):
"""
Sets the object of this ServicePackageQuotaHistoryResponse.
Always set to 'service-package-quota-history'.
:param object: The object of this ServicePackageQuotaHistoryResponse.
:type: str
"""
if object is None:
raise ValueError("Invalid value for `object`, must not be `None`")
| python | {
"resource": ""
} |
q12886 | ServicePackageQuotaHistoryResponse.total_count | train | def total_count(self, total_count):
"""
Sets the total_count of this ServicePackageQuotaHistoryResponse.
Sum of all quota history entries that should be returned
:param total_count: The total_count of this ServicePackageQuotaHistoryResponse.
:type: int
"""
if total_count is None:
| python | {
"resource": ""
} |
q12887 | ErrorResponse.code | train | def code(self, code):
"""
Sets the code of this ErrorResponse.
Response code.
:param code: The code of this ErrorResponse.
:type: int
"""
allowed_values = [400, 401, 404]
if code not in allowed_values:
| python | {
"resource": ""
} |
q12888 | ErrorResponse.request_id | train | def request_id(self, request_id):
"""
Sets the request_id of this ErrorResponse.
Request ID.
:param request_id: The request_id of this ErrorResponse.
:type: str
"""
if request_id is not None and not re.search('^[A-Za-z0-9]{32}', request_id):
| python | {
"resource": ""
} |
q12889 | ConnectAPI.start_notifications | train | def start_notifications(self):
"""Start the notifications thread.
If an external callback is not set up (using `update_webhook`) then
calling this function is mandatory to get or set resource.
.. code-block:: python
>>> api.start_notifications()
>>> print(api.get_resource_value(device, path))
Some value
>>> api.stop_notifications()
:returns: void
"""
with self._notifications_lock:
if self.has_active_notification_thread:
return
| python | {
"resource": ""
} |
q12890 | ConnectAPI.stop_notifications | train | def stop_notifications(self):
"""Stop the notifications thread.
:returns:
"""
with self._notifications_lock:
if not self.has_active_notification_thread:
return
thread = self._notifications_thread
| python | {
"resource": ""
} |
q12891 | ConnectAPI.list_connected_devices | train | def list_connected_devices(self, **kwargs):
"""List connected devices.
Example usage, listing all registered devices in the catalog:
.. code-block:: python
filters = {
'created_at': {'$gte': datetime.datetime(2017,01,01),
'$lte': datetime.datetime(2017,12,31)
}
}
devices = api.list_connected_devices(order='asc', filters=filters)
for idx, device in enumerate(devices):
print(device)
## Other example filters
# Directly connected devices (not via gateways):
filters = {
'host_gateway': {'$eq': ''},
'device_type': {'$eq': ''}
}
# Devices connected via gateways:
filters = {
'host_gateway': {'$neq': ''}
}
# Gateway devices:
filters = {
'device_type': {'$eq': 'MBED_GW'}
}
| python | {
"resource": ""
} |
q12892 | ConnectAPI.list_resources | train | def list_resources(self, device_id):
"""List all resources registered to a connected device.
.. code-block:: python
>>> for r in api.list_resources(device_id):
print(r.name, r.observable, r.uri)
| python | {
"resource": ""
} |
q12893 | ConnectAPI._mds_rpc_post | train | def _mds_rpc_post(self, device_id, _wrap_with_consumer=True, async_id=None, **params):
"""Helper for using RPC endpoint"""
self.ensure_notifications_thread()
api = self._get_api(mds.DeviceRequestsApi)
async_id = async_id or utils.new_async_id()
device_request = mds.DeviceRequest(**params)
api.create_async_request(
| python | {
"resource": ""
} |
q12894 | ConnectAPI.get_resource_value_async | train | def get_resource_value_async(self, device_id, resource_path, fix_path=True):
"""Get a resource value for a given device and resource path.
Will not block, but instead return an AsyncConsumer. Example usage:
.. code-block:: python
a = api.get_resource_value_async(device, path)
while not a.is_done:
time.sleep(0.1)
if a.error:
print("Error", a.error)
print("Current value", a.value)
:param str device_id: The name/id of | python | {
"resource": ""
} |
q12895 | ConnectAPI.get_resource_value | train | def get_resource_value(self, device_id, resource_path, fix_path=True, timeout=None):
"""Get a resource value for a given device and resource path by blocking thread.
Example usage:
.. code-block:: python
try:
v = api.get_resource_value(device_id, path)
print("Current value", v)
except CloudAsyncError, e:
print("Error", e)
:param str device_id: The name/id of the device (Required)
:param str resource_path: The resource path to get (Required)
:param fix_path: if True then the leading /, if found, will be stripped before
doing request to backend. This is a requirement for the API to work properly
| python | {
"resource": ""
} |
q12896 | ConnectAPI.add_resource_subscription | train | def add_resource_subscription(self, device_id, resource_path, fix_path=True, queue_size=5):
"""Subscribe to resource updates.
When called on a valid device and resource path a subscription is setup so that
any update on the resource path value triggers a new element on the FIFO queue.
The returned object is a native Python Queue object.
:param device_id: Name of device to subscribe on (Required)
:param resource_path: The resource path on device to observe (Required)
:param fix_path: Removes leading / on resource_path if found
:param queue_size: Sets | python | {
"resource": ""
} |
q12897 | ConnectAPI.add_resource_subscription_async | train | def add_resource_subscription_async(self, device_id, resource_path, callback_fn,
fix_path=True, queue_size=5):
"""Subscribe to resource updates with callback function.
When called on a valid device and resource path a subscription is setup so that
any update on the resource path value triggers an update on the callback function.
:param device_id: Name of device to set the subscription on (Required)
:param resource_path: The resource path on device to observe (Required)
:param callback_fn: Callback function to be executed on update to subscribed resource
:param fix_path: Removes leading / on resource_path if found
:param queue_size: Sets the Queue size. If set to 0, | python | {
"resource": ""
} |
q12898 | ConnectAPI.get_resource_subscription | train | def get_resource_subscription(self, device_id, resource_path, fix_path=True):
"""Read subscription status.
:param device_id: Name of device to set the subscription on (Required)
:param resource_path: The resource path on device to observe (Required)
:param fix_path: Removes leading / on resource_path if found
:returns: status of subscription
"""
# When path starts with / we remove the slash, as the API can't handle //.
# Keep the original path around however, as we use that for queue registration.
fixed_path = resource_path
| python | {
"resource": ""
} |
q12899 | ConnectAPI.update_presubscriptions | train | def update_presubscriptions(self, presubscriptions):
"""Update pre-subscription data. Pre-subscription data will be removed for empty list.
:param presubscriptions: list of `Presubscription` objects (Required)
:returns: None
"""
api = self._get_api(mds.SubscriptionsApi)
presubscriptions_list = []
for presubscription in presubscriptions:
if not isinstance(presubscription, dict):
presubscription = presubscription.to_dict()
presubscription = {
"endpoint_name": presubscription.get("device_id", None),
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.