Instruction:
Can you generate a brief explanation for the following Python 3 code
def _url(self, url=None, parameters=None):

        uri = url or self._settings["url"]
        if url and self._settings["base_url"]:
            uri = "%s/%s" % (self._settings["base_url"], url)
        uri += ".json"
        if parameters:
            uri += "?%s" % urllib.urlencode(parameters)
        return uri

Response: Build the destination URL.


Instruction:
Can you implement a function in Python 3 that
tells if this message is a text message.

Response:
def is_text(self):
        """ Tells if this message is a text message.

        Returns:
            bool. Success
        """
        return self.type in [
            self._TYPE_PASTE,
            self._TYPE_TEXT,
            self._TYPE_TWEET
        ]


Instruction:
Make a summary of the following Python 3 code
def get_rooms(self, sort=True):
        rooms = self._connection.get("rooms")
        if sort:
            rooms.sort(key=operator.itemgetter("name"))
        return rooms

Response: Get the rooms list.


Instruction:
Write a Python 3 function that can
get a room by name.

Response:
def get_room_by_name(self, name):
        """ Get a room by name.

        Returns:
            :class:`Room`. Room

        Raises:
            RoomNotFoundException
        """
        rooms = self.get_rooms()
        for room in rooms or []:
            if room["name"] == name:
                return self.get_room(room["id"])
        raise RoomNotFoundException("Room %s not found" % name)


Instruction:
Given the following Python 3 function, write the documentation
def get_room(self, id):
        if id not in self._rooms:
            self._rooms[id] = Room(self, id)
        return self._rooms[id]

Response:
Get room.

        Returns:
            :class:`Room`. Room


Instruction:
Create a Python 3 function to
get user. Returns: :class:`User`. User

Response:
def get_user(self, id = None):
        """ Get user.

        Returns:
            :class:`User`. User
        """
        if not id:
            id = self._user.id

        if id not in self._users:
            self._users[id] = self._user if id == self._user.id else User(self, id)

        return self._users[id]


Instruction:
Write a Python 3 function for
searching transcripts. Args: terms (str): Terms for search Returns: array. Messages

Response:
def search(self, terms):
        """ Search transcripts.

        Args:
            terms (str): Terms for search

        Returns:
            array. Messages
        """
        messages = self._connection.get("search/%s" % urllib.quote_plus(terms), key="messages")
        if messages:
            messages = [Message(self, message) for message in messages]
        return messages


Instruction:
Write a Python 3 script to
dump a cookie into a simple cookie.

Response:
def cookie_dump(key, value='', max_age=None, expires=None, path='/',
                domain=None, secure=False, httponly=False):
    """
    :rtype: ``Cookie.SimpleCookie``
    """
    cookie = SimpleCookie()
    cookie[key] = value
    for attr in ('max_age', 'expires', 'path', 'domain',
                 'secure', 'httponly'):
        attr_key = attr.replace('_', '-')
        attr_value = locals()[attr]
        if attr_value:
            cookie[key][attr_key] = attr_value
    return cookie


Instruction:
Make a summary of the following Python 3 code
def response_status_string(code):
    mean = HTTP_STATUS_CODES.get(code, 'unknown').upper()
    return '{code} {mean}'.format(code=code, mean=mean)

Response: Return a string representation of the status code.


Instruction:
Given the following Python 3 function, write the documentation
def cookies(self):
        http_cookie = self.environ.get('HTTP_COOKIE', '')
        _cookies = {
            k: v.value
            for (k, v) in SimpleCookie(http_cookie).items()
        }
        return _cookies

Response:
Request cookies

        :rtype: dict


Instruction:
How would you implement a function in Python 3 that
attaches an observer function to the current stream.

Response:
def attach(self, observer):
        """ Attach an observer.

        Args:
            observer (func): A function to be called when new messages arrive

        Returns:
            :class:`Stream`. Current instance to allow chaining
        """
        if not observer in self._observers:
            self._observers.append(observer)
        return self


Instruction:
Can you generate a brief explanation for the following Python 3 code
def incoming(self, messages):
        if self._observers:
            campfire = self._room.get_campfire()
            for message in messages:
                for observer in self._observers:
                    observer(Message(campfire, message))

Response: Called when incoming messages arrive.


Instruction:
Write a Python 3 script to
call by the thread, it runs the process. NEVER call this method directly. Instead call start() to start the thread. To stop, call stop(), and then join()

Response:
def run(self):
        """ Called by the thread, it runs the process.

        NEVER call this method directly. Instead call start() to start the thread.

        To stop, call stop(), and then join()
        """

        if self._live:
            self._use_process = True

        self._abort = False
        campfire = self._room.get_campfire()

        if self._live:
            process = LiveStreamProcess(campfire.get_connection().get_settings(), self._room.id)
        else:
            process = StreamProcess(campfire.get_connection().get_settings(), self._room.id, pause=self._pause)

        if not self._use_process:
            process.set_callback(self.incoming)

        if self._use_process:
            queue = Queue()
            process.set_queue(queue)
            process.start()
            if not process.is_alive():
                return

        self._streaming = True

        while not self._abort:
            if self._use_process:
                if not process.is_alive():
                    self._abort = True
                    break

                try:
                    incoming = queue.get_nowait()
                    if isinstance(incoming, list):
                        self.incoming(incoming)
                    elif isinstance(incoming, Exception):
                        self._abort = True
                        if self._error_callback:
                            self._error_callback(incoming, self._room)

                except Empty:
                    time.sleep(self._pause)
                    pass
            else:
                process.fetch()
                time.sleep(self._pause)

        self._streaming = False
        if self._use_process and self._abort and not process.is_alive() and self._error_callback:
            self._error_callback(Exception("Streaming process was killed"), self._room)

        if self._use_process:
            queue.close()
            if process.is_alive():
                process.stop()
                process.terminate()
            process.join()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def run(self):
        if not self._queue:
            raise Exception("No queue available to send messages")

        while True:
            self.fetch()
            time.sleep(self._pause)

Response:
Called by the process, it runs it.

        NEVER call this method directly. Instead call start() to start the separate process.
        If you don't want to use a second process, then call fetch() directly on this istance.

        To stop, call terminate()


Instruction:
Can you generate the documentation for the following Python 3 function
def received(self, messages):
        if messages:
            if self._queue:
                self._queue.put_nowait(messages)

            if self._callback:
                self._callback(messages)

Response: Called when new messages arrive.


Instruction:
Write a Python 3 script to
call by the process, it runs it. NEVER call this method directly. Instead call start() to start the separate process. If you don't want to use a second process, then call fetch() directly on this istance. To stop, call terminate()

Response:
def run(self):
        """ Called by the process, it runs it.

        NEVER call this method directly. Instead call start() to start the separate process.
        If you don't want to use a second process, then call fetch() directly on this istance.

        To stop, call terminate()
        """
        if not self._queue:
            raise Exception("No queue available to send messages")

        factory = LiveStreamFactory(self)
        self._reactor.connectSSL("streaming.campfirenow.com", 443, factory, ssl.ClientContextFactory())
        self._reactor.run()


Instruction:
Can you implement a function in Python 3 that
calls when a connection is made

Response:
def connectionMade(self):
        """ Called when a connection is made, and used to send out headers """

        headers = [
            "GET %s HTTP/1.1" % ("/room/%s/live.json" % self.factory.get_stream().get_room_id())
        ]

        connection_headers = self.factory.get_stream().get_connection().get_headers()
        for header in connection_headers:
            headers.append("%s: %s" % (header, connection_headers[header]))

        headers.append("Host: streaming.campfirenow.com")

        self.transport.write("\r\n".join(headers) + "\r\n\r\n")
        self.factory.get_stream().set_protocol(self)


Instruction:
How would you explain what the following Python 3 function does
def lineReceived(self, line):
        while self._in_header:
            if line:
                self._headers.append(line)
            else:
                http, status, message = self._headers[0].split(" ", 2)
                status = int(status)
                if status == 200:
                    self.factory.get_stream().connected()
                else:
                    self.factory.continueTrying = 0
                    self.transport.loseConnection()
                    self.factory.get_stream().disconnected(RuntimeError(status, message))
                    return

                self._in_header = False
            break
        else:
            try:
                self._len_expected = int(line, 16)
                self.setRawMode()
            except:
                pass

Response: Callback issued by twisted when new line arrives.


Instruction:
Explain what the following Python 3 code does
def rawDataReceived(self, data):
        if self._len_expected is not None:
            data, extra = data[:self._len_expected], data[self._len_expected:]
            self._len_expected -= len(data)
        else:
            extra = ""

        self._buffer += data
        if self._len_expected == 0:
            data = self._buffer.strip()
            if data:
                lines = data.split("\r")
                for line in lines:
                    try:
                        message = self.factory.get_stream().get_connection().parse(line)
                        if message:
                            self.factory.get_stream().received([message])
                    except ValueError:
                        pass

            self._buffer = ""
            self._len_expected = None
            self.setLineMode(extra)

Response: Process data received from the broker.


Instruction:
Can you tell what is the following Python 3 function doing
def get_func(self, path):
        for url_match, func_pair in self._urls_regex_map.items():
            m = url_match.match(path)
            if m is not None:
                return func_pair.func, func_pair.methods, m.groupdict()
        return None, None, None

Response: Get the function and methods for a given path.


Instruction:
How would you code a function in Python 3 to
replace type to regex.

Response:
def _replace_type_to_regex(cls, match):
        """ /<int:id>  -> r'(?P<id>\d+)' """
        groupdict = match.groupdict()
        _type = groupdict.get('type')
        type_regex = cls.TYPE_REGEX_MAP.get(_type, '[^/]+')
        name = groupdict.get('name')
        return r'(?P<{name}>{type_regex})'.format(
            name=name, type_regex=type_regex
        )


Instruction:
Explain what the following Python 3 code does
def styles(self):
        styles = get_all_styles()
        whitelist = self.app.config.get('CSL_STYLES_WHITELIST')
        if whitelist:
            return {k: v for k, v in styles.items() if k in whitelist}
        return styles

Response: Get a dictionary of CSL styles.


Instruction:
Explain what the following Python 3 code does
def init_app(self, app):
        state = _InvenioCSLRESTState(app)
        app.extensions['invenio-csl-rest'] = state
        return state

Response: Initialize the Flask application.


Instruction:
How would you code a function in Python 3 to
start producing a new entry for the specified consumer.

Response:
def startProducing(self, consumer):
        """ Start producing.

        Args:
            consumer: Consumer
        """
        self._consumer = consumer
        self._current_deferred = defer.Deferred()
        self._sent = 0
        self._paused = False

        if not hasattr(self, "_chunk_headers"):
            self._build_chunk_headers()

        if self._data:
            block = ""
            for field in self._data:
                block += self._chunk_headers[field]
                block += self._data[field]
                block += "\r\n"

            self._send_to_consumer(block)

        if self._files:
            self._files_iterator = self._files.iterkeys()
            self._files_sent = 0
            self._files_length = len(self._files)
            self._current_file_path = None
            self._current_file_handle = None
            self._current_file_length = None
            self._current_file_sent = 0

            result = self._produce()
            if result:
                return result
        else:
            return defer.succeed(None)

        return self._current_deferred


Instruction:
Create a Python 3 function for
sending a block of bytes to the consumer.

Response:
def _send_to_consumer(self, block):
        """ Send a block of bytes to the consumer.

        Args:
            block (str): Block of bytes
        """
        self._consumer.write(block)
        self._sent += len(block)
        if self._callback:
            self._callback(self._sent, self.length)


Instruction:
Can you create a Python 3 function that
returns the total length of this request.

Response:
def _length(self):
        """ Returns total length for this request.

        Returns:
            int. Length
        """
        self._build_chunk_headers()

        length = 0

        if self._data:
            for field in self._data:
                length += len(self._chunk_headers[field])
                length += len(self._data[field])
                length += 2

        if self._files:
            for field in self._files:
                length += len(self._chunk_headers[field])
                length += self._file_size(field)
                length += 2

        length += len(self.boundary)
        length += 6

        return length


Instruction:
Write a Python 3 script for
building headers for each field.

Response:
def _build_chunk_headers(self):
        """ Build headers for each field. """
        if hasattr(self, "_chunk_headers") and self._chunk_headers:
            return

        self._chunk_headers = {}
        for field in self._files:
            self._chunk_headers[field] = self._headers(field, True)
        for field in self._data:
            self._chunk_headers[field] = self._headers(field)


Instruction:
Implement a function in Python 3 to
return the headers of the encoding of this parameter.

Response:
def _headers(self, name, is_file=False):
        """ Returns the header of the encoding of this parameter.

        Args:
            name (str): Field name

        Kwargs:
            is_file (bool): If true, this is a file field

        Returns:
            array. Headers
        """
        value = self._files[name] if is_file else self._data[name]
        _boundary = self.boundary.encode("utf-8") if isinstance(self.boundary, unicode) else urllib.quote_plus(self.boundary)

        headers = ["--%s" % _boundary]

        if is_file:
            disposition = 'form-data; name="%s"; filename="%s"' % (name, os.path.basename(value))
        else:
            disposition = 'form-data; name="%s"' % name

        headers.append("Content-Disposition: %s" % disposition)

        if is_file:
            file_type = self._file_type(name)
        else:
            file_type = "text/plain; charset=utf-8"

        headers.append("Content-Type: %s" % file_type)

        if is_file:
            headers.append("Content-Length: %i" % self._file_size(name))
        else:
            headers.append("Content-Length: %i" % len(value))

        headers.append("")
        headers.append("")

        return "\r\n".join(headers)


Instruction:
Here you have a function in Python 3, explain what it does
def _boundary(self):
        boundary = None
        try:
            import uuid
            boundary = uuid.uuid4().hex
        except ImportError:
            import random, sha
            bits = random.getrandbits(160)
            boundary = sha.new(str(bits)).hexdigest()
        return boundary

Response: Returns a random string to use as the boundary for a message.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _file_type(self, field):
        type = mimetypes.guess_type(self._files[field])[0]
        return type.encode("utf-8") if isinstance(type, unicode) else str(type)

Response: Returns the file type for given file field.


Instruction:
Write a Python 3 function that can
return the size of the file in the given field.

Response:
def _file_size(self, field):
        """ Returns the file size for given file field.

        Args:
            field (str): File field

        Returns:
            int. File size
        """
        size = 0
        try:
            handle = open(self._files[field], "r")
            size = os.fstat(handle.fileno()).st_size
            handle.close()
        except:
            size = 0
        self._file_lengths[field] = size
        return self._file_lengths[field]


Instruction:
Here you have a function in Python 3, explain what it does
def _filename(draw, result_type=None):
    # Various ASCII chars have a special meaning for the operating system,
    # so make them more common
    ascii_char = characters(min_codepoint=0x01, max_codepoint=0x7f)
    if os.name == 'nt':  # pragma: no cover
        # Windows paths can contain all surrogates and even surrogate pairs
        # if two paths are concatenated. This makes it more likely for them to
        # be generated.
        surrogate = characters(
            min_codepoint=0xD800, max_codepoint=0xDFFF)
        uni_char = characters(min_codepoint=0x1)
        text_strategy = text(
            alphabet=one_of(uni_char, surrogate, ascii_char))

        def text_to_bytes(path):
            fs_enc = sys.getfilesystemencoding()
            try:
                return path.encode(fs_enc, 'surrogatepass')
            except UnicodeEncodeError:
                return path.encode(fs_enc, 'replace')

        bytes_strategy = text_strategy.map(text_to_bytes)
    else:
        latin_char = characters(min_codepoint=0x01, max_codepoint=0xff)
        bytes_strategy = text(alphabet=one_of(latin_char, ascii_char)).map(
            lambda t: t.encode('latin-1'))

        unix_path_text = bytes_strategy.map(
            lambda b: b.decode(
                sys.getfilesystemencoding(),
                'surrogateescape' if PY3 else 'ignore'))

        # Two surrogates generated through surrogateescape can generate
        # a valid utf-8 sequence when encoded and result in a different
        # code point when decoded again. Can happen when two paths get
        # concatenated. Shuffling makes it possible to generate such a case.
        text_strategy = permutations(draw(unix_path_text)).map(u"".join)

    if result_type is None:
        return draw(one_of(bytes_strategy, text_strategy))
    elif result_type is bytes:
        return draw(bytes_strategy)
    else:
        return draw(text_strategy)

Response: Generate a path value of type result_type.


Instruction:
Given the following Python 3 function, write the documentation
def _str_to_path(s, result_type):

    assert isinstance(s, str)
    if isinstance(s, bytes) and result_type is text_type:
        return s.decode('ascii')
    elif isinstance(s, text_type) and result_type is bytes:
        return s.encode('ascii')
    return s

Response: Given an ASCII str returns a path of the given type.


Instruction:
Write a Python 3 function that can
generate a root component for a path.

Response:
def _path_root(draw, result_type):
    """Generates a root component for a path."""

    # Based on https://en.wikipedia.org/wiki/Path_(computing)

    def tp(s=''):
        return _str_to_path(s, result_type)

    if os.name != 'nt':
        return tp(os.sep)

    sep = sampled_from([os.sep, os.altsep or os.sep]).map(tp)
    name = _filename(result_type)
    char = characters(min_codepoint=ord("A"), max_codepoint=ord("z")).map(
        lambda c: tp(str(c)))

    relative = sep
    # [drive_letter]:\
    drive = builds(lambda *x: tp().join(x), char, just(tp(':')), sep)
    # \\?\[drive_spec]:\
    extended = builds(
        lambda *x: tp().join(x), sep, sep, just(tp('?')), sep, drive)

    network = one_of([
        # \\[server]\[sharename]\
        builds(lambda *x: tp().join(x), sep, sep, name, sep, name, sep),
        # \\?\[server]\[sharename]\
        builds(lambda *x: tp().join(x),
               sep, sep, just(tp('?')), sep, name, sep, name, sep),
        # \\?\UNC\[server]\[sharename]\
        builds(lambda *x: tp().join(x),
               sep, sep, just(tp('?')), sep, just(tp('UNC')), sep, name, sep,
               name, sep),
        # \\.\[physical_device]\
        builds(lambda *x: tp().join(x),
               sep, sep, just(tp('.')), sep, name, sep),
    ])

    final = one_of(relative, drive, extended, network)

    return draw(final)


Instruction:
Here you have a function in Python 3, explain what it does
def fspaths(draw, allow_pathlike=None):
    has_pathlike = hasattr(os, 'PathLike')

    if allow_pathlike is None:
        allow_pathlike = has_pathlike
    if allow_pathlike and not has_pathlike:
        raise InvalidArgument(
            'allow_pathlike: os.PathLike not supported, use None instead '
            'to enable it only when available')

    result_type = draw(sampled_from([bytes, text_type]))

    def tp(s=''):
        return _str_to_path(s, result_type)

    special_component = sampled_from([tp(os.curdir), tp(os.pardir)])
    normal_component = _filename(result_type)
    path_component = one_of(normal_component, special_component)
    extension = normal_component.map(lambda f: tp(os.extsep) + f)
    root = _path_root(result_type)

    def optional(st):
        return one_of(st, just(result_type()))

    sep = sampled_from([os.sep, os.altsep or os.sep]).map(tp)
    path_part = builds(lambda s, l: s.join(l), sep, lists(path_component))
    main_strategy = builds(lambda *x: tp().join(x),
                           optional(root), path_part, optional(extension))

    if allow_pathlike and hasattr(os, 'fspath'):
        pathlike_strategy = main_strategy.map(lambda p: _PathLike(p))
        main_strategy = one_of(main_strategy, pathlike_strategy)

    return draw(main_strategy)

Response: A strategy which generates filesystem path values.


Instruction:
Write a Python 3 function for
handling the extends command

Response:
def handle_extends(self, text):
        """replace all blocks in extends with current blocks"""
        match = self.re_extends.match(text)
        if match:
            extra_text = self.re_extends.sub('', text, count=1)
            blocks = self.get_blocks(extra_text)
            path = os.path.join(self.base_dir, match.group('path'))
            with open(path, encoding='utf-8') as fp:
                return self.replace_blocks_in_extends(fp.read(), blocks)
        else:
            return None


Instruction:
Given the following Python 3 function, write the documentation
def flush_buffer(self):
        self.code_builder.add_line('{0}.extend([{1}])',
                                   self.result_var, ','.join(self.buffered))
        self.buffered = []

Response: flush all buffered string into code


Instruction:
Can you implement a function in Python 3 that
strips the token from the given text.

Response:
def strip_token(self, text, start, end):
        """{{ a }} -> a"""
        text = text.replace(start, '', 1)
        text = text.replace(end, '', 1)
        return text


Instruction:
Implement a Python 3 function for
calling by the thread, it runs the process. NEVER call this method directly. Instead call start() to start the thread. Before finishing the thread using this thread, call join()

Response:
def run(self):
        """ Called by the thread, it runs the process.

        NEVER call this method directly. Instead call start() to start the thread.

        Before finishing the thread using this thread, call join()
        """
        queue = Queue()
        process = UploadProcess(self._connection_settings, self._room, queue, self._files)
        if self._data:
            process.add_data(self._data)
        process.start()

        if not process.is_alive():
            return

        self._uploading = True

        done = False
        while not self._abort and not done:
            if not process.is_alive():
                self._abort = True
                break

            messages = None
            try:
                data = queue.get()
                if not data:
                    done = True
                    if self._finished_callback:
                        self._finished_callback()
                elif isinstance(data, tuple):
                    sent, total = data
                    if self._progress_callback:
                        self._progress_callback(sent, total)
                else:
                    self._abort = True
                    if self._error_callback:
                        self._error_callback(data, self._room)
            except Empty:
                time.sleep(0.5)

        self._uploading = False
        if self._abort and not process.is_alive() and self._error_callback:
            self._error_callback(Exception("Upload process was killed"), self._room)

        queue.close()
        if process.is_alive():
            queue.close()
            process.terminate()
        process.join()


Instruction:
Can you generate the documentation for the following Python 3 function
def add_data(self, data):
        if not self._data:
            self._data = {}
        self._data.update(data)

Response:
Add POST data.

        Args:
            data (dict): key => value dictionary


Instruction:
How would you code a function in Python 3 to
call by the process, it runs it. NEVER call this method directly. Instead call start() to start the separate process. If you don't want to use a second process, then call fetch() directly on this istance. To stop, call terminate()

Response:
def run(self):
        """ Called by the process, it runs it.

        NEVER call this method directly. Instead call start() to start the separate process.
        If you don't want to use a second process, then call fetch() directly on this istance.

        To stop, call terminate()
        """

        producer_deferred = defer.Deferred()
        producer_deferred.addCallback(self._request_finished)
        producer_deferred.addErrback(self._request_error)

        receiver_deferred = defer.Deferred()
        receiver_deferred.addCallback(self._response_finished)
        receiver_deferred.addErrback(self._response_error)

        self._producer = producer.MultiPartProducer(
            self._files,
            self._data,
            callback = self._request_progress,
            deferred = producer_deferred
        )
        self._receiver = receiver.StringReceiver(receiver_deferred)

        headers = {
            'Content-Type': "multipart/form-data; boundary=%s" % self._producer.boundary
        }

        self._reactor, request = self._connection.build_twisted_request(
            "POST",
            "room/%s/uploads" % self._room.id,
            extra_headers = headers,
            body_producer = self._producer
        )

        request.addCallback(self._response)
        request.addErrback(self._shutdown)

        self._reactor.run()


Instruction:
Implement a Python 3 function for
logging an error message to the log file.

Response:
def log_error(self, text: str) -> None:
        '''
        Given some error text it will log the text if self.log_errors is True

        :param text: Error text to log
        '''
        if self.log_errors:
            with self._log_fp.open('a+') as log_file:
                log_file.write(f'{text}\n')


Instruction:
Can you tell what is the following Python 3 function doing
def parse_conll(self, texts: List[str], retry_count: int = 0) -> List[str]:
        '''
        Processes the texts using TweeboParse and returns them in CoNLL format.

        :param texts: The List of Strings to be processed by TweeboParse.
        :param retry_count: The number of times it has retried for. Default
                            0 does not require setting, main purpose is for
                            recursion.
        :return: A list of CoNLL formated strings.
        :raises ServerError: Caused when the server is not running.
        :raises :py:class:`requests.exceptions.HTTPError`: Caused when the
                input texts is not formated correctly e.g. When you give it a
                String not a list of Strings.
        :raises :py:class:`json.JSONDecodeError`: Caused if after self.retries
                attempts to parse the data it cannot decode the data.

        :Example:

        '''
        post_data = {'texts': texts, 'output_type': 'conll'}
        try:
            response = requests.post(f'http://{self.hostname}:{self.port}',
                                     json=post_data,
                                     headers={'Connection': 'close'})
            response.raise_for_status()
        except (requests.exceptions.ConnectionError,
                requests.exceptions.Timeout) as server_error:
            raise ServerError(server_error, self.hostname, self.port)
        except requests.exceptions.HTTPError as http_error:
            raise http_error
        else:
            try:
                return response.json()
            except json.JSONDecodeError as json_exception:
                if retry_count == self.retries:
                    self.log_error(response.text)
                    raise Exception('Json Decoding error cannot parse this '
                                    f':\n{response.text}')
                return self.parse_conll(texts, retry_count + 1)

Response: Processes the texts using TweeboParse and returns them in CoNLL format.


Instruction:
How would you code a function in Python 3 to
set entity data to be parsed as datetimes

Response:
def set_data(self, data={}, datetime_fields=[]):
        """ Set entity data

        Args:
            data (dict): Entity data
            datetime_fields (array): Fields that should be parsed as datetimes
        """
        if datetime_fields:
            for field in datetime_fields:
                if field in data:
                    data[field] = self._parse_datetime(data[field])

        super(CampfireEntity, self).set_data(data)


Instruction:
Write a Python 3 function that can
parse a datetime string from YYYYMMDD HHMMSS + HHMM

Response:
def _parse_datetime(self, value):
        """ Parses a datetime string from "YYYY/MM/DD HH:MM:SS +HHMM" format

        Args:
            value (str): String

        Returns:
            datetime. Datetime
        """
        offset = 0
        pattern = r"\s+([+-]{1}\d+)\Z"
        matches = re.search(pattern, value)
        if matches:
            value = re.sub(pattern, '', value)
            offset = datetime.timedelta(hours=int(matches.group(1))/100)
        return datetime.datetime.strptime(value, "%Y/%m/%d %H:%M:%S") - offset


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

        # .... I feel this stuff could be done a lot better.
        total_acceleration = Vector.null()
        max_jerk = self.max_acceleration

        for behavior in self.behaviors:
            acceleration, importance = behavior.update()
            weighted_acceleration = acceleration * importance

            """
            if max_jerk >= weighted_acceleration.magnitude:
                max_jerk -= weighted_acceleration.magnitude
                total_acceleration += weighted_acceleration
            elif max_jerk > 0 and max_jerk < weighted_acceleration.magnitude:
                total_acceleration += weighted_acceleration.normal * max_jerk
                break
            else:
                break """
            total_acceleration += weighted_acceleration

        self.acceleration = total_acceleration

        # Update position and velocity.
        Sprite.update(self, time)

        # Update facing direction.
        if self.velocity.magnitude > 0.0:
            self.facing = self.velocity.normal

Response: Update the acceleration and position of the current object.


Instruction:
Make a summary of the following Python 3 code
def update (self):
        delta_velocity = Vector.null()
        target_position = self.target.get_position()
        sprite_position = self.sprite.get_position()

        desired_direction = target_position - sprite_position

        if 0.0 == self.los or desired_direction.magnitude <= self.los:
            try:
                desired_normal = desired_direction.normal
            except NullVectorError:
                desired_normal = Vector.null()
            desired_velocity = desired_normal * self.sprite.get_max_speed()
            delta_velocity = desired_velocity - self.sprite.get_velocity()

        self.last_delta_velocity = delta_velocity
        return delta_velocity, self.power

Response: Update the current time and velocity.


Instruction:
Make a summary of the following Python 3 code
def on_enter_stage(self):
        with self.world._unlock_temporarily():
            self.forum.connect_everyone(self.world, self.actors)

        # 1. Setup the forum.

        self.forum.on_start_game()

        # 2. Setup the world.

        with self.world._unlock_temporarily():
            self.world.on_start_game()

        # 3. Setup the actors.  Because this is done after the forum and the
        #    world have been setup, this signals to the actors that they can
        #    send messages and query the game world as usual.

        num_players = len(self.actors) - 1

        for actor in self.actors:
            actor.on_setup_gui(self.gui)

        for actor in self.actors:
            actor.on_start_game(num_players)

Response: Setup the actors the forum and the world to begin the game.


Instruction:
Given the following Python 3 function, write the documentation
def on_update_stage(self, dt):

        for actor in self.actors:
            actor.on_update_game(dt)

        self.forum.on_update_game()

        with self.world._unlock_temporarily():
            self.world.on_update_game(dt)

        if self.world.has_game_ended():
            self.exit_stage()

Response: Sequentially update the actors the world and the messaging system.


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

        # 1. Let the forum react to the end of the game.  Local forums don't
        #    react to this, but remote forums take the opportunity to stop
        #    trying to extract tokens from messages.

        self.forum.on_finish_game()

        # 2. Let the actors react to the end of the game.

        for actor in self.actors:
            actor.on_finish_game()

        # 3. Let the world react to the end of the game.

        with self.world._unlock_temporarily():
            self.world.on_finish_game()

Response: This method is called when the game is finished.


Instruction:
Create a Python 3 function to
return a list of all the tokens that are referenced by this message.

Response:
def tokens_referenced(self):
        """
        Return a list of all the tokens that are referenced (i.e. contained in)
        this message.  Tokens that haven't been assigned an id yet are searched
        recursively for tokens.  So this method may return fewer results after
        the message is sent.  This information is used by the game engine to
        catch mistakes like forgetting to add a token to the world or keeping a
        stale reference to a token after its been removed.
        """
        tokens = set()

        # Use the pickle machinery to find all the tokens contained at any
        # level of this message.  When an object is being pickled, the Pickler
        # calls its persistent_id() method for each object it encounters.  We
        # hijack this method to add every Token we encounter to a list.

        # This definitely feels like a hacky abuse of the pickle machinery, but
        # that notwithstanding this should be quite robust and quite fast.

        def persistent_id(obj):
            from .tokens import Token

            if isinstance(obj, Token):
                tokens.add(obj)

                # Recursively descend into tokens that haven't been assigned an
                # id yet, but not into tokens that have.

                return obj.id

        from pickle import Pickler
        from io import BytesIO

        # Use BytesIO to basically ignore the serialized data stream, since we
        # only care about visiting all the objects that would be pickled.

        pickler = Pickler(BytesIO())
        pickler.persistent_id = persistent_id
        pickler.dump(self)

        return tokens


Instruction:
Can you tell what is the following Python 3 function doing
def wrap_handler(self, handler, context_switcher):
        context_switcher.add_context_in(lambda: LOGGER.addHandler(self.handler))
        context_switcher.add_context_out(lambda: LOGGER.removeHandler(self.handler))

Response: Enable or disable handler.


Instruction:
Write a Python 3 function for
using when application is starting.

Response:
def init_async(self, loop=None):
        """Use when application is starting."""
        self._loop = loop or asyncio.get_event_loop()
        self._async_lock = asyncio.Lock(loop=loop)

        # FIX: SQLITE in memory database
        if not self.database == ':memory:':
            self._state = ConnectionLocal()


Instruction:
Can you tell what is the following Python 3 function doing
async def async_connect(self):
        if self._async_lock is None:
            raise Exception('Error, database not properly initialized before async connection')

        async with self._async_lock:
            self.connect(True)

        return self._state.conn

Response: Catch a connection asyncrounosly.


Instruction:
Make a summary of the following Python 3 code
def _close(self, conn):
        super(PooledAIODatabase, self)._close(conn)
        for waiter in self._waiters:
            if not waiter.done():
                logger.debug('Release a waiter')
                waiter.set_result(True)
                break

Response: Release all waiters and set the result to True.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def receive_id_from_server(self):
        for message in self.pipe.receive():
            if isinstance(message, IdFactory):
                self.actor_id_factory = message
                return True
        return False

Response: This method is called by the game when a new id is received from the server.


Instruction:
Can you write a function in Python 3 where it
executes a sync request.

Response:
def execute_sync(self, message):
        """
        Respond when the server indicates that the client is out of sync.

        The server can request a sync when this client sends a message that
        fails the check() on the server.  If the reason for the failure isn't
        very serious, then the server can decide to send it as usual in the
        interest of a smooth gameplay experience.  When this happens, the
        server sends out an extra response providing the clients with the
        information they need to resync themselves.
        """
        info("synchronizing message: {message}")

        # Synchronize the world.

        with self.world._unlock_temporarily():
            message._sync(self.world)
            self.world._react_to_sync_response(message)

        # Synchronize the tokens.

        for actor in self.actors:
            actor._react_to_sync_response(message)


Instruction:
How would you code a function in Python 3 to
execute the undo action for the given message.

Response:
def execute_undo(self, message):
        """
        Manage the response when the server rejects a message.

        An undo is when required this client sends a message that the server
        refuses to pass on to the other clients playing the game.  When this
        happens, the client must undo the changes that the message made to the
        world before being sent or crash.  Note that unlike sync requests, undo
        requests are only reported to the client that sent the offending
        message.
        """
        info("undoing message: {message}")

        # Roll back changes that the original message made to the world.

        with self.world._unlock_temporarily():
            message._undo(self.world)
            self.world._react_to_undo_response(message)

        # Give the actors a chance to react to the error.  For example, a
        # GUI actor might inform the user that there are connectivity
        # issues and that their last action was countermanded.

        for actor in self.actors:
            actor._react_to_undo_response(message)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _relay_message(self, message):
        info("relaying message: {message}")

        if not message.was_sent_by(self._id_factory):
            self.pipe.send(message)
            self.pipe.deliver()

Response:
Relay a message from the server to the client represented
        by this actor.


Instruction:
Implement a function in Python 3 to
create a new DataItem.

Response:
def generate(request):
    """ Create a new DataItem. """
    models.DataItem.create(
        content=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(20))
    )
    return muffin.HTTPFound('/')


Instruction:
Implement a Python 3 function for
checking if the given object is an active token and raises an ApiUsageError if it is not.

Response:
def require_active_token(object):
    """
    Raise an ApiUsageError if the given object is not a token that is currently
    participating in the game.  To be participating in the game, the given
    token must have an id number and be associated with the world.
    """
    require_token(object)
    token = object

    if not token.has_id:
        raise ApiUsageError("""\
                token {token} should have an id, but doesn't.

                This error usually means that a token was added to the world
                without being assigned an id number.  To correct this, make
                sure that you're using a message (i.e. CreateToken) to create
                all of your tokens.""")

    if not token.has_world:
        raise ApiUsageError("""\
                token {token} (id={token.id}) not in world.

                You can get this error if you try to remove the same token from
                the world twice.  This might happen is you don't get rid of
                every reference to a token after it's removed the first time,
                then later on you try to remove the stale reference.""")


Instruction:
Can you tell what is the following Python 3 function doing
def add_safety_checks(meta, members):
        for member_name, member_value in members.items():
            members[member_name] = meta.add_safety_check(
                    member_name, member_value)

Response: Iterate through each member of the class being created and add a safety check to every member of the class that isn t marked as read - only.


Instruction:
Make a summary of the following Python 3 code
def add_safety_check(member_name, member_value):
        import functools
        from types import FunctionType

        # Bail if the given member is read-only, private, or not a method.

        is_method = isinstance(member_value, FunctionType)
        is_read_only = hasattr(member_value, '_kxg_read_only')
        is_private = member_name.startswith('_')

        if not is_method or is_read_only or is_private:
            return member_value

        def safety_checked_method(self, *args, **kwargs):
            """
            Make sure that the token the world is locked before a non-read-only
            method is called.
            """
            # Because these checks are pretty magical, I want to be really
            # careful to avoid raising any exceptions other than the check
            # itself (which comes with a very clear error message).  Here, that
            # means using getattr() to make sure the world attribute actually
            # exists.  For example, there's nothing wrong with the following
            # code, but it does call a safety-checked method before the world
            # attribute is defined:
            #
            # class MyToken(kxg.Token):
            #     def __init__(self):
            #         self.init_helper()
            #         super().__init__()

            world = getattr(self, 'world', None)
            if world and world.is_locked():
                nonlocal member_name
                raise ApiUsageError("""\
                        attempted unsafe invocation of
                        {self.__class__.__name__}.{member_name}().

                        This error brings attention to situations that might
                        cause synchronization issues in multiplayer games.  The
                        {member_name}() method is not marked as read-only, but
                        it was invoked from outside the context of a message.
                        This means that if {member_name}() makes any changes to
                        the world, those changes will not be propagated.  If
                        {member_name}() is actually read-only, label it with
                        the @kxg.read_only decorator.""")

            # After making that check, call the method as usual.

            return member_value(self, *args, **kwargs)

        # Preserve any "forum observer" decorations that have been placed on
        # the method and restore the method's original name and module strings,
        # to make inspection and debugging a little easier.

        functools.update_wrapper(
                safety_checked_method, member_value,
                assigned=functools.WRAPPER_ASSIGNMENTS + (
                    '_kxg_subscribe_to_message',
                    '_kxg_subscribe_to_sync_response',
                    '_kxg_subscribe_to_undo_response',
                )
        )
        return safety_checked_method

Response: Add a safety check to the given member.


Instruction:
Explain what the following Python 3 code does
def watch_method(self, method_name, callback):

        # Make sure a token method with the given name exists, and complain if
        # nothing is found.

        try:
            method = getattr(self, method_name)
        except AttributeError:
            raise ApiUsageError("""\
                    {self.__class__.__name__} has no such method
                    {method_name}() to watch.

                    This error usually means that you used the @watch_token
                    decorator on a method of a token extension class that
                    didn't match the name of any method in the corresponding
                    token class.  Check for typos.""")

        # Wrap the method in a WatchedMethod object, if that hasn't already
        # been done.  This object manages a list of callback method and takes
        # responsibility for calling them after the method itself has been
        # called.

        if not isinstance(method, Token.WatchedMethod):
            setattr(self, method_name, Token.WatchedMethod(method))
            method = getattr(self, method_name)

        # Add the given callback to the watched method.

        method.add_watcher(callback)

Response: Register a given callback to be called whenever the method with the given name is called.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _remove_from_world(self):
        self.on_remove_from_world()
        self._extensions = {}
        self._disable_forum_observation()
        self._world = None
        self._id = None

Response: Remove the token from the world.


Instruction:
Can you tell what is the following Python 3 function doing
def _unlock_temporarily(self):
        if not self._is_locked:
            yield
        else:
            try:
                self._is_locked = False
                yield
            finally:
                self._is_locked = True

Response: Unlocks the world for the duration of a with - block.


Instruction:
Can you generate the documentation for the following Python 3 function
def scan(xml):

    if xml.tag is et.Comment:
        yield {'type': COMMENT, 'text': xml.text}
        return

    if xml.tag is et.PI:
        if xml.text:
            yield {'type': PI, 'target': xml.target, 'text': xml.text}
        else:
            yield {'type': PI, 'target': xml.target}
        return

    obj = _elt2obj(xml)
    obj['type'] = ENTER
    yield obj

    assert type(xml.tag) is str, xml
    if xml.text:
        yield {'type': TEXT, 'text': xml.text}

    for c in xml:
        for x in scan(c): yield x
        if c.tail:
            yield {'type': TEXT, 'text': c.tail}

    yield {'type': EXIT}

Response: Converts XML tree to event generator


Instruction:
How would you explain what the following Python 3 function does
def unscan(events, nsmap=None):

    root = None
    last_closed_elt = None
    stack = []
    for obj in events:

        if obj['type'] == ENTER:
            elt = _obj2elt(obj, nsmap=nsmap)
            if stack:
                stack[-1].append(elt)
            elif root is not None:
                raise RuntimeError('Event stream tried to create second XML tree')
            else:
                root = elt
            stack.append(elt)
            last_closed_elt = None

        elif obj['type'] == EXIT:
            last_closed_elt = stack.pop()

        elif obj['type'] == COMMENT:
            elt = et.Comment(obj['text'])
            stack[-1].append(elt)

        elif obj['type'] == PI:
            elt = et.PI(obj['target'])
            if obj.get('text'):
                elt.text = obj['text']
            stack[-1].append(elt)

        elif obj['type'] == TEXT:
            text = obj['text']
            if text:
                if last_closed_elt is None:
                    stack[-1].text = (stack[-1].text or '') + text
                else:
                    last_closed_elt.tail = (last_closed_elt.tail or '') + text
        else:
            assert False, obj

    if root is None:
        raise RuntimeError('Empty XML event stream')

    return root

Response: Converts events stream into lXML tree


Instruction:
Write a Python 3 function that can
parse the file content into events stream

Response:
def parse(filename):
    """Parses file content into events stream"""
    for event, elt in et.iterparse(filename, events= ('start', 'end', 'comment', 'pi'), huge_tree=True):
        if event == 'start':
            obj = _elt2obj(elt)
            obj['type'] = ENTER
            yield obj
            if elt.text:
                yield {'type': TEXT, 'text': elt.text}
        elif event == 'end':
            yield {'type': EXIT}
            if elt.tail:
                yield {'type': TEXT, 'text': elt.tail}
            elt.clear()
        elif event == 'comment':
            yield {'type': COMMENT, 'text': elt.text}
        elif event == 'pi':
            yield {'type': PI, 'text': elt.text}
        else:
            assert False, (event, elt)


Instruction:
How would you code a function in Python 3 to
yield all events that are sub - tree

Response:
def subtree(events):
    """selects sub-tree events"""
    stack = 0
    for obj in events:
        if obj['type'] == ENTER:
            stack += 1
        elif obj['type'] == EXIT:
            if stack == 0:
                break
            stack -= 1
        yield obj


Instruction:
Can you generate a brief explanation for the following Python 3 code
def merge_text(events):
    text = []
    for obj in events:
        if obj['type'] == TEXT:
            text.append(obj['text'])
        else:
            if text:
                yield {'type': TEXT, 'text': ''.join(text)}
                text.clear()
            yield obj
    if text:
        yield {'type': TEXT, 'text': ''.join(text)}

Response: merges each run of successive text events into one text event


Instruction:
Make a summary of the following Python 3 code
def with_peer(events):

    stack = []
    for obj in events:
        if obj['type'] == ENTER:
            stack.append(obj)
            yield obj, None
        elif obj['type'] == EXIT:
            yield obj, stack.pop()
        else:
            yield obj, None

Response: yields all events that are ENTER or EXIT


Instruction:
Can you tell what is the following Python 3 function doing
def from_date(datetime_date):
        return BusinessDate.from_ymd(datetime_date.year, datetime_date.month, datetime_date.day)

Response: construct BusinessDate instance from datetime. date instance


Instruction:
Given the following Python 3 function, write the documentation
def from_string(date_str):
        if date_str.count('-'):
            str_format = '%Y-%m-%d'
        elif date_str.count('.'):
            str_format = '%d.%m.%Y'
        elif date_str.count('/'):
            str_format = '%m/%d/%Y'
        elif len(date_str) == 8:
            str_format = '%Y%m%d'
        elif len(date_str) == 4:
            year = ord(date_str[0]) * 256 + ord(date_str[1])
            month = ord(date_str[2])
            day = ord(date_str[3])
            return BusinessDate.from_ymd(year, month, day)
        else:
            msg = "the date string " + date_str + " has not the right format"
            raise ValueError(msg)

        d = datetime.strptime(date_str, str_format)

        return BusinessDate.from_ymd(d.year, d.month, d.day)

Response: constructs a new date object from a string


Instruction:
Create a Python 3 function for
constructing datetime. date instance represented calendar date of BusinessDate instance

Response:
def to_date(self):
        """
        construct datetime.date instance represented calendar date of BusinessDate instance

        :return datetime.date:
        """
        y, m, d = self.to_ymd()
        return date(y, m, d)


Instruction:
Write a Python 3 script for
checking whether the provided date is a business date.

Response:
def is_businessdate(in_date):
        """
        checks whether the provided date is a date
        :param BusinessDate, int or float in_date:
        :return bool:
        """
        # Note: if the data range has been created from pace_xl, then all the dates are bank dates
        # and here it remains to check the validity.
        # !!! However, if the data has been read from json string via json.load() function
        # it does not recognize that this numbers are bankdates, just considers them as integers
        # therefore, additional check is useful here, first to convert the date if it is integer to BusinessDate,
        # then check the validity.
        # (as the parameter to this method should always be a BusinessDate)
        if not isinstance(in_date, BaseDate):
            try:  # to be removed
                in_date = BusinessDate(in_date)
            except:
                return False
        y, m, d, = in_date.to_ymd()
        return is_valid_ymd(y, m, d)


Instruction:
Can you tell what is the following Python 3 function doing
def is_business_day(self, holiday_obj=None):
        y, m, d = BusinessDate.to_ymd(self)
        if weekday(y, m, d) > FRIDAY:
            return False
        holiday_list = holiday_obj if holiday_obj is not None else DEFAULT_HOLIDAYS
        if self in holiday_list:
            return False
        elif date(y, m, d) in holiday_list:
            return False
        return True

Response: method to check if a date falls on business day


Instruction:
Create a Python 3 function for
adding a period to the current object

Response:
def add_period(self, p, holiday_obj=None):
        """
        addition of a period object

        :param BusinessDate d:
        :param p:
        :type p: BusinessPeriod or str
        :param list holiday_obj:
        :return bankdate:
        """

        if isinstance(p, (list, tuple)):
            return [BusinessDate.add_period(self, pd) for pd in p]
        elif isinstance(p, str):
            period = BusinessPeriod(p)
        else:
            period = p

        res = self
        res = BusinessDate.add_months(res, period.months)
        res = BusinessDate.add_years(res, period.years)
        res = BusinessDate.add_days(res, period.days)

        if period.businessdays:
            if holiday_obj:
                res = BusinessDate.add_business_days(res, period.businessdays, holiday_obj)
            else:
                res = BusinessDate.add_business_days(res, period.businessdays, period.holiday)

        return res


Instruction:
Explain what the following Python 3 code does
def add_business_days(self, days_int, holiday_obj=None):

        res = self
        if days_int >= 0:
            count = 0
            while count < days_int:
                res = BusinessDate.add_days(res, 1)
                if BusinessDate.is_business_day(res, holiday_obj):
                    count += 1
        else:
            count = 0
            while count > days_int:
                res = BusinessDate.add_days(res, -1)
                if BusinessDate.is_business_day(res, holiday_obj):
                    count -= 1

        return res

Response: private method for the addition of business days used in the addition of a BusinessPeriod only


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

        if end_date < self:
            y, m, d = BusinessDate.diff(end_date, self)
            return -y, -m, -d
        y = end_date.year - self.year
        m = end_date.month - self.month

        while m < 0:
            y -= 1
            m += 12
        while m > 12:
            y += 1
            m -= 12

        s = BusinessDate.add_years(BusinessDate.add_months(self, m), y)
        d = BusinessDate.diff_in_days(s, end_date)

        if d < 0:
            m -= 1
            if m < 0:
                y -= 1
                m += 12
            s = BusinessDate.add_years(BusinessDate.add_months(self, m), y)

        d = BusinessDate.diff_in_days(s, end_date)

        return -int(y), -int(m), -int(d)

Response: returns a tuple of years months days


Instruction:
Given the following Python 3 function, write the documentation
def get_30_360(self, end):
        start_day = min(self.day, 30)
        end_day = 30 if (start_day == 30 and end.day == 31) else end.day
        return (360 * (end.year - self.year) + 30 * (end.month - self.month) + (end_day - start_day)) / 360.0

Response: Return the 30 - degree count of the current object.


Instruction:
Explain what the following Python 3 code does
def get_act_act(self, end):
        # split end-self in year portions

        # if the period does not lie within a year split the days in the period as following:
        #           restdays of start year / years in between / days in the end year
        # REMARK: following the affore mentioned ISDA Definition the first day of the period is included whereas the
        # last day will be excluded
        # What remains to check now is only whether the start and end year are leap or non-leap years. The quotients
        # can be easily calculated and for the years in between they are always one (365/365 = 1; 366/366 = 1)

        if end.year - self.year == 0:
            if BusinessDate.is_leap_year(self.year):
                return BusinessDate.diff_in_days(self, end) / 366.0  # leap year: 366 days
            else:
                # return BusinessDate.diff_in_days(self, end) / 366.0
                return BusinessDate.diff_in_days(self, end) / 365.0  # non-leap year: 365 days
        else:
            rest_year1 = BusinessDate.diff_in_days(self, BusinessDate(
                date(self.year, 12, 31))) + 1  # since the first day counts

            rest_year2 = abs(BusinessDate.diff_in_days(end, BusinessDate(
                date(end.year, 1, 1))))  # here the last day is automatically not counted

            years_in_between = end.year - self.year - 1

            return years_in_between + rest_year1 / (366.0 if is_leap_year(self.year) else 365.0) + rest_year2 / (
                366.0 if is_leap_year(end.year) else 365.0)

Response: returns the number of days in the act day of the current object


Instruction:
How would you code a function in Python 3 to
return the 30E - 360 of the time between this date and the given date.

Response:
def get_30E_360(self, end):
        """
        implements the 30E/360 Day Count Convention (4.16(g) 2006 ISDA Definitons)
        """

        y1, m1, d1 = self.to_ymd()
        # adjust to date immediately following the the last day
        y2, m2, d2 = end.add_days(0).to_ymd()

        d1 = min(d1, 30)
        d2 = min(d2, 30)

        return (360 * (y2 - y1) + 30 * (m2 - m1) + (d2 - d1)) / 360.0


Instruction:
Write a Python 3 script to
implement the 30E/360 (ISDA) Day Count Convention (4.16(h) 2006 ISDA Definitions) :param end: :return:

Response:
def get_30E_360_ISDA(self, end):
        """
        implements the 30E/360 (ISDA) Day Count Convention (4.16(h) 2006 ISDA Definitions)
        :param end:
        :return:
        """
        y1, m1, d1 = self.to_ymd()
        # ajdust to date immediately following the last day
        y2, m2, d2 = end.add_days(0).to_ymd()

        if (m1 == 2 and d1 >= 28) or d1 == 31:
            d1 = 30
        if (m2 == 2 and d2 >= 28) or d2 == 31:
            d2 = 30

        return (360 * (y2 - y1) + 30 * (m2 - m1) + (d2 - d1)) / 360.0


Instruction:
Explain what the following Python 3 code does
def adjust_previous(self, holidays_obj=None):
        while not BusinessDate.is_business_day(self, holidays_obj):
            self = BusinessDate.add_days(self, -1)
        return self

Response: Adjusts the calendar to the previous date.


Instruction:
Explain what the following Python 3 code does
def adjust_follow(self, holidays_obj=None):
        while not BusinessDate.is_business_day(self, holidays_obj):
            self = BusinessDate.add_days(self, 1)
        return self

Response: Adjusts the follow date to follow the current date.


Instruction:
Can you tell what is the following Python 3 function doing
def adjust_mod_follow(self, holidays_obj=None):
        month = self.month
        new = BusinessDate.adjust_follow(self, holidays_obj)
        if month != new.month:
            new = BusinessDate.adjust_previous(self, holidays_obj)
        self = new
        return self

Response: Adjusts the calendar to be modified following.


Instruction:
Can you implement a function in Python 3 that
adjusts the calendar to be the previous date.

Response:
def adjust_mod_previous(self, holidays_obj=None):
        """
        ajusts to Business Day Convention "Modified Preceding" (not in 2006 ISDA Definitons).
        """
        month = self.month
        new = BusinessDate.adjust_previous(self, holidays_obj)
        if month != new.month:
            new = BusinessDate.adjust_follow(self, holidays_obj)
        self = new
        return self


Instruction:
Here you have a function in Python 3, explain what it does
def is_businessperiod(cls, in_period):
        try:  # to be removed
            if str(in_period).upper() == '0D':
                return True
            else:
                p = BusinessPeriod(str(in_period))
                return not (p.days == 0 and p.months == 0 and p.years == 0 and p.businessdays == 0)
        except:
            return False

Response: Checks if the object in_period is a businessperiod.


Instruction:
Make a summary of the following Python 3 code
def quoted(parser=any_token):
    quote_char = quote()
    value, _ = many_until(parser, partial(one_of, quote_char))
    return build_string(value)

Response: Parses as much as possible until it encounters a matching closing quote.


Instruction:
How would you code a function in Python 3 to
return the number of days in a given month

Response:
def days_in_month(year, month):
    """
    returns number of days for the given year and month

    :param int year: calendar year
    :param int month: calendar month
    :return int:
    """

    eom = _days_per_month[month - 1]
    if is_leap_year(year) and month == 2:
        eom += 1

    return eom


Instruction:
Write a Python 3 function for
returning True if the year month and day are valid YMD.

Response:
def is_valid_ymd(year, month, day):
    """
    return True if (year,month, day) can be represented in Excel-notation
    (number of days since 30.12.1899) for calendar days, otherwise False

    :param int year: calendar year
    :param int month: calendar month
    :param int day: calendar day
    :return bool:
    """

    return 1 <= month <= 12 and 1 <= day <= days_in_month(year, month) and year >= 1899


Instruction:
Given the following Python 3 function, write the documentation
def from_excel_to_ymd(excel_int):

    int_date = int(floor(excel_int))
    int_date -= 1  if excel_int > 60 else 0
    # jan dingerkus: There are two errors in excels own date <> int conversion.
    # The first is that there exists the 00.01.1900 and the second that there never happend to be a 29.2.1900 since it
    # was no leap year. So there is the int 60 <> 29.2.1900 which has to be jumped over.

    year = (int_date - 1) // 365
    rest_days = int_date - 365 * year - (year + 3) // 4 + (year + 99) // 100 - (year + 299) // 400
    year += 1900

    while rest_days <= 0:
        year -= 1
        rest_days += days_in_year(year)

    month = 1
    if is_leap_year(year) and rest_days == 60:
        month = 2
        day = 29
    else:
        if is_leap_year(year) and rest_days > 60:
            rest_days -= 1

        while rest_days > _cum_month_days[month]:
            month += 1

        day = rest_days - _cum_month_days[month - 1]
    return year, month, day

Response: Convert an int into a tuple of year month and day.


Instruction:
Given the following Python 3 function, write the documentation
def from_ymd_to_excel(year, month, day):
    if not is_valid_ymd(year, month, day):
        raise ValueError("Invalid date {0}.{1}.{2}".format(year, month, day))

    days = _cum_month_days[month - 1] + day
    days += 1 if (is_leap_year(year) and month > 2) else 0

    years_distance = year - 1900
    days += years_distance * 365 + \
            (years_distance + 3) // 4 - (years_distance + 99) // 100 + (years_distance + 299) // 400

    # count days since 30.12.1899 (excluding 30.12.1899) (workaround for excel bug)
    days += 1 if (year, month, day) > (1900, 2, 28) else 0
    return days

Response: Converts a date in YYYYMMDD format into Microsoft Excel representation


Instruction:
Write a Python 3 function that can
add a number of years to a date

Response:
def add_years(d, years_int):
        """
        adds number of years to a date
        :param BaseDateFloat d: date to add years to
        :param int years_int: number of years to add
        :return BaseDate: resulting date
        """

        y, m, d = BaseDate.to_ymd(d)
        if not is_leap_year(years_int) and m == 2:
            d = min(28, d)
        return BaseDateFloat.from_ymd(y + years_int, m, d)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_days(d, days_int):
        n = date(d.year, d.month, d.day) + timedelta(days_int)
        return BaseDateDatetimeDate(n.year, n.month, n.day)

Response: add_days adds a number of days to a date


Instruction:
Can you create a Python 3 function that
calculates difference between start and end dates in days

Response:
def diff_in_days(start, end):
        """
        calculate difference between given dates in days

        :param BaseDateDatetimeDate start: state date
        :param BaseDateDatetimeDate end: end date
        :return float: difference between end date and start date in days
        """
        diff = date(end.year, end.month, end.day) - date(start.year, start.month, start.day)
        return float(diff.days)


Instruction:
Explain what the following Python 3 code does
def add_days(date_obj, days_int):
        n = from_ymd_to_excel(*date_obj.date) + days_int

        return BaseDateTuple(*from_excel_to_ymd(n))

Response: add_days adds a number of days to a date tuple


Instruction:
How would you explain what the following Python 3 function does
def add_years(date_obj, years_int):
        y, m, d = BaseDateTuple.to_ymd(date_obj)
        y += years_int
        if not is_leap_year(y) and m == 2:
            d = min(28, d)
        return BaseDateTuple.from_ymd(y, m, d)

Response: add_years adds a number of years to the base date tuple d


Instruction:
How would you code a function in Python 3 to
calculate difference between start and end dates in days

Response:
def diff_in_days(start, end):
        """
        calculate difference between given dates in days

        :param BaseDateTuple start: state date
        :param BaseDateTuple end: end date
        :return float: difference between end date and start date in days
        """

        diff = from_ymd_to_excel(*end.date)-from_ymd_to_excel(*start.date)
        return float(diff)


Instruction:
Implement a Python 3 function for
registering connection s middleware and prepare self database.

Response:
def startup(self, app):
        """Register connection's middleware and prepare self database."""
        self.database.init_async(app.loop)
        if not self.cfg.connection_manual:
            app.middlewares.insert(0, self._middleware)


Instruction:
Create a Python 3 function for
registering a model in self. models.

Response:
def register(self, model):
        """Register a model in self."""
        self.models[model._meta.table_name] = model
        model._meta.database = self.database
        return model


Instruction:
Here you have a function in Python 3, explain what it does
async def manage(self):
        cm = _ContextManager(self.database)
        if isinstance(self.database.obj, AIODatabase):
            cm.connection = await self.database.async_connect()

        else:
            cm.connection = self.database.connect()

        return cm

Response: Manage a database connection.


Instruction:
Write a Python 3 script for
writing your migrations here. > Model = migrator.orm['name'] > migrator.sql(sql) > migrator.create_table(Model) > migrator.drop_table(Model, cascade=True) > migrator.add_columns(Model, **fields) > migrator.change_columns(Model, **fields) > migrator.drop_columns(Model, *field_names, cascade=True) > migrator.rename_column(Model, old_field_name, new_field_name) > migrator.rename_table(Model, new_table_name) > migrator.add_index(Model, *col_names, unique=False) > migrator.drop_index(Model, index_name) > migrator.add_not_null(Model, field_name) > migrator.drop_not_null(Model, field_name) > migrator.add_default(Model, field_name, default)

Response:
def migrate(migrator, database, **kwargs):
    """ Write your migrations here.

    > Model = migrator.orm['name']

    > migrator.sql(sql)
    > migrator.create_table(Model)
    > migrator.drop_table(Model, cascade=True)
    > migrator.add_columns(Model, **fields)
    > migrator.change_columns(Model, **fields)
    > migrator.drop_columns(Model, *field_names, cascade=True)
    > migrator.rename_column(Model, old_field_name, new_field_name)
    > migrator.rename_table(Model, new_table_name)
    > migrator.add_index(Model, *col_names, unique=False)
    > migrator.drop_index(Model, index_name)
    > migrator.add_not_null(Model, field_name)
    > migrator.drop_not_null(Model, field_name)
    > migrator.add_default(Model, field_name, default)

    """
    @migrator.create_table
    class DataItem(pw.Model):
        created = pw.DateTimeField(default=dt.datetime.utcnow)
        content = pw.CharField()


Instruction:
Given the following Python 3 function, write the documentation
def chain(*args):
    def chain_block(*args, **kwargs):
        v = args[0](*args, **kwargs)
        for p in args[1:]:
            v = p(v)
        return v
    return chain_block

Response: Runs a series of parsers in sequence passing the result of each parser to the next.


Instruction:
Can you generate the documentation for the following Python 3 function
def one_of(these):
    ch = peek()
    try:
        if (ch is EndOfFile) or (ch not in these):
            fail(list(these))
    except TypeError:
        if ch != these:
            fail([these])
    next()
    return ch

Response: Returns the current token if is found in the collection provided. Fails otherwise.


Instruction:
How would you explain what the following Python 3 function does
def not_one_of(these):
    ch = peek()
    desc = "not_one_of" + repr(these)
    try:
        if (ch is EndOfFile) or (ch in these):
            fail([desc])
    except TypeError:
        if ch != these:
            fail([desc])
    next()
    return ch

Response: Returns the current token if it is not found in the collection provided.


Instruction:
Create a Python 3 function to
return the current token if it satisfies the guard function provided. Fails if the guard function provided is not a function.

Response:
def satisfies(guard):
    """Returns the current token if it satisfies the guard function provided.

    Fails otherwise.
    This is the a generalisation of one_of.
    """
    i = peek()
    if (i is EndOfFile) or (not guard(i)):
        fail(["<satisfies predicate " + _fun_to_str(guard) + ">"])
    next()
    return i


Instruction:
Can you write a function in Python 3 where it
succeeds if the given parser cannot consume input

Response:
def not_followed_by(parser):
    """Succeeds if the given parser cannot consume input"""
    @tri
    def not_followed_by_block():
        failed = object()
        result = optional(tri(parser), failed)
        if result != failed:
            fail(["not " + _fun_to_str(parser)])
    choice(not_followed_by_block)


Instruction:
Write a Python 3 function for
applying the parser to input zero or more times.

Response:
def many(parser):
    """Applies the parser to input zero or more times.

    Returns a list of parser results.
    """
    results = []
    terminate = object()
    while local_ps.value:
        result = optional(parser, terminate)
        if result == terminate:
            break
        results.append(result)
    return results


Instruction:
Write a Python 3 function for
consuming as many of these as it can until it is encountered.

Response:
def many_until(these, term):
    """Consumes as many of these as it can until it term is encountered.

    Returns a tuple of the list of these results and the term result
    """
    results = []
    while True:
        stop, result = choice(_tag(True, term),
                              _tag(False, these))
        if stop:
            return results, result
        else:
            results.append(result)


Instruction:
Explain what the following Python 3 code does
def many_until1(these, term):
    first = [these()]
    these_results, term_result = many_until(these, term)
    return (first + these_results, term_result)

Response: Like many_until but must consume at least one of these.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def sep1(parser, separator):
    first = [parser()]
    def inner():
        separator()
        return parser()
    return first + many(tri(inner))

Response: Like sep but must consume at least one of parser.


Instruction:
Can you generate the documentation for the following Python 3 function
def string(string):
    found = []
    for c in string:
        found.append(one_of(c))
    return found

Response: Iterates over a string and returns a list of items that match the input.


Instruction:
Given the following Python 3 function, write the documentation
def seq(*sequence):
    results = {}
    for p in sequence:
        if callable(p):
            p()
            continue
        k, v = p
        results[k] = v()
    return results

Response: Runs a series of parsers in sequence optionally storing results in a dictionary.


Instruction:
How would you explain what the following Python 3 function does
def _fill(self, size):
        try:
            for i in range(size):
                self.buffer.append(self.source.next())
        except StopIteration:
            self.buffer.append((EndOfFile, EndOfFile))
        self.len = len(self.buffer)

Response: fills the internal buffer with the specified size


Instruction:
Can you generate a brief explanation for the following Python 3 code
def next(self):
        self.index += 1
        t = self.peek()
        if not self.depth:
            self._cut()
        return t

Response: Advances to and returns the next token or returns EndOfFile


Instruction:
How would you explain what the following Python 3 function does
def current(self):
        if self.index >= self.len:
            self._fill((self.index - self.len) + 1)
        return self.index < self.len and self.buffer[self.index] or (EndOfFile, EndOfFile)

Response: Returns the current token or position


Instruction:
Write a Python 3 script for
running a game being developed with the kxg game engine. Usage: {exe_name} sandbox [<num_ais>] [-v...] {exe_name} client [--host HOST] [--port PORT] [-v...] {exe_name} server <num_guis> [<num_ais>] [--host HOST] [--port PORT] [-v...] {exe_name} debug <num_guis> [<num_ais>] [--host HOST] [--port PORT] [-v...] {exe_name} --help Commands: sandbox Play a single-player game with the specified number of AIs. None of the multiplayer machinery will be used. client Launch a client that will try to connect to a server on the given host and port. Once it connects and the game starts, the client will allow you to play the game against any other connected clients. server Launch a server that will manage a game between the given number of human and AI players. The human players must connect using this command's client mode. debug Debug a multiplayer game locally. This command launches a server and the given number of clients all in different processes, and configures the logging system such that the output from each process can be easily distinguished. Arguments: <num_guis> The number of human players that will be playing the game. Only needed by commands that will launch some sort of multiplayer server. <num_ais> The number of AI players that will be playing the game. Only needed by commands that will launch single-player games or multiplayer servers. Options: -x --host HOST [default: {default_host}] The address of the machine running the server. Must be accessible from the machines running the clients. -p --port PORT [default: {default_port}] The port that the server should listen on. Don't specify a value less than 1024 unless the server is running with root permissions. -v --verbose Have the game engine log more information about what it's doing. You can specify this option several times to get more and more information. This command is provided so that you can start writing your game with the least possible amount of boilerplate code. However, the clients and servers provided by this command are not capable of running a production game. Once you have written your game and want to give it a polished set of menus and options, you'll have to write new Stage subclasses encapsulating that logic and you'll have to call those stages yourself by interacting more directly with the Theater class. The online documentation has more information on this process.

Response:
def main(world_cls, referee_cls, gui_cls, gui_actor_cls, ai_actor_cls,
        theater_cls=PygletTheater, default_host=DEFAULT_HOST,
        default_port=DEFAULT_PORT, argv=None):
    """
Run a game being developed with the kxg game engine.

Usage:
    {exe_name} sandbox [<num_ais>] [-v...]
    {exe_name} client [--host HOST] [--port PORT] [-v...]
    {exe_name} server <num_guis> [<num_ais>] [--host HOST] [--port PORT] [-v...]
    {exe_name} debug <num_guis> [<num_ais>] [--host HOST] [--port PORT] [-v...]
    {exe_name} --help

Commands:
    sandbox
        Play a single-player game with the specified number of AIs.  None of
        the multiplayer machinery will be used.

    client
        Launch a client that will try to connect to a server on the given host
        and port.  Once it connects and the game starts, the client will allow
        you to play the game against any other connected clients.

    server
        Launch a server that will manage a game between the given number of
        human and AI players.  The human players must connect using this
        command's client mode.

    debug
        Debug a multiplayer game locally.  This command launches a server and
        the given number of clients all in different processes, and configures
        the logging system such that the output from each process can be easily
        distinguished.

Arguments:
    <num_guis>
        The number of human players that will be playing the game.  Only needed
        by commands that will launch some sort of multiplayer server.

    <num_ais>
        The number of AI players that will be playing the game.  Only needed by
        commands that will launch single-player games or multiplayer servers.

Options:
    -x --host HOST          [default: {default_host}]
        The address of the machine running the server.  Must be accessible from
        the machines running the clients.

    -p --port PORT          [default: {default_port}]
        The port that the server should listen on.  Don't specify a value less
        than 1024 unless the server is running with root permissions.

    -v --verbose
        Have the game engine log more information about what it's doing.  You
        can specify this option several times to get more and more information.

This command is provided so that you can start writing your game with the least
possible amount of boilerplate code.  However, the clients and servers provided
by this command are not capable of running a production game.  Once you have
written your game and want to give it a polished set of menus and options,
you'll have to write new Stage subclasses encapsulating that logic and you'll
have to call those stages yourself by interacting more directly with the
Theater class.  The online documentation has more information on this process.
    """
    import sys, os, docopt, nonstdlib

    exe_name = os.path.basename(sys.argv[0])
    usage = main.__doc__.format(**locals()).strip()
    args = docopt.docopt(usage, argv or sys.argv[1:])
    num_guis = int(args['<num_guis>'] or 1)
    num_ais = int(args['<num_ais>'] or 0)
    host, port = args['--host'], int(args['--port'])

    logging.basicConfig(
            format='%(levelname)s: %(name)s: %(message)s',
            level=nonstdlib.verbosity(args['--verbose']),
    )

    # Use the given game objects and command line arguments to play a game!

    if args['debug']:
        print("""\
****************************** KNOWN BUG WARNING ******************************
In debug mode, every message produced by the logging system gets printed twice.
I know vaguely why this is happening, but as of yet I've not been able to fix
it.  In the mean time, don't let this confuse you!
*******************************************************************************""")
        game = MultiplayerDebugger(
                world_cls, referee_cls, gui_cls, gui_actor_cls, num_guis,
                ai_actor_cls, num_ais, theater_cls, host, port)
    else:
        game = theater_cls()
        ai_actors = [ai_actor_cls() for i in range(num_ais)]

        if args['sandbox']:
            game.gui = gui_cls()
            game.initial_stage = UniplayerGameStage(
                    world_cls(), referee_cls(), gui_actor_cls(), ai_actors)
            game.initial_stage.successor = PostgameSplashStage()

        if args['client']:
            game.gui = gui_cls()
            game.initial_stage = ClientConnectionStage(
                    world_cls(), gui_actor_cls(), host, port)

        if args['server']:
            game.initial_stage = ServerConnectionStage(
                    world_cls(), referee_cls(), num_guis, ai_actors,
                    host, port)

    game.play()


Instruction:
Explain what the following Python 3 code does
def _run_supervisor(self):
        import time

        still_supervising = lambda: (
                multiprocessing.active_children()
                or not self.log_queue.empty()
                or not self.exception_queue.empty())

        try:
            while still_supervising():
                # When a log message is received, make a logger with the same
                # name in this process and use it to re-log the message.  It
                # will get handled in this process.

                try:
                    record = self.log_queue.get_nowait()
                    logger = logging.getLogger(record.name)
                    logger.handle(record)
                except queue.Empty:
                    pass

                # When an exception is received, immediately re-raise it.

                try:
                    exception = self.exception_queue.get_nowait()
                except queue.Empty:
                    pass
                else:
                    raise exception

                # Sleep for a little bit, and make sure that the workers haven't
                # outlived their time limit.

                time.sleep(1/self.frame_rate)
                self.elapsed_time += 1/self.frame_rate

                if self.time_limit and self.elapsed_time > self.time_limit:
                    raise RuntimeError("timeout")

        # Make sure the workers don't outlive the supervisor, no matter how the
        # polling loop ended (e.g. normal execution or an exception).

        finally:
            for process in multiprocessing.active_children():
                process.terminate()

Response: This function runs the supervisor process.


Instruction:
Here you have a function in Python 3, explain what it does
def field_type(self):
        if not self.model:
            return 'JSON'
        database = self.model._meta.database
        if isinstance(database, Proxy):
            database = database.obj
        if Json and isinstance(database, PostgresqlDatabase):
            return 'JSON'
        return 'TEXT'

Response: Return database field type.


Instruction:
Can you tell what is the following Python 3 function doing
def python_value(self, value):
        if self.field_type == 'TEXT' and isinstance(value, str):
            return self.loads(value)
        return value

Response: Parse value from database.


Instruction:
Given the following Python 3 function, write the documentation
def get_fsapi_endpoint(self):
        endpoint = yield from self.__session.get(self.fsapi_device_url, timeout = self.timeout)
        text = yield from endpoint.text(encoding='utf-8')
        doc = objectify.fromstring(text)
        return doc.webfsapi.text

Response: Parse the fsapi endpoint from the device url.


Instruction:
Create a Python 3 function to
create a session on the frontier silicon device.

Response:
def create_session(self):
        """Create a session on the frontier silicon device."""
        req_url = '%s/%s' % (self.__webfsapi, 'CREATE_SESSION')
        sid = yield from self.__session.get(req_url, params=dict(pin=self.pin),
                                            timeout = self.timeout)
        text = yield from sid.text(encoding='utf-8')
        doc = objectify.fromstring(text)
        return doc.sessionId.text


Instruction:
Here you have a function in Python 3, explain what it does
def call(self, path, extra=None):
        try:
            if not self.__webfsapi:
                self.__webfsapi = yield from self.get_fsapi_endpoint()

            if not self.sid:
                self.sid = yield from self.create_session()

            if not isinstance(extra, dict):
                extra = dict()

            params = dict(pin=self.pin, sid=self.sid)
            params.update(**extra)

            req_url = ('%s/%s' % (self.__webfsapi, path))
            result = yield from self.__session.get(req_url, params=params,
                                                   timeout = self.timeout)
            if result.status == 200:
                text = yield from result.text(encoding='utf-8')
            else:
                self.sid = yield from self.create_session()
                params = dict(pin=self.pin, sid=self.sid)
                params.update(**extra)
                result = yield from self.__session.get(req_url, params=params,
                                                       timeout = self.timeout)
                text = yield from result.text(encoding='utf-8')

            return objectify.fromstring(text)
        except Exception as e:
            logging.info('AFSAPI Exception: ' +traceback.format_exc())

        return None

Response: Execute a frontier silicon API call.


Instruction:
Here you have a function in Python 3, explain what it does
def handle_text(self, item):
        doc = yield from self.handle_get(item)
        if doc is None:
            return None

        return doc.value.c8_array.text or None

Response: Helper method for fetching a text value.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def handle_int(self, item):
        doc = yield from self.handle_get(item)
        if doc is None:
            return None

        return int(doc.value.u8.text) or None

Response: Helper method for fetching an integer value.


Instruction:
Create a Python 3 function for
handling a long item. Result is integer.

Response:
def handle_long(self, item):
        """Helper method for fetching a long value. Result is integer."""
        doc = yield from self.handle_get(item)
        if doc is None:
            return None

        return int(doc.value.u32.text) or None


Instruction:
Here you have a function in Python 3, explain what it does
def handle_list(self, item):
        doc = yield from self.call('LIST_GET_NEXT/'+item+'/-1', dict(
            maxItems=100,
        ))

        if doc is None:
            return []

        if not doc.status == 'FS_OK':
            return []

        ret = list()
        for index, item in enumerate(list(doc.iterchildren('item'))):
            temp = dict(band=index)
            for field in list(item.iterchildren()):
                temp[field.get('name')] = list(field.iterchildren()).pop()
            ret.append(temp)

        return ret

Response: Helper method for fetching a list ( map ) value.


Instruction:
How would you implement a function in Python 3 that
checks if the device is on.

Response:
def get_power(self):
        """Check if the device is on."""
        power = (yield from self.handle_int(self.API.get('power')))
        return bool(power)


Instruction:
Can you implement a function in Python 3 that
powers on or off the device.

Response:
def set_power(self, value=False):
        """Power on or off the device."""
        power = (yield from self.handle_set(
            self.API.get('power'), int(value)))
        return bool(power)


Instruction:
Implement a Python 3 function for
getting the modes supported by this device.

Response:
def get_modes(self):
        """Get the modes supported by this device."""
        if not self.__modes:
            self.__modes = yield from self.handle_list(
                self.API.get('valid_modes'))

        return self.__modes


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_mode_list(self):
        self.__modes = yield from self.get_modes()
        return (yield from self.collect_labels(self.__modes))

Response: Get the label list of the supported modes.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_mode(self):
        mode = None
        int_mode = (yield from self.handle_long(self.API.get('mode')))
        modes = yield from self.get_modes()
        for temp_mode in modes:
            if temp_mode['band'] == int_mode:
                mode = temp_mode['label']

        return str(mode)

Response: Get the currently active mode on the device.


Instruction:
Create a Python 3 function to
set the currently active mode on the device.

Response:
def set_mode(self, value):
        """Set the currently active mode on the device (DAB, FM, Spotify)."""
        mode = -1
        modes = yield from self.get_modes()
        for temp_mode in modes:
            if temp_mode['label'] == value:
                mode = temp_mode['band']

        return (yield from self.handle_set(self.API.get('mode'), mode))


Instruction:
Explain what the following Python 3 code does
def get_volume_steps(self):
        if not self.__volume_steps:
            self.__volume_steps = yield from self.handle_int(
                self.API.get('volume_steps'))

        return self.__volume_steps

Response: Read the maximum volume level of the device.


Instruction:
Explain what the following Python 3 code does
def get_mute(self):
        mute = (yield from self.handle_int(self.API.get('mute')))
        return bool(mute)

Response: Check if the device is muted.


Instruction:
Make a summary of the following Python 3 code
def set_mute(self, value=False):
        mute = (yield from self.handle_set(self.API.get('mute'), int(value)))
        return bool(mute)

Response: Mute or unmute the device.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_play_status(self):
        status = yield from self.handle_int(self.API.get('status'))
        return self.PLAY_STATES.get(status)

Response: Get the play status of the device.


Instruction:
Create a Python 3 function for
getting the equaliser modes supported by this device.

Response:
def get_equalisers(self):
        """Get the equaliser modes supported by this device."""
        if not self.__equalisers:
            self.__equalisers = yield from self.handle_list(
                self.API.get('equalisers'))

        return self.__equalisers


Instruction:
Can you tell what is the following Python 3 function doing
def get_equaliser_list(self):
        self.__equalisers = yield from self.get_equalisers()
        return (yield from self.collect_labels(self.__equalisers))

Response: Get the list of the supported modes.


Instruction:
How would you explain what the following Python 3 function does
def set_sleep(self, value=False):
        return (yield from self.handle_set(self.API.get('sleep'), int(value)))

Response: Set device sleep timer.


Instruction:
Can you tell what is the following Python 3 function doing
def _set_range(self, start, stop, value, value_len):
        assert stop >= start and value_len >= 0
        range_len = stop - start
        if range_len < value_len:
            self._insert_zeros(stop, stop + value_len - range_len)
            self._copy_to_range(start, value, value_len)
        elif range_len > value_len:
            self._del_range(stop - (range_len - value_len), stop)
            self._copy_to_range(start, value, value_len)
        else:
            self._copy_to_range(start, value, value_len)

Response: Set the value of the log entry.


Instruction:
How would you implement a function in Python 3 that
parses genotype from VCF line data

Response:
def _parse_genotype(self, vcf_fields):
        """Parse genotype from VCF line data"""
        format_col = vcf_fields[8].split(':')
        genome_data = vcf_fields[9].split(':')
        try:
            gt_idx = format_col.index('GT')
        except ValueError:
            return []
        return [int(x) for x in re.split(r'[\|/]', genome_data[gt_idx]) if
                x != '.']


Instruction:
Can you tell what is the following Python 3 function doing
def setDefaultIREncoding(encoding):
	'''
		setDefaultIREncoding - Sets the default encoding used by IndexedRedis.
		  This will be the default encoding used for field data. You can override this on a
		  per-field basis by using an IRField (such as IRUnicodeField or IRRawField)

		@param encoding - An encoding (like utf-8)
	'''
	try:
		b''.decode(encoding)
	except:
		raise ValueError('setDefaultIREncoding was provided an invalid codec. Got (encoding="%s")' %(str(encoding), ))

	global defaultIREncoding
	defaultIREncoding = encoding

Response: Sets the default encoding used by IndexedRedis.


Instruction:
Can you tell what is the following Python 3 function doing
def _getReprProperties(self):
		'''
			_getReprProperties - Get the properties of this field to display in repr().

				These should be in the form of $propertyName=$propertyRepr

				The default IRField implementation handles just the "hashIndex" property.

				defaultValue is part of "__repr__" impl. You should just extend this method
				with your object's properties instead of rewriting repr.

		'''
		ret = []
		if getattr(self, 'valueType', None) is not None:
			ret.append('valueType=%s' %(self.valueType.__name__, ))
		if hasattr(self, 'hashIndex'):
			ret.append('hashIndex=%s' %(self.hashIndex, ))

		return ret

Response: Returns a list of properties to be displayed in the repr.


Instruction:
Implement a function in Python 3 to
return a copy of this IRField.

Response:
def copy(self):
		'''
			copy - Create a copy of this IRField.

			  Each subclass should implement this, as you'll need to pass in the args to constructor.

			@return <IRField (or subclass)> - Another IRField that has all the same values as this one.
		'''
		return self.__class__(name=self.name, valueType=self.valueType, defaultValue=self.defaultValue, hashIndex=self.hashIndex)


Instruction:
Implement a function in Python 3 to
return the object associated with this data.

Response:
def getObj(self):
		'''
			getObj - Fetch (if not fetched) and return the obj associated with this data.
		'''
		if self.obj is None:
			if not self.pk:
				return None
			self.obj = self.foreignModel.objects.get(self.pk)

		return self.obj