text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_registration_dt(self, use_cached=True):
"""Get the datetime of when this device was added to Device Cloud""" |
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:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 lon else None, ) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_to_group(self, group_path):
"""Add a device to a group, if the group doesn't exist it is created :param group_path: Path or "name" of the group """ |
if self.get_group_path() != group_path:
post_data = ADD_GROUP_TEMPLATE.format(connectware_id=self.get_connectware_id(),
group_path=group_path)
self._conn.put('/ws/DeviceCore', post_data)
# Invalidate cache
self.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 b... |
tags = self.get_tags()
orig_tag_cnt = len(tags)
# print("self.get_tags() {}".format(tags))
if isinstance(new_tags, six.string_types):
new_tags = new_tags.split(',')
# print("spliting tags :: {}".format(new_tags))
for tag in new_tags:
if not... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 l... |
tags = self.get_tags()
tags.remove(tag)
post_data = TAGS_TEMPLATE.format(connectware_id=self.get_connectware_id(),
tags=escape(",".join(tags)))
self._conn.put('/ws/DeviceCore', post_data)
# Invalidate cache
self._device_json = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iter_json_pages(self, path, page_size=1000, **params):
"""Return an iterator over JSON items from a paginated resource Legacy resources (prior to V1) impleme... |
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
while remaining_size > 0:
reqparams = {"start": offset, "size": page_size}
reqparams.update(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, path, **kwargs):
"""Perform an HTTP GET request of the specified path in Device Cloud Make an HTTP GET request against Device Cloud with this accou... |
url = self._make_url(path)
return self._make_request("GET", url, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_json(self, path, **kwargs):
"""Perform an HTTP GET request with JSON headers of the specified path against Device Cloud Make an HTTP GET request against ... |
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.text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 t... |
url = self._make_url(path)
return self._make_request("POST", url, data=data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put(self, path, data, **kwargs):
"""Perform an HTTP PUT request of the specified path in Device Cloud Make an HTTP PUT request against Device Cloud with this... |
url = self._make_url(path)
return self._make_request("PUT", url, data=data, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 r... |
url = self._make_url(path)
return self._make_request("DELETE", url, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 j... |
uri = "/ws/sci/{0}".format(job_id)
# TODO: do parsing here?
return self._conn.get(uri) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_sci_async(self, operation, target, payload, **sci_options):
"""Send an asynchronous SCI request, and wraps the job in an object to manage it :param str ... |
sci_options['synchronous'] = False
resp = self.send_sci(operation, target, payload, **sci_options)
dom = ET.fromstring(resp.content)
job_element = dom.find('.//jobId')
if job_element is None:
return
job_id = int(job_element.text)
return AsyncRequestPr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_sci(self, operation, target, payload, reply=None, synchronous=None, sync_timeout=None, cache=None, allow_offline=None, wait_for_reconnect=None):
"""Send... |
if not isinstance(payload, six.string_types) and not isinstance(payload, six.binary_type):
raise TypeError("payload is required to be a string or bytes")
# validate targets and bulid targets xml section
try:
iter(target)
targets = target
except TypeE... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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
parser = DateTimeParser()
try:
arrow_dt = arrow.Arrow.fromdatetime(parser.parse_iso(iso8601))
return a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
if input is None:
return input
elif isinstance(input, datetime.datetime):
arrow_dt = arrow.Arrow.fromdatetime(input, input.tzinfo or 'utc')
return arrow_dt.to('utc').datetime
if isinstance(input, six.string_types):
# try to convert from ISO8601
return iso8601_to_dt(i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 beyond the library boundaries")
return dt.isoformat().replace("+00:00", "Z") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_filedata(self, condition=None, page_size=1000):
"""Return a generator over all results matching the provided condition :param condition: An :class:`.Expr... |
condition = validate_type(condition, type(None), Expression, *six.string_types)
page_size = validate_type(page_size, *six.integer_types)
if condition is None:
condition = (fd_path == "~/") # home directory
params = {"embed": "true", "condition": condition.compile()}
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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: Th... |
path = validate_type(path, *six.string_types)
name = validate_type(name, *six.string_types)
data = validate_type(data, six.binary_type)
content_type = validate_type(content_type, type(None), *six.string_types)
archive_str = "true" if validate_type(archive, bool) else "false"
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.... |
path = validate_type(path, *six.string_types)
if not path.startswith("/"):
path = "/" + path
self._conn.delete("/ws/FileData{path}".format(path=path)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def walk(self, root="~/"):
"""Emulation of os.walk behavior against Device Cloud filedata store This method will yield tuples in the form ``(dirpath, FileDataDir... |
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 += "/"
for fd_object in self.get_filedata(fd_path == query_fd_path):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_data(self):
"""Get the data associated with this filedata object :returns: Data associated with this object or None if none exists :rtype: str (Python2)/... |
# 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
return base64.decodestring(six.b(base64_data)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_file(self, *args, **kwargs):
"""Write a file into this directory This method takes the same arguments as :meth:`.FileDataAPI.write_file` with the excep... |
return self._fdapi.write_file(self.get_path(), *args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_monitors(self, condition=None, page_size=1000):
"""Return an iterator over all monitors matching the provided condition Get all inactive monitors and pri... |
req_kwargs = {}
if condition:
req_kwargs['condition'] = condition.compile()
for monitor_data in self._conn.iter_json_pages("/ws/Monitor", **req_kwargs):
yield DeviceCloudMonitor.from_json(self._conn, monitor_data, self._tcp_client_manager) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_monitor(self, topics):
"""Attempts to find a Monitor in device cloud that matches the provided topics :param topics: a string list of topics (e.g. ``['De... |
for monitor in self.get_monitors(MON_TOPIC_ATTR == ",".join(topics)):
return monitor # return the first one, even if there are multiple
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_encoder_method(stream_type):
"""A function to get the python type to device cloud type converter function. :param stream_type: The streams data type :re... |
if stream_type is not None:
return DSTREAM_TYPE_MAP.get(stream_type.upper(), (lambda x: x, lambda x: x))[1]
else:
return lambda x: x |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_decoder_method(stream_type):
""" A function to get Device Cloud type to python type converter function. :param stream_type: The streams data type :retur... |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:
uri_suffix = ""
streams = {}
response = self._conn.get_json("/ws/DataStream{}... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 met... |
stream_id = validate_type(stream_id, *six.string_types)
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 (set([None, ]) | set(list(DSTREAM_TYPE_MAP.keys())... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_stream_if_exists(self, stream_id):
"""Return a reference to a stream with the given ``stream_id`` if it exists This works similar to :py:meth:`get_stream... |
stream = self.get_stream(stream_id)
try:
stream.get_data_type(use_cached=True)
except NoSuchStreamException:
return None
else:
return stream |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 whi... |
type_converter = _get_decoder_method(stream.get_data_type())
data = type_converter(json_data.get("data"))
return cls(
# these are actually properties of the stream, not the data point
stream_id=stream.get_stream_id(),
data_type=stream.get_data_type(),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_rollup_json(cls, stream, json_data):
"""Rollup json data from the server looks slightly different :param DataStream stream: The :class:`~DataStream` out... |
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 data, all rollup data is float type
type_converter = _get_decoder_method(stream.get_data_type())
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_description(self, description):
"""Set the description for this data point""" |
self._description = validate_type(description, type(None), *six.string_types) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_quality(self, quality):
"""Set the quality for this sample Quality is stored on Device Cloud as a 32-bit integer, so the input to this function should be... |
if isinstance(quality, *six.string_types):
quality = int(quality)
elif isinstance(quality, float):
quality = int(quality)
self._quality = validate_type(quality, type(None), *six.integer_types) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_location(self, location):
"""Set the location for this data point The location must be either None (if no location data is known) or a 3-tuple of floatin... |
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:
self._location = tuple(map(float, parts))
return
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_data_type(self, data_type):
"""Set the data type for ths data point The data type is actually associated with the stream itself and should not (generally... |
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_TYPE_MAP.keys())):
raise ValueError("Provided data type not in available set of types")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
self._units = validate_type(unit, type(None), *six.string_types) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_xml(self):
"""Convert this datapoint into a form suitable for pushing to device cloud An XML string will be returned that will contain all pieces of infor... |
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>{}</streamId>".format(self.get_stream_id()))
out.write("<d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 DeviceCloudHttpException as http_exception:
if http_exception.response.status_code == 404:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ty... |
dtype = self._get_stream_metadata(use_cached).get("dataType")
if dtype is not None:
dtype = dtype.upper()
return dtype |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 d... |
data_ttl_text = self._get_stream_metadata(use_cached).get("dataTtl")
return int(data_ttl_text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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-up... |
rollup_ttl_text = self._get_stream_metadata(use_cached).get("rollupTtl")
return int(rollup_ttl_text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 fo... |
current_value = self._get_stream_metadata(use_cached).get("currentValue")
if current_value:
return DataPoint.from_json(self, current_value)
else:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
"""Delete this stream from Device Cloud along with its history This call will return None on success and raise an exception in the event of an ... |
try:
self._conn.delete("/ws/DataStream/{}".format(self.get_stream_id()))
except DeviceCloudHttpException as http_excpeption:
if http_excpeption.response.status_code == 404:
raise NoSuchStreamException() # this branch is present, but the DC appears to just return... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_datapoint(self, datapoint):
"""Delete the provided datapoint from this stream :raises devicecloud.DeviceCloudHttpException: in the case of an unexpect... |
datapoint = validate_type(datapoint, DataPoint)
self._conn.delete("/ws/DataPoint/{stream_id}/{datapoint_id}".format(
stream_id=self.get_stream_id(),
datapoint_id=datapoint.get_id(),
)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
start_dt = to_none_or_dt(validate_type(start_dt, datetime.datetime, type(None)))
end_dt = to_none_or_dt(validate_type(end_dt, datetime.datetime, type(None)))
params = {}
if start_dt is not None:
params['startTime'] = isoformat(start_dt)
if end_dt is not None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 informa... |
if not isinstance(datapoint, DataPoint):
raise TypeError("First argument must be a DataPoint object")
datapoint._stream_id = self.get_stream_id()
if self._cached_data is not None and datapoint.get_data_type() is None:
datapoint._data_type = self.get_data_type()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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=100... |
is_rollup = False
if (rollup_interval is not None) or (rollup_method is not None):
is_rollup = True
numeric_types = [
STREAM_TYPE_INTEGER,
STREAM_TYPE_LONG,
STREAM_TYPE_FLOAT,
STREAM_TYPE_DOUBLE,
ST... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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: Pus... |
try:
data = session.socket.recv(6 - len(session.data))
if len(data) == 0: # No Data on Socket. Likely closed.
return NO_DATA
session.data += data
# Data still not completely read.
if len(session.data) < 6:
return INCOMPLETE
except ssl.SSLError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 t... |
if len(session.data) == session.message_length:
# Data Already completely read. Return
return True
try:
data = session.socket.recv(session.message_length - len(session.data))
if len(data) == 0:
raise PushException("No Data on Socket!")
session.data += data
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_connection_request(self):
""" Sends a ConnectionRequest to the iDigi server using the credentials established with the id of the monitor as defined in t... |
try:
self.log.info("Sending ConnectionRequest for Monitor %s."
% self.monitor_id)
# Send connection request and perform a receive to ensure
# request is authenticated.
# Protocol Version = 1.
payload = struct.pack('!H', 0x01)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 already established for %s." % self)
try:
# Create socket, wrap in SSL and connect.
self.socket = socket.socket(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _consume_queue(self):
""" Continually blocks until data is on the internal queue, then calls the session's registered callback and sends a PublishMessageRece... |
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)
if result is None:
self.log.warn("Callback %r returned None, exp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def queue_callback(self, session, block_id, data):
""" Queues up a callback event to occur for a session with the given payload data. Will block if the queue is ... |
self._queue.put((session, block_id, data)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _restart_session(self, session):
"""Restarts and re-establishes session :param session: The session to restart """ |
# 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 session for Monitor Id %s."
% session.monitor_id)
del self... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)
except Empty:
pass # nothing to write after timeout
except socket.error as err:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _select(self):
""" While the client is not marked as closed, performs a socket select on all PushSession sockets. If any data is received, parses and forward... |
try:
while not self.closed:
try:
inputready = select.select(self.sessions.keys(), [], [], 0.1)[0]
for sock in inputready:
session = self.sessions[sock]
sck = session.socket
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)
self._writer_thread.start() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_session(self, callback, monitor_id):
""" Creates and Returns a PushSession instance based on the input monitor and callback. When data is received, ca... |
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, monitor_id, self)
session.start()
self.sessions[session.socket.fileno()] = session
se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
"""Stops all session activity. Blocks until io and writer thread dies """ |
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.log.info("Waiting for Writer Thread to stop...")
self.closed = True
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def plotF0(fromTuple, toTuple, mergeTupleList, fnFullPath):
'''
Plots the original data in a graph above the plot of the dtw'ed data
'''
_matplotlibCheck()
plt.hold(True)
fig, (ax0) = plt.subplots(nrows=1)
# Old data
plot1 = ax0.plot(fromTuple[0], fromTuple[1], color='red',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getPitchForIntervals(data, tgFN, tierName):
'''
Preps data for use in f0Morph
'''
tg = tgio.openTextgrid(tgFN)
data = tg.tierDict[tierName].getValuesInIntervals(data)
data = [dataList for _, dataList in data]
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def f0Morph(fromWavFN, pitchPath, stepList,
outputName, doPlotPitchSteps, fromPitchData, toPitchData,
outputMinPitch, outputMaxPitch, praatEXE, keepPitchRange=False,
keepAveragePitch=False, sourcePitchDataList=None,
minIntervalLength=0.3):
'''
Resynthesizes the pi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def adjustPeakHeight(self, heightAmount):
'''
Adjust peak height
The foot of the accent is left unchanged and intermediate
values are linearly scaled
'''
if heightAmount == 0:
return
pitchList = [f0V for _, f0V in self.pointList]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def addPlateau(self, plateauAmount, pitchSampFreq=None):
'''
Add a plateau
A negative plateauAmount will move the peak backwards.
A positive plateauAmount will move the peak forwards.
All points on the side of the peak growth will also get moved.
i.e. th... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def shiftAccent(self, shiftAmount):
'''
Move the whole accent earlier or later
'''
if shiftAmount == 0:
return
self.pointList = [(time + shiftAmount, pitch)
for time, pitch in self.pointList]
# Update shift amounts
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def deleteOverlapping(self, targetList):
'''
Erase points from another list that overlap with points in this list
'''
start = self.pointList[0][0]
stop = self.pointList[-1][0]
if self.netLeftShift < 0:
start += self.netLeftShift
i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def reintegrate(self, fullPointList):
'''
Integrates the pitch values of the accent into a larger pitch contour
'''
# Erase the original region of the accent
fullPointList = _deletePoints(fullPointList, self.minT, self.maxT)
# Erase the new region of the accent
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def detect(filename, include_confidence=False):
""" Detect the encoding of a file. Returns only the predicted current encoding as a string. If `include_confidenc... |
f = open(filename)
detection = chardet.detect(f.read())
f.close()
encoding = detection.get('encoding')
confidence = detection.get('confidence')
if include_confidence:
return (encoding, confidence)
return encoding |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(url, localFileName=None, localDirName=None):
""" Utility function for downloading files from the web and retaining the same filename. """ |
localName = url2name(url)
req = Request(url)
r = urlopen(req)
if r.info().has_key('Content-Disposition'):
# If the response has Content-Disposition, we take file name from it
localName = r.info()['Content-Disposition'].split('filename=')
if len(localName) > 1:
localN... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _t(unistr, charset_from, charset_to):
""" This is a unexposed function, is responsibility for translation internal. """ |
# if type(unistr) is str:
# try:
# unistr = unistr.decode('utf-8')
# # Python 3 returns AttributeError when .decode() is called on a str
# # This means it is already unicode.
# except AttributeError:
# pass
# try:
# if type(unistr) is not unicode:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def identify(text):
"""Identify whether a string is simplified or traditional Chinese. Returns: None: if there are no recognizd Chinese characters. EITHER: if th... |
filtered_text = set(list(text)).intersection(ALL_CHARS)
if len(filtered_text) is 0:
return None
if filtered_text.issubset(SHARED_CHARS):
return EITHER
if filtered_text.issubset(TRAD_CHARS):
return TRAD
if filtered_text.issubset(SIMP_CHARS):
return SIMP
if filtere... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def makeSequenceRelative(absVSequence):
'''
Puts every value in a list on a continuum between 0 and 1
Also returns the min and max values (to reverse the process)
'''
if len(absVSequence) < 2 or len(set(absVSequence)) == 1:
raise RelativizeSequenceException(absVSequence)
minV = min(ab... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def makeSequenceAbsolute(relVSequence, minV, maxV):
'''
Makes every value in a sequence absolute
'''
return [(value * (maxV - minV)) + minV for value in relVSequence] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _makeTimingRelative(absoluteDataList):
'''
Given normal pitch tier data, puts the times on a scale from 0 to 1
Input is a list of tuples of the form
([(time1, pitch1), (time2, pitch2),...]
Also returns the start and end time so that the process can be reversed
'''
timingSeq = [row[0] ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _makeTimingAbsolute(relativeDataList, startTime, endTime):
'''
Maps values from 0 to 1 to the provided start and end time
Input is a list of tuples of the form
([(time1, pitch1), (time2, pitch2),...]
'''
timingSeq = [row[0] for row in relativeDataList]
valueSeq = [list(row[1:]) for row... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _getSmallestDifference(inputList, targetVal):
'''
Returns the value in inputList that is closest to targetVal
Iteratively splits the dataset in two, so it should be pretty fast
'''
targetList = inputList[:]
retVal = None
while True:
# If we're down to one value, stop iterati... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _getNearestMappingIndexList(fromValList, toValList):
'''
Finds the indicies for data points that are closest to each other.
The inputs should be in relative time, scaled from 0 to 1
e.g. if you have [0, .1, .5., .9] and [0, .1, .2, 1]
will output [0, 1, 1, 2]
'''
indexList = []
for... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def morphChunkedDataLists(fromDataList, toDataList, stepList):
'''
Morph one set of data into another, in a stepwise fashion
A convenience function. Given a set of paired data lists,
this will morph each one individually.
Returns a single list with all data combined together.
'''
assert(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def morphAveragePitch(fromDataList, toDataList):
'''
Adjusts the values in fromPitchList to have the same average as toPitchList
Because other manipulations can alter the average pitch, morphing the pitch
is the last pitch manipulation that should be done
After the morphing, the code remov... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def morphRange(fromDataList, toDataList):
'''
Changes the scale of values in one distribution to that of another
ie The maximum value in fromDataList will be set to the maximum value in
toDataList. The 75% largest value in fromDataList will be set to the
75% largest value in toDataList, etc.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getIntervals(fn, tierName, filterFunc=None,
includeUnlabeledRegions=False):
'''
Get information about the 'extract' tier, used by several merge scripts
'''
tg = tgio.openTextgrid(fn)
tier = tg.tierDict[tierName]
if includeUnlabeledRegions is True:
tier = tgio._... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def changeDuration(fromWavFN, durationParameters, stepList, outputName,
outputMinPitch, outputMaxPitch, praatEXE):
'''
Uses praat to morph duration in one file to duration in another
Praat uses the PSOLA algorithm
'''
rootPath = os.path.split(fromWavFN)[0]
# Prep output dir... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def textgridMorphDuration(fromTGFN, toTGFN):
'''
A convenience function. Morphs interval durations of one tg to another.
This assumes the two textgrids have the same number of segments.
'''
fromTG = tgio.openTextgrid(fromTGFN)
toTG = tgio.openTextgrid(toTGFN)
adjustedTG = tgio.Textgrid... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split_text(text, include_part_of_speech=False, strip_english=False, strip_numbers=False):
u""" Split Chinese text at word boundaries. include_pos: also retur... |
if not include_part_of_speech:
seg_list = pseg.cut(text)
if strip_english:
seg_list = filter(lambda x: not contains_english(x), seg_list)
if strip_numbers:
seg_list = filter(lambda x: not _is_number(x), seg_list)
return list(map(lambda i: i.word, seg_list))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_special_atom(cron_atom, span):
""" Returns a boolean indicating whether or not the string can be parsed by parse_atom to produce a static set. In the proc... |
for special_char in ('%', '#', 'L', 'W'):
if special_char not in cron_atom:
continue
if special_char == '#':
if span != DAYS_OF_WEEK:
raise ValueError("\"#\" invalid where used.")
elif not VALIDATE_POUND.match(cron_atom):
raise Va... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_atom(parse, minmax):
""" Returns a set containing valid values for a given cron-style range of numbers. The 'minmax' arguments is a two element iterabl... |
parse = parse.strip()
increment = 1
if parse == '*':
return set(xrange(minmax[0], minmax[1] + 1))
elif parse.isdigit():
# A single number still needs to be returned as a set
value = int(parse)
if value >= minmax[0] and value <= minmax[1]:
return set((value,))... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_numtab(self):
""" Recomputes the sets for the static ranges of the trigger time. This method should only be called by the user if the string_tab memb... |
self.numerical_tab = []
for field_str, span in zip(self.string_tab, FIELD_RANGES):
split_field_str = field_str.split(',')
if len(split_field_str) > 1 and "*" in split_field_str:
raise ValueError("\"*\" must be alone in a field.")
unified = set()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_trigger(self, date_tuple, utc_offset=0):
""" Returns boolean indicating if the trigger is active at the given time. The date tuple should be in the loc... |
year, month, day, hour, mins = date_tuple
given_date = datetime.date(year, month, day)
zeroday = datetime.date(*self.epoch[:3])
last_dom = calendar.monthrange(year, month)[-1]
dom_matched = True
# In calendar and datetime.date.weekday, Monday = 0
given_dow = (da... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show(self):
"""Show the structure of self.rules_list, only for debug.""" |
for rule in self.rules_list:
result = ", ".join([str(check) for check, deny in rule])
print(result) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
"""Run self.rules_list. Return True if one rule channel has been passed. Otherwise return False and the deny() method of the last failed rule. """ |
failed_result = None
for rule in self.rules_list:
for check, deny in rule:
if not check():
failed_result = (False, deny)
break
else:
return (True, None)
return failed_result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_fraction(self, value):
"""Set the meter indicator. Value should be between 0 and 1.""" |
if value < 0:
value *= -1
value = min(value, 1)
if self.horizontal:
width = int(self.width * value)
height = self.height
else:
width = self.width
height = int(self.height * value)
self.canvas.coords(self.meter, self.xpo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_status(self):
"""Update status informations in tkinter window.""" |
try:
# all this may fail if the connection to the fritzbox is down
self.update_connection_status()
self.max_stream_rate.set(self.get_stream_rate_str())
self.ip.set(self.status.external_ip)
self.uptime.set(self.status.str_uptime)
upstream, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_num(num, unit='bytes'):
""" Returns a human readable string of a byte-value. If 'num' is bits, set unit='bits'. """ |
if unit == 'bytes':
extension = 'B'
else:
# if it's not bytes, it's bits
extension = 'Bit'
for dimension in (unit, 'K', 'M', 'G', 'T'):
if num < 1024:
if dimension == unit:
return '%3.1f %s' % (num, dimension)
return '%3.1f %s%s' % (nu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_headers(content_disposition, location=None, relaxed=False):
"""Build a ContentDisposition from header values. """ |
LOGGER.debug(
'Content-Disposition %r, Location %r', content_disposition, location)
if content_disposition is None:
return ContentDisposition(location=location)
# Both alternatives seem valid.
if False:
# Require content_disposition to be ascii bytes (0-127),
# or cha... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_header( filename, disposition='attachment', filename_compat=None ):
"""Generate a Content-Disposition header for a given filename. For legacy clients t... |
# While this method exists, it could also sanitize the filename
# by rejecting slashes or other weirdness that might upset a receiver.
if disposition != 'attachment':
assert is_token(disposition)
rv = disposition
if is_token(filename):
rv += '; filename=%s' % (filename, )
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.