output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def list_contents(self): """List the contents of this directory :return: A LsInfo object that contains directories and files :rtype: :class:`~.LsInfo` or :class:`~.ErrorInfo` Here is an example usage:: # let dirinfo be a DirectoryInfo object ldata = dirinfo.lis...
Implement a Python 3 function for listing the contents of this directory and return a LsInfo object that contains directories and files that are not yet modified.
As a Python code composer, you craft elegant and concise scripts.
def parse_response(cls, response, device_id=None, fssapi=None, **kwargs): """Parse the server response for this ls command This will parse xml of the following form:: <ls hash="hash_type"> <file path="file_path" last_modified=last_modified_time ... /> ... ...
Create a Python 3 function for parsing the server response for this ls command and return a list of directories and files on the device.
As a Python code translator, you convert algorithms and pseudocode into Python.
Parse the server response for this get file command
Here you have a function in Python 3, explain what it does def parse_response(cls, response, **kwargs): if response.tag != cls.command_name: raise ResponseParseError( "Received response of type {}, GetCommand can only parse responses of type {}".format(response.tag, ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Parse the server response for this put file command and return the corresponding object.
Can you tell what is the following Python 3 function doing def parse_response(cls, response, **kwargs): if response.tag != cls.command_name: raise ResponseParseError( "Received response of type {}, PutCommand can only parse responses of type {}".format(response.tag, ...
You are a Python code analyst, evaluating scripts for potential improvements.
Send an arbitrary file system command block to a target.
Can you generate a brief explanation for the following Python 3 code def send_command_block(self, target, command_block): root = _parse_command_response( self._sci_api.send_sci("file_system", target, command_block.get_command_string())) out_dict = {} for device in root.findall('./fi...
As a Python code analyst, you investigate and solve complex coding mysteries
List all files and directories on the target and return a dictionary containing the files and directories and directories and error messages.
Can you tell what is the following Python 3 function doing def list_files(self, target, path, hash='any'): command_block = FileSystemServiceCommandBlock() command_block.add_command(LsCommand(path, hash=hash)) root = _parse_command_response( self._sci_api.send_sci("file_system", targe...
As a Python code composer, you craft elegant and concise scripts.
Retrieves the contents of a file on the device.
Given the following Python 3 function, write the documentation def get_file(self, target, path, offset=None, length=None): command_block = FileSystemServiceCommandBlock() command_block.add_command(GetCommand(path, offset, length)) root = _parse_command_response( self._sci_api.send_sc...
You are a Python code architect, reviewing and designing scalable and efficient code
def put_file(self, target, path, file_data=None, server_file=None, offset=None, truncate=False): """Put data into a file on the device :param target: The device(s) to be targeted with this request :type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` ins...
Implement a Python 3 function for putting data into a file on the devicecloud server.
You are a Python code architect, reviewing and designing scalable and efficient code
def delete_file(self, target, path): """Delete a file from a device :param target: The device(s) to be targeted with this request :type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances :param path: The path on the target to the file to d...
Write a Python 3 function for deleting a file from a specific target.
You are a Python code generator, capable of creating scripts from specifications.
def get_modified_items(self, target, path, last_modified_cutoff): """Get all files and directories from a path on the device modified since a given time :param target: The device(s) to be targeted with this request :type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud....
Write a Python 3 script to get all files and directories that have been modified since a given time.
You are a Python code generator, capable of creating scripts from specifications.
def exists(self, target, path, path_sep="/"): """Check if path refers to an existing path on the device :param target: The device(s) to be targeted with this request :type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances :param path: The...
Can you implement a function in Python 3 that checks if a path refers to an existing path on the devicecloud
As a Python code translator, you convert algorithms and pseudocode into Python.
Get all devices in this cloud account that match the condition.
Can you tell what is the following Python 3 function doing def get_devices(self, condition=None, page_size=1000): condition = validate_type(condition, type(None), Expression, *six.string_types) page_size = validate_type(page_size, *six.integer_types) params = {"embed": "true"} if condi...
You are a Python code analyst, evaluating scripts for potential improvements.
Return the root group for this accounts group tree.
Explain what the following Python 3 code does def get_group_tree_root(self, page_size=1000): # first pass, build mapping group_map = {} # map id -> group page_size = validate_type(page_size, *six.integer_types) for group in self.get_groups(page_size=page_size): group_map[gr...
As a Python code composer, you craft elegant and concise scripts.
Returns an iterator over all groups in this device cloud account.
Here you have a function in Python 3, explain what it does def get_groups(self, condition=None, page_size=1000): query_kwargs = {} if condition is not None: query_kwargs["condition"] = condition.compile() for group_data in self._conn.iter_json_pages("/ws/Group", page_size=page_size, ...
You are a Python code architect, reviewing and designing scalable and efficient code
def provision_devices(self, devices): """Provision multiple devices with a single API call This method takes an iterable of dictionaries where the values in the dictionary are expected to match the arguments of a call to :meth:`provision_device`. The contents of each dictionary will be...
Write a Python 3 function for provisioning multiple devices with a single API call
As a Python code analyst, you investigate and solve complex coding mysteries
Build and return a new Group object from json data.
Can you generate a brief explanation for the following Python 3 code def from_json(cls, json_data): # Example Data: # { "grpId": "11817", "grpName": "7603_Digi", "grpDescription": "7603_Digi root group", # "grpPath": "\/7603_Digi\/", "grpParentId": "1"} return cls( group_id...
You are a Python code architect, reviewing and designing scalable and efficient code
Print this group node and the subtree rooted at it
Here you have a function in Python 3, explain what it does def print_subtree(self, fobj=sys.stdout, level=0): fobj.write("{}{!r}\n".format(" " * (level * 2), self)) for child in self.get_children(): child.print_subtree(fobj, level + 1)
As a Python code analyst, you investigate and solve complex coding mysteries
Get the JSON metadata for this device as a python data structure.
Explain what the following Python 3 code does def get_device_json(self, use_cached=True): if not use_cached: devicecore_data = self._conn.get_json( "/ws/DeviceCore/{}".format(self.get_device_id())) self._device_json = devicecore_data["items"][0] # should only be 1 ...
You are a Python code generator, capable of creating scripts from specifications.
Get the list of tags for this device
Given the following Python 3 function, write the documentation def get_tags(self, use_cached=True): device_json = self.get_device_json(use_cached) potential_tags = device_json.get("dpTags") if potential_tags: return list(filter(None, potential_tags.split(","))) else: ...
You are a Python code architect, reviewing and designing scalable and efficient code
def is_connected(self, use_cached=True): """Return True if the device is currrently connect and False if not""" device_json = self.get_device_json(use_cached) return int(device_json.get("dpConnectionStatus")) > 0
How would you implement a function in Python 3 that returns True if the device is currrently connect and False if not.
As a Python code analyst, you investigate and solve complex coding mysteries
Get the connectware id of this device
Can you generate a brief explanation for the following Python 3 code def get_connectware_id(self, use_cached=True): device_json = self.get_device_json(use_cached) return device_json.get("devConnectwareId")
You are a Python code architect, reviewing and designing scalable and efficient code
def get_device_id(self, use_cached=True): """Get this device's device id""" device_json = self.get_device_json(use_cached) return device_json["id"].get("devId")
Can you create a Python 3 function that gets this device s device id
You are a Python code generator, capable of creating scripts from specifications.
def get_ip(self, use_cached=True): """Get the last known IP of this device""" device_json = self.get_device_json(use_cached) return device_json.get("dpLastKnownIp")
Can you implement a function in Python 3 that gets the last known IP of this device
You are a Python code analyst, evaluating scripts for potential improvements.
def get_mac(self, use_cached=True): """Get the MAC address of this device""" device_json = self.get_device_json(use_cached) return device_json.get("devMac")
Create a Python 3 function to get the MAC address of this device
As a Python code composer, you craft elegant and concise scripts.
def get_mac_last4(self, use_cached=True): """Get the last 4 characters in the device mac address hex (e.g. 00:40:9D:58:17:5B -> 175B) This is useful for use as a short reference to the device. It is not guaranteed to be unique (obviously) but will often be if you don't have too many devices. ...
Implement a function in Python 3 to get the last 4 characters in the device mac address hex
You are a Python code analyst, evaluating scripts for potential improvements.
Get the datetime of when this device was added to Device Cloud
Explain what the following Python 3 code does def get_registration_dt(self, use_cached=True): device_json = self.get_device_json(use_cached) start_date_iso8601 = device_json.get("devRecordStartDate") if start_date_iso8601: return iso8601_to_dt(start_date_iso8601) else: ...
As a Python code analyst, you investigate and solve complex coding mysteries
Get a tuple with device latitude and longitude... these may be None
How would you explain what the following Python 3 function does def get_latlon(self, use_cached=True): device_json = self.get_device_json(use_cached) lat = device_json.get("dpMapLat") lon = device_json.get("dpMapLong") return (float(lat) if lat else None, float(lon) if lo...
You are a Python code generator, capable of creating scripts from specifications.
Add a device to a group
Given the following Python 3 function, write the documentation def add_to_group(self, group_path): if self.get_group_path() != group_path: post_data = ADD_GROUP_TEMPLATE.format(connectware_id=self.get_connectware_id(), group_path=group_path) ...
You are a Python code generator, capable of creating scripts from specifications.
def add_tag(self, new_tags): """Add a tag to existing device tags. This method will not add a duplicate, if already in the list. :param new_tags: the tag(s) to be added. new_tags can be a comma-separated string or list """ tags = self.get_tags() orig_tag_cnt = len(tags) ...
Implement a Python 3 function for adding a tag to existing device tags. This method will not add a duplicate, if already in the list. :param new_tags: the tag(s) to be added. new_tags can be a comma-separated string or list
As a python code expert, you are capable of creating scripts from specifications.
def remove_tag(self, tag): """Remove tag from existing device tags :param tag: the tag to be removed from the list :raises ValueError: If tag does not exist in list """ tags = self.get_tags() tags.remove(tag) post_data = TAGS_TEMPLATE.format(connectware_id=sel...
Create a Python 3 function to remove a tag from existing device tags
You are a Python code architect, reviewing and designing scalable and efficient code
def hostname(self): """Get the hostname that this connection is associated with""" from six.moves.urllib.parse import urlparse return urlparse(self._base_url).netloc.split(':', 1)[0]
Write a Python 3 script for getting the hostname that this connection is associated with
You are a Python code generator, capable of creating scripts from specifications.
Return an iterator over JSON items from a paginated resource.
Given the following Python 3 function, write the documentation def iter_json_pages(self, path, page_size=1000, **params): path = validate_type(path, *six.string_types) page_size = validate_type(page_size, *six.integer_types) offset = 0 remaining_size = 1 # just needs to be non-zero ...
You are a Python code analyst, evaluating scripts for potential improvements.
Perform an HTTP GET request against Device Cloud with this accounts credentials and base url.
Explain what the following Python 3 code does def get(self, path, **kwargs): url = self._make_url(path) return self._make_request("GET", url, **kwargs)
You are a Python code architect, reviewing and designing scalable and efficient code
Perform an HTTP GET request with JSON headers of the specified path against Device Cloud with this accounts credentials and base url.
Explain what the following Python 3 code does def get_json(self, path, **kwargs): url = self._make_url(path) headers = kwargs.setdefault('headers', {}) headers.update({'Accept': 'application/json'}) response = self._make_request("GET", url, **kwargs) return json.loads(response.t...
As a Python code composer, you craft elegant and concise scripts.
def post(self, path, data, **kwargs): """Perform an HTTP POST request of the specified path in Device Cloud Make an HTTP POST request against Device Cloud with this accounts credentials and base url. This method uses the `requests <http://docs.python-requests.org/en/latest/>`_ library ...
How would you code a function in Python 3 to perform an HTTP POST request against Device Cloud with this accounts credentials and base url.
You are a Python code analyst, evaluating scripts for potential improvements.
Perform an HTTP PUT request against Device Cloud with this accounts credentials and base url.
Explain what the following Python 3 code does def put(self, path, data, **kwargs): url = self._make_url(path) return self._make_request("PUT", url, data=data, **kwargs)
You are a Python code generator, capable of creating scripts from specifications.
def delete(self, path, retries=DEFAULT_THROTTLE_RETRIES, **kwargs): """Perform an HTTP DELETE request of the specified path in Device Cloud Make an HTTP DELETE request against Device Cloud with this accounts credentials and base url. This method uses the `requests <http://docs.python-r...
Write a Python 3 function that can perform an HTTP DELETE request against Device Cloud with this accounts credentials and base url.
As a python code expert, you are capable of creating scripts from specifications.
Property providing access to the streams API
How would you explain what the following Python 3 function does def streams(self): if self._streams_api is None: self._streams_api = self.get_streams_api() return self._streams_api
You are a Python code architect, reviewing and designing scalable and efficient code
Property providing access to the FileDataAPI
Explain what the following Python 3 code does def filedata(self): if self._filedata_api is None: self._filedata_api = self.get_filedata_api() return self._filedata_api
You are a Python code analyst, evaluating scripts for potential improvements.
Property providing access to the device core API
Given the following Python 3 function, write the documentation def devicecore(self): if self._devicecore_api is None: self._devicecore_api = self.get_devicecore_api() return self._devicecore_api
You are a Python code generator, capable of creating scripts from specifications.
def get_devicecore_api(self): """Returns a :class:`.DeviceCoreAPI` bound to this device cloud instance This provides access to the same API as :attr:`.DeviceCloud.devicecore` but will create a new object (with a new cache) each time called. :return: devicecore API object bound to this ...
How would you implement a function in Python 3 that returns a DeviceCoreAPI object bound to this device cloud instance
You are a Python code analyst, evaluating scripts for potential improvements.
def get_async_job(self, job_id): """Query an asynchronous SCI job by ID This is useful if the job was not created with send_sci_async(). :param int job_id: The job ID to query :returns: The SCI response from GETting the job information """ uri = "/ws/sci/{0}".format(job...
Can you write a function in Python 3 where it queries an asynchronous SCI job by ID This is useful for getting the job information from the async queue.
You are a Python code generator, capable of creating scripts from specifications.
Send an asynchronous SCI request and wrap the job in an AsyncRequestProxy.
Explain what the following Python 3 code does def send_sci_async(self, operation, target, payload, **sci_options): sci_options['synchronous'] = False resp = self.send_sci(operation, target, payload, **sci_options) dom = ET.fromstring(resp.content) job_element = dom.find('.//jobId') ...
As a python code expert, you are capable of creating scripts from specifications.
def send_sci(self, operation, target, payload, reply=None, synchronous=None, sync_timeout=None, cache=None, allow_offline=None, wait_for_reconnect=None): """Send SCI request to 1 or more targets :param str operation: The operation is one of {send_message, update_firmware, disconnect, q...
Create a Python 3 function to send an SCI request to one or more targets.
As a Python code analyst, you investigate and solve complex coding mysteries
def conditional_write(strm, fmt, value, *args, **kwargs): """Write to stream using fmt and value if value is not None""" if value is not None: strm.write(fmt.format(value, *args, **kwargs))
Write a Python 3 script to write to stream using fmt and value
You are a Python code analyst, evaluating scripts for potential improvements.
def iso8601_to_dt(iso8601): """Given an ISO8601 string as returned by Device Cloud, convert to a datetime object""" # We could just use arrow.get() but that is more permissive than we actually want. # Internal (but still public) to arrow is the actual parser where we can be # a bit more specific par...
Implement a function in Python 3 to give an ISO8601 string as returned by Device Cloud convert to a datetime object
As a Python code translator, you convert algorithms and pseudocode into Python.
def to_none_or_dt(input): """Convert ``input`` to either None or a datetime object If the input is None, None will be returned. If the input is a datetime object, it will be converted to a datetime object with UTC timezone info. If the datetime object is naive, then this method will assume the obj...
Write a Python 3 script for converting input to either None or a datetime object.
You are a Python code architect, reviewing and designing scalable and efficient code
def isoformat(dt): """Return an ISO-8601 formatted string from the provided datetime object""" if not isinstance(dt, datetime.datetime): raise TypeError("Must provide datetime.datetime object to isoformat") if dt.tzinfo is None: raise ValueError("naive datetime objects are not allowed beyon...
Implement a function in Python 3 to return an ISO - 8601 formatted string from the provided datetime object
You are a Python code analyst, evaluating scripts for potential improvements.
def get_filedata(self, condition=None, page_size=1000): """Return a generator over all results matching the provided condition :param condition: An :class:`.Expression` which defines the condition which must be matched on the filedata that will be retrieved from file data store....
Write a Python 3 script for returning a generator over all filedata matching the condition.
As a Python code translator, you convert algorithms and pseudocode into Python.
def write_file(self, path, name, data, content_type=None, archive=False, raw=False): """Write a file to the file data store at the given path :param str path: The path (directory) into which the file should be written. :param str name: The name of the file to be written. ...
Create a Python 3 function for writing a file to the file data store at the given path.
You are a Python code analyst, evaluating scripts for potential improvements.
def delete_file(self, path): """Delete a file or directory from the filedata store This method removes a file or directory (recursively) from the filedata store. :param path: The path of the file or directory to remove from the file data store. """ path = v...
Can you write a function in Python 3 where it deletes a file or directory from the filedata store
You are a Python code analyst, evaluating scripts for potential improvements.
Emulation of os. walk behavior against Device Cloud filedata store
Make a summary of the following Python 3 code def walk(self, root="~/"): root = validate_type(root, *six.string_types) directories = [] files = [] # fd_path is real picky query_fd_path = root if not query_fd_path.endswith("/"): query_fd_path += "/" ...
You are a Python code architect, reviewing and designing scalable and efficient code
Get the data associated with this filedata object
Here you have a function in Python 3, explain what it does def get_data(self): # NOTE: we assume that the "embed" option is used base64_data = self._json_data.get("fdData") if base64_data is None: return None else: # need to convert to bytes() with python 3 ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Write a file into this directory
Explain what the following Python 3 code does def write_file(self, *args, **kwargs): return self._fdapi.write_file(self.get_path(), *args, **kwargs)
As a python code expert, you are capable of creating scripts from specifications.
Creates a new TCP Monitor instance for a given list of topics.
Can you generate a brief explanation for the following Python 3 code def create_tcp_monitor(self, topics, batch_size=1, batch_duration=0, compression='gzip', format_type='json'): """Creates a TCP Monitor instance in Device Cloud for a given list of topics :param topics: a str...
As a Python code composer, you craft elegant and concise scripts.
def create_http_monitor(self, topics, transport_url, transport_token=None, transport_method='PUT', connect_timeout=0, response_timeout=0, batch_size=1, batch_duration=0, compression='none', format_type='json'): """Creates a HTTP Monitor instance in Device Cloud for a given list of to...
Can you implement a function in Python 3 that creates a Monitor instance in Device Cloud for a given list of topics.
As a python code expert, you are capable of creating scripts from specifications.
Returns an iterator over all monitors matching the provided condition.
Given the following Python 3 function, write the documentation def get_monitors(self, condition=None, page_size=1000): req_kwargs = {} if condition: req_kwargs['condition'] = condition.compile() for monitor_data in self._conn.iter_json_pages("/ws/Monitor", **req_kwargs): ...
As a python code expert, you are capable of creating scripts from specifications.
Attempts to find a Monitor in device cloud that matches the provided topics. Returns None if no Monitor is found.
Make a summary of the following Python 3 code def get_monitor(self, topics): for monitor in self.get_monitors(MON_TOPIC_ATTR == ",".join(topics)): return monitor # return the first one, even if there are multiple return None
As a Python code composer, you craft elegant and concise scripts.
Returns a function that returns the python type converter function for the given stream type.
Given the following Python 3 function, write the documentation def _get_decoder_method(stream_type): if stream_type is not None: return DSTREAM_TYPE_MAP.get(stream_type.upper(), (lambda x: x, lambda x: x))[0] else: return lambda x: x
As a python code expert, you are capable of creating scripts from specifications.
def _get_streams(self, uri_suffix=None): """Clear and update internal cache of stream objects""" # TODO: handle paging, perhaps change this to be a generator if uri_suffix is not None and not uri_suffix.startswith('/'): uri_suffix = '/' + uri_suffix elif uri_suffix is None: ...
Create a Python 3 function to get a list of all the streams in the system
As a Python code composer, you craft elegant and concise scripts.
def create_stream(self, stream_id, data_type, description=None, data_ttl=None, rollup_ttl=None, units=None): """Create a new data stream on Device Cloud This method will attempt to create a new data stream on Device Cloud. This method will only succeed if the stream does n...
How would you implement a function in Python 3 that creates a new data stream on Device Cloud This method will attempt to create a new data stream on Device Cloud. This method will only succeed if the stream does not already exist. :param str stream_id: The path/id of the stream being created on Device Cloud. :param st...
As a Python code analyst, you investigate and solve complex coding mysteries
Return a reference to a stream with the given stream_id if it exists.
How would you explain what the following Python 3 function does def get_stream_if_exists(self, stream_id): stream = self.get_stream(stream_id) try: stream.get_data_type(use_cached=True) except NoSuchStreamException: return None else: return stream
As a Python code analyst, you investigate and solve complex coding mysteries
def bulk_write_datapoints(self, datapoints): """Perform a bulk write (or set of writes) of a collection of data points This method takes a list (or other iterable) of datapoints and writes them to Device Cloud in an efficient manner, minimizing the number of HTTP requests that need to b...
Create a Python 3 function to perform a bulk write (or set of writes) of a collection of data points This method takes a list (or other iterable) of datapoints and writes them to Device Cloud in an efficient manner, minimizing the number of HTTP requests that need to be made. As this call is performed from outside the ...
As a Python code analyst, you investigate and solve complex coding mysteries
def from_json(cls, stream, json_data): """Create a new DataPoint object from device cloud JSON data :param DataStream stream: The :class:`~DataStream` out of which this data is coming :param dict json_data: Deserialized JSON data from Device Cloud about this device :raises ValueError: i...
Write a Python 3 script to create a new DataPoint object from a JSON data stream.
As a Python code composer, you craft elegant and concise scripts.
Create a new data point from a rollup json data stream.
How would you explain what the following Python 3 function does def from_rollup_json(cls, stream, json_data): dp = cls.from_json(stream, json_data) # Special handling for timestamp timestamp = isoformat(dc_utc_timestamp_to_dt(int(json_data.get("timestamp")))) # Special handling for dat...
As a python code expert, you are capable of creating scripts from specifications.
def set_stream_id(self, stream_id): """Set the stream id associated with this data point""" stream_id = validate_type(stream_id, type(None), *six.string_types) if stream_id is not None: stream_id = stream_id.lstrip('/') self._stream_id = stream_id
How would you code a function in Python 3 to set the stream id associated with this data point
As a Python code translator, you convert algorithms and pseudocode into Python.
Set the description for this data point
How would you explain what the following Python 3 function does def set_description(self, description): self._description = validate_type(description, type(None), *six.string_types)
As a Python code translator, you convert algorithms and pseudocode into Python.
Set the quality for this sample
Can you tell what is the following Python 3 function doing def set_quality(self, quality): if isinstance(quality, *six.string_types): quality = int(quality) elif isinstance(quality, float): quality = int(quality) self._quality = validate_type(quality, type(None), *six.in...
You are a Python code generator, capable of creating scripts from specifications.
Set the location for this data point.
Explain what the following Python 3 code does def set_location(self, location): if location is None: self._location = location elif isinstance(location, *six.string_types): # from device cloud, convert from csv parts = str(location).split(",") if len(parts) == 3: ...
As a Python code composer, you craft elegant and concise scripts.
Set the data type for the current entry point.
Can you generate the documentation for the following Python 3 function def set_data_type(self, data_type): validate_type(data_type, type(None), *six.string_types) if isinstance(data_type, *six.string_types): data_type = str(data_type).upper() if not data_type in ({None} | set(DSTREAM...
As a Python code translator, you convert algorithms and pseudocode into Python.
def set_units(self, unit): """Set the unit for this data point Unit, as with data_type, are actually associated with the stream and not the individual data point. As such, changing this within a stream is not encouraged. Setting the unit on the data point is useful when the st...
Write a Python 3 function that can set the unit for this data point
As a Python code composer, you craft elegant and concise scripts.
Convert this datapoint into a form suitable for pushing to device cloud cloud.
Make a summary of the following Python 3 code def to_xml(self): type_converter = _get_encoder_method(self._data_type) # Convert from python native to device cloud encoded_data = type_converter(self._data) out = StringIO() out.write("<DataPoint>") out.write("<streamId>{}<...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _get_stream_metadata(self, use_cached): """Retrieve metadata about this stream from Device Cloud""" if self._cached_data is None or not use_cached: try: self._cached_data = self._conn.get_json("/ws/DataStream/%s" % self._stream_id)["items"][0] except DeviceClo...
How would you code a function in Python 3 to retrieve metadata about this stream from Device Cloud
As a Python code composer, you craft elegant and concise scripts.
def get_data_type(self, use_cached=True): """Get the data type of this stream if it exists The data type is the type of data stored in this data stream. Valid types include: * INTEGER - data can be represented with a network (= big-endian) 32-bit two's-complement integer. Data with ...
Create a Python 3 function to get the data type of this data stream.
As a Python code composer, you craft elegant and concise scripts.
def get_data_ttl(self, use_cached=True): """Retrieve the dataTTL for this stream The dataTtl is the time to live (TTL) in seconds for data points stored in the data stream. A data point expires after the configured amount of time and is automatically deleted. :param bool use_cached: If...
Can you create a Python 3 function that retrieves the data TTL for this stream.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_rollup_ttl(self, use_cached=True): """Retrieve the rollupTtl for this stream The rollupTtl is the time to live (TTL) in seconds for the aggregate roll-ups of data points stored in the stream. A roll-up expires after the configured amount of time and is automatically deleted. ...
Can you create a Python 3 function that retrieves the rollupTtl associated with this stream in seconds.
As a python code expert, you are capable of creating scripts from specifications.
def get_current_value(self, use_cached=False): """Return the most recent DataPoint value written to a stream The current value is the last recorded data point for this stream. :param bool use_cached: If False, the function will always request the latest from Device Cloud. If True, ...
Write a Python 3 script to return the current value written to a stream.
As a Python code translator, you convert algorithms and pseudocode into Python.
Delete this stream from Device Cloud along with its history
Here you have a function in Python 3, explain what it does def delete(self): try: self._conn.delete("/ws/DataStream/{}".format(self.get_stream_id())) except DeviceCloudHttpException as http_excpeption: if http_excpeption.response.status_code == 404: raise NoSuchSt...
You are a Python code analyst, evaluating scripts for potential improvements.
def delete_datapoint(self, datapoint): """Delete the provided datapoint from this stream :raises devicecloud.DeviceCloudHttpException: in the case of an unexpected http error """ datapoint = validate_type(datapoint, DataPoint) self._conn.delete("/ws/DataPoint/{stream_id}/{datap...
Write a Python 3 script to delete the provided datapoint from this stream
You are a Python code analyst, evaluating scripts for potential improvements.
def delete_datapoints_in_time_range(self, start_dt=None, end_dt=None): """Delete datapoints from this stream between the provided start and end times If neither a start or end time is specified, all data points in the stream will be deleted. :param start_dt: The datetime after which da...
Can you implement a function in Python 3 that deletes datapoints from this stream between the provided start and end times.
As a Python code translator, you convert algorithms and pseudocode into Python.
def write(self, datapoint): """Write some raw data to a stream using the DataPoint API This method will mutate the datapoint provided to populate it with information available from the stream as it is available (but without making any new HTTP requests). For instance, we will add in in...
Write a Python 3 function that can write some raw data to a stream using the DataPoint API
As a Python code composer, you craft elegant and concise scripts.
Reads one or more data points from a Device Cloud stream.
How would you explain what the following Python 3 function does def read(self, start_time=None, end_time=None, use_client_timeline=True, newest_first=True, rollup_interval=None, rollup_method=None, timezone=None, page_size=1000): """Read one or more DataPoints from a stream .. warning:: ...
As a python code expert, you are capable of creating scripts from specifications.
def _quoted(value): """Return a single-quoted and escaped (percent-encoded) version of value This function will also perform transforms of known data types to a representation that will be handled by Device Cloud. For instance, datetime objects will be converted to ISO8601. """ if isinstance(...
How would you implement a function in Python 3 that returns a single - quoted and escaped version of value
You are a Python code architect, reviewing and designing scalable and efficient code
Compile this expression into a query string
Can you generate the documentation for the following Python 3 function def compile(self): return "{lhs}{sep}{rhs}".format( lhs=self.lhs.compile(), sep=self.sep, rhs=self.rhs.compile(), )
As a python code expert, you are capable of creating scripts from specifications.
Compile this expression into a query string
Explain what the following Python 3 code does def compile(self): return "{attribute}{sep}{value}".format( attribute=self.attribute, sep=self.sep, value=_quoted(self.value) )
You are a Python code analyst, evaluating scripts for potential improvements.
def _read_msg_header(session): """ Perform a read on input socket to consume headers and then return a tuple of message type, message length. :param session: Push Session to read data for. Returns response type (i.e. PUBLISH_MESSAGE) if header was completely read, otherwise None if header was ...
Write a Python 3 script to read a message header from the socket and return the response type.
You are a Python code architect, reviewing and designing scalable and efficient code
def _read_msg(session): """ Perform a read on input socket to consume message and then return the payload and block_id in a tuple. :param session: Push Session to read data for. """ if len(session.data) == session.message_length: # Data Already completely read. Return return Tr...
Can you create a Python 3 function that reads a message from the socket and return the payload and block_id in a tuple.
You are a Python code analyst, evaluating scripts for potential improvements.
Send a ConnectionRequest to the iDigi server.
Can you tell what is the following Python 3 function doing def send_connection_request(self): try: self.log.info("Sending ConnectionRequest for Monitor %s." % self.monitor_id) # Send connection request and perform a receive to ensure # request is aut...
As a python code expert, you are capable of creating scripts from specifications.
def start(self): """Creates a TCP connection to Device Cloud and sends a ConnectionRequest message""" self.log.info("Starting Insecure Session for Monitor %s" % self.monitor_id) if self.socket is not None: raise Exception("Socket already established for %s." % self) try: ...
Write a Python 3 script to start a TCP connection to Device Cloud and sends a ConnectionRequest message.
You are a Python code generator, capable of creating scripts from specifications.
def stop(self): """Stop/Close this session Close the socket associated with this session and puts Session into a state such that it can be re-established later. """ if self.socket is not None: self.socket.close() self.socket = None self.data =...
How would you code a function in Python 3 to stop the session and close the socket associated with this session.
As a Python code translator, you convert algorithms and pseudocode into Python.
def start(self): """ Creates a SSL connection to the iDigi Server and sends a ConnectionRequest message. """ self.log.info("Starting SSL Session for Monitor %s." % self.monitor_id) if self.socket is not None: raise Exception("Socket alrea...
Write a Python 3 function for starting the SSL connection to the iDigi Server and sends a ConnectionRequest message.
You are a Python code analyst, evaluating scripts for potential improvements.
Continually blocks until data is received from the internal queue and sends a PublishMessageReceived to the client.
Given the following Python 3 function, write the documentation def _consume_queue(self): while True: session, block_id, raw_data = self._queue.get() data = json.loads(raw_data.decode('utf-8')) # decode as JSON try: result = session.callback(data) ...
You are a Python code architect, reviewing and designing scalable and efficient code
Queues up a callback event to occur for a given session with the given payload data. Will block if the queue is full.
How would you explain what the following Python 3 function does def queue_callback(self, session, block_id, data): self._queue.put((session, block_id, data))
You are a Python code architect, reviewing and designing scalable and efficient code
Restarts and re - establishes the session.
Can you tell what is the following Python 3 function doing def _restart_session(self, session): # remove old session key, if socket is None, that means the # session was closed by user and there is no need to restart. if session.socket is not None: self.log.info("Attempting restart s...
You are a Python code analyst, evaluating scripts for potential improvements.
def _writer(self): """ Indefinitely checks the writer queue for data to write to socket. """ while not self.closed: try: sock, data = self._write_queue.get(timeout=0.1) self._write_queue.task_done() sock.send(data) ...
Can you write a function in Python 3 where it writes to the master socket.
As a python code expert, you are capable of creating scripts from specifications.
def _clean_dead_sessions(self): """ Traverses sessions to determine if any sockets were removed (indicates a stopped session). In these cases, remove the session. """ for sck in list(self.sessions.keys()): session = self.sessions[sck] if session.so...
Can you implement a function in Python 3 that traverses sessions to determine if any sockets were removed (indicates a stopped session). In these cases, remove the session.
As a Python code composer, you craft elegant and concise scripts.
Performs a socket select and returns a list of the unique identifiers.
Make a summary of the following Python 3 code def _select(self): try: while not self.closed: try: inputready = select.select(self.sessions.keys(), [], [], 0.1)[0] for sock in inputready: session = self.sessions[sock] ...
As a python code expert, you are capable of creating scripts from specifications.
def _init_threads(self): """Initializes the IO and Writer threads""" if self._io_thread is None: self._io_thread = Thread(target=self._select) self._io_thread.start() if self._writer_thread is None: self._writer_thread = Thread(target=self._writer) ...
How would you code a function in Python 3 to initialize the IO and Writer threads.
You are a Python code analyst, evaluating scripts for potential improvements.
Creates and returns a PushSession instance based on the input monitor_id and callback.
Can you tell what is the following Python 3 function doing def create_session(self, callback, monitor_id): self.log.info("Creating Session for Monitor %s." % monitor_id) session = SecurePushSession(callback, monitor_id, self, self._ca_certs) \ if self._secure else PushSession(callback, monit...
As a Python code analyst, you investigate and solve complex coding mysteries
Stops all session activity. Blocks until io and writer threads dies .
Can you generate the documentation for the following Python 3 function def stop(self): if self._io_thread is not None: self.log.info("Waiting for I/O thread to stop...") self.closed = True self._io_thread.join() if self._writer_thread is not None: self.lo...
You are a Python code architect, reviewing and designing scalable and efficient code