Instruction:
Can you generate a brief explanation for the following Python 3 code
def from_pdf(
        cls, pdf, filename, width=288, height=432, dpi=203, font_path=None,
        center_of_pixel=False, use_bindings=False
    ):
        """
        Filename is 1-8 alphanumeric characters to identify the GRF in ZPL.

        Dimensions and DPI are for a typical 4"x6" shipping label.
        E.g. 432 points / 72 points in an inch / 203 dpi = 6 inches

        Using center of pixel will improve barcode quality but may decrease
        the quality of some text.

        use_bindings=False:
            - Uses subprocess.Popen
            - Forks so there is a memory spike
            - Easier to setup - only needs the gs binary

        use_bindings=True:
            - Uses python-ghostscript
            - Doesn't fork so should use less memory
            - python-ghostscript is a bit buggy
            - May be harder to setup - even if you have updated the gs binary
              there may stil be old libgs* files on your system
        """

        # Most arguments below are based on what CUPS uses
        setpagedevice = [
            '/.HWMargins[0.000000 0.000000 0.000000 0.000000]',
            '/Margins[0 0]'
        ]

        cmd = [
            'gs',
            '-dQUIET',
            '-dPARANOIDSAFER',
            '-dNOPAUSE',
            '-dBATCH',
            '-dNOINTERPOLATE',
            '-sDEVICE=pngmono',
            '-dAdvanceDistance=1000',
            '-r%s' % int(dpi),
            '-dDEVICEWIDTHPOINTS=%s' % int(width),
            '-dDEVICEHEIGHTPOINTS=%s' % int(height),
            '-dFIXEDMEDIA',
            '-dPDFFitPage',
            '-c',
            '<<%s>>setpagedevice' % ' '.join(setpagedevice)
        ]

        if center_of_pixel:
            cmd += ['0 .setfilladjust']

        if font_path and os.path.exists(font_path):
            cmd += ['-I' + font_path]

        if use_bindings:
            import ghostscript
            # python-ghostscript doesn't like reading/writing from
            # stdin/stdout so we need to use temp files
            with tempfile.NamedTemporaryFile() as in_file, \
                 tempfile.NamedTemporaryFile() as out_file:

                in_file.write(pdf)
                in_file.flush()

                # Ghostscript seems to be sensitive to argument order
                cmd[13:13] += [
                    '-sOutputFile=%s' % out_file.name
                ]
                cmd += [
                    '-f', in_file.name
                ]

                try:
                    ghostscript.Ghostscript(*[c.encode('ascii') for c in cmd])
                except Exception as e:
                    raise GRFException(e)

                pngs = out_file.read()
        else:
            from subprocess import PIPE, Popen
            # Ghostscript seems to be sensitive to argument order
            cmd[13:13] += [
                '-sstdout=%stderr',
                '-sOutputFile=%stdout',
            ]
            cmd += [
                '-f', '-'
            ]
            p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
            pngs, stderr = p.communicate(pdf)
            if stderr:
                raise GRFException(stderr)

        # This is what PIL uses to identify PNGs
        png_start = b'\211PNG\r\n\032\n'

        grfs = []
        for png in pngs.split(png_start)[1:]:
            grfs.append(cls.from_image(png_start + png, filename))
        return grfs

Response: Create a new instance of the base class from a PDF file.


Instruction:
How would you explain what the following Python 3 function does
def _optimise_barcodes(
        self, data, min_bar_height=20, min_bar_count=100, max_gap_size=30,
        min_percent_white=0.2, max_percent_white=0.8, **kwargs
    ):
        """
        min_bar_height    = Minimum height of black bars in px. Set this too
                            low and it might pick up text and data matrices,
                            too high and it might pick up borders, tables, etc.
        min_bar_count     = Minimum number of parallel black bars before a
                            pattern is considered a potential barcode.
        max_gap_size      = Biggest white gap in px allowed between black bars.
                            This is only important if you have multiple
                            barcodes next to each other.
        min_percent_white = Minimum percentage of white bars between black
                            bars. This helps to ignore solid rectangles.
        max_percent_white = Maximum percentage of white bars between black
                            bars. This helps to ignore solid rectangles.
        """

        re_bars = re.compile(r'1{%s,}' % min_bar_height)

        bars = {}
        for i, line in enumerate(data):
            for match in re_bars.finditer(line):
                try:
                    bars[match.span()].append(i)
                except KeyError:
                    bars[match.span()] = [i]

        grouped_bars = []
        for span, seen_at in bars.items():
            group = []
            for coords in seen_at:
                if group and coords - group[-1] > max_gap_size:
                    grouped_bars.append((span, group))
                    group = []
                group.append(coords)
            grouped_bars.append((span, group))

        suspected_barcodes = []
        for span, seen_at in grouped_bars:
            if len(seen_at) < min_bar_count:
                continue
            pc_white = len(seen_at) / float(seen_at[-1] - seen_at[0])
            if pc_white >= min_percent_white and pc_white <= max_percent_white:
                suspected_barcodes.append((span, seen_at))

        for span, seen_at in suspected_barcodes:
            barcode = []
            for line in data[seen_at[0]:seen_at[-1]+1]:
                barcode.append(line[span[0]])
            barcode = ''.join(barcode)

            # Do the actual optimisation
            barcode = self._optimise_barcode(barcode)

            barcode = list(barcode)
            barcode.reverse()
            width = span[1] - span[0]
            for i in range(seen_at[0], seen_at[-1]+1):
                line = data[i]
                line = (
                    line[:span[0]] + (barcode.pop() * width) + line[span[1]:]
                )
                data[i] = line

        return data

Response: Optimise barcodes in the data.


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['id'] = u(array.get('id'))
        data['title'] = u(array.get('title'))
        data['prices'] = LabeledPrice.from_array_list(array.get('prices'), list_level=1)

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

Response: Deserialize a new ShippingOption from a given dictionary.


Instruction:
Write a Python 3 script for
converting a string from camel case to underscore.

Response:
def convert_to_underscore(name):
    """ "someFunctionWhatever" -> "some_function_whatever" """
    s1 = _first_cap_re.sub(r'\1_\2', name)
    return _all_cap_re.sub(r'\1_\2', s1).lower()


Instruction:
Make a summary of the following Python 3 code
def func(command, description, link, params_string, returns="On success, the sent Message is returned.", return_type="Message"):
    description_with_tabs = "\t\t" + description.strip().replace("\n", "\n\t\t")
    param_list_args = []
    param_list_kwargs = []
    args = []
    args2 = []
    kwargs = []
    kwargs2 = []
    asserts = []
    str_args = ""
    str_kwargs = ""
    param_strings = params_string.split("\n")
    for param in param_strings:
        assert_commands, assert_comments, param_name, param_type, table, non_buildin_type, param_name_input = parse_param_types(param)
        param_required = table[2].strip()
        param_needed = None
        if param_required == "Yes":
            param_needed = True
        elif param_required == "Optional":
            param_needed = False
        param_description = table[3].strip()
        if param_needed:
            param_list_args.append(Param(param_name, param_type,param_needed, param_description))
            args.append(param_name)
            args2.append("{param_name}={param_name}".format(param_name=param_name))
            str_args += '\t\t:param {key}: {descr}\n\t\t:type  {key}: {type}\n\n'.format(key=param_name, descr=param_description, type=param_type)
            if assert_commands:
                asserts.append("assert({var} is not None)".format(var=param_name))
                asserts.append("assert({ass})".format(ass=" or ".join(assert_commands)) + (("  # {comment}".format(comment=", ".join(assert_comments))) if assert_comments else ""))
        else:
            param_list_kwargs.append(Param(param_name, param_type,param_needed, param_description))
            kwargs.append("{param_name}=None".format(param_name=param_name))
            kwargs2.append("{param_name}={param_name}".format(param_name=param_name))
            str_kwargs += '\t\t:keyword {key}: {descr}\n\t\t:type    {key}: {type}\n\n'.format(key=param_name, descr=param_description, type=param_type)
            if assert_commands:
                asserts.append("assert({var} is None or {ass})".format(var=param_name, ass=" or ".join(assert_commands)) + (("  # {comment}".format(comment=", ".join(assert_comments))) if assert_comments else ""))
    args.extend(kwargs)
    args2.extend(kwargs2)
    asserts_string = "\n\t\t" + "\n\t\t".join(asserts)
    text = ""
    if len(str_args)>0:
        text += '\n\t\tParameters:\n\n'
        text += str_args
    if len(str_kwargs)>0:
        text += '\n\t\tOptional keyword parameters:\n\n'
        text += str_kwargs
    do_args = ['"%s"' % command]
    do_args.extend(args2)
    result = '\tdef {funcname}(self, {params}):\n\t\t"""\n{description_with_tabs}\n\n\t\t{link}\n\n' \
           '{paramshit}\n' \
           '\t\tReturns:\n\n\t\t:return: {returns}\n\t\t:rtype:  {return_type}\n\t\t"""{asserts_with_tabs}\n\t\treturn self.do({do_args})\n\t# end def {funcname}'.format(
        funcname=convert_to_underscore(command),
        params=", ".join(args), description_with_tabs=description_with_tabs, link=link,
        returns=returns, return_type=return_type, command=command, do_args=", ".join(do_args),
        asserts_with_tabs=asserts_string,
        paramshit = text
    )
    result = result.replace("\t", "    ")
    return result

Response: A function that returns a single message.


Instruction:
How would you implement a function in Python 3 that
lives template for pycharm: y = clazz(clazz="$clazz$", parent_clazz="%parent$", description="$desc$", link="$lnk$", params_string="$first_param$")

Response:
def clazz(clazz, parent_clazz, description, link, params_string, init_super_args=None):
    """
    Live template for pycharm:

    y = clazz(clazz="$clazz$", parent_clazz="%parent$", description="$desc$", link="$lnk$", params_string="$first_param$")
    """
    init_description_w_tabs  = description.strip().replace("\n", "\n\t\t")
    clazz_description_w_tabs = description.strip().replace("\n", "\n\t")
    imports = [[], []]
    args = []
    args2 = []
    kwargs = []
    kwargs2 = []
    asserts = []
    str_args = ""
    str_kwargs = ""
    to_array1 = []
    to_array2 = []
    from_array1 = []
    from_array2 = []
    param_strings = params_string.split("\n")
    for param in param_strings:
        assert_commands, assert_comments, param_name, param_type, table, non_buildin_type, param_name_input = parse_param_types(param)
        param_description = table[2].strip()
        param_needed = not param_description.startswith("Optional.")
        asserts.append("")
        if param_needed:
            args.append(param_name)
            str_args += '\n\n\t\t:param {key}: {descr}\n\t\t:type  {key}: {type}'.format(key=param_name, descr=param_description, type=get_type_path(param_type))
            if assert_commands:
                asserts.append("assert({var} is not None)".format(var=param_name))
                asserts.append("assert({ass})".format(ass=" or ".join(assert_commands)) + (("  # {comment}".format(comment=", ".join(assert_comments))) if assert_comments else ""))
            if non_buildin_type:
                to_array1.append('array["{var}"] = self.{var}.to_array()'.format(var=param_name))
                from_array1.append("data['{var}'] = {type}.from_array(array.get('{array_key}'))".format(var=param_name, array_key=param_name_input, type=non_buildin_type))
            else:
                to_array1.append('array["{var}"] = self.{var}'.format(var=param_name))
                from_array2.append("data['{var}'] = array.get('{array_key}')  # type {type}".format(var=param_name, array_key=param_name_input, type=non_buildin_type))
            # end if non_buildin_type
        else:
            kwargs.append("{param_name}=None".format(param_name=param_name))
            str_kwargs += '\n\n\t\t:keyword {key}: {descr}\n\t\t:type    {key}: {type}'.format(key=param_name, descr=param_description, type=param_type)
            if assert_commands:
                asserts.append("assert({var} is None or {ass})".format(var=param_name, ass=" or ".join(assert_commands)) + (("  # {comment}".format(comment=", ".join(assert_comments))) if assert_comments else ""))
            to_array2.append('if self.{var} is not None:'.format(var=param_name))
            if non_buildin_type:
                to_array2.append('\tarray["{var}"] = self.{var}.to_array()'.format(var=param_name))
                from_array2.append("data['{var}'] = {type}.from_array(array.get('{array_key}'))".format(var=param_name, array_key=param_name_input, type=non_buildin_type))
            else:
                to_array2.append('\tarray["{var}"] = self.{var}'.format(var=param_name))
                from_array2.append("data['{var}'] = array.get('{array_key}')  # type {type}".format(var=param_name, array_key=param_name_input, type=non_buildin_type))
        # end if non_buildin_type
        asserts.append("self.{param_name} = {param_name}".format(param_name=param_name))
    param_description = ""
    if len(str_args)>0:
        param_description += '\n\t\tParameters:'
        param_description += str_args
    if len(str_kwargs)>0:
        param_description += '\n\n\n\t\tOptional keyword parameters:'
        param_description += str_kwargs
    args.extend(kwargs)
    to_array = ["array = super({clazz}, self).to_array()".format(clazz=clazz)]
    to_array.extend(to_array1)
    to_array.extend(to_array2)
    from_array = ["data = super({clazz}).from_array(array)".format(clazz=clazz)]
    from_array.extend(from_array1)
    from_array.extend(from_array2)
    from_array.append("return {clazz}(**data)".format(clazz=clazz))
    result = 'class {clazz}({parent_clazz}):\n' \
             '\t"""\n' \
             '\t{clazz_description_w_tabs}\n' \
             '\n' \
             '\t{link}\n' \
             '\t"""\n' \
             '\tdef __init__(self, {params}):\n' \
             '\t\t"""\n' \
             '\t\t{init_description_w_tabs}\n' \
             '\n' \
             '\t\t{link}\n' \
             '\n' \
             '{param_description}\n' \
             '\t\t"""\n' \
             '\t\tsuper({clazz}, self).__init__({init_super_args})\n' \
             '\t\t{asserts_with_tabs}\n' \
             '\t# end def __init__\n' \
             '\n' \
             '\tdef to_array(self):\n' \
             '\t\t{to_array_with_tabs}\n' \
             '\t\treturn array\n' \
             '\t# end def to_array\n' \
             '\n' \
             '\t@staticmethod\n' \
             '\tdef from_array(array):\n' \
             '\t\tif array is None:\n' \
             '\t\t\treturn None\n' \
             '\t\t# end if\n' \
             '\t\t{from_array_with_tabs}\n' \
             '\t# end def from_array\n' \
             '# end class {clazz}\n'.format(
        clazz=clazz, parent_clazz=parent_clazz, params=", ".join(args), param_description = param_description,
        clazz_description_w_tabs=clazz_description_w_tabs, init_description_w_tabs=init_description_w_tabs, link=link,
        asserts_with_tabs="\n\t\t".join(asserts), to_array_with_tabs="\n\t\t".join(to_array),
        from_array_with_tabs="\n\t\t".join(from_array),
        init_super_args=(", ".join(init_super_args) if init_super_args else "")
    )
    result = result.replace("\t", "    ")
    return result


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

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

        :return: dictionary representation of this object.
        :rtype: dict
        """
        array = super(User, self).to_array()
        array['id'] = int(self.id)  # type int
        array['is_bot'] = bool(self.is_bot)  # type bool
        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.username is not None:
            array['username'] = u(self.username)  # py2: type unicode, py3: type str

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

        return array


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

        data = {}
        data['id'] = int(array.get('id'))
        data['is_bot'] = bool(array.get('is_bot'))
        data['first_name'] = u(array.get('first_name'))
        data['last_name'] = u(array.get('last_name')) if array.get('last_name') is not None else None
        data['username'] = u(array.get('username')) if array.get('username') is not None else None
        data['language_code'] = u(array.get('language_code')) if array.get('language_code') is not None else None
        data['_raw'] = array
        return User(**data)

Response: Deserialize a new User from a given dictionary.


Instruction:
Create a Python 3 function to
serialize this Chat to a dictionary.

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

        :return: dictionary representation of this object.
        :rtype: dict
        """
        array = super(Chat, self).to_array()
        array['id'] = int(self.id)  # type int
        array['type'] = u(self.type)  # 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.username is not None:
            array['username'] = u(self.username)  # py2: type unicode, py3: type str

        if self.first_name is not None:
            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.all_members_are_administrators is not None:
            array['all_members_are_administrators'] = bool(self.all_members_are_administrators)  # type bool
        if self.photo is not None:
            array['photo'] = self.photo.to_array()  # type ChatPhoto

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

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

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

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

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


Instruction:
Can you tell what is the following Python 3 function doing
def from_array(array):
        if array is None or not array:
            return None
        # end if
        assert_type_or_raise(array, dict, parameter_name="array")
        from pytgbot.api_types.receivable.media import ChatPhoto
        from pytgbot.api_types.receivable.updates import Message

        data = {}
        data['id'] = int(array.get('id'))
        data['type'] = u(array.get('type'))
        data['title'] = u(array.get('title')) if array.get('title') is not None else None
        data['username'] = u(array.get('username')) if array.get('username') is not None else None
        data['first_name'] = u(array.get('first_name')) if array.get('first_name') is not None else None
        data['last_name'] = u(array.get('last_name')) if array.get('last_name') is not None else None
        data['all_members_are_administrators'] = bool(array.get('all_members_are_administrators')) if array.get('all_members_are_administrators') is not None else None
        data['photo'] = ChatPhoto.from_array(array.get('photo')) if array.get('photo') is not None else None
        data['description'] = u(array.get('description')) if array.get('description') is not None else None
        data['invite_link'] = u(array.get('invite_link')) if array.get('invite_link') is not None else None
        data['pinned_message'] = Message.from_array(array.get('pinned_message')) if array.get('pinned_message') is not None else None
        data['sticker_set_name'] = u(array.get('sticker_set_name')) if array.get('sticker_set_name') is not None else None
        data['can_set_sticker_set'] = bool(array.get('can_set_sticker_set')) if array.get('can_set_sticker_set') is not None else None
        data['_raw'] = array
        return Chat(**data)

Response: Deserialize a new Chat from a given dictionary.


Instruction:
Can you tell what is the following Python 3 function doing
def to_array(self):
        array = super(ChatMember, self).to_array()
        array['user'] = self.user.to_array()  # type User

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

        if self.until_date is not None:
            array['until_date'] = int(self.until_date)  # type int
        if self.can_be_edited is not None:
            array['can_be_edited'] = bool(self.can_be_edited)  # type bool
        if self.can_change_info is not None:
            array['can_change_info'] = bool(self.can_change_info)  # type bool
        if self.can_post_messages is not None:
            array['can_post_messages'] = bool(self.can_post_messages)  # type bool
        if self.can_edit_messages is not None:
            array['can_edit_messages'] = bool(self.can_edit_messages)  # type bool
        if self.can_delete_messages is not None:
            array['can_delete_messages'] = bool(self.can_delete_messages)  # type bool
        if self.can_invite_users is not None:
            array['can_invite_users'] = bool(self.can_invite_users)  # type bool
        if self.can_restrict_members is not None:
            array['can_restrict_members'] = bool(self.can_restrict_members)  # type bool
        if self.can_pin_messages is not None:
            array['can_pin_messages'] = bool(self.can_pin_messages)  # type bool
        if self.can_promote_members is not None:
            array['can_promote_members'] = bool(self.can_promote_members)  # type bool
        if self.can_send_messages is not None:
            array['can_send_messages'] = bool(self.can_send_messages)  # type bool
        if self.can_send_media_messages is not None:
            array['can_send_media_messages'] = bool(self.can_send_media_messages)  # type bool
        if self.can_send_other_messages is not None:
            array['can_send_other_messages'] = bool(self.can_send_other_messages)  # type bool
        if self.can_add_web_page_previews is not None:
            array['can_add_web_page_previews'] = bool(self.can_add_web_page_previews)  # type bool
        return array

Response: Serializes this ChatMember to a dictionary.


Instruction:
Can you generate the documentation for the following Python 3 function
def loads(s, single=False):
    corpus = etree.fromstring(s)
    if single:
        ds = _deserialize_mrs(next(corpus))
    else:
        ds = (_deserialize_mrs(mrs_elem) for mrs_elem in corpus)
    return ds

Response: Deserialize MRX string representations


Instruction:
How would you explain what the following Python 3 function does
def to_array(self):
        array = super(InlineQueryResultArticle, self).to_array()
        # 'type' and 'id' given by superclass
        array['title'] = u(self.title)  # py2: type unicode, py3: type str
        array['input_message_content'] = self.input_message_content.to_array()  # type InputMessageContent
        if self.reply_markup is not None:
            array['reply_markup'] = self.reply_markup.to_array()  # type InlineKeyboardMarkup
        if self.url is not None:
            array['url'] = u(self.url)  # py2: type unicode, py3: type str
        if self.hide_url is not None:
            array['hide_url'] = bool(self.hide_url)  # type bool
        if self.description is not None:
            array['description'] = u(self.description)  # py2: type unicode, py3: type str
        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 InlineQueryResultArticle to a dictionary.


Instruction:
Make a summary of the following Python 3 code
def to_array(self):
        array = super(InlineQueryResultGif, self).to_array()
        # 'type' and 'id' given by superclass
        array['gif_url'] = u(self.gif_url)  # py2: type unicode, py3: type str
        array['thumb_url'] = u(self.thumb_url)  # py2: type unicode, py3: type str
        if self.gif_width is not None:
            array['gif_width'] = int(self.gif_width)  # type int
        if self.gif_height is not None:
            array['gif_height'] = int(self.gif_height)  # type int
        if self.gif_duration is not None:
            array['gif_duration'] = int(self.gif_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

Response: Serializes this InlineQueryResultGif to a dictionary.


Instruction:
Make a summary of the following Python 3 code
def to_array(self):
        array = super(InlineQueryResultAudio, self).to_array()
        # 'type' and 'id' given by superclass
        array['audio_url'] = u(self.audio_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.performer is not None:
            array['performer'] = u(self.performer)  # py2: type unicode, py3: type str
        if self.audio_duration is not None:
            array['audio_duration'] = int(self.audio_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

Response: Serializes this InlineQueryResultAudio to a dictionary.


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

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

        :return: dictionary representation of this object.
        :rtype: dict
        """
        array = super(InlineQueryResultLocation, self).to_array()
        # 'type' and 'id' given by superclass
        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
        if self.live_period is not None:
            array['live_period'] = int(self.live_period)  # 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
        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


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

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

        :return: dictionary representation of this object.
        :rtype: dict
        """
        array = super(InlineQueryResultContact, self).to_array()
        # 'type' and 'id' given by superclass
        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.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


Instruction:
Write a Python 3 script to
serialize 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()
        # 'type' and 'id' given by superclass
        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:
Can you generate the documentation for the following Python 3 function
def to_array(self):
        array = super(InlineQueryResultCachedGif, self).to_array()
        # 'type' and 'id' given by superclass
        array['gif_file_id'] = u(self.gif_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

Response: Serializes this InlineQueryResultCachedGif to a dictionary.


Instruction:
How would you explain what the following Python 3 function does
def to_array(self):
        array = super(InlineQueryResultCachedDocument, self).to_array()
        # 'type' and 'id' given by superclass
        array['title'] = u(self.title)  # py2: type unicode, py3: type str
        array['document_file_id'] = u(self.document_file_id)  # 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

Response: Serializes this InlineQueryResultCachedDocument to a dictionary.


Instruction:
Given the following Python 3 function, write the documentation
def to_array(self):
        array = super(InlineQueryResultCachedVoice, self).to_array()
        # 'type' and 'id' given by superclass
        array['voice_file_id'] = u(self.voice_file_id)  # 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.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 InlineQueryResultCachedVoice to a dictionary.


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

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

        :return: dictionary representation of this object.
        :rtype: dict
        """
        array = super(InputTextMessageContent, self).to_array()
        array['message_text'] = u(self.message_text)  # 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.disable_web_page_preview is not None:
            array['disable_web_page_preview'] = bool(self.disable_web_page_preview)  # type bool
        return array


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

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

        :return: dictionary representation of this object.
        :rtype: dict
        """
        array = super(InputLocationMessageContent, self).to_array()
        array['latitude'] = float(self.latitude)  # type float
        array['longitude'] = float(self.longitude)  # type float
        if self.live_period is not None:
            array['live_period'] = int(self.live_period)  # type int
        return array


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

        data = {}
        data['latitude'] = float(array.get('latitude'))
        data['longitude'] = float(array.get('longitude'))
        data['live_period'] = int(array.get('live_period')) if array.get('live_period') is not None else None

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

Response: Deserialize a new InputLocationMessageContent from a given dictionary.


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

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

        :return: dictionary representation of this object.
        :rtype: dict
        """
        array = super(InputVenueMessageContent, self).to_array()
        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
        return array


Instruction:
Can you generate a brief explanation for the following Python 3 code
def to_array(self):
        array = super(InputContactMessageContent, 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.vcard is not None:
            array['vcard'] = u(self.vcard)  # py2: type unicode, py3: type str
        return array

Response: Serializes this InputContactMessageContent to a dictionary.


Instruction:
Write a Python 3 function for
returning a new object of the specified class.

Response:
def clazz(clazz, parent_clazz, description, link, params_string, init_super_args=None):
    """
    Live template for pycharm:

    y = clazz(clazz="$clazz$", parent_clazz="%parent$", description="$description$", link="$lnk$", params_string="$first_param$")
    """
    variables_needed = []
    variables_optional = []
    imports = set()
    for param in params_string.split("\n"):
        variable = parse_param_types(param)
        # any variable.types has always_is_value => lenght must be 1.
        assert(not any([type_.always_is_value is not None for type_ in variable.types]) or len(variable.types) == 1)
        if variable.optional:
            variables_optional.append(variable)
        else:
            variables_needed.append(variable)
        # end if
        imports.update(variable.all_imports)
    # end for
    imports = list(imports)
    imports.sort()
    if isinstance(parent_clazz, str):
        parent_clazz = to_type(parent_clazz, "parent class")
    assert isinstance(parent_clazz, Type)

    clazz_object = Clazz(imports=imports,
        clazz=clazz, parent_clazz=parent_clazz, link=link, description=description,
        parameters=variables_needed, keywords=variables_optional
    )
    return clazz_object


Instruction:
How would you explain what the following Python 3 function does
def func(command, description, link, params_string, returns="On success, the sent Message is returned.", return_type="Message"):
    variables_needed = []
    variables_optional = []
    imports = set()
    if params_string:  # WHITELISTED_FUNCS have no params
        for param in params_string.split("\n"):
            variable = parse_param_types(param)
            # any variable.types has always_is_value => lenght must be 1.
            assert (not any([type_.always_is_value is not None for type_ in variable.types]) or len(variable.types) == 1)
            if variable.optional:
                variables_optional.append(variable)
            else:
                variables_needed.append(variable)
            # end if
            imports.update(variable.all_imports)
        # end for
    # end if
    imports = list(imports)
    imports.sort()
    returns = Variable(types=as_types(return_type, variable_name="return type"), description=returns)
    func_object = Function(
        imports=imports, api_name=command, link=link, description=description, returns=returns,
        parameters=variables_needed, keywords=variables_optional
    )
    return func_object

Response: Function to create a function object.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def to_type(type_string, variable_name) -> Type:
    # type_string = type_string.strip()
    # remove "list of " and set .is_list accordingly.
    # is_list, type_string = can_strip_prefix(type_string, "list of ")
    # var_type = Type(string=type_string, is_list=is_list)

    var_type = Type(type_string)
    # remove "list of " and set .is_list accordingly.
    is_list = True
    while is_list:
        is_list, var_type.string = can_strip_prefix(var_type.string, "list of ")
        if is_list:
            var_type.is_list += 1
        # end if
    # end for
    if var_type.string == "True":
        var_type.string = "bool"
        var_type.always_is_value = "True"
    # end if
    if var_type.string in ["int", "bool", "float", "object", "None", "str"]:
        var_type.is_builtin = True
    elif var_type.string == "unicode_type":
        var_type.string = "unicode_type"
        var_type.is_builtin = False
        var_type.import_path = "luckydonaldUtils.encoding"
        var_type.description = "py2: unicode, py3: str"
    elif var_type.string in CLASS_TYPE_PATHS:
        var_type.import_path = CLASS_TYPE_PATHS[var_type.string][CLASS_TYPE_PATHS__IMPORT].rstrip(".")
        var_type.is_builtin = False
    else:
        logger.warn(
            "Added unrecognized type in param <{var}>: {type!r}".format(var=variable_name, type=var_type.string))
    # end if
    return var_type

Response: Converts a type string to a new type object.


Instruction:
How would you implement a function in Python 3 that
returns True if the given text starts with the given prefix False otherwise.

Response:
def can_strip_prefix(text:str, prefix:str) -> (bool, str):
    """
    If the given text starts with the given prefix, True and the text without that prefix is returned.
    Else False and the original text is returned.

    Note: the text always is stripped, before returning.

    :param text:
    :param prefix:
    :return: (bool, str)  :class:`bool` whether he text started with given prefix, :class:`str` the text without prefix
    """
    if text.startswith(prefix):
        return True, text[len(prefix):].strip()
    return False, text.strip()


Instruction:
Create a Python 3 function for
returning the class name of the class.

Response:
def class_name(self) -> str:
        """
        Makes the fist letter big, keep the rest of the camelCaseApiName.
        """
        if not self.api_name:  # empty string
            return self.api_name
        # end if
        return self.api_name[0].upper() + self.api_name[1:]


Instruction:
Write a Python 3 script for
returning the class name of the TeleFlask message.

Response:
def class_name_teleflask_message(self) -> str:
        """
        If it starts with `Send` remove that.
        """
        # strip leading "Send"
        name = self.class_name  # "sendPhoto" -> "SendPhoto"
        name = name[4:] if name.startswith('Send') else name  # "SendPhoto" -> "Photo"
        name = name + "Message"  # "Photo" -> "PhotoMessage"

        # e.g. "MessageMessage" will be replaced as "TextMessage"
        # b/c "sendMessage" -> "SendMessage" -> "Message" -> "MessageMessage"  ==> "TextMessage"
        if name in MESSAGE_CLASS_OVERRIDES:
            return MESSAGE_CLASS_OVERRIDES[name]
        # end if
        return name


Instruction:
Explain what the following Python 3 code does
def full(self):
        if self.path:
            if self.name:
                return self.path + "." + self.name
            else:
                return self.path
            # end if
        else:
            if self.name:
                return self.name
            else:
                return ""

Response: Returns the full path of the resource.


Instruction:
Explain what the following Python 3 code does
def from_array_list(required_type, result, list_level, is_builtin):
    logger.debug("Trying parsing as {type}, list_level={list_level}, is_builtin={is_builtin}".format(
        type=required_type.__name__, list_level=list_level, is_builtin=is_builtin
    ))
    if list_level > 0:
        assert isinstance(result, (list, tuple))
        return [from_array_list(required_type, obj, list_level-1, is_builtin) for obj in result]
    # end if
    if is_builtin:
        if isinstance(result, required_type):
            logger.debug("Already is correct type.")
            return required_type(result)
        elif isinstance(required_type, unicode_type):  # handle str, so emojis work for py2.
            return u(result)
        else:
            import ast
            logger.warn("Trying parsing with ast.literal_eval()...")
            return ast.literal_eval(str(result))  # raises ValueError if it could not parse
        # end if
    else:
        return required_type.from_array(result)

Response: Parses the result of a list of objects into a new object of type required_type.


Instruction:
How would you code a function in Python 3 to
convert a dict or list of objects to a json - like representation of a variable supporting types with a. to_array function.

Response:
def as_array(obj):
    """
    Creates an json-like representation of a variable, supporting types with a `.to_array()` function.

    :rtype: dict|list|str|int|float|bool|None
    """
    if hasattr(obj, "to_array"):
        return obj.to_array()
    elif isinstance(obj, (list, tuple)):
        return [as_array(x) for x in obj]
    elif isinstance(obj, dict):
        return {key:as_array(obj[key]) for key in obj.keys()}
    else:
        _json_dumps(obj)  # raises error if is wrong json
        return obj


Instruction:
Given the following Python 3 function, write the documentation
def from_array_list(cls, result, list_level):
        return from_array_list(cls, result, list_level, is_builtin=False)

Response: Tries to parse the result as type given in required_type while traversing into lists as often as specified in list_level.


Instruction:
Given the following Python 3 function, write the documentation
def do(self, command, files=None, use_long_polling=False, request_timeout=None, **query):
        url, params = self._prepare_request(command, query)
        return {
            "url": url, "params": params, "files": files, "stream": use_long_polling,
            "verify": True,  # No self signed certificates. Telegram should be trustworthy anyway...
            "timeout": request_timeout
        }

Response: Send a request to the API.


Instruction:
Can you tell what is the following Python 3 function doing
def to_array(self):
        array = super(Update, self).to_array()
        array['update_id'] = int(self.update_id)  # type int
        if self.message is not None:
            array['message'] = self.message.to_array()  # type Message
        if self.edited_message is not None:
            array['edited_message'] = self.edited_message.to_array()  # type Message
        if self.channel_post is not None:
            array['channel_post'] = self.channel_post.to_array()  # type Message
        if self.edited_channel_post is not None:
            array['edited_channel_post'] = self.edited_channel_post.to_array()  # type Message
        if self.inline_query is not None:
            array['inline_query'] = self.inline_query.to_array()  # type InlineQuery
        if self.chosen_inline_result is not None:
            array['chosen_inline_result'] = self.chosen_inline_result.to_array()  # type ChosenInlineResult
        if self.callback_query is not None:
            array['callback_query'] = self.callback_query.to_array()  # type CallbackQuery
        if self.shipping_query is not None:
            array['shipping_query'] = self.shipping_query.to_array()  # type ShippingQuery
        if self.pre_checkout_query is not None:
            array['pre_checkout_query'] = self.pre_checkout_query.to_array()  # type PreCheckoutQuery
        return array

Response: Serializes this Update to a dictionary.


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

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

        :return: dictionary representation of this object.
        :rtype: dict
        """
        array = super(WebhookInfo, self).to_array()
        array['url'] = u(self.url)  # py2: type unicode, py3: type str
        array['has_custom_certificate'] = bool(self.has_custom_certificate)  # type bool
        array['pending_update_count'] = int(self.pending_update_count)  # type int
        if self.last_error_date is not None:
            array['last_error_date'] = int(self.last_error_date)  # type int
        if self.last_error_message is not None:
            array['last_error_message'] = u(self.last_error_message)  # py2: type unicode, py3: type str
        if self.max_connections is not None:
            array['max_connections'] = int(self.max_connections)  # type int
        if self.allowed_updates is not None:
            array['allowed_updates'] = self._as_array(self.allowed_updates)  # type list of str
        return array


Instruction:
Can you generate a brief explanation for the following Python 3 code
def to_array(self):
        array = super(Message, self).to_array()
        array['message_id'] = int(self.message_id)  # type int
        array['date'] = int(self.date)  # type int
        array['chat'] = self.chat.to_array()  # type Chat
        if self.from_peer is not None:
            array['from'] = self.from_peer.to_array()  # type User
        if self.forward_from is not None:
            array['forward_from'] = self.forward_from.to_array()  # type User
        if self.forward_from_chat is not None:
            array['forward_from_chat'] = self.forward_from_chat.to_array()  # type Chat
        if self.forward_from_message_id is not None:
            array['forward_from_message_id'] = int(self.forward_from_message_id)  # type int
        if self.forward_signature is not None:
            array['forward_signature'] = u(self.forward_signature)  # py2: type unicode, py3: type str
        if self.forward_date is not None:
            array['forward_date'] = int(self.forward_date)  # type int
        if self.reply_to_message is not None:
            array['reply_to_message'] = self.reply_to_message.to_array()  # type Message
        if self.edit_date is not None:
            array['edit_date'] = int(self.edit_date)  # type int
        if self.media_group_id is not None:
            array['media_group_id'] = u(self.media_group_id)  # py2: type unicode, py3: type str
        if self.author_signature is not None:
            array['author_signature'] = u(self.author_signature)  # py2: type unicode, py3: type str
        if self.text is not None:
            array['text'] = u(self.text)  # py2: type unicode, py3: type str
        if self.entities is not None:
            array['entities'] = self._as_array(self.entities)  # type list of MessageEntity
        if self.caption_entities is not None:
            array['caption_entities'] = self._as_array(self.caption_entities)  # type list of MessageEntity
        if self.audio is not None:
            array['audio'] = self.audio.to_array()  # type Audio
        if self.document is not None:
            array['document'] = self.document.to_array()  # type Document
        if self.animation is not None:
            array['animation'] = self.animation.to_array()  # type Animation
        if self.game is not None:
            array['game'] = self.game.to_array()  # type Game
        if self.photo is not None:
            array['photo'] = self._as_array(self.photo)  # type list of PhotoSize
        if self.sticker is not None:
            array['sticker'] = self.sticker.to_array()  # type Sticker
        if self.video is not None:
            array['video'] = self.video.to_array()  # type Video
        if self.voice is not None:
            array['voice'] = self.voice.to_array()  # type Voice
        if self.video_note is not None:
            array['video_note'] = self.video_note.to_array()  # type VideoNote
        if self.caption is not None:
            array['caption'] = u(self.caption)  # py2: type unicode, py3: type str
        if self.contact is not None:
            array['contact'] = self.contact.to_array()  # type Contact
        if self.location is not None:
            array['location'] = self.location.to_array()  # type Location
        if self.venue is not None:
            array['venue'] = self.venue.to_array()  # type Venue
        if self.new_chat_members is not None:
            array['new_chat_members'] = self._as_array(self.new_chat_members)  # type list of User
        if self.left_chat_member is not None:
            array['left_chat_member'] = self.left_chat_member.to_array()  # type User
        if self.new_chat_title is not None:
            array['new_chat_title'] = u(self.new_chat_title)  # py2: type unicode, py3: type str
        if self.new_chat_photo is not None:
            array['new_chat_photo'] = self._as_array(self.new_chat_photo)  # type list of PhotoSize
        if self.delete_chat_photo is not None:
            array['delete_chat_photo'] = bool(self.delete_chat_photo)  # type bool
        if self.group_chat_created is not None:
            array['group_chat_created'] = bool(self.group_chat_created)  # type bool
        if self.supergroup_chat_created is not None:
            array['supergroup_chat_created'] = bool(self.supergroup_chat_created)  # type bool
        if self.channel_chat_created is not None:
            array['channel_chat_created'] = bool(self.channel_chat_created)  # type bool
        if self.migrate_to_chat_id is not None:
            array['migrate_to_chat_id'] = int(self.migrate_to_chat_id)  # type int
        if self.migrate_from_chat_id is not None:
            array['migrate_from_chat_id'] = int(self.migrate_from_chat_id)  # type int
        if self.pinned_message is not None:
            array['pinned_message'] = self.pinned_message.to_array()  # type Message
        if self.invoice is not None:
            array['invoice'] = self.invoice.to_array()  # type Invoice
        if self.successful_payment is not None:
            array['successful_payment'] = self.successful_payment.to_array()  # type SuccessfulPayment
        if self.connected_website is not None:
            array['connected_website'] = u(self.connected_website)  # py2: type unicode, py3: type str
        if self.passport_data is not None:
            array['passport_data'] = self.passport_data.to_array()  # type PassportData
        return array

Response: Serializes this Message 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 ..receivable.peer import User, Chat
        from ..receivable.media import Animation, Audio, Contact, Document, Game, Location, MessageEntity, PhotoSize
        from ..receivable.media import Sticker, Venue, Video, VideoNote, Voice
        from ..receivable.payments import Invoice, SuccessfulPayment
        from ..receivable.passport import PassportData

        data = {}
        data['message_id'] = int(array.get('message_id'))
        data['date'] = int(array.get('date'))
        data['chat'] = Chat.from_array(array.get('chat'))
        data['from_peer'] = User.from_array(array.get('from')) if array.get('from') is not None else None
        data['forward_from'] = User.from_array(array.get('forward_from')) if array.get('forward_from') is not None else None
        data['forward_from_chat'] = Chat.from_array(array.get('forward_from_chat')) if array.get('forward_from_chat') is not None else None
        data['forward_from_message_id'] = int(array.get('forward_from_message_id')) if array.get('forward_from_message_id') is not None else None
        data['forward_signature'] = u(array.get('forward_signature')) if array.get('forward_signature') is not None else None
        data['forward_date'] = int(array.get('forward_date')) if array.get('forward_date') is not None else None
        data['reply_to_message'] = Message.from_array(array.get('reply_to_message')) if array.get('reply_to_message') is not None else None
        data['edit_date'] = int(array.get('edit_date')) if array.get('edit_date') is not None else None
        data['media_group_id'] = u(array.get('media_group_id')) if array.get('media_group_id') is not None else None
        data['author_signature'] = u(array.get('author_signature')) if array.get('author_signature') is not None else None
        data['text'] = u(array.get('text')) if array.get('text') is not None else None
        data['entities'] = MessageEntity.from_array_list(array.get('entities'), list_level=1) if array.get('entities') is not None else None
        data['caption_entities'] = MessageEntity.from_array_list(array.get('caption_entities'), list_level=1) if array.get('caption_entities') is not None else None
        data['audio'] = Audio.from_array(array.get('audio')) if array.get('audio') is not None else None
        data['document'] = Document.from_array(array.get('document')) if array.get('document') is not None else None
        data['animation'] = Animation.from_array(array.get('animation')) if array.get('animation') is not None else None
        data['game'] = Game.from_array(array.get('game')) if array.get('game') is not None else None
        data['photo'] = PhotoSize.from_array_list(array.get('photo'), list_level=1) if array.get('photo') is not None else None
        data['sticker'] = Sticker.from_array(array.get('sticker')) if array.get('sticker') is not None else None
        data['video'] = Video.from_array(array.get('video')) if array.get('video') is not None else None
        data['voice'] = Voice.from_array(array.get('voice')) if array.get('voice') is not None else None
        data['video_note'] = VideoNote.from_array(array.get('video_note')) if array.get('video_note') is not None else None
        data['caption'] = u(array.get('caption')) if array.get('caption') is not None else None
        data['contact'] = Contact.from_array(array.get('contact')) if array.get('contact') is not None else None
        data['location'] = Location.from_array(array.get('location')) if array.get('location') is not None else None
        data['venue'] = Venue.from_array(array.get('venue')) if array.get('venue') is not None else None
        data['new_chat_members'] = User.from_array_list(array.get('new_chat_members'), list_level=1) if array.get('new_chat_members') is not None else None
        data['left_chat_member'] = User.from_array(array.get('left_chat_member')) if array.get('left_chat_member') is not None else None
        data['new_chat_title'] = u(array.get('new_chat_title')) if array.get('new_chat_title') is not None else None
        data['new_chat_photo'] = PhotoSize.from_array_list(array.get('new_chat_photo'), list_level=1) if array.get('new_chat_photo') is not None else None
        data['delete_chat_photo'] = bool(array.get('delete_chat_photo')) if array.get('delete_chat_photo') is not None else None
        data['group_chat_created'] = bool(array.get('group_chat_created')) if array.get('group_chat_created') is not None else None
        data['supergroup_chat_created'] = bool(array.get('supergroup_chat_created')) if array.get('supergroup_chat_created') is not None else None
        data['channel_chat_created'] = bool(array.get('channel_chat_created')) if array.get('channel_chat_created') is not None else None
        data['migrate_to_chat_id'] = int(array.get('migrate_to_chat_id')) if array.get('migrate_to_chat_id') is not None else None
        data['migrate_from_chat_id'] = int(array.get('migrate_from_chat_id')) if array.get('migrate_from_chat_id') is not None else None
        data['pinned_message'] = Message.from_array(array.get('pinned_message')) if array.get('pinned_message') is not None else None
        data['invoice'] = Invoice.from_array(array.get('invoice')) if array.get('invoice') is not None else None
        data['successful_payment'] = SuccessfulPayment.from_array(array.get('successful_payment')) if array.get('successful_payment') is not None else None
        data['connected_website'] = u(array.get('connected_website')) if array.get('connected_website') is not None else None
        data['passport_data'] = PassportData.from_array(array.get('passport_data')) if array.get('passport_data') is not None else None
        data['_raw'] = array
        return Message(**data)

Response: Deserialize a new Message from a given dictionary.


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

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

        :return: dictionary representation of this object.
        :rtype: dict
        """
        array = super(CallbackQuery, self).to_array()
        array['id'] = u(self.id)  # py2: type unicode, py3: type str
        array['from'] = self.from_peer.to_array()  # type User
        array['chat_instance'] = u(self.chat_instance)  # py2: type unicode, py3: type str
        if self.message is not None:
            array['message'] = self.message.to_array()  # type Message
        if self.inline_message_id is not None:
            array['inline_message_id'] = u(self.inline_message_id)  # py2: type unicode, py3: type str
        if self.data is not None:
            array['data'] = u(self.data)  # py2: type unicode, py3: type str
        if self.game_short_name is not None:
            array['game_short_name'] = u(self.game_short_name)  # py2: type unicode, py3: type str
        return array


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

        data = {}
        data['id'] = u(array.get('id'))
        data['from_peer'] = User.from_array(array.get('from'))
        data['chat_instance'] = u(array.get('chat_instance'))
        data['message'] = Message.from_array(array.get('message')) if array.get('message') is not None else None
        data['inline_message_id'] = u(array.get('inline_message_id')) if array.get('inline_message_id') is not None else None
        data['data'] = u(array.get('data')) if array.get('data') is not None else None
        data['game_short_name'] = u(array.get('game_short_name')) if array.get('game_short_name') is not None else None
        data['_raw'] = array
        return CallbackQuery(**data)

Response: Deserialize a new CallbackQuery from a given dictionary.


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

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

        :return: dictionary representation of this object.
        :rtype: dict
        """
        array = super(ResponseParameters, self).to_array()
        if self.migrate_to_chat_id is not None:
            array['migrate_to_chat_id'] = int(self.migrate_to_chat_id)  # type int
        if self.retry_after is not None:
            array['retry_after'] = int(self.retry_after)  # type int
        return array


Instruction:
Write a Python 3 function for
returning an Xmrs object for all the RMRS components.

Response:
def Rmrs(top=None, index=None, xarg=None,
         eps=None, args=None, hcons=None, icons=None,
         lnk=None, surface=None, identifier=None, vars=None):
    """
    Construct an :class:`Xmrs` from RMRS components.

    Robust Minimal Recursion Semantics (RMRS) are like MRS, but all
    predications have a nodeid ("anchor"), and arguments are not
    contained by the source predications, but instead reference the
    nodeid of their predication.

    Args:
        top: the TOP (or maybe LTOP) variable
        index: the INDEX variable
        xarg: the XARG variable
        eps: an iterable of EPs
        args: a nested mapping of `{nodeid: {rargname: value}}`
        hcons: an iterable of HandleConstraint objects
        icons: an iterable of IndividualConstraint objects
        lnk: the Lnk object associating the MRS to the surface form
        surface: the surface string
        identifier: a discourse-utterance id
        vars: a mapping of variables to a list of `(property, value)`
            pairs

    Example:

    >>> m = Rmrs(
    >>>     top='h0',
    >>>     index='e2',
    >>>     eps=[ElementaryPredication(
    >>>         10000,
    >>>         Pred.surface('_rain_v_1_rel'),
    >>>         'h1'
    >>>     )],
    >>>     args={10000: {'ARG0': 'e2'}},
    >>>     hcons=[HandleConstraint('h0', 'qeq', 'h1'),
    >>>     vars={'e2': {'SF': 'prop-or-ques', 'TENSE': 'present'}}
    >>> )
    """
    eps = list(eps or [])
    args = list(args or [])
    if vars is None: vars = {}
    for arg in args:
        if arg.nodeid is None:
            raise XmrsStructureError("RMRS args must have a nodeid.")
    # make the EPs more MRS-like (with arguments)
    for ep in eps:
        if ep.nodeid is None:
            raise XmrsStructureError("RMRS EPs must have a nodeid.")
        epargs = ep.args
        for rargname, value in args.get(ep.nodeid, {}).items():
            epargs[rargname] = value
    hcons = list(hcons or [])
    icons = list(icons or [])
    return Xmrs(top=top, index=index, xarg=xarg,
                eps=eps, hcons=hcons, icons=icons, vars=vars,
                lnk=lnk, surface=surface, identifier=identifier)


Instruction:
Can you create a Python 3 function that
returns a new instance of the class cls from xmrs.

Response:
def from_xmrs(cls, xmrs, **kwargs):
        """
        Facilitate conversion among subclasses.

        Args:
            xmrs (:class:`Xmrs`): instance to convert from; possibly
                an instance of a subclass, such as :class:`Mrs` or
                :class:`Dmrs`
            **kwargs: additional keyword arguments that may be used
                by a subclass's redefinition of :meth:`from_xmrs`.
        """
        x = cls()
        x.__dict__.update(xmrs.__dict__)
        return x


Instruction:
How would you code a function in Python 3 to
incorporate the list of EPs given by eps*.

Response:
def add_eps(self, eps):
        """
        Incorporate the list of EPs given by *eps*.
        """
        # (nodeid, pred, label, args, lnk, surface, base)
        _nodeids, _eps, _vars = self._nodeids, self._eps, self._vars
        for ep in eps:
            try:
                if not isinstance(ep, ElementaryPredication):
                    ep = ElementaryPredication(*ep)
            except TypeError:
                raise XmrsError('Invalid EP data: {}'.format(repr(ep)))
            # eplen = len(ep)
            # if eplen < 3:
            #     raise XmrsError(
            #         'EPs must have length >= 3: (nodeid, pred, label, ...)'
            #     )
            nodeid, lbl = ep.nodeid, ep.label
            if nodeid in _eps:
                raise XmrsError(
                    'EP already exists in Xmrs: {} ({})'
                    .format(nodeid, ep[1])
                )
            _nodeids.append(nodeid)
            _eps[nodeid] = ep
            if lbl is not None:
                _vars[lbl]['refs']['LBL'].append(nodeid)
            for role, val in ep.args.items():
                # if the val is not in _vars, it might still be a
                # variable; check with var_re
                if val in _vars or var_re.match(val):
                    vardict = _vars[val]
                    vardict['refs'][role].append(nodeid)


Instruction:
Explain what the following Python 3 code does
def add_hcons(self, hcons):
        # (hi, relation, lo)
        _vars = self._vars
        _hcons = self._hcons
        for hc in hcons:
            try:
                if not isinstance(hc, HandleConstraint):
                    hc = HandleConstraint(*hc)
            except TypeError:
                raise XmrsError('Invalid HCONS data: {}'.format(repr(hc)))

            hi = hc.hi
            lo = hc.lo
            if hi in _hcons:
                raise XmrsError(
                    'Handle constraint already exists for hole %s.' % hi
                )
            _hcons[hi] = hc
            # the following should also ensure lo and hi are in _vars
            if 'hcrefs' not in _vars[lo]:
                _vars[lo]['hcrefs'] = []
            for role, refs in _vars[hi]['refs'].items():
                for nodeid in refs:
                    _vars[lo]['hcrefs'].append((nodeid, role, hi))

Response: Add HandleConstraints to the internal list of HandleConstraints.


Instruction:
Make a summary of the following Python 3 code
def add_icons(self, icons):
        _vars, _icons = self._vars, self._icons
        for ic in icons:
            try:
                if not isinstance(ic, IndividualConstraint):
                    ic = IndividualConstraint(*ic)
            except TypeError:
                raise XmrsError('Invalid ICONS data: {}'.format(repr(ic)))
            left = ic.left
            right = ic.right
            if left not in _icons:
                _icons[left] = []
            _icons[left].append(ic)
            # the following should also ensure left and right are in _vars
            if 'icrefs' not in _vars[right]:
                _vars[right]['icrefs'] = []
            _vars[right]['icrefs'].append(ic)
            _vars[left]

Response: Add the given ICONS to the internal list of the internal list.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def nodeid(self, iv, quantifier=False):
        return next(iter(self.nodeids(ivs=[iv], quantifier=quantifier)), None)

Response: Returns the nodeid of the predication selected by iv.


Instruction:
Given the following Python 3 function, write the documentation
def nodeids(self, ivs=None, quantifier=None):
        if ivs is None:
            nids = list(self._nodeids)
        else:
            _vars = self._vars
            nids = []
            for iv in ivs:
                if iv in _vars and IVARG_ROLE in _vars[iv]['refs']:
                    nids.extend(_vars[iv]['refs'][IVARG_ROLE])
                else:
                    raise KeyError(iv)
        if quantifier is not None:
            nids = [n for n in nids if self.ep(n).is_quantifier()==quantifier]
        return nids

Response: Return the list of nodeids given by ivs or all nodeids.


Instruction:
How would you explain what the following Python 3 function does
def eps(self, nodeids=None):
        if nodeids is None: nodeids = self._nodeids
        _eps = self._eps
        return [_eps[nodeid] for nodeid in nodeids]

Response: Return the EPs with the given nodeid or all EPs.


Instruction:
Explain what the following Python 3 code does
def icons(self, left=None):
        if left is not None:
            return self._icons[left]
        else:
            return list(chain.from_iterable(self._icons.values()))

Response: Returns the ICONS with left variable left or all ICONS.


Instruction:
How would you explain what the following Python 3 function does
def properties(self, var_or_nodeid, as_list=False):
        props = []
        if var_or_nodeid in self._vars:
            props = self._vars[var_or_nodeid]['props']
        elif var_or_nodeid in self._eps:
            var = self._eps[var_or_nodeid][3].get(IVARG_ROLE)
            props = self._vars.get(var, {}).get('props', [])
        else:
            raise KeyError(var_or_nodeid)
        if not as_list:
            props = dict(props)
        return props

Response: Returns a dictionary of variable properties for a given variable or nodeid.


Instruction:
Can you create a Python 3 function that
returns the Pred objects for the given nodeids or all Pred objects if nodeids is None.

Response:
def preds(self, nodeids=None):
        """
        Return the Pred objects for *nodeids*, or all Preds.

        Args:
            nodeids: an iterable of nodeids of predications to return
                Preds from; if `None`, return all Preds
        """
        if nodeids is None: nodeids = self._nodeids
        _eps = self._eps
        return [_eps[nid][1] for nid in nodeids]


Instruction:
Can you generate the documentation for the following Python 3 function
def labels(self, nodeids=None):
        if nodeids is None: nodeids = self._nodeids
        _eps = self._eps
        return [_eps[nid][2] for nid in nodeids]

Response: Returns the list of labels for the given nodeids or all labels if nodeids is None.


Instruction:
Write a Python 3 script to
return the arguments going from *nodeid* to other predications.

Response:
def outgoing_args(self, nodeid):
        """
        Return the arguments going from *nodeid* to other predications.

        Valid arguments include regular variable arguments and scopal
        (label-selecting or HCONS) arguments. MOD/EQ
        links, intrinsic arguments, and constant arguments are not
        included.

        Args:
            nodeid: the nodeid of the EP that is the arguments' source
        Returns:
            dict: `{role: tgt}`
        """
        _vars = self._vars
        _hcons = self._hcons
        args = self.args(nodeid)  # args is a copy; we can edit it
        for arg, val in list(args.items()):
            # don't include constant args or intrinsic args
            if arg == IVARG_ROLE or val not in _vars:
                del args[arg]
            else:
                refs = _vars[val]['refs']
                # don't include if not HCONS or pointing to other IV or LBL
                if not (val in _hcons or IVARG_ROLE in refs or 'LBL' in refs):
                    del args[arg]
        return args


Instruction:
Write a Python 3 script for
returning the arguments that target *nodeid*.

Response:
def incoming_args(self, nodeid):
        """
        Return the arguments that target *nodeid*.

        Valid arguments include regular variable arguments and scopal
        (label-selecting or HCONS) arguments. MOD/EQ
        links and intrinsic arguments are not included.

        Args:
            nodeid: the nodeid of the EP that is the arguments' target
        Returns:
            dict: `{source_nodeid: {rargname: value}}`
        """
        _vars = self._vars
        ep = self._eps[nodeid]
        lbl = ep[2]
        iv = ep[3].get(IVARG_ROLE)
        in_args_list = []
        # variable args
        if iv in _vars:
            for role, nids in _vars[iv]['refs'].items():
                # ignore intrinsic args, even if shared
                if role != IVARG_ROLE:
                    in_args_list.append((nids, role, iv))
        if lbl in _vars:
            for role, nids in _vars[lbl]['refs'].items():
                # basic label equality isn't "incoming"; ignore
                if role != 'LBL':
                    in_args_list.append((nids, role, lbl))
            for nid, role, hi in _vars[lbl].get('hcrefs', []):
                in_args_list.append(([nid], role, hi))
        in_args = {}
        for nids, role, tgt in in_args_list:
            for nid in nids:
                if nid not in in_args:
                    in_args[nid] = {}
                in_args[nid][role] = tgt
        return in_args


Instruction:
Can you create a Python 3 function that
returns the heads of the labelset selected by label.

Response:
def labelset_heads(self, label):
        """
        Return the heads of the labelset selected by *label*.

        Args:
            label: the label from which to find head nodes/EPs.
        Returns:
            An iterable of nodeids.
        """
        _eps = self._eps
        _vars = self._vars
        _hcons = self._hcons
        nodeids = {nodeid: _eps[nodeid][3].get(IVARG_ROLE, None)
                for nodeid in _vars[label]['refs']['LBL']}
        if len(nodeids) <= 1:
            return list(nodeids)

        scope_sets = {}
        for nid in nodeids:
            scope_sets[nid] = _ivs_in_scope(nid, _eps, _vars, _hcons)

        out = {}
        for n in nodeids:
            out[n] = 0
            for role, val in _eps[n][3].items():
                if role == IVARG_ROLE or role == CONSTARG_ROLE:
                    continue
                elif any(val in s for n2, s in scope_sets.items() if n2 != n):
                    out[n] += 1

        candidates = [n for n, out_deg in out.items() if out_deg == 0]
        rank = {}
        for n in candidates:
            iv = nodeids[n]
            pred = _eps[n][1]
            if iv in _vars and self.nodeid(iv, quantifier=True) is not None:
                rank[n] = 0
            elif pred.is_quantifier():
                rank[n] = 0
            elif pred.type == Pred.ABSTRACT:
                rank[n] = 2
            else:
                rank[n] = 1

        return sorted(candidates, key=lambda n: rank[n])


Instruction:
Explain what the following Python 3 code does
def subgraph(self, nodeids):
        _eps, _vars = self._eps, self._vars
        _hcons, _icons = self._hcons, self._icons
        top = index = xarg = None
        eps = [_eps[nid] for nid in nodeids]
        lbls = set(ep[2] for ep in eps)
        hcons = []
        icons = []
        subvars = {}
        if self.top:
            top = self.top
            tophc = _hcons.get(top, None)
            if tophc is not None and tophc[2] in lbls:
                subvars[top] = {}
            elif top not in lbls:
                top = None  # nevermind, set it back to None
        # do index after we know if it is an EPs intrinsic variable.
        # what about xarg? I'm not really sure.. just put it in
        if self.xarg:
            xarg = self.xarg
            subvars[self.xarg] = _vars[self.xarg]['props']
        subvars.update((lbl, {}) for lbl in lbls)
        subvars.update(
            (var, _vars[var]['props'])
            for ep in eps for var in ep[3].values()
            if var in _vars
        )
        if self.index in subvars:
            index = self.index
        # hcons and icons; only if the targets exist in the new subgraph
        for var in subvars:
            hc = _hcons.get(var, None)
            if hc is not None and hc[2] in lbls:
                hcons.append(hc)
            for ic in _icons.get(var, []):
                if ic[0] in subvars and ic[2] in subvars:
                    icons.append(ic)
        return Xmrs(
            top=top, index=index, xarg=xarg,
            eps=eps, hcons=hcons, icons=icons, vars=subvars,
            lnk=self.lnk, surface=self.surface, identifier=self.identifier
        )

Response: Returns an Xmrs object with only the specified nodeids.


Instruction:
Make a summary of the following Python 3 code
def is_connected(self):
        nids = set(self._nodeids)  # the nids left to find
        if len(nids) == 0:
            raise XmrsError('Cannot compute connectedness of an empty Xmrs.')
        # build a basic dict graph of relations
        edges = []
        # label connections
        for lbl in self.labels():
            lblset = self.labelset(lbl)
            edges.extend((x, y) for x in lblset for y in lblset if x != y)
        # argument connections
        _vars = self._vars
        for nid in nids:
            for rarg, tgt in self.args(nid).items():
                if tgt not in _vars:
                    continue
                if IVARG_ROLE in _vars[tgt]['refs']:
                    tgtnids = list(_vars[tgt]['refs'][IVARG_ROLE])
                elif tgt in self._hcons:
                    tgtnids = list(self.labelset(self.hcon(tgt)[2]))
                elif 'LBL' in _vars[tgt]['refs']:
                    tgtnids = list(_vars[tgt]['refs']['LBL'])
                else:
                    tgtnids = []
                # connections are bidirectional
                edges.extend((nid, t) for t in tgtnids if nid != t)
                edges.extend((t, nid) for t in tgtnids if nid != t)
        g = {nid: set() for nid in nids}
        for x, y in edges:
            g[x].add(y)
        connected_nids = _bfs(g)
        if connected_nids == nids:
            return True
        elif connected_nids.difference(nids):
            raise XmrsError(
                'Possibly bogus nodeids: {}'
                .format(', '.join(connected_nids.difference(nids)))
            )
        return False

Response: Return True if the Xmrs represents a connected graph.


Instruction:
Can you create a Python 3 function that
checks that the Xmrs is well - formed and that all of the EPs in the Xmrs are well - formed.

Response:
def validate(self):
        """
        Check that the Xmrs is well-formed.

        The Xmrs is analyzed and a list of problems is compiled. If
        any problems exist, an :exc:`XmrsError` is raised with the list
        joined as the error message. A well-formed Xmrs has the
        following properties:

        * All predications have an intrinsic variable
        * Every intrinsic variable belongs one predication and maybe
          one quantifier
        * Every predication has no more than one quantifier
        * All predications have a label
        * The graph of predications form a net (i.e. are connected).
          Connectivity can be established with variable arguments,
          QEQs, or label-equality.
        * The lo-handle for each QEQ must exist as the label of a
          predication
        """
        errors = []
        ivs, bvs = {}, {}
        _vars = self._vars
        _hcons = self._hcons
        labels = defaultdict(set)
        # ep_args = {}
        for ep in self.eps():
            nid, lbl, args, is_q = (
                ep.nodeid, ep.label, ep.args, ep.is_quantifier()
            )
            if lbl is None:
                errors.append('EP ({}) is missing a label.'.format(nid))
            labels[lbl].add(nid)
            iv = args.get(IVARG_ROLE)
            if iv is None:
                errors.append('EP {nid} is missing an intrinsic variable.'
                              .format(nid))
            if is_q:
                if iv in bvs:
                    errors.append('{} is the bound variable for more than '
                                  'one quantifier.'.format(iv))
                bvs[iv] = nid
            else:
                if iv in ivs:
                    errors.append('{} is the intrinsic variable for more '
                                  'than one EP.'.format(iv))
                ivs[iv] = nid
            # ep_args[nid] = args
        for hc in _hcons.values():
            if hc[2] not in labels:
                errors.append('Lo variable of HCONS ({} {} {}) is not the '
                              'label of any EP.'.format(*hc))
        if not self.is_connected():
            errors.append('Xmrs structure is not connected.')
        if errors:
            raise XmrsError('\n'.join(errors))


Instruction:
Write a Python 3 script for
encoding the Mrs as a dictionary suitable for JSON serialization.

Response:
def to_dict(self, short_pred=True, properties=True):
        """
        Encode the Mrs as a dictionary suitable for JSON serialization.
        """
        def _lnk(obj): return {'from': obj.cfrom, 'to': obj.cto}
        def _ep(ep, short_pred=True):
            p = ep.pred.short_form() if short_pred else ep.pred.string
            d = dict(label=ep.label, predicate=p, arguments=ep.args)
            if ep.lnk is not None: d['lnk'] = _lnk(ep)
            return d
        def _hcons(hc): return {'relation':hc[1], 'high':hc[0], 'low':hc[2]}
        def _icons(ic): return {'relation':ic[1], 'left':ic[0], 'right':ic[2]}
        def _var(v):
            d = {'type': var_sort(v)}
            if properties and self.properties(v):
                d['properties'] = self.properties(v)
            return d

        d = dict(
            relations=[_ep(ep, short_pred=short_pred) for ep in self.eps()],
            constraints=([_hcons(hc) for hc in self.hcons()] +
                         [_icons(ic) for ic in self.icons()]),
            variables={v: _var(v) for v in self.variables()}
        )
        if self.top is not None: d['top'] = self.top
        if self.index is not None: d['index'] = self.index
        # if self.xarg is not None: d['xarg'] = self.xarg
        # if self.lnk is not None: d['lnk'] = self.lnk
        # if self.surface is not None: d['surface'] = self.surface
        # if self.identifier is not None: d['identifier'] = self.identifier
        return d


Instruction:
Create a Python 3 function to
decode a dictionary into an Mrs object.

Response:
def from_dict(cls, d):
        """
        Decode a dictionary, as from :meth:`to_dict`, into an Mrs object.
        """
        def _lnk(o):
            return None if o is None else Lnk.charspan(o['from'], o['to'])
        def _ep(ep):
            return ElementaryPredication(
                nodeid=None,
                pred=Pred.surface_or_abstract(ep['predicate']),
                label=ep['label'],
                args=ep.get('arguments', {}),
                lnk=_lnk(ep.get('lnk')),
                surface=ep.get('surface'),
                base=ep.get('base')
            )
        eps = [_ep(rel) for rel in d.get('relations', [])]
        hcons = [(c['high'], c['relation'], c['low'])
                 for c in d.get('constraints', []) if 'high' in c]
        icons = [(c['high'], c['relation'], c['low'])
                 for c in d.get('constraints', []) if 'left' in c]
        variables = {var: list(data.get('properties', {}).items())
                     for var, data in d.get('variables', {}).items()}
        return cls(
            top=d.get('top'),
            index=d.get('index'),
            xarg=d.get('xarg'),
            rels=eps,
            hcons=hcons,
            icons=icons,
            lnk=_lnk(d.get('lnk')),
            surface=d.get('surface'),
            identifier=d.get('identifier'),
            vars=variables
        )


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

Response:
def to_dict(self, short_pred=True, properties=True):
        """
        Encode the Dmrs as a dictionary suitable for JSON serialization.
        """
        qs = set(self.nodeids(quantifier=True))
        def _lnk(obj): return {'from': obj.cfrom, 'to': obj.cto}
        def _node(node, short_pred=True):
            p = node.pred.short_form() if short_pred else node.pred.string
            d = dict(nodeid=node.nodeid, predicate=p)
            if node.lnk is not None: d['lnk'] = _lnk(node)
            if properties and node.sortinfo:
                if node.nodeid not in qs:
                    d['sortinfo'] = node.sortinfo
            if node.surface is not None: d['surface'] = node.surface
            if node.base is not None: d['base'] = node.base
            if node.carg is not None: d['carg'] = node.carg
            return d
        def _link(link): return {
            'from': link.start, 'to': link.end,
            'rargname': link.rargname, 'post': link.post
        }

        d = dict(
            nodes=[_node(n) for n in nodes(self)],
            links=[_link(l) for l in links(self)]
        )
        # if self.top is not None: ... currently handled by links
        if self.index is not None:
            idx = self.nodeid(self.index)
            if idx is not None:
                d['index'] = idx
        if self.xarg is not None:
            xarg = self.nodeid(self.index)
            if xarg is not None:
                d['index'] = xarg
        if self.lnk is not None: d['lnk'] = _lnk(self)
        if self.surface is not None: d['surface'] = self.surface
        if self.identifier is not None: d['identifier'] = self.identifier
        return d


Instruction:
Can you generate a brief explanation for the following Python 3 code
def from_dict(cls, d):
        def _node(obj):
            return Node(
                obj.get('nodeid'),
                Pred.surface_or_abstract(obj.get('predicate')),
                sortinfo=obj.get('sortinfo'),
                lnk=_lnk(obj.get('lnk')),
                surface=obj.get('surface'),
                base=obj.get('base'),
                carg=obj.get('carg')
            )
        def _link(obj):
            return Link(obj.get('from'), obj.get('to'),
                        obj.get('rargname'), obj.get('post'))
        def _lnk(o):
            return None if o is None else Lnk.charspan(o['from'], o['to'])
        return cls(
            nodes=[_node(n) for n in d.get('nodes', [])],
            links=[_link(l) for l in d.get('links', [])],
            lnk=_lnk(d.get('lnk')),
            surface=d.get('surface'),
            identifier=d.get('identifier')
        )

Response: Decode a dictionary into a Dmrs object.


Instruction:
Can you create a Python 3 function that
encodes the Dmrs as triples suitable for PENMAN serialization.

Response:
def to_triples(self, short_pred=True, properties=True):
        """
        Encode the Dmrs as triples suitable for PENMAN serialization.
        """
        ts = []
        qs = set(self.nodeids(quantifier=True))
        for n in nodes(self):
            pred = n.pred.short_form() if short_pred else n.pred.string
            ts.append((n.nodeid, 'predicate', pred))
            if n.lnk is not None:
                ts.append((n.nodeid, 'lnk', '"{}"'.format(str(n.lnk))))
            if n.carg is not None:
                ts.append((n.nodeid, 'carg', '"{}"'.format(n.carg)))
            if properties and n.nodeid not in qs:
                for key, value in n.sortinfo.items():
                    ts.append((n.nodeid, key.lower(), value))

        for l in links(self):
            if safe_int(l.start) == LTOP_NODEID:
                ts.append((l.start, 'top', l.end))
            else:
                relation = '{}-{}'.format(l.rargname.upper(), l.post)
                ts.append((l.start, relation, l.end))
        return ts


Instruction:
Given the following Python 3 function, write the documentation
def from_triples(cls, triples, remap_nodeids=True):
        top_nid = str(LTOP_NODEID)
        top = lnk = surface = identifier = None
        nids, nd, edges = [], {}, []
        for src, rel, tgt in triples:
            src, tgt = str(src), str(tgt)  # hack for int-converted src/tgt
            if src == top_nid and rel == 'top':
                top = tgt
                continue
            elif src not in nd:
                if top is None:
                    top=src
                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.islower():
                nd[src]['si'].append((rel, tgt))
            else:
                rargname, post = rel.rsplit('-', 1)
                edges.append((src, tgt, rargname, post))
        if remap_nodeids:
            nidmap = dict((nid, FIRST_NODEID+i) for i, nid in enumerate(nids))
        else:
            nidmap = dict((nid, nid) for nid in nids)
        nodes = [
            Node(
                nodeid=nidmap[nid],
                pred=nd[nid]['pred'],
                sortinfo=nd[nid]['si'],
                lnk=nd[nid]['lnk'],
                carg=nd[nid]['carg']
            ) for i, nid in enumerate(nids)
        ]
        links = [Link(nidmap[s], nidmap[t], r, p) for s, t, r, p in edges]
        if top:
            links.append(Link(LTOP_NODEID, nidmap[top], None, H_POST))
        return cls(
            nodes=nodes,
            links=links,
            lnk=lnk,
            surface=surface,
            identifier=identifier
        )

Response: Decode triples as from _to_triples_ into a Dmrs object.


Instruction:
How would you explain what the following Python 3 function does
def to_array(self):
        array = super(Invoice, 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['start_parameter'] = u(self.start_parameter)  # py2: type unicode, py3: type str
        array['currency'] = u(self.currency)  # py2: type unicode, py3: type str
        array['total_amount'] = int(self.total_amount)  # type int
        return array

Response: Serializes this Invoice to a dictionary.


Instruction:
Create a Python 3 function to
serialize this ShippingAddress to a dictionary.

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

        :return: dictionary representation of this object.
        :rtype: dict
        """
        array = super(ShippingAddress, self).to_array()
        array['country_code'] = u(self.country_code)  # py2: type unicode, py3: type str
        array['state'] = u(self.state)  # py2: type unicode, py3: type str
        array['city'] = u(self.city)  # py2: type unicode, py3: type str
        array['street_line1'] = u(self.street_line1)  # py2: type unicode, py3: type str
        array['street_line2'] = u(self.street_line2)  # py2: type unicode, py3: type str
        array['post_code'] = u(self.post_code)  # py2: type unicode, py3: type str
        return array


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

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

        :return: dictionary representation of this object.
        :rtype: dict
        """
        array = super(OrderInfo, self).to_array()
        if self.name is not None:
            array['name'] = u(self.name)  # py2: type unicode, py3: type str
        if self.phone_number is not None:
            array['phone_number'] = u(self.phone_number)  # py2: type unicode, py3: type str
        if self.email is not None:
            array['email'] = u(self.email)  # py2: type unicode, py3: type str
        if self.shipping_address is not None:
            array['shipping_address'] = self.shipping_address.to_array()  # type ShippingAddress
        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")

        data = {}
        data['name'] = u(array.get('name')) if array.get('name') is not None else None
        data['phone_number'] = u(array.get('phone_number')) if array.get('phone_number') is not None else None
        data['email'] = u(array.get('email')) if array.get('email') is not None else None
        data['shipping_address'] = ShippingAddress.from_array(array.get('shipping_address')) if array.get('shipping_address') is not None else None
        data['_raw'] = array
        return OrderInfo(**data)

Response: Deserialize a new OrderInfo from a given dictionary.


Instruction:
Given the following Python 3 function, write the documentation
def to_array(self):
        array = super(SuccessfulPayment, self).to_array()
        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
        array['telegram_payment_charge_id'] = u(self.telegram_payment_charge_id)  # py2: type unicode, py3: type str
        array['provider_payment_charge_id'] = u(self.provider_payment_charge_id)  # 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

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

        data = {}
        data['currency'] = u(array.get('currency'))
        data['total_amount'] = int(array.get('total_amount'))
        data['invoice_payload'] = u(array.get('invoice_payload'))
        data['telegram_payment_charge_id'] = u(array.get('telegram_payment_charge_id'))
        data['provider_payment_charge_id'] = u(array.get('provider_payment_charge_id'))
        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 SuccessfulPayment(**data)

Response: Deserialize a new SuccessfulPayment from a given dictionary.


Instruction:
Can you tell what is the following Python 3 function doing
def to_array(self):
        array = super(ShippingQuery, self).to_array()
        array['id'] = u(self.id)  # py2: type unicode, py3: type str
        array['from'] = self.from_peer.to_array()  # type User
        array['invoice_payload'] = u(self.invoice_payload)  # py2: type unicode, py3: type str
        array['shipping_address'] = self.shipping_address.to_array()  # type ShippingAddress
        return array

Response: Serializes this ShippingQuery to a dictionary.