Instruction:
How would you explain what the following Python 3 function does
def to_array(self):
        array = super(GameMessage, self).to_array()
        array['game_short_name'] = u(self.game_short_name)  # py2: type unicode, py3: type str

        if self.receiver is not None:
            if isinstance(self.receiver, None):
                array['chat_id'] = None(self.receiver)  # type Noneelif isinstance(self.receiver, str):
                array['chat_id'] = u(self.receiver)  # py2: type unicode, py3: type str
            elif isinstance(self.receiver, int):
                array['chat_id'] = int(self.receiver)  # type intelse:
                raise TypeError('Unknown type, must be one of None, str, int.')
            # end if

        if self.reply_id is not None:
            if isinstance(self.reply_id, DEFAULT_MESSAGE_ID):
                array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id)  # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int):
                array['reply_to_message_id'] = int(self.reply_id)  # type intelse:
                raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.')
            # end if

        if self.disable_notification is not None:
            array['disable_notification'] = bool(self.disable_notification)  # type bool
        if self.reply_markup is not None:
            array['reply_markup'] = self.reply_markup.to_array()  # type InlineKeyboardMarkup

        return array

Response: Serializes this GameMessage to a dictionary.


Instruction:
Given the following Python 3 function, write the documentation
def from_array(array):
        if array is None or not array:
            return None
        # end if
        assert_type_or_raise(array, dict, parameter_name="array")
        from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup

        data = {}
        data['game_short_name'] = u(array.get('game_short_name'))
        if array.get('chat_id') is None:
            data['receiver'] = None
        elif isinstance(array.get('chat_id'), None):
            data['receiver'] = None(array.get('chat_id'))
        elif isinstance(array.get('chat_id'), str):
            data['receiver'] = u(array.get('chat_id'))
        elif isinstance(array.get('chat_id'), int):
            data['receiver'] = int(array.get('chat_id'))
        else:
            raise TypeError('Unknown type, must be one of None, str, int or None.')
        # end if
        if array.get('reply_to_message_id') is None:
            data['reply_id'] = None
        elif isinstance(array.get('reply_to_message_id'), DEFAULT_MESSAGE_ID):
            data['reply_id'] = DEFAULT_MESSAGE_ID(array.get('reply_to_message_id'))
        elif isinstance(array.get('reply_to_message_id'), int):
            data['reply_id'] = int(array.get('reply_to_message_id'))
        else:
            raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int or None.')
        # end if
        data['disable_notification'] = bool(array.get('disable_notification')) if array.get('disable_notification') is not None else None
        data['reply_markup'] = InlineKeyboardMarkup.from_array(array.get('reply_markup')) if array.get('reply_markup') is not None else None
        return GameMessage(**data)

Response: Deserialize a new GameMessage from a given dictionary.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def select_nodeids(xmrs, iv=None, label=None, pred=None):
    def datamatch(nid):
        ep = xmrs.ep(nid)
        return ((iv is None or ep.iv == iv) and
                (pred is None or ep.pred == pred) and
                (label is None or ep.label == label))
    return list(filter(datamatch, xmrs.nodeids()))

Response:
Returns a list of nodeids in xmrs that match if their corresponding
            matches the given intrinsic variable label and predicate.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def select_nodes(xmrs, nodeid=None, pred=None):
    nodematch = lambda n: ((nodeid is None or n.nodeid == nodeid) and
                           (pred is None or n.pred == pred))
    return list(filter(nodematch, nodes(xmrs)))

Response: Return the list of matching nodes in xmrs.


Instruction:
Write a Python 3 function for
selecting the elements in a base - level elementary pre - predication from a semantic structure.

Response:
def select_eps(xmrs, nodeid=None, iv=None, label=None, pred=None):
    """
    Return the list of matching elementary predications in *xmrs*.

    :class:`~delphin.mrs.components.ElementaryPredication` objects for
    *xmrs* match if their `nodeid` matches *nodeid*,
    `intrinsic_variable` matches *iv*, `label` matches *label*, and
    `pred` to *pred*. The *nodeid*, *iv*, *label*, and *pred* filters
    are ignored if they are `None`.

    Args:
        xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to
            query
        nodeid (optional): nodeid to match
        iv (str, optional): intrinsic variable to match
        label (str, optional): label to match
        pred (str, :class:`~delphin.mrs.components.Pred`, optional):
            predicate to match
    Returns:
        list: matching elementary predications
    """
    epmatch = lambda n: ((nodeid is None or n.nodeid == nodeid) and
                         (iv is None or n.iv == iv) and
                         (label is None or n.label == label) and
                         (pred is None or n.pred == pred))
    return list(filter(epmatch, xmrs.eps()))


Instruction:
Write a Python 3 script for
selecting the arguments from the given xmrs.

Response:
def select_args(xmrs, nodeid=None, rargname=None, value=None):
    """
    Return the list of matching (nodeid, role, value) triples in *xmrs*.

    Predication arguments in *xmrs* match if the `nodeid` of the
    :class:`~delphin.mrs.components.ElementaryPredication` they are
    arguments of match *nodeid*, their role matches *rargname*, and
    their value matches *value*. The *nodeid*, *rargname*, and *value*
    filters are ignored if they are `None`.

    Note:
        The *value* filter matches the variable, handle, or constant
        that is the overt value for the argument. If you want to find
        arguments that target a particular nodeid, look into
        :meth:`Xmrs.incoming_args() <delphin.mrs.xmrs.Xmrs.incoming_args>`.
        If you want to match a target value to its resolved object, see
        :func:`find_argument_target`.
    Args:
        xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to
            query
        nodeid (optional): nodeid to match
        rargname (str, optional): role name to match
        value (str, optional): argument value to match
    Returns:
        list: matching arguments as (nodeid, role, value) triples
    """
    argmatch = lambda a: ((nodeid is None or a[0] == nodeid) and
                          (rargname is None or
                           a[1].upper() == rargname.upper()) and
                          (value is None or a[2] == value))
    all_args = (
        (nid, role, val)
        for nid in xmrs.nodeids()
        for role, val in sorted(
            xmrs.args(nid).items(),
            key=lambda i: rargname_sortkey(i[0])
        )
    )
    return list(filter(argmatch, all_args))


Instruction:
Write a Python 3 script to
select the links in the given xmrs.

Response:
def select_links(xmrs, start=None, end=None, rargname=None, post=None):
    """
    Return the list of matching links for *xmrs*.

    :class:`~delphin.mrs.components.Link` objects for *xmrs* match if
    their `start` matches *start*, `end` matches *end*, `rargname`
    matches *rargname*, and `post` matches *post*. The *start*, *end*,
    *rargname*, and *post* filters are ignored if they are `None`.

    Args:
        xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to
            query
        start (optional): link start nodeid to match
        end (optional): link end nodeid to match
        rargname (str, optional): role name to match
        post (str, optional): Link post-slash label to match
    Returns:
        list: matching links
    """
    linkmatch = lambda l: (
        (start is None or l.start == start) and
        (end is None or l.end == end) and
        (rargname is None or l.rargname == rargname) and
        (post is None or l.post == post))
    return list(filter(linkmatch, links(xmrs)))


Instruction:
How would you explain what the following Python 3 function does
def select_hcons(xmrs, hi=None, relation=None, lo=None):
    hcmatch = lambda hc: (
        (hi is None or hc.hi == hi) and
        (relation is None or hc.relation == relation) and
        (lo is None or hc.lo == lo))
    return list(filter(hcmatch, xmrs.hcons()))

Response: Select the HCONS for the given xmrs.


Instruction:
Can you tell what is the following Python 3 function doing
def select_icons(xmrs, left=None, relation=None, right=None):
    icmatch = lambda ic: (
        (left is None or ic.left == left) and
        (relation is None or ic.relation == relation) and
        (right is None or ic.right == right))
    return list(filter(icmatch, xmrs.icons()))

Response: Returns a list of ICONS for xmrs matching left and right variables.


Instruction:
Write a Python 3 function for
returning the target of an argument.

Response:
def find_argument_target(xmrs, nodeid, rargname):
    """
    Return the target of an argument (rather than just the variable).

    Note:
        If the argument value is an intrinsic variable whose target is
        an EP that has a quantifier, the non-quantifier EP's nodeid
        will be returned. With this nodeid, one can then use
        :meth:`Xmrs.nodeid() <delphin.mrs.xmrs.Xmrs.nodeid>` to get its
        quantifier's nodeid.
    Args:
        xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to
            use
        nodeid: nodeid of the argument.
        rargname: role name of the argument.
    Returns:
        The object that is the target of the argument. Possible values
        include:

        ==================  =====  =============================
        Argument value      e.g.   Target
        ------------------  -----  -----------------------------
        intrinsic variable  x4     nodeid; of the EP with the IV
        hole variable       h0     nodeid; HCONS's labelset head
        label               h1     nodeid; label's labelset head
        unbound variable    i3     the variable itself
        constant            "IBM"  the constant itself
        ==================  =====  =============================
    """
    tgt = xmrs.args(nodeid)[rargname]
    if tgt in xmrs.variables():
        try:
            return xmrs.nodeid(tgt)
        except KeyError:
            pass

        try:
            tgt = xmrs.hcon(tgt).lo
            return next(iter(xmrs.labelset_heads(tgt)), None)
        except KeyError:
            pass

        try:
            return next(iter(xmrs.labelset_heads(tgt)))
        except (KeyError, StopIteration):
            pass
    return tgt


Instruction:
Create a Python 3 function to
yield all subgraphs matching a list of predicates.

Response:
def find_subgraphs_by_preds(xmrs, preds, connected=None):
    """
    Yield subgraphs matching a list of predicates.

    Predicates may match multiple EPs/nodes in the *xmrs*, meaning that
    more than one subgraph is possible. Also, predicates in *preds*
    match in number, so if a predicate appears twice in *preds*, there
    will be two matching EPs/nodes in each subgraph.

    Args:
        xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to
            use
        preds: iterable of predicates to include in subgraphs
        connected (bool, optional): if `True`, all yielded subgraphs
            must be connected, as determined by
            :meth:`Xmrs.is_connected() <delphin.mrs.xmrs.Xmrs.is_connected>`.
    Yields:
        A :class:`~delphin.mrs.xmrs.Xmrs` object for each subgraphs found.
    """
    preds = list(preds)
    count = len(preds)
    # find all lists of nodeids such that the lists have no repeated nids;
    # keep them as a list (fixme: why not just get sets?)
    nidsets = set(
        tuple(sorted(ns))
        for ns in filter(
            lambda ns: len(set(ns)) == count,
            product(*[select_nodeids(xmrs, pred=p) for p in preds])
        )
    )
    for nidset in nidsets:
        sg = xmrs.subgraph(nidset)
        if connected is None or sg.is_connected() == connected:
            yield sg


Instruction:
Given the following Python 3 function, write the documentation
def intrinsic_variables(xmrs):
    ivs = set(
        ep.intrinsic_variable for ep in xmrs.eps()
        if not ep.is_quantifier() and ep.intrinsic_variable is not None
    )
    return sorted(ivs, key=var_id)

Response: Return the list of all intrinsic variables in xmrs


Instruction:
Can you generate a brief explanation for the following Python 3 code
def bound_variables(xmrs):
    bvs = set(
        ep.intrinsic_variable for ep in xmrs.eps()
        if ep.is_quantifier() and ep.intrinsic_variable is not None
    )
    return sorted(bvs, key=var_id)

Response: Return the list of all bound variables in xmrs


Instruction:
Can you tell what is the following Python 3 function doing
def in_labelset(xmrs, nodeids, label=None):
    nodeids = set(nodeids)
    if label is None:
        label = xmrs.ep(next(iter(nodeids))).label
    return nodeids.issubset(xmrs._vars[label]['refs']['LBL'])

Response: Test if all nodeids share a label.


Instruction:
Can you implement a function in Python 3 that
returns a tuple with the value for the json url argument and a dictionary for the multipart file upload.

Response:
def get_input_media_referenced_files(self, var_name):
        """
        Generates a tuple with the value for the json/url argument and a dictionary for the multipart file upload.
        Will return something which might be similar to
        `('attach://{var_name}', {var_name: ('foo.png', open('foo.png', 'rb'), 'image/png')})`

        or in the case of the :class:`InputFileUseFileID` class, just
        `('AwADBAADbXXXXXXXXXXXGBdhD2l6_XX', None)`

        :param var_name: name used to reference the file.
        :type  var_name: str

        :return: tuple of (file_id, dict)
        :rtype: tuple
        """
        # file to be uploaded
        string = 'attach://{name}'.format(name=var_name)
        return string, self.get_request_files(var_name)


Instruction:
Implement a function in Python 3 to
create a new instance of the InputFile subclass.

Response:
def factory(
            cls, file_id=None, path=None, url=None, blob=None, mime=None,
            prefer_local_download=True, prefer_str=False, create_instance=True
    ):
        """
        Creates a new InputFile subclass instance fitting the given parameters.

        :param prefer_local_download: If `True`, we download the file and send it to telegram. This is the default.
                                      If `False`, we send Telegram just the URL, and they'll try to download it.
        :type  prefer_local_download: bool

        :param prefer_str: Return just the `str` instead of a `InputFileUseFileID` or `InputFileUseUrl` object.
        :type  prefer_str: bool

        :param create_instance: If we should return a instance ready to use (default),
                                or the building parts being a tuple of `(class, args_tuple, kwargs_dict)`.
                                Setting this to `False` is probably only ever required for internal usage
                                by the :class:`InputFile` constructor which uses this very factory.
        :type  create_instance: bool

        :returns: if `create_instance=True` it returns a instance of some InputFile subclass or a string,
                  if `create_instance=False` it returns a tuple of the needed class, args and kwargs needed
                  to create a instance.
        :rtype: InputFile|InputFileFromBlob|InputFileFromDisk|InputFileFromURL|str|tuple
        """
        if create_instance:
            clazz, args, kwargs = cls.factory(
                file_id=file_id,
                path=path,
                url=url,
                blob=blob,
                mime=mime,
                create_instance=False,
            )
            return clazz(*args, **kwargs)
        if file_id:
            if prefer_str:
                assert_type_or_raise(file_id, str, parameter_name='file_id')
                return str, (file_id,), dict()
            # end if
            return InputFileUseFileID, (file_id,), dict()
        if blob:
            name = "file"
            suffix = ".blob"
            if path:
                name = os_path.basename(os_path.normpath(path))  # http://stackoverflow.com/a/3925147/3423324#last-part
                name, suffix = os_path.splitext(name)  # http://stackoverflow.com/a/541394/3423324#extension
            elif url:
                # http://stackoverflow.com/a/18727481/3423324#how-to-extract-a-filename-from-a-url
                url = urlparse(url)
                name = os_path.basename(url.path)
                name, suffix = os_path.splitext(name)
            # end if
            if mime:
                import mimetypes
                suffix = mimetypes.guess_extension(mime)
                suffix = '.jpg' if suffix == '.jpe' else suffix  # .jpe -> .jpg
            # end if
            if not suffix or not suffix.strip().lstrip("."):
                logger.debug("suffix was empty. Using '.blob'")
                suffix = ".blob"
            # end if
            name = "{filename}{suffix}".format(filename=name, suffix=suffix)
            return InputFileFromBlob, (blob,), dict(name=name, mime=mime)
        if path:
            return InputFileFromDisk, (path,), dict(mime=mime)
        if url:
            if prefer_local_download:
                return InputFileFromURL, (url,), dict(mime=mime)
            # end if
            # else -> so we wanna let telegram handle it
            if prefer_str:
                assert_type_or_raise(url, str, parameter_name='url')
                return str, (url,), dict()
            # end if
            return InputFileUseUrl, (url,), dict()

        # end if
        raise ValueError('Could not find a matching subclass. You might need to do it manually instead.')


Instruction:
Make a summary of the following Python 3 code
def to_array(self):
        array = super(PassportData, self).to_array()
        array['data'] = self._as_array(self.data)  # type list of EncryptedPassportElement
        array['credentials'] = self.credentials.to_array()  # type EncryptedCredentials
        return array

Response: Serializes this PassportData to a dictionary.


Instruction:
Can you generate the documentation for the following Python 3 function
def to_array(self):
        array = super(PassportFile, self).to_array()
        array['file_id'] = u(self.file_id)  # py2: type unicode, py3: type str
        array['file_size'] = int(self.file_size)  # type int
        array['file_date'] = int(self.file_date)  # type int
        return array

Response: Serializes this PassportFile to a dictionary.


Instruction:
Here you have a function in Python 3, explain what it does
def to_array(self):
        array = super(EncryptedPassportElement, self).to_array()
        array['type'] = u(self.type)  # py2: type unicode, py3: type str

        array['hash'] = u(self.hash)  # py2: type unicode, py3: type str

        if self.data is not None:
            array['data'] = u(self.data)  # py2: type unicode, py3: type str
        if self.phone_number is not None:
            array['phone_number'] = u(self.phone_number)  # py2: type unicode, py3: type str
        if self.email is not None:
            array['email'] = u(self.email)  # py2: type unicode, py3: type str
        if self.files is not None:
            array['files'] = self._as_array(self.files)  # type list of PassportFile
        if self.front_side is not None:
            array['front_side'] = self.front_side.to_array()  # type PassportFile
        if self.reverse_side is not None:
            array['reverse_side'] = self.reverse_side.to_array()  # type PassportFile
        if self.selfie is not None:
            array['selfie'] = self.selfie.to_array()  # type PassportFile
        if self.translation is not None:
            array['translation'] = self._as_array(self.translation)  # type list of PassportFile
        return array

Response: Serializes this EncryptedPassportElement to a dictionary.


Instruction:
Can you tell what is the following Python 3 function doing
def from_array(array):
        if array is None or not array:
            return None
        # end if
        assert_type_or_raise(array, dict, parameter_name="array")

        data = {}
        data['type'] = u(array.get('type'))
        data['hash'] = u(array.get('hash'))
        data['data'] = u(array.get('data')) if array.get('data') is not None else None
        data['phone_number'] = u(array.get('phone_number')) if array.get('phone_number') is not None else None
        data['email'] = u(array.get('email')) if array.get('email') is not None else None
        data['files'] = PassportFile.from_array_list(array.get('files'), list_level=1) if array.get('files') is not None else None
        data['front_side'] = PassportFile.from_array(array.get('front_side')) if array.get('front_side') is not None else None
        data['reverse_side'] = PassportFile.from_array(array.get('reverse_side')) if array.get('reverse_side') is not None else None
        data['selfie'] = PassportFile.from_array(array.get('selfie')) if array.get('selfie') is not None else None
        data['translation'] = PassportFile.from_array_list(array.get('translation'), list_level=1) if array.get('translation') is not None else None
        data['_raw'] = array
        return EncryptedPassportElement(**data)

Response: Deserialize a new EncryptedPassportElement from a given dictionary.


Instruction:
Make a summary of the following Python 3 code
def to_array(self):
        array = super(EncryptedCredentials, self).to_array()
        array['data'] = u(self.data)  # py2: type unicode, py3: type str
        array['hash'] = u(self.hash)  # py2: type unicode, py3: type str
        array['secret'] = u(self.secret)  # py2: type unicode, py3: type str
        return array

Response: Serializes this EncryptedCredentials to a dictionary.


Instruction:
How would you explain what the following Python 3 function does
def from_array(array):
        if array is None or not array:
            return None
        # end if
        assert_type_or_raise(array, dict, parameter_name="array")

        data = {}
        data['data'] = u(array.get('data'))
        data['hash'] = u(array.get('hash'))
        data['secret'] = u(array.get('secret'))
        data['_raw'] = array
        return EncryptedCredentials(**data)

Response: Deserialize a new EncryptedCredentials instance from a given dictionary.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_updates(self, offset=None, limit=100, poll_timeout=0, allowed_updates=None, request_timeout=None, delta=timedelta(milliseconds=100), error_as_empty=False):
        from datetime import datetime

        assert(offset is None or isinstance(offset, int))
        assert(limit is None or isinstance(limit, int))
        assert(poll_timeout is None or isinstance(poll_timeout, int))
        assert(allowed_updates is None or isinstance(allowed_updates, list))
        if poll_timeout and not request_timeout is None:
            request_timeout = poll_timeout + 2
        # end if

        if delta.total_seconds() > poll_timeout:
            now = datetime.now()
            if self._last_update - now < delta:
                wait = ((now - self._last_update) - delta).total_seconds()  # can be 0.2
                wait = 0 if wait < 0 else wait
                if wait != 0:
                    logger.debug("Sleeping {i} seconds.".format(i=wait))
                # end if
                sleep(wait)
            # end if
        # end if
        self._last_update = datetime.now()
        try:
            result = self.do(
                "getUpdates", offset=offset, limit=limit, timeout=poll_timeout, allowed_updates=allowed_updates,
                use_long_polling=poll_timeout != 0, request_timeout=request_timeout
            )
            if self.return_python_objects:
                logger.debug("Trying to parse {data}".format(data=repr(result)))
                from pytgbot.api_types.receivable.updates import Update
                try:
                    return Update.from_array_list(result, list_level=1)
                except TgApiParseException:
                    logger.debug("Failed parsing as api_type Update", exc_info=True)
                # end try
                # no valid parsing so far
                raise TgApiParseException("Could not parse result.")  # See debug log for details!
            # end if return_python_objects
            return result
        except (requests.RequestException, TgApiException) as e:
            if error_as_empty:
                logger.warn("Network related error happened in get_updates(), but will be ignored: " + str(e),
                            exc_info=True)
                self._last_update = datetime.now()
                return DictObject(result=[], exception=e)
            else:
                raise

Response: This method returns a list of updates from the server using long polling.


Instruction:
Given the following Python 3 function, write the documentation
def get_me(self):
        result = self.do("getMe")
        if self.return_python_objects:
            logger.debug("Trying to parse {data}".format(data=repr(result)))
            from pytgbot.api_types.receivable.peer import User
            try:
                return User.from_array(result)
            except TgApiParseException:
                logger.debug("Failed parsing as api_type User", exc_info=True)
            # end try
            # no valid parsing so far
            raise TgApiParseException("Could not parse result.")  # See debug log for details!
        # end if return_python_objects
        return result

Response: A simple method for testing your bot s auth token. Requires no parameters. Returns basic information about the bot in form of a User object. Requires no parameters. Returns a User object.


Instruction:
How would you code a function in Python 3 to
use this method to forward a message from one chat to another.

Response:
def forward_message(self, chat_id, from_chat_id, message_id, disable_notification=False):
        """
        Use this method to forward messages of any kind. On success, the sent Message is returned.

        https://core.telegram.org/bots/api#forwardmessage

        Parameters:

        :param chat_id: Unique identifier for the target chat (chat id of user chat or group chat) or username of the
                        target channel (in the format @channelusername)
        :type  chat_id: int | str|unicode

        :param from_chat_id: Unique identifier for the chat where the original message was sent
                             (id for chats or the channel's username in the format @channelusername)
        :type  from_chat_id: int | str|unicode

        :param message_id: Message identifier in the chat specified in from_chat_id
        :type  message_id: int

        Optional keyword parameters:

        :param disable_notification: Sends the message silently. Users will receive a notification with no sound.
        :type  disable_notification: bool

        Returns:

        :return: On success, the sent Message is returned
        :rtype:  pytgbot.api_types.receivable.updates.Message
        """
        assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")

        assert_type_or_raise(from_chat_id, (int, unicode_type), parameter_name="from_chat_id")

        assert_type_or_raise(message_id, int, parameter_name="message_id")

        assert_type_or_raise(disable_notification, None, bool, parameter_name="disable_notification")

        result = self.do(
            "forwardMessage", chat_id=chat_id, from_chat_id=from_chat_id, message_id=message_id,
            disable_notification=disable_notification
        )
        if self.return_python_objects:
            logger.debug("Trying to parse {data}".format(data=repr(result)))
            from pytgbot.api_types.receivable.updates import Message
            try:
                return Message.from_array(result)
            except TgApiParseException:
                logger.debug("Failed parsing as api_type Message", exc_info=True)
            # end try
            # no valid parsing so far
            raise TgApiParseException("Could not parse result.")  # See debug log for details!
        # end if return_python_objects
        return result


Instruction:
Create a Python 3 function for
using this method to send a group of photos or videos as an album. You must be an administrator in the chat for this to work and must have the appropriate admin rights. You must have the appropriate admin rights.

Response:
def send_media_group(self, chat_id, media, disable_notification=None, reply_to_message_id=None):
        """
        Use this method to send a group of photos or videos as an album. On success, an array of the sent Messages is returned.

        https://core.telegram.org/bots/api#sendmediagroup

        Parameters:

        :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
        :type  chat_id: int | str|unicode

        :param media: A array describing photos and videos to be sent, must include 2–10 items
        :type  media: list of (pytgbot.api_types.sendable.input_media.InputMediaPhoto|pytgbot.api_types.sendable.input_media.InputMediaVideo)

        Optional keyword parameters:

        :param disable_notification: Sends the messages silently. Users will receive a notification with no sound.
        :type  disable_notification: bool

        :param reply_to_message_id: If the messages are a reply, ID of the original message
        :type  reply_to_message_id: int

        Returns:

        :return: On success, an array of the sent Messages is returned
        :rtype:  Messages
        """
        assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
        from .api_types.sendable.input_media import InputMediaPhoto, InputMediaVideo

        files = {}
        new_media = []
        assert_type_or_raise(media, list, parameter_name="media")
        for i, medium in enumerate(media):
            assert_type_or_raise(medium, InputMediaPhoto, InputMediaVideo, parameter_name="media[{i}]".format(i=i))
            assert isinstance(medium, (InputMediaPhoto, InputMediaVideo))
            new_medium, file = medium.get_request_data('pytgbot{i}'.format(i=i), full_data=True)
            logger.debug('InputMedia {} found.'.format(new_medium))
            new_media.append(new_medium)
            if file:
                files.update(file)
            # end if
        # end for
        new_media = json.dumps(new_media)

        assert_type_or_raise(disable_notification, None, bool, parameter_name="disable_notification")

        assert_type_or_raise(reply_to_message_id, None, int, parameter_name="reply_to_message_id")

        result = self.do(
            "sendMediaGroup", chat_id=chat_id, media=new_media, files=files,
            disable_notification=disable_notification, reply_to_message_id=reply_to_message_id,
        )
        if self.return_python_objects:
            logger.debug("Trying to parse {data}".format(data=repr(result)))    # no valid parsing so far
            if not isinstance(result, list):
                raise TgApiParseException("Could not parse result als list.")  # See debug log for details!
            # end if
            from .api_types.receivable.updates import Message
            return [Message.from_array(msg) for msg in result]  # parse them all as Message.
            raise TgApiParseException("Could not parse result.")  # See debug log for details!
        # end if return_python_objects
        return result


Instruction:
Implement a function in Python 3 to
use this method to send answers to an inline query. On success, True is returned. No more than 50 results per query are allowed. https://core.telegram.org/bots/api#answerinlinequery Parameters: :param inline_query_id: Unique identifier for the answered query :type inline_query_id: str|unicode :param results: A JSON-serialized array of results for the inline query :type results: list of pytgbot.api_types.sendable.inline.InlineQueryResult Optional keyword parameters: :param cache_time: The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300. :type cache_time: int :param is_personal: Pass True, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query :type is_personal: bool :param next_offset: Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don‘t support pagination. Offset length can’t exceed 64 bytes. :type next_offset: str|unicode :param switch_pm_text: If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter switch_pm_parameter :type switch_pm_text: str|unicode :param switch_pm_parameter: Deep-linking parameter for the /start message sent to the bot when user presses the switch button. 1-64 characters, only `A-Z`, `a-z`, `0-9`, `_` and `-` are allowed. Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a "Connect your YouTube account" button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an oauth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot's inline capabilities. :type switch_pm_parameter: str|unicode Returns: :return: On success, True is returned :rtype: bool

Response:
def answer_inline_query(self, inline_query_id, results, cache_time=None, is_personal=None, next_offset=None,
                            switch_pm_text=None, switch_pm_parameter=None):
        """
        Use this method to send answers to an inline query. On success, True is returned.
        No more than 50 results per query are allowed.

        https://core.telegram.org/bots/api#answerinlinequery

        Parameters:

        :param inline_query_id: Unique identifier for the answered query
        :type  inline_query_id: str|unicode

        :param results: A JSON-serialized array of results for the inline query
        :type  results: list of pytgbot.api_types.sendable.inline.InlineQueryResult

        Optional keyword parameters:

        :param cache_time: The maximum amount of time in seconds that the result of the inline query may be cached on
                             the server. Defaults to 300.
        :type  cache_time: int

        :param is_personal: Pass True, if results may be cached on the server side only for the user that sent the
                              query. By default, results may be returned to any user who sends the same query
        :type  is_personal: bool

        :param next_offset: Pass the offset that a client should send in the next query with the same text to receive
                            more results. Pass an empty string if there are no more results or if you don‘t support
                            pagination. Offset length can’t exceed 64 bytes.
        :type  next_offset: str|unicode

        :param switch_pm_text: If passed, clients will display a button with specified text that switches
                               the user to a private chat with the bot and sends the bot a start message with the
                               parameter switch_pm_parameter
        :type  switch_pm_text: str|unicode

        :param switch_pm_parameter: Deep-linking parameter for the /start message sent to the bot when user presses
                                    the switch button. 1-64 characters, only `A-Z`, `a-z`, `0-9`, `_` and `-` are allowed.
                                      Example:
                                         An inline bot that sends YouTube videos can ask the user to connect the
                                         bot to their YouTube account to adapt search results accordingly.
                                         To do this, it displays a "Connect your YouTube account" button above the
                                         results, or even before showing any.
                                         The user presses the button, switches to a private chat with the bot and,
                                         in doing so, passes a start parameter that instructs the bot to return an
                                         oauth link.
                                         Once done, the bot can offer a switch_inline button so that
                                         the user can easily return to the chat where they wanted to use the bot's
                                         inline capabilities.
        :type  switch_pm_parameter: str|unicode

        Returns:

        :return: On success, True is returned
        :rtype: bool
        """
        assert_type_or_raise(inline_query_id, int, unicode_type, parameter_name="inline_query_id")
        if isinstance(inline_query_id, int):
            inline_query_id = u(inline_query_id)
        # end if
        assert isinstance(inline_query_id, unicode_type)

        assert_type_or_raise(results, list, tuple, InlineQueryResult, parameter_name="results")

        if isinstance(results, InlineQueryResult):
            results = [results]
        assert(isinstance(results, (list, tuple)))  # list of InlineQueryResult
        result_objects = []
        for result in results:
            if not isinstance(result, InlineQueryResult):  # checks all elements of results
                raise ValueError("Parameter results is not list of InlineQueryResult")
            # end if
            result_objects.append(result.to_array())
        # end for results

        assert_type_or_raise(cache_time, None, int, parameter_name="cache_time")

        assert_type_or_raise(is_personal, None, bool, parameter_name="is_personal")

        assert_type_or_raise(next_offset, None, unicode_type, str, int, parameter_name="next_offset")
        if next_offset is not None:
            assert(isinstance(next_offset, (str, unicode_type, int)))
            next_offset = u(next_offset)
        # end if

        assert_type_or_raise(switch_pm_text, None, unicode_type, parameter_name="switch_pm_text")

        assert_type_or_raise(switch_pm_parameter, None, unicode_type, parameter_name="switch_pm_parameter")

        result = self.do(
            "answerInlineQuery", inline_query_id=inline_query_id, results=json.dumps(result_objects),
            cache_time=cache_time, is_personal=is_personal, next_offset=next_offset, switch_pm_text=switch_pm_text,
            switch_pm_parameter=switch_pm_parameter
        )
        if self.return_python_objects:
            logger.debug("Trying to parse {data}".format(data=repr(result)))
            try:
                return from_array_list(bool, result, list_level=0, is_builtin=True)
            except TgApiParseException:
                logger.debug("Failed parsing as primitive bool", exc_info=True)
            # end try
            # no valid parsing so far
            raise TgApiParseException("Could not parse result.")  # See debug log for details!
        # end if return_python_objects
        return result


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_game_score(self, user_id, score, force=False, disable_edit_message=False, chat_id=None, message_id=None, inline_message_id=None):
        assert_type_or_raise(user_id, int, parameter_name="user_id")

        assert_type_or_raise(score, int, parameter_name="score")

        assert_type_or_raise(force, None, bool, parameter_name="force")

        assert_type_or_raise(disable_edit_message, None, bool, parameter_name="disable_edit_message")

        assert_type_or_raise(chat_id, None, int, parameter_name="chat_id")

        assert_type_or_raise(message_id, None, int, parameter_name="message_id")

        assert_type_or_raise(inline_message_id, None, unicode_type, parameter_name="inline_message_id")

        result = self.do("setGameScore", user_id=user_id, score=score, force=force, disable_edit_message=disable_edit_message, chat_id=chat_id, message_id=message_id, inline_message_id=inline_message_id)
        if self.return_python_objects:
            logger.debug("Trying to parse {data}".format(data=repr(result)))
            from pytgbot.api_types.receivable.updates import Message
            try:
                return Message.from_array(result)
            except TgApiParseException:
                logger.debug("Failed parsing as api_type Message", exc_info=True)
            # end try

            try:
                return from_array_list(bool, result, list_level=0, is_builtin=True)
            except TgApiParseException:
                logger.debug("Failed parsing as primitive bool", exc_info=True)
            # end try
            # no valid parsing so far
            raise TgApiParseException("Could not parse result.")  # See debug log for details!
        # end if return_python_objects
        return result

Response: Use this method to set the score of a user in a game message.


Instruction:
Explain what the following Python 3 code does
def _postprocess_request(self, r):
        from DictObject import DictObject
        import requests

        assert isinstance(r, requests.Response)

        try:
            logger.debug(r.json())
            res = DictObject.objectify(r.json())
        except Exception as e:
            raise TgApiResponseException('Parsing answer as json failed.', r, e)
        # end if
        res["response"] = r  # TODO: does this failes on json lists? Does TG does that?
        # TG should always return an dict, with at least a status or something.
        if self.return_python_objects:
            if res.ok is not True:
                raise TgApiServerException(
                    error_code=res.error_code if "error_code" in res else None,
                    response=res.response if "response" in res else None,
                    description=res.description if "description" in res else None,
                    request=r.request
                )
            # end if not ok
            if "result" not in res:
                raise TgApiParseException('Key "result" is missing.')
            # end if no result
            return res.result
        # end if return_python_objects
        return res

Response: This method converts the response from the server to either the response or a parsed response.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _do_fileupload(self, file_param_name, value, _command=None, _file_is_optional=False, **kwargs):
        from .api_types.sendable.files import InputFile
        from luckydonaldUtils.encoding import unicode_type
        from luckydonaldUtils.encoding import to_native as n

        if value is None and _file_is_optional:
            # Is None but set optional, so do nothing.
            pass
        elif isinstance(value, str):
            kwargs[file_param_name] = str(value)
        elif isinstance(value, unicode_type):
            kwargs[file_param_name] = n(value)
        elif isinstance(value, InputFile):
            files = value.get_request_files(file_param_name)
            if "files" in kwargs and kwargs["files"]:
                # already are some files there, merge them.
                assert isinstance(kwargs["files"], dict), \
                    'The files should be of type dict, but are of type {}.'.format(type(kwargs["files"]))
                for key in files.keys():
                    assert key not in kwargs["files"], '{key} would be overwritten!'
                    kwargs["files"][key] = files[key]
                # end for
            else:
                # no files so far
                kwargs["files"] = files
            # end if
        else:
            raise TgApiTypeError("Parameter {key} is not type (str, {text_type}, {input_file_type}), but type {type}".format(
                key=file_param_name, type=type(value), input_file_type=InputFile, text_type=unicode_type))
        # end if
        if not _command:
            # command as camelCase  # "voice_note" -> "sendVoiceNote"  # https://stackoverflow.com/a/10984923/3423324
            command = re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), "send_" + file_param_name)
        else:
            command = _command
        # end def
        return self.do(command, **kwargs)

Response: This method is used to send a file to Telegram servers.


Instruction:
Write a Python 3 function for
serializing this LabeledPrice to a dictionary.

Response:
def to_array(self):
        """
        Serializes this LabeledPrice to a dictionary.

        :return: dictionary representation of this object.
        :rtype: dict
        """
        array = super(LabeledPrice, self).to_array()
        array['label'] = u(self.label)  # py2: type unicode, py3: type str

        array['amount'] = int(self.amount)  # type int
        return array


Instruction:
Can you tell what is the following Python 3 function doing
def from_array(array):
        if array is None or not array:
            return None
        # end if
        assert_type_or_raise(array, dict, parameter_name="array")

        data = {}
        data['label'] = u(array.get('label'))
        data['amount'] = int(array.get('amount'))

        instance = LabeledPrice(**data)
        instance._raw = array
        return instance

Response: Deserialize a new LabeledPrice from a given dictionary.


Instruction:
Can you create a Python 3 function that
serializes this ShippingOption to a dictionary.

Response:
def to_array(self):
        """
        Serializes this ShippingOption to a dictionary.

        :return: dictionary representation of this object.
        :rtype: dict
        """
        array = super(ShippingOption, self).to_array()
        array['id'] = u(self.id)  # py2: type unicode, py3: type str

        array['title'] = u(self.title)  # py2: type unicode, py3: type str

        array['prices'] = self._as_array(self.prices)  # type list of LabeledPrice

        return array


Instruction:
Explain what the following Python 3 code does
def from_array(array):
        if array is None or not array:
            return None
        # end if
        assert_type_or_raise(array, dict, parameter_name="array")
        from pytgbot.api_types.sendable.payments import LabeledPrice

        data = {}
        data['id'] = u(array.get('id'))
        data['title'] = u(array.get('title'))
        data['prices'] = LabeledPrice.from_array_list(array.get('prices'), list_level=1)

        instance = ShippingOption(**data)
        instance._raw = array
        return instance

Response: Deserialize a new ShippingOption from a given dictionary.


Instruction:
Make a summary of the following Python 3 code
def _prepare_target(ts, tables, buffer_size):
    for tablename in tables:
        table = ts[tablename]
        table[:] = []
        if buffer_size is not None and table.is_attached():
            table.write(append=False)

Response: Prepare the target for processing.


Instruction:
Write a Python 3 function that can
normalize source rows and selectors.

Response:
def _prepare_source(selector, source):
    """Normalize source rows and selectors."""
    tablename, fields = get_data_specifier(selector)
    if len(fields) != 1:
        raise ItsdbError(
            'Selector must specify exactly one data column: {}'
            .format(selector)
        )
    if isinstance(source, TestSuite):
        if not tablename:
            tablename = source.relations.find(fields[0])[0]
        source = source[tablename]
    cols = list(source.fields.keys()) + fields
    return source, cols


Instruction:
Make a summary of the following Python 3 code
def _add_record(table, data, buffer_size):
    fields = table.fields
    # remove any keys that aren't relation fields
    for invalid_key in set(data).difference([f.name for f in fields]):
        del data[invalid_key]
    table.append(Record.from_dict(fields, data))
    # write if requested and possible
    if buffer_size is not None and table.is_attached():
        # for now there isn't a public method to get the number of new
        # records, so use private members
        if (len(table) - 1) - table._last_synced_index > buffer_size:
            table.commit()

Response: Prepare and append a Record into its Table ; flush to disk if necessary.


Instruction:
Can you implement a function in Python 3 that
returns a tuple of table and column names for some [ incr tsdb() ] data specifier.

Response:
def get_data_specifier(string):
    """
    Return a tuple (table, col) for some [incr tsdb()] data specifier.
    For example::

        item              -> ('item', None)
        item:i-input      -> ('item', ['i-input'])
        item:i-input@i-wf -> ('item', ['i-input', 'i-wf'])
        :i-input          -> (None, ['i-input'])
        (otherwise)       -> (None, None)
    """
    match = data_specifier_re.match(string)
    if match is None:
        return (None, None)
    table = match.group('table')
    if table is not None:
        table = table.strip()
    cols = _split_cols(match.group('cols'))
    return (table, cols)


Instruction:
Make a summary of the following Python 3 code
def decode_row(line, fields=None):
    cols = line.rstrip('\n').split(_field_delimiter)
    cols = list(map(unescape, cols))
    if fields is not None:
        if len(cols) != len(fields):
            raise ItsdbError(
                'Wrong number of fields: {} != {}'
                .format(len(cols), len(fields))
            )
        for i in range(len(cols)):
            col = cols[i]
            if col:
                field = fields[i]
                col = _cast_to_datatype(col, field)
            cols[i] = col
    return cols

Response: Decode a raw line from a profile into a list of column values.


Instruction:
Write a Python 3 function for
encoding a list of column values into a [ incr tsdb ) - encoded string.

Response:
def encode_row(fields):
    """
    Encode a list of column values into a [incr tsdb()] profile line.

    Encoding involves escaping special characters for each value, then
    joining the values into a single string with the field delimiter
    (`"@"` by default). It does not fill in default values (see
    make_row()).

    Args:
        fields: a list of column values
    Returns:
        A [incr tsdb()]-encoded string
    """
    # NOTE: str(f) only works for Python3
    unicode_fields = [unicode(f) for f in fields]
    escaped_fields = map(escape, unicode_fields)
    return _field_delimiter.join(escaped_fields)


Instruction:
Can you create a Python 3 function that
determines if the table path should end in. gz or not and return it.

Response:
def _table_filename(tbl_filename):
    """
    Determine if the table path should end in .gz or not and return it.

    A .gz path is preferred only if it exists and is newer than any
    regular text file path.

    Raises:
        :class:`delphin.exceptions.ItsdbError`: when neither the .gz
            nor text file exist.
    """
    tbl_filename = str(tbl_filename)  # convert any Path objects

    txfn = _normalize_table_path(tbl_filename)
    gzfn = txfn + '.gz'

    if os.path.exists(txfn):
        if (os.path.exists(gzfn) and
                os.stat(gzfn).st_mtime > os.stat(txfn).st_mtime):
            tbl_filename = gzfn
        else:
            tbl_filename = txfn
    elif os.path.exists(gzfn):
        tbl_filename = gzfn
    else:
        raise ItsdbError(
            'Table does not exist at {}(.gz)'
            .format(tbl_filename)
        )

    return tbl_filename


Instruction:
Given the following Python 3 function, write the documentation
def _open_table(tbl_filename, encoding):
    path = _table_filename(tbl_filename)
    if path.endswith('.gz'):
        # gzip.open() cannot use mode='rt' until Python2.7 support
        # is gone; until then use TextIOWrapper
        gzfile = GzipFile(path, mode='r')
        gzfile.read1 = gzfile.read  # Python2 hack
        with TextIOWrapper(gzfile, encoding=encoding) as f:
            yield f
    else:
        with io.open(path, encoding=encoding) as f:
            yield f

Response: Open the compressed or text table file.


Instruction:
Create a Python 3 function for
encoding a mapping of column names to values into a [ incr tsdb ) - encoded string.

Response:
def make_row(row, fields):
    """
    Encode a mapping of column name to values into a [incr tsdb()]
    profile line. The *fields* parameter determines what columns are
    used, and default values are provided if a column is missing from
    the mapping.

    Args:
        row: a mapping of column names to values
        fields: an iterable of :class:`Field` objects
    Returns:
        A [incr tsdb()]-encoded string
    """
    if not hasattr(row, 'get'):
        row = {f.name: col for f, col in zip(fields, row)}

    row_fields = []
    for f in fields:
        val = row.get(f.name, None)
        if val is None:
            val = str(f.default_value())
        row_fields.append(val)
    return encode_row(row_fields)


Instruction:
Explain what the following Python 3 code does
def select_rows(cols, rows, mode='list', cast=True):
    mode = mode.lower()
    if mode == 'list':
        modecast = lambda cols, data: data
    elif mode == 'dict':
        modecast = lambda cols, data: dict(zip(cols, data))
    elif mode == 'row':
        modecast = lambda cols, data: encode_row(data)
    else:
        raise ItsdbError('Invalid mode for select operation: {}\n'
                         '  Valid options include: list, dict, row'
                         .format(mode))
    for row in rows:
        try:
            data = [row.get(c, cast=cast) for c in cols]
        except TypeError:
            data = [row.get(c) for c in cols]
        yield modecast(cols, data)

Response: This function returns a generator that yields the selected data from rows.


Instruction:
Write a Python 3 function for
yielding triples of value left_rows right_rows where value left_rows and right_rows are lists of rows that share the same same MimeType column value for key.

Response:
def match_rows(rows1, rows2, key, sort_keys=True):
    """
    Yield triples of `(value, left_rows, right_rows)` where
    `left_rows` and `right_rows` are lists of rows that share the same
    column value for *key*. This means that both *rows1* and *rows2*
    must have a column with the same name *key*.

    .. warning::

       Both *rows1* and *rows2* will exist in memory for this
       operation, so it is not recommended for very large tables on
       low-memory systems.

    Args:
        rows1: a :class:`Table` or list of :class:`Record` objects
        rows2: a :class:`Table` or list of :class:`Record` objects
        key (str): the column name on which to match
        sort_keys (bool): if `True`, yield matching rows sorted by the
            matched key instead of the original order
    """
    matched = OrderedDict()
    for i, rows in enumerate([rows1, rows2]):
        for row in rows:
            val = row[key]
            try:
                data = matched[val]
            except KeyError:
                matched[val] = ([], [])
                data = matched[val]
            data[i].append(row)
    vals = matched.keys()
    if sort_keys:
        vals = sorted(vals, key=safe_int)
    for val in vals:
        left, right = matched[val]
        yield (val, left, right)


Instruction:
How would you code a function in Python 3 to
join two tables and returns the resulting Table object.

Response:
def join(table1, table2, on=None, how='inner', name=None):
    """
    Join two tables and return the resulting Table object.

    Fields in the resulting table have their names prefixed with their
    corresponding table name. For example, when joining `item` and
    `parse` tables, the `i-input` field of the `item` table will be
    named `item:i-input` in the resulting Table. Pivot fields (those
    in *on*) are only stored once without the prefix.

    Both inner and left joins are possible by setting the *how*
    parameter to `inner` and `left`, respectively.

    .. warning::

       Both *table2* and the resulting joined table will exist in
       memory for this operation, so it is not recommended for very
       large tables on low-memory systems.

    Args:
        table1 (:class:`Table`): the left table to join
        table2 (:class:`Table`): the right table to join
        on (str): the shared key to use for joining; if `None`, find
            shared keys using the schemata of the tables
        how (str): the method used for joining (`"inner"` or `"left"`)
        name (str): the name assigned to the resulting table
    """
    if how not in ('inner', 'left'):
        ItsdbError('Only \'inner\' and \'left\' join methods are allowed.')
    # validate and normalize the pivot
    on = _join_pivot(on, table1, table2)
    # the fields of the joined table
    fields = _RelationJoin(table1.fields, table2.fields, on=on)
    # get key mappings to the right side (useful for inner and left joins)
    get_key = lambda rec: tuple(rec.get(k) for k in on)
    key_indices = set(table2.fields.index(k) for k in on)
    right = defaultdict(list)
    for rec in table2:
        right[get_key(rec)].append([c for i, c in enumerate(rec)
                                    if i not in key_indices])
    # build joined table
    rfill = [f.default_value() for f in table2.fields if f.name not in on]
    joined = []
    for lrec in table1:
        k = get_key(lrec)
        if how == 'left' or k in right:
            joined.extend(lrec + rrec for rrec in right.get(k, [rfill]))

    return Table(fields, joined)


Instruction:
Can you implement a function in Python 3 that
returns the default value for a column.

Response:
def default_value(fieldname, datatype):
    """
    Return the default value for a column.

    If the column name (e.g. *i-wf*) is defined to have an idiosyncratic
    value, that value is returned. Otherwise the default value for the
    column's datatype is returned.

    Args:
        fieldname: the column name (e.g. `i-wf`)
        datatype: the datatype of the column (e.g. `:integer`)
    Returns:
        The default value for the column.

    .. deprecated:: v0.7.0
    """
    if fieldname in tsdb_coded_attributes:
        return str(tsdb_coded_attributes[fieldname])
    else:
        return _default_datatype_values.get(datatype, '')


Instruction:
Can you generate the documentation for the following Python 3 function
def make_skeleton(path, relations, item_rows, gzip=False):
    try:
        os.makedirs(path)
    except OSError:
        raise ItsdbError('Path already exists: {}.'.format(path))

    import shutil
    shutil.copyfile(relations, os.path.join(path, _relations_filename))
    prof = ItsdbProfile(path, index=False)
    prof.write_table('item', item_rows, gzip=gzip)
    return prof

Response:
Create a new profile skeleton from an existing relations file and a list of rows
    for the item table.


Instruction:
Write a Python 3 script to
yield rows matching all applicable filters.

Response:
def filter_rows(filters, rows):
    """
    Yield rows matching all applicable filters.

    Filter functions have binary arity (e.g. `filter(row, col)`) where
    the first parameter is the dictionary of row data, and the second
    parameter is the data at one particular column.

    Args:
        filters: a tuple of (cols, filter_func) where filter_func will
            be tested (filter_func(row, col)) for each col in cols where
            col exists in the row
        rows: an iterable of rows to filter
    Yields:
        Rows matching all applicable filters

    .. deprecated:: v0.7.0
    """
    for row in rows:
        if all(condition(row, row.get(col))
               for (cols, condition) in filters
               for col in cols
               if col is None or col in row):
            yield row


Instruction:
Make a summary of the following Python 3 code
def apply_rows(applicators, rows):
    for row in rows:
        for (cols, function) in applicators:
            for col in (cols or []):
                value = row.get(col, '')
                row[col] = function(row, value)
        yield row

Response: Yield rows after applying the applicator functions to each column of the rows.


Instruction:
Can you create a Python 3 function that
gets the default value of the field.

Response:
def default_value(self):
        """Get the default value of the field."""
        if self.name in tsdb_coded_attributes:
            return tsdb_coded_attributes[self.name]
        elif self.datatype == ':integer':
            return -1
        else:
            return ''


Instruction:
Make a summary of the following Python 3 code
def keys(self):
        keys = self._keys
        if keys is None:
            keys = tuple(self[i].name for i in self.key_indices)
        return keys

Response: Return the tuple of field names of key fields.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def from_file(cls, source):
        if hasattr(source, 'read'):
            relations = cls.from_string(source.read())
        else:
            with open(source) as f:
                relations = cls.from_string(f.read())
        return relations

Response: Instantiate Relations from a relations file.


Instruction:
Make a summary of the following Python 3 code
def from_string(cls, s):
        tables = []
        seen = set()
        current_table = None
        lines = list(reversed(s.splitlines()))  # to pop() in right order
        while lines:
            line = lines.pop().strip()
            table_m = re.match(r'^(?P<table>\w.+):$', line)
            field_m = re.match(r'\s*(?P<name>\S+)'
                               r'(\s+(?P<attrs>[^#]+))?'
                               r'(\s*#\s*(?P<comment>.*)$)?',
                               line)
            if table_m is not None:
                table_name = table_m.group('table')
                if table_name in seen:
                    raise ItsdbError(
                        'Table {} already defined.'.format(table_name)
                    )
                current_table = (table_name, [])
                tables.append(current_table)
                seen.add(table_name)
            elif field_m is not None and current_table is not None:
                name = field_m.group('name')
                attrs = field_m.group('attrs').split()
                datatype = attrs.pop(0)
                key = ':key' in attrs
                partial = ':partial' in attrs
                comment = field_m.group('comment')
                current_table[1].append(
                    Field(name, datatype, key, partial, comment)
                )
            elif line != '':
                raise ItsdbError('Invalid line: ' + line)
        return cls(tables)

Response: Instantiate Relations from a string.


Instruction:
Write a Python 3 function that can
return the list of tables that define the field fieldname.

Response:
def find(self, fieldname):
        """
        Return the list of tables that define the field *fieldname*.
        """
        tablename, _, column = fieldname.rpartition(':')
        if tablename and tablename in self._field_map[column]:
            return tablename
        else:
            return self._field_map[fieldname]


Instruction:
Explain what the following Python 3 code does
def path(self, source, target):
        visited = set(source.split('+'))  # split on + for joins
        targets = set(target.split('+')) - visited
        # ensure sources and targets exists
        for tablename in visited.union(targets):
            self[tablename]
        # base case; nothing to do
        if len(targets) == 0:
            return []
        paths = [[(tablename, None)] for tablename in visited]
        while True:
            newpaths = []
            for path in paths:
                laststep, pivot = path[-1]
                if laststep in targets:
                    return path[1:]
                else:
                    for key in self[laststep].keys():
                        for step in set(self.find(key)) - visited:
                            visited.add(step)
                            newpaths.append(path + [(step, key)])
            if newpaths:
                paths = newpaths
            else:
                break

        raise ItsdbError('no relation path found from {} to {}'
                         .format(source, target))

Response: Find the path of id fields connecting two tables.


Instruction:
Create a Python 3 function to
create a Record bound to a table.

Response:
def _make(cls, fields, iterable, table, rowid):
        """
        Create a Record bound to a :class:`Table`.

        This is a helper method for creating Records from rows of a
        Table that is attached to a file. It is not meant to be called
        directly. It specifies the row number and a weak reference to
        the Table object so that when the Record is modified it is
        kept in the Table's in-memory list (see Record.__setitem__()),
        otherwise the changes would not be retained the next time the
        record is requested from the Table. The use of a weak
        reference to the Table is to avoid a circular reference and
        thus allow it to be properly garbage collected.
        """
        record = cls(fields, iterable)
        record._tableref = weakref.ref(table)
        record._rowid = rowid
        return record


Instruction:
Can you create a Python 3 function that
creates a Record object from a dictionary of field names to column values.

Response:
def from_dict(cls, fields, mapping):
        """
        Create a Record from a dictionary of field mappings.

        The *fields* object is used to determine the column indices
        of fields in the mapping.

        Args:
            fields: the Relation schema for the table of this record
            mapping: a dictionary or other mapping from field names to
                column values
        Returns:
            a :class:`Record` object
        """
        iterable = [None] * len(fields)
        for key, value in mapping.items():
            try:
                index = fields.index(key)
            except KeyError:
                raise ItsdbError('Invalid field name(s): ' + key)
            iterable[index] = value
        return cls(fields, iterable)


Instruction:
Write a Python 3 script for
returning the value of the field with the given key.

Response:
def get(self, key, default=None, cast=True):
        """
        Return the field data given by field name *key*.

        Args:
            key: the field name of the data to return
            default: the value to return if *key* is not in the row
        """
        tablename, _, key = key.rpartition(':')
        if tablename and tablename not in self.fields.name.split('+'):
            raise ItsdbError('column requested from wrong table: {}'
                             .format(tablename))
        try:
            index = self.fields.index(key)
            value = list.__getitem__(self, index)
        except (KeyError, IndexError):
            value = default
        else:
            if cast:
                field = self.fields[index]
                value = _cast_to_datatype(value, field)
        return value


Instruction:
Can you generate the documentation for the following Python 3 function
def write(self, records=None, path=None, fields=None, append=False,
              gzip=None):
        """
        Write the table to disk.

        The basic usage has no arguments and writes the table's data
        to the attached file. The parameters accommodate a variety of
        use cases, such as using *fields* to refresh a table to a
        new schema or *records* and *append* to incrementally build a
        table.

        Args:
            records: an iterable of :class:`Record` objects to write;
                if `None` the table's existing data is used
            path: the destination file path; if `None` use the
                path of the file attached to the table
            fields (:class:`Relation`): table schema to use for
                writing, otherwise use the current one
            append: if `True`, append rather than overwrite
            gzip: compress with gzip if non-empty
        Examples:
            >>> table.write()
            >>> table.write(results, path='new/path/result')
        """
        if path is None:
            if not self.is_attached():
                raise ItsdbError('no path given for detached table')
            else:
                path = self.path
        path = _normalize_table_path(path)
        dirpath, name = os.path.split(path)
        if fields is None:
            fields = self.fields
        if records is None:
            records = iter(self)
        _write_table(
            dirpath,
            name,
            records,
            fields,
            append=append,
            gzip=gzip,
            encoding=self.encoding)

        if self.is_attached() and path == _normalize_table_path(self.path):
            self.path = _table_filename(path)
            self._sync_with_file()

Response: Writes the table to disk.


Instruction:
Write a Python 3 script for
committing changes to disk if attached.

Response:
def commit(self):
        """
        Commit changes to disk if attached.

        This method helps normalize the interface for detached and
        attached tables and makes writing attached tables a bit more
        efficient. For detached tables nothing is done, as there is no
        notion of changes, but neither is an error raised (unlike with
        :meth:`write`). For attached tables, if all changes are new
        records, the changes are appended to the existing file, and
        otherwise the whole file is rewritten.
        """
        if not self.is_attached():
            return
        changes = self.list_changes()
        if changes:
            indices, records = zip(*changes)
            if min(indices) > self._last_synced_index:
                self.write(records, append=True)
            else:
                self.write(append=False)


Instruction:
Implement a Python 3 function for
attaching the table to the file at path.

Response:
def attach(self, path, encoding='utf-8'):
        """
        Attach the Table to the file at *path*.

        Attaching a table to a file means that only changed records
        are stored in memory, which greatly reduces the memory
        footprint of large profiles at some cost of
        performance. Tables created from :meth:`Table.from_file()` or
        from an attached :class:`TestSuite` are automatically
        attached. Attaching a file does not immediately flush the
        contents to disk; after attaching the table must be separately
        written to commit the in-memory data.

        A non-empty table will fail to attach to a non-empty file to
        avoid data loss when merging the contents. In this case, you
        may delete or clear the file, clear the table, or attach to
        another file.

        Args:
            path: the path to the table file
            encoding: the character encoding of the files in the testsuite
        """
        if self.is_attached():
            raise ItsdbError('already attached at {}'.format(self.path))

        try:
            path = _table_filename(path)
        except ItsdbError:
            # neither path nor path.gz exist; create new empty file
            # (note: if the file were non-empty this would be destructive)
            path = _normalize_table_path(path)
            open(path, 'w').close()
        else:
            # path or path.gz exists; check if merging would be a problem
            if os.stat(path).st_size > 0 and len(self._records) > 0:
                raise ItsdbError(
                    'cannot attach non-empty table to non-empty file')

        self.path = path
        self.encoding = encoding

        # if _records is not empty then we're attaching to an empty file
        if len(self._records) == 0:
            self._sync_with_file()


Instruction:
Can you write a function in Python 3 where it
detaches the table from a file.

Response:
def detach(self):
        """
        Detach the table from a file.

        Detaching a table reads all data from the file and places it
        in memory. This is useful when constructing or significantly
        manipulating table data, or when more speed is needed. Tables
        created by the default constructor are detached.

        When detaching, only unmodified records are loaded from the
        file; any uncommited changes in the Table are left as-is.

        .. warning::

           Very large tables may consume all available RAM when
           detached.  Expect the in-memory table to take up about
           twice the space of an uncompressed table on disk, although
           this may vary by system.
        """
        if not self.is_attached():
            raise ItsdbError('already detached')
        records = self._records
        for i, line in self._enum_lines():
            if records[i] is None:
                # check number of columns?
                records[i] = tuple(decode_row(line))
        self.path = None
        self.encoding = None


Instruction:
Can you tell what is the following Python 3 function doing
def list_changes(self):
        if not self.is_attached():
            raise ItsdbError('changes are not tracked for detached tables.')
        return [(i, self[i]) for i, row in enumerate(self._records)
                if row is not None]

Response: Return a list of modified records. This is only applicable for attached tables.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _sync_with_file(self):
        self._records = []
        i = -1
        for i, line in self._enum_lines():
            self._records.append(None)
        self._last_synced_index = i

Response: Clear in - memory structures so table is synced with the file.


Instruction:
Make a summary of the following Python 3 code
def _enum_lines(self):
        with _open_table(self.path, self.encoding) as lines:
            for i, line in enumerate(lines):
                yield i, line

Response: Enumerate lines from the attached file.


Instruction:
How would you explain what the following Python 3 function does
def _enum_attached_rows(self, indices):
        records = self._records
        i = 0
        # first rows covered by the file
        for i, line in self._enum_lines():
            if i in indices:
                row = records[i]
                if row is None:
                    row = decode_row(line)
                yield (i, row)
        # then any uncommitted rows
        for j in range(i, len(records)):
            if j in indices:
                if records[j] is not None:
                    yield (j, records[j])

Response: Enumerate the on - disk and in - memory records.


Instruction:
Create a Python 3 function for
yielding records from a slice index.

Response:
def _iterslice(self, slice):
        """Yield records from a slice index."""
        indices = range(*slice.indices(len(self._records)))
        if self.is_attached():
            rows = self._enum_attached_rows(indices)
            if slice.step is not None and slice.step < 0:
                rows = reversed(list(rows))
        else:
            rows = zip(indices, self._records[slice])

        fields = self.fields
        for i, row in rows:
            yield Record._make(fields, row, self, i)


Instruction:
How would you code a function in Python 3 to
get a single non - slice index.

Response:
def _getitem(self, index):
        """Get a single non-slice index."""
        row = self._records[index]
        if row is not None:
            pass
        elif self.is_attached():
            # need to handle negative indices manually
            if index < 0:
                index = len(self._records) + index
            row = next((decode_row(line)
                        for i, line in self._enum_lines()
                        if i == index),
                       None)
            if row is None:
                raise ItsdbError('could not retrieve row in attached table')
        else:
            raise ItsdbError('invalid row in detached table: {}'.format(index))

        return Record._make(self.fields, row, self, index)


Instruction:
Write a Python 3 script for
adding each record in records to the end of the table.

Response:
def extend(self, records):
        """
        Add each record in *records* to the end of the table.

        Args:
            record: an iterable of :class:`Record` or other iterables
                containing column values
        """
        fields = self.fields
        for record in records:
            record = _cast_record_to_str_tuple(record, fields)
            self._records.append(record)


Instruction:
Implement a Python 3 function for
selecting columns from each row in the table.

Response:
def select(self, cols, mode='list'):
        """
        Select columns from each row in the table.

        See :func:`select_rows` for a description of how to use the
        *mode* parameter.

        Args:
            cols: an iterable of Field (column) names
            mode: how to return the data
        """
        if isinstance(cols, stringtypes):
            cols = _split_cols(cols)
        if not cols:
            cols = [f.name for f in self.fields]
        return select_rows(cols, self, mode=mode)


Instruction:
Can you tell what is the following Python 3 function doing
def add_filter(self, table, cols, condition):
        if table is not None and table not in self.relations:
            raise ItsdbError('Cannot add filter; table "{}" is not defined '
                             'by the relations file.'
                             .format(table))
        # this is a hack, though perhaps well-motivated
        if cols is None:
            cols = [None]
        self.filters[table].append((cols, condition))

Response: Add a filter to the list of filters for the given table and columns.


Instruction:
Write a Python 3 function for
adding an applicator to the internal list of related tables.

Response:
def add_applicator(self, table, cols, function):
        """
        Add an applicator. When reading *table*, rows in *table* will be
        modified by apply_rows().

        Args:
            table: The table to apply the function to.
            cols: The columns in *table* to apply the function on.
            function: The applicator function.
        """

        if table not in self.relations:
            raise ItsdbError('Cannot add applicator; table "{}" is not '
                             'defined by the relations file.'
                             .format(table))
        if cols is None:
            raise ItsdbError('Cannot add applicator; columns not specified.')
        fields = set(f.name for f in self.relations[table])
        for col in cols:
            if col not in fields:
                raise ItsdbError('Cannot add applicator; column "{}" not '
                                 'defined by the relations file.'
                                 .format(col))
        self.applicators[table].append((cols, function))


Instruction:
Write a Python 3 script for
yielding the rows in the [ incr tsdb() *table. A row is a dictionary mapping column names to values.

Response:
def read_raw_table(self, table):
        """
        Yield rows in the [incr tsdb()] *table*. A row is a dictionary
        mapping column names to values. Data from a profile is decoded
        by decode_row(). No filters or applicators are used.
        """
        fields = self.table_relations(table) if self.cast else None
        field_names = [f.name for f in self.table_relations(table)]
        field_len = len(field_names)
        table_path = os.path.join(self.root, table)
        with _open_table(table_path, self.encoding) as tbl:
            for line in tbl:
                cols = decode_row(line, fields=fields)
                if len(cols) != field_len:
                    # should this throw an exception instead?
                    logging.error('Number of stored fields ({}) '
                                  'differ from the expected number({}); '
                                  'fields may be misaligned!'
                                  .format(len(cols), field_len))
                row = OrderedDict(zip(field_names, cols))
                yield row


Instruction:
Create a Python 3 function for
yielding rows in the [ incr tsdb () * table * that pass any defined filters and apply_rows to each row.

Response:
def read_table(self, table, key_filter=True):
        """
        Yield rows in the [incr tsdb()] *table* that pass any defined
        filters, and with values changed by any applicators. If no
        filters or applicators are defined, the result is the same as
        from ItsdbProfile.read_raw_table().
        """
        filters = self.filters[None] + self.filters[table]
        if key_filter:
            for f in self.relations[table]:
                key = f.name
                if f.key and (self._index.get(key) is not None):
                    ids = self._index[key]
                    # Can't keep local variables (like ids) in the scope of
                    # the lambda expression, so make it a default argument.
                    # Source: http://stackoverflow.com/a/938493/1441112
                    function = lambda r, x, ids=ids: x in ids
                    filters.append(([key], function))
        applicators = self.applicators[table]
        rows = self.read_raw_table(table)
        return filter_rows(filters, apply_rows(applicators, rows))


Instruction:
Write a Python 3 script to
yield rows from table.

Response:
def select(self, table, cols, mode='list', key_filter=True):
        """
        Yield selected rows from *table*. This method just calls
        select_rows() on the rows read from *table*.
        """
        if cols is None:
            cols = [c.name for c in self.relations[table]]
        rows = self.read_table(table, key_filter=key_filter)
        for row in select_rows(cols, rows, mode=mode):
            yield row


Instruction:
Can you tell what is the following Python 3 function doing
def join(self, table1, table2, key_filter=True):
        get_keys = lambda t: (f.name for f in self.relations[t] if f.key)
        keys = set(get_keys(table1)).intersection(get_keys(table2))
        if not keys:
            raise ItsdbError(
                'Cannot join tables "{}" and "{}"; no shared key exists.'
                .format(table1, table2)
            )
        key = keys.pop()
        # this join method stores the whole of table2 in memory, but it is
        # MUCH faster than a nested loop method. Most profiles will fit in
        # memory anyway, so it's a decent tradeoff
        table2_data = defaultdict(list)
        for row in self.read_table(table2, key_filter=key_filter):
            table2_data[row[key]].append(row)
        for row1 in self.read_table(table1, key_filter=key_filter):
            for row2 in table2_data.get(row1[key], []):
                joinedrow = OrderedDict(
                    [('{}:{}'.format(table1, k), v)
                     for k, v in row1.items()] +
                    [('{}:{}'.format(table2, k), v)
                     for k, v in row2.items()]
                )
                yield joinedrow

Response: Yields rows from a table built by joining tables table1 and table2.


Instruction:
Here you have a function in Python 3, explain what it does
def write_table(self, table, rows, append=False, gzip=False):
        _write_table(self.root,
                     table,
                     rows,
                     self.table_relations(table),
                     append=append,
                     gzip=gzip,
                     encoding=self.encoding)

Response: Encode and write out a table to the profile directory.


Instruction:
Can you tell what is the following Python 3 function doing
def write_profile(self, profile_directory, relations_filename=None,
                      key_filter=True,
                      append=False, gzip=None):
        """
        Write all tables (as specified by the relations) to a profile.

        Args:
            profile_directory: The directory of the output profile
            relations_filename: If given, read and use the relations
                at this path instead of the current profile's
                relations
            key_filter: If True, filter the rows by keys in the index
            append: If `True`, append profile data to existing tables
                in the output profile directory
            gzip: If `True`, compress tables using `gzip`. Table
                filenames will have `.gz` appended. If `False`, only
                write out text files. If `None`, use whatever the
                original file was.
        """
        if relations_filename:
            src_rels = os.path.abspath(relations_filename)
            relations = get_relations(relations_filename)
        else:
            src_rels = os.path.abspath(os.path.join(self.root,
                                                    _relations_filename))
            relations = self.relations

        tgt_rels = os.path.abspath(os.path.join(profile_directory,
                                                _relations_filename))
        if not (os.path.isfile(tgt_rels) and src_rels == tgt_rels):
            with open(tgt_rels, 'w') as rel_fh:
                print(open(src_rels).read(), file=rel_fh)

        tables = self._tables
        if tables is not None:
            tables = set(tables)
        for table, fields in relations.items():
            if tables is not None and table not in tables:
                continue
            try:
                fn = _table_filename(os.path.join(self.root, table))
                _gzip = gzip if gzip is not None else fn.endswith('.gz')
                rows = list(self.read_table(table, key_filter=key_filter))
                _write_table(
                    profile_directory, table, rows, fields,
                    append=append, gzip=_gzip, encoding=self.encoding
                )
            except ItsdbError:
                logging.warning(
                    'Could not write "{}"; table doesn\'t exist.'.format(table)
                )
                continue

        self._cleanup(gzip=gzip)

Response: Write all tables in the current profile to a profile.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def exists(self, table=None):
        if not os.path.isdir(self.root):
            return False
        if not os.path.isfile(os.path.join(self.root, _relations_filename)):
            return False
        if table is not None:
            try:
                _table_filename(os.path.join(self.root, table))
            except ItsdbError:
                return False
        return True

Response: Returns True if the profile or a table exist.


Instruction:
Can you create a Python 3 function that
returns the size in bytes of the profile or table.

Response:
def size(self, table=None):
        """
        Return the size, in bytes, of the profile or *table*.

        If *table* is `None`, this function returns the size of the
        whole profile (i.e. the sum of the table sizes). Otherwise, it
        returns the size of *table*.

        Note: if the file is gzipped, it returns the compressed size.
        """
        size = 0
        if table is None:
            for table in self.relations:
                size += self.size(table)
        else:
            try:
                fn = _table_filename(os.path.join(self.root, table))
                size += os.stat(fn).st_size
            except ItsdbError:
                pass
        return size


Instruction:
Create a Python 3 function for
requesting a parse of input on server and return the response.

Response:
def parse(input, server=default_erg_server, params=None, headers=None):
    """
    Request a parse of *input* on *server* and return the response.

    Args:
        input (str): sentence to be parsed
        server (str): the url for the server (the default LOGON server
            is used by default)
        params (dict): a dictionary of request parameters
        headers (dict): a dictionary of additional request headers
    Returns:
        A ParseResponse containing the results, if the request was
        successful.
    Raises:
        requests.HTTPError: if the status code was not 200
    """
    return next(parse_from_iterable([input], server, params, headers), None)


Instruction:
Make a summary of the following Python 3 code
def parse_from_iterable(
        inputs,
        server=default_erg_server,
        params=None,
        headers=None):
    """
    Request parses for all *inputs*.

    Args:
        inputs (iterable): sentences to parse
        server (str): the url for the server (the default LOGON server
            is used by default)
        params (dict): a dictionary of request parameters
        headers (dict): a dictionary of additional request headers
    Yields:
        ParseResponse objects for each successful response.
    Raises:
        requests.HTTPError: for the first response with a status code
            that is not 200
    """
    client = DelphinRestClient(server)
    for input in inputs:
        yield client.parse(input, params=params, headers=headers)

Response: This function parses the input sentences into a list of ParseResponse objects.


Instruction:
Explain what the following Python 3 code does
def parse(self, sentence, params=None, headers=None):
        if params is None:
            params = {}
        params['input'] = sentence

        hdrs = {'Accept': 'application/json'}
        if headers is not None:
            hdrs.update(headers)

        url = urljoin(self.server, 'parse')
        r = requests.get(url, params=params, headers=hdrs)
        if r.status_code == 200:
            return _RestResponse(r.json())
        else:
            r.raise_for_status()

Response: Request a parse of a sentence and return the response.


Instruction:
Can you tell what is the following Python 3 function doing
def _calculate_crc_ccitt(data):
    global CRC_CCITT_TABLE
    if not CRC_CCITT_TABLE:
        crc_ccitt_table = []
        for i in range(0, 256):
            crc = 0
            c = i << 8

            for j in range(0, 8):
                if (crc ^ c) & 0x8000:
                    crc = c_ushort(crc << 1).value ^ 0x1021
                else:
                    crc = c_ushort(crc << 1).value

                c = c_ushort(c << 1).value

            crc_ccitt_table.append(crc)
            CRC_CCITT_TABLE = crc_ccitt_table

    is_string = _is_string(data)
    crc_value = 0x0000  # XModem version

    for c in data:
        d = ord(c) if is_string else c
        tmp = ((crc_value >> 8) & 0xff) ^ d
        crc_value = ((crc_value << 8) & 0xff00) ^ CRC_CCITT_TABLE[tmp]

    return crc_value

Response: Calculate the CRC value of a single object.


Instruction:
Given the following Python 3 function, write the documentation
def to_zpl_line(self, compression=3, **kwargs):
        if compression == 3:
            data = base64.b64encode(zlib.compress(self.data.bytes))
            data = ':Z64:%s:%s' % (data.decode('ascii'), self._calc_crc(data))
        elif compression == 1:
            data = base64.b64encode(self.data.bytes)
            data = ':B64:%s:%s' % (data.decode('ascii'), self._calc_crc(data))
        else:
            lines = []
            last_unique_line = None

            for line in self.data.hex_rows:
                if line.endswith('00'):
                    line = line.rstrip('0')
                    if len(line) % 2:
                        line += '0'
                    line += ','
                if line == last_unique_line:
                    line = ':'
                else:
                    last_unique_line = line
                lines.append(line)

            data = '\n'.join(lines)
            to_compress = set(RE_UNCOMPRESSED.findall(data))
            to_compress = sorted(to_compress, reverse=True)
            for uncompressed in to_compress:
                uncompressed = uncompressed[0]
                repeat = len(uncompressed)
                compressed = ''
                while repeat >= 400:
                    compressed += 'z'
                    repeat -= 400
                if repeat >= 20:
                    value = repeat // 20
                    repeat -= value * 20
                    compressed += chr(value + 70).lower()
                if repeat > 0:
                    compressed += chr(repeat + 70)
                data = data.replace(uncompressed, compressed + uncompressed[0])

            data = data.replace('\n', '')

        zpl = '~DGR:%s.GRF,%s,%s,%s' % (
            self.filename,
            self.data.filesize,
            self.data.width // 8,
            data
        )

        return zpl

Response: Convert the data to a ZPL line.


Instruction:
Can you write a function in Python 3 where it
returns the ZPL representation of the current stateful version of the image.

Response:
def to_zpl(
        self, quantity=1, pause_and_cut=0, override_pause=False,
        print_mode='C', print_orientation='N', media_tracking='Y', **kwargs
    ):
        """
        The most basic ZPL to print the GRF. Since ZPL printers are stateful
        this may not work and you may need to build your own.
        """
        zpl = [
            self.to_zpl_line(**kwargs),  # Download image to printer
            '^XA',  # Start Label Format
            '^MM%s,Y' % print_mode,
            '^PO%s' % print_orientation,
            '^MN%s' % media_tracking,
            '^FO0,0',  # Field Origin to 0,0
            '^XGR:%s.GRF,1,1' % self.filename,  # Draw image
            '^FS',  # Field Separator
            '^PQ%s,%s,0,%s' % (
                int(quantity),  # Print Quantity
                int(pause_and_cut),  # Pause and cut every N labels
                'Y' if override_pause else 'N'  # Don't pause between cuts
            ),
            '^XZ',  # End Label Format
            '^IDR:%s.GRF' % self.filename  # Delete image from printer
        ]
        return ''.join(zpl)


Instruction:
Here you have a function in Python 3, explain what it does
def from_image(cls, image, filename):

        source = Image.open(BytesIO(image))
        source = source.convert('1')
        width = int(math.ceil(source.size[0] / 8.0))

        data = []
        for line in _chunked(list(source.getdata()), source.size[0]):
            row = ''.join(['0' if p else '1' for p in line])
            row = row.ljust(width * 8, '0')
            data.append(row)
        data = GRFData(width, bin=''.join(data))

        return cls(filename, data)

Response: Create a GRF from an image.