Instruction:
Can you create a Python 3 function that
makes a request to the specified service.

Response:
async def make_request(self, service: str, method: str, path: str,
                           body: bytes=None, query: str=None,
                           headers: dict=None, correlation_id: str=None,
                           content_type: str=None,
                           timeout:int = 30,
                           **kwargs) -> webtypes.Response:
        """
        Method for actually making a request
        :param service: service to make request too
        :param method: HTTP method: GET/PUT/POST etc.
        :param path: routing path.
            Should support dots `foo.2.bars` or slashes `foo/2/bars`
        :param body: request body. Bytes-like object
        :param query: query string. Example: `foo=bar&cabbage=green`
        :param headers: Dictionary of headers
        :param correlation_id:
        :param content_type: example: `application/json`
        :param timeout: time to wait for response in seconds before getting
            an asyncio.TimeoutError
        :param kwargs: Should except **kwargs for compatability for
            other possible options on other transports
            (for example, http might need a `port` option)
        :return:
        """


Instruction:
Given the following Python 3 function, write the documentation
def execute(self, request_object):

        # If the request object is not valid then return a failure response
        if not request_object.is_valid:
            return ResponseFailure.build_from_invalid_request(
                request_object)

        # Try to process the request and handle any errors encountered
        try:
            return self.process_request(request_object)

        except ValidationError as err:
            return ResponseFailure.build_unprocessable_error(err.normalized_messages)

        except ObjectNotFoundError:
            return ResponseFailure.build_not_found(
                [{'identifier': 'Object with this ID does not exist.'}])

        except Exception as exc:
            logger.error(
                f'{self.__class__.__name__} execution failed due to error {exc}',
                exc_info=True)
            return ResponseFailure.build_system_error([{exc.__class__.__name__: exc}])

Response: Generic executor method of all UseCases


Instruction:
How would you explain what the following Python 3 function does
def FunctionTimer(on_done=None):
    '''
    To check execution time of a function
    borrowed from https://medium.com/pythonhive/python-decorator-to-measure-the-execution-time-of-methods-fa04cb6bb36d

    >>> def logger(details, args, kwargs): #some function that uses the time output
    ...     print(details)
    ...
    >>> @FunctionTimer(on_done= logger)
    ... def foo(t=10):
    ...     print('foo executing...')
    ...     time.sleep(t)
    ...
    >>> @FunctionTimer(on_done= logger)
    ... def bar(t, n):
    ...     for i in range(n):
    ...             print('bar executing...')
    ...             time.sleep(1)
    ...     foo(t)
    ...
    >>> bar(3,2)
    bar executing...
    bar executing...
    foo executing...
    ('foo', 3)
    ('bar', 5)
    '''
    def decfn(fn):

        def timed(*args, **kwargs):
            ts = time.time()
            result = fn(*args, **kwargs)
            te = time.time()
            if on_done:
                on_done((fn.__name__,int(te - ts)), args, kwargs)
            else:
                print(('%r  %d sec(s)' % (fn.__name__, (te - ts))))

            return result

        return timed

    return decfn

Response: Decorator to measure execution time of a function in a sequence.


Instruction:
Explain what the following Python 3 code does
async def exchange_declare(self):
        await self.channel.exchange_declare(
            self.exchange,
            self.exchange_type,
            durable=self.durable,
            auto_delete=self.auto_delete,
            no_wait=self.no_wait,
        )

Response: Override this method to change how an exchange is declared


Instruction:
Explain what the following Python 3 code does
async def queue_declare(self):
        await self.channel.queue_declare(
                self.queue,
                durable=self.durable,
                exclusive=self.exclusive,
                no_wait=self.no_wait
            )

Response: Override this method to change how a queue is declared


Instruction:
Can you write a function in Python 3 where it
converts the given entity to a dictionary record

Response:
def from_entity(cls, entity: Entity) -> 'DictModel':
        """Convert the entity to a dictionary record """
        dict_obj = {}
        for field_name in entity.meta_.attributes:
            dict_obj[field_name] = getattr(entity, field_name)
        return dict_obj


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_connection(self):
        database = {
            'data': _databases.setdefault(self.identifier, defaultdict(dict)),
            'lock': _locks.setdefault(self.identifier, Lock()),
            'counters': _counters
        }
        return database

Response: Return the dictionary database object


Instruction:
Can you create a Python 3 function that
returns a repository object configured with a live connection

Response:
def get_repository(self, entity_cls):
        """Return a repository object configured with a live connection"""
        model_cls = self.get_model(entity_cls)
        return DictRepository(self, entity_cls, model_cls)


Instruction:
Can you tell what is the following Python 3 function doing
def _evaluate_lookup(self, key, value, negated, db):
        results = {}
        for record_key, record_value in db.items():
            match = True

            stripped_key, lookup_class = self._extract_lookup(key)
            lookup = lookup_class(record_value[stripped_key], value)

            if negated:
                match &= not eval(lookup.as_expression())
            else:
                match &= eval(lookup.as_expression())

            if match:
                results[record_key] = record_value

        return results

Response: Evaluate the lookup criteria for the given key and value in the given database.


Instruction:
Write a Python 3 function that can
run raw queries on the database and return all results.

Response:
def raw(self, query: Any, data: Any = None):
        """Run raw queries on the database

        As an example of running ``raw`` queries on a Dict repository, we will run the query
        on all possible schemas, and return all results.
        """
        assert isinstance(query, str)

        conn = self.get_connection()
        items = []

        for schema_name in conn['data']:
            input_db = conn['data'][schema_name]
            try:
                # Ensures that the string contains double quotes around keys and values
                query = query.replace("'", "\"")
                criteria = json.loads(query)

                for key, value in criteria.items():
                    input_db = self._evaluate_lookup(key, value, False, input_db)

                items.extend(list(input_db.values()))

            except json.JSONDecodeError:
                # FIXME Log Exception
                raise Exception("Query Malformed")
            except KeyError:
                # We encountered a repository where the key was not found
                pass

        return items


Instruction:
Can you create a Python 3 function that
sets the values of the auto fields using counter

Response:
def _set_auto_fields(self, model_obj):
        """Set the values of the auto field using counter"""
        for field_name, field_obj in \
                self.entity_cls.meta_.auto_fields:
            counter_key = f'{self.schema_name}_{field_name}'
            if not (field_name in model_obj and model_obj[field_name] is not None):
                # Increment the counter and it should start from 1
                counter = next(self.conn['counters'][counter_key])
                if not counter:
                    counter = next(self.conn['counters'][counter_key])

                model_obj[field_name] = counter
        return model_obj


Instruction:
Write a Python 3 function that can
write a record to the dict repository

Response:
def create(self, model_obj):
        """Write a record to the dict repository"""
        # Update the value of the counters
        model_obj = self._set_auto_fields(model_obj)

        # Add the entity to the repository
        identifier = model_obj[self.entity_cls.meta_.id_field.field_name]
        with self.conn['lock']:
            self.conn['data'][self.schema_name][identifier] = model_obj

        return model_obj


Instruction:
Can you generate the documentation for the following Python 3 function
def _filter(self, criteria: Q, db):
        # Filter the dictionary objects based on the filters
        negated = criteria.negated
        input_db = None

        if criteria.connector == criteria.AND:
            # Trim database records over successive iterations
            #   Whatever is left at the end satisfy all criteria (AND)
            input_db = db
            for child in criteria.children:
                if isinstance(child, Q):
                    input_db = self._filter(child, input_db)
                else:
                    input_db = self.provider._evaluate_lookup(child[0], child[1],
                                                              negated, input_db)
        else:
            # Grow database records over successive iterations
            #   Whatever is left at the end satisfy any criteria (OR)
            input_db = {}
            for child in criteria.children:
                if isinstance(child, Q):
                    results = self._filter(child, db)
                else:
                    results = self.provider._evaluate_lookup(child[0], child[1], negated, db)

                input_db = {**input_db, **results}

        return input_db

Response: Recursive function to filter items from dictionary based on the filters


Instruction:
Make a summary of the following Python 3 code
def filter(self, criteria: Q, offset: int = 0, limit: int = 10, order_by: list = ()):

        if criteria.children:
            items = list(self._filter(criteria, self.conn['data'][self.schema_name]).values())
        else:
            items = list(self.conn['data'][self.schema_name].values())

        # Sort the filtered results based on the order_by clause
        for o_key in order_by:
            reverse = False
            if o_key.startswith('-'):
                reverse = True
                o_key = o_key[1:]
            items = sorted(items, key=itemgetter(o_key), reverse=reverse)

        result = ResultSet(
            offset=offset,
            limit=limit,
            total=len(items),
            items=items[offset: offset + limit])
        return result

Response: Read the repository and return results as per the filer


Instruction:
How would you code a function in Python 3 to
update the entity record in the dictionary

Response:
def update(self, model_obj):
        """Update the entity record in the dictionary """
        identifier = model_obj[self.entity_cls.meta_.id_field.field_name]
        with self.conn['lock']:
            # Check if object is present
            if identifier not in self.conn['data'][self.schema_name]:
                raise ObjectNotFoundError(
                    f'`{self.__class__.__name__}` object with identifier {identifier} '
                    f'does not exist.')

            self.conn['data'][self.schema_name][identifier] = model_obj
        return model_obj


Instruction:
Explain what the following Python 3 code does
def update_all(self, criteria: Q, *args, **kwargs):
        items = self._filter(criteria, self.conn['data'][self.schema_name])

        update_count = 0
        for key in items:
            item = items[key]
            item.update(*args)
            item.update(kwargs)
            self.conn['data'][self.schema_name][key] = item

            update_count += 1

        return update_count

Response: Update all objects satisfying the criteria


Instruction:
Here you have a function in Python 3, explain what it does
def delete_all(self, criteria: Q = None):
        if criteria:
            # Delete the object from the dictionary and return the deletion count
            items = self._filter(criteria, self.conn['data'][self.schema_name])

            # Delete all the matching identifiers
            with self.conn['lock']:
                for identifier in items:
                    self.conn['data'][self.schema_name].pop(identifier, None)

            return len(items)
        else:
            with self.conn['lock']:
                if self.schema_name in self.conn['data']:
                    del self.conn['data'][self.schema_name]

Response: Delete all the items in the dictionary by its criteria


Instruction:
Write a Python 3 function for
running raw query on Repository.

Response:
def raw(self, query: Any, data: Any = None):
        """Run raw query on Repository.

        For this stand-in repository, the query string is a json string that contains kwargs
        criteria with straigh-forward equality checks. Individual criteria are always ANDed
        and the result is always a subset of the full repository.

        We will ignore the `data` parameter for this kind of repository.
        """
        # Ensure that we are dealing with a string, for this repository
        assert isinstance(query, str)

        input_db = self.conn['data'][self.schema_name]
        result = None

        try:
            # Ensures that the string contains double quotes around keys and values
            query = query.replace("'", "\"")
            criteria = json.loads(query)

            for key, value in criteria.items():
                input_db = self.provider._evaluate_lookup(key, value, False, input_db)

            items = list(input_db.values())
            result = ResultSet(
                offset=1,
                limit=len(items),
                total=len(items),
                items=items)

        except json.JSONDecodeError:
            # FIXME Log Exception
            raise Exception("Query Malformed")

        return result


Instruction:
Make a summary of the following Python 3 code
def process_source(self):
        if isinstance(self.source, str):
            # Replace single and double quotes with escaped single-quote
            self.source = self.source.replace("'", "\'").replace('"', "\'")
            return "\"{source}\"".format(source=self.source)
        return self.source

Response: Return source with transformations if any


Instruction:
Write a Python 3 script to
return target with transformations if any

Response:
def process_target(self):
        """Return target with transformations, if any"""
        if isinstance(self.target, str):
            # Replace single and double quotes with escaped single-quote
            self.target = self.target.replace("'", "\'").replace('"', "\'")
            return "\"{target}\"".format(target=self.target)
        return self.target


Instruction:
Write a Python 3 script for
returning a response dict like Trial because Status can t be pickled.

Response:
def challenge(arg: ChallengeArg) -> dict:
    """ Response is dict like `Trial` because Status(OwlEnum) can't be pickled.
    """

    name: str = arg.req.name.get_or(str(arg.seq))
    log_prefix = f"[{arg.seq} / {arg.number_of_request}]"

    logger.info_lv3(f"{log_prefix} {'-'*80}")
    logger.info_lv3(f"{log_prefix}  {arg.seq}. {arg.req.name.get_or(arg.req.path)}")
    logger.info_lv3(f"{log_prefix} {'-'*80}")

    path_str_one = arg.path_one.map(lambda x: re.sub(x.before, x.after, arg.req.path)).get_or(arg.req.path)
    path_str_other = arg.path_other.map(lambda x: re.sub(x.before, x.after, arg.req.path)).get_or(arg.req.path)
    qs_str_one = create_query_string(arg.req.qs, arg.query_one, arg.req.url_encoding)
    qs_str_other = create_query_string(arg.req.qs, arg.query_other, arg.req.url_encoding)
    url_one = f'{arg.host_one}{path_str_one}?{qs_str_one}'
    url_other = f'{arg.host_other}{path_str_other}?{qs_str_other}'

    # Get two responses
    req_time = now()
    try:
        logger.info_lv3(f"{log_prefix} One   URL:   {url_one}")
        logger.debug(f"{log_prefix} One   PROXY: {arg.proxy_one.map(lambda x: x.to_dict()).get()}")
        logger.info_lv3(f"{log_prefix} Other URL:   {url_other}")
        logger.debug(f"{log_prefix} Other PROXY: {arg.proxy_other.map(lambda x: x.to_dict()).get()}")
        r_one, r_other = concurrent_request(arg.session, arg.req.headers,
                                            url_one, url_other,
                                            arg.proxy_one, arg.proxy_other)
        logger.info_lv3(
            f"{log_prefix} One:   {r_one.status_code} / {to_sec(r_one.elapsed)}s / {len(r_one.content)}b / {r_one.headers.get('content-type')}" # noqa
        )
        logger.info_lv3(
            f"{log_prefix} Other: {r_other.status_code} / {to_sec(r_other.elapsed)}s / {len(r_other.content)}b / {r_other.headers.get('content-type')}" # noqa
        )
    except ConnectionError:
        logger.info_lv1(f"{log_prefix} 💀 {arg.req.name.get()}")
        # TODO: Integrate logic into create_trial
        return {
            "seq": arg.seq,
            "name": name,
            "tags": [],
            "request_time": req_time.isoformat(),
            "status": 'failure',
            "path": arg.req.path,
            "queries": arg.req.qs,
            "headers": arg.req.headers,
            "one": {
                "url": url_one,
                "type": "unknown",
            },
            "other": {
                "url": url_other,
                "type": "unknown",
            }
        }

    res_one: Response = res2res(Response.from_requests(r_one, arg.default_response_encoding_one), arg.req)
    res_other: Response = res2res(Response.from_requests(r_other, arg.default_response_encoding_other), arg.req)

    dict_one: TOption[dict] = res2dict(res_one)
    dict_other: TOption[dict] = res2dict(res_other)

    # Create diff
    # Either dict_one or dic_other is None, it means that it can't be analyzed, therefore return None
    ddiff = None if dict_one.is_none() or dict_other.is_none() \
        else {} if res_one.body == res_other.body \
        else DeepDiff(dict_one.get(), dict_other.get())

    initial_diffs_by_cognition: Optional[TDict[DiffKeys]] = TDict({
        "unknown": DiffKeys.from_dict({
            "changed": TList(ddiff.get('type_changes', {}).keys() | ddiff.get('values_changed', {}).keys())
                .map(to_jumeaux_xpath)
                .order_by(_),
            "added": TList(ddiff.get('dictionary_item_added', {}) | ddiff.get('iterable_item_added', {}).keys())
                .map(to_jumeaux_xpath)
                .order_by(_),
            "removed": TList(ddiff.get('dictionary_item_removed', {}) | ddiff.get('iterable_item_removed', {}).keys())
                .map(to_jumeaux_xpath)
                .order_by(_)
        })
    }) if ddiff is not None else None

    # Judgement
    status, diffs_by_cognition = judgement(res_one, res_other, dict_one, dict_other,
                                           name, arg.req.path, arg.req.qs, arg.req.headers, initial_diffs_by_cognition)
    status_symbol = "O" if status == Status.SAME else "X"
    log_msg = f"{log_prefix} {status_symbol} ({res_one.status_code} - {res_other.status_code}) <{res_one.elapsed_sec}s - {res_other.elapsed_sec}s> {arg.req.name.get_or(arg.req.path)}"  # noqa
    (logger.info_lv2 if status == Status.SAME else logger.info_lv1)(log_msg)

    file_one: Optional[str] = None
    file_other: Optional[str] = None
    prop_file_one: Optional[str] = None
    prop_file_other: Optional[str] = None
    if store_criterion(status, name, arg.req, res_one, res_other):
        dir = f'{arg.res_dir}/{arg.key}'
        file_one = f'one/({arg.seq}){name}'
        file_other = f'other/({arg.seq}){name}'
        write_to_file(file_one, dir, dump(res_one))
        write_to_file(file_other, dir, dump(res_other))
        if not dict_one.is_none():
            prop_file_one = f'one-props/({arg.seq}){name}.json'
            write_to_file(prop_file_one, dir, TDict(dict_one.get()).to_json().encode('utf-8', errors='replace'))
        if not dict_other.is_none():
            prop_file_other = f'other-props/({arg.seq}){name}.json'
            write_to_file(prop_file_other, dir, TDict(dict_other.get()).to_json().encode('utf-8', errors='replace'))

    return global_addon_executor.apply_did_challenge(
        DidChallengeAddOnPayload.from_dict({
            "trial": Trial.from_dict({
                "seq": arg.seq,
                "name": name,
                "tags": [], # TODO: tags created by reqs2reqs
                "request_time": req_time.isoformat(),
                "status": status,
                "path": arg.req.path,
                "queries": arg.req.qs,
                "headers": arg.req.headers,
                "diffs_by_cognition": diffs_by_cognition,
                "one": {
                    "url": res_one.url,
                    "type": res_one.type,
                    "status_code": res_one.status_code,
                    "byte": res_one.byte,
                    "response_sec": res_one.elapsed_sec,
                    "content_type": res_one.content_type,
                    "mime_type": res_one.mime_type,
                    "encoding": res_one.encoding,
                    "file": file_one,
                    "prop_file": prop_file_one,
                },
                "other": {
                    "url": res_other.url,
                    "type": res_other.type,
                    "status_code": res_other.status_code,
                    "byte": res_other.byte,
                    "response_sec": res_other.elapsed_sec,
                    "content_type": res_other.content_type,
                    "mime_type": res_other.mime_type,
                    "encoding": res_other.encoding,
                    "file": file_other,
                    "prop_file": prop_file_other,
                }
            })
        }),
        DidChallengeAddOnReference.from_dict({
            "res_one": res_one,
            "res_other": res_other,
            "res_one_props": dict_one,
            "res_other_props": dict_other,
        })
    ).trial.to_dict()


Instruction:
How would you implement a function in Python 3 that
parses a URL to a topic.

Response:
def parse_url_to_topic(method, route):
    """
    Transforms a URL to a topic.

    `GET /bar/{id}` -> `get.bar.*`
    `POST /bar/{id}` -> `post.bar.*`
    `GET /foo/bar/{id}/baz` -? `get.foo.bar.*.baz`

    Possible gotchas

    `GET /foo/{id}` -> `get.foo.*`
    `GET /foo/{id}:action` -> `get.foo.*`

    However, once it hits the service the router will be able to distinguish the two requests.
    """
    route = route.replace('.', '?')
    route = route.replace('/', '.').strip('.')
    topic = f'{method.value.lower()}.{route}'
    # need to replace `{id}` and `{id}:some_method` with just `*`
    return re.sub(r"\.\{[^\}]*\}[:\w\d_-]*", ".*", topic)


Instruction:
Can you implement a function in Python 3 that
uses for example of Transformer. function

Response:
def wrap(anything: bytes, encoding: str) -> str:
    """Use for example of Transformer.function
    """
    return json.dumps({
        "wrap": load_json(anything.decode(encoding))
    }, ensure_ascii=False)


Instruction:
Create a Python 3 function for
returning a ResultSet containing only the records matching the given criteria.

Response:
def filter(self, criteria: Q, offset: int = 0, limit: int = 10,
               order_by: list = ()) -> ResultSet:
        """
        Filter objects from the repository. Method must return a `ResultSet`
        object
        """


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _format_fields(cls, declared_fields: typing.List[tuple]):
        formatted_fields = []
        for declared_field in declared_fields:
            field_name = field_type = field_defn = None

            # Case when only (name), or "name", is specified
            if isinstance(declared_field, str) or len(declared_field) == 1:
                field_name = declared_field
                field_type = typing.Any
                field_defn = field(default=None)

            # Case when (name, type) are specified
            elif len(declared_field) == 2:
                field_name = declared_field[0]
                field_type = declared_field[1]
                field_defn = field(default=None)

            # Case when (name, type, field) are specified
            elif len(declared_field) == 3:
                field_name = declared_field[0]
                field_type = declared_field[1]

                # Process the definition and create a `field` object
                # Definition will be of the form `{'required': False, 'default': 'John'}`
                assert isinstance(declared_field[2], dict)
                metadata = default = None
                if 'required' in declared_field[2] and declared_field[2]['required']:
                    metadata = {'required': True}
                if 'default' in declared_field[2]:
                    default = declared_field[2]['default']
                field_defn = field(default=default, metadata=metadata)

            formatted_fields.append((field_name, field_type, field_defn))

        return formatted_fields

Response: Process the declared fields and construct a list of tuples that can be fed into dataclass constructor factory factory.


Instruction:
Create a Python 3 function to
save a sequence of samples as a WAV file

Response:
def save(params, filename, source):
    '''
    Write a sequence of samples as a WAV file
    Currently a 16 bit mono file
    '''
    writer = wave.open(filename, 'wb');
    # Set the WAV file parameters, currently default values
    writer.setnchannels(1)
    writer.setsampwidth(2)
    writer.setframerate(params.sample_rate)
    data_out = array.array('h')
    for x in source:
        data_out.append(int(x * 32766))
    writer.writeframes(data_out.tostring())
    writer.close()


Instruction:
Implement a Python 3 function for
returning the item with the lowest priority. Raises IndexError if the object is empty.

Response:
def smallest(self):
        """Return the item with the lowest priority.

        Raises IndexError if the object is empty.
        """

        heap = self._heap
        v, k = heap[0]
        while k not in self or self[k] != v:
            heappop(heap)
            v, k = heap[0]

        return k


Instruction:
Can you generate a brief explanation for the following Python 3 code
def pop_smallest(self):

        heap = self._heap
        v, k = heappop(heap)
        while k not in self or self[k] != v:
            v, k = heappop(heap)
        del self[k]
        return k

Response: Return the item with the lowest priority and remove it. Raises IndexError if the object is empty. Returns the item with the lowest priority and remove it. Raises IndexError if the object is empty.


Instruction:
Can you create a Python 3 function that
decodes the original body.

Response:
def body(self) -> dict:
        """ Decoded Body """
        if self.ignore_content_type:
            return self.original_body
        if self._body is None and self.original_body is not None:
            if isinstance(self.original_body, bytes):
                self._body = self.parser.decode(self.original_body)
            else:
                self._body = self.original_body
        return self._body


Instruction:
Create a Python 3 function for
returning the raw HTTP request body.

Response:
def raw_body(self) -> bytes:
        """ Encoded Body """
        if self._raw_body is None and self.original_body is not None:
            if isinstance(self.original_body, dict):
                self._raw_body = self.parser.encode(self.original_body)
                if isinstance(self._raw_body, str):
                    self._raw_body = self._raw_body.encode()
            elif isinstance(self.original_body, str):
                self._raw_body = self.original_body.encode()
            elif isinstance(self.original_body, bytes):
                self._raw_body = self.original_body
            else:
                self._raw_body = self.parser.encode(self.original_body)
                if isinstance(self._raw_body, str):
                    self._raw_body = self._raw_body.encode()
        return self._raw_body


Instruction:
Given the following Python 3 function, write the documentation
def send_messages(self, messages):
        msg_count = 0
        for message in messages:  # .message() triggers header validation
            message.message()
            email.outbox.append(message)
            msg_count += 1

        return msg_count

Response: Redirect messages to the dummy outbox


Instruction:
Write a Python 3 function for
generating a square wave of the given frequency amplitude and offset ratio

Response:
def square_wave(params, frequency=400, amplitude=1,
                offset=0, ratio=0.5):
    '''
    Generate a square wave
    :param params: buffer parameters, controls length of signal created
    :param frequency: wave frequency (array or value)
    :param amplitude: wave amplitude (array or value)
    :param offset: offset of wave mean from zero (array or value)
    :param ratio: ratio of high to low time (array or value)
    :return: array of resulting signal
    '''
    frequency = create_buffer(params, frequency)
    amplitude = create_buffer(params, amplitude)
    offset = create_buffer(params, offset)
    ratio = create_buffer(params, ratio)
    phase = np.add.accumulate(frequency / params.sample_rate) % 1
    output = offset + amplitude * np.where(phase < ratio, 1, -1)
    return output


Instruction:
How would you implement a function in Python 3 that
generates a noise signal

Response:
def noise(params, amplitude=1, offset=0):
    '''
    Generate a noise signal
    :param params: buffer parameters, controls length of signal created
    :param amplitude: wave amplitude (array or value)
    :param offset: offset of wave mean from zero (array or value)
    :return: array of resulting signal
    '''
    amplitude = create_buffer(params, amplitude)
    offset = create_buffer(params, offset)
    output = offset + amplitude * (np.random.random(params.length)*2 - 1)
    return output


Instruction:
Explain what the following Python 3 code does
def table_wave(params, frequency=400, amplitude=1,
                offset=0, table=None):
    '''
    Generate a wave from a wavetable
    :param params: buffer parameters, controls length of signal created
    :param frequency: wave frequency (array or value)
    :param amplitude: wave amplitude (array or value)
    :param offset: offset of wave mean from zero (array or value)
    :param table: table of values representing one full cycle of the waveform. Nominally the values
     should be between +/-1 (array). The array can be any size.
    :return: array of resulting signal
    '''
    if not table:
        table = create_sine_table(65536)
    size = table.size
    frequency = create_buffer(params, frequency)
    amplitude = create_buffer(params, amplitude)
    offset = create_buffer(params, offset)
    index = np.floor((np.add.accumulate(frequency / params.sample_rate) % 1) * size).astype(int)
    output = offset + amplitude * table[index]
    return output

Response: Generate a wave from a wavetable.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def sine_wave(params, frequency=400, amplitude=1, offset=0):
    '''
    Generate a sine wave
    Convenience function, table_wave generates a sine wave by default
    :param params: buffer parameters, controls length of signal created
    :param frequency: wave frequency (array or value)
    :param amplitude: wave amplitude (array or value)
    :param offset: offset of wave mean from zero (array or value)
    :return: array of resulting signal
    '''
    return table_wave(params, frequency, amplitude, offset)

Response: Generates a sine wave from a buffer parameters controls length of signal created


Instruction:
Can you write a function in Python 3 where it
converts a midi value to a frequency.

Response:
def midi2f(params, midi=69):
    '''
    Convert a midi value to a frequency.
    Midi value 69 corresponds to A4 (440Hz). Changing the midi value by 1 corresponds to
    one semitone
    :param params: buffer parameters, controls length of signal created
    :param midi: midi value
    :return: array of resulting frequency
    '''
    midi = create_buffer(params, midi)
    output = 2**((midi - 69)/12)*440
    return output


Instruction:
How would you implement a function in Python 3 that
fetches Lookup by name

Response:
def get_lookup(self, lookup_name):
        """Fetch Lookup by name"""
        from protean.core.repository import BaseLookup
        lookup = self._get_lookup(lookup_name)

        # If unable to find Lookup, or if Lookup is the wrong class, raise Error
        if lookup is None or (lookup is not None and not issubclass(lookup, BaseLookup)):
            raise NotImplementedError

        return lookup


Instruction:
Write a Python 3 function for
merging a list of dicts into a single dict.

Response:
def merge_dicts(dicts):
        """
        Merge dicts in reverse to preference the order of the original list. e.g.,
        merge_dicts([a, b]) will preference the keys in 'a' over those in 'b'.
        """
        merged = {}
        for d in reversed(dicts):
            merged.update(d)
        return merged


Instruction:
Implement a function in Python 3 to
register a Lookup to a class

Response:
def register_lookup(cls, lookup, lookup_name=None):
        """Register a Lookup to a class"""
        if lookup_name is None:
            lookup_name = lookup.lookup_name
        if 'class_lookups' not in cls.__dict__:
            cls.class_lookups = {}

        cls.class_lookups[lookup_name] = lookup
        cls._clear_cached_lookups()

        return lookup


Instruction:
Write a Python 3 function for
removing given lookup from cls. class_lookups.

Response:
def _unregister_lookup(cls, lookup, lookup_name=None):
        """
        Remove given lookup from cls lookups. For use in tests only as it's
        not thread-safe.
        """
        if lookup_name is None:
            lookup_name = lookup.lookup_name
        del cls.class_lookups[lookup_name]


Instruction:
Explain what the following Python 3 code does
def deconstruct(self):
        path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
        args, kwargs = (), {}

        if len(self.children) == 1 and not isinstance(self.children[0], Q):
            child = self.children[0]
            kwargs = {child[0]: child[1]}
        else:
            args = tuple(self.children)
            if self.connector != self.default:
                kwargs = {'_connector': self.connector}
        if self.negated:
            kwargs['_negated'] = True
        return path, args, kwargs

Response: Deconstruct a Q Object


Instruction:
Can you generate a brief explanation for the following Python 3 code
def perform_import(val):
    if val is None:
        return None
    elif isinstance(val, str):
        return import_from_string(val)
    elif isinstance(val, (list, tuple)):
        return [import_from_string(item) for item in val]
    return val

Response: Perform a necessary import or imports.


Instruction:
Implement a Python 3 function for
attempting to import a class from a string representation.

Response:
def import_from_string(val):
    """
    Attempt to import a class from a string representation.
    """
    try:
        module_path, class_name = val.rsplit('.', 1)
        module = import_module(module_path)
        return getattr(module, class_name)
    except (ImportError, AttributeError) as e:
        msg = f"Could not import {val}. {e.__class__.__name__}: {e}"
        raise ImportError(msg)


Instruction:
Write a Python 3 function that can
load Context with data

Response:
def set_context(self, data):
        """Load Context with data"""
        for key in data:
            setattr(self.local_context, key, data[key])


Instruction:
Can you write a function in Python 3 where it
resets all associated values and clean up dictionary items

Response:
def _reset_values(self, instance):
        """Reset all associated values and clean up dictionary items"""
        self.value = None
        self.reference.value = None
        instance.__dict__.pop(self.field_name, None)
        instance.__dict__.pop(self.reference.field_name, None)
        self.reference.delete_cached_value(instance)


Instruction:
How would you implement a function in Python 3 that
chooses the Linkage attribute between via and designated id_field of the target class.

Response:
def linked_attribute(self):
        """Choose the Linkage attribute between `via` and designated `id_field` of the target class

        This method is initially called from `__set_name__()` -> `get_attribute_name()`
        at which point, the `to_cls` has not been initialized properly. We simply default
        the linked attribute to 'id' in that case.

        Eventually, when setting value the first time, the `to_cls` entity is initialized
        and the attribute name is reset correctly.
        """
        if isinstance(self.to_cls, str):
            return 'id'
        else:
            return self.via or self.to_cls.meta_.id_field.attribute_name


Instruction:
Write a Python 3 function for
choosing the Linkage attribute between via and own entity s id_field

Response:
def _linked_attribute(self, owner):
        """Choose the Linkage attribute between `via` and own entity's `id_field`

           FIXME Explore converting this method into an attribute, and treating it
           uniformly at `association` level.
        """
        return self.via or (utils.inflection.underscore(owner.__name__) + '_id')


Instruction:
Explain what the following Python 3 code does
def _fetch_objects(self, key, value):
        return self.to_cls.query.filter(**{key: value})

Response: Fetch Multiple linked objects


Instruction:
Write a Python 3 script for
writing a frame and set a waiter for the response ( unless no_wait is set

Response:
async def _write_frame_awaiting_response(self, waiter_id, frame, request,
                                         no_wait, check_open=True, drain=True):
    '''Write a frame and set a waiter for
    the response (unless no_wait is set)'''
    if no_wait:
        await self._write_frame(frame, request, check_open=check_open,
                                     drain=drain)
        return None

    f = self._set_waiter(waiter_id)
    try:
        await self._write_frame(frame, request, check_open=check_open,
                                     drain=drain)
    except Exception:
        self._get_waiter(waiter_id)
        f.cancel()
        raise
    result = await f
    try:
        self._get_waiter(waiter_id)
    except aioamqp.SynchronizationError:
        # no waiter to get
        pass
    return result


Instruction:
How would you explain what the following Python 3 function does
def sequencer(params, source_specs):
    '''
    Add a sequence of sounds to a buffer
    :param params: buffer parameters, controls length of signal created
    :param source_spec: list of tuples containing (source, sample). The source is added into the output buffer
    at the sample position given by the second element in the tuple
    :return:
    '''
    output = np.zeros(params.length, dtype=np.float)
    for source, pos in source_specs:
        if pos >= 0:
            length = min(source.size, params.length - pos)
            if length > 0:
                output[pos:pos+length] += source[:length]
    return output

Response: This function adds a sequence of sounds to a buffer containing the length of the source_specs.


Instruction:
Create a Python 3 function for
loading the fields from the base classes.

Response:
def _load_base_class_fields(new_class, bases, attrs):
        """If this class is subclassing another Entity, add that Entity's
        fields.  Note that we loop over the bases in *reverse*.
        This is necessary in order to maintain the correct order of fields.
        """
        for base in reversed(bases):
            if hasattr(base, 'meta_') and \
                    hasattr(base.meta_, 'declared_fields'):
                base_class_fields = {
                    field_name: field_obj for (field_name, field_obj)
                    in base.meta_.declared_fields.items()
                    if field_name not in attrs and not field_obj.identifier
                }
                new_class._load_fields(base_class_fields)


Instruction:
Given the following Python 3 function, write the documentation
def _load_fields(new_class, attrs):
        for attr_name, attr_obj in attrs.items():
            if isinstance(attr_obj, (Field, Reference)):
                setattr(new_class, attr_name, attr_obj)
                new_class.meta_.declared_fields[attr_name] = attr_obj

Response:
Load field items into Class.
COOKIES This method sets up the primary attribute of an association.
COOKIES


Instruction:
Make a summary of the following Python 3 code
def _set_up_reference_fields(new_class):
        if new_class.meta_.declared_fields:
            for _, field in new_class.meta_.declared_fields.items():
                if isinstance(field, Reference):
                    shadow_field_name, shadow_field = field.get_shadow_field()
                    setattr(new_class, shadow_field_name, shadow_field)
                    shadow_field.__set_name__(new_class, shadow_field_name)

Response: Walk through relation fields and setup shadow attributes


Instruction:
How would you code a function in Python 3 to
create and return a default ID field that is Auto generated

Response:
def _create_id_field(new_class):
        """Create and return a default ID field that is Auto generated"""
        id_field = Auto(identifier=True)

        setattr(new_class, 'id', id_field)
        id_field.__set_name__(new_class, 'id')

        # Ensure ID field is updated properly in Meta attribute
        new_class.meta_.declared_fields['id'] = id_field
        new_class.meta_.id_field = id_field


Instruction:
Can you implement a function in Python 3 that
loads list of attributes from declared fields

Response:
def _load_attributes(new_class):
        """Load list of attributes from declared fields"""
        for field_name, field_obj in new_class.meta_.declared_fields.items():
            new_class.meta_.attributes[field_obj.get_attribute_name()] = field_obj


Instruction:
Make a summary of the following Python 3 code
def unique_fields(self):
        return [(field_name, field_obj)
                for field_name, field_obj in self.declared_fields.items()
                if field_obj.unique]

Response: Return the unique fields for this entity


Instruction:
Write a Python 3 function that can
return entity data as a dictionary

Response:
def to_dict(self):
        """ Return entity data as a dictionary """
        return {field_name: getattr(self, field_name, None)
                for field_name in self.meta_.declared_fields}


Instruction:
Can you tell what is the following Python 3 function doing
def clone(self):
        clone_copy = copy.deepcopy(self)
        clone_copy.state_ = EntityState()

        return clone_copy

Response: Deepclone the entity but reset state


Instruction:
Implement a function in Python 3 to
get a specific Record from the Repository.

Response:
def get(cls, identifier: Any) -> 'Entity':
        """Get a specific Record from the Repository

        :param identifier: id of the record to be fetched from the repository.
        """
        logger.debug(f'Lookup `{cls.__name__}` object with identifier {identifier}')
        # Get the ID field for the entity
        filters = {
            cls.meta_.id_field.field_name: identifier
        }

        # Find this item in the repository or raise Error
        results = cls.query.filter(**filters).limit(1).all()
        if not results:
            raise ObjectNotFoundError(
                f'`{cls.__name__}` object with identifier {identifier} '
                f'does not exist.')

        # Return the first result
        return results.first


Instruction:
Given the following Python 3 function, write the documentation
def reload(self) -> None:
        if not self.state_.is_persisted or self.state_.is_changed:
            raise InvalidStateError(f'`{self.__class__.__name__}` object is in invalid state')

        # Retrieve the entity's ID by the configured Identifier field
        identifier = getattr(self, self.meta_.id_field.field_name)
        logger.debug(f'Lookup `{self.__class__.__name__}` object with '
                     f'identifier {self.meta_.id_field}')

        # Fetch the entity data from db by its identifier
        db_value = self.get(identifier)

        # Update own data from fetched entity data
        # This allows us to ``dog.reload()`` instead of ``dog = dog.reload()``
        self._update_data(db_value.to_dict())

Response: Reloads the entity from the repository


Instruction:
How would you explain what the following Python 3 function does
def find_by(cls, **kwargs) -> 'Entity':
        logger.debug(f'Lookup `{cls.__name__}` object with values '
                     f'{kwargs}')

        # Find this item in the repository or raise Error
        results = cls.query.filter(**kwargs).limit(1).all()

        if not results:
            raise ObjectNotFoundError(
                f'`{cls.__name__}` object with values {[item for item in kwargs.items()]} '
                f'does not exist.')

        # Return the first result
        return results.first

Response: Find a specific entity record that matches one or more criteria.


Instruction:
Write a Python 3 script to
return True if objects matching the provided filters and excludes exist if not return false.

Response:
def exists(cls, excludes_, **filters):
        """ Return `True` if objects matching the provided filters and excludes
        exist if not return false.

        Calls the `filter` method by default, but can be overridden for better and
            quicker implementations that may be supported by a database.

        :param excludes_: entities without this combination of field name and
            values will be returned
        """
        results = cls.query.filter(**filters).exclude(**excludes_)
        return bool(results)


Instruction:
Write a Python 3 script for
creating a new record in the repository.

Response:
def create(cls, *args, **kwargs) -> 'Entity':
        """Create a new record in the repository.

        Also performs unique validations before creating the entity

        :param args: positional arguments for the entity
        :param kwargs: keyword arguments for the entity
        """
        logger.debug(
            f'Creating new `{cls.__name__}` object using data {kwargs}')

        model_cls = repo_factory.get_model(cls)
        repository = repo_factory.get_repository(cls)

        try:
            # Build the entity from the input arguments
            # Raises validation errors, if any, at this point
            entity = cls(*args, **kwargs)

            # Do unique checks, create this object and return it
            entity._validate_unique()

            # Perform Pre-Save Actions
            entity.pre_save()

            # Build the model object and create it
            model_obj = repository.create(model_cls.from_entity(entity))

            # Update the auto fields of the entity
            for field_name, field_obj in entity.meta_.declared_fields.items():
                if isinstance(field_obj, Auto):
                    if isinstance(model_obj, dict):
                        field_val = model_obj[field_name]
                    else:
                        field_val = getattr(model_obj, field_name)
                    setattr(entity, field_name, field_val)

            # Set Entity status to saved
            entity.state_.mark_saved()

            # Perform Post-Save Actions
            entity.post_save()

            return entity
        except ValidationError:
            # FIXME Log Exception
            raise


Instruction:
Write a Python 3 script to
save a new Entity into the repository.

Response:
def save(self):
        """Save a new Entity into repository.

        Performs unique validations before creating the entity.
        """
        logger.debug(
            f'Saving `{self.__class__.__name__}` object')

        # Fetch Model class and connected repository from Repository Factory
        model_cls = repo_factory.get_model(self.__class__)
        repository = repo_factory.get_repository(self.__class__)

        try:
            # Do unique checks, update the record and return the Entity
            self._validate_unique(create=False)

            # Perform Pre-Save Actions
            self.pre_save()

            # Build the model object and create it
            model_obj = repository.create(model_cls.from_entity(self))

            # Update the auto fields of the entity
            for field_name, field_obj in self.meta_.declared_fields.items():
                if isinstance(field_obj, Auto):
                    if isinstance(model_obj, dict):
                        field_val = model_obj[field_name]
                    else:
                        field_val = getattr(model_obj, field_name)
                    setattr(self, field_name, field_val)

            # Set Entity status to saved
            self.state_.mark_saved()

            # Perform Post-Save Actions
            self.post_save()

            return self
        except Exception:
            # FIXME Log Exception
            raise


Instruction:
How would you explain what the following Python 3 function does
def update(self, *data, **kwargs) -> 'Entity':
        logger.debug(f'Updating existing `{self.__class__.__name__}` object with id {self.id}')

        # Fetch Model class and connected repository from Repository Factory
        model_cls = repo_factory.get_model(self.__class__)
        repository = repo_factory.get_repository(self.__class__)

        try:
            # Update entity's data attributes
            self._update_data(*data, **kwargs)

            # Do unique checks, update the record and return the Entity
            self._validate_unique(create=False)

            # Perform Pre-Save Actions
            self.pre_save()

            repository.update(model_cls.from_entity(self))

            # Set Entity status to saved
            self.state_.mark_saved()

            # Perform Post-Save Actions
            self.post_save()

            return self
        except Exception:
            # FIXME Log Exception
            raise

Response: Update an existing entity s data attributes and returns the new entity.


Instruction:
Implement a function in Python 3 to
validate the unique constraints for the entity.

Response:
def _validate_unique(self, create=True):
        """ Validate the unique constraints for the entity """
        # Build the filters from the unique constraints
        filters, excludes = {}, {}

        for field_name, field_obj in self.meta_.unique_fields:
            lookup_value = getattr(self, field_name, None)
            # Ignore empty lookup values
            if lookup_value in Field.empty_values:
                continue
            # Ignore identifiers on updates
            if not create and field_obj.identifier:
                excludes[field_name] = lookup_value
                continue
            filters[field_name] = lookup_value

        # Lookup the objects by the filters and raise error on results
        for filter_key, lookup_value in filters.items():
            if self.exists(excludes, **{filter_key: lookup_value}):
                field_obj = self.meta_.declared_fields[filter_key]
                field_obj.fail('unique',
                               entity_name=self.__class__.__name__,
                               field_name=filter_key)


Instruction:
How would you code a function in Python 3 to
delete a Record from the Repository and return the object.

Response:
def delete(self):
        """Delete a Record from the Repository

        will perform callbacks and run validations before deletion.

        Throws ObjectNotFoundError if the object was not found in the repository.
        """
        # Fetch Model class and connected repository from Repository Factory
        model_cls = repo_factory.get_model(self.__class__)
        repository = repo_factory.get_repository(self.__class__)

        try:
            if not self.state_.is_destroyed:
                # Update entity's data attributes
                repository.delete(model_cls.from_entity(self))

                # Set Entity status to saved
                self.state_.mark_destroyed()

            return self
        except Exception:
            # FIXME Log Exception
            raise


Instruction:
Can you create a Python 3 function that
adds an item to the internal dictionary.

Response:
def add(self, item, count=1):
        '''
        When we receive stream of data, we add them in the chunk
        which has limit on the no. of items that it will store.
        >>> s = StreamCounter(5,5)
        >>> data_stream = ['a','b','c','d']
        >>> for item in data_stream:
        ...     s.add(item)
        >>> s.chunk_size
        5
        >>> s.n_items_seen
        4
        >>> s.n_chunk_items_seen
        4
        >>> s.n_chunks
        0
        >>> from pprint import pprint
        >>> pprint(s.chunked_counts.get(s.n_chunks, {}))
        {'a': 1, 'b': 1, 'c': 1, 'd': 1}
        >>> s.counts_total
        4
        >>> data_stream = ['a','b','c','d','e','f','g','e']
        >>> for item in data_stream:
        ...     s.add(item)
        >>> s.chunk_size
        5
        >>> s.n_items_seen
        12
        >>> s.n_chunk_items_seen
        2
        >>> s.n_chunks
        2
        >>> s.chunked_counts.get(s.n_chunks, {})
        {'g': 1, 'e': 1}
        '''
        self.n_items_seen += count
        self.n_chunk_items_seen += count

        # get current chunk
        chunk_id = self.n_chunks
        chunk = self.chunked_counts.get(chunk_id, {})
        self.chunked_counts[chunk_id] = chunk

        # update count in the current chunk counter dict
        if item in chunk:
            chunk[item] += count
        else:
            self.n_counts += 1
            chunk[item] = count

        # is the current chunk done?
        if self.n_chunk_items_seen >= self.chunk_size:
            self.n_chunks += 1
            self.n_chunk_items_seen = 0

        # In case we reached max capacity in count entries,
        # drop oldest chunks until we come back within limit
        while self.n_counts >= self.max_counts:
            self._drop_oldest_chunk()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _drop_oldest_chunk(self):
        '''
        To handle the case when the items comming in the chunk
        is more than the maximum capacity of the chunk. Our intent
        behind is to remove the oldest chunk. So that the items come
        flowing in.
        >>> s = StreamCounter(5,5)
        >>> data_stream = ['a','b','c','d']
        >>> for item in data_stream:
        ...     s.add(item)
        >>> min(s.chunked_counts.keys())
        0
        >>> s.chunked_counts
        {0: {'a': 1, 'b': 1, 'c': 1, 'd': 1}}
        >>> data_stream = ['a','b','c','d','a','e','f']
        >>> for item in data_stream:
        ...     s.add(item)
        >>> min(s.chunked_counts.keys())
        2
        >>> s.chunked_counts
        {2: {'f': 1}}
        '''
        chunk_id = min(self.chunked_counts.keys())
        chunk = self.chunked_counts.pop(chunk_id)

        self.n_counts -= len(chunk)
        for k, v in list(chunk.items()):
            self.counts[k] -= v
            self.counts_total -= v

Response: Drop the oldest chunk from the internal counts.


Instruction:
How would you explain what the following Python 3 function does
def get(self, item, default=0, normalized=False):
        '''
        When we have the stream of data pushed in the chunk
        we can retrive count of an item using this method.
        >>> stream_counter_obj = StreamCounter(5,5)
        >>> data_stream = ['a','b','c']
        >>> for item in data_stream:
        ...     stream_counter_obj.add(item)
        >>> stream_counter_obj.get('a')
        1
        >>> stream_counter_obj.get('b')
        1
        >>> stream_counter_obj.get('c')
        1
        >>> stream_counter_obj.get('d')
        0
        >>> data_stream.extend(['d','e','f'])
        >>> for item in data_stream:
        ...     stream_counter_obj.add(item)
        >>> stream_counter_obj.get('a')
        0
        >>> stream_counter_obj.get('b')
        0
        >>> stream_counter_obj.get('c')
        1
        >>> stream_counter_obj.get('d')
        1
        >>> stream_counter_obj.get('e')
        1
        >>> stream_counter_obj.get('f')
        1
        '''
        c = self.counts.get(item, default)
        if not normalized:
            return c

        return c / float(self.counts_total)

Response: Get the count of an item from the cache.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def message(self):
        return '\n'.join(
            [self.from_email, str(self.to), self.subject, self.body])

Response: Convert the message to a mime compliant email string


Instruction:
Write a Python 3 script to
return a list of all recipients of the email.

Response:
def recipients(self):
        """
        Return a list of all recipients of the email (includes direct
        addressees as well as Cc and Bcc entries).
        """
        return [email for email in (self.to + self.cc + self.bcc) if email]


Instruction:
Write a Python 3 function that can
retrieve connection to send email

Response:
def get_connection(self, fail_silently=False):
        """Retrieve connection to send email"""
        from protean.services.email import get_connection

        if not self.connection:
            self.connection = get_connection(fail_silently=fail_silently)

        return self.connection


Instruction:
Can you generate the documentation for the following Python 3 function
def send(self, fail_silently=False):
        if not self.recipients():
            # Don't bother creating the network connection if
            # there's nobody to send to.
            return 0
        return self.get_connection(fail_silently).send_messages([self])

Response: Send the email message.


Instruction:
Given the following Python 3 function, write the documentation
def add_static_route(self, method: Union[str, Methods], route: str, handler: Callable,
                         skip_middleware=False):
        """
        Adds a static route. A static route is a special route that
        doesnt follow any of the normal rules, and never has any path
        parameters.
        Ideally, this is used for non-public facing endpoints such as
        "/healthcheck", or "/stats" or something of that nature.

        All static routes SKIP middlewares
        """
        if isinstance(method, str):
            method = Methods(method.upper())
        route = self._prefix + route
        route = route.strip('/')
        if route not in self._static_routes:
            self._static_routes[route] = {}
        self._static_routes[route][method] = handler

Response: Adds a static route to the internal routes dict.


Instruction:
How would you code a function in Python 3 to
add a prefix to routes contained within.

Response:
def prefix(self, prefix):
        """
        Adds a prefix to routes contained within.
        """
        original_prefix = self._prefix
        self._prefix += prefix
        yield self
        self._prefix = original_prefix


Instruction:
Can you write a function in Python 3 where it
returns all the error messages as a dictionary

Response:
def normalized_messages(self, no_field_name='_entity'):
        """Return all the error messages as a dictionary"""
        if isinstance(self.messages, dict):
            return self.messages
        if not self.field_names:
            return {no_field_name: self.messages}

        return dict((name, self.messages) for name in self.field_names)


Instruction:
Can you tell what is the following Python 3 function doing
def generate_random_string(length=6):
    '''
    Returns a random string of a specified length.

    >>> len(generate_random_string(length=25))
    25

    Test randomness. Try N times and observe no duplicaton
    >>> N = 100
    >>> len(set(generate_random_string(10) for i in range(N))) == N
    True
    '''
    n = int(length / 2 + 1)
    x = binascii.hexlify(os.urandom(n))
    s = x[:length]
    return s.decode('utf-8')

Response: Returns a random string of a specified length.


Instruction:
Can you implement a function in Python 3 that
returns current timestamp of the last 1432166400 - > 1432166400 - > 1432166400

Response:
def get_timestamp(dt=None):
    '''
    Return current timestamp if @dt is None
    else return timestamp of @dt.

    >>> t = datetime.datetime(2015, 0o5, 21)
    >>> get_timestamp(t)
    1432166400
    '''

    if dt is None: dt = datetime.datetime.utcnow()
    t = dt.utctimetuple()

    return calendar.timegm(t)


Instruction:
Can you implement a function in Python 3 that
gets datetime from an epoch timestamp

Response:
def get_datetime(epoch):
    '''
    get datetime from an epoch timestamp

    >>> get_datetime(1432188772)
    datetime.datetime(2015, 5, 21, 6, 12, 52)
    '''

    t = time.gmtime(epoch)
    dt = datetime.datetime(*t[:6])

    return dt


Instruction:
Make a summary of the following Python 3 code
def convert_ts(tt):
    '''
    tt: time.struct_time(tm_year=2012, tm_mon=10, tm_mday=23, tm_hour=0,
    tm_min=0, tm_sec=0, tm_wday=1, tm_yday=297, tm_isdst=-1)

    >>> tt = time.strptime("23.10.2012", "%d.%m.%Y")
    >>> convert_ts(tt)
    1350950400

    tt: time.struct_time(tm_year=1513, tm_mon=1, tm_mday=1, tm_hour=0,
    tm_min=0, tm_sec=0, tm_wday=2, tm_yday=1, tm_isdst=0)

    >>> tt = time.strptime("1.1.1513", "%d.%m.%Y")
    >>> convert_ts(tt)
    0
    >>> tt = 12
    >>> convert_ts(tt)
    '''
    try:
        ts = calendar.timegm(tt)

        '''
        As from the github issue https://github.com/prashanthellina/rsslurp/issues/680,
        there are some cases where we might get timestamp in negative values, so consider
        0 if the converted timestamp is negative value.
        '''
        if ts < 0: ts = 0
    except TypeError:
        ts = None
    return ts

Response: Convert a timestamp to a date in the current date format.


Instruction:
Can you tell what is the following Python 3 function doing
def xcode(text, encoding='utf8', mode='ignore'):
    '''
    Converts unicode encoding to str

    >>> xcode(b'hello')
    b'hello'
    >>> xcode('hello')
    b'hello'
    '''
    return text.encode(encoding, mode) if isinstance(text, str) else text

Response: Converts unicode encoding to str


Instruction:
Implement a Python 3 function for
returning all the keys in nested a dictionary.

Response:
def serialize_dict_keys(d, prefix=""):
    """returns all the keys in nested a dictionary.
    >>> sorted(serialize_dict_keys({"a": {"b": {"c": 1, "b": 2} } }))
    ['a', 'a.b', 'a.b.b', 'a.b.c']
    """
    keys = []
    for k, v in d.items():
        fqk = '{}{}'.format(prefix, k)
        keys.append(fqk)
        if isinstance(v, dict):
            keys.extend(serialize_dict_keys(v, prefix="{}.".format(fqk)))

    return keys


Instruction:
Implement a function in Python 3 to
flatten a nested dictionary d into a nested dictionary of items.

Response:
def flatten_dict(d,
                 parent_key='', sep='.',
                 ignore_under_prefixed=True,
                 mark_value=True):
    '''
    Flattens a nested dictionary

    >>> from pprint import pprint
    >>> d = {"a": {"b": {"c": 1, "b": 2, "__d": 'ignore', "_e": "mark"} } }
    >>> fd = flatten_dict(d)
    >>> pprint(fd)
    {'a.b._e': "'mark'", 'a.b.b': 2, 'a.b.c': 1}
    '''
    items = {}
    for k in d:
        if ignore_under_prefixed and k.startswith('__'): continue
        v = d[k]
        if mark_value and k.startswith('_') and not k.startswith('__'):
            v = MarkValue(repr(v))

        new_key = sep.join((parent_key, k)) if parent_key else k
        if isinstance(v, collections.MutableMapping):
            items.update(flatten_dict(v, new_key, sep=sep,
                                        ignore_under_prefixed=True,
                                        mark_value=True)
                            )
        else:
            items[new_key] = v

    return items


Instruction:
Can you generate the documentation for the following Python 3 function
def deepgetattr(obj, attr, default=AttributeError):
    try:
        return reduce(getattr, attr.split('.'), obj)
    except AttributeError:
        if default is not AttributeError:
            return default
        raise

Response: Get the ultimate value of an attribute in an object.


Instruction:
Can you implement a function in Python 3 that
sets the limit on number of file descriptors that this process can open.

Response:
def set_file_limits(n):
    '''
    Set the limit on number of file descriptors
    that this process can open.

    '''

    try:
        resource.setrlimit(resource.RLIMIT_NOFILE, (n, n))
        return True
    except ValueError:
        return False


Instruction:
Explain what the following Python 3 code does
def memoize(f):
    '''
    Caches result of a function
    From: https://goo.gl/aXt4Qy

    >>> import time

    >>> @memoize
    ... def test(msg):
    ...     # Processing for result that takes time
    ...     time.sleep(1)
    ...     return msg
    >>>
    >>> for i in range(5):
    ...     start = time.time()
    ...     test('calling memoized function')
    ...     time_taken = time.time() - start
    ...     # For first time it takes usual time
    ...     if i == 0 and time_taken >= 1: print('ok')
    ...     # Faster from the 2nd time
    ...     elif i != 0 and time_taken <= 1: print('ok')
    ...     else: print('NOT ok!')
    'calling memoized function'
    ok
    'calling memoized function'
    ok
    'calling memoized function'
    ok
    'calling memoized function'
    ok
    'calling memoized function'
    ok
    '''
    class memodict(dict):

        @wraps(f)
        def __getitem__(self, *args):
            return super(memodict, self).__getitem__(*args)

        def __missing__(self, key):
            self[key] = ret = f(key)
            return ret
    return memodict().__getitem__

Response: Memoizes the result of a function f.


Instruction:
Make a summary of the following Python 3 code
def load_object(imp_path):
    '''
    Given a python import path, load the object
    For dynamic imports in a program

    >>> isdir = load_object('os.path.isdir')
    >>> isdir('/tmp')
    True

    >>> num = load_object('numbers.Number')
    >>> isinstance('x', num)
    False
    >>> isinstance(777, num)
    True
    '''
    module_name, obj_name = imp_path.split('.', 1)
    module = __import__(module_name)
    obj = attrgetter(obj_name)(module)

    return obj

Response: Given a python import path load the object


Instruction:
Write a Python 3 script for
performing validation on value. Raise a : exc : ValidationException if validation does not succeed.

Response:
def _run_validators(self, value):
        """Perform validation on ``value``. Raise a :exc:`ValidationError` if
        validation does not succeed.
        """
        if value in self.empty_values:
            return

        errors = []
        for validator in self.validators:
            try:
                validator(value)
            except exceptions.ValidationError as err:
                if isinstance(err.messages, dict):
                    errors.append(err.messages)
                else:
                    errors.extend(err.messages)

        if errors:
            raise exceptions.ValidationError(errors)


Instruction:
Can you generate the documentation for the following Python 3 function
def _load(self, value: Any):

        if value in self.empty_values:
            # If a default has been set for the field return it
            if self.default is not None:
                default = self.default
                value = default() if callable(default) else default
                return value

            # If no default is set and this field is required
            elif self.required:
                self.fail('required')

            # In all other cases just return `None` as we do not want to
            # run validations against an empty value
            else:
                return None

        # If choices exist then validate that value is be one of the choices
        if self.choices:
            value_list = value
            if not isinstance(value, (list, tuple)):
                value_list = [value]
            for v in value_list:
                if v not in self.choice_dict:
                    self.fail(
                        'invalid_choice', value=v,
                        choices=list(self.choice_dict))

        # Cast and Validate the value for this Field
        value = self._cast_to_type(value)

        # Call the rest of the validators defined for this Field
        self._run_validators(value)

        return value

Response: Load the value for the field and run validators and return the value.


Instruction:
How would you explain what the following Python 3 function does
def _extract_lookup(self, key):
        parts = key.split('__')
        # 'exact' is the default lookup if there was no explicit comparison op in `key`
        #   Assume there is only one `__` in the key.
        #   FIXME Change for child attribute query support
        op = 'exact' if len(parts) == 1 else parts[1]

        # Construct and assign the lookup class as a filter criteria
        return parts[0], self.get_lookup(op)

Response: Extract lookup method based on key name format


Instruction:
Implement a Python 3 function for
transforming from json to Request

Response:
def exec(self, payload: Log2ReqsAddOnPayload) -> TList[Request]:
        """Transform from json to Request

        Exception:
            ValueError: If path does not exist.
        """
        try:
            return Request.from_jsonf_to_list(payload.file, encoding=self.config.encoding)
        except TypeError as e:
            raise ValueError(e)


Instruction:
Create a Python 3 function to
return the expiry value usable by this backend based upon the provided timeout.

Response:
def get_backend_expiry(self, expiry=DEFAULT_EXPIRY):
        """
        Return the expiry value usable by this backend based upon the provided
        timeout.
        """
        if expiry == DEFAULT_EXPIRY:
            expiry = self.default_expiry
        elif expiry == 0:
            # avoid time.time() related precision issues
            expiry = -1
        return None if expiry is None else time.time() + expiry


Instruction:
Write a Python 3 function that can
fetch a bunch of keys from the cache.

Response:
def get_many(self, keys):
        """
        Fetch a bunch of keys from the cache. For certain backends (memcached,
        pgsql) this can be *much* faster when fetching multiple values.
        Return a dict mapping each key in keys to its value. If the given
        key is missing, it will be missing from the response dict.
        """
        d = {}
        for k in keys:
            val = self.get(k)
            if val is not None:
                d[k] = val

        return d


Instruction:
Can you implement a function in Python 3 that
increments the value of a key in the cache.

Response:
def incr(self, key, delta=1):
        """
        Add delta to value in the cache. If the key does not exist, raise a
        ValueError exception.
        """
        value = self.get(key)
        if value is None:
            raise ValueError("Key '%s' not found" % key)
        new_value = value + delta
        self.set(key, new_value)
        return new_value


Instruction:
Make a summary of the following Python 3 code
def set_many(self, data, expiry=DEFAULT_EXPIRY):
        for key, value in data.items():
            self.set(key, value, expiry=expiry)
        return []

Response: Set a bunch of values in the cache at once from a dict of key - value pairs.


Instruction:
Given the following Python 3 function, write the documentation
def init_logger(v_num: int):
    logging.addLevelName(LogLevel.INFO_LV1.value, 'INFO_LV1')  # type: ignore # Prevent for enum problem
    logging.addLevelName(LogLevel.INFO_LV2.value, 'INFO_LV2')  # type: ignore # Prevent for enum problem
    logging.addLevelName(LogLevel.INFO_LV3.value, 'INFO_LV3')  # type: ignore # Prevent for enum problem

    logging.config.dictConfig(create_logger_config({  # type: ignore # Prevent for enum problem
        0: LogLevel.INFO_LV1,
        1: LogLevel.INFO_LV2,
        2: LogLevel.INFO_LV3,
        3: LogLevel.DEBUG,
    }[v_num]))

Response: Call when initialize Jumeaux!!


Instruction:
How would you implement a function in Python 3 that
reads config file and initialize providers

Response:
def _initialize_providers(self):
        """Read config file and initialize providers"""
        configured_providers = active_config.DATABASES
        provider_objects = {}

        if not isinstance(configured_providers, dict) or configured_providers == {}:
            raise ConfigurationError(
                "'DATABASES' config must be a dict and at least one "
                "provider must be defined")

        if 'default' not in configured_providers:
            raise ConfigurationError(
                "You must define a 'default' provider")

        for provider_name, conn_info in configured_providers.items():
            provider_full_path = conn_info['PROVIDER']
            provider_module, provider_class = provider_full_path.rsplit('.', maxsplit=1)

            provider_cls = getattr(importlib.import_module(provider_module), provider_class)
            provider_objects[provider_name] = provider_cls(conn_info)

        return provider_objects


Instruction:
Write a Python 3 function for
fetching a specific provider with the specified name in Configuration file

Response:
def get_provider(self, provider_name='default'):
        """Fetch provider with the name specified in Configuration file"""
        try:
            if self._providers is None:
                self._providers = self._initialize_providers()
            return self._providers[provider_name]
        except KeyError:
            raise AssertionError(f'No Provider registered with name {provider_name}')


Instruction:
Make a summary of the following Python 3 code
def get_connection(self, provider_name='default'):
        try:
            return self._providers[provider_name].get_connection()
        except KeyError:
            raise AssertionError(f'No Provider registered with name {provider_name}')

Response: Fetch connection from Provider


Instruction:
Create a Python 3 function to
update the default settings for an extension from an object

Response:
def update_defaults(self, ext_config):
        """ Update the default settings for an extension from an object"""
        for setting in dir(ext_config):
            if setting.isupper() and not hasattr(self, setting):
                setattr(self, setting, getattr(ext_config, setting))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def keeprunning(wait_secs=0, exit_on_success=False,
                on_success=None, on_error=None, on_done=None):
    '''
    Example 1: dosomething needs to run until completion condition
    without needing to have a loop in its code. Also, when error
    happens, we should NOT terminate execution

    >>> from deeputil import AttrDict
    >>> @keeprunning(wait_secs=1)
    ... def dosomething(state):
    ...     state.i += 1
    ...     print (state)
    ...     if state.i % 2 == 0:
    ...         print("Error happened")
    ...         1 / 0 # create an error condition
    ...     if state.i >= 7:
    ...         print ("Done")
    ...         raise keeprunning.terminate
    ...

    >>> state = AttrDict(i=0)
    >>> dosomething(state)
    AttrDict({'i': 1})
    AttrDict({'i': 2})
    Error happened
    AttrDict({'i': 3})
    AttrDict({'i': 4})
    Error happened
    AttrDict({'i': 5})
    AttrDict({'i': 6})
    Error happened
    AttrDict({'i': 7})
    Done

    Example 2: In case you want to log exceptions while
    dosomething keeps running, or perform any other action
    when an exceptions arise

    >>> def some_error(__exc__):
    ...     print (__exc__)
    ...
    >>> @keeprunning(on_error=some_error)
    ... def dosomething(state):
    ...     state.i += 1
    ...     print (state)
    ...     if state.i % 2 == 0:
    ...         print("Error happened")
    ...         1 / 0 # create an error condition
    ...     if state.i >= 7:
    ...         print ("Done")
    ...         raise keeprunning.terminate
    ...

    >>> state = AttrDict(i=0)
    >>> dosomething(state)
    AttrDict({'i': 1})
    AttrDict({'i': 2})
    Error happened
    division by zero
    AttrDict({'i': 3})
    AttrDict({'i': 4})
    Error happened
    division by zero
    AttrDict({'i': 5})
    AttrDict({'i': 6})
    Error happened
    division by zero
    AttrDict({'i': 7})
    Done

    Example 3: Full set of arguments that can be passed in @keeprunning()
    with class implementations

    >>> # Class that has some class variables
    ... class Demo(object):
    ...     SUCCESS_MSG = 'Yay!!'
    ...     DONE_MSG = 'STOPPED AT NOTHING!'
    ...     ERROR_MSG = 'Error'
    ...
    ...     # Functions to be called by @keeprunning
    ...     def success(self):
    ...         print((self.SUCCESS_MSG))
    ...
    ...     def failure(self, __exc__):
    ...         print((self.ERROR_MSG, __exc__))
    ...
    ...     def task_done(self):
    ...         print((self.DONE_MSG))
    ...
    ...     #Actual use of keeprunning with all arguments passed
    ...     @keeprunning(wait_secs=1, exit_on_success=False,
    ...             on_success=success, on_error=failure, on_done=task_done)
    ...     def dosomething(self, state):
    ...         state.i += 1
    ...         print (state)
    ...         if state.i % 2 == 0:
    ...             print("Error happened")
    ...             # create an error condition
    ...             1 / 0
    ...         if state.i >= 7:
    ...             print ("Done")
    ...             raise keeprunning.terminate
    ...

    >>> demo = Demo()
    >>> state = AttrDict(i=0)
    >>> demo.dosomething(state)
    AttrDict({'i': 1})
    Yay!!
    AttrDict({'i': 2})
    Error happened
    ('Error', ZeroDivisionError('division by zero'))
    AttrDict({'i': 3})
    Yay!!
    AttrDict({'i': 4})
    Error happened
    ('Error', ZeroDivisionError('division by zero'))
    AttrDict({'i': 5})
    Yay!!
    AttrDict({'i': 6})
    Error happened
    ('Error', ZeroDivisionError('division by zero'))
    AttrDict({'i': 7})
    Done
    STOPPED AT NOTHING!
    '''
    def decfn(fn):

        def _call_callback(cb, fargs):
            if not cb: return
            # get the getargspec fn in inspect module (python 2/3 support)
            G = getattr(inspect, 'getfullargspec', getattr(inspect, 'getargspec'))
            cb_args = G(cb).args
            cb_args = dict([(a, fargs.get(a, None)) for a in cb_args])
            cb(**cb_args)

        def _fn(*args, **kwargs):
            fargs = inspect.getcallargs(fn, *args, **kwargs)
            fargs.update(dict(__fn__=fn, __exc__=None))

            while 1:
                try:
                    fn(*args, **kwargs)
                    if exit_on_success: break
                except (SystemExit, KeyboardInterrupt):
                    raise
                except KeepRunningTerminate:
                    break
                except Exception as exc:
                    fargs.update(dict(__exc__=exc))
                    _call_callback(on_error, fargs)
                    fargs.update(dict(__exc__=None))
                    if wait_secs: time.sleep(wait_secs)
                    continue

                _call_callback(on_success, fargs)

            _call_callback(on_done, fargs)

        return _fn

    return decfn

Response: This function is a generator function that returns a sequence of nodes that are not yet in the tree.


Instruction:
Can you write a function in Python 3 where it
registers the given entity with the factory.

Response:
def register(self, entity_cls, provider_name=None):
        """ Register the given model with the factory
        :param entity_cls: Entity class to be registered
        :param provider: Optional provider to associate with Entity class
        """
        self._validate_entity_cls(entity_cls)

        # Register the entity if not registered already
        entity_name = fully_qualified_name(entity_cls)
        provider_name = provider_name or entity_cls.meta_.provider or 'default'

        try:
            entity = self._get_entity_by_class(entity_cls)

            if entity:
                # This probably is an accidental re-registration of the entity
                #   and we should warn the user of a possible repository confusion
                raise ConfigurationError(
                    f'Entity {entity_name} has already been registered')
        except AssertionError:
            # Entity has not been registered yet. Let's go ahead and add it to the registry.
            entity_record = RepositoryFactory.EntityRecord(
                name=entity_cls.__name__,
                qualname=entity_name,
                entity_cls=entity_cls,
                provider_name=provider_name,
                model_cls=None
            )
            self._registry[entity_name] = entity_record
            logger.debug(
                f'Registered entity {entity_name} with provider {provider_name}')


Instruction:
Create a Python 3 function for
fetching by Entity Name in values

Response:
def _find_entity_in_records_by_class_name(self, entity_name):
        """Fetch by Entity Name in values"""
        records = {
            key: value for (key, value)
            in self._registry.items()
            if value.name == entity_name
        }
        # If more than one record was found, we are dealing with the case of
        #   an Entity name present in multiple places (packages or plugins). Throw an error
        #   and ask for a fully qualified Entity name to be specified
        if len(records) > 1:
            raise ConfigurationError(
                f'Entity with name {entity_name} has been registered twice. '
                f'Please use fully qualified Entity name to specify the exact Entity.')
        elif len(records) == 1:
            return next(iter(records.values()))
        else:
            raise AssertionError(f'No Entity registered with name {entity_name}')


Instruction:
Here you have a function in Python 3, explain what it does
def _get_entity_by_class(self, entity_cls):
        entity_qualname = fully_qualified_name(entity_cls)
        if entity_qualname in self._registry:
            return self._registry[entity_qualname]
        else:
            return self._find_entity_in_records_by_class_name(entity_cls.__name__)

Response: Fetch Entity record with Entity class details


Instruction:
Can you write a function in Python 3 where it
fetches an Entity record with an Entity name

Response:
def _get_entity_by_name(self, entity_name):
        """Fetch Entity record with an Entity name"""
        if entity_name in self._registry:
            return self._registry[entity_name]
        else:
            return self._find_entity_in_records_by_class_name(entity_name)


Instruction:
How would you explain what the following Python 3 function does
def _validate_entity_cls(self, entity_cls):
        # Import here to avoid cyclic dependency
        from protean.core.entity import Entity

        if not issubclass(entity_cls, Entity):
            raise AssertionError(
                f'Entity {entity_cls.__name__} must be subclass of `Entity`')

        if entity_cls.meta_.abstract is True:
            raise NotSupportedError(
                f'{entity_cls.__name__} class has been marked abstract'
                f' and cannot be instantiated')

Response: Validate that the given Entity class is a valid class.


Instruction:
How would you explain what the following Python 3 function does
def get_model(self, entity_cls):
        entity_record = self._get_entity_by_class(entity_cls)

        model_cls = None
        if entity_record.model_cls:
            model_cls = entity_record.model_cls
        else:
            # We should ask the Provider to give a fully baked model the first time
            #   that has been initialized properly for this entity
            provider = self.get_provider(entity_record.provider_name)
            baked_model_cls = provider.get_model(entity_record.entity_cls)

            # Record for future reference
            new_entity_record = entity_record._replace(model_cls=baked_model_cls)
            self._registry[entity_record.qualname] = new_entity_record

            model_cls = baked_model_cls

        return model_cls

Response: Retrieve Model class connected to Entity


Instruction:
Explain what the following Python 3 code does
def get_repository(self, entity_cls):
        entity_record = self._get_entity_by_class(entity_cls)
        provider = self.get_provider(entity_record.provider_name)

        return provider.get_repository(entity_record.entity_cls)

Response: Retrieve a Repository for the Model with a live connection


Instruction:
Explain what the following Python 3 code does
async def set_heater_values(heater_data, heater):
    heater.current_temp = heater_data.get('currentTemp')
    heater.device_status = heater_data.get('deviceStatus')
    heater.available = heater.device_status == 0
    heater.name = heater_data.get('deviceName')
    heater.fan_status = heater_data.get('fanStatus')
    heater.is_holiday = heater_data.get('isHoliday')

    # Room assigned devices don't report canChangeTemp
    # in selectDevice response.
    if heater.room is None:
        heater.can_change_temp = heater_data.get('canChangeTemp')

    # Independent devices report their target temperature via
    # holidayTemp value. But isHoliday is still set to 0.
    # Room assigned devices may have set "Control Device individually"
    # which effectively set their isHoliday value to 1.
    # In this mode they behave similar to independent devices
    # reporting their target temperature also via holidayTemp.
    if heater.independent_device or heater.is_holiday == 1:
        heater.set_temp = heater_data.get('holidayTemp')
    elif heater.room is not None:
        if heater.room.current_mode == 1:
            heater.set_temp = heater.room.comfort_temp
        elif heater.room.current_mode == 2:
            heater.set_temp = heater.room.sleep_temp
        elif heater.room.current_mode == 3:
            heater.set_temp = heater.room.away_temp
    heater.power_status = heater_data.get('powerStatus')
    heater.tibber_control = heater_data.get('tibberControl')
    heater.open_window = heater_data.get('open_window',
                                         heater_data.get('open')
                                         )
    heater.is_heating = heater_data.get('heatStatus',
                                        heater_data.get('heaterFlag')
                                        )
    try:
        heater.sub_domain = int(float(heater_data.get('subDomain',
                                                      heater_data.get('subDomainId',
                                                                      heater.sub_domain)
                                                      )))
    except ValueError:
        pass

Response: Set heater values from heater data.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def sync_connect(self):
        loop = asyncio.get_event_loop()
        task = loop.create_task(self.connect())
        loop.run_until_complete(task)

Response: Close the Mill connection.


Instruction:
How would you code a function in Python 3 to
close the Mill connection.

Response:
def sync_close_connection(self):
        """Close the Mill connection."""
        loop = asyncio.get_event_loop()
        task = loop.create_task(self.close_connection())
        loop.run_until_complete(task)


Instruction:
Make a summary of the following Python 3 code
async def request(self, command, payload, retry=3):
        # pylint: disable=too-many-return-statements

        if self._token is None:
            _LOGGER.error("No token")
            return None

        _LOGGER.debug(command, payload)

        nonce = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(16))
        url = API_ENDPOINT_2 + command
        timestamp = int(time.time())
        signature = hashlib.sha1(str(REQUEST_TIMEOUT
                                     + str(timestamp)
                                     + nonce
                                     + self._token).encode("utf-8")).hexdigest()

        headers = {
            "Content-Type": "application/x-zc-object",
            "Connection": "Keep-Alive",
            "X-Zc-Major-Domain": "seanywell",
            "X-Zc-Msg-Name": "millService",
            "X-Zc-Sub-Domain": "milltype",
            "X-Zc-Seq-Id": "1",
            "X-Zc-Version": "1",
            "X-Zc-Timestamp": str(timestamp),
            "X-Zc-Timeout": REQUEST_TIMEOUT,
            "X-Zc-Nonce": nonce,
            "X-Zc-User-Id": str(self._user_id),
            "X-Zc-User-Signature": signature,
            "X-Zc-Content-Length": str(len(payload)),
        }
        try:
            with async_timeout.timeout(self._timeout):
                resp = await self.websession.post(url,
                                                  data=json.dumps(payload),
                                                  headers=headers)
        except asyncio.TimeoutError:
            if retry < 1:
                _LOGGER.error("Timed out sending command to Mill: %s", command)
                return None
            return await self.request(command, payload, retry - 1)
        except aiohttp.ClientError:
            _LOGGER.error("Error sending command to Mill: %s", command, exc_info=True)
            return None

        result = await resp.text()

        _LOGGER.debug(result)

        if not result or result == '{"errorCode":0}':
            return None

        if 'access token expire' in result or 'invalid signature' in result:
            if retry < 1:
                return None
            if not await self.connect():
                return None
            return await self.request(command, payload, retry - 1)

        if '"error":"device offline"' in result:
            if retry < 1:
                _LOGGER.error("Failed to send request, %s", result)
                return None
            _LOGGER.debug("Failed to send request, %s. Retrying...", result)
            await asyncio.sleep(3)
            return await self.request(command, payload, retry - 1)

        if 'errorCode' in result:
            _LOGGER.error("Failed to send request, %s", result)
            return None
        data = json.loads(result)
        return data

Response: Send a command to Mill.


Instruction:
Here you have a function in Python 3, explain what it does
def sync_request(self, command, payload, retry=2):
        loop = asyncio.get_event_loop()
        task = loop.create_task(self.request(command, payload, retry))
        return loop.run_until_complete(task)

Response: Send a request to the server and return the response.


Instruction:
Write a Python 3 script for
requesting data for all rooms and heaters.

Response:
async def update_rooms(self):
        """Request data."""
        homes = await self.get_home_list()
        for home in homes:
            payload = {"homeId": home.get("homeId"), "timeZoneNum": "+01:00"}
            data = await self.request("selectRoombyHome", payload)
            rooms = data.get('roomInfo', [])
            for _room in rooms:
                _id = _room.get('roomId')
                room = self.rooms.get(_id, Room())
                room.room_id = _id
                room.comfort_temp = _room.get("comfortTemp")
                room.away_temp = _room.get("awayTemp")
                room.sleep_temp = _room.get("sleepTemp")
                room.name = _room.get("roomName")
                room.current_mode = _room.get("currentMode")
                room.heat_status = _room.get("heatStatus")
                room.home_name = data.get("homeName")
                room.avg_temp = _room.get("avgTemp")

                self.rooms[_id] = room
                payload = {"roomId": _room.get("roomId"), "timeZoneNum": "+01:00"}
                room_device = await self.request("selectDevicebyRoom", payload)

                if room_device is None:
                    continue
                heater_info = room_device.get('deviceInfo', [])
                for _heater in heater_info:
                    _id = _heater.get('deviceId')
                    heater = self.heaters.get(_id, Heater())
                    heater.device_id = _id
                    heater.independent_device = False
                    heater.can_change_temp = _heater.get('canChangeTemp')
                    heater.name = _heater.get('deviceName')
                    heater.room = room
                    self.heaters[_id] = heater


Instruction:
Write a Python 3 function that can
request data from the server.

Response:
def sync_update_rooms(self):
        """Request data."""
        loop = asyncio.get_event_loop()
        task = loop.create_task(self.update_rooms())
        return loop.run_until_complete(task)


Instruction:
Given the following Python 3 function, write the documentation
async def set_room_temperatures_by_name(self, room_name, sleep_temp=None,
                                            comfort_temp=None, away_temp=None):
        """Set room temps by name."""
        if sleep_temp is None and comfort_temp is None and away_temp is None:
            return
        for room_id, _room in self.rooms.items():
            if _room.name == room_name:
                await self.set_room_temperatures(room_id, sleep_temp,
                                                 comfort_temp, away_temp)
                return
        _LOGGER.error("Could not find a room with name %s", room_name)

Response: Set room temps by name.


Instruction:
Can you create a Python 3 function that
updates the list of available HEALPix entries.

Response:
def sync_update_heaters(self):
        """Request data."""
        loop = asyncio.get_event_loop()
        task = loop.create_task(self.update_heaters())
        loop.run_until_complete(task)


Instruction:
How would you code a function in Python 3 to
throttle update the list of available HEALPix entries.

Response:
async def throttle_update_heaters(self):
        """Throttle update device."""
        if (self._throttle_time is not None
                and dt.datetime.now() - self._throttle_time < MIN_TIME_BETWEEN_UPDATES):
            return
        self._throttle_time = dt.datetime.now()
        await self.update_heaters()


Instruction:
Write a Python 3 script to
throttle update all devices and rooms.

Response:
async def throttle_update_all_heaters(self):
        """Throttle update all devices and rooms."""
        if (self._throttle_all_time is not None
                and dt.datetime.now() - self._throttle_all_time
                < MIN_TIME_BETWEEN_UPDATES):
            return
        self._throttle_all_time = dt.datetime.now()
        await self.find_all_heaters()


Instruction:
Implement a Python 3 function for
transforming csv as below.

Response:
def exec(self, payload: Log2ReqsAddOnPayload) -> TList[Request]:
        """Transform csv as below.
            "title1","/path1","a=1&b=2","header1=1&header2=2"
            "title2","/path2","c=1"
            "title3","/path3",,"header1=1&header2=2"
            "title4","/path4"

        Exception:
            ValueError: If fomat is invalid.
        """
        outputs = []

        with open(payload.file, encoding=self.config.encoding) as f:
            rs = csv.DictReader(f, ('name', 'path', 'qs', 'headers'), restval={}, dialect=self.config.dialect)
            for r in rs:
                if len(r) > 4:
                    raise ValueError
                r['qs'] = urlparser.parse_qs(r['qs'], keep_blank_values=self.config.keep_blank)

                # XXX: This is bad implementation but looks simple...
                r['headers'] = urlparser.parse_qs(r['headers'], keep_blank_values=self.config.keep_blank)
                for k, v in r['headers'].items():
                    r['headers'][k] = v[0]

                outputs.append(r)

        return Request.from_dicts(outputs)


Instruction:
Write a Python 3 function for
echoing a single nucite object.

Response:
def echo(params, source, delay, strength):
    '''
    Create an echo
    :param params:
    :param source:
    :param delay:
    :param strength:
    :return:
    '''
    source = create_buffer(params, source)
    delay = create_buffer(params, delay)
    strength = create_buffer(params, strength)
    output = source[:]
    for i in range(params.length):
        d = int(i - delay[i])
        if 0 <= d < params.length:
            output[i] += source[d]*strength[i]
    return output


Instruction:
Write a Python 3 function that can
return a copy of the current QuerySet.

Response:
def _clone(self):
        """
        Return a copy of the current QuerySet.
        """
        clone = self.__class__(self._entity_cls, criteria=self._criteria,
                               offset=self._offset, limit=self._limit,
                               order_by=self._order_by)
        return clone


Instruction:
Here you have a function in Python 3, explain what it does
def _add_q(self, q_object):
        self._criteria = self._criteria._combine(q_object, q_object.connector)

Response: Add a Q - object to the current filter.


Instruction:
Can you create a Python 3 function that
limits number of records

Response:
def limit(self, limit):
        """Limit number of records"""
        clone = self._clone()

        if isinstance(limit, int):
            clone._limit = limit

        return clone


Instruction:
Write a Python 3 script for
fetching results after offset value

Response:
def offset(self, offset):
        """Fetch results after `offset` value"""
        clone = self._clone()

        if isinstance(offset, int):
            clone._offset = offset

        return clone