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.receivable.peer import User

        data = {}
        data['id'] = u(array.get('id'))
        data['from_peer'] = User.from_array(array.get('from'))
        data['invoice_payload'] = u(array.get('invoice_payload'))
        data['shipping_address'] = ShippingAddress.from_array(array.get('shipping_address'))
        data['_raw'] = array
        return ShippingQuery(**data)

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


Instruction:
Can you write a function in Python 3 where it
serializes this PreCheckoutQuery to a dictionary.

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

        :return: dictionary representation of this object.
        :rtype: dict
        """
        array = super(PreCheckoutQuery, self).to_array()
        array['id'] = u(self.id)  # py2: type unicode, py3: type str
        array['from'] = self.from_peer.to_array()  # type User
        array['currency'] = u(self.currency)  # py2: type unicode, py3: type str
        array['total_amount'] = int(self.total_amount)  # type int
        array['invoice_payload'] = u(self.invoice_payload)  # py2: type unicode, py3: type str
        if self.shipping_option_id is not None:
            array['shipping_option_id'] = u(self.shipping_option_id)  # py2: type unicode, py3: type str
        if self.order_info is not None:
            array['order_info'] = self.order_info.to_array()  # type OrderInfo
        return array


Instruction:
Here you have a function in Python 3, explain what it 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.receivable.peer import User

        data = {}
        data['id'] = u(array.get('id'))
        data['from_peer'] = User.from_array(array.get('from'))
        data['currency'] = u(array.get('currency'))
        data['total_amount'] = int(array.get('total_amount'))
        data['invoice_payload'] = u(array.get('invoice_payload'))
        data['shipping_option_id'] = u(array.get('shipping_option_id')) if array.get('shipping_option_id') is not None else None
        data['order_info'] = OrderInfo.from_array(array.get('order_info')) if array.get('order_info') is not None else None
        data['_raw'] = array
        return PreCheckoutQuery(**data)

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


Instruction:
Can you generate a brief explanation for the following Python 3 code
def to_array(self):
        array = super(InputMediaPhoto, self).to_array()
        array['type'] = u(self.type)  # py2: type unicode, py3: type str

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

        if self.caption is not None:
            array['caption'] = u(self.caption)  # py2: type unicode, py3: type str

        if self.parse_mode is not None:
            array['parse_mode'] = u(self.parse_mode)  # py2: type unicode, py3: type str

        return array

Response: Serializes this InputMediaPhoto to a dictionary.


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

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

        if self.thumb is not None:
            if isinstance(self.thumb, InputFile):
                array['thumb'] = self.thumb.to_array()  # type InputFile
            elif isinstance(self.thumb, str):
                array['thumb'] = u(self.thumb)  # py2: type unicode, py3: type str
            else:
                raise TypeError('Unknown type, must be one of InputFile, str.')
            # end if

        if self.caption is not None:
            array['caption'] = u(self.caption)  # py2: type unicode, py3: type str

        if self.parse_mode is not None:
            array['parse_mode'] = u(self.parse_mode)  # py2: type unicode, py3: type str

        if self.width is not None:
            array['width'] = int(self.width)  # type int
        if self.height is not None:
            array['height'] = int(self.height)  # type int
        if self.duration is not None:
            array['duration'] = int(self.duration)  # type int
        return array

Response: Serializes this InputMediaAnimation to a dictionary.


Instruction:
Given the following Python 3 function, write the documentation
def to_array(self):
        array = super(InputMediaAudio, self).to_array()
        array['type'] = u(self.type)  # py2: type unicode, py3: type str

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

        if self.thumb is not None:
            if isinstance(self.thumb, InputFile):
                array['thumb'] = self.thumb.to_array()  # type InputFile
            elif isinstance(self.thumb, str):
                array['thumb'] = u(self.thumb)  # py2: type unicode, py3: type str
            else:
                raise TypeError('Unknown type, must be one of InputFile, str.')
            # end if

        if self.caption is not None:
            array['caption'] = u(self.caption)  # py2: type unicode, py3: type str

        if self.parse_mode is not None:
            array['parse_mode'] = u(self.parse_mode)  # py2: type unicode, py3: type str

        if self.duration is not None:
            array['duration'] = int(self.duration)  # type int
        if self.performer is not None:
            array['performer'] = u(self.performer)  # py2: type unicode, py3: type str

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

        return array

Response: Serializes this InputMediaAudio to a dictionary.


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

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

        if self.thumb is not None:
            if isinstance(self.thumb, InputFile):
                array['thumb'] = self.thumb.to_array()  # type InputFile
            elif isinstance(self.thumb, str):
                array['thumb'] = u(self.thumb)  # py2: type unicode, py3: type str
            else:
                raise TypeError('Unknown type, must be one of InputFile, str.')
            # end if

        if self.caption is not None:
            array['caption'] = u(self.caption)  # py2: type unicode, py3: type str

        if self.parse_mode is not None:
            array['parse_mode'] = u(self.parse_mode)  # py2: type unicode, py3: type str

        return array

Response: Serializes this InputMediaDocument to a dictionary.


Instruction:
Can you create a Python 3 function that
serializes Xmrs objects to the Prolog representation and write to a file.

Response:
def dump(destination, ms, single=False, pretty_print=False, **kwargs):
    """
    Serialize Xmrs objects to the Prolog representation and write to a file.

    Args:
        destination: filename or file object where data will be written
        ms: an iterator of Xmrs objects to serialize (unless the
            *single* option is `True`)
        single: if `True`, treat *ms* as a single Xmrs object
            instead of as an iterator
        pretty_print: if `True`, add newlines and indentation
    """
    text = dumps(ms,
                 single=single,
                 pretty_print=pretty_print,
                 **kwargs)

    if hasattr(destination, 'write'):
        print(text, file=destination)
    else:
        with open(destination, 'w') as fh:
            print(text, file=fh)


Instruction:
Write a Python 3 script to
serialize an Xmrs object to the Prolog representation

Response:
def dumps(ms, single=False, pretty_print=False, **kwargs):
    """
    Serialize an Xmrs object to the Prolog representation

    Args:
        ms: an iterator of Xmrs objects to serialize (unless the
            *single* option is `True`)
        single: if `True`, treat *ms* as a single Xmrs object instead
            of as an iterator
        pretty_print: if `True`, add newlines and indentation
    Returns:
        the Prolog string representation of a corpus of Xmrs
    """
    if single:
        ms = [ms]
    return serialize(ms, pretty_print=pretty_print, **kwargs)


Instruction:
How would you code a function in Python 3 to
read a variable - property mapping from source and return the VPM instance.

Response:
def load(source, semi=None):
    """
    Read a variable-property mapping from *source* and return the VPM.

    Args:
        source: a filename or file-like object containing the VPM
            definitions
        semi (:class:`~delphin.mrs.semi.SemI`, optional): if provided,
            it is passed to the VPM constructor
    Returns:
        a :class:`VPM` instance
    """
    if hasattr(source, 'read'):
        return _load(source, semi)
    else:
        with open(source, 'r') as fh:
            return _load(fh, semi)


Instruction:
Make a summary of the following Python 3 code
def _valmatch(vs, ss, op, varsort, semi, section):
    if op in _EQUAL_OPS or semi is None:
        return all(
            s == v or  # value equality
            (s == '*' and v is not None) or  # non-null wildcard
            (
                v is None and (  # value is null (any or with matching varsort)
                    s == '!' or
                    (s[0], s[-1], s[1:-1]) == ('[', ']', varsort)
                )
            )
            for v, s in zip(vs, ss)
        )
    else:
        pass

Response: Return True if every value in vs and ss matches the given condition.


Instruction:
Can you tell what is the following Python 3 function doing
def apply(self, var, props, reverse=False):
        vs, vid = sort_vid_split(var)
        if reverse:
            # variable type mapping is disabled in reverse
            # tms = [(b, op, a) for a, op, b in self._typemap if op in _RL_OPS]
            tms = []
        else:
            tms = [(a, op, b) for a, op, b in self._typemap if op in _LR_OPS]
        for src, op, tgt in tms:
            if _valmatch([vs], src, op, None, self._semi, 'variables'):
                vs = vs if tgt == ['*'] else tgt[0]
                break
        newvar = '{}{}'.format(vs, vid)

        newprops = {}
        for featsets, valmap in self._propmap:
            if reverse:
                tgtfeats, srcfeats = featsets
                pms = [(b, op, a) for a, op, b in valmap if op in _RL_OPS]
            else:
                srcfeats, tgtfeats = featsets
                pms = [(a, op, b) for a, op, b in valmap if op in _LR_OPS]
            vals = [props.get(f) for f in srcfeats]
            for srcvals, op, tgtvals in pms:
                if _valmatch(vals, srcvals, op, vs, self._semi, 'properties'):
                    for i, featval in enumerate(zip(tgtfeats, tgtvals)):
                        k, v = featval
                        if v == '*':
                            print(i, len(vals), vals, k, v)
                            if i < len(vals) and vals[i] is not None:
                                newprops[k] = vals[i]
                        elif v != '!':
                            newprops[k] = v
                    break

        return newvar, newprops

Response: Applies the VPM to a variable and properties.


Instruction:
Given the following Python 3 function, write the documentation
def convert(path, source_fmt, target_fmt, select='result:mrs',
            properties=True, show_status=False, predicate_modifiers=False,
            color=False, pretty_print=False, indent=None):
    """
    Convert between various DELPH-IN Semantics representations.

    Args:
        path (str, file): filename, testsuite directory, open file, or
            stream of input representations
        source_fmt (str): convert from this format
        target_fmt (str): convert to this format
        select (str): TSQL query for selecting data (ignored if *path*
            is not a testsuite directory; default: `"result:mrs"`)
        properties (bool): include morphosemantic properties if `True`
            (default: `True`)
        show_status (bool): show disconnected EDS nodes (ignored if
            *target_fmt* is not `"eds"`; default: `False`)
        predicate_modifiers (bool): apply EDS predicate modification
            for certain kinds of patterns (ignored if *target_fmt* is
            not an EDS format; default: `False`)
        color (bool): apply syntax highlighting if `True` and
            *target_fmt* is `"simplemrs"` (default: `False`)
        pretty_print (bool): if `True`, format the output with
            newlines and default indentation (default: `False`)
        indent (int, optional): specifies an explicit number of spaces
            for indentation (implies *pretty_print*)
    Returns:
        str: the converted representation
    """
    if source_fmt.startswith('eds') and not target_fmt.startswith('eds'):
        raise ValueError(
            'Conversion from EDS to non-EDS currently not supported.')

    if indent:
        pretty_print = True
        indent = 4 if indent is True else safe_int(indent)

    if len(tsql.inspect_query('select ' + select)['projection']) != 1:
        raise ValueError('Exactly 1 column must be given in selection query: '
                         '(e.g., result:mrs)')

    # read
    loads = _get_codec(source_fmt)
    if path is None:
        xs = loads(sys.stdin.read())
    elif hasattr(path, 'read'):
        xs = loads(path.read())
    elif os.path.isdir(path):
        ts = itsdb.TestSuite(path)
        xs = [
            next(iter(loads(r[0])), None)
            for r in tsql.select(select, ts)
        ]
    else:
        xs = loads(open(path, 'r').read())

    # write
    dumps = _get_codec(target_fmt, load=False)
    kwargs = {}
    if color: kwargs['color'] = color
    if pretty_print: kwargs['pretty_print'] = pretty_print
    if indent: kwargs['indent'] = indent
    if target_fmt == 'eds':
        kwargs['pretty_print'] = pretty_print
        kwargs['show_status'] = show_status
    if target_fmt.startswith('eds'):
        kwargs['predicate_modifiers'] = predicate_modifiers
    kwargs['properties'] = properties

    # this is not a great way to improve robustness when converting
    # many representations, but it'll do until v1.0.0. Also, it only
    # improves robustness on the output, not the input.
    # Note that all the code below is to replace the following:
    #     return dumps(xs, **kwargs)
    head, joiner, tail = _get_output_details(target_fmt)
    parts = []
    if pretty_print:
        joiner = joiner.strip() + '\n'
    def _trim(s):
        if head and s.startswith(head):
            s = s[len(head):].lstrip('\n')
        if tail and s.endswith(tail):
            s = s[:-len(tail)].rstrip('\n')
        return s
    for x in xs:
        try:
            s = dumps([x], **kwargs)
        except (PyDelphinException, KeyError, IndexError):
            logging.exception('could not convert representation')
        else:
            s = _trim(s)
            parts.append(s)
    # set these after so head and tail are used correctly in _trim
    if pretty_print:
        if head:
            head += '\n'
        if tail:
            tail = '\n' + tail
    return head + joiner.join(parts) + tail

Response: Convert from one format to another.


Instruction:
Implement a function in Python 3 to
select data from [ incr tsdb () ] profiles.

Response:
def select(dataspec, testsuite, mode='list', cast=True):
    """
    Select data from [incr tsdb()] profiles.

    Args:
        query (str): TSQL select query (e.g., `'i-id i-input mrs'` or
            `'* from item where readings > 0'`)
        testsuite (str, TestSuite): testsuite or path to testsuite
            containing data to select
        mode (str): see :func:`delphin.itsdb.select_rows` for a
            description of the *mode* parameter (default: `list`)
        cast (bool): if `True`, cast column values to their datatype
            according to the relations file (default: `True`)
    Returns:
        a generator that yields selected data
    """
    if isinstance(testsuite, itsdb.ItsdbProfile):
        testsuite = itsdb.TestSuite(testsuite.root)
    elif not isinstance(testsuite, itsdb.TestSuite):
        testsuite = itsdb.TestSuite(testsuite)
    return tsql.select(dataspec, testsuite, mode=mode, cast=cast)


Instruction:
Create a Python 3 function to
create a new TSDB profile file for the specified source and relations files.

Response:
def mkprof(destination, source=None, relations=None, where=None,
           in_place=False, skeleton=False, full=False, gzip=False):
    """
    Create [incr tsdb()] profiles or skeletons.

    Data for the testsuite may come from an existing testsuite or from
    a list of sentences. There are four main usage patterns:

        - `source="testsuite/"` -- read data from `testsuite/`
        - `source=None, in_place=True` -- read data from *destination*
        - `source=None, in_place=False` -- read sentences from stdin
        - `source="sents.txt"` -- read sentences from `sents.txt`

    For the latter two, the *relations* parameter must be specified.

    Args:
        destination (str): path of the new testsuite
        source (str): path to a source testsuite or a file containing
            sentences; if not given and *in_place* is `False`,
            sentences are read from stdin
        relations (str): path to a relations file to use for the
            created testsuite; if `None` and *source* is given, the
            relations file of the source testsuite is used
        where (str): TSQL condition to filter records by; ignored if
            *source* is not a testsuite
        in_place (bool): if `True` and *source* is not given, use
            *destination* as the source for data (default: `False`)
        skeleton (bool): if `True`, only write tsdb-core files
            (default: `False`)
        full (bool): if `True`, copy all data from the source
            testsuite (requires *source* to be a testsuite path;
            default: `False`)
        gzip (bool): if `True`, non-empty tables will be compressed
            with gzip
    """
    # basic validation
    if skeleton and full:
        raise ValueError("'skeleton' is incompatible with 'full'")
    elif skeleton and in_place:
        raise ValueError("'skeleton' is incompatible with 'in_place'")
    elif in_place and source is not None:
        raise ValueError("'in_place' is incompatible with 'source'")
    if in_place:
        source = destination
    if full and (source is None or not os.path.isdir(source)):
        raise ValueError("'full' must be used with a source testsuite")
    if relations is None and source is not None and os.path.isdir(source):
        relations = os.path.join(source, 'relations')
    elif relations is None or not os.path.isfile(relations):
        raise ValueError('invalid or missing relations file: {}'
                         .format(relations))
    # setup destination testsuite
    _prepare_output_directory(destination)
    dts = itsdb.TestSuite(path=destination, relations=relations)
    # input is sentences on stdin
    if source is None:
        dts.write({'item': _lines_to_rows(sys.stdin, dts.relations)},
                  gzip=gzip)
    # input is sentence file
    elif os.path.isfile(source):
        with open(source) as fh:
            dts.write({'item': _lines_to_rows(fh, dts.relations)},
                      gzip=gzip)
    # input is source testsuite
    elif os.path.isdir(source):
        sts = itsdb.TestSuite(source)
        tables = dts.relations.tables if full else itsdb.tsdb_core_files
        where = '' if where is None else 'where ' + where
        for table in tables:
            if sts.size(table) > 0:
                # filter the data, but use all if the query fails
                # (e.g., if the filter and table cannot be joined)
                try:
                    rows = tsql.select(
                        '* from {} {}'.format(table, where), sts, cast=False)
                except itsdb.ItsdbError:
                    rows = sts[table]
                dts.write({table: rows}, gzip=gzip)
    dts.reload()
    # unless a skeleton was requested, make empty files for other tables
    if not skeleton:
        for table in dts.relations:
            if len(dts[table]) == 0:
                dts.write({table: []})

    # summarize what was done
    if sys.stdout.isatty():
        _red = lambda s: '\x1b[1;31m{}\x1b[0m'.format(s)
    else:
        _red = lambda s: s
    fmt = '{:>8} bytes\t{}'
    for filename in ['relations'] + list(dts.relations.tables):
        path = os.path.join(destination, filename)
        if os.path.isfile(path):
            stat = os.stat(path)
            print(fmt.format(stat.st_size, filename))
        elif os.path.isfile(path + '.gz'):
            stat = os.stat(path + '.gz')
            print(fmt.format(stat.st_size, _red(filename + '.gz')))


Instruction:
How would you explain what the following Python 3 function does
def repp(file, config=None, module=None, active=None,
         format=None, trace_level=0):
    """
    Tokenize with a Regular Expression PreProcessor (REPP).

    Results are printed directly to stdout. If more programmatic
    access is desired, the :mod:`delphin.repp` module provides a
    similar interface.

    Args:
        file (str, file): filename, open file, or stream of sentence
            inputs
        config (str): path to a PET REPP configuration (.set) file
        module (str): path to a top-level REPP module; other modules
            are found by external group calls
        active (list): select which modules are active; if `None`, all
            are used; incompatible with *config* (default: `None`)
        format (str): the output format (`"yy"`, `"string"`, `"line"`,
            or `"triple"`; default: `"yy"`)
        trace_level (int): if `0` no trace info is printed; if `1`,
            applied rules are printed, if greather than `1`, both
            applied and unapplied rules (in order) are printed
            (default: `0`)
    """
    from delphin.repp import REPP

    if config is not None and module is not None:
        raise ValueError("cannot specify both 'config' and 'module'")
    if config is not None and active:
        raise ValueError("'active' cannot be used with 'config'")
    if config:
        r = REPP.from_config(config)
    elif module:
        r = REPP.from_file(module, active=active)
    else:
        r = REPP()  # just tokenize

    if hasattr(file, 'read'):
        for line in file:
            _repp(r, line, format, trace_level)
    else:
        with io.open(file, encoding='utf-8') as fh:
            for line in fh:
                _repp(r, line, format, trace_level)

Response: Tokenize with a Regular Expression PreProcessor.


Instruction:
Can you tell what is the following Python 3 function doing
def compare(testsuite, gold, select='i-id i-input mrs'):
    from delphin.mrs import simplemrs, compare as mrs_compare

    if not isinstance(testsuite, itsdb.TestSuite):
        if isinstance(testsuite, itsdb.ItsdbProfile):
            testsuite = testsuite.root
        testsuite = itsdb.TestSuite(testsuite)
    if not isinstance(gold, itsdb.TestSuite):
        if isinstance(gold, itsdb.ItsdbProfile):
            gold = gold.root
        gold = itsdb.TestSuite(gold)

    queryobj = tsql.inspect_query('select ' + select)
    if len(queryobj['projection']) != 3:
        raise ValueError('select does not return 3 fields: ' + select)

    input_select = '{} {}'.format(queryobj['projection'][0],
                                  queryobj['projection'][1])
    i_inputs = dict(tsql.select(input_select, testsuite))

    matched_rows = itsdb.match_rows(
        tsql.select(select, testsuite),
        tsql.select(select, gold),
        0)

    for (key, testrows, goldrows) in matched_rows:
        (test_unique, shared, gold_unique) = mrs_compare.compare_bags(
            [simplemrs.loads_one(row[2]) for row in testrows],
            [simplemrs.loads_one(row[2]) for row in goldrows])
        yield {'id': key,
               'input': i_inputs[key],
               'test': test_unique,
               'shared': shared,
               'gold': gold_unique}

Response: Compare two sets of items in a set of items.


Instruction:
Can you tell what is the following Python 3 function doing
def non_argument_modifiers(role='ARG1', only_connecting=True):
    def func(xmrs, deps):
        edges = []
        for src in deps:
            for _, tgt in deps[src]:
                edges.append((src, tgt))
        components = _connected_components(xmrs.nodeids(), edges)

        ccmap = {}
        for i, component in enumerate(components):
            for n in component:
                ccmap[n] = i

        addl = {}
        if not only_connecting or len(components) > 1:
            lsh = xmrs.labelset_heads
            lblheads = {v: lsh(v) for v, vd in xmrs._vars.items()
                        if 'LBL' in vd['refs']}
            for heads in lblheads.values():
                if len(heads) > 1:
                    first = heads[0]
                    joined = set([ccmap[first]])
                    for other in heads[1:]:
                        occ = ccmap[other]
                        srt = var_sort(xmrs.args(other).get(role, 'u0'))
                        needs_edge = not only_connecting or occ not in joined
                        edge_available = srt == 'u'
                        if needs_edge and edge_available:
                            addl.setdefault(other, []).append((role, first))
                            joined.add(occ)
        return addl

    return func

Response: Returns a function that returns a mapping of non - argument modifier dependencies.


Instruction:
Can you tell what is the following Python 3 function doing
def dumps(ms, single=False,
          properties=False, pretty_print=True,
          show_status=False, predicate_modifiers=False, **kwargs):
    """
    Serialize an Xmrs object to a Eds representation

    Args:
        ms: an iterator of :class:`~delphin.mrs.xmrs.Xmrs` objects to
            serialize (unless the *single* option is `True`)
        single (bool): if `True`, treat *ms* as a single
            :class:`~delphin.mrs.xmrs.Xmrs` object instead of as an
            iterator
        properties (bool): if `False`, suppress variable properties
        pretty_print (bool): if `True`, add newlines and indentation
        show_status (bool): if `True`, annotate disconnected graphs and
            nodes
    Returns:
        an :class:`Eds` string representation of a corpus of Xmrs
    """
    if not pretty_print and kwargs.get('indent'):
        pretty_print = True
    if single:
        ms = [ms]
    return serialize(
        ms,
        properties=properties,
        pretty_print=pretty_print,
        show_status=show_status,
        predicate_modifiers=predicate_modifiers,
        **kwargs
    )

Response: Serialize an Xmrs object to an Eds representation of a corpus of Xmrs objects.


Instruction:
Make a summary of the following Python 3 code
def nodes(self):
        getnode = self._nodes.__getitem__
        return [getnode(nid) for nid in self._nodeids]

Response: Return the list of nodes.


Instruction:
Create a Python 3 function to
encode the Eds as a dictionary suitable for JSON serialization.

Response:
def to_dict(self, properties=True):
        """
        Encode the Eds as a dictionary suitable for JSON serialization.
        """
        nodes = {}
        for node in self.nodes():
            nd = {
                'label': node.pred.short_form(),
                'edges': self.edges(node.nodeid)
            }
            if node.lnk is not None:
                nd['lnk'] = {'from': node.cfrom, 'to': node.cto}
            if properties:
                if node.cvarsort is not None:
                    nd['type'] = node.cvarsort
                props = node.properties
                if props:
                    nd['properties'] = props
            if node.carg is not None:
                nd['carg'] = node.carg
            nodes[node.nodeid] = nd
        return {'top': self.top, 'nodes': nodes}


Instruction:
Explain what the following Python 3 code does
def from_dict(cls, d):
        makepred, charspan = Pred.surface_or_abstract, Lnk.charspan
        top = d.get('top')
        nodes, edges = [], []
        for nid, node in d.get('nodes', {}).items():
            props = node.get('properties', {})
            if 'type' in node:
                props[CVARSORT] = node['type']
            if not props:
                props = None
            lnk = None
            if 'lnk' in node:
                lnk = charspan(node['lnk']['from'], node['lnk']['to'])
            nodes.append(
                Node(
                    nodeid=nid,
                    pred=makepred(node['label']),
                    sortinfo=props,
                    lnk=lnk,
                    carg=node.get('carg')
                )
            )
            edges.extend(
                (nid, rargname, tgtnid)
                for rargname, tgtnid in node.get('edges', {}).items()
            )
        nodes.sort(key=lambda n: (n.cfrom, -n.cto))
        return cls(top, nodes=nodes, edges=edges)

Response: Decode a dictionary into an Eds object.


Instruction:
Write a Python 3 function for
encoding the Eds as triples suitable for PENMAN serialization.

Response:
def to_triples(self, short_pred=True, properties=True):
        """
        Encode the Eds as triples suitable for PENMAN serialization.
        """
        node_triples, edge_triples = [], []
        # sort nodeids just so top var is first
        nodes = sorted(self.nodes(), key=lambda n: n.nodeid != self.top)
        for node in nodes:
            nid = node.nodeid
            pred = node.pred.short_form() if short_pred else node.pred.string
            node_triples.append((nid, 'predicate', pred))
            if node.lnk:
                node_triples.append((nid, 'lnk', '"{}"'.format(str(node.lnk))))
            if node.carg:
                node_triples.append((nid, 'carg', '"{}"'.format(node.carg)))
            if properties:
                if node.cvarsort is not None:
                    node_triples.append((nid, 'type', node.cvarsort))
                props = node.properties
                node_triples.extend((nid, p, v) for p, v in props.items())
            edge_triples.extend(
                (nid, rargname, tgt)
                for rargname, tgt in sorted(
                    self.edges(nid).items(),
                    key=lambda x: rargname_sortkey(x[0])
                )
            )
        return node_triples + edge_triples


Instruction:
Can you generate a brief explanation for the following Python 3 code
def from_triples(cls, triples):
        nids, nd, edges = [], {}, []
        for src, rel, tgt in triples:
            if src not in nd:
                nids.append(src)
                nd[src] = {'pred': None, 'lnk': None, 'carg': None, 'si': []}
            if rel == 'predicate':
                nd[src]['pred'] = Pred.surface_or_abstract(tgt)
            elif rel == 'lnk':
                cfrom, cto = tgt.strip('"<>').split(':')
                nd[src]['lnk'] = Lnk.charspan(int(cfrom), int(cto))
            elif rel == 'carg':
                if (tgt[0], tgt[-1]) == ('"', '"'):
                    tgt = tgt[1:-1]
                nd[src]['carg'] = tgt
            elif rel == 'type':
                nd[src]['si'].append((CVARSORT, tgt))
            elif rel.islower():
                nd[src]['si'].append((rel, tgt))
            else:
                edges.append((src, rel, tgt))
        nodes = [
            Node(
                nodeid=nid,
                pred=nd[nid]['pred'],
                sortinfo=nd[nid]['si'],
                lnk=nd[nid]['lnk'],
                carg=nd[nid]['carg']
            ) for nid in nids
        ]
        top = nids[0] if nids else None
        return cls(top=top, nodes=nodes, edges=edges)

Response: Decode triples as from _to_triples_ into an Eds object.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def next(self, skip=None):
        buffer = self._buffer
        popleft = buffer.popleft
        if skip is not None:
            while True:
                try:
                    if not skip(buffer[0]):
                        break
                    popleft()
                except IndexError:
                    self._buffer_fill()
        try:
            datum = popleft()
        except IndexError:
            self._buffer_fill()
            datum = popleft()
        return datum

Response: Returns the next datum in the buffer.


Instruction:
Explain what the following Python 3 code does
def peek(self, n=0, skip=None, drop=False):
        buffer = self._buffer
        popleft = buffer.popleft
        datum = None
        if skip is not None:
            stack = []
            stackpush = stack.append
            while n >= 0:
                try:
                    datum = popleft()
                except IndexError:
                    self._buffer_fill()
                    datum = popleft()
                if not skip(datum):
                    n -= 1
                    stackpush(datum)
                elif not drop:
                    stackpush(datum)
            buffer.extendleft(reversed(stack))
        else:
            self._buffer_fill(n + 1)
            datum = buffer[n]
        return datum

Response: Return the n th datum from the buffer.


Instruction:
Write a Python 3 function that can
serialize this InlineQueryResultPhoto to a dictionary.

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

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

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

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

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

        if self.photo_width is not None:
            array['photo_width'] = int(self.photo_width)  # type int
        if self.photo_height is not None:
            array['photo_height'] = int(self.photo_height)  # type int
        if self.title is not None:
            array['title'] = u(self.title)  # py2: type unicode, py3: type str

        if self.description is not None:
            array['description'] = u(self.description)  # py2: type unicode, py3: type str

        if self.caption is not None:
            array['caption'] = u(self.caption)  # py2: type unicode, py3: type str

        if self.parse_mode is not None:
            array['parse_mode'] = u(self.parse_mode)  # py2: type unicode, py3: type str

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

        if self.input_message_content is not None:
            array['input_message_content'] = self.input_message_content.to_array()  # type InputMessageContent

        return array


Instruction:
Can you write a function in Python 3 where it
serializes this InlineQueryResultMpeg4Gif to a dictionary.

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

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

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

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

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

        if self.mpeg4_width is not None:
            array['mpeg4_width'] = int(self.mpeg4_width)  # type int
        if self.mpeg4_height is not None:
            array['mpeg4_height'] = int(self.mpeg4_height)  # type int
        if self.mpeg4_duration is not None:
            array['mpeg4_duration'] = int(self.mpeg4_duration)  # type int
        if self.title is not None:
            array['title'] = u(self.title)  # py2: type unicode, py3: type str

        if self.caption is not None:
            array['caption'] = u(self.caption)  # py2: type unicode, py3: type str

        if self.parse_mode is not None:
            array['parse_mode'] = u(self.parse_mode)  # py2: type unicode, py3: type str

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

        if self.input_message_content is not None:
            array['input_message_content'] = self.input_message_content.to_array()  # type InputMessageContent

        return array


Instruction:
Implement a function in Python 3 to
serialize this InlineQueryResultVideo to a dictionary.

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

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

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

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

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

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

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

        if self.caption is not None:
            array['caption'] = u(self.caption)  # py2: type unicode, py3: type str

        if self.parse_mode is not None:
            array['parse_mode'] = u(self.parse_mode)  # py2: type unicode, py3: type str

        if self.video_width is not None:
            array['video_width'] = int(self.video_width)  # type int
        if self.video_height is not None:
            array['video_height'] = int(self.video_height)  # type int
        if self.video_duration is not None:
            array['video_duration'] = int(self.video_duration)  # type int
        if self.description is not None:
            array['description'] = u(self.description)  # py2: type unicode, py3: type str

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

        if self.input_message_content is not None:
            array['input_message_content'] = self.input_message_content.to_array()  # type InputMessageContent

        return array


Instruction:
How would you implement a function in Python 3 that
serializes this InlineQueryResultVoice to a dictionary.

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

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

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

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

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

        if self.caption is not None:
            array['caption'] = u(self.caption)  # py2: type unicode, py3: type str

        if self.parse_mode is not None:
            array['parse_mode'] = u(self.parse_mode)  # py2: type unicode, py3: type str

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

        if self.input_message_content is not None:
            array['input_message_content'] = self.input_message_content.to_array()  # type InputMessageContent

        return array


Instruction:
Can you generate a brief explanation for the following Python 3 code
def to_array(self):
        array = super(InlineQueryResultDocument, self).to_array()
        array['type'] = u(self.type)  # py2: type unicode, py3: type str

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

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

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

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

        if self.caption is not None:
            array['caption'] = u(self.caption)  # py2: type unicode, py3: type str

        if self.parse_mode is not None:
            array['parse_mode'] = u(self.parse_mode)  # py2: type unicode, py3: type str

        if self.description is not None:
            array['description'] = u(self.description)  # py2: type unicode, py3: type str

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

        if self.input_message_content is not None:
            array['input_message_content'] = self.input_message_content.to_array()  # type InputMessageContent

        if self.thumb_url is not None:
            array['thumb_url'] = u(self.thumb_url)  # py2: type unicode, py3: type str

        if self.thumb_width is not None:
            array['thumb_width'] = int(self.thumb_width)  # type int
        if self.thumb_height is not None:
            array['thumb_height'] = int(self.thumb_height)  # type int
        return array

Response: Serializes this InlineQueryResultDocument to a dictionary.


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

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

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

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

        if self.foursquare_id is not None:
            array['foursquare_id'] = u(self.foursquare_id)  # py2: type unicode, py3: type str

        if self.foursquare_type is not None:
            array['foursquare_type'] = u(self.foursquare_type)  # py2: type unicode, py3: type str

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

        if self.input_message_content is not None:
            array['input_message_content'] = self.input_message_content.to_array()  # type InputMessageContent

        if self.thumb_url is not None:
            array['thumb_url'] = u(self.thumb_url)  # py2: type unicode, py3: type str

        if self.thumb_width is not None:
            array['thumb_width'] = int(self.thumb_width)  # type int
        if self.thumb_height is not None:
            array['thumb_height'] = int(self.thumb_height)  # type int
        return array

Response: Serializes this InlineQueryResultVenue to a dictionary.


Instruction:
Write a Python 3 script for
serializing this InlineQueryResultGame to a dictionary.

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

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

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

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

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

        return array


Instruction:
Implement a function in Python 3 to
serialize this InlineQueryResultCachedPhoto to a dictionary.

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

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

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

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

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

        if self.description is not None:
            array['description'] = u(self.description)  # py2: type unicode, py3: type str

        if self.caption is not None:
            array['caption'] = u(self.caption)  # py2: type unicode, py3: type str

        if self.parse_mode is not None:
            array['parse_mode'] = u(self.parse_mode)  # py2: type unicode, py3: type str

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

        if self.input_message_content is not None:
            array['input_message_content'] = self.input_message_content.to_array()  # type InputMessageContent

        return array


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

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

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

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

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

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

        if self.caption is not None:
            array['caption'] = u(self.caption)  # py2: type unicode, py3: type str

        if self.parse_mode is not None:
            array['parse_mode'] = u(self.parse_mode)  # py2: type unicode, py3: type str

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

        if self.input_message_content is not None:
            array['input_message_content'] = self.input_message_content.to_array()  # type InputMessageContent

        return array


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

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

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

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

        if self.input_message_content is not None:
            array['input_message_content'] = self.input_message_content.to_array()  # type InputMessageContent

        return array

Response: Serializes this InlineQueryResultCachedSticker to a dictionary.


Instruction:
Can you implement a function in Python 3 that
serializes this InlineQueryResultCachedVideo to a dictionary.

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

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

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

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

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

        if self.description is not None:
            array['description'] = u(self.description)  # py2: type unicode, py3: type str

        if self.caption is not None:
            array['caption'] = u(self.caption)  # py2: type unicode, py3: type str

        if self.parse_mode is not None:
            array['parse_mode'] = u(self.parse_mode)  # py2: type unicode, py3: type str

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

        if self.input_message_content is not None:
            array['input_message_content'] = self.input_message_content.to_array()  # type InputMessageContent

        return array


Instruction:
Can you generate a brief explanation for the following Python 3 code
def to_array(self):
        array = super(InlineQueryResultCachedAudio, self).to_array()
        array['type'] = u(self.type)  # py2: type unicode, py3: type str

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

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

        if self.caption is not None:
            array['caption'] = u(self.caption)  # py2: type unicode, py3: type str

        if self.parse_mode is not None:
            array['parse_mode'] = u(self.parse_mode)  # py2: type unicode, py3: type str

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

        if self.input_message_content is not None:
            array['input_message_content'] = self.input_message_content.to_array()  # type InputMessageContent

        return array

Response: Serializes this InlineQueryResultCachedAudio to a dictionary.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def to_array(self):
        array = super(MessageEntity, self).to_array()
        array['type'] = u(self.type)  # py2: type unicode, py3: type str

        array['offset'] = int(self.offset)  # type int
        array['length'] = int(self.length)  # type int
        if self.url is not None:
            array['url'] = u(self.url)  # py2: type unicode, py3: type str

        if self.user is not None:
            array['user'] = self.user.to_array()  # type User

        return array

Response: Serializes this MessageEntity to a dictionary.


Instruction:
Can you tell what is the following Python 3 function doing
def to_array(self):
        array = super(PhotoSize, self).to_array()
        array['file_id'] = u(self.file_id)  # py2: type unicode, py3: type str

        array['width'] = int(self.width)  # type int
        array['height'] = int(self.height)  # type int
        if self.file_size is not None:
            array['file_size'] = int(self.file_size)  # type int
        return array

Response: Serializes this PhotoSize to a dictionary.


Instruction:
Can you write a function in Python 3 where it
serializes this Audio to a dictionary.

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

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

        array['duration'] = int(self.duration)  # type int
        if self.performer is not None:
            array['performer'] = u(self.performer)  # py2: type unicode, py3: type str

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

        if self.mime_type is not None:
            array['mime_type'] = u(self.mime_type)  # py2: type unicode, py3: type str

        if self.file_size is not None:
            array['file_size'] = int(self.file_size)  # type int
        if self.thumb is not None:
            array['thumb'] = self.thumb.to_array()  # type PhotoSize

        return array


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")
        from pytgbot.api_types.receivable.media import PhotoSize

        data = {}
        data['file_id'] = u(array.get('file_id'))
        data['duration'] = int(array.get('duration'))
        data['performer'] = u(array.get('performer')) if array.get('performer') is not None else None
        data['title'] = u(array.get('title')) if array.get('title') is not None else None
        data['mime_type'] = u(array.get('mime_type')) if array.get('mime_type') is not None else None
        data['file_size'] = int(array.get('file_size')) if array.get('file_size') is not None else None
        data['thumb'] = PhotoSize.from_array(array.get('thumb')) if array.get('thumb') is not None else None
        data['_raw'] = array
        return Audio(**data)

Response: Deserialize a new Audio from a given dictionary.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def to_array(self):
        array = super(Document, self).to_array()
        array['file_id'] = u(self.file_id)  # py2: type unicode, py3: type str

        if self.thumb is not None:
            array['thumb'] = self.thumb.to_array()  # type PhotoSize

        if self.file_name is not None:
            array['file_name'] = u(self.file_name)  # py2: type unicode, py3: type str

        if self.mime_type is not None:
            array['mime_type'] = u(self.mime_type)  # py2: type unicode, py3: type str

        if self.file_size is not None:
            array['file_size'] = int(self.file_size)  # type int
        return array

Response: Serializes this Document to a dictionary.


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

        array['width'] = int(self.width)  # type int
        array['height'] = int(self.height)  # type int
        array['duration'] = int(self.duration)  # type int
        if self.thumb is not None:
            array['thumb'] = self.thumb.to_array()  # type PhotoSize

        if self.file_name is not None:
            array['file_name'] = u(self.file_name)  # py2: type unicode, py3: type str

        if self.mime_type is not None:
            array['mime_type'] = u(self.mime_type)  # py2: type unicode, py3: type str

        if self.file_size is not None:
            array['file_size'] = int(self.file_size)  # type int
        return array

Response: Serializes this Animation to a dictionary.


Instruction:
Implement a Python 3 function for
serializing this Voice to a dictionary.

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

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

        array['duration'] = int(self.duration)  # type int
        if self.mime_type is not None:
            array['mime_type'] = u(self.mime_type)  # py2: type unicode, py3: type str

        if self.file_size is not None:
            array['file_size'] = int(self.file_size)  # type int
        return array


Instruction:
Given the following Python 3 function, write the documentation
def to_array(self):
        array = super(VideoNote, self).to_array()
        array['file_id'] = u(self.file_id)  # py2: type unicode, py3: type str

        array['length'] = int(self.length)  # type int
        array['duration'] = int(self.duration)  # type int
        if self.thumb is not None:
            array['thumb'] = self.thumb.to_array()  # type PhotoSize

        if self.file_size is not None:
            array['file_size'] = int(self.file_size)  # type int
        return array

Response: Serializes this VideoNote to a dictionary.


Instruction:
Write a Python 3 script to
serialize this Contact to a dictionary.

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

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

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

        if self.last_name is not None:
            array['last_name'] = u(self.last_name)  # py2: type unicode, py3: type str

        if self.user_id is not None:
            array['user_id'] = int(self.user_id)  # type int
        if self.vcard is not None:
            array['vcard'] = u(self.vcard)  # py2: type unicode, py3: type str

        return array


Instruction:
Make a summary of the following Python 3 code
def to_array(self):
        array = super(Location, self).to_array()
        array['longitude'] = float(self.longitude)  # type float
        array['latitude'] = float(self.latitude)  # type float
        return array

Response: Serializes this Location 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")

        data = {}
        data['longitude'] = float(array.get('longitude'))
        data['latitude'] = float(array.get('latitude'))
        data['_raw'] = array
        return Location(**data)

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


Instruction:
Make a summary of the following Python 3 code
def to_array(self):
        array = super(Venue, self).to_array()
        array['location'] = self.location.to_array()  # type Location

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

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

        if self.foursquare_id is not None:
            array['foursquare_id'] = u(self.foursquare_id)  # py2: type unicode, py3: type str

        if self.foursquare_type is not None:
            array['foursquare_type'] = u(self.foursquare_type)  # py2: type unicode, py3: type str

        return array

Response: Serializes this Venue 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")
        from pytgbot.api_types.receivable.media import Location

        data = {}
        data['location'] = Location.from_array(array.get('location'))
        data['title'] = u(array.get('title'))
        data['address'] = u(array.get('address'))
        data['foursquare_id'] = u(array.get('foursquare_id')) if array.get('foursquare_id') is not None else None
        data['foursquare_type'] = u(array.get('foursquare_type')) if array.get('foursquare_type') is not None else None
        data['_raw'] = array
        return Venue(**data)

Response: Deserialize a new Venue from a given dictionary.


Instruction:
Can you generate the documentation for the following Python 3 function
def to_array(self):
        array = super(UserProfilePhotos, self).to_array()
        array['total_count'] = int(self.total_count)  # type int
        array['photos'] = self._as_array(self.photos)  # type list of list of PhotoSize

        return array

Response: Serializes this UserProfilePhotos to a dictionary.


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.receivable.media import PhotoSize

        data = {}
        data['total_count'] = int(array.get('total_count'))
        data['photos'] = PhotoSize.from_array_list(array.get('photos'), list_level=2)
        data['_raw'] = array
        return UserProfilePhotos(**data)

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


Instruction:
Can you generate a brief explanation for the following Python 3 code
def to_array(self):
        array = super(File, self).to_array()
        array['file_id'] = u(self.file_id)  # py2: type unicode, py3: type str

        if self.file_size is not None:
            array['file_size'] = int(self.file_size)  # type int
        if self.file_path is not None:
            array['file_path'] = u(self.file_path)  # py2: type unicode, py3: type str

        return array

Response: Serializes this File to a dictionary.


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

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

        return array

Response: Serializes this ChatPhoto to a dictionary.


Instruction:
Write a Python 3 script to
serialize this Sticker to a dictionary.

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

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

        array['width'] = int(self.width)  # type int
        array['height'] = int(self.height)  # type int
        if self.thumb is not None:
            array['thumb'] = self.thumb.to_array()  # type PhotoSize

        if self.emoji is not None:
            array['emoji'] = u(self.emoji)  # py2: type unicode, py3: type str

        if self.set_name is not None:
            array['set_name'] = u(self.set_name)  # py2: type unicode, py3: type str

        if self.mask_position is not None:
            array['mask_position'] = self.mask_position.to_array()  # type MaskPosition

        if self.file_size is not None:
            array['file_size'] = int(self.file_size)  # type int
        return array


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.receivable.media import PhotoSize
        from pytgbot.api_types.receivable.stickers import MaskPosition

        data = {}
        data['file_id'] = u(array.get('file_id'))
        data['width'] = int(array.get('width'))
        data['height'] = int(array.get('height'))
        data['thumb'] = PhotoSize.from_array(array.get('thumb')) if array.get('thumb') is not None else None
        data['emoji'] = u(array.get('emoji')) if array.get('emoji') is not None else None
        data['set_name'] = u(array.get('set_name')) if array.get('set_name') is not None else None
        data['mask_position'] = MaskPosition.from_array(array.get('mask_position')) if array.get('mask_position') is not None else None
        data['file_size'] = int(array.get('file_size')) if array.get('file_size') is not None else None
        data['_raw'] = array
        return Sticker(**data)

Response: Deserialize a new Sticker from a given dictionary.


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

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

        array['photo'] = self._as_array(self.photo)  # type list of PhotoSize

        if self.text is not None:
            array['text'] = u(self.text)  # py2: type unicode, py3: type str

        if self.text_entities is not None:
            array['text_entities'] = self._as_array(self.text_entities)  # type list of MessageEntity

        if self.animation is not None:
            array['animation'] = self.animation.to_array()  # type Animation

        return array

Response: Serializes this Game to a dictionary.


Instruction:
Here you have a function in Python 3, explain what it 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.receivable.media import Animation
        from pytgbot.api_types.receivable.media import MessageEntity
        from pytgbot.api_types.receivable.media import PhotoSize

        data = {}
        data['title'] = u(array.get('title'))
        data['description'] = u(array.get('description'))
        data['photo'] = PhotoSize.from_array_list(array.get('photo'), list_level=1)
        data['text'] = u(array.get('text')) if array.get('text') is not None else None
        data['text_entities'] = MessageEntity.from_array_list(array.get('text_entities'), list_level=1) if array.get('text_entities') is not None else None
        data['animation'] = Animation.from_array(array.get('animation')) if array.get('animation') is not None else None
        data['_raw'] = array
        return Game(**data)

Response: Deserialize a new Game from a given dictionary.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def from_array(array):
        data = super(DownloadableMedia).from_array(array)
        data["file_id"] = array.get("file_id")
        data["file_size"] = array.get("file_size")  # can be None
        return data

Response: Subclass for all : class:`Media which has a file_id and file_size attribute extracted from the array.


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")
        from .stickers import MaskPosition

        data = {}
        data['file_id'] = u(array.get('file_id'))
        data['width'] = int(array.get('width'))
        data['height'] = int(array.get('height'))
        data['thumb'] = PhotoSize.from_array(array.get('thumb')) if array.get('thumb') is not None else None
        data['emoji'] = u(array.get('emoji')) if array.get('emoji') is not None else None
        data['set_name'] = u(array.get('set_name')) if array.get('set_name') is not None else None
        data['mask_position'] = MaskPosition.from_array(array.get('mask_position')) if array.get(
            'mask_position') is not None else None
        data['file_size'] = int(array.get('file_size')) if array.get('file_size') is not None else None
        data['_raw'] = array
        return Sticker(**data)

Response: Deserialize a new Sticker from a given 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['file_id'] = u(array.get('file_id'))
        data['length'] = int(array.get('length'))
        data['duration'] = int(array.get('duration'))
        data['thumb'] = PhotoSize.from_array(array.get('thumb')) if array.get('thumb') is not None else None
        data['file_size'] = int(array.get('file_size')) if array.get('file_size') is not None else None
        data['_raw'] = array
        return VideoNote(**data)

Response: Deserialize a new VideoNote from a given dictionary.


Instruction:
Make a summary of the following Python 3 code
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['total_count'] = int(array.get('total_count'))
        data['photos'] = PhotoSize.from_array_list(array.get('photos'), list_level=2)
        data['_raw'] = array
        return UserProfilePhotos(**data)

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


Instruction:
How would you explain what the following Python 3 function does
def to_array(self):
        array = super(ReplyKeyboardMarkup, self).to_array()
        array['keyboard'] = self._as_array(self.keyboard)  # type list of list of KeyboardButton

        if self.resize_keyboard is not None:
            array['resize_keyboard'] = bool(self.resize_keyboard)  # type bool
        if self.one_time_keyboard is not None:
            array['one_time_keyboard'] = bool(self.one_time_keyboard)  # type bool
        if self.selective is not None:
            array['selective'] = bool(self.selective)  # type bool
        return array

Response: Serializes this ReplyKeyboardMarkup to a dictionary.


Instruction:
Can you tell what is the following Python 3 function doing
def to_array(self):
        array = super(KeyboardButton, self).to_array()
        array['text'] = u(self.text)  # py2: type unicode, py3: type str

        if self.request_contact is not None:
            array['request_contact'] = bool(self.request_contact)  # type bool
        if self.request_location is not None:
            array['request_location'] = bool(self.request_location)  # type bool
        return array

Response: Serializes this KeyboardButton to a dictionary.


Instruction:
Can you generate the documentation for the following Python 3 function
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['text'] = u(array.get('text'))
        data['request_contact'] = bool(array.get('request_contact')) if array.get('request_contact') is not None else None
        data['request_location'] = bool(array.get('request_location')) if array.get('request_location') is not None else None

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

Response: Deserialize a new KeyboardButton from a given dictionary.


Instruction:
Write a Python 3 function that can
serialize this ReplyKeyboardRemove to a dictionary.

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

        :return: dictionary representation of this object.
        :rtype: dict
        """
        array = super(ReplyKeyboardRemove, self).to_array()
        array['remove_keyboard'] = bool(self.remove_keyboard)  # type bool
        if self.selective is not None:
            array['selective'] = bool(self.selective)  # type bool
        return array


Instruction:
Can you write a function in Python 3 where it
serializes this InlineKeyboardMarkup to a dictionary.

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

        :return: dictionary representation of this object.
        :rtype: dict
        """
        array = super(InlineKeyboardMarkup, self).to_array()
        array['inline_keyboard'] = self._as_array(self.inline_keyboard)  # type list of list of InlineKeyboardButton

        return array


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

        if self.url is not None:
            array['url'] = u(self.url)  # py2: type unicode, py3: type str

        if self.callback_data is not None:
            array['callback_data'] = u(self.callback_data)  # py2: type unicode, py3: type str

        if self.switch_inline_query is not None:
            array['switch_inline_query'] = u(self.switch_inline_query)  # py2: type unicode, py3: type str

        if self.switch_inline_query_current_chat is not None:
            array['switch_inline_query_current_chat'] = u(self.switch_inline_query_current_chat)  # py2: type unicode, py3: type str

        if self.callback_game is not None:
            array['callback_game'] = self.callback_game.to_array()  # type CallbackGame

        if self.pay is not None:
            array['pay'] = bool(self.pay)  # type bool
        return array

Response: Serializes this InlineKeyboardButton to a dictionary.


Instruction:
Here you have a function in Python 3, explain what it 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.receivable.updates import CallbackGame

        data = {}
        data['text'] = u(array.get('text'))
        data['url'] = u(array.get('url')) if array.get('url') is not None else None
        data['callback_data'] = u(array.get('callback_data')) if array.get('callback_data') is not None else None
        data['switch_inline_query'] = u(array.get('switch_inline_query')) if array.get('switch_inline_query') is not None else None
        data['switch_inline_query_current_chat'] = u(array.get('switch_inline_query_current_chat')) if array.get('switch_inline_query_current_chat') is not None else None
        data['callback_game'] = CallbackGame.from_array(array.get('callback_game')) if array.get('callback_game') is not None else None
        data['pay'] = bool(array.get('pay')) if array.get('pay') is not None else None

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

Response: Deserialize a new InlineKeyboardButton from a given dictionary.


Instruction:
Can you generate the documentation for the following Python 3 function
def to_array(self):
        array = super(ForceReply, self).to_array()
        array['force_reply'] = bool(self.force_reply)  # type bool
        if self.selective is not None:
            array['selective'] = bool(self.selective)  # type bool
        return array

Response: Serializes this ForceReply 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")

        data = {}
        data['force_reply'] = bool(array.get('force_reply'))
        data['selective'] = bool(array.get('selective')) if array.get('selective') is not None else None

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

Response: Deserialize a new ForceReply from a given dictionary.


Instruction:
Write a Python 3 script for
serializing this PassportElementErrorDataField to a dictionary.

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

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


Instruction:
Explain what the following Python 3 code does
def to_array(self):
        array = super(PassportElementErrorReverseSide, self).to_array()
        array['source'] = u(self.source)  # py2: type unicode, py3: type str
        array['type'] = u(self.type)  # py2: type unicode, py3: type str
        array['file_hash'] = u(self.file_hash)  # py2: type unicode, py3: type str
        array['message'] = u(self.message)  # py2: type unicode, py3: type str
        return array

Response: Serializes this PassportElementErrorReverseSide to a dictionary.


Instruction:
Make a summary of the following Python 3 code
def to_array(self):
        array = super(PassportElementErrorFiles, self).to_array()
        array['source'] = u(self.source)  # py2: type unicode, py3: type str
        array['type'] = u(self.type)  # py2: type unicode, py3: type str
        array['file_hashes'] = self._as_array(self.file_hashes)  # type list of str
        array['message'] = u(self.message)  # py2: type unicode, py3: type str
        return array

Response: Serializes this PassportElementErrorFiles 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")

        data = {}
        data['source'] = u(array.get('source'))
        data['type'] = u(array.get('type'))
        data['file_hashes'] = PassportElementErrorFiles._builtin_from_array_list(required_type=unicode_type, value=array.get('file_hashes'), list_level=1)
        data['message'] = u(array.get('message'))

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

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


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

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

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

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

        return array

Response: Serializes this PassportElementErrorUnspecified to a dictionary.


Instruction:
Make a summary of the following Python 3 code
def to_array(self):
        array = super(InlineQuery, self).to_array()
        array['id'] = u(self.id)  # py2: type unicode, py3: type str
        array['from'] = self.from_peer.to_array()  # type User
        array['query'] = u(self.query)  # py2: type unicode, py3: type str
        array['offset'] = u(self.offset)  # py2: type unicode, py3: type str
        if self.location is not None:
            array['location'] = self.location.to_array()  # type Location
        return array

Response: Serializes this InlineQuery to a dictionary.


Instruction:
Can you generate a brief explanation for the following Python 3 code
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.receivable.media import Location
        from pytgbot.api_types.receivable.peer import User

        data = {}
        data['id'] = u(array.get('id'))
        data['from_peer'] = User.from_array(array.get('from'))
        data['query'] = u(array.get('query'))
        data['offset'] = u(array.get('offset'))
        data['location'] = Location.from_array(array.get('location')) if array.get('location') is not None else None
        data['_raw'] = array
        return InlineQuery(**data)

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


Instruction:
Here you have a function in Python 3, explain what it does
def to_array(self):
        array = super(ChosenInlineResult, self).to_array()
        array['result_id'] = u(self.result_id)  # py2: type unicode, py3: type str
        array['from'] = self.from_peer.to_array()  # type User
        array['query'] = u(self.query)  # py2: type unicode, py3: type str
        if self.location is not None:
            array['location'] = self.location.to_array()  # type Location
        if self.inline_message_id is not None:
            array['inline_message_id'] = u(self.inline_message_id)  # py2: type unicode, py3: type str
        return array

Response: Serializes this ChosenInlineResult to a dictionary.


Instruction:
Can you generate the documentation for the following Python 3 function
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.receivable.inline import ChosenInlineResult
        from pytgbot.api_types.receivable.inline import InlineQuery
        from pytgbot.api_types.receivable.payments import PreCheckoutQuery
        from pytgbot.api_types.receivable.payments import ShippingQuery
        from pytgbot.api_types.receivable.updates import CallbackQuery
        from pytgbot.api_types.receivable.updates import Message

        data = {}
        data['update_id'] = int(array.get('update_id'))
        data['message'] = Message.from_array(array.get('message')) if array.get('message') is not None else None
        data['edited_message'] = Message.from_array(array.get('edited_message')) if array.get('edited_message') is not None else None
        data['channel_post'] = Message.from_array(array.get('channel_post')) if array.get('channel_post') is not None else None
        data['edited_channel_post'] = Message.from_array(array.get('edited_channel_post')) if array.get('edited_channel_post') is not None else None
        data['inline_query'] = InlineQuery.from_array(array.get('inline_query')) if array.get('inline_query') is not None else None
        data['chosen_inline_result'] = ChosenInlineResult.from_array(array.get('chosen_inline_result')) if array.get('chosen_inline_result') is not None else None
        data['callback_query'] = CallbackQuery.from_array(array.get('callback_query')) if array.get('callback_query') is not None else None
        data['shipping_query'] = ShippingQuery.from_array(array.get('shipping_query')) if array.get('shipping_query') is not None else None
        data['pre_checkout_query'] = PreCheckoutQuery.from_array(array.get('pre_checkout_query')) if array.get('pre_checkout_query') is not None else None
        data['_raw'] = array
        return Update(**data)

Response: Deserialize a new Update from a given dictionary.


Instruction:
Here you have a function in Python 3, explain what it does
def from_dict(cls, d):
        return cls(
            d['id'],
            d['start'],
            d['end'],
            Lnk.charspan(d['from'], d['to']) if 'from' in d else None,
            # d.get('paths', [1]),
            form=d['form'],
            surface=d.get('surface'),
            # ipos=
            # lrules=
            pos=zip(d.get('tags', []), d.get('probabilities', []))
        )

Response: Decode from a dictionary as from : meth : to_dict.


Instruction:
Explain what the following Python 3 code does
def to_dict(self):
        d = {
            'id': self.id,
            'start': self.start,
            'end': self.end,
            'form': self.form
        }
        if self.lnk is not None:
            cfrom, cto = self.lnk.data
            d['from'] = cfrom
            d['to'] = cto
        # d['paths'] = self.paths
        if self.surface is not None:
            d['surface'] = self.surface
        # d['ipos'] = self.ipos
        # d['lrules'] = self.lrules
        if self.pos:
            d['tags'] = [ps[0] for ps in self.pos]
            d['probabilities'] = [ps[1] for ps in self.pos]
        return d

Response: Encode the token as a dictionary suitable for JSON serialization.


Instruction:
Can you create a Python 3 function that
decodes from the YY token lattice format.

Response:
def from_string(cls, s):
        """
        Decode from the YY token lattice format.
        """
        def _qstrip(s):
            return s[1:-1]  # remove assumed quote characters
        tokens = []
        for match in _yy_re.finditer(s):
            d = match.groupdict()
            lnk, pos = None, []
            if d['lnkfrom'] is not None:
                lnk = Lnk.charspan(d['lnkfrom'], d['lnkto'])
            if d['pos'] is not None:
                ps = d['pos'].strip().split()
                pos = list(zip(map(_qstrip, ps[::2]), map(float, ps[1::2])))
            tokens.append(
                YyToken(
                    int(d['id']),
                    int(d['start']),
                    int(d['end']),
                    lnk,
                    list(map(int, d['paths'].strip().split())),
                    _qstrip(d['form']),
                    None if d['surface'] is None else _qstrip(d['surface']),
                    int(d['ipos']),
                    list(map(_qstrip, d['lrules'].strip().split())),
                    pos
                )
            )
        return cls(tokens)


Instruction:
Given the following Python 3 function, write the documentation
def load(fh, single=False, version=_default_version,
         strict=False, errors='warn'):
    """
    Deserialize SimpleMRSs from a file (handle or filename)

    Args:
        fh (str, file): input filename or file object
        single: if `True`, only return the first read Xmrs object
        strict: deprecated; a `True` value is the same as
            `errors='strict'`, and a `False` value is the same as
            `errors='warn'`
        errors: if `'strict'`, ill-formed MRSs raise an error; if
            `'warn'`, raise a warning instead; if `'ignore'`, do not
            warn or raise errors for ill-formed MRSs
    Returns:
        a generator of Xmrs objects (unless the *single* option is
        `True`)
    """
    if isinstance(fh, stringtypes):
        s = open(fh, 'r').read()
    else:
        s = fh.read()
    return loads(s, single=single, version=version,
                 strict=strict, errors=errors)

Response: Deserialize SimpleMRSs from a file - like object.


Instruction:
Make a summary of the following Python 3 code
def dumps(ms, single=False, version=_default_version, properties=True,
          pretty_print=False, color=False, **kwargs):
    """
    Serialize an Xmrs object to a SimpleMRS representation

    Args:
        ms: an iterator of Xmrs objects to serialize (unless the
            *single* option is `True`)
        single: if `True`, treat *ms* as a single Xmrs object instead
            of as an iterator
        properties: if `False`, suppress variable properties
        pretty_print: if `True`, add newlines and indentation
        color: if `True`, colorize the output with ANSI color codes
    Returns:
        a SimpleMrs string representation of a corpus of Xmrs
    """
    if not pretty_print and kwargs.get('indent'):
        pretty_print = True
    if single:
        ms = [ms]
    return serialize(ms, version=version, properties=properties,
                     pretty_print=pretty_print, color=color)

Response: Serialize an Xmrs object to a SimpleMrs string representation


Instruction:
Write a Python 3 function for
reading and return a tuple of the pred s lnk type and lnk value if a pred lnk is specified.

Response:
def _read_lnk(tokens):
    """Read and return a tuple of the pred's lnk type and lnk value,
       if a pred lnk is specified."""
    # < FROM : TO > or < FROM # TO > or < TOK... > or < @ EDGE >
    lnk = None
    if tokens[0] == '<':
        tokens.popleft()  # we just checked this is a left angle
        if tokens[0] == '>':
            pass  # empty <> brackets the same as no lnk specified
        # edge lnk: ['@', EDGE, ...]
        elif tokens[0] == '@':
            tokens.popleft()  # remove the @
            lnk = Lnk.edge(tokens.popleft())  # edge lnks only have one number
        # character span lnk: [FROM, ':', TO, ...]
        elif tokens[1] == ':':
            lnk = Lnk.charspan(tokens.popleft(), tokens[1])
            tokens.popleft()  # this should be the colon
            tokens.popleft()  # and this is the cto
        # chart vertex range lnk: [FROM, '#', TO, ...]
        elif tokens[1] == '#':
            lnk = Lnk.chartspan(tokens.popleft(), tokens[1])
            tokens.popleft()  # this should be the hash
            tokens.popleft()  # and this is the to vertex
        # tokens lnk: [(TOK,)+ ...]
        else:
            lnkdata = []
            while tokens[0] != '>':
                lnkdata.append(int(tokens.popleft()))
            lnk = Lnk.tokens(lnkdata)
        _read_literals(tokens, '>')
    return lnk


Instruction:
Can you generate the documentation for the following Python 3 function
def serialize(ms, version=_default_version, properties=True,
              pretty_print=False, color=False):
    """Serialize an MRS structure into a SimpleMRS string."""
    delim = '\n' if pretty_print else _default_mrs_delim
    output = delim.join(
        _serialize_mrs(m, properties=properties,
                       version=version, pretty_print=pretty_print)
        for m in ms
    )
    if color:
        output = highlight(output)
    return output

Response: Serialize an MRS structure into a SimpleMRS string.


Instruction:
How would you code a function in Python 3 to
serialize an MRS argument into the SimpleMRS format.

Response:
def _serialize_argument(rargname, value, varprops):
    """Serialize an MRS argument into the SimpleMRS format."""
    _argument = '{rargname}: {value}{props}'
    if rargname == CONSTARG_ROLE:
        value = '"{}"'.format(value)
    props = ''
    if value in varprops:
        props = ' [ {} ]'.format(
            ' '.join(
                [var_sort(value)] +
                list(map('{0[0]}: {0[1]}'.format,
                         [(k.upper(), v) for k, v in varprops[value]]))
            )
        )
        del varprops[value]  # only print props once
    return _argument.format(
        rargname=rargname,
        value=str(value),
        props=props
    )


Instruction:
Can you create a Python 3 function that
serializes an Elementary Predication into the SimpleMRS encoding.

Response:
def _serialize_ep(ep, varprops, version=_default_version):
    """Serialize an Elementary Predication into the SimpleMRS encoding."""
    # ('nodeid', 'pred', 'label', 'args', 'lnk', 'surface', 'base')
    args = ep[3]
    arglist = ' '.join([_serialize_argument(rarg, args[rarg], varprops)
                        for rarg in sorted(args, key=rargname_sortkey)])
    if version < 1.1 or len(ep) < 6 or ep[5] is None:
        surface = ''
    else:
        surface = ' "%s"' % ep[5]
    lnk = None if len(ep) < 5 else ep[4]
    pred = ep[1]
    predstr = pred.string
    return '[ {pred}{lnk}{surface} LBL: {label}{s}{args} ]'.format(
        pred=predstr,
        lnk=_serialize_lnk(lnk),
        surface=surface,
        label=str(ep[2]),
        s=' ' if arglist else '',
        args=arglist
    )


Instruction:
Explain what the following Python 3 code does
def _serialize_lnk(lnk):
    s = ""
    if lnk is not None:
        s = '<'
        if lnk.type == Lnk.CHARSPAN:
            cfrom, cto = lnk.data
            s += ''.join([str(cfrom), ':', str(cto)])
        elif lnk.type == Lnk.CHARTSPAN:
            cfrom, cto = lnk.data
            s += ''.join([str(cfrom), '#', str(cto)])
        elif lnk.type == Lnk.TOKENS:
            s += ' '.join([str(t) for t in lnk.data])
        elif lnk.type == Lnk.EDGE:
            s += ''.join(['@', str(lnk.data)])
        s += '>'
    return s

Response:
Serialize a predication lnk to surface form into the SimpleMRS
       encoding.


Instruction:
Can you generate the documentation for the following Python 3 function
def _serialize_hcons(hcons):
    toks = ['HCONS:', '<']
    for hc in hcons:
        toks.extend(hc)
        # reln = hcon[1]
        # toks += [hcon[0], rel, str(hcon.lo)]
    toks += ['>']
    return ' '.join(toks)

Response: Serialize HandleConstraints into the SimpleMRS encoding.


Instruction:
Given the following Python 3 function, write the documentation
def _serialize_icons(icons):
    toks = ['ICONS:', '<']
    for ic in icons:
        toks.extend(ic)
        # toks += [str(icon.left),
        #          icon.relation,
        #          str(icon.right)]
    toks += ['>']
    return ' '.join(toks)

Response: Serialize [IndividualConstraints into the SimpleMRS encoding.


Instruction:
Implement a Python 3 function for
encoding the node as a dictionary suitable for JSON serialization.

Response:
def to_dict(self, fields=_all_fields, labels=None):
        """
        Encode the node as a dictionary suitable for JSON serialization.

        Args:
            fields: if given, this is a whitelist of fields to include
                on nodes (`daughters` and `form` are always shown)
            labels: optional label annotations to embed in the
                derivation dict; the value is a list of lists matching
                the structure of the derivation (e.g.,
                `["S" ["NP" ["NNS" ["Dogs"]]] ["VP" ["VBZ" ["bark"]]]]`)
        Returns:
            dict: the dictionary representation of the structure
        """
        fields = set(fields)
        diff = fields.difference(_all_fields)
        if isinstance(labels, Sequence):
            labels = _map_labels(self, labels)
        elif labels is None:
            labels = {}
        if diff:
            raise ValueError(
                'Invalid field(s): {}'.format(', '.join(diff))
            )
        return _to_dict(self, fields, labels)


Instruction:
Can you tell what is the following Python 3 function doing
def is_head(self):
        if (self._head or self.is_root() or
                len(getattr(self._parent, 'daughters', [None])) == 1):
            return True
        elif any(dtr._head for dtr in self._parent.daughters):
            return False
        return None

Response: Return True if the node is a head.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def preterminals(self):
        nodes = []
        for dtr in self.daughters:
            if isinstance(dtr, UdfTerminal):
                nodes.append(self)
            else:
                nodes.extend(dtr.preterminals())
        return nodes

Response: Return the list of preterminals of this instance.


Instruction:
Can you tell what is the following Python 3 function doing
def load(fh, model):
    graphs = penman.load(fh, cls=XMRSCodec)
    xs = [model.from_triples(g.triples()) for g in graphs]
    return xs

Response: Deserialize PENMAN graphs from a file handle or filename.


Instruction:
Explain what the following Python 3 code does
def loads(s, model):
    graphs = penman.loads(s, cls=XMRSCodec)
    xs = [model.from_triples(g.triples()) for g in graphs]
    return xs

Response: Deserialize PENMAN graphs from a string containing triples


Instruction:
Given the following Python 3 function, write the documentation
def dump(destination, xs, model=None, properties=False, indent=True, **kwargs):
    text = dumps(
        xs, model=model, properties=properties, indent=indent, **kwargs
    )
    if hasattr(destination, 'write'):
        print(text, file=destination)
    else:
        with open(destination, 'w') as fh:
            print(text, file=fh)

Response: Serialize Xmrs objects to PENMAN and write to a file.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def dumps(xs, model=None, properties=False, indent=True, **kwargs):
    xs = list(xs)

    if not xs:
        return ''

    given_class = xs[0].__class__  # assume they are all the same
    if model is None:
        model = xs[0].__class__

    if not hasattr(model, 'to_triples'):
        raise TypeError(
            '{} class does not implement to_triples()'.format(model.__name__)
        )

    # convert MRS to DMRS if necessary; EDS cannot convert
    if given_class.__name__ in ('Mrs', 'Xmrs'):
        xs = [model.from_xmrs(x, **kwargs) for x in xs]
    elif given_class.__name__ == 'Eds' and model.__name__ != 'Eds':
        raise ValueError('Cannot convert EDS to non-EDS')

    codec = XMRSCodec()
    graphs = [
        codec.triples_to_graph(model.to_triples(x, properties=properties))
        for x in xs
    ]

    if 'pretty_print' in kwargs:
        indent = kwargs['pretty_print']

    return penman.dumps(graphs, cls=XMRSCodec, indent=indent)

Response: Serialize Xmrs objects to PENMAN notation.


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")

        data = {}
        data['keyboard'] = KeyboardButton.from_array_list(array.get('keyboard'), list_level=2)
        data['resize_keyboard'] = bool(array.get('resize_keyboard')) if array.get('resize_keyboard') is not None else None
        data['one_time_keyboard'] = bool(array.get('one_time_keyboard')) if array.get('one_time_keyboard') is not None else None
        data['selective'] = bool(array.get('selective')) if array.get('selective') is not None else None

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

Response: Deserialize a new ReplyKeyboardMarkup from a given dictionary.


Instruction:
Create a Python 3 function for
preparing the request for the next request.

Response:
def _prepare_request(self, command, query):
        """
        :param command: The Url command parameter
        :type  command: str

        :param query: will get json encoded.
        :type  query: dict

        :return:
        """
        from luckydonaldUtils.encoding import to_native as n
        from pytgbot.api_types.sendable import Sendable
        from pytgbot.api_types import as_array
        from DictObject import DictObject
        import json

        params = {}
        for key in query.keys():
            element = query[key]
            if element is not None:
                if isinstance(element, Sendable):
                    params[key] = json.dumps(as_array(element))
                else:
                    params[key] = element
        url = self._base_url.format(api_key=n(self.api_key), command=n(command))
        return DictObject(url=url, params=params)