Instruction:
Implement a function in Python 3 to
send a request to the API and return the response.

Response:
def do(self, command, files=None, use_long_polling=False, request_timeout=None, **query):
        """
        Send a request to the api.

        If the bot is set to return the json objects, it will look like this:

        ```json
        {
            "ok": bool,
            "result": {...},
            # optionally present:
            "description": "human-readable description of the result",
            "error_code": int
        }
        ```

        :param command: The Url command parameter
        :type  command: str

        :keyword request_timeout: When the request should time out.
        :type    request_timeout: int

        :keyword files: if it needs to send files.

        :keyword use_long_polling: if it should use long polling.
                                (see http://docs.python-requests.org/en/latest/api/#requests.Response.iter_content)
        :type    use_long_polling: bool

        :param query: will get json encoded.

        :return: The json response from the server, or, if `self.return_python_objects` is `True`, a parsed return type.
        :rtype: DictObject.DictObject | pytgbot.api_types.receivable.Receivable
        """
        params = self._prepare_request(command, query)
        r = self._do_request(
            params.url, params=params.params,
            files=files, stream=use_long_polling,  timeout=request_timeout
        )
        return self._process_response(r)


Instruction:
How would you explain what the following Python 3 function does
def parse_table(tag):
    first = True
    table_header = None
    table_type = 'unknown'
    param_strings = []

    thead = tag.find('thead', recursive=False)
    theads = None  # list (items in <tr> row) of <th>/<tr> elements.
    if thead:
        theads = thead.find_all(["th", "td"])
    # end if
    tbody = tag.find('tbody', recursive=False)
    if tbody:
        tbody_rows = tbody.find_all("tr")
    else:
        tbody_rows = tag.find_all("tr")
    # end if
    tbodys = [  # list (rows) of list (items in <tr> row) of <tr> elements.
        row.find_all(["td" ,"th"]) for row in tbody_rows
    ]
    if not thead:  # so first row = header
        theads = tbody_rows[0]
        tbodys = tbody_rows[1:]
    # end if

    # TABLE HEADER

    found_columns = []
    for column in theads:
        # Either (a) `<td><strong> ... </strong></td>`
        # or new (b) `<th> ... </th>`
        col = column.find("strong")
        if col:
            # (a) `<td><strong> ... </strong></td>`
            col_text = col.text
        else:
            # (b) `<th> ... </th>`
            col_text = column.text
        # end if
        found_columns.append(col_text)
    # end def

    # if TABLE is func
    for test_columns in func_fields:
        if found_columns == test_columns:
            table_header = test_columns
            table_type = 'func'
            break
        # end if
    # end for

    # if TABLE is class
    if not table_header:  # only check if we don't have a result yet
        # search class now
        for test_columns in class_fields:
            if found_columns == test_columns:
                if table_header is not None:
                    raise AssertionError("Table detected as func and class: {!r}".format(found_columns))
                table_header = test_columns
                table_type = 'class'
                break
            # end if
        # end for
    # end if

    # TABLE is none of the above
    if not table_header:  # we don't have a result yet
        raise AssertionError("Unknown table, {!r}".format(found_columns))
    # end if

    # TABLE BODY

    for tds in tbodys:
        string = "\t".join([col.text for col in tds])
        logger.debug("t: " + string)
        param_strings.append(string)
        pass
    # end for row
    return table_type, param_strings

Response: Parses the table and returns tuple of type class or func and list of param strings.


Instruction:
Create a Python 3 function to
receive a list of results (type :class:`Clazz` or :class:`Function`), and put them into the right files in :var:`folder` :param folder: Where the files should be in. :type folder: str :param results: A list of :class:`Clazz` or :class:`Function` objects, which will be used to calculate the source code. :type results: Union(Clazz, Function)

Response:
def safe_to_file(folder, results):
    """
    Receives a list of results (type :class:`Clazz` or :class:`Function`), and put them into the right files in :var:`folder`

    :param folder: Where the files should be in.
    :type  folder: str

    :param results: A list of :class:`Clazz` or :class:`Function` objects, which will be used to calculate the source code.
    :type  results: Union(Clazz, Function)

    """
    functions = []
    message_send_functions = []
    clazzes = {} # "filepath": [Class, Class, ...]

    # split results into functions and classes
    for result in results:
        assert isinstance(result, (Clazz, Function))
        if isinstance(result, Clazz):
            import_path = get_type_path(result.clazz)
            import_path = import_path.rstrip(".")
            file_path = calc_path_and_create_folders(folder, import_path)
            result.filepath = file_path
            if file_path not in clazzes:
                clazzes[file_path] = []
            clazzes[file_path].append(result)
        else:
            assert isinstance(result, Function)
            import_path = "pytgbot.bot."
            file_path = calc_path_and_create_folders(folder, import_path)
            result.filepath = file_path
            functions.append(result)

            if result.name.startswith('send_'):
                import_path = "teleflask_messages."
                file_path = calc_path_and_create_folders(folder, import_path)
                result2 = safe_eval(repr(result), SAVE_VALUES)  # serialize + unserialize = deepcopy
                result2.filepath = file_path
                message_send_functions.append(result2)
            # end if
        # end if
    # end for

    bot_template = get_template("bot.template")
    clazzfile_template = get_template("classfile.template")
    teleflask_messages_template = get_template("teleflask_messages_file.template")
    for path, clazz_list in clazzes.items():
        clazz_imports = set()
        for clazz_ in clazz_list:
            assert isinstance(clazz_, Clazz)
            assert isinstance(clazz_.parent_clazz, Type)
            clazz_imports.add(clazz_.parent_clazz.as_import)
        # end for
        clazz_imports = list(clazz_imports)
        clazz_imports.sort()
        is_sendable = ("sendable" in path)
        try:
            with open(path, "w") as f:
                result = clazzfile_template.render(clazzes=clazz_list, imports=clazz_imports, is_sendable=is_sendable)
                result = result.replace("\t", "    ")
                f.write(result)
                # end with
        except IOError:
            raise  # lol
            # end try
    # end for classes
    if functions:
        txt = bot_template.render(functions=functions)
        with open(functions[0].filepath, "w") as f:
            f.write(txt)
        # end with
    # end if
    if message_send_functions:
        txt = teleflask_messages_template.render(functions=message_send_functions)
        with open(message_send_functions[0].filepath, "w") as f:
            f.write(txt)


Instruction:
How would you explain what the following Python 3 function does
def calc_path_and_create_folders(folder, import_path):
    file_path = abspath(path_join(folder, import_path[:import_path.rfind(".")].replace(".", folder_seperator) + ".py"))
    mkdir_p(dirname(file_path))
    return file_path

Response: calculate the path and create the needed folders


Instruction:
How would you implement a function in Python 3 that
reads a file to string buffer

Response:
def read_file_to_buffer(filename):
    """
    Reads a file to string buffer
    :param filename:
    :return:
    """
    f = open(filename, "r")
    buf = BytesIO(f.read())
    f.close()
    return buf


Instruction:
Write a Python 3 function that can
parse the arguments of a nova tree structure.

Response:
def parse_args(string):
    """
    `"yada hoa" yupi yeah 12 "" None "None"` -> `["yada hoa", "yupi", "yeah", 12, "", None, "None"]`
    :param str:
    :return:
    """
    import ast
    is_quoted = False
    result_parts = []
    current_str = ""
    while len(string) > 0:
        if string[0] == "\"":
            is_quoted = not is_quoted
            current_str += string[0]
        elif string[0].isspace():
            if is_quoted:
                current_str += string[0]
            else:
                result_parts.append(current_str)
                current_str = ""
            # end if
        else:
            current_str += string[0]
        # end if
        string = string[1:]
    # end while
    if current_str:  # last part of the array
        result_parts.append(current_str)
    # end if
    for i in range(len(result_parts)):
        # Will try for each element if it is something pythonic. Parsed type will replace original list element.
        try:
            part = ast.literal_eval(result_parts[i])
            result_parts[i] = part  # write it back.
        except ValueError:
            # could not parse -> is string
            pass  # because already is str.
        # end try
    # end for
    return result_parts


Instruction:
Make a summary of the following Python 3 code
def overwrite_color(self, string, color, prefix=False, reset=False):
        if isinstance(color, int):
            color = self.prepare_color(color)
        # end if
        prefix = color if prefix else ""
        if isinstance(reset, int):
            reset = self.prepare_color(reset)
        elif isinstance(reset, bool):
            reset = self.formatter.color_off if reset else ""
        # end if
        return (
            prefix +
            string.replace(self.formatter.color_off, self.formatter.color_off+color).replace(self.formatter.all_off, self.formatter.all_off + color) +
            reset
        )

Response: Overwrites the color of the input string with the new color.


Instruction:
Write a Python 3 script to
print the peer to the terminal.

Response:
def print_peer(self, peer, show_id=True, id_prefix="", reply=True):
        """
        :param id_prefix: Prefix of the #id thing. Set a string, or true to have it generated.
        :type  id_prefix: str|bool
        """
        if isinstance(id_prefix, bool):
            if id_prefix:  # True
                if isinstance(peer, User):
                    id_prefix = "user"
                elif isinstance(peer, Chat):
                    id_prefix = peer.type
                else:
                    id_prefix = "unknown"
                # end if
            else:  # False
                id_prefix = ""
            # end if
        # end if
        peer_string = self.peer_to_string(peer)
        if show_id and "id" in peer:
            peer_string += " ({color_lightblue}{id_prefix}#{id}{color_off})".format(id_prefix=id_prefix, id=peer.id, **self.color.formatter)
        return peer_string


Instruction:
Implement a function in Python 3 to
convert a textual representation of MRS from one source format to another.

Response:
def convert(txt, src_fmt, tgt_fmt, single=True, **kwargs):
    """
    Convert a textual representation of \*MRS from one the src_fmt
    representation to the tgt_fmt representation. By default, only
    read and convert a single \*MRS object (e.g. for `mrx` this
    starts at <mrs> and not <mrs-list>), but changing the `mode`
    argument to `corpus` (alternatively: `list`) reads and converts
    multiple \*MRSs.

    Args:
        txt: A string of semantic data.
        src_fmt: The original representation format of txt.
        tgt_fmt: The representation format to convert to.
        single: If True, assume txt represents a single \*MRS, otherwise
            read it as a corpus (or list) of \*MRSs.
        kwargs: Any other keyword arguments to pass to the serializer
            of the target format. See Notes.
    Returns:
        A string in the target format.
    Notes:
        src_fmt and tgt_fmt may be one of the following:

        | format    | description                  |
        | --------- | ---------------------------- |
        | simplemrs | The popular SimpleMRS format |
        | mrx       | The XML format of MRS        |
        | dmrx      | The XML format of DMRS       |

        Additional keyword arguments for the serializer may include:

        | option       | description                         |
        | ------------ | ----------------------------------- |
        | pretty_print | print with newlines and indentation |
        | color        | print with syntax highlighting      |
    """
    from importlib import import_module
    reader = import_module('{}.{}'.format('delphin.mrs', src_fmt.lower()))
    writer = import_module('{}.{}'.format('delphin.mrs', tgt_fmt.lower()))
    return writer.dumps(
        reader.loads(txt, single=single),
        single=single,
        **kwargs
    )


Instruction:
How would you explain what the following Python 3 function does
def _peek(tokens, n=0):
    return tokens.peek(n=n, skip=_is_comment, drop=True)

Response: Peek and drop comments from a sequence of tokens.


Instruction:
Here you have a function in Python 3, explain what it does
def _shift(tokens):
    after = tokens.peek(n=1, skip=_is_comment, drop=True)
    tok = tokens._buffer.popleft()
    return tok[0], tok[1], tok[2], after[0]

Response: pop the next token then peek the gid of the following


Instruction:
Can you tell what is the following Python 3 function doing
def _accumulate(lexitems):
    data = []
    stack = []
    break_on = 10
    in_def = False
    for item in lexitems:
        gid = item[0]
        # only yield comments outside of definitions
        if gid in (2, 3):
            if len(data) == 0:
                yield [item]
            else:
                continue
        elif gid == 20:
            assert len(data) == 0
            yield [item]
        # the following just checks if the previous definition was not
        # terminated when the next one is read in
        elif gid in (7, 8):
            if in_def:
                yield data[:-1]
                data = data[-1:] + [item]
                stack = []
                break_on = 10
            else:
                data.append(item)
                in_def = True
        else:
            data.append(item)
            if gid == break_on:
                if len(stack) == 0:
                    yield data
                    data = []
                    in_def = False
                else:
                    break_on = stack.pop()
            elif gid in (13, 14, 15):
                stack.append(break_on)
                break_on = gid + 3
    if data:
        yield data

Response: Yields lists of tokens based on very simple parsing that checks the level of nesting within a structure.


Instruction:
Can you create a Python 3 function that
collects the contents of a bounded multiline string

Response:
def _bounded(p1, p2, line, pos, line_no, lines):
    """Collect the contents of a bounded multiline string"""
    substrings = []
    start_line_no = line_no
    end = pos
    while not line.startswith(p2, end):
        if line[end] == '\\':
            end += 2
        else:
            end += 1
        if end >= len(line):
            substrings.append(line[pos:])
            try:
                line_no, line = next(lines)
            except StopIteration:
                pattern = 'docstring' if p1 == '"""' else 'block comment'
                raise TdlParsingError('Unterminated {}'.format(pattern),
                                      line_number=start_line_no)
            pos = end = 0
    substrings.append(line[pos:end])
    end += len(p2)
    return ''.join(substrings), start_line_no, line_no, line, end


Instruction:
Here you have a function in Python 3, explain what it does
def iterparse(source, encoding='utf-8'):
    if hasattr(source, 'read'):
        for event in _parse2(source):
            yield event
    else:
        with io.open(source, encoding=encoding) as fh:
            for event in _parse2(fh):
                yield event

Response: Parse the TDL file source and iteratively yield parse events.


Instruction:
Explain what the following Python 3 code does
def tokenize(s):
    return [m.group(m.lastindex) for m in _tdl_re.finditer(s)]

Response: Tokenize a string s of TDL code.


Instruction:
Can you generate the documentation for the following Python 3 function
def parse(f, encoding='utf-8'):
    if hasattr(f, 'read'):
        for event in _parse(f):
            yield event
    else:
        with io.open(f, encoding=encoding) as fh:
            for event in _parse(fh):
                yield event

Response: Parse the TDL file f and yield the interpreted contents.


Instruction:
Can you generate the documentation for the following Python 3 function
def format(obj, indent=0):
    if isinstance(obj, TypeDefinition):
        return _format_typedef(obj, indent)
    elif isinstance(obj, Conjunction):
        return _format_conjunction(obj, indent)
    elif isinstance(obj, Term):
        return _format_term(obj, indent)
    elif isinstance(obj, _MorphSet):
        return _format_morphset(obj, indent)
    elif isinstance(obj, _Environment):
        return _format_environment(obj, indent)
    elif isinstance(obj, FileInclude):
        return _format_include(obj, indent)
    else:
        raise ValueError('cannot format object as TDL: {!r}'.format(obj))

Response: Serialize a Term Conjunction or TypeDefinition object to string.


Instruction:
Here you have a function in Python 3, explain what it does
def normalize(self):
        for attr in self._avm:
            val = self._avm[attr]
            if isinstance(val, Conjunction):
                val.normalize()
                if len(val.terms) == 1 and isinstance(val.terms[0], AVM):
                    self._avm[attr] = val.terms[0]
            elif isinstance(val, AVM):
                val.normalize()

Response: Normalizes the AVM conjunctions to just the AVM.


Instruction:
Here you have a function in Python 3, explain what it does
def features(self, expand=False):
        fs = []
        for featpath, val in super(AVM, self).features(expand=expand):
            # don't juse Conjunction.features() here because we want to
            # include the non-AVM terms, too
            if expand and isinstance(val, Conjunction):
                for term in val.terms:
                    if isinstance(term, AVM):
                        for fp, v in term.features(True):
                            fs.append(('{}.{}'.format(featpath, fp), v))
                    else:
                        fs.append((featpath, term))
            else:
                fs.append((featpath, val))
        return fs

Response: Return the list of tuples of feature paths and feature values.


Instruction:
Can you implement a function in Python 3 that
returns the list of values in the ConsList feature structure.

Response:
def values(self):
        """
        Return the list of values in the ConsList feature structure.
        """
        if self._avm is None:
            return []
        else:
            vals = [val for _, val in _collect_list_items(self)]
            # the < a . b > notation puts b on the last REST path,
            # which is not returned by _collect_list_items()
            if self.terminated and self[self._last_path] is not None:
                vals.append(self[self._last_path])
            return vals


Instruction:
Create a Python 3 function for
appending an item to the end of an open ConsList.

Response:
def append(self, value):
        """
        Append an item to the end of an open ConsList.

        Args:
            value (:class:`Conjunction`, :class:`Term`): item to add
        Raises:
            :class:`TdlError`: when appending to a closed list
        """
        if self._avm is not None and not self.terminated:
            path = self._last_path
            if path:
                path += '.'
            self[path + LIST_HEAD] = value
            self._last_path = path + LIST_TAIL
            self[self._last_path] = AVM()
        else:
            raise TdlError('Cannot append to a closed list.')


Instruction:
How would you code a function in Python 3 to
terminate the tail of the list.

Response:
def terminate(self, end):
        """
        Set the value of the tail of the list.

        Adding values via :meth:`append` places them on the `FIRST`
        feature of some level of the feature structure (e.g.,
        `REST.FIRST`), while :meth:`terminate` places them on the
        final `REST` feature (e.g., `REST.REST`). If *end* is a
        :class:`Conjunction` or :class:`Term`, it is typically a
        :class:`Coreference`, otherwise *end* is set to
        `tdl.EMPTY_LIST_TYPE` or `tdl.LIST_TYPE`. This method does
        not necessarily close the list; if *end* is `tdl.LIST_TYPE`,
        the list is left open, otherwise it is closed.

        Args:
            end (str, :class:`Conjunction`, :class:`Term`): value to
            use as the end of the list.
        """
        if self.terminated:
            raise TdlError('Cannot terminate a closed list.')
        if end == LIST_TYPE:
            self.terminated = False
        elif end == EMPTY_LIST_TYPE:
            if self._last_path:
                self[self._last_path] = None
            else:
                self._avm = None
            self.terminated = True
        elif self._last_path:
            self[self._last_path] = end
            self.terminated = True
        else:
            raise TdlError('Empty list must be {} or {}'.format(
                LIST_TYPE, EMPTY_LIST_TYPE))


Instruction:
How would you code a function in Python 3 to
rearrange the conjunction to a conventional form.

Response:
def normalize(self):
        """
        Rearrange the conjunction to a conventional form.

        This puts any coreference(s) first, followed by type terms,
        then followed by AVM(s) (including lists). AVMs are
        normalized via :meth:`AVM.normalize`.
        """
        corefs = []
        types = []
        avms = []
        for term in self._terms:
            if isinstance(term, TypeTerm):
                types.append(term)
            elif isinstance(term, AVM):
                term.normalize()
                avms.append(term)
            elif isinstance(term, Coreference):
                corefs.append(term)
            else:
                raise TdlError('unexpected term {}'.format(term))
        self._terms = corefs + types + avms


Instruction:
Implement a Python 3 function for
adding a term to the current conjunction.

Response:
def add(self, term):
        """
        Add a term to the conjunction.

        Args:
            term (:class:`Term`, :class:`Conjunction`): term to add;
                if a :class:`Conjunction`, all of its terms are added
                to the current conjunction.
        Raises:
            :class:`TypeError`: when *term* is an invalid type
        """
        if isinstance(term, Conjunction):
            for term_ in term.terms:
                self.add(term_)
        elif isinstance(term, Term):
            self._terms.append(term)
        else:
            raise TypeError('Not a Term or Conjunction')


Instruction:
Can you generate the documentation for the following Python 3 function
def types(self):
        return [term for term in self._terms
                if isinstance(term, (TypeIdentifier, String, Regex))]

Response: Return the list of type terms in the conjunction.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def features(self, expand=False):
        featvals = []
        for term in self._terms:
            if isinstance(term, AVM):
                featvals.extend(term.features(expand=expand))
        return featvals

Response: Return the list of feature - value pairs in the conjunction.


Instruction:
Create a Python 3 function for
returning the first string term in the conjunction or None.

Response:
def string(self):
        """
        Return the first string term in the conjunction, or `None`.
        """
        for term in self._terms:
            if isinstance(term, String):
                return str(term)
        return None


Instruction:
How would you implement a function in Python 3 that
returns the documentation of the type.

Response:
def documentation(self, level='first'):
        """
        Return the documentation of the type.

        By default, this is the first docstring on a top-level term.
        By setting *level* to `"top"`, the list of all docstrings on
        top-level terms is returned, including the type's `docstring`
        value, if not `None`, as the last item. The docstring for the
        type itself is available via :attr:`TypeDefinition.docstring`.

        Args:
            level (str): `"first"` or `"top"`
        Returns:
            a single docstring or a list of docstrings

        """
        docs = (t.docstring for t in list(self.conjunction.terms) + [self]
                if t.docstring is not None)
        if level.lower() == 'first':
            doc = next(docs, None)
        elif level.lower() == 'top':
            doc = list(docs)
        return doc


Instruction:
Can you generate the documentation for the following Python 3 function
def local_constraints(self):
        cs = []
        for feat, val in self._avm.items():
            try:
                if val.supertypes and not val._avm:
                    cs.append((feat, val))
                else:
                    for subfeat, subval in val.features():
                        cs.append(('{}.{}'.format(feat, subfeat), subval))
            except AttributeError:
                cs.append((feat, val))
        return cs

Response: Return the constraints defined in the local AVM.


Instruction:
Can you tell what is the following Python 3 function doing
def values(self):
        def collect(d):
            if d is None or d.get('FIRST') is None:
                return []
            vals = [d['FIRST']]
            vals.extend(collect(d.get('REST')))
            return vals
        return collect(self)

Response: Return the list of values in the current locale.


Instruction:
How would you explain what the following Python 3 function does
def to_dict(self):
        d = {'rargname': self.rargname, 'value': self.value}
        if self.properties:
            d['properties'] = self.properties
        if self.optional:
            d['optional'] = self.optional
        return d

Response: Return a dictionary representation of the Role.


Instruction:
Can you write a function in Python 3 where it
returns a dictionary representation of the Predicate.

Response:
def to_dict(self):
        """Return a dictionary representation of the Predicate."""
        return {
            'predicate': self.predicate,
            'parents': list(self.supertypes),
            'synopses': [[role.to_dict() for role in synopsis]
                         for synopsis in self.synopses]
        }


Instruction:
Implement a function in Python 3 to
return a dictionary representation of the SemI.

Response:
def to_dict(self):
        """Return a dictionary representation of the SemI."""
        make = lambda pair: (pair[0], pair[1].to_dict())
        return dict(
            variables=dict(make(v) for v in self.variables.items()),
            properties=dict(make(p) for p in self.properties.items()),
            roles=dict(make(r) for r in self.roles.items()),
            predicates=dict(make(p) for p in self.predicates.items())
        )


Instruction:
How would you explain what the following Python 3 function does
def sort_vid_split(vs):
    match = var_re.match(vs)
    if match is None:
        raise ValueError('Invalid variable string: {}'.format(str(vs)))
    else:
        return match.groups()

Response: Split a valid variable string into its variable sort and id.


Instruction:
How would you explain what the following Python 3 function does
def links(xmrs):

    # Links exist for every non-intrinsic argument that has a variable
    # that is the intrinsic variable of some other predicate, as well
    # as for label equalities when no argument link exists (even
    # considering transitivity).
    links = []
    prelinks = []

    _eps = xmrs._eps
    _hcons = xmrs._hcons
    _vars = xmrs._vars

    lsh = xmrs.labelset_heads
    lblheads = {v: lsh(v) for v, vd in _vars.items() if 'LBL' in vd['refs']}

    top = xmrs.top
    if top is not None:
        prelinks.append((0, top, None, top, _vars[top]))

    for nid, ep in _eps.items():
        for role, val in ep[3].items():
            if role == IVARG_ROLE or val not in _vars:
                continue
            prelinks.append((nid, ep[2], role, val, _vars[val]))

    for src, srclbl, role, val, vd in prelinks:
        if IVARG_ROLE in vd['refs']:
            tgtnids = [n for n in vd['refs'][IVARG_ROLE]
                       if not _eps[n].is_quantifier()]
            if len(tgtnids) == 0:
                continue  # maybe some bad MRS with a lonely quantifier
            tgt = tgtnids[0]  # what do we do if len > 1?
            tgtlbl = _eps[tgt][2]
            post = EQ_POST if srclbl == tgtlbl else NEQ_POST
        elif val in _hcons:
            lbl = _hcons[val][2]
            if lbl not in lblheads or len(lblheads[lbl]) == 0:
                continue  # broken MRS; log this?
            tgt = lblheads[lbl][0]  # sorted list; first item is most "heady"
            post = H_POST
        elif 'LBL' in vd['refs']:
            if val not in lblheads or len(lblheads[val]) == 0:
                continue  # broken MRS; log this?
            tgt = lblheads[val][0]  # again, should be sorted already
            post = HEQ_POST
        else:
            continue  # CARGs, maybe?
        links.append(Link(src, tgt, role, post))

    # now EQ links unattested by arg links
    for lbl, heads in lblheads.items():
        # I'm pretty sure this does what we want
        if len(heads) > 1:
            first = heads[0]
            for other in heads[1:]:
                links.append(Link(other, first, BARE_EQ_ROLE, EQ_POST))
        # If not, something like this is more explicit
        # lblset = self.labelset(lbl)
        # sg = g.subgraph(lblset)
        # ns = [nid for nid, deg in sg.degree(lblset).items() if deg == 0]
        # head = self.labelset_head(lbl)
        # for n in ns:
        #     links.append(Link(head, n, post=EQ_POST))
    def _int(x):
        try:
            return int(x)
        except ValueError:
            return 0
    return sorted(
        links,
        key=lambda link: (_int(link.start), _int(link.end), link.rargname)
    )

Response: Return the list of Links for the MRS.


Instruction:
Write a Python 3 function that can
return the list of all HandleConstraints in * xmrs*.

Response:
def hcons(xmrs):
    """Return the list of all HandleConstraints in *xmrs*."""
    return [
        HandleConstraint(hi, reln, lo)
        for hi, reln, lo in sorted(xmrs.hcons(), key=lambda hc: var_id(hc[0]))
    ]


Instruction:
Create a Python 3 function for
returning the list of all IndividualConstraints in * xmrs*.

Response:
def icons(xmrs):
    """Return the list of all IndividualConstraints in *xmrs*."""
    return [
        IndividualConstraint(left, reln, right)
        for left, reln, right in sorted(xmrs.icons(),
                                        key=lambda ic: var_id(ic[0]))
    ]


Instruction:
Make a summary of the following Python 3 code
def split_pred_string(predstr):
    predstr = predstr.strip('"\'')  # surrounding quotes don't matter
    rel_added = False
    if not predstr.lower().endswith('_rel'):
        logging.debug('Predicate does not end in "_rel": {}'
                      .format(predstr))
        rel_added = True
        predstr += '_rel'
    match = Pred.pred_re.search(predstr)
    if match is None:
        logging.debug('Unexpected predicate string: {}'.format(predstr))
        return (predstr, None, None, None)
    # _lemma_pos(_sense)?_end
    return (match.group('lemma'), match.group('pos'),
            match.group('sense'), None if rel_added else match.group('end'))

Response: Split a predicate string into a set of words and their components.


Instruction:
Explain what the following Python 3 code does
def is_valid_pred_string(predstr):
    predstr = predstr.strip('"').lstrip("'")
    # this is a stricter regex than in Pred, but doesn't check POS
    return re.match(
        r'_([^ _\\]|\\.)+_[a-z](_([^ _\\]|\\.)+)?(_rel)?$'
        r'|[^_]([^ \\]|\\.)+(_rel)?$',
        predstr
    ) is not None

Response: Return True if predstr is a valid predicate string.


Instruction:
Given the following Python 3 function, write the documentation
def normalize_pred_string(predstr):
    tokens = [t for t in split_pred_string(predstr)[:3] if t is not None]
    if predstr.lstrip('\'"')[:1] == '_':
        tokens = [''] + tokens
    return '_'.join(tokens).lower()

Response: Normalizes the predicate string to a conventional form.


Instruction:
Given the following Python 3 function, write the documentation
def nodes(xmrs):
    nodes = []
    _props = xmrs.properties
    varsplit = sort_vid_split
    for p in xmrs.eps():
        sortinfo = None
        iv = p.intrinsic_variable
        if iv is not None:
            sort, _ = varsplit(iv)
            sortinfo = _props(iv)
            sortinfo[CVARSORT] = sort
        nodes.append(
            Node(p.nodeid, p.pred, sortinfo, p.lnk, p.surface, p.base, p.carg)
        )
    return nodes

Response: Return the list of Nodes for xmrs *.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def new(self, sort, properties=None):
        if sort is None:
            sort = UNKNOWNSORT
        # find next available vid
        vid, index = self.vid, self.index
        while vid in index:
            vid += 1
        varstring = '{}{}'.format(sort, vid)
        index[vid] = varstring
        if properties is None:
            properties = []
        self.store[varstring] = properties
        self.vid = vid + 1
        return (varstring, properties)

Response: Create a new variable for the given sort.


Instruction:
Can you tell what is the following Python 3 function doing
def charspan(cls, start, end):
        return cls(Lnk.CHARSPAN, (int(start), int(end)))

Response: Create a Lnk object for a character span.


Instruction:
Can you write a function in Python 3 where it
returns a Lnk object for a chart span.

Response:
def chartspan(cls, start, end):
        """
        Create a Lnk object for a chart span.

        Args:
            start: the initial chart vertex
            end: the final chart vertex
        """
        return cls(Lnk.CHARTSPAN, (int(start), int(end)))


Instruction:
Can you tell what is the following Python 3 function doing
def tokens(cls, tokens):
        return cls(Lnk.TOKENS, tuple(map(int, tokens)))

Response: Returns a Lnk object for a list of token identifiers.


Instruction:
Here you have a function in Python 3, explain what it does
def cfrom(self):
        cfrom = -1
        try:
            if self.lnk.type == Lnk.CHARSPAN:
                cfrom = self.lnk.data[0]
        except AttributeError:
            pass  # use default cfrom of -1
        return cfrom

Response: Returns the initial character position in the surface string.


Instruction:
How would you code a function in Python 3 to
return the final character position in the surface string.

Response:
def cto(self):
        """
        The final character position in the surface string.

        Defaults to -1 if there is no valid cto value.
        """
        cto = -1
        try:
            if self.lnk.type == Lnk.CHARSPAN:
                cto = self.lnk.data[1]
        except AttributeError:
            pass  # use default cto of -1
        return cto


Instruction:
Make a summary of the following Python 3 code
def realpred(cls, lemma, pos, sense=None):
        string_tokens = [lemma]
        if pos is not None:
            string_tokens.append(pos)
        if sense is not None:
            sense = str(sense)
            string_tokens.append(sense)
        predstr = '_'.join([''] + string_tokens + ['rel'])
        return cls(Pred.REALPRED, lemma, pos, sense, predstr)

Response: Instantiate a Pred from its components.


Instruction:
Implement a Python 3 function for
returning a dict mapping from the locale to the local locale.

Response:
def properties(self):
        """
        Morphosemantic property mapping.

        Unlike :attr:`sortinfo`, this does not include `cvarsort`.
        """
        d = dict(self.sortinfo)
        if CVARSORT in d:
            del d[CVARSORT]
        return d


Instruction:
Create a Python 3 function to
update HTTP GET params with the given fields that user wants to fetch.

Response:
def update_get_params(self):
        """Update HTTP GET params with the given fields that user wants to fetch."""
        if isinstance(self._fields, (tuple, list)):  # tuples & lists > x,y,z
            self.get_params["fields"] = ",".join([str(_) for _ in self._fields])
        elif isinstance(self._fields, str):
            self.get_params["fields"] = self._fields


Instruction:
Create a Python 3 function for
making an API call to fetch the raw data for the given probe and stores the raw data.

Response:
def _fetch_meta_data(self):
        """Makes an API call to fetch meta data for the given probe and stores the raw data."""
        is_success, meta_data = AtlasRequest(
            url_path=self.API_META_URL.format(self.id),
            key=self.api_key,
            server=self.server,
            verify=self.verify,
            user_agent=self._user_agent
        ).get(**self.get_params)

        self.meta_data = meta_data
        if not is_success:
            return False

        return True


Instruction:
Can you implement a function in Python 3 that
populates the instance properties of the class properties based on the meta data from the API response.

Response:
def _populate_data(self):
        """Assing some probe's raw meta data from API response to instance properties"""
        if self.id is None:
            self.id = self.meta_data.get("id")
        self.is_anchor = self.meta_data.get("is_anchor")
        self.country_code = self.meta_data.get("country_code")
        self.description = self.meta_data.get("description")
        self.is_public = self.meta_data.get("is_public")
        self.asn_v4 = self.meta_data.get("asn_v4")
        self.asn_v6 = self.meta_data.get("asn_v6")
        self.address_v4 = self.meta_data.get("address_v4")
        self.address_v6 = self.meta_data.get("address_v6")
        self.prefix_v4 = self.meta_data.get("prefix_v4")
        self.prefix_v6 = self.meta_data.get("prefix_v6")
        self.geometry = self.meta_data.get("geometry")
        self.tags = self.meta_data.get("tags")
        self.status = self.meta_data.get("status", {}).get("name")


Instruction:
Explain what the following Python 3 code does
def _populate_data(self):
        if self.id is None:
            self.id = self.meta_data.get("id")

        self.stop_time = None
        self.creation_time = None
        self.start_time = None
        self.populate_times()
        self.protocol = self.meta_data.get("af")
        self.target_ip = self.meta_data.get("target_ip")
        self.target_asn = self.meta_data.get("target_asn")
        self.target = self.meta_data.get("target")
        self.description = self.meta_data.get("description")
        self.is_oneoff = self.meta_data.get("is_oneoff")
        self.is_public = self.meta_data.get("is_public")
        self.interval = self.meta_data.get("interval")
        self.resolve_on_probe = self.meta_data.get("resolve_on_probe")
        self.status_id = self.meta_data.get("status", {}).get("id")
        self.status = self.meta_data.get("status", {}).get("name")
        self.type = self.get_type()
        self.result_url = self.meta_data.get("result")

Response: Populates the instance properties of the object with the raw meta data from the API response to the instance properties.


Instruction:
Write a Python 3 script to
get the type of the object.

Response:
def get_type(self):
        """
        Getting type of measurement keeping backwards compatibility for
        v2 API output changes.
        """
        mtype = None
        if "type" not in self.meta_data:
            return mtype

        mtype = self.meta_data["type"]
        if isinstance(mtype, dict):
            mtype = self.meta_data.get("type", {}).get("name", "").upper()
        elif isinstance(mtype, str):
            mtype = mtype

        return mtype


Instruction:
How would you implement a function in Python 3 that
populates the internal times of the object with the meta data times that comes with measurement if they are present.

Response:
def populate_times(self):
        """
        Populates all different meta data times that comes with measurement if
        they are present.
        """
        stop_time = self.meta_data.get("stop_time")
        if stop_time:
            stop_naive = datetime.utcfromtimestamp(stop_time)
            self.stop_time = stop_naive.replace(tzinfo=tzutc())

        creation_time = self.meta_data.get("creation_time")
        if creation_time:
            creation_naive = datetime.utcfromtimestamp(creation_time)
            self.creation_time = creation_naive.replace(tzinfo=tzutc())

        start_time = self.meta_data.get("start_time")
        if start_time:
            start_naive = datetime.utcfromtimestamp(start_time)
            self.start_time = start_naive.replace(tzinfo=tzutc())


Instruction:
Here you have a function in Python 3, explain what it does
def set_tags(self, value):
        log = (
            'Sources fields "tags" should be a dict in the format '
            '{"include": [ "tag1", "tag2", "tagN" ],'
            '"exclude": [ "tag1", "tag2", "tagN" ] }'
        )

        if not isinstance(value, dict):
            raise MalFormattedSource(log)

        if not set(value.keys()).issubset(set(["include", "exclude"])):
            raise MalFormattedSource(log)

        for tag_list in value.values():
            if not isinstance(tag_list, list):
                raise MalFormattedSource(log)
            if [tag for tag in tag_list if not isinstance(tag, str)]:
                raise MalFormattedSource(log)

        self._tags = value

Response: Setter for tags attribute


Instruction:
Implement a function in Python 3 to
build the API structure for the resource.

Response:
def build_api_struct(self):
        """
        Calls the clean method of the class and returns the info in a structure
        that Atlas API is accepting.
        """
        self.clean()
        r = {
            "type": self._type,
            "requested": self._requested,
            "value": self._value
        }
        if self._tags:
            r["tags"] = self._tags

        return r


Instruction:
Here you have a function in Python 3, explain what it does
def set_type(self, value):
        if self.action == "remove" and value != "probes":
            log = "Sources field 'type' when action is remove should always be 'probes'."
            raise MalFormattedSource(log)
        self._type = value

Response: Setter for type attribute


Instruction:
Explain what the following Python 3 code does
def clean(self):
        if not all([self._type, self._requested, self._value, self._action]):
            raise MalFormattedSource(
                "<type, requested, value, action> fields are required."
            )

Response: Checks that the user has entered all required attributes.


Instruction:
How would you explain what the following Python 3 function does
def build_api_struct(self):
        data = super(AtlasChangeSource, self).build_api_struct()
        data.update({"action": self._action})
        return data

Response: Builds the API structure for this atlas change source.


Instruction:
Create a Python 3 function for
adding an option and its value to the class as an attribute and stores it in the used options set.

Response:
def add_option(self, **options):
        """
        Adds an option and its value to the class as an attribute and stores it
        to the used options set.
        """
        for option, value in options.items():
            setattr(self, option, value)
            self._store_option(option)


Instruction:
Can you implement a function in Python 3 that
initializes the required options as class members.

Response:
def _init_required_options(self, **kwargs):
        """
        Initialize the required option as class members. The value will be
        either None or the specified value in the kwargs or __init__. The logic
        here is to make the required options accesible to edit after a class
        instance has been created.
        """
        for field in self.required_options:
            setattr(self, field, kwargs.get(field))
            self._store_option(field)


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

        # make sure the correct measurement type is set.
        if not self.measurement_type:
            log = "Please define a valid measurement type."
            raise MalFormattedMeasurement(log)

        # make sure the required fields are set.
        for roption in self.required_options:
            if getattr(self, roption, None) is None:
                log = "%s Measurement field: <%s> is required" % (
                    self.__class__.__name__, roption
                )
                raise MalFormattedMeasurement(log)

Response: Clean the user entered data making sure required fields are set.


Instruction:
Here you have a function in Python 3, explain what it does
def build_api_struct(self):
        self.clean()
        data = {"type": self.measurement_type}

        # add all options
        for option in self.used_options:
            option_key, option_value = self.v2_translator(option)
            data.update({option_key: option_value})

        return data

Response: Builds the API struct that contains the info in the API.


Instruction:
Write a Python 3 function that can
initiate the channel we want to start streams from.

Response:
def connect(self):
        """Initiate the channel we want to start streams from."""
        self.socketIO = SocketIO(
            host=self.iosocket_server,
            port=80,
            resource=self.iosocket_resource,
            proxies=self.proxies,
            headers=self.headers,
            transports=["websocket"],
            Namespace=AtlasNamespace,
        )

        self.socketIO.on(self.EVENT_NAME_ERROR, self.handle_error)


Instruction:
Can you generate the documentation for the following Python 3 function
def bind_channel(self, channel, callback):

        # Remove the following list when deprecation time expires
        if channel in self.CHANNELS:
            warning = (
                "The event name '{}' will soon be deprecated. Use "
                "the real event name '{}' instead."
            ).format(channel, self.CHANNELS[channel])

            self.handle_error(warning)
            channel = self.CHANNELS[channel]
        # -------------------------------------------------------

        if channel == self.EVENT_NAME_ERROR:
            self.error_callback = callback
        elif channel == self.EVENT_NAME_RESULTS:
            self.socketIO.on(channel, partial(self.unpack_results, callback))
        else:
            self.socketIO.on(channel, callback)

Response: Bind given channel with given callback


Instruction:
Here you have a function in Python 3, explain what it does
def start_stream(self, stream_type, **stream_parameters):
        if stream_type:
            self.subscribe(stream_type, **stream_parameters)
        else:
            self.handle_error("You need to set a stream type")

Response: Starts a new stream for given type with given parameters


Instruction:
Write a Python 3 script to
subscribe to stream with give parameters.

Response:
def subscribe(self, stream_type, **parameters):
        """Subscribe to stream with give parameters."""
        parameters["stream_type"] = stream_type

        if (stream_type == "result") and ("buffering" not in parameters):
            parameters["buffering"] = True

        self.socketIO.emit(self.EVENT_NAME_SUBSCRIBE, parameters)


Instruction:
Can you generate the documentation for the following Python 3 function
def timeout(self, seconds=None):
        if seconds is None:
            self.socketIO.wait()
        else:
            self.socketIO.wait(seconds=seconds)

Response: Times out all streams after n seconds or wait forever


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

        if not self.api_filters:
            return self.url

        # Reduce complex objects to simpler strings
        for k, v in self.api_filters.items():
            if isinstance(v, datetime):  # datetime > UNIX timestamp
                self.api_filters[k] = int(calendar.timegm(v.timetuple()))
            if isinstance(v, (tuple, list)):  # tuples & lists > x,y,z
                self.api_filters[k] = ",".join([str(_) for _ in v])

        if (
            self.id_filter in self.api_filters and
            len(str(self.api_filters[self.id_filter])) > self.URL_LENGTH_LIMIT
        ):
            self.build_url_chunks()
            return self.split_urls.pop(0)

        filters = '&'.join("%s=%s" % (k, v) for (k, v) in self.api_filters.items())

        return "%s?%s" % (self.url, filters)

Response: Build the url path based on the filter options.


Instruction:
Make a summary of the following Python 3 code
def build_url_chunks(self):
        CHUNK_SIZE = 500

        id_filter = str(self.api_filters.pop(self.id_filter)).split(',')
        chuncks = list(self.chunks(id_filter, CHUNK_SIZE))
        filters = '&'.join("%s=%s" % (k, v) for (k, v) in self.api_filters.items())

        for chunk in chuncks:
            if filters:
                url = "{0}?{1}&{2}={3}".format(self.url, filters, self.id_filter, ','.join(chunk))
            else:
                url = "{0}?{1}={2}".format(self.url, self.id_filter, ','.join(chunk))
            self.split_urls.append(url)

Response: Build url for all the url chunks


Instruction:
Create a Python 3 function for
querying API for the next batch of objects and store next url and current batch of objects.

Response:
def next_batch(self):
        """
        Querying API for the next batch of objects and store next url and
        batch of objects.
        """
        is_success, results = AtlasRequest(
            url_path=self.atlas_url,
            user_agent=self._user_agent,
            server=self.server,
            verify=self.verify,
        ).get()

        if not is_success:
            raise APIResponseError(results)

        self.total_count = results.get("count")
        self.atlas_url = self.build_next_url(results.get("next"))
        self.current_batch = results.get("results", [])


Instruction:
Create a Python 3 function for
building next url in a format compatible with cousteau. Path + query

Response:
def build_next_url(self, url):
        """Builds next url in a format compatible with cousteau. Path + query"""
        if not url:
            if self.split_urls:  # If we had a long request give the next part
                self.total_count_flag = False  # Reset flag for count
                return self.split_urls.pop(0)
            else:
                return None

        parsed_url = urlparse(url)
        return "{0}?{1}".format(parsed_url.path, parsed_url.query)


Instruction:
Write a Python 3 script to
return header for the HTTP request.

Response:
def get_headers(self):
        """Return header for the HTTP request."""
        headers = {
            "User-Agent": self.http_agent,
            "Content-Type": "application/json",
            "Accept": "application/json"
        }
        if self.headers:
            headers.update(self.headers)

        return headers


Instruction:
Write a Python 3 script to
execute the given HTTP method and returns if it s success or not the response as a string if it s success and the response as a python object after unjson if it s not success.

Response:
def http_method(self, method):
        """
        Execute the given HTTP method and returns if it's success or not
        and the response as a string if not success and as python object after
        unjson if it's success.
        """
        self.build_url()

        try:
            response = self.get_http_method(method)
            is_success = response.ok

            try:
                response_message = response.json()
            except ValueError:
                response_message = response.text

        except requests.exceptions.RequestException as exc:
            is_success = False
            response_message = exc.args

        return is_success, response_message


Instruction:
Write a Python 3 function for
getting the http method that will be called from the requests library

Response:
def get_http_method(self, method):
        """Gets the http method that will be called from the requests library"""
        return self.http_methods[method](self.url, **self.http_method_args)


Instruction:
Explain what the following Python 3 code does
def get(self, **url_params):
        if url_params:
            self.http_method_args["params"].update(url_params)
        return self.http_method("GET")

Response: Makes the HTTP GET to the url.


Instruction:
Write a Python 3 script for
making the HTTP POST to the url sending post_data.

Response:
def post(self):
        """
        Makes the HTTP POST to the url sending post_data.
        """
        self._construct_post_data()

        post_args = {"json": self.post_data}
        self.http_method_args.update(post_args)

        return self.http_method("POST")


Instruction:
Implement a Python 3 function for
transforming time field to datetime object if there is any.

Response:
def clean_time(self, time):
        """
        Transform time field to datetime object if there is any.
        """
        if isinstance(time, int):
            time = datetime.utcfromtimestamp(time)
        elif isinstance(time, str):
            time = parser.parse(time)

        return time


Instruction:
How would you explain what the following Python 3 function does
def _construct_post_data(self):
        definitions = [msm.build_api_struct() for msm in self.measurements]
        probes = [source.build_api_struct() for source in self.sources]
        self.post_data = {
            "definitions": definitions,
            "probes": probes,
            "is_oneoff": self.is_oneoff
        }

        if self.is_oneoff:
            self.post_data.update({"is_oneoff": self.is_oneoff})

        if self.start_time:
            self.post_data.update(
                {"start_time": int(calendar.timegm(self.start_time.timetuple()))}
            )
        if self.stop_time:
            self.post_data.update(
                {"stop_time": int(calendar.timegm(self.stop_time.timetuple()))}
            )

        if self.bill_to:
            self.post_data.update({"bill_to": self.bill_to})

Response:
Constructs the data structure that is required from the atlas API based
            on measurements sources and times user has specified.


Instruction:
Write a Python 3 function for
checking format of probe ids and transform it to something API understands.

Response:
def clean_probes(self, probe_ids):
        """
        Checks format of probe ids and transform it to something API
        understands.
        """
        if isinstance(probe_ids, (tuple, list)):  # tuples & lists > x,y,z
            probe_ids = ",".join([str(_) for _ in probe_ids])

        return probe_ids


Instruction:
Can you generate the documentation for the following Python 3 function
def update_http_method_params(self):
        url_params = {}

        if self.start:
            url_params.update(
                {"start": int(calendar.timegm(self.start.timetuple()))}
            )

        if self.stop:
            url_params.update(
                {"stop": int(calendar.timegm(self.stop.timetuple()))}
            )

        if self.probe_ids:
            url_params.update({"probe_ids": self.probe_ids})

        self.http_method_args["params"].update(url_params)

Response: Update the HTTP method parameters based on msm_id and query filters.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def query(self, query, media=None, year=None, fields=None, extended=None, **kwargs):
        # Validate parameters
        if not media:
            warnings.warn(
                "\"media\" parameter is now required on the Trakt['search'].query() method",
                DeprecationWarning, stacklevel=2
            )

        if fields and not media:
            raise ValueError('"fields" can only be used when the "media" parameter is defined')

        # Build query
        query = {
            'query': query
        }

        if year:
            query['year'] = year

        if fields:
            query['fields'] = fields

        if extended:
            query['extended'] = extended

        # Serialize media items
        if isinstance(media, list):
            media = ','.join(media)

        # Send request
        response = self.http.get(
            params=[media],
            query=query
        )

        # Parse response
        items = self.get_data(response, **kwargs)

        if isinstance(items, requests.Response):
            return items

        if items is not None:
            return SearchMapper.process_many(self.client, items)

        return None

Response: Search by title description media year and fields.


Instruction:
Write a Python 3 script for
returning the season identifier which is compatible with requests that require season definitions.

Response:
def to_identifier(self):
        """Return the season identifier which is compatible with requests that require season definitions.

        :return: Season identifier/definition
        :rtype: :class:`~python:dict`
        """

        return {
            'number': self.pk,
            'episodes': [
                episode.to_dict()
                for episode in self.episodes.values()
            ]
        }


Instruction:
Can you generate the documentation for the following Python 3 function
def to_dict(self):

        result = self.to_identifier()

        result.update({
            'ids': dict([
                (key, value) for (key, value) in self.keys[1:]  # NOTE: keys[0] is the season identifier
            ])
        })

        if self.rating:
            result['rating'] = self.rating.value
            result['rated_at'] = to_iso8601_datetime(self.rating.timestamp)

        result['in_watchlist'] = self.in_watchlist if self.in_watchlist is not None else 0

        # Extended Info
        if self.first_aired:
            result['first_aired'] = to_iso8601_datetime(self.first_aired)

        if self.episode_count:
            result['episode_count'] = self.episode_count

        if self.aired_episodes:
            result['aired_episodes'] = self.aired_episodes

        return result

Response: Dump Season object to a dictionary.


Instruction:
Can you tell what is the following Python 3 function doing
def to_dict(self):

        result = self.to_identifier()

        result.update({
            'title': self.title,

            'watched': 1 if self.is_watched else 0,
            'collected': 1 if self.is_collected else 0,

            'plays': self.plays if self.plays is not None else 0,
            'in_watchlist': self.in_watchlist if self.in_watchlist is not None else 0,
            'progress': self.progress,

            'last_watched_at': to_iso8601_datetime(self.last_watched_at),
            'collected_at': to_iso8601_datetime(self.collected_at),
            'paused_at': to_iso8601_datetime(self.paused_at),

            'ids': dict([
                (key, value) for (key, value) in self.keys[1:]  # NOTE: keys[0] is the (<season>, <episode>) identifier
            ])
        })

        if self.rating:
            result['rating'] = self.rating.value
            result['rated_at'] = to_iso8601_datetime(self.rating.timestamp)

        # Extended Info
        if self.first_aired:
            result['first_aired'] = to_iso8601_datetime(self.first_aired)

        if self.updated_at:
            result['updated_at'] = to_iso8601_datetime(self.updated_at)

        if self.overview:
            result['overview'] = self.overview

        if self.available_translations:
            result['available_translations'] = self.available_translations

        return result

Response: Dump the episode to a dictionary.


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

        print('Authentication aborted')

        # Authentication aborted
        self.is_authenticating.acquire()
        self.is_authenticating.notify_all()
        self.is_authenticating.release()

Response: Called when device authentication was aborted.


Instruction:
Write a Python 3 function that can
construct the device authentication poller.

Response:
def poll(self, device_code, expires_in, interval, **kwargs):
        """Construct the device authentication poller.

        :param device_code: Device authentication code
        :type device_code: str

        :param expires_in: Device authentication code expiry (in seconds)
        :type         in: int

        :param interval: Device authentication poll interval
        :type interval: int

        :rtype: DeviceOAuthPoller
        """
        return DeviceOAuthPoller(self.client, device_code, expires_in, interval)


Instruction:
Can you create a Python 3 function that
dumps this movie to a dictionary.

Response:
def to_dict(self):
        """Dump movie to a dictionary.

        :return: Movie dictionary
        :rtype: :class:`~python:dict`
        """

        result = self.to_identifier()

        result.update({
            'watched': 1 if self.is_watched else 0,
            'collected': 1 if self.is_collected else 0,

            'plays': self.plays if self.plays is not None else 0,
            'in_watchlist': self.in_watchlist if self.in_watchlist is not None else 0,
            'progress': self.progress,

            'last_watched_at': to_iso8601_datetime(self.last_watched_at),
            'collected_at': to_iso8601_datetime(self.collected_at),
            'paused_at': to_iso8601_datetime(self.paused_at)
        })

        if self.rating:
            result['rating'] = self.rating.value
            result['rated_at'] = to_iso8601_datetime(self.rating.timestamp)

        # Extended Info
        if self.released:
            result['released'] = to_iso8601_date(self.released)

        if self.updated_at:
            result['updated_at'] = to_iso8601_datetime(self.updated_at)

        if self.overview:
            result['overview'] = self.overview

        if self.tagline:
            result['tagline'] = self.tagline

        if self.runtime:
            result['runtime'] = self.runtime

        if self.certification:
            result['certification'] = self.certification

        if self.homepage:
            result['homepage'] = self.homepage

        if self.trailer:
            result['trailer'] = self.trailer

        if self.language:
            result['language'] = self.language

        if self.available_translations:
            result['available_translations'] = self.available_translations

        if self.genres:
            result['genres'] = self.genres

        return result


Instruction:
Can you tell what is the following Python 3 function doing
def to_dict(self):

        result = super(Progress, self).to_dict()

        label = LABELS['last_progress_change'][self.progress_type]
        result[label] = to_iso8601_datetime(self.last_progress_change)

        if self.progress_type == 'watched':
            result['reset_at'] = self.reset_at

        result['seasons'] = [
            season.to_dict()
            for season in self.seasons.values()
        ]

        if self.hidden_seasons:
            result['hidden_seasons'] = [
                popitems(season.to_dict(), ['number', 'ids'])
                for season in self.hidden_seasons.values()
            ]

        if self.next_episode:
            result['next_episode'] = popitems(self.next_episode.to_dict(), ['season', 'number', 'title', 'ids'])
            result['next_episode']['season'] = self.next_episode.keys[0][0]

        if self.last_episode:
            result['last_episode'] = popitems(self.last_episode.to_dict(), ['season', 'number', 'title', 'ids'])
            result['last_episode']['season'] = self.last_episode.keys[0][0]

        return result

Response: Dump this Progress object to a dictionary.


Instruction:
Can you implement a function in Python 3 that
performs scrobble action. :param action: Action to perform (either :code:`start`, :code:`pause` or :code:`stop`) :type action: :class:`~python:str` :param movie: Movie definition (or `None`) **Example:** .. code-block:: python { 'title': 'Guardians of the Galaxy', 'year': 2014, 'ids': { 'tmdb': 118340 } } :type movie: :class:`~python:dict` :param show: Show definition (or `None`) **Example:** .. code-block:: python { 'title': 'Breaking Bad', 'year': 2008, 'ids': { 'tvdb': 81189 } } :type show: :class:`~python:dict` :param episode: Episode definition (or `None`) **Example:** .. code-block:: python { "season": 3, "number": 11 } :type episode: :class:`~python:dict` :param progress: Current movie/episode progress percentage :type progress: :class:`~python:float` :param kwargs: Extra request options :type kwargs: :class:`~python:dict` :return: Response (or `None`) **Example:** .. code-block:: python { 'action': 'start', 'progress': 1.25, 'sharing': { 'facebook': true, 'twitter': true, 'tumblr': false }, 'movie': { 'title': 'Guardians of the Galaxy', 'year': 2014, 'ids': { 'trakt': 28, 'slug': 'guardians-of-the-galaxy-2014', 'imdb': 'tt2015381', 'tmdb': 118340 } } } :rtype: :class:`~python:dict`

Response:
def action(self, action, movie=None, show=None, episode=None, progress=0.0, **kwargs):
        """Perform scrobble action.

        :param action: Action to perform (either :code:`start`, :code:`pause` or :code:`stop`)
        :type action: :class:`~python:str`

        :param movie: Movie definition (or `None`)

            **Example:**

            .. code-block:: python

                {
                    'title': 'Guardians of the Galaxy',
                    'year': 2014,

                    'ids': {
                        'tmdb': 118340
                    }
                }

        :type movie: :class:`~python:dict`

        :param show: Show definition (or `None`)

            **Example:**

            .. code-block:: python

                {
                    'title': 'Breaking Bad',
                    'year': 2008,

                    'ids': {
                        'tvdb': 81189
                    }
                }

        :type show: :class:`~python:dict`

        :param episode: Episode definition (or `None`)

            **Example:**

            .. code-block:: python

                {
                    "season": 3,
                    "number": 11
                }

        :type episode: :class:`~python:dict`

        :param progress: Current movie/episode progress percentage
        :type progress: :class:`~python:float`

        :param kwargs: Extra request options
        :type kwargs: :class:`~python:dict`

        :return: Response (or `None`)

            **Example:**

            .. code-block:: python

                {
                    'action': 'start',
                    'progress': 1.25,

                    'sharing': {
                        'facebook': true,
                        'twitter': true,
                        'tumblr': false
                    },

                    'movie': {
                        'title': 'Guardians of the Galaxy',
                        'year': 2014,

                        'ids': {
                            'trakt': 28,
                            'slug': 'guardians-of-the-galaxy-2014',
                            'imdb': 'tt2015381',
                            'tmdb': 118340
                        }
                    }
                }

        :rtype: :class:`~python:dict`
        """
        if movie and (show or episode):
            raise ValueError('Only one media type should be provided')

        if not movie and not episode:
            raise ValueError('Missing media item')

        data = {
            'progress': progress,
            'app_version': kwargs.pop('app_version', self.client.version),
            'app_date': kwargs.pop('app_date', None)
        }

        if movie:
            # TODO validate
            data['movie'] = movie
        elif episode:
            if show:
                data['show'] = show

            # TODO validate
            data['episode'] = episode

        response = self.http.post(
            action,
            data=data,
            **popitems(kwargs, [
                'authenticated',
                'validate_token'
            ])
        )

        return self.get_data(response, **kwargs)


Instruction:
Given the following Python 3 function, write the documentation
def start(self, movie=None, show=None, episode=None, progress=0.0, **kwargs):
        return self.action(
            'start',
            movie, show, episode,
            progress,

            **kwargs
        )

Response: Send the scrobble start action.


Instruction:
Write a Python 3 function for
sending the scrobble pause action.

Response:
def pause(self, movie=None, show=None, episode=None, progress=0.0, **kwargs):
        """Send the scrobble "pause' action.

        Use this method when the video is paused. The playback progress will be saved and
        :code:`Trakt['sync/playback'].get()` can be used to resume the video from this exact
        position. Un-pause a video by calling the :code:`Trakt['scrobble'].start()` method again.

        :param movie: Movie definition (or `None`)

            **Example:**

            .. code-block:: python

                {
                    'title': 'Guardians of the Galaxy',
                    'year': 2014,

                    'ids': {
                        'tmdb': 118340
                    }
                }

        :type movie: :class:`~python:dict`

        :param show: Show definition (or `None`)

            **Example:**

            .. code-block:: python

                {
                    'title': 'Breaking Bad',
                    'year': 2008,

                    'ids': {
                        'tvdb': 81189
                    }
                }

        :type show: :class:`~python:dict`

        :param episode: Episode definition (or `None`)

            **Example:**

            .. code-block:: python

                {
                    "season": 3,
                    "number": 11
                }

        :type episode: :class:`~python:dict`

        :param progress: Current movie/episode progress percentage
        :type progress: :class:`~python:float`

        :param kwargs: Extra request options
        :type kwargs: :class:`~python:dict`

        :return: Response (or `None`)

            **Example:**

            .. code-block:: python

                {
                    'action': 'pause',
                    'progress': 75,

                    'sharing': {
                        'facebook': true,
                        'twitter': true,
                        'tumblr': false
                    },

                    'movie': {
                        'title': 'Guardians of the Galaxy',
                        'year': 2014,

                        'ids': {
                            'trakt': 28,
                            'slug': 'guardians-of-the-galaxy-2014',
                            'imdb': 'tt2015381',
                            'tmdb': 118340
                        }
                    }
                }

        :rtype: :class:`~python:dict`
        """
        return self.action(
            'pause',
            movie, show, episode,
            progress,

            **kwargs
        )


Instruction:
Create a Python 3 function for
sending the scrobble stop action.

Response:
def stop(self, movie=None, show=None, episode=None, progress=0.0, **kwargs):
        """Send the scrobble "stop" action.

        Use this method when the video is stopped or finishes playing on its own. If the
        progress is above 80%, the video will be scrobbled and the :code:`action` will be set
        to **scrobble**.

        If the progress is less than 80%, it will be treated as a *pause* and the :code:`action`
        will be set to **pause**. The playback progress will be saved and :code:`Trakt['sync/playback'].get()`
        can be used to resume the video from this exact position.

        **Note:** If you prefer to use a threshold higher than 80%, you should use :code:`Trakt['scrobble'].pause()`
        yourself so it doesn't create duplicate scrobbles.

        :param movie: Movie definition (or `None`)

            **Example:**

            .. code-block:: python

                {
                    'title': 'Guardians of the Galaxy',
                    'year': 2014,

                    'ids': {
                        'tmdb': 118340
                    }
                }

        :type movie: :class:`~python:dict`

        :param show: Show definition (or `None`)

            **Example:**

            .. code-block:: python

                {
                    'title': 'Breaking Bad',
                    'year': 2008,

                    'ids': {
                        'tvdb': 81189
                    }
                }

        :type show: :class:`~python:dict`

        :param episode: Episode definition (or `None`)

            **Example:**

            .. code-block:: python

                {
                    "season": 3,
                    "number": 11
                }

        :type episode: :class:`~python:dict`

        :param progress: Current movie/episode progress percentage
        :type progress: :class:`~python:float`

        :param kwargs: Extra request options
        :type kwargs: :class:`~python:dict`

        :return: Response (or `None`)

            **Example:**

            .. code-block:: python

                {
                    'action': 'scrobble',
                    'progress': 99.9,

                    'sharing': {
                        'facebook': true,
                        'twitter': true,
                        'tumblr': false
                    },

                    'movie': {
                        'title': 'Guardians of the Galaxy',
                        'year': 2014,

                        'ids': {
                            'trakt': 28,
                            'slug': 'guardians-of-the-galaxy-2014',
                            'imdb': 'tt2015381',
                            'tmdb': 118340
                        }
                    }
                }

        :rtype: :class:`~python:dict`
        """
        return self.action(
            'stop',
            movie, show, episode,
            progress,

            **kwargs
        )


Instruction:
Can you generate a brief explanation for the following Python 3 code
def delete(self, **kwargs):

        return self._client['users/*/lists/*'].delete(self.username, self.id, **kwargs)

Response:
Delete the list.

        :param kwargs: Extra request options
        :type kwargs: :class:`~python:dict`

        :return: Boolean to indicate if the request was successful
        :rtype: :class:`~python:bool`


Instruction:
Create a Python 3 function for
updating the list with the current object attributes.

Response:
def update(self, **kwargs):
        """Update the list with the current object attributes.

        :param kwargs: Extra request options
        :type kwargs: :class:`~python:dict`

        :return: Boolean to indicate if the request was successful
        :rtype: :class:`~python:bool`
        """

        item = self._client['users/*/lists/*'].update(self.username, self.id, return_type='data', **kwargs)

        if not item:
            return False

        self._update(item)
        return True


Instruction:
Can you write a function in Python 3 where it
removes specified items from the list.

Response:
def remove(self, items, **kwargs):
        """Remove specified items from the list.

        :param items: Items that should be removed from the list
        :type items: :class:`~python:list`

        :param kwargs: Extra request options
        :type kwargs: :class:`~python:dict`

        :return: Response
        :rtype: :class:`~python:dict`
        """

        return self._client['users/*/lists/*'].remove(self.username, self.id, items, **kwargs)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def like(self, **kwargs):

        return self._client['users/*/lists/*'].like(self.username, self.id, **kwargs)

Response:
Like the list.

        :param kwargs: Extra request options
        :type kwargs: :class:`~python:dict`

        :return: Boolean to indicate if the request was successful
        :rtype: :class:`~python:bool`


Instruction:
Here you have a function in Python 3, explain what it does
def get(self, source, media, collection=None, start_date=None, days=None, query=None, years=None, genres=None,
            languages=None, countries=None, runtimes=None, ratings=None, certifications=None, networks=None,
            status=None, **kwargs):
        """Retrieve calendar items.

        The `all` calendar displays info for all shows airing during the specified period. The `my` calendar displays
        episodes for all shows that have been watched, collected, or watchlisted.

        :param source: Calendar source (`all` or `my`)
        :type source: str

        :param media: Media type (`dvd`, `movies` or `shows`)
        :type media: str

        :param collection: Collection type (`new`, `premieres`)
        :type collection: str or None

        :param start_date: Start date (defaults to today)
        :type start_date: datetime or None

        :param days: Number of days to display (defaults to `7`)
        :type days: int or None

        :param query: Search title or description.
        :type query: str or None

        :param years: Year or range of years (e.g. `2014`, or `2014-2016`)
        :type years: int or str or tuple or None

        :param genres: Genre slugs (e.g. `action`)
        :type genres: str or list of str or None

        :param languages: Language codes (e.g. `en`)
        :type languages: str or list of str or None

        :param countries: Country codes (e.g. `us`)
        :type countries: str or list of str or None

        :param runtimes: Runtime range in minutes (e.g. `30-90`)
        :type runtimes: str or tuple or None

        :param ratings: Rating range between `0` and `100` (e.g. `75-100`)
        :type ratings: str or tuple or None

        :param certifications: US Content Certification (e.g. `pg-13`, `tv-pg`)
        :type certifications: str or list of str or None

        :param networks: (TV) Network name (e.g. `HBO`)
        :type networks: str or list of str or None

        :param status: (TV) Show status (e.g. `returning series`, `in production`, ended`)
        :type status: str or list of str or None

        :return: Items
        :rtype: list of trakt.objects.video.Video
        """
        if source not in ['all', 'my']:
            raise ValueError('Unknown collection type: %s' % (source,))

        if media not in ['dvd', 'movies', 'shows']:
            raise ValueError('Unknown media type: %s' % (media,))

        # Default `start_date` to today when only `days` is provided
        if start_date is None and days:
            start_date = datetime.utcnow()

        # Request calendar collection
        response = self.http.get(
            '/calendars/%s/%s%s' % (
                source, media,
                ('/' + collection) if collection else ''
            ),
            params=[
                start_date.strftime('%Y-%m-%d') if start_date else None,
                days
            ],
            query={
                'query': query,
                'years': years,
                'genres': genres,

                'languages': languages,
                'countries': countries,
                'runtimes': runtimes,

                'ratings': ratings,
                'certifications': certifications,

                # TV
                'networks': networks,
                'status': status
            },
            **popitems(kwargs, [
                'authenticated',
                'validate_token'
            ])
        )

        # Parse response
        items = self.get_data(response, **kwargs)

        if isinstance(items, requests.Response):
            return items

        # Map items
        if media == 'shows':
            return SummaryMapper.episodes(
                self.client, items,
                parse_show=True
            )

        return SummaryMapper.movies(self.client, items)

Response: Retrieve all items from the specified calendar.


Instruction:
How would you code a function in Python 3 to
return a flat episode iterator.

Response:
def episodes(self):
        """Return a flat episode iterator.

        :returns: Iterator :code:`((season_num, episode_num), Episode)`
        :rtype: iterator
        """

        for sk, season in iteritems(self.seasons):
            # Yield each episode in season
            for ek, episode in iteritems(season.episodes):
                yield (sk, ek), episode


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

        result = self.to_identifier()

        result['seasons'] = [
            season.to_dict()
            for season in self.seasons.values()
        ]

        result['in_watchlist'] = self.in_watchlist if self.in_watchlist is not None else 0

        if self.rating:
            result['rating'] = self.rating.value
            result['rated_at'] = to_iso8601_datetime(self.rating.timestamp)

        # Extended Info
        if self.first_aired:
            result['first_aired'] = to_iso8601_datetime(self.first_aired)

        if self.updated_at:
            result['updated_at'] = to_iso8601_datetime(self.updated_at)

        if self.overview:
            result['overview'] = self.overview

        if self.airs:
            result['airs'] = self.airs

        if self.runtime:
            result['runtime'] = self.runtime

        if self.certification:
            result['certification'] = self.certification

        if self.network:
            result['network'] = self.network

        if self.country:
            result['country'] = self.country

        if self.status:
            result['status'] = self.status

        if self.homepage:
            result['homepage'] = self.homepage

        if self.language:
            result['language'] = self.language

        if self.available_translations:
            result['available_translations'] = self.available_translations

        if self.genres:
            result['genres'] = self.genres

        if self.aired_episodes:
            result['aired_episodes'] = self.aired_episodes

        return result

Response: Dump show to a dictionary.


Instruction:
Explain what the following Python 3 code does
def construct_url(self):
        path = [self.path]
        path.extend(self.params)

        # Build URL
        url = self.client.base_url + '/'.join(
            str(value) for value in path
            if value
        )

        # Append query parameters (if defined)
        query = self.encode_query(self.query)

        if query:
            url += '?' + query

        return url

Response: Construct a full trakt request URI with params and query parameters.


Instruction:
Write a Python 3 script to
search for officers by name.

Response:
def search_officers(self, term, disqualified=False, **kwargs):
        """Search for officers by name.

        Args:
          term (str): Officer name to search on.
          disqualified (Optional[bool]): True to search for disqualified
            officers
          kwargs (dict): additional keywords passed into
            requests.session.get params keyword.
        """
        search_type = ('officers' if not disqualified else
                       'disqualified-officers')
        params = kwargs
        params['q'] = term
        baseuri = self._BASE_URI + 'search/{}'.format(search_type)
        res = self.session.get(baseuri, params=params)
        self.handle_http_error(res)
        return res


Instruction:
Can you write a function in Python 3 where it
searches for company addresses by company number.

Response:
def address(self, num):
        """Search for company addresses by company number.

        Args:
          num (str): Company number to search on.
        """
        url_root = "company/{}/registered-office-address"
        baseuri = self._BASE_URI + url_root.format(num)
        res = self.session.get(baseuri)
        self.handle_http_error(res)
        return res


Instruction:
Make a summary of the following Python 3 code
def profile(self, num):
        baseuri = self._BASE_URI + "company/{}".format(num)
        res = self.session.get(baseuri)
        self.handle_http_error(res)
        return res

Response: Search for company profile by company number.


Instruction:
Create a Python 3 function to
search for a company s filling history by company number.

Response:
def filing_history(self, num, transaction=None, **kwargs):
        """Search for a company's filling history by company number.

        Args:
          num (str): Company number to search on.

          transaction (Optional[str]): Filing record number.
          kwargs (dict): additional keywords passed into
            requests.session.get params keyword.
        """
        baseuri = self._BASE_URI + "company/{}/filing-history".format(num)
        if transaction is not None:
            baseuri += "/{}".format(transaction)
        res = self.session.get(baseuri, params=kwargs)
        self.handle_http_error(res)
        return res


Instruction:
Explain what the following Python 3 code does
def charges(self, num, charge_id=None, **kwargs):
        baseuri = self._BASE_URI + "company/{}/charges".format(num)
        if charge_id is not None:
            baseuri += "/{}".format(charge_id)
            res = self.session.get(baseuri, params=kwargs)
        else:
            res = self.session.get(baseuri, params=kwargs)
        self.handle_http_error(res)
        return res

Response: Search for charges against a company by company number.


Instruction:
Write a Python 3 function that can
search for a company s registered officers by company number.

Response:
def officers(self, num, **kwargs):
        """Search for a company's registered officers by company number.

        Args:
          num (str): Company number to search on.
          kwargs (dict): additional keywords passed into
            requests.session.get *params* keyword.
        """
        baseuri = self._BASE_URI + "company/{}/officers".format(num)
        res = self.session.get(baseuri, params=kwargs)
        self.handle_http_error(res)
        return res


Instruction:
How would you explain what the following Python 3 function does
def disqualified(self, num, natural=True, **kwargs):
        search_type = 'natural' if natural else 'corporate'
        baseuri = (self._BASE_URI +
                   'disqualified-officers/{}/{}'.format(search_type, num))
        res = self.session.get(baseuri, params=kwargs)
        self.handle_http_error(res)
        return res

Response: Search for disqualified officers by officer ID.


Instruction:
Implement a function in Python 3 to
search for a list of persons with significant control based on company number num.

Response:
def persons_significant_control(self, num, statements=False, **kwargs):
        """Search for a list of persons with significant control.

        Searches for persons of significant control based on company number for
        a specified company. Specify statements=True to only search for
        officers with statements.

        Args:
            num (str, int): Company number to search on.
            statements (Optional[bool]): Search only for persons with
                statements. Default is False.
            kwargs (dict): additional keywords passed into requests.session.get
            *params* keyword.
        """
        baseuri = (self._BASE_URI +
                   'company/{}/persons-with-significant-control'.format(num))

        # Only append statements to the URL if statements is True
        if statements is True:
            baseuri += '-statements'

        res = self.session.get(baseuri, params=kwargs)
        self.handle_http_error(res)
        return res


Instruction:
How would you explain what the following Python 3 function does
def significant_control(self,
                            num,
                            entity_id,
                            entity_type='individual',
                            **kwargs):
        """Get details of a specific entity with significant control.

        Args:
            num (str, int): Company number to search on.
            entity_id (str, int): Entity id to request details for
            entity_type (str, int): What type of entity to search for. Defaults
                to 'individual'. Other possible opetions are
                'corporate' (for corporate entitys), 'legal' (for legal
                persons), 'statements' (for a person with significant control
                statement) and 'secure' (for a super secure person).
            kwargs (dict): additional keywords passed into requests.session.get
            *params* keyword.
        """
        # Dict mapping entity_type strings to url strings
        entities = {'individual': 'individual',
                    'corporate': 'corporate-entity',
                    'legal': 'legal-person',
                    'statements': 'persons-with-significant-control-statements',
                    'secure': 'super-secure'}

        # Make sure correct entity_type supplied
        try:
            entity = entities[entity_type]
        except KeyError as e:
            msg = ("Wrong entity_type supplied. Please choose from " +
                   "individual, corporate, legal, statements or secure")
            raise Exception(msg) from e

        # Construct the request and return the result
        baseuri = (self._BASE_URI +
                   'company/{}/persons-with-significant-control/'.format(num) +
                   '{}/{}'.format(entity, entity_id))
        res = self.session.get(baseuri, params=kwargs)
        self.handle_http_error(res)
        return res

Response: Get details of a specific entity with significant control.


Instruction:
Implement a Python 3 function for
requesting for a document by the document id. Normally the response. content can be saved as a pdf file.

Response:
def document(self, document_id, **kwargs):
        """Requests for a document by the document id.
           Normally the response.content can be saved as a pdf file

        Args:
           document_id (str): The id of the document retrieved.
           kwargs (dict): additional keywords passed into
            requests.session.get *params* keyword.
        """
        baseuri = '{}document/{}/content'.format(self._DOCUMENT_URI,
                                                 document_id)
        res = self.session.get(baseuri, params=kwargs)
        self.handle_http_error(res)
        return res


Instruction:
Implement a function in Python 3 to
add file to webhook

Response:
def add_file(self, file, filename):
        """
        add file to webhook
        :param file: file content
        :param filename: filename
        :return:
        """
        self.files['_{}'.format(filename)] = (filename, file)


Instruction:
Explain what the following Python 3 code does
def add_embed(self, embed):
        self.embeds.append(embed.__dict__ if isinstance(embed, DiscordEmbed) else embed)

Response: add embedded rich content


Instruction:
Make a summary of the following Python 3 code
def json(self):
        data = dict()
        embeds = self.embeds
        self.embeds = list()
        # convert DiscordEmbed to dict
        for embed in embeds:
            self.add_embed(embed)
        for key, value in self.__dict__.items():
            if value and key not in ['url', 'files', 'filename']:
                data[key] = value
        embeds_empty = all(not embed for embed in data["embeds"]) if 'embeds' in data else True
        if embeds_empty and 'content' not in data and bool(self.files) is False:
            logger.error('webhook message is empty! set content or embed data')
        return data

Response: convert webhook data to json


Instruction:
Write a Python 3 script to
set timestamp of embed content

Response:
def set_timestamp(self, timestamp=str(datetime.datetime.utcfromtimestamp(time.time()))):
        """
        set timestamp of embed content
        :param timestamp: (optional) timestamp of embed content
        """
        self.timestamp = timestamp


Instruction:
Here you have a function in Python 3, explain what it does
def set_footer(self, **kwargs):
        self.footer = {
            'text': kwargs.get('text'),
            'icon_url': kwargs.get('icon_url'),
            'proxy_icon_url': kwargs.get('proxy_icon_url')
        }

Response: set footer information of embed


Instruction:
Can you tell what is the following Python 3 function doing
def set_image(self, **kwargs):
        self.image = {
            'url': kwargs.get('url'),
            'proxy_url': kwargs.get('proxy_url'),
            'height': kwargs.get('height'),
            'width': kwargs.get('width'),
        }

Response: set image of embed


Instruction:
Implement a Python 3 function for
setting thumbnail of embed

Response:
def set_thumbnail(self, **kwargs):
        """
        set thumbnail of embed
        :keyword url: source url of thumbnail (only supports http(s) and attachments)
        :keyword proxy_url: a proxied thumbnail of the image
        :keyword height: height of thumbnail
        :keyword width: width of thumbnail
        """
        self.thumbnail = {
            'url': kwargs.get('url'),
            'proxy_url': kwargs.get('proxy_url'),
            'height': kwargs.get('height'),
            'width': kwargs.get('width'),
        }


Instruction:
Explain what the following Python 3 code does
def set_video(self, **kwargs):
        self.video = {
            'url': kwargs.get('url'),
            'height': kwargs.get('height'),
            'width': kwargs.get('width'),
        }

Response: set video of embed


Instruction:
Write a Python 3 script to
set author of embed

Response:
def set_author(self, **kwargs):
        """
        set author of embed
        :keyword name: name of author
        :keyword url: url of author
        :keyword icon_url: url of author icon (only supports http(s) and attachments)
        :keyword proxy_icon_url: a proxied url of author icon
        """
        self.author = {
            'name': kwargs.get('name'),
            'url': kwargs.get('url'),
            'icon_url': kwargs.get('icon_url'),
            'proxy_icon_url': kwargs.get('proxy_icon_url'),
        }


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_embed_field(self, **kwargs):
        self.fields.append({
            'name': kwargs.get('name'),
            'value': kwargs.get('value'),
            'inline': kwargs.get('inline', True)
        })

Response: add a field to embed