Instruction:
Implement a function in Python 3 to
transplant a node from another document to become a child of this node.

Response:
def transplant_node(self, node):
        """
        Transplant a node from another document to become a child of this node,
        removing it from the source document.  The node to be transplanted can
        be a :class:`Node` based on the same underlying XML library
        implementation and adapter, or a "raw" node from that implementation.

        :param node: the node in another document to transplant.
        :type node: xml4h or implementation node
        """
        if isinstance(node, xml4h.nodes.Node):
            child_impl_node = node.impl_node
            original_parent_impl_node = node.parent.impl_node
        else:
            child_impl_node = node  # Assume it's a valid impl node
            original_parent_impl_node = self.adapter.get_node_parent(node)
        self.adapter.import_node(self.impl_node, child_impl_node,
            original_parent_impl_node, clone=False)


Instruction:
How would you code a function in Python 3 to
find all the children of this node with optional name and namespace URI.

Response:
def find(self, name=None, ns_uri=None, first_only=False):
        """
        Find :class:`Element` node descendants of this node, with optional
        constraints to limit the results.

        :param name: limit results to elements with this name.
            If *None* or ``'*'`` all element names are matched.
        :type name: string or None
        :param ns_uri: limit results to elements within this namespace URI.
            If *None* all elements are matched, regardless of namespace.
        :type ns_uri: string or None
        :param bool first_only: if *True* only return the first result node
            or *None* if there is no matching node.

        :returns: a list of :class:`Element` nodes matching any given
            constraints, or a single node if ``first_only=True``.
        """
        if name is None:
            name = '*'  # Match all element names
        if ns_uri is None:
            ns_uri = '*'  # Match all namespaces
        impl_nodelist = self.adapter.find_node_elements(
            self.impl_node, name=name, ns_uri=ns_uri)
        if first_only:
            if impl_nodelist:
                return self.adapter.wrap_node(
                    impl_nodelist[0], self.adapter.impl_document, self.adapter)
            else:
                return None
        return self._convert_nodelist(impl_nodelist)


Instruction:
Write a Python 3 script for
finding the first node descendant of this node that matches any optional constraints.

Response:
def find_first(self, name=None, ns_uri=None):
        """
        Find the first :class:`Element` node descendant of this node that
        matches any optional constraints, or None if there are no matching
        elements.

        Delegates to :meth:`find` with ``first_only=True``.
        """
        return self.find(name=name, ns_uri=ns_uri, first_only=True)


Instruction:
Explain what the following Python 3 code does
def find_doc(self, name=None, ns_uri=None, first_only=False):
        return self.document.find(name=name, ns_uri=ns_uri,
            first_only=first_only)

Response: Find the document descendants of this node.


Instruction:
How would you implement a function in Python 3 that
serializes this node and its descendants to text and write it to a given writer.

Response:
def write(self, writer=None, encoding='utf-8', indent=0, newline='',
            omit_declaration=False, node_depth=0, quote_char='"'):
        """
        Serialize this node and its descendants to text, writing
        the output to a given *writer* or to stdout.

        :param writer: an object such as a file or stream to which XML text
            is sent. If *None* text is sent to :attr:`sys.stdout`.
        :type writer: a file, stream, etc or None
        :param string encoding: the character encoding for serialized text.
        :param indent: indentation prefix to apply to descendent nodes for
            pretty-printing. The value can take many forms:

            - *int*: the number of spaces to indent. 0 means no indent.
            - *string*: a literal prefix for indented nodes, such as ``\\t``.
            - *bool*: no indent if *False*, four spaces indent if *True*.
            - *None*: no indent
        :type indent: string, int, bool, or None
        :param newline: the string value used to separate lines of output.
            The value can take a number of forms:

            - *string*: the literal newline value, such as ``\\n`` or ``\\r``.
              An empty string means no newline.
            - *bool*: no newline if *False*, ``\\n`` newline if *True*.
            - *None*: no newline.
        :type newline: string, bool, or None
        :param boolean omit_declaration: if *True* the XML declaration header
            is omitted, otherwise it is included. Note that the declaration is
            only output when serializing an :class:`xml4h.nodes.Document` node.
        :param int node_depth: the indentation level to start at, such as 2 to
            indent output as if the given *node* has two ancestors.
            This parameter will only be useful if you need to output XML text
            fragments that can be assembled into a document.  This parameter
            has no effect unless indentation is applied.
        :param string quote_char: the character that delimits quoted content.
            You should never need to mess with this.

        Delegates to :func:`xml4h.writer.write_node` applied to this node.
        """
        xml4h.write_node(self,
            writer=writer, encoding=encoding, indent=indent,
            newline=newline, omit_declaration=omit_declaration,
            node_depth=node_depth, quote_char=quote_char)


Instruction:
Given the following Python 3 function, write the documentation
def xml(self, indent=4, **kwargs):
        writer = StringIO()
        self.write(writer, indent=indent, **kwargs)
        return writer.getvalue()

Response: Returns this node as XML text.


Instruction:
Here you have a function in Python 3, explain what it does
def xpath(self, xpath, **kwargs):
        result = self.adapter.xpath_on_node(self.impl_node, xpath, **kwargs)
        if isinstance(result, (list, tuple)):
            return [self._maybe_wrap_node(r) for r in result]
        else:
            return self._maybe_wrap_node(result)

Response: Perform an XPath query on the current node.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_attributes(self, attr_obj=None, ns_uri=None, **attr_dict):
        self._set_element_attributes(self.impl_node,
            attr_obj=attr_obj, ns_uri=ns_uri, **attr_dict)

Response: Add or update this element s attributes.


Instruction:
Can you generate the documentation for the following Python 3 function
def attributes(self):
        attr_impl_nodes = self.adapter.get_node_attributes(self.impl_node)
        return AttributeDict(attr_impl_nodes, self.impl_node, self.adapter)

Response: Get or set this element s attributes as name value pairs.


Instruction:
Make a summary of the following Python 3 code
def attribute_nodes(self):
        impl_attr_nodes = self.adapter.get_node_attributes(self.impl_node)
        wrapped_attr_nodes = [
            self.adapter.wrap_node(a, self.adapter.impl_document, self.adapter)
            for a in impl_attr_nodes]
        return sorted(wrapped_attr_nodes, key=lambda x: x.name)

Response:
returns a list of this element s attributes as
            : class : Attribute nodes.


Instruction:
Can you generate the documentation for the following Python 3 function
def attribute_node(self, name, ns_uri=None):
        attr_impl_node = self.adapter.get_node_attribute_node(
            self.impl_node, name, ns_uri)
        return self.adapter.wrap_node(
            attr_impl_node, self.adapter.impl_document, self.adapter)

Response: returns the node that matches the given attribute name and ns_uri


Instruction:
Can you implement a function in Python 3 that
defines a namespace prefix that will serve as shorthand for the given namespace URI in element names.

Response:
def set_ns_prefix(self, prefix, ns_uri):
        """
        Define a namespace prefix that will serve as shorthand for the given
        namespace URI in element names.

        :param string prefix: prefix that will serve as an alias for a
            the namespace URI.
        :param string ns_uri: namespace URI that will be denoted by the
            prefix.
        """
        self._add_ns_prefix_attr(self.impl_node, prefix, ns_uri)


Instruction:
Can you create a Python 3 function that
adds a new child element to this element with an optional namespace enumeration definition.

Response:
def add_element(self, name, ns_uri=None, attributes=None,
            text=None, before_this_element=False):
        """
        Add a new child element to this element, with an optional namespace
        definition. If no namespace is provided the child will be assigned
        to the default namespace.

        :param string name: a name for the child node. The name may be used
            to apply a namespace to the child by including:

            - a prefix component in the name of the form
              ``ns_prefix:element_name``, where the prefix has already been
              defined for a namespace URI (such as via :meth:`set_ns_prefix`).
            - a literal namespace URI value delimited by curly braces, of
              the form ``{ns_uri}element_name``.
        :param ns_uri: a URI specifying the new element's namespace. If the
            ``name`` parameter specifies a namespace this parameter is ignored.
        :type ns_uri: string or None
        :param attributes: collection of attributes to assign to the new child.
        :type attributes: dict, list, tuple, or None
        :param text: text value to assign to the new child.
        :type text: string or None
        :param bool before_this_element: if *True* the new element is
            added as a sibling preceding this element, instead of as a child.
            In other words, the new element will be a child of this element's
            parent node, and will immediately precent this element in the DOM.

        :return: the new child as a an :class:`Element` node.
        """
        # Determine local name, namespace and prefix info from tag name
        prefix, local_name, node_ns_uri = \
            self.adapter.get_ns_info_from_node_name(name, self.impl_node)
        if prefix:
            qname = u'%s:%s' % (prefix, local_name)
        else:
            qname = local_name
        # If no name-derived namespace, apply an alternate namespace
        if node_ns_uri is None:
            if ns_uri is None:
                # Default document namespace
                node_ns_uri = self.adapter.get_ns_uri_for_prefix(
                    self.impl_node, None)
            else:
                # keyword-parameter namespace
                node_ns_uri = ns_uri
        # Create element
        child_elem = self.adapter.new_impl_element(
            qname, node_ns_uri, parent=self.impl_node)
        # If element's default namespace was defined by literal uri prefix,
        # create corresponding xmlns attribute for element...
        if not prefix and '}' in name:
            self._set_element_attributes(child_elem,
                {'xmlns': node_ns_uri}, ns_uri=self.XMLNS_URI)
        # ...otherwise define keyword-defined namespace as the default, if any
        elif ns_uri is not None:
            self._set_element_attributes(child_elem,
                {'xmlns': ns_uri}, ns_uri=self.XMLNS_URI)
        # Create subordinate nodes
        if attributes is not None:
            self._set_element_attributes(child_elem, attr_obj=attributes)
        if text is not None:
            self._add_text(child_elem, text)
        # Add new element to its parent before a given node...
        if before_this_element:
            self.adapter.add_node_child(
                self.adapter.get_node_parent(self.impl_node),
                child_elem, before_sibling=self.impl_node)
        # ...or in the default position, appended after existing nodes
        else:
            self.adapter.add_node_child(self.impl_node, child_elem)
        return self.adapter.wrap_node(
            child_elem, self.adapter.impl_document, self.adapter)


Instruction:
Given the following Python 3 function, write the documentation
def add_text(self, text):
        if not isinstance(text, basestring):
            text = unicode(text)
        self._add_text(self.impl_node, text)

Response: Add a text node to this element.


Instruction:
Can you generate the documentation for the following Python 3 function
def add_instruction(self, target, data):
        self._add_instruction(self.impl_node, target, data)

Response: Add an instruction node to this element.


Instruction:
Write a Python 3 function for
returning a list of name value attribute pairs sorted by attribute name.

Response:
def items(self):
        """
        :return: a list of name/value attribute pairs sorted by attribute name.
        """
        sorted_keys = sorted(self.keys())
        return [(k, self[k]) for k in sorted_keys]


Instruction:
Make a summary of the following Python 3 code
def namespace_uri(self, name):
        a_node = self.adapter.get_node_attribute_node(self.impl_element, name)
        if a_node is None:
            return None
        return self.adapter.get_node_namespace_uri(a_node)

Response: returns the namespace URI associated with the named attribute or None if no such attribute exists.


Instruction:
Create a Python 3 function to
return the prefix component of the named attribute

Response:
def prefix(self, name):
        """
        :param string name: the name of an attribute to look up.

        :return: the prefix component of the named attribute's name,
            or None.
        """
        a_node = self.adapter.get_node_attribute_node(self.impl_element, name)
        if a_node is None:
            return None
        return a_node.prefix


Instruction:
Given the following Python 3 function, write the documentation
def element(self):
        return self.adapter.wrap_node(
            self.impl_element, self.adapter.impl_document, self.adapter)

Response: Returns the Element that contains these attributes.


Instruction:
Can you generate the documentation for the following Python 3 function
def filter(self, local_name=None, name=None, ns_uri=None, node_type=None,
            filter_fn=None, first_only=False):
        """
        Apply filters to the set of nodes in this list.

        :param local_name: a local name used to filter the nodes.
        :type local_name: string or None
        :param name: a name used to filter the nodes.
        :type name: string or None
        :param ns_uri: a namespace URI used to filter the nodes.
            If *None* all nodes are returned regardless of namespace.
        :type ns_uri: string or None
        :param node_type: a node type definition used to filter the nodes.
        :type node_type: int node type constant, class, or None
        :param filter_fn: an arbitrary function to filter nodes in this list.
            This function must accept a single :class:`Node` argument and
            return a bool indicating whether to include the node in the
            filtered results.

            .. note:: if ``filter_fn`` is provided all other filter arguments
                are ignore.
        :type filter_fn: function or None

        :return: the type of the return value depends on the value of the
            ``first_only`` parameter and how many nodes match the filter:

            - if ``first_only=False`` return a :class:`NodeList` of filtered
              nodes, which will be empty if there are no matching nodes.
            - if ``first_only=True`` and at least one node matches,
              return the first matching :class:`Node`
            - if ``first_only=True`` and there are no matching nodes,
              return *None*
        """
        # Build our own filter function unless a custom function is provided
        if filter_fn is None:
            def filter_fn(n):
                # Test node type first in case other tests require this type
                if node_type is not None:
                    # Node type can be specified as an integer constant (e.g.
                    # ELEMENT_NODE) or a class.
                    if isinstance(node_type, int):
                        if not n.is_type(node_type):
                            return False
                    elif n.__class__ != node_type:
                        return False
                if name is not None and n.name != name:
                    return False
                if local_name is not None and n.local_name != local_name:
                    return False
                if ns_uri is not None and n.ns_uri != ns_uri:
                    return False
                return True
        # Filter nodes
        nodelist = filter(filter_fn, self)
        # If requested, return just the first node (or None if no nodes)
        if first_only:
            return nodelist[0] if nodelist else None
        else:
            return NodeList(nodelist)

Response: This method filters the set of nodes in this list based on the given parameters.


Instruction:
Make a summary of the following Python 3 code
def get_all_analytics(user, job_id):

    args = schemas.args(flask.request.args.to_dict())
    v1_utils.verify_existence_and_get(job_id, models.JOBS)

    query = v1_utils.QueryBuilder(_TABLE, args, _A_COLUMNS)
    # If not admin nor rh employee then restrict the view to the team
    if user.is_not_super_admin() and not user.is_read_only_user():
        query.add_extra_condition(_TABLE.c.team_id.in_(user.teams_ids))

    query.add_extra_condition(_TABLE.c.job_id == job_id)

    nb_rows = query.get_number_of_rows()
    rows = query.execute(fetchall=True)
    rows = v1_utils.format_result(rows, _TABLE.name)

    return flask.jsonify({'analytics': rows, '_meta': {'count': nb_rows}})

Response: Get all analytics of a job.


Instruction:
Given the following Python 3 function, write the documentation
def write_node(node, writer=None, encoding='utf-8', indent=0, newline='',
        omit_declaration=False, node_depth=0, quote_char='"'):
    """
    Serialize an *xml4h* DOM node and its descendants to text, writing
    the output to a given *writer* or to stdout.

    :param node: the DOM node whose content and descendants will
        be serialized.
    :type node: an :class:`xml4h.nodes.Node` or subclass
    :param writer: an object such as a file or stream to which XML text
        is sent. If *None* text is sent to :attr:`sys.stdout`.
    :type writer: a file, stream, etc or None
    :param string encoding: the character encoding for serialized text.
    :param indent: indentation prefix to apply to descendent nodes for
        pretty-printing. The value can take many forms:

        - *int*: the number of spaces to indent. 0 means no indent.
        - *string*: a literal prefix for indented nodes, such as ``\\t``.
        - *bool*: no indent if *False*, four spaces indent if *True*.
        - *None*: no indent.
    :type indent: string, int, bool, or None
    :param newline: the string value used to separate lines of output.
        The value can take a number of forms:

        - *string*: the literal newline value, such as ``\\n`` or ``\\r``.
          An empty string means no newline.
        - *bool*: no newline if *False*, ``\\n`` newline if *True*.
        - *None*: no newline.
    :type newline: string, bool, or None
    :param boolean omit_declaration: if *True* the XML declaration header
        is omitted, otherwise it is included. Note that the declaration is
        only output when serializing an :class:`xml4h.nodes.Document` node.
    :param int node_depth: the indentation level to start at, such as 2 to
        indent output as if the given *node* has two ancestors.
        This parameter will only be useful if you need to output XML text
        fragments that can be assembled into a document.  This parameter
        has no effect unless indentation is applied.
    :param string quote_char: the character that delimits quoted content.
        You should never need to mess with this.
    """
    def _sanitize_write_value(value):
        """Return XML-encoded value."""
        if not value:
            return value
        return (value
            .replace("&", "&")
            .replace("<", "<")
            .replace("\"", """)
            .replace(">", ">")
            )

    def _write_node_impl(node, node_depth):
        """
        Internal write implementation that does the real work while keeping
        track of node depth.
        """
        # Output document declaration if we're outputting the whole doc
        if node.is_document:
            if not omit_declaration:
                writer.write(
                    '<?xml version=%s1.0%s' % (quote_char, quote_char))
                if encoding:
                    writer.write(' encoding=%s%s%s'
                        % (quote_char, encoding, quote_char))
                writer.write('?>%s' % newline)
            for child in node.children:
                _write_node_impl(child,
                    node_depth)  # node_depth not incremented
            writer.write(newline)
        elif node.is_document_type:
            writer.write("<!DOCTYPE %s SYSTEM %s%s%s"
                % (node.name, quote_char, node.public_id))
            if node.system_id is not None:
                writer.write(
                    " %s%s%s" % (quote_char, node.system_id, quote_char))
            if node.children:
                writer.write("[")
                for child in node.children:
                    _write_node_impl(child, node_depth + 1)
                writer.write("]")
            writer.write(">")
        elif node.is_text:
            writer.write(_sanitize_write_value(node.value))
        elif node.is_cdata:
            if ']]>' in node.value:
                raise ValueError("']]>' is not allowed in CDATA node value")
            writer.write("<![CDATA[%s]]>" % node.value)
        #elif node.is_entity_reference:  # TODO
        elif node.is_entity:
            writer.write(newline + indent * node_depth)
            writer.write("<!ENTITY ")
            if node.is_paremeter_entity:
                writer.write('%% ')
            writer.write("%s %s%s%s>"
                % (node.name, quote_char, node.value, quote_char))
        elif node.is_processing_instruction:
            writer.write(newline + indent * node_depth)
            writer.write("<?%s %s?>" % (node.target, node.data))
        elif node.is_comment:
            if '--' in node.value:
                raise ValueError("'--' is not allowed in COMMENT node value")
            writer.write("<!--%s-->" % node.value)
        elif node.is_notation:
            writer.write(newline + indent * node_depth)
            writer.write("<!NOTATION %s" % node.name)
            if node.is_system_identifier:
                writer.write(" system %s%s%s>"
                    % (quote_char, node.external_id, quote_char))
            elif node.is_system_identifier:
                writer.write(" system %s%s%s %s%s%s>"
                    % (quote_char, node.external_id, quote_char,
                    quote_char, node.uri, quote_char))
        elif node.is_attribute:
            writer.write(" %s=%s" % (node.name, quote_char))
            writer.write(_sanitize_write_value(node.value))
            writer.write(quote_char)
        elif node.is_element:
            # Only need a preceding newline if we're in a sub-element
            if node_depth > 0:
                writer.write(newline)
            writer.write(indent * node_depth)
            writer.write("<" + node.name)

            for attr in node.attribute_nodes:
                _write_node_impl(attr, node_depth)
            if node.children:
                found_indented_child = False
                writer.write(">")
                for child in node.children:
                    _write_node_impl(child, node_depth + 1)
                    if not (child.is_text
                            or child.is_comment
                            or child.is_cdata):
                        found_indented_child = True
                if found_indented_child:
                    writer.write(newline + indent * node_depth)
                writer.write('</%s>' % node.name)
            else:
                writer.write('/>')
        else:
            raise exceptions.Xml4hImplementationBug(
                'Cannot write node with class: %s' % node.__class__)

    # Sanitize whitespace parameters
    if indent is True:
        indent = ' ' * 4
    elif indent is False:
        indent = ''
    elif isinstance(indent, int):
        indent = ' ' * indent
    # If indent but no newline set, always apply a newline (it makes sense)
    if indent and not newline:
        newline = True

    if newline is None or newline is False:
        newline = ''
    elif newline is True:
        newline = '\n'

    # We always need a writer, use stdout by default
    if writer is None:
        writer = sys.stdout

    # Apply a text encoding if we have one
    if encoding is None:
        writer = writer
    else:
        writer = codecs.getwriter(encoding)(writer)

    # Do the business...
    _write_node_impl(node, node_depth)

Response: Serialize a node to a given writer or to stdout.


Instruction:
Write a Python 3 script for
encrypting a chunk of a GCM file with the given key and decrypts it.

Response:
def encry_decry_chunk(chunk, key, algo, bool_encry, assoc_data):
    """
    When bool_encry is True, encrypt a chunk of the file with the key and a randomly generated nonce. When it is False,
    the function extract the nonce from the cipherchunk (first 16 bytes), and decrypt the rest of the chunk.
    :param chunk: a chunk in bytes to encrypt or decrypt.
    :param key: a 32 bytes key in bytes.
    :param algo: a string of algorithm. Can be "srp" , "AES" or "twf"
    :param bool_encry: if bool_encry is True, chunk is encrypted. Else, it will be decrypted.
    :param assoc_data: bytes string of additional data for GCM Authentication.
    :return: if bool_encry is True, corresponding nonce + cipherchunk else, a decrypted chunk.
    """
    engine = botan.cipher(algo=algo, encrypt=bool_encry)
    engine.set_key(key=key)
    engine.set_assoc_data(assoc_data)
    if bool_encry is True:
        nonce = generate_nonce_timestamp()
        engine.start(nonce=nonce)
        return nonce + engine.finish(chunk)
    else:
        nonce = chunk[:__nonce_length__]
        encryptedchunk = chunk[__nonce_length__:__nonce_length__ + __gcmtag_length__ + __chunk_size__]
        engine.start(nonce=nonce)
        decryptedchunk = engine.finish(encryptedchunk)
        if decryptedchunk == b"":
            raise Exception("Integrity failure: Invalid passphrase or corrupted data")
        return decryptedchunk


Instruction:
Create a Python 3 function to
query Bugzilla API to retrieve the needed infos.

Response:
def retrieve_info(self):
        """Query Bugzilla API to retrieve the needed infos."""

        scheme = urlparse(self.url).scheme
        netloc = urlparse(self.url).netloc
        query = urlparse(self.url).query

        if scheme not in ('http', 'https'):
            return

        for item in query.split('&'):
            if 'id=' in item:
                ticket_id = item.split('=')[1]
                break
        else:
            return

        bugzilla_url = '%s://%s/%s%s' % (scheme, netloc, _URI_BASE, ticket_id)

        result = requests.get(bugzilla_url)
        self.status_code = result.status_code

        if result.status_code == 200:
            tree = ElementTree.fromstring(result.content)

            self.title = tree.findall("./bug/short_desc").pop().text
            self.issue_id = tree.findall("./bug/bug_id").pop().text
            self.reporter = tree.findall("./bug/reporter").pop().text
            self.assignee = tree.findall("./bug/assigned_to").pop().text
            self.status = tree.findall("./bug/bug_status").pop().text
            self.product = tree.findall("./bug/product").pop().text
            self.component = tree.findall("./bug/component").pop().text
            self.created_at = tree.findall("./bug/creation_ts").pop().text
            self.updated_at = tree.findall("./bug/delta_ts").pop().text
            try:
                self.closed_at = (
                    tree.findall("./bug/cf_last_closed").pop().text
                )
            except IndexError:
                # cf_last_closed is present only if the issue has been closed
                # if not present it raises an IndexError, meaning the issue
                # isn't closed yet, which is a valid use case.
                pass


Instruction:
Can you generate the documentation for the following Python 3 function
def maxlen(max_length,
           strict=False  # type: bool
           ):
    """
    'Maximum length' validation_function generator.
    Returns a validation_function to check that len(x) <= max_length (strict=False, default) or len(x) < max_length (strict=True)

    :param max_length: maximum length for x
    :param strict: Boolean flag to switch between len(x) <= max_length (strict=False) and len(x) < max_length
    (strict=True)
    :return:
    """
    if strict:
        def maxlen_(x):
            if len(x) < max_length:
                return True
            else:
                # raise Failure('maxlen: len(x) < ' + str(max_length) + ' does not hold for x=' + str(x))
                raise TooLong(wrong_value=x, max_length=max_length, strict=True)
    else:
        def maxlen_(x):
            if len(x) <= max_length:
                return True
            else:
                # raise Failure('maxlen: len(x) <= ' + str(max_length) + ' does not hold for x=' + str(x))
                raise TooLong(wrong_value=x, max_length=max_length, strict=False)

    maxlen_.__name__ = 'length_{}lesser_than_{}'.format('strictly_' if strict else '', max_length)
    return maxlen_

Response: Maximum length validation_function generator.


Instruction:
Can you generate the documentation for the following Python 3 function
def has_length(ref_length):
    def has_length_(x):
        if len(x) == ref_length:
            return True
        else:
            raise WrongLength(wrong_value=x, ref_length=ref_length)

    has_length_.__name__ = 'length_equals_{}'.format(ref_length)
    return has_length_

Response: length equals validation function generator.


Instruction:
Write a Python 3 script for
being length between validation_function generator.

Response:
def length_between(min_len,
                   max_len,
                   open_left=False,  # type: bool
                   open_right=False  # type: bool
                   ):
    """
    'Is length between' validation_function generator.
    Returns a validation_function to check that `min_len <= len(x) <= max_len (default)`. `open_right` and `open_left`
    flags allow to transform each side into strict mode. For example setting `open_left=True` will enforce
    `min_len < len(x) <= max_len`.

    :param min_len: minimum length for x
    :param max_len: maximum length for x
    :param open_left: Boolean flag to turn the left inequality to strict mode
    :param open_right: Boolean flag to turn the right inequality to strict mode
    :return:
    """
    if open_left and open_right:
        def length_between_(x):
            if (min_len < len(x)) and (len(x) < max_len):
                return True
            else:
                # raise Failure('length between: {} < len(x) < {} does not hold for x={}'.format(min_len, max_len,
                # x))
                raise LengthNotInRange(wrong_value=x, min_length=min_len, left_strict=True, max_length=max_len,
                                       right_strict=True)
    elif open_left:
        def length_between_(x):
            if (min_len < len(x)) and (len(x) <= max_len):
                return True
            else:
                # raise Failure('length between: {} < len(x) <= {} does not hold for x={}'.format(min_len, max_len,
                # x))
                raise LengthNotInRange(wrong_value=x, min_length=min_len, left_strict=True, max_length=max_len,
                                       right_strict=False)
    elif open_right:
        def length_between_(x):
            if (min_len <= len(x)) and (len(x) < max_len):
                return True
            else:
                # raise Failure('length between: {} <= len(x) < {} does not hold for x={}'.format(min_len, max_len,
                #  x))
                raise LengthNotInRange(wrong_value=x, min_length=min_len, left_strict=False, max_length=max_len,
                                       right_strict=True)
    else:
        def length_between_(x):
            if (min_len <= len(x)) and (len(x) <= max_len):
                return True
            else:
                # raise Failure('length between: {} <= len(x) <= {} does not hold for x={}'.format(min_len,
                #  max_len, x))
                raise LengthNotInRange(wrong_value=x, min_length=min_len, left_strict=False, max_length=max_len,
                                       right_strict=False)

    length_between_.__name__ = 'length_between_{}_and_{}'.format(min_len, max_len)
    return length_between_


Instruction:
Implement a function in Python 3 to
value in validation_function generator.

Response:
def is_in(allowed_values  # type: Set
          ):
    """
    'Values in' validation_function generator.
    Returns a validation_function to check that x is in the provided set of allowed values

    :param allowed_values: a set of allowed values
    :return:
    """
    def is_in_allowed_values(x):
        if x in allowed_values:
            return True
        else:
            # raise Failure('is_in: x in ' + str(allowed_values) + ' does not hold for x=' + str(x))
            raise NotInAllowedValues(wrong_value=x, allowed_values=allowed_values)

    is_in_allowed_values.__name__ = 'is_in_{}'.format(allowed_values)
    return is_in_allowed_values


Instruction:
Can you generate the documentation for the following Python 3 function
def is_subset(reference_set  # type: Set
              ):
    """
    'Is subset' validation_function generator.
    Returns a validation_function to check that x is a subset of reference_set

    :param reference_set: the reference set
    :return:
    """
    def is_subset_of(x):
        missing = x - reference_set
        if len(missing) == 0:
            return True
        else:
            # raise Failure('is_subset: len(x - reference_set) == 0 does not hold for x=' + str(x)
            #                   + ' and reference_set=' + str(reference_set) + '. x contains unsupported '
            #                      'elements ' + str(missing))
            raise NotSubset(wrong_value=x, reference_set=reference_set, unsupported=missing)

    is_subset_of.__name__ = 'is_subset_of_{}'.format(reference_set)
    return is_subset_of

Response: Is subset validation_function generator.


Instruction:
Here you have a function in Python 3, explain what it does
def is_superset(reference_set  # type: Set
                ):
    """
    'Is superset' validation_function generator.
    Returns a validation_function to check that x is a superset of reference_set

    :param reference_set: the reference set
    :return:
    """
    def is_superset_of(x):
        missing = reference_set - x
        if len(missing) == 0:
            return True
        else:
            # raise Failure('is_superset: len(reference_set - x) == 0 does not hold for x=' + str(x)
            #               + ' and reference_set=' + str(reference_set) + '. x does not contain required '
            #                       'elements ' + str(missing))
            raise NotSuperset(wrong_value=x, reference_set=reference_set, missing=missing)

    is_superset_of.__name__ = 'is_superset_of_{}'.format(reference_set)
    return is_superset_of

Response: Is superset validation_function generator.


Instruction:
How would you implement a function in Python 3 that
generates a validation_function for collection inputs where each element of the input is validated against the validation_function_func.

Response:
def on_all_(*validation_func):
    """
    Generates a validation_function for collection inputs where each element of the input will be validated against the
    validation_functions provided. For convenience, a list of validation_functions can be provided and will be replaced
    with an 'and_'.

    Note that if you want to apply DIFFERENT validation_functions for each element in the input, you should rather use
    on_each_.

    :param validation_func: the base validation function or list of base validation functions to use. A callable, a
    tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
    are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit
    `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
    of callables, they will be transformed to functions automatically.
    :return:
    """
    # create the validation functions
    validation_function_func = _process_validation_function_s(list(validation_func))

    def on_all_val(x):
        # validate all elements in x in turn
        for idx, x_elt in enumerate(x):
            try:
                res = validation_function_func(x_elt)
            except Exception as e:
                raise InvalidItemInSequence(wrong_value=x_elt, wrapped_func=validation_function_func, validation_outcome=e)

            if not result_is_success(res):
                # one element of x was not valid > raise
                # raise Failure('on_all_(' + str(validation_func) + '): failed validation for input '
                #                       'element [' + str(idx) + ']: ' + str(x_elt))
                raise InvalidItemInSequence(wrong_value=x_elt, wrapped_func=validation_function_func, validation_outcome=res)
        return True

    on_all_val.__name__ = 'apply_<{}>_on_all_elts'.format(get_callable_name(validation_function_func))
    return on_all_val


Instruction:
Explain what the following Python 3 code does
def on_each_(*validation_functions_collection):
    # create a tuple of validation functions.
    validation_function_funcs = tuple(_process_validation_function_s(validation_func)
                                      for validation_func in validation_functions_collection)

    # generate a validation function based on the tuple of validation_functions lists
    def on_each_val(x  # type: Tuple
                    ):
        if len(validation_function_funcs) != len(x):
            raise Failure('on_each_: x does not have the same number of elements than validation_functions_collection.')
        else:
            # apply each validation_function on the input with the same position in the collection
            idx = -1
            for elt, validation_function_func in zip(x, validation_function_funcs):
                idx += 1
                try:
                    res = validation_function_func(elt)
                except Exception as e:
                    raise InvalidItemInSequence(wrong_value=elt,
                                                wrapped_func=validation_function_func,
                                                validation_outcome=e)

                if not result_is_success(res):
                    # one validation_function was unhappy > raise
                    # raise Failure('on_each_(' + str(validation_functions_collection) + '): _validation_function [' + str(idx)
                    #               + '] (' + str(validation_functions_collection[idx]) + ') failed validation for '
                    #                       'input ' + str(x[idx]))
                    raise InvalidItemInSequence(wrong_value=elt,
                                                wrapped_func=validation_function_func,
                                                validation_outcome=res)
            return True

    on_each_val.__name__ = 'map_<{}>_on_elts' \
                           ''.format('(' + ', '.join([get_callable_name(f) for f in validation_function_funcs]) + ')')
    return on_each_val

Response: Generates a validation function for each element of the input.


Instruction:
Create a Python 3 function for
getting all the jobs events from a given sequence number.

Response:
def get_jobs_events_from_sequence(user, sequence):
    """Get all the jobs events from a given sequence number."""

    args = schemas.args(flask.request.args.to_dict())

    if user.is_not_super_admin():
        raise dci_exc.Unauthorized()

    query = sql.select([models.JOBS_EVENTS]). \
        select_from(models.JOBS_EVENTS.join(models.JOBS,
                    models.JOBS.c.id == models.JOBS_EVENTS.c.job_id)). \
        where(_TABLE.c.id >= sequence)
    sort_list = v1_utils.sort_query(args['sort'], _JOBS_EVENTS_COLUMNS,
                                    default='created_at')
    query = v1_utils.add_sort_to_query(query, sort_list)

    if args.get('limit', None):
        query = query.limit(args.get('limit'))
    if args.get('offset', None):
        query = query.offset(args.get('offset'))

    rows = flask.g.db_conn.execute(query).fetchall()

    query_nb_rows = sql.select([func.count(models.JOBS_EVENTS.c.id)])
    nb_rows = flask.g.db_conn.execute(query_nb_rows).scalar()

    return json.jsonify({'jobs_events': rows, '_meta': {'count': nb_rows}})


Instruction:
Given the following Python 3 function, write the documentation
def from_file(cls, f):
        element = ElementIterator.from_file(f)
        assert element.tag == "mediawiki"
        return cls.from_element(element)

Response: Constructs a : class ~mwxml. iteration. dump. Dump from a plain text file pointer.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def from_page_xml(cls, page_xml):
        header = """
        <mediawiki xmlns="http://www.mediawiki.org/xml/export-0.5/"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xsi:schemaLocation="http://www.mediawiki.org/xml/export-0.5/
                     http://www.mediawiki.org/xml/export-0.5.xsd" version="0.5"
                   xml:lang="en">
        <siteinfo>
        </siteinfo>
        """

        footer = "</mediawiki>"

        return cls.from_file(mwtypes.files.concat(header, page_xml, footer))

Response: Constructs a ~mwxml. iteration. dump. Dump from a page XML.


Instruction:
Explain what the following Python 3 code does
def calc_derivation(passphrase, salt):
    argonhash = argon2.low_level.hash_secret_raw((str.encode(passphrase)), salt=salt, hash_len=32,
                                                 time_cost=__argon2_timing_cost__, memory_cost=__argon2_memory_cost__,
                                                 parallelism=__argon2_parallelism__, type=argon2.low_level.Type.I)
    return argonhash

Response: Calculates a 32 bytes key derivation with Argon2.


Instruction:
Create a Python 3 function for
getting the text value of the node s children.

Response:
def get_node_text(self, node):
        """
        Return contatenated value of all text node children of this element
        """
        text_children = [n.nodeValue for n in self.get_node_children(node)
                         if n.nodeType == xml.dom.Node.TEXT_NODE]
        if text_children:
            return u''.join(text_children)
        else:
            return None


Instruction:
Can you create a Python 3 function that
sets text value of node.

Response:
def set_node_text(self, node, text):
        """
        Set text value as sole Text child node of element; any existing
        Text nodes are removed
        """
        # Remove any existing Text node children
        for child in self.get_node_children(node):
            if child.nodeType == xml.dom.Node.TEXT_NODE:
                self.remove_node_child(node, child, True)
        if text is not None:
            text_node = self.new_impl_text(text)
            self.add_node_child(node, text_node)


Instruction:
Create a Python 3 function for
creating strings from glob strings.

Response:
def _get_contents(self):
        """Create strings from glob strings."""
        def files():
            for value in super(GlobBundle, self)._get_contents():
                for path in glob.glob(value):
                    yield path
        return list(files())


Instruction:
Given the following Python 3 function, write the documentation
def is_generic_type(tp):
    if NEW_TYPING:
        return (isinstance(tp, type) and issubclass(tp, Generic) or
                isinstance(tp, _GenericAlias) and
                tp.__origin__ not in (Union, tuple, ClassVar, collections.abc.Callable))
    # SMA: refering to is_callable_type and is_tuple_type to avoid duplicate code
    return isinstance(tp, GenericMeta) and not is_callable_type(tp) and not is_tuple_type(tp)

Response: Test if the given type is a generic type.


Instruction:
Make a summary of the following Python 3 code
def is_union_type(tp):
    if NEW_TYPING:
        return (tp is Union or
                isinstance(tp, _GenericAlias) and tp.__origin__ is Union)
    try:
        from typing import _Union
        return type(tp) is _Union
    except ImportError:
        # SMA: support for very old typing module <=3.5.3
        return type(tp) is Union or type(tp) is type(Union)

Response: Test if the type is a union type.


Instruction:
How would you implement a function in Python 3 that
tests if the type represents a class variable.

Response:
def is_classvar(tp):
    """Test if the type represents a class variable. Examples::

        is_classvar(int) == False
        is_classvar(ClassVar) == True
        is_classvar(ClassVar[int]) == True
        is_classvar(ClassVar[List[T]]) == True
    """
    if NEW_TYPING:
        return (tp is ClassVar or
                isinstance(tp, _GenericAlias) and tp.__origin__ is ClassVar)
    try:
        from typing import _ClassVar
        return type(tp) is _ClassVar
    except:
        # SMA: support for very old typing module <=3.5.3
        return False


Instruction:
Here you have a function in Python 3, explain what it does
def parse(to_parse, ignore_whitespace_text_nodes=True, adapter=None):
    if adapter is None:
        adapter = best_adapter
    if isinstance(to_parse, basestring) and '<' in to_parse:
        return adapter.parse_string(to_parse, ignore_whitespace_text_nodes)
    else:
        return adapter.parse_file(to_parse, ignore_whitespace_text_nodes)

Response: Parses an XML document into an XML structure.


Instruction:
Can you create a Python 3 function that
builds a new XML tree tree.

Response:
def build(tagname_or_element, ns_uri=None, adapter=None):
    """
    Return a :class:`~xml4h.builder.Builder` that represents an element in
    a new or existing XML DOM and provides "chainable" methods focussed
    specifically on adding XML content.

    :param tagname_or_element: a string name for the root node of a
        new XML document, or an :class:`~xml4h.nodes.Element` node in an
        existing document.
    :type tagname_or_element: string or :class:`~xml4h.nodes.Element` node
    :param ns_uri: a namespace URI to apply to the new root node. This
        argument has no effect this method is acting on an element.
    :type ns_uri: string or None
    :param adapter: the *xml4h* implementation adapter class used to
        interact with the document DOM nodes.
        If None, :attr:`best_adapter` will be used.
    :type adapter: adapter class or None

    :return: a :class:`~xml4h.builder.Builder` instance that represents an
        :class:`~xml4h.nodes.Element` node in an XML DOM.
    """
    if adapter is None:
        adapter = best_adapter
    if isinstance(tagname_or_element, basestring):
        doc = adapter.create_document(
            tagname_or_element, ns_uri=ns_uri)
        element = doc.root
    elif isinstance(tagname_or_element, xml4h.nodes.Element):
        element = tagname_or_element
    else:
        raise xml4h.exceptions.IncorrectArgumentTypeException(
            tagname_or_element, [basestring, xml4h.nodes.Element])
    return Builder(element)


Instruction:
Create a Python 3 function for
returning a user - friendly description of a NonePolicy taking into account NoneArgPolicy orrow

Response:
def get_none_policy_text(none_policy,   # type: int
                         verbose=False  # type: bool
                         ):
    """
    Returns a user-friendly description of a NonePolicy taking into account NoneArgPolicy

    :param none_policy:
    :param verbose:
    :return:
    """
    if none_policy is NonePolicy.SKIP:
        return "accept None without performing validation" if verbose else 'SKIP'
    elif none_policy is NonePolicy.FAIL:
        return "fail on None without performing validation" if verbose else 'FAIL'
    elif none_policy is NonePolicy.VALIDATE:
        return "validate None as any other values" if verbose else 'VALIDATE'
    elif none_policy is NoneArgPolicy.SKIP_IF_NONABLE_ELSE_FAIL:
        return "accept None without validation if the argument is optional, otherwise fail on None" if verbose \
            else 'SKIP_IF_NONABLE_ELSE_FAIL'
    elif none_policy is NoneArgPolicy.SKIP_IF_NONABLE_ELSE_VALIDATE:
        return "accept None without validation if the argument is optional, otherwise validate None as any other " \
               "values" if verbose else 'SKIP_IF_NONABLE_ELSE_VALIDATE'
    else:
        raise ValueError('Invalid none_policy ' + str(none_policy))


Instruction:
How would you explain what the following Python 3 function does
def _add_none_handler(validation_callable,  # type: Callable
                      none_policy           # type: int
                      ):
    # type: (...) -> Callable
    """
    Adds a wrapper or nothing around the provided validation_callable, depending on the selected policy

    :param validation_callable:
    :param none_policy: an int representing the None policy, see NonePolicy
    :return:
    """
    if none_policy is NonePolicy.SKIP:
        return _none_accepter(validation_callable)  # accept all None values

    elif none_policy is NonePolicy.FAIL:
        return _none_rejecter(validation_callable)  # reject all None values

    elif none_policy is NonePolicy.VALIDATE:
        return validation_callable                  # do not handle None specifically, do not wrap

    else:
        raise ValueError('Invalid none_policy : ' + str(none_policy))

Response: Adds a wrapper or nothing around the provided validation_callable depending on the selected NonePolicy.


Instruction:
How would you explain what the following Python 3 function does
def add_base_type_dynamically(error_type, additional_type):
    # the new type created dynamically, with the same name
    class new_error_type(with_metaclass(MetaReprForValidator, error_type, additional_type, object)):
        pass

    new_error_type.__name__ = error_type.__name__ + '[' + additional_type.__name__ + ']'
    if sys.version_info >= (3, 0):
        new_error_type.__qualname__ = error_type.__qualname__ + '[' + additional_type.__qualname__+ ']'
    new_error_type.__module__ = error_type.__module__

    return new_error_type

Response: Utility method to create a new type dynamically inheriting from both error_type and additional_type.


Instruction:
Can you generate the documentation for the following Python 3 function
def assert_valid(name,              # type: str
                 value,             # type: Any
                 *validation_func,  # type: ValidationFuncs
                 **kwargs):
    """
    Validates value `value` using validation function(s) `base_validator_s`.
    As opposed to `is_valid`, this function raises a `ValidationError` if validation fails.

    It is therefore designed to be used for defensive programming, in an independent statement before the code that you
    intent to protect.

    ```python
    assert_valid(x, isfinite):
    ...<your code>
    ```

    Note: this is a friendly alias for `_validator(base_validator_s)(value)`

    :param validation_func: the base validation function or list of base validation functions to use. A callable, a
        tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
        are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit
        `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
        of callables, they will be transformed to functions automatically.
    :param name: the name of the variable to validate. It will be used in error messages
    :param value: the value to validate
    :param none_policy: describes how None values should be handled. See `NonePolicy` for the various possibilities.
        Default is `NonePolicy.VALIDATE`, meaning that None values will be treated exactly like other values and follow
        the same validation process.
    :param error_type: a subclass of ValidationError to raise in case of validation failure. By default a
        ValidationError will be raised with the provided help_msg
    :param help_msg: an optional help message to be used in the raised error in case of validation failure.
    :param kw_context_args: optional keyword arguments providing additional context, that will be provided to the error
        in case of validation failure
    :return: nothing in case of success. In case of failure, raises a <error_type> if provided, or a ValidationError.
    """
    error_type, help_msg, none_policy = pop_kwargs(kwargs, [('error_type', None),
                                                            ('help_msg', None),
                                                            ('none_policy', None)], allow_others=True)
    # the rest of keyword arguments is used as context.
    kw_context_args = kwargs

    return Validator(*validation_func, error_type=error_type, help_msg=help_msg,
                     none_policy=none_policy).assert_valid(name=name, value=value, **kw_context_args)

Response: Ensures that a value is valid for a given variable.


Instruction:
Write a Python 3 script to
validate value using validation function.

Response:
def is_valid(value,
             *validation_func,  # type: Union[Callable, List[Callable]]
             **kwargs
             ):
    # type: (...) -> bool
    """
    Validates value `value` using validation function(s) `validator_func`.
    As opposed to `assert_valid`, this function returns a boolean indicating if validation was a success or a failure.
    It is therefore designed to be used within if ... else ... statements:

    ```python
    if is_valid(x, isfinite):
        ...<code>
    else
        ...<code>
    ```

    Note: this is a friendly alias for `return _validator(validator_func, return_bool=True)(value)`

    :param validation_func: the base validation function or list of base validation functions to use. A callable, a
    tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
    are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit
    `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
    of callables, they will be transformed to functions automatically.
    :param value: the value to validate
    :param none_policy: describes how None values should be handled. See `NonePolicy` for the various possibilities.
    Default is `NonePolicy.VALIDATE`, meaning that None values will be treated exactly like other values and follow
    the same validation process. Note that errors raised by NonePolicy.FAIL will be caught and transformed into a
    returned value of False
    :return: True if validation was a success, False otherwise
    """
    none_policy = pop_kwargs(kwargs, [('none_policy', None)])

    return Validator(*validation_func, none_policy=none_policy).is_valid(value)


Instruction:
Can you implement a function in Python 3 that
creates an exception or a validator with a specific name.

Response:
def create_manually(cls,
                        validation_function_name,  # type: str
                        var_name,                  # type: str
                        var_value,
                        validation_outcome=None,   # type: Any
                        help_msg=None,             # type: str
                        append_details=True,       # type: bool
                        **kw_context_args):
        """
        Creates an instance without using a Validator.

        This method is not the primary way that errors are created - they should rather created by the validation entry
        points. However it can be handy in rare edge cases.

        :param validation_function_name:
        :param var_name:
        :param var_value:
        :param validation_outcome:
        :param help_msg:
        :param append_details:
        :param kw_context_args:
        :return:
        """
        # create a dummy validator
        def val_fun(x):
            pass
        val_fun.__name__ = validation_function_name
        validator = Validator(val_fun, error_type=cls, help_msg=help_msg, **kw_context_args)

        # create the exception
        # e = cls(validator, var_value, var_name, validation_outcome=validation_outcome, help_msg=help_msg,
        #         append_details=append_details, **kw_context_args)
        e = validator._create_validation_error(var_name, var_value, validation_outcome, error_type=cls,
                                               help_msg=help_msg, **kw_context_args)
        return e


Instruction:
Make a summary of the following Python 3 code
def get_details(self):

        # create the exception main message according to the type of result
        if isinstance(self.validation_outcome, Exception):

            prefix = 'Validation function [{val}] raised ' if self.display_prefix_for_exc_outcomes else ''

            # new: we now remove  "Root validator was [{validator}]", users can get it through e.validator
            contents = ('Error validating {what}. ' + prefix + '{exception}: {details}')\
                         .format(what=self.get_what_txt(),
                                 val=self.validator.get_main_function_name(),
                                 exception=type(self.validation_outcome).__name__,
                                 details=end_with_dot(str(self.validation_outcome)))

        else:
            contents = 'Error validating {what}: validation function [{val}] returned [{result}].' \
                       ''.format(what=self.get_what_txt(), val=self.validator.get_main_function_name(),
                                 result=self.validation_outcome)

        # return 'Wrong value: [{}]'.format(self.var_value)
        return contents

Response: This function returns the details of the error and the exception main message according to the type of validation outcome.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def assert_valid(self,
                     name,             # type: str
                     value,            # type: Any
                     error_type=None,  # type: Type[ValidationError]
                     help_msg=None,    # type: str
                     **kw_context_args):
        """
        Asserts that the provided named value is valid with respect to the inner base validation functions. It returns
        silently in case of success, and raises a `ValidationError` or a subclass in case of failure. This corresponds
        to a 'Defensive programming' (sometimes known as 'Offensive programming') mode.

        By default this raises instances of `ValidationError` with a default message, in case of failure. There are
        two ways that you can customize this behaviour:

         * if you set `help_msg` in this method or in `Validator` constructor, instances of `ValidationError` created
         will be customized with the provided help message.

         * if you set `error_type` in this method or in `Validator` constructor, instances of your custom class will be
         created. Note that you may still provide a `help_msg`.

        It is recommended that Users define their own validation error types (case 2 above), so as to provide a unique
        error type for each kind of applicative error. This eases the process of error handling at app-level.

        :param name: the name of the variable to validate (for error messages)
        :param value: the value to validate
        :param error_type: a subclass of `ValidationError` to raise in case of validation failure. By default a
            `ValidationError` will be raised with the provided `help_msg`
        :param help_msg: an optional help message to be used in the raised error in case of validation failure.
        :param kw_context_args: optional contextual information to store in the exception, and that may be also used
            to format the help message
        :return: nothing in case of success. Otherwise, raises a ValidationError
        """
        try:
            # perform validation
            res = self.main_function(value)

        except Exception as e:
            # caught any exception: raise ValidationError or subclass with that exception in the details
            # --old bad idea: first wrap into a failure ==> NO !!! I tried and it was making it far too messy/verbose

            # note: we do not have to 'raise x from e' of `raise_from`since the ValidationError constructor already
            # sets the __cause__ so we can safely take the same handling than for non-exception failures.
            res = e

        # check the result
        if not result_is_success(res):
            raise_(self._create_validation_error(name, value, validation_outcome=res, error_type=error_type,
                                                 help_msg=help_msg, **kw_context_args))

Response: This method checks that the provided value is valid with respect to the inner base validation functions.


Instruction:
Create a Python 3 function to
create a validation error for the current object.

Response:
def _create_validation_error(self,
                                 name,                     # type: str
                                 value,                    # type: Any
                                 validation_outcome=None,  # type: Any
                                 error_type=None,          # type: Type[ValidationError]
                                 help_msg=None,            # type: str
                                 **kw_context_args):
        """ The function doing the final error raising.  """

        # first merge the info provided in arguments and in self
        error_type = error_type or self.error_type
        help_msg = help_msg or self.help_msg
        ctx = copy(self.kw_context_args)
        ctx.update(kw_context_args)

        # allow the class to override the name
        name = self._get_name_for_errors(name)

        if issubclass(error_type, TypeError) or issubclass(error_type, ValueError):
            # this is most probably a custom error type, it is already annotated with ValueError and/or TypeError
            # so use it 'as is'
            new_error_type = error_type
        else:
            # Add the appropriate TypeError/ValueError base type dynamically
            additional_type = None
            if isinstance(validation_outcome, Exception):
                if is_error_of_type(validation_outcome, TypeError):
                    additional_type = TypeError
                elif is_error_of_type(validation_outcome, ValueError):
                    additional_type = ValueError
            if additional_type is None:
                # not much we can do here, let's assume a ValueError, that is more probable
                additional_type = ValueError

            new_error_type = add_base_type_dynamically(error_type, additional_type)

        # then raise the appropriate ValidationError or subclass
        return new_error_type(validator=self, var_value=value, var_name=name, validation_outcome=validation_outcome,
                              help_msg=help_msg, **ctx)


Instruction:
How would you implement a function in Python 3 that
validates the provided value and returns a boolean indicating success or failure.

Response:
def is_valid(self,
                 value  # type: Any
                 ):
        # type: (...) -> bool
        """
        Validates the provided value and returns a boolean indicating success or failure. Any Exception happening in
        the validation process will be silently caught.

        :param value: the value to validate
        :return: a boolean flag indicating success or failure
        """
        # noinspection PyBroadException
        try:
            # perform validation
            res = self.main_function(value)

            # return a boolean indicating if success or failure
            return result_is_success(res)

        except Exception:
            # caught exception means failure > return False
            return False


Instruction:
How would you implement a function in Python 3 that
deletes a tag by id.

Response:
def delete_tag_by_id(user, tag_id):
    """Delete a tag."""
    query = _TABLE.delete().where(_TABLE.c.id == tag_id)
    result = flask.g.db_conn.execute(query)

    if not result.rowcount:
        raise dci_exc.DCIConflict('Tag deletion conflict', tag_id)

    return flask.Response(None, 204, content_type='application/json')


Instruction:
Make a summary of the following Python 3 code
def init_app(self, app, entry_point_group='invenio_assets.bundles',
                 **kwargs):
        """Initialize application object.

        :param app: An instance of :class:`~flask.Flask`.
        :param entry_point_group: A name of entry point group used to load
            ``webassets`` bundles.

        .. versionchanged:: 1.0.0b2
           The *entrypoint* has been renamed to *entry_point_group*.
        """
        self.init_config(app)
        self.env.init_app(app)
        self.collect.init_app(app)
        self.webpack.init_app(app)

        if entry_point_group:
            self.load_entrypoint(entry_point_group)

        app.extensions['invenio-assets'] = self

Response:
Initialize application object.

        :param app: An instance of :class:`~flask.Flask`.
        :param entry_point_group: A name of entry point group used to load
            ``webassets`` bundles.

        .. versionchanged:: 1.0.0b2
           The *entrypoint* has been renamed to *entry_point_group*.


Instruction:
Explain what the following Python 3 code does
def init_config(self, app):
        app.config.setdefault('REQUIREJS_BASEURL', app.static_folder)
        app.config.setdefault('COLLECT_STATIC_ROOT', app.static_folder)
        app.config.setdefault('COLLECT_STORAGE', 'flask_collect.storage.link')
        app.config.setdefault(
            'COLLECT_FILTER', partial(collect_staticroot_removal, app))
        app.config.setdefault(
            'WEBPACKEXT_PROJECT', 'invenio_assets.webpack:project')

Response:
Initialize configuration.

        :param app: An instance of :class:`~flask.Flask`.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def load_entrypoint(self, entry_point_group):
        for ep in pkg_resources.iter_entry_points(entry_point_group):
            self.env.register(ep.name, ep.load())

Response: Load the entry point.


Instruction:
Can you create a Python 3 function that
checks that value is an instance of one of the allowed types.

Response:
def assert_instance_of(value,
                       allowed_types  # type: Union[Type, Tuple[Type]]
                       ):
    """
    An inlined version of instance_of(var_types)(value) without 'return True': it does not return anything in case of
    success, and raises a HasWrongType exception in case of failure.

    Used in validate and validation/validator

    :param value: the value to check
    :param allowed_types: the type(s) to enforce. If a tuple of types is provided it is considered alternate types: one
        match is enough to succeed. If None, type will not be enforced
    :return:
    """
    if not isinstance(value, allowed_types):
        try:
            # more than 1 ?
            allowed_types[1]
            raise HasWrongType(wrong_value=value, ref_type=allowed_types,
                               help_msg='Value should be an instance of any of {ref_type}')
        except IndexError:
            # 1
            allowed_types = allowed_types[0]
        except TypeError:
            # 1
            pass
        raise HasWrongType(wrong_value=value, ref_type=allowed_types)


Instruction:
Given the following Python 3 function, write the documentation
def assert_subclass_of(typ,
                       allowed_types  # type: Union[Type, Tuple[Type]]
                       ):
    """
    An inlined version of subclass_of(var_types)(value) without 'return True': it does not return anything in case of
    success, and raises a IsWrongType exception in case of failure.

    Used in validate and validation/validator

    :param typ: the type to check
    :param allowed_types: the type(s) to enforce. If a tuple of types is provided it is considered alternate types:
        one match is enough to succeed. If None, type will not be enforced
    :return:
    """
    if not issubclass(typ, allowed_types):
        try:
            # more than 1 ?
            allowed_types[1]
            raise IsWrongType(wrong_value=typ, ref_type=allowed_types,
                              help_msg='Value should be a subclass of any of {ref_type}')
        except IndexError:
            # 1
            allowed_types = allowed_types[0]
        except TypeError:
            # 1
            pass
        raise IsWrongType(wrong_value=typ, ref_type=allowed_types)

Response: Checks that the value is a subclass of the type specified in typ.


Instruction:
Given the following Python 3 function, write the documentation
def validate(name,                   # type: str
             value,                  # type: Any
             enforce_not_none=True,  # type: bool
             equals=None,            # type: Any
             instance_of=None,       # type: Union[Type, Tuple[Type]]
             subclass_of=None,       # type: Union[Type, Tuple[Type]]
             is_in=None,             # type: Container
             subset_of=None,         # type: Set
             contains = None,        # type: Union[Any, Iterable]
             superset_of=None,       # type: Set
             min_value=None,         # type: Any
             min_strict=False,       # type: bool
             max_value=None,         # type: Any
             max_strict=False,       # type: bool
             length=None,            # type: int
             min_len=None,           # type: int
             min_len_strict=False,   # type: bool
             max_len=None,           # type: int
             max_len_strict=False,   # type: bool
             custom=None,            # type: Callable[[Any], Any]
             error_type=None,        # type: Type[ValidationError]
             help_msg=None,          # type: str
             **kw_context_args):
    """
    A validation function for quick inline validation of `value`, with minimal capabilities:

    * None handling: reject None (enforce_not_none=True, default), or accept None silently (enforce_not_none=False)
    * Type validation: `value` should be an instance of any of `var_types` if provided
    * Value validation:
       * if `allowed_values` is provided, `value` should be in that set
       * if `min_value` (resp. `max_value`) is provided, `value` should be greater than it. Comparison is not strict by
       default and can be set to strict by setting `min_strict`, resp. `max_strict`, to `True`
       * if `min_len` (resp. `max_len`) is provided, `len(value)` should be greater than it. Comparison is not strict by
       default and can be set to strict by setting `min_len_strict`, resp. `max_len_strict`, to `True`

    :param name: the applicative name of the checked value, that will be used in error messages
    :param value: the value to check
    :param enforce_not_none: boolean, default True. Whether to enforce that `value` is not None.
    :param equals: an optional value to enforce.
    :param instance_of: optional type(s) to enforce. If a tuple of types is provided it is considered alternate types: one
        match is enough to succeed. If None, type will not be enforced
    :param subclass_of: optional type(s) to enforce. If a tuple of types is provided it is considered alternate types: one
        match is enough to succeed. If None, type will not be enforced
    :param is_in: an optional set of allowed values.
    :param subset_of: an optional superset for the variable
    :param contains: an optional value that the variable should contain (value in variable == True)
    :param superset_of: an optional subset for the variable
    :param min_value: an optional minimum value
    :param min_strict: if True, only values strictly greater than `min_value` will be accepted
    :param max_value: an optional maximum value
    :param max_strict: if True, only values strictly lesser than `max_value` will be accepted
    :param length: an optional strict length
    :param min_len: an optional minimum length
    :param min_len_strict: if True, only values with length strictly greater than `min_len` will be accepted
    :param max_len: an optional maximum length
    :param max_len_strict: if True, only values with length strictly lesser than `max_len` will be accepted
    :param custom: a custom base validation function or list of base validation functions to use. This is the same
        syntax than for valid8 decorators. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type),
        or a list of several such elements. Nested lists are supported and indicate an implicit `and_`. Tuples indicate
        an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be
        used instead of callables, they will be transformed to functions automatically.
    :param error_type: a subclass of `ValidationError` to raise in case of validation failure. By default a
        `ValidationError` will be raised with the provided `help_msg`
    :param help_msg: an optional help message to be used in the raised error in case of validation failure.
    :param kw_context_args: optional contextual information to store in the exception, and that may be also used
        to format the help message
    :return: nothing in case of success. Otherwise, raises a ValidationError
    """

    # backwards compatibility
    instance_of = instance_of or (kw_context_args.pop('allowed_types') if 'allowed_types' in kw_context_args else None)
    is_in = is_in or (kw_context_args.pop('allowed_values') if 'allowed_values' in kw_context_args else None)

    try:
        # the following corresponds to an inline version of
        # - _none_rejecter in base.py
        # - gt/lt in comparables.py
        # - is_in/contains/subset_of/superset_of/has_length/minlen/maxlen/is_in in collections.py
        # - instance_of/subclass_of in types.py

        # try (https://github.com/orf/inliner) to perform the inlining below automatically without code duplication ?
        # > maybe not because quite dangerous (AST mod) and below we skip the "return True" everywhere for performance
        #
        # Another alternative: easy Cython compiling https://github.com/AlanCristhian/statically
        # > but this is not py2 compliant

        if value is None:
            # inlined version of _none_rejecter in base.py
            if enforce_not_none:
                raise ValueIsNone(wrong_value=value)
                # raise MissingMandatoryParameterException('Error, ' + name + '" is mandatory, it should be non-None')

            # else do nothing and return

        else:
            if equals is not None:
                if value != equals:
                    raise NotEqual(wrong_value=value, ref_value=equals)

            if instance_of is not None:
                assert_instance_of(value, instance_of)

            if subclass_of is not None:
                assert_subclass_of(value, subclass_of)

            if is_in is not None:
                # inlined version of is_in(allowed_values=allowed_values)(value) without 'return True'
                if value not in is_in:
                    raise NotInAllowedValues(wrong_value=value, allowed_values=is_in)

            if contains is not None:
                # inlined version of contains(ref_value=contains)(value) without 'return True'
                if contains not in value:
                    raise DoesNotContainValue(wrong_value=value, ref_value=contains)

            if subset_of is not None:
                # inlined version of is_subset(reference_set=subset_of)(value)
                missing = value - subset_of
                if len(missing) != 0:
                    raise NotSubset(wrong_value=value, reference_set=subset_of, unsupported=missing)

            if superset_of is not None:
                # inlined version of is_superset(reference_set=superset_of)(value)
                missing = superset_of - value
                if len(missing) != 0:
                    raise NotSuperset(wrong_value=value, reference_set=superset_of, missing=missing)

            if min_value is not None:
                # inlined version of gt(min_value=min_value, strict=min_strict)(value) without 'return True'
                if min_strict:
                    if not value > min_value:
                        raise TooSmall(wrong_value=value, min_value=min_value, strict=True)
                else:
                    if not value >= min_value:
                        raise TooSmall(wrong_value=value, min_value=min_value, strict=False)

            if max_value is not None:
                # inlined version of lt(max_value=max_value, strict=max_strict)(value) without 'return True'
                if max_strict:
                    if not value < max_value:
                        raise TooBig(wrong_value=value, max_value=max_value, strict=True)
                else:
                    if not value <= max_value:
                        raise TooBig(wrong_value=value, max_value=max_value, strict=False)

            if length is not None:
                # inlined version of has_length() without 'return True'
                if len(value) != length:
                    raise WrongLength(wrong_value=value, ref_length=length)

            if min_len is not None:
                # inlined version of minlen(min_length=min_len, strict=min_len_strict)(value) without 'return True'
                if min_len_strict:
                    if not len(value) > min_len:
                        raise TooShort(wrong_value=value, min_length=min_len, strict=True)
                else:
                    if not len(value) >= min_len:
                        raise TooShort(wrong_value=value, min_length=min_len, strict=False)

            if max_len is not None:
                # inlined version of maxlen(max_length=max_len, strict=max_len_strict)(value) without 'return True'
                if max_len_strict:
                    if not len(value) < max_len:
                        raise TooLong(wrong_value=value, max_length=max_len, strict=True)
                else:
                    if not len(value) <= max_len:
                        raise TooLong(wrong_value=value, max_length=max_len, strict=False)

    except Exception as e:
        err = _QUICK_VALIDATOR._create_validation_error(name, value, validation_outcome=e, error_type=error_type,
                                                        help_msg=help_msg, **kw_context_args)
        raise_(err)

    if custom is not None:
        # traditional custom validator
        assert_valid(name, value, custom, error_type=error_type, help_msg=help_msg, **kw_context_args)
    else:
        # basic (and not enough) check to verify that there was no typo leading an argument to be put in kw_context_args
        if error_type is None and help_msg is None and len(kw_context_args) > 0:
            raise ValueError("Keyword context arguments have been provided but help_msg and error_type are not: {}"
                             "".format(kw_context_args))

Response: Generic validation function for quick inline validation of a value.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def gt(min_value,    # type: Any
       strict=False  # type: bool
       ):
    """
    'Greater than' validation_function generator.
    Returns a validation_function to check that x >= min_value (strict=False, default) or x > min_value (strict=True)

    :param min_value: minimum value for x
    :param strict: Boolean flag to switch between x >= min_value (strict=False) and x > min_value (strict=True)
    :return:
    """
    if strict:
        def gt_(x):
            if x > min_value:
                return True
            else:
                # raise Failure('x > ' + str(min_value) + ' does not hold for x=' + str(x))
                # '{val} is not strictly greater than {ref}'
                raise TooSmall(wrong_value=x, min_value=min_value, strict=True)
    else:
        def gt_(x):
            if x >= min_value:
                return True
            else:
                # raise Failure('x >= ' + str(min_value) + ' does not hold for x=' + str(x))
                # '{val} is not greater than {ref}'
                raise TooSmall(wrong_value=x, min_value=min_value, strict=False)

    gt_.__name__ = '{}greater_than_{}'.format('strictly_' if strict else '', min_value)
    return gt_

Response: Returns a validation_function generator. It returns a validation_function to check that x > = min_value


Instruction:
Here you have a function in Python 3, explain what it does
def lt(max_value,    # type: Any
       strict=False  # type: bool
       ):
    """
    'Lesser than' validation_function generator.
    Returns a validation_function to check that x <= max_value (strict=False, default) or x < max_value (strict=True)

    :param max_value: maximum value for x
    :param strict: Boolean flag to switch between x <= max_value (strict=False) and x < max_value (strict=True)
    :return:
    """
    if strict:
        def lt_(x):
            if x < max_value:
                return True
            else:
                # raise Failure('x < ' + str(max_value) + ' does not hold for x=' + str(x))
                # '{val} is not strictly lesser than {ref}'
                raise TooBig(wrong_value=x, max_value=max_value, strict=True)
    else:
        def lt_(x):
            if x <= max_value:
                return True
            else:
                # raise Failure('x <= ' + str(max_value) + ' does not hold for x=' + str(x))
                # '{val} is not lesser than {ref}'
                raise TooBig(wrong_value=x, max_value=max_value, strict=False)

    lt_.__name__ = '{}lesser_than_{}'.format('strictly_' if strict else '', max_value)
    return lt_

Response: Returns a validation_function generator. It checks that x < max_value and returns True if x < max_value


Instruction:
How would you explain what the following Python 3 function does
def between(min_val,          # type: Any
            max_val,          # type: Any
            open_left=False,  # type: bool
            open_right=False  # type: bool
            ):
    """
    'Is between' validation_function generator.
    Returns a validation_function to check that min_val <= x <= max_val (default). open_right and open_left flags allow
    to transform each side into strict mode. For example setting open_left=True will enforce min_val < x <= max_val

    :param min_val: minimum value for x
    :param max_val: maximum value for x
    :param open_left: Boolean flag to turn the left inequality to strict mode
    :param open_right: Boolean flag to turn the right inequality to strict mode
    :return:
    """
    if open_left and open_right:
        def between_(x):
            if (min_val < x) and (x < max_val):
                return True
            else:
                # raise Failure('{} < x < {} does not hold for x={}'.format(min_val, max_val, x))
                raise NotInRange(wrong_value=x, min_value=min_val, left_strict=True,
                                 max_value=max_val, right_strict=True)
    elif open_left:
        def between_(x):
            if (min_val < x) and (x <= max_val):
                return True
            else:
                # raise Failure('between: {} < x <= {} does not hold for x={}'.format(min_val, max_val, x))
                raise NotInRange(wrong_value=x, min_value=min_val, left_strict=True,
                                 max_value=max_val, right_strict=False)
    elif open_right:
        def between_(x):
            if (min_val <= x) and (x < max_val):
                return True
            else:
                # raise Failure('between: {} <= x < {} does not hold for x={}'.format(min_val, max_val, x))
                raise NotInRange(wrong_value=x, min_value=min_val, left_strict=False,
                                 max_value=max_val, right_strict=True)
    else:
        def between_(x):
            if (min_val <= x) and (x <= max_val):
                return True
            else:
                # raise Failure('between: {} <= x <= {} does not hold for x={}'.format(min_val, max_val, x))
                raise NotInRange(wrong_value=x, min_value=min_val, left_strict=False,
                                 max_value=max_val, right_strict=False)

    between_.__name__ = 'between_{}_and_{}'.format(min_val, max_val)
    return between_

Response: Is between validation_function generator.


Instruction:
Here you have a function in Python 3, explain what it does
def _sub_process_main(started_event: Event,
                      channel_name: str,
                      connection: Connection,
                      consumer_configuration: BrightsideConsumerConfiguration,
                      consumer_factory: Callable[[Connection, BrightsideConsumerConfiguration, logging.Logger], BrightsideConsumer],
                      command_processor_factory: Callable[[str], CommandProcessor],
                      mapper_func: Callable[[BrightsideMessage], Request]) -> None:
    """
    This is the main method for the sub=process, everything we need to create the message pump and
    channel it needs to be passed in as parameters that can be pickled as when we run they will be serialized
    into this process. The data should be value types, not reference types as we will receive a copy of the original.
    Inter-process communication is signalled by the event - to indicate startup - and the pipeline to facilitate a
    sentinel or stop message
    :param started_event: Used by the sub-process to signal that it is ready
    :param channel_name: The name we want to give the channel to the broker for identification
    :param connection: The 'broker' connection
    :param consumer_configuration: How to configure our consumer of messages from the channel
    :param consumer_factory: Callback to create the consumer. User code as we don't know what consumer library they
        want to use. Arame? Something else?
    :param command_processor_factory: Callback to  register subscribers, policies, and task queues then build command
        processor. User code that provides us with their requests and handlers
    :param mapper_func: We need to map between messages on the wire and our handlers
    :return:
    """

    logger = logging.getLogger(__name__)
    consumer = consumer_factory(connection, consumer_configuration, logger)
    channel = Channel(name=channel_name, consumer=consumer, pipeline=consumer_configuration.pipeline)

    # TODO: Fix defaults that need passed in config values
    command_processor = command_processor_factory(channel_name)
    message_pump = MessagePump(command_processor=command_processor, channel=channel, mapper_func=mapper_func,
                               timeout=500, unacceptable_message_limit=None, requeue_count=None)

    logger.debug("Starting the message pump for %s", channel_name)
    message_pump.run(started_event)

Response: This is the main method for the sub - process. It is called by the main function of the main function of the sub - process.


Instruction:
Can you implement a function in Python 3 that
runs migrations in offline mode.

Response:
def run_migrations_offline():
    """Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.

    Calls to context.execute() here emit the given string to the
    script output.

    """
    app_conf = dci_config.generate_conf()
    url = app_conf['SQLALCHEMY_DATABASE_URI']
    context.configure(
        url=url, target_metadata=target_metadata, literal_binds=True,
    )

    with context.begin_transaction():
        context.run_migrations()


Instruction:
Can you generate the documentation for the following Python 3 function
def run_migrations_online():
    app_conf = dci_config.generate_conf()
    connectable = dci_config.get_engine(app_conf)
    with connectable.connect() as connection:
        context.configure(
            connection=connection,
            target_metadata=target_metadata,
        )

        with context.begin_transaction():
            context.run_migrations()

Response: Run migrations in online mode.


Instruction:
Can you write a function in Python 3 where it
sends a 401 reject response that enables basic auth.

Response:
def reject():
    """Sends a 401 reject response that enables basic auth."""

    auth_message = ('Could not verify your access level for that URL.'
                    'Please login with proper credentials.')
    auth_message = json.dumps({'_status': 'Unauthorized',
                               'message': auth_message})

    headers = {'WWW-Authenticate': 'Basic realm="Login required"'}
    return flask.Response(auth_message, 401, headers=headers,
                          content_type='application/json')


Instruction:
Can you write a function in Python 3 where it
modifies a contact. Returns status message Optional Parameters: * name -- Contact name Type: String * email -- Contact email address Type: String * cellphone -- Cellphone number, without the country code part. In some countries you are supposed to exclude leading zeroes. (Requires countrycode and countryiso) Type: String * countrycode -- Cellphone country code (Requires cellphone and countryiso) Type: String * countryiso -- Cellphone country ISO code. For example: US (USA), GB (Britain) or SE (Sweden) (Requires cellphone and countrycode) Type: String * defaultsmsprovider -- Default SMS provider Type: String ['clickatell', 'bulksms', 'esendex', 'cellsynt'] * directtwitter -- Send tweets as direct messages Type: Boolean Default: True * twitteruser -- Twitter user Type: String

Response:
def modify(self, **kwargs):
        """Modify a contact.

        Returns status message

        Optional Parameters:

            * name -- Contact name
                    Type: String

            * email -- Contact email address
                    Type: String

            * cellphone -- Cellphone number, without the country code part. In
                some countries you are supposed to exclude leading zeroes.
                (Requires countrycode and countryiso)
                    Type: String

            * countrycode -- Cellphone country code (Requires cellphone and
                countryiso)
                    Type: String

            * countryiso -- Cellphone country ISO code. For example: US (USA),
                GB (Britain) or SE (Sweden) (Requires cellphone and
                countrycode)
                    Type: String

            * defaultsmsprovider -- Default SMS provider
                    Type: String ['clickatell', 'bulksms', 'esendex',
                                  'cellsynt']

            * directtwitter -- Send tweets as direct messages
                    Type: Boolean
                    Default: True

            * twitteruser -- Twitter user
                    Type: String
        """

        # Warn user about unhandled parameters
        for key in kwargs:
            if key not in ['email', 'cellphone', 'countrycode', 'countryiso',
                           'defaultsmsprovider', 'directtwitter',
                           'twitteruser', 'name']:
                sys.stderr.write("'%s'" % key + ' is not a valid argument ' +
                                 'of <PingdomContact>.modify()\n')

        response = self.pingdom.request('PUT', 'notification_contacts/%s' % self.id, kwargs)

        return response.json()['message']


Instruction:
Can you implement a function in Python 3 that
establishes a connection to the broker.

Response:
def _establish_connection(self, conn: BrokerConnection) -> None:
        """
        We don't use a pool here. We only have one consumer connection per process, so
        we get no value from a pool, and we want to use a heartbeat to keep the consumer
        collection alive, which does not work with a pool
        :return: the connection to the transport
        """
        try:
            self._logger.debug("Establishing connection.")
            self._conn = conn.ensure_connection(max_retries=3)
            self._logger.debug('Got connection: %s', conn.as_uri())
        except kombu_exceptions.OperationalError as oe:
            self._logger.error("Error connecting to RMQ, could not retry %s", oe)
            # Try to clean up the mess
            if self._conn is not None:
                self._conn.close()
            else:
                conn.close()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def run_heartbeat_continuously(self) -> threading.Event:

        cancellation_event = threading.Event()

        # Effectively a no-op if we are not actually a long-running thread
        if not self._is_long_running_handler:
            return cancellation_event

        self._logger.debug("Running long running handler on %s", self._conn)

        def _send_heartbeat(cnx: BrokerConnection, period: int, logger: logging.Logger) -> None:
                while not cancellation_event.is_set():
                    cnx.heartbeat_check()
                    time.sleep(period)
                logger.debug("Signalled to exit long-running handler heartbeat")

        heartbeat_thread = threading.Thread(target=_send_heartbeat, args=(self._conn, 1, self._logger), daemon=True)
        self._logger.debug("Begin heartbeat thread for  %s", self._conn)
        heartbeat_thread.start()
        self._logger.debug("Heartbeat running on thread for  %s", self._conn)
        return cancellation_event

Response: Runs the heartbeat on the broker thread.


Instruction:
How would you explain what the following Python 3 function does
def _check(user, topic):
    # if export_control then check the team is associated to the product, ie.:
    #   - the current user belongs to the product's team
    #   OR
    #   - the product's team belongs to the user's parents teams
    if topic['export_control']:
        product = v1_utils.verify_existence_and_get(topic['product_id'],
                                                    models.PRODUCTS)
        return (user.is_in_team(product['team_id']) or
                product['team_id'] in user.parent_teams_ids)
    return False

Response: Checks if the user is in the team of the product.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_stream_or_content_from_request(request):

    if request.stream.tell():
        logger.info('Request stream already consumed. '
                    'Storing file content using in-memory data.')
        return request.data

    else:
        logger.info('Storing file content using request stream.')
        return request.stream

Response: Checks if the stream is already consumed and if so returns the content from the request stream. If not returns improper value.


Instruction:
Create a Python 3 function for
returning result of performing the given XPath query on the given node. All known namespace prefix-to-URI mappings in the document are automatically included in the XPath invocation. If an empty/default namespace (i.e. None) is defined, this is converted to the prefix name '_' so it can be used despite empty namespace prefixes being unsupported by XPath.

Response:
def xpath_on_node(self, node, xpath, **kwargs):
        """
        Return result of performing the given XPath query on the given node.

        All known namespace prefix-to-URI mappings in the document are
        automatically included in the XPath invocation.

        If an empty/default namespace (i.e. None) is defined, this is
        converted to the prefix name '_' so it can be used despite empty
        namespace prefixes being unsupported by XPath.
        """
        if isinstance(node, etree._ElementTree):
            # Document node lxml.etree._ElementTree has no nsmap, lookup root
            root = self.get_impl_root(node)
            namespaces_dict = root.nsmap.copy()
        else:
            namespaces_dict = node.nsmap.copy()
        if 'namespaces' in kwargs:
            namespaces_dict.update(kwargs['namespaces'])
        # Empty namespace prefix is not supported, convert to '_' prefix
        if None in namespaces_dict:
            default_ns_uri = namespaces_dict.pop(None)
            namespaces_dict['_'] = default_ns_uri
        # Include XMLNS namespace if it's not already defined
        if not 'xmlns' in namespaces_dict:
            namespaces_dict['xmlns'] = nodes.Node.XMLNS_URI
        return node.xpath(xpath, namespaces=namespaces_dict)


Instruction:
How would you implement a function in Python 3 that
returns True if the given namespace name or value is defined in an ancestor of the given node.

Response:
def _is_ns_in_ancestor(self, node, name, value):
        """
        Return True if the given namespace name/value is defined in an
        ancestor of the given node, meaning that the given node need not
        have its own attributes to apply that namespacing.
        """
        curr_node = self.get_node_parent(node)
        while curr_node.__class__ == etree._Element:
            if (hasattr(curr_node, 'nsmap')
                    and curr_node.nsmap.get(name) == value):
                return True
            for n, v in curr_node.attrib.items():
                if v == value and '{%s}' % nodes.Node.XMLNS_URI in n:
                    return True
            curr_node = self.get_node_parent(curr_node)
        return False