Instruction:
Here you have a function in Python 3, explain what it does
def compare(node1, node2):
    if not os.path.isdir("a"):
        print("error: comparison feature not initialized", file=sys.stderr)
        sys.exit(4)

    print("=" * 80)
    print("WERKZEUG INTERNAL BENCHMARK -- COMPARE MODE".center(80))
    print("-" * 80)

    def _hg_update(repo, node):
        def hg(*x):
            return subprocess.call(
                ["hg"] + list(x), cwd=repo, stdout=null_out, stderr=null_out
            )

        hg("revert", "-a", "--no-backup")
        client = subprocess.Popen(
            ["hg", "status", "--unknown", "-n", "-0"], stdout=subprocess.PIPE, cwd=repo
        )
        unknown = client.communicate()[0]
        if unknown:
            client = subprocess.Popen(
                ["xargs", "-0", "rm", "-f"],
                cwd=repo,
                stdout=null_out,
                stdin=subprocess.PIPE,
            )
            client.communicate(unknown)
        hg("pull", "../..")
        hg("update", node)
        if node == "tip":
            diff = subprocess.Popen(
                ["hg", "diff"], cwd="..", stdout=subprocess.PIPE
            ).communicate()[0]
            if diff:
                client = subprocess.Popen(
                    ["hg", "import", "--no-commit", "-"],
                    cwd=repo,
                    stdout=null_out,
                    stdin=subprocess.PIPE,
                )
                client.communicate(diff)

    _hg_update("a", node1)
    _hg_update("b", node2)
    d1 = run("a", no_header=True)
    d2 = run("b", no_header=True)

    print("DIRECT COMPARISON".center(80))
    print("-" * 80)
    for key in sorted(d1):
        delta = d1[key] - d2[key]
        if abs(1 - d1[key] / d2[key]) < TOLERANCE or abs(delta) < MIN_RESOLUTION:
            delta = "=="
        else:
            delta = "%+.4f (%+d%%)" % (delta, round(d2[key] / d1[key] * 100 - 100))
        print("%36s   %.4f    %.4f    %s" % (format_func(key), d1[key], d2[key], delta))
    print("-" * 80)

Response: Compares two Werkzeug hg versions.


Instruction:
Here you have a function in Python 3, explain what it does
def filter_hidden_frames(self):
        for group in self.groups:
            group.filter_hidden_frames()

        self.frames[:] = [frame for group in self.groups for frame in group.frames]

Response: Remove the frames according to the paste spec.


Instruction:
How would you explain what the following Python 3 function does
def log(self, logfile=None):
        if logfile is None:
            logfile = sys.stderr
        tb = self.plaintext.rstrip() + u"\n"
        logfile.write(to_native(tb, "utf-8", "replace"))

Response: Log the ASCII traceback into a file object.


Instruction:
Write a Python 3 function for
creating a paste and return the paste id.

Response:
def paste(self):
        """Create a paste and return the paste id."""
        data = json.dumps(
            {
                "description": "Werkzeug Internal Server Error",
                "public": False,
                "files": {"traceback.txt": {"content": self.plaintext}},
            }
        ).encode("utf-8")
        try:
            from urllib2 import urlopen
        except ImportError:
            from urllib.request import urlopen
        rv = urlopen("https://api.github.com/gists", data=data)
        resp = json.loads(rv.read().decode("utf-8"))
        rv.close()
        return {"url": resp["html_url"], "id": resp["id"]}


Instruction:
Write a Python 3 script for
rendering the traceback for the interactive console.

Response:
def render_summary(self, include_title=True):
        """Render the traceback for the interactive console."""
        title = ""
        classes = ["traceback"]
        if not self.frames:
            classes.append("noframe-traceback")
            frames = []
        else:
            library_frames = sum(frame.is_library for frame in self.frames)
            mark_lib = 0 < library_frames < len(self.frames)
            frames = [group.render(mark_lib=mark_lib) for group in self.groups]

        if include_title:
            if self.is_syntax_error:
                title = u"Syntax Error"
            else:
                title = u"Traceback (most recent call last):"

        if self.is_syntax_error:
            description_wrapper = u"
%s
"
        else:
            description_wrapper = u"
%s
"

        return SUMMARY_HTML % {
            "classes": u" ".join(classes),
            "title": u"
%s
" % title if title else u"",
            "frames": u"\n".join(frames),
            "description": description_wrapper % escape(self.exception),
        }


Instruction:
Can you create a Python 3 function that
renders the Full HTML page with the traceback info.

Response:
def render_full(self, evalex=False, secret=None, evalex_trusted=True):
        """Render the Full HTML page with the traceback info."""
        exc = escape(self.exception)
        return PAGE_HTML % {
            "evalex": "true" if evalex else "false",
            "evalex_trusted": "true" if evalex_trusted else "false",
            "console": "false",
            "title": exc,
            "exception": exc,
            "exception_type": escape(self.exception_type),
            "summary": self.render_summary(include_title=False),
            "plaintext": escape(self.plaintext),
            "plaintext_cs": re.sub("-{2,}", "-", self.plaintext),
            "traceback_id": self.id,
            "secret": secret,
        }


Instruction:
Can you tell what is the following Python 3 function doing
def exception(self):
        buf = traceback.format_exception_only(self.exc_type, self.exc_value)
        rv = "".join(buf).strip()
        return to_unicode(rv, "utf-8", "replace")

Response: String representation of the exception.


Instruction:
Given the following Python 3 function, write the documentation
def render(self, mark_lib=True):
        return FRAME_HTML % {
            "id": self.id,
            "filename": escape(self.filename),
            "lineno": self.lineno,
            "function_name": escape(self.function_name),
            "lines": self.render_line_context(),
            "library": "library" if mark_lib and self.is_library else "",
        }

Response: Render a single frame in a traceback.


Instruction:
Create a Python 3 function for
evaluating code in the context of the frame.

Response:
def eval(self, code, mode="single"):
        """Evaluate code in the context of the frame."""
        if isinstance(code, string_types):
            if PY2 and isinstance(code, text_type):  # noqa
                code = UTF8_COOKIE + code.encode("utf-8")
            code = compile(code, "<interactive>", mode)
        return eval(code, self.globals, self.locals)


Instruction:
Write a Python 3 script to
decorate a function as responder that accepts the request as first argument and returns a WSGI response.

Response:
def application(cls, f):
        """Decorate a function as responder that accepts the request as first
        argument.  This works like the :func:`responder` decorator but the
        function is passed the request object as first argument and the
        request object will be closed automatically::

            @Request.application
            def my_wsgi_app(request):
                return Response('Hello World!')

        As of Werkzeug 0.14 HTTP exceptions are automatically caught and
        converted to responses instead of failing.

        :param f: the WSGI callable to decorate
        :return: a new WSGI callable
        """
        #: return a callable that wraps the -2nd argument with the request
        #: and calls the function with all the arguments up to that one and
        #: the request.  The return value is then called with the latest
        #: two arguments.  This makes it possible to use this decorator for
        #: both methods and standalone WSGI functions.
        from ..exceptions import HTTPException

        def application(*args):
            request = cls(args[-2])
            with request:
                try:
                    resp = f(*args[:-2] + (request,))
                except HTTPException as e:
                    resp = e.get_response(args[-2])
                return resp(*args[-2:])

        return update_wrapper(application, f)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def close(self):
        files = self.__dict__.get("files")
        for _key, value in iter_multi_items(files or ()):
            value.close()

Response: Closes all associated resources of this request object.


Instruction:
Can you generate the documentation for the following Python 3 function
def path(self):
        raw_path = wsgi_decoding_dance(
            self.environ.get("PATH_INFO") or "", self.charset, self.encoding_errors
        )
        return "/" + raw_path.lstrip("/")

Response: The path of the current URL.


Instruction:
Create a Python 3 function for
returning the full path to the resource.

Response:
def full_path(self):
        """Requested path as unicode, including the query string."""
        return self.path + u"?" + to_unicode(self.query_string, self.url_charset)


Instruction:
Can you generate the documentation for the following Python 3 function
def base_url(self):
        return get_current_url(
            self.environ, strip_querystring=True, trusted_hosts=self.trusted_hosts
        )

Response: Like url but without the querystring


Instruction:
Here you have a function in Python 3, explain what it does
def access_route(self):
        if "HTTP_X_FORWARDED_FOR" in self.environ:
            addr = self.environ["HTTP_X_FORWARDED_FOR"].split(",")
            return self.list_storage_class([x.strip() for x in addr])
        elif "REMOTE_ADDR" in self.environ:
            return self.list_storage_class([self.environ["REMOTE_ADDR"]])
        return self.list_storage_class()

Response: Returns a list of all ip addresses that are forwarded to the client ip.


Instruction:
Given the following Python 3 function, write the documentation
def on_show(request, page_name):
    revision_id = request.args.get("rev", type=int)
    query = RevisionedPage.query.filter_by(name=page_name)
    if revision_id:
        query = query.filter_by(revision_id=revision_id)
        revision_requested = True
    else:
        query = query.order_by(RevisionedPage.revision_id.desc())
        revision_requested = False
    page = query.first()
    if page is None:
        return page_missing(request, page_name, revision_requested)
    return Response(generate_template("action_show.html", page=page))

Response: Displays the page the user requests.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def on_edit(request, page_name):
    change_note = error = ""
    revision = (
        Revision.query.filter(
            (Page.name == page_name) & (Page.page_id == Revision.page_id)
        )
        .order_by(Revision.revision_id.desc())
        .first()
    )
    if revision is None:
        page = None
    else:
        page = revision.page

    if request.method == "POST":
        text = request.form.get("text")
        if request.form.get("cancel") or revision and revision.text == text:
            return redirect(href(page.name))
        elif not text:
            error = "You cannot save empty revisions."
        else:
            change_note = request.form.get("change_note", "")
            if page is None:
                page = Page(page_name)
                session.add(page)
            session.add(Revision(page, text, change_note))
            session.commit()
            return redirect(href(page.name))

    return Response(
        generate_template(
            "action_edit.html",
            revision=revision,
            page=page,
            new=page is None,
            page_name=page_name,
            change_note=change_note,
            error=error,
        )
    )

Response: Edit the current revision of a page.


Instruction:
Can you create a Python 3 function that
shows the list of recent changes.

Response:
def on_log(request, page_name):
    """Show the list of recent changes."""
    page = Page.query.filter_by(name=page_name).first()
    if page is None:
        return page_missing(request, page_name, False)
    return Response(generate_template("action_log.html", page=page))


Instruction:
How would you code a function in Python 3 to
show the diff between two revisions.

Response:
def on_diff(request, page_name):
    """Show the diff between two revisions."""
    old = request.args.get("old", type=int)
    new = request.args.get("new", type=int)
    error = ""
    diff = page = old_rev = new_rev = None

    if not (old and new):
        error = "No revisions specified."
    else:
        revisions = dict(
            (x.revision_id, x)
            for x in Revision.query.filter(
                (Revision.revision_id.in_((old, new)))
                & (Revision.page_id == Page.page_id)
                & (Page.name == page_name)
            )
        )
        if len(revisions) != 2:
            error = "At least one of the revisions requested does not exist."
        else:
            new_rev = revisions[new]
            old_rev = revisions[old]
            page = old_rev.page
            diff = unified_diff(
                (old_rev.text + "\n").splitlines(True),
                (new_rev.text + "\n").splitlines(True),
                page.name,
                page.name,
                format_datetime(old_rev.timestamp),
                format_datetime(new_rev.timestamp),
                3,
            )

    return Response(
        generate_template(
            "action_diff.html",
            error=error,
            old_revision=old_rev,
            new_revision=new_rev,
            page=page,
            diff=diff,
        )
    )


Instruction:
Implement a Python 3 function for
reverting an old revision.

Response:
def on_revert(request, page_name):
    """Revert an old revision."""
    rev_id = request.args.get("rev", type=int)

    old_revision = page = None
    error = "No such revision"

    if request.method == "POST" and request.form.get("cancel"):
        return redirect(href(page_name))

    if rev_id:
        old_revision = Revision.query.filter(
            (Revision.revision_id == rev_id)
            & (Revision.page_id == Page.page_id)
            & (Page.name == page_name)
        ).first()
        if old_revision:
            new_revision = (
                Revision.query.filter(
                    (Revision.page_id == Page.page_id) & (Page.name == page_name)
                )
                .order_by(Revision.revision_id.desc())
                .first()
            )
            if old_revision == new_revision:
                error = "You tried to revert the current active revision."
            elif old_revision.text == new_revision.text:
                error = (
                    "There are no changes between the current "
                    "revision and the revision you want to "
                    "restore."
                )
            else:
                error = ""
                page = old_revision.page
                if request.method == "POST":
                    change_note = request.form.get("change_note", "")
                    change_note = "revert" + (change_note and ": " + change_note or "")
                    session.add(Revision(page, old_revision.text, change_note))
                    session.commit()
                    return redirect(href(page_name))

    return Response(
        generate_template(
            "action_revert.html", error=error, old_revision=old_revision, page=page
        )
    )


Instruction:
Can you implement a function in Python 3 that
displays if page or revision does not exist.

Response:
def page_missing(request, page_name, revision_requested, protected=False):
    """Displayed if page or revision does not exist."""
    return Response(
        generate_template(
            "page_missing.html",
            page_name=page_name,
            revision_requested=revision_requested,
            protected=protected,
        ),
        status=404,
    )


Instruction:
Write a Python 3 function that can
start a new interactive python session.

Response:
def shell(no_ipython):
    """Start a new interactive python session."""
    banner = "Interactive Werkzeug Shell"
    namespace = make_shell()
    if not no_ipython:
        try:
            try:
                from IPython.frontend.terminal.embed import InteractiveShellEmbed

                sh = InteractiveShellEmbed.instance(banner1=banner)
            except ImportError:
                from IPython.Shell import IPShellEmbed

                sh = IPShellEmbed(banner=banner)
        except ImportError:
            pass
        else:
            sh(local_ns=namespace)
            return
    from code import interact

    interact(banner, local=namespace)


Instruction:
Can you create a Python 3 function that
gets all the fields from a class.

Response:
def _get_fields(attrs, field_class, pop=False, ordered=False):
    """Get fields from a class. If ordered=True, fields will sorted by creation index.

    :param attrs: Mapping of class attributes
    :param type field_class: Base field class
    :param bool pop: Remove matching fields
    """
    fields = [
        (field_name, field_value)
        for field_name, field_value in iteritems(attrs)
        if is_instance_or_subclass(field_value, field_class)
    ]
    if pop:
        for field_name, _ in fields:
            del attrs[field_name]
    if ordered:
        fields.sort(key=lambda pair: pair[1]._creation_index)
    return fields


Instruction:
Implement a Python 3 function for
collecting fields from a class following its method resolution order.

Response:
def _get_fields_by_mro(klass, field_class, ordered=False):
    """Collect fields from a class, following its method resolution order. The
    class itself is excluded from the search; only its parents are checked. Get
    fields from ``_declared_fields`` if available, else use ``__dict__``.

    :param type klass: Class whose fields to retrieve
    :param type field_class: Base field class
    """
    mro = inspect.getmro(klass)
    # Loop over mro in reverse to maintain correct order of fields
    return sum(
        (
            _get_fields(
                getattr(base, '_declared_fields', base.__dict__),
                field_class,
                ordered=ordered,
            )
            for base in mro[:0:-1]
        ),
        [],
    )


Instruction:
Explain what the following Python 3 code does
def resolve_hooks(self):
        mro = inspect.getmro(self)

        hooks = defaultdict(list)

        for attr_name in dir(self):
            # Need to look up the actual descriptor, not whatever might be
            # bound to the class. This needs to come from the __dict__ of the
            # declaring class.
            for parent in mro:
                try:
                    attr = parent.__dict__[attr_name]
                except KeyError:
                    continue
                else:
                    break
            else:
                # In case we didn't find the attribute and didn't break above.
                # We should never hit this - it's just here for completeness
                # to exclude the possibility of attr being undefined.
                continue

            try:
                hook_config = attr.__marshmallow_hook__
            except AttributeError:
                pass
            else:
                for key in iterkeys(hook_config):
                    # Use name here so we can get the bound method later, in
                    # case the processor was a descriptor or something.
                    hooks[key].append(attr_name)

        return hooks

Response:
Add in the decorated processors
        By doing this by adding in the decorated processors


Instruction:
Explain what the following Python 3 code does
def _call_and_store(getter_func, data, field_name, error_store, index=None):
        try:
            value = getter_func(data)
        except ValidationError as err:
            error_store.store_error(err.messages, field_name, index=index)
            # When a Nested field fails validation, the marshalled data is stored
            # on the ValidationError's valid_data attribute
            return err.valid_data or missing
        return value

Response: Calls the getter_func with data as its argument and stores any ValidationErrors.


Instruction:
How would you code a function in Python 3 to
serialize the raw data of the current object into a list of the items that are stored in the internal state.

Response:
def _serialize(
        self, obj, fields_dict, error_store, many=False,
        accessor=None, dict_class=dict, index_errors=True,
        index=None,
    ):
        """Takes raw data (a dict, list, or other object) and a dict of
        fields to output and serializes the data based on those fields.

        :param obj: The actual object(s) from which the fields are taken from
        :param dict fields_dict: Mapping of field names to :class:`Field` objects.
        :param ErrorStore error_store: Structure to store errors.
        :param bool many: Set to `True` if ``data`` should be serialized as
            a collection.
        :param callable accessor: Function to use for getting values from ``obj``.
        :param type dict_class: Dictionary class used to construct the output.
        :param bool index_errors: Whether to store the index of invalid items in
            ``self.errors`` when ``many=True``.
        :param int index: Index of the item being serialized (for storing errors) if
            serializing a collection, otherwise `None`.
        :return: A dictionary of the marshalled data

        .. versionchanged:: 1.0.0
            Renamed from ``marshal``.
        """
        index = index if index_errors else None
        if many and obj is not None:
            self._pending = True
            ret = [
                self._serialize(
                    d, fields_dict, error_store, many=False,
                    dict_class=dict_class, accessor=accessor,
                    index=idx, index_errors=index_errors,
                )
                for idx, d in enumerate(obj)
            ]
            self._pending = False
            return ret
        items = []
        for attr_name, field_obj in iteritems(fields_dict):
            if getattr(field_obj, 'load_only', False):
                continue
            key = field_obj.data_key or attr_name
            getter = lambda d: field_obj.serialize(attr_name, d, accessor=accessor)
            value = self._call_and_store(
                getter_func=getter,
                data=obj,
                field_name=key,
                error_store=error_store,
                index=index,
            )
            if value is missing:
                continue
            items.append((key, value))
        ret = dict_class(items)
        return ret


Instruction:
Make a summary of the following Python 3 code
def dump(self, obj, many=None):
        error_store = ErrorStore()
        errors = {}
        many = self.many if many is None else bool(many)
        if many and is_iterable_but_not_string(obj):
            obj = list(obj)

        if self._has_processors(PRE_DUMP):
            try:
                processed_obj = self._invoke_dump_processors(
                    PRE_DUMP,
                    obj,
                    many,
                    original_data=obj,
                )
            except ValidationError as error:
                errors = error.normalized_messages()
                result = None
        else:
            processed_obj = obj

        if not errors:
            result = self._serialize(
                processed_obj,
                self.fields,
                error_store,
                many=many,
                accessor=self.get_attribute,
                dict_class=self.dict_class,
                index_errors=self.opts.index_errors,
            )
            errors = error_store.errors

        if not errors and self._has_processors(POST_DUMP):
            try:
                result = self._invoke_dump_processors(
                    POST_DUMP,
                    result,
                    many,
                    original_data=obj,
                )
            except ValidationError as error:
                errors = error.normalized_messages()
        if errors:
            exc = ValidationError(
                errors,
                data=obj,
                valid_data=result,
            )
            # User-defined error handler
            self.handle_error(exc, obj)
            raise exc

        return result

Response: Serialize an object to native Python data types according to this schema s fields.


Instruction:
Explain what the following Python 3 code does
def dumps(self, obj, many=None, *args, **kwargs):
        serialized = self.dump(obj, many=many)
        return self.opts.render_module.dumps(serialized, *args, **kwargs)

Response: Same as dump except return a JSON - encoded string.


Instruction:
Explain what the following Python 3 code does
def load(self, data, many=None, partial=None, unknown=None):
        return self._do_load(
            data, many, partial=partial, unknown=unknown,
            postprocess=True,
        )

Response: Deserialize a data structure to an object defined by this Schema s fields.


Instruction:
Here you have a function in Python 3, explain what it does
def loads(
        self, json_data, many=None, partial=None, unknown=None,
        **kwargs
    ):
        """Same as :meth:`load`, except it takes a JSON string as input.

        :param str json_data: A JSON string of the data to deserialize.
        :param bool many: Whether to deserialize `obj` as a collection. If `None`, the
            value for `self.many` is used.
        :param bool|tuple partial: Whether to ignore missing fields and not require
            any fields declared. Propagates down to ``Nested`` fields as well. If
            its value is an iterable, only missing fields listed in that iterable
            will be ignored. Use dot delimiters to specify nested fields.
        :param unknown: Whether to exclude, include, or raise an error for unknown
            fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`.
            If `None`, the value for `self.unknown` is used.
        :return: A dict of deserialized data
        :rtype: dict

        .. versionadded:: 1.0.0
        .. versionchanged:: 3.0.0b7
            This method returns the deserialized data rather than a ``(data, errors)`` duple.
            A :exc:`ValidationError <marshmallow.exceptions.ValidationError>` is raised
            if invalid data are passed.
        """
        data = self.opts.render_module.loads(json_data, **kwargs)
        return self.load(data, many=many, partial=partial, unknown=unknown)

Response: This method loads the data from a JSON string into a dict.


Instruction:
Write a Python 3 script for
validating the data against the schema of the object.

Response:
def validate(self, data, many=None, partial=None):
        """Validate `data` against the schema, returning a dictionary of
        validation errors.

        :param dict data: The data to validate.
        :param bool many: Whether to validate `data` as a collection. If `None`, the
            value for `self.many` is used.
        :param bool|tuple partial: Whether to ignore missing fields and not require
            any fields declared. Propagates down to ``Nested`` fields as well. If
            its value is an iterable, only missing fields listed in that iterable
            will be ignored. Use dot delimiters to specify nested fields.
        :return: A dictionary of validation errors.
        :rtype: dict

        .. versionadded:: 1.1.0
        """
        try:
            self._do_load(data, many, partial=partial, postprocess=False)
        except ValidationError as exc:
            return exc.messages
        return {}


Instruction:
Implement a Python 3 function for
applying then flatten nested schema options

Response:
def _normalize_nested_options(self):
        """Apply then flatten nested schema options"""
        if self.only is not None:
            # Apply the only option to nested fields.
            self.__apply_nested_option('only', self.only, 'intersection')
            # Remove the child field names from the only option.
            self.only = self.set_class(
                [field.split('.', 1)[0] for field in self.only],
            )
        excludes = set(self.opts.exclude) | set(self.exclude)
        if excludes:
            # Apply the exclude option to nested fields.
            self.__apply_nested_option('exclude', excludes, 'union')
        if self.exclude:
            # Remove the parent field names from the exclude option.
            self.exclude = self.set_class(
                [field for field in self.exclude if '.' not in field],
            )
        if self.opts.exclude:
            # Remove the parent field names from the meta exclude option.
            self.opts.exclude = self.set_class(
                [field for field in self.opts.exclude if '.' not in field],
            )


Instruction:
Explain what the following Python 3 code does
def __apply_nested_option(self, option_name, field_names, set_operation):
        # Split nested field names on the first dot.
        nested_fields = [name.split('.', 1) for name in field_names if '.' in name]
        # Partition the nested field names by parent field.
        nested_options = defaultdict(list)
        for parent, nested_names in nested_fields:
            nested_options[parent].append(nested_names)
        # Apply the nested field options.
        for key, options in iter(nested_options.items()):
            new_options = self.set_class(options)
            original_options = getattr(self.declared_fields[key], option_name, ())
            if original_options:
                if set_operation == 'union':
                    new_options |= self.set_class(original_options)
                if set_operation == 'intersection':
                    new_options &= self.set_class(original_options)
            setattr(self.declared_fields[key], option_name, new_options)

Response: Applies nested options to nested fields.


Instruction:
Can you write a function in Python 3 where it
initializes the fields based on the schema options.

Response:
def _init_fields(self):
        """Update fields based on schema options."""
        if self.opts.fields:
            available_field_names = self.set_class(self.opts.fields)
        else:
            available_field_names = self.set_class(self.declared_fields.keys())
            if self.opts.additional:
                available_field_names |= self.set_class(self.opts.additional)

        invalid_fields = self.set_class()

        if self.only is not None:
            # Return only fields specified in only option
            field_names = self.set_class(self.only)

            invalid_fields |= field_names - available_field_names
        else:
            field_names = available_field_names

        # If "exclude" option or param is specified, remove those fields.
        exclude_field_names = set(self.opts.exclude) | set(self.exclude)
        if exclude_field_names:
            # Note that this isn't available_field_names, since we want to
            # apply "only" for the actual calculation.
            field_names = field_names - exclude_field_names

            invalid_fields |= exclude_field_names - available_field_names

        if invalid_fields:
            message = 'Invalid fields for {}: {}.'.format(self, invalid_fields)
            raise ValueError(message)

        fields_dict = self.dict_class()
        for field_name in field_names:
            field_obj = self.declared_fields.get(field_name, ma_fields.Inferred())
            self._bind_field(field_name, field_obj)
            fields_dict[field_name] = field_obj

        dump_data_keys = [
            obj.data_key or name for name, obj in iteritems(fields_dict) if not obj.load_only
        ]
        if len(dump_data_keys) != len(set(dump_data_keys)):
            data_keys_duplicates = {x for x in dump_data_keys if dump_data_keys.count(x) > 1}
            raise ValueError(
                'The data_key argument for one or more fields collides '
                "with another field's name or data_key argument. "
                'Check the following field names and '
                'data_key arguments: {}'.format(list(data_keys_duplicates)),
            )

        load_attributes = [
            obj.attribute or name for name, obj in iteritems(fields_dict) if not obj.dump_only
        ]
        if len(load_attributes) != len(set(load_attributes)):
            attributes_duplicates = {x for x in load_attributes if load_attributes.count(x) > 1}
            raise ValueError(
                'The attribute argument for one or more fields collides '
                "with another field's name or attribute argument. "
                'Check the following field names and '
                'attribute arguments: {}'.format(list(attributes_duplicates)),
            )

        return fields_dict


Instruction:
Given the following Python 3 function, write the documentation
def _bind_field(self, field_name, field_obj):
        try:
            if field_name in self.load_only:
                field_obj.load_only = True
            if field_name in self.dump_only:
                field_obj.dump_only = True
            field_obj._bind_to_schema(field_name, self)
            self.on_bind_field(field_name, field_obj)
        except TypeError:
            # field declared as a class, not an instance
            if (isinstance(field_obj, type) and
                    issubclass(field_obj, base.FieldABC)):
                msg = ('Field for "{}" must be declared as a '
                       'Field instance, not a class. '
                       'Did you mean "fields.{}()"?'
                       .format(field_name, field_obj.__name__))
                raise TypeError(msg)

Response: Bind a field to the schema.


Instruction:
Create a Python 3 function for
registering a schema - level validator.

Response:
def validates_schema(
    fn=None,
    pass_many=False,
    pass_original=False,
    skip_on_field_errors=True,
):
    """Register a schema-level validator.

    By default, receives a single object at a time, regardless of whether ``many=True``
    is passed to the `Schema`. If ``pass_many=True``, the raw data (which may be a collection)
    and the value for ``many`` is passed.

    If ``pass_original=True``, the original data (before unmarshalling) will be passed as
    an additional argument to the method.

    If ``skip_on_field_errors=True``, this validation method will be skipped whenever
    validation errors have been detected when validating fields.

    .. versionchanged:: 3.0.0b1
        ``skip_on_field_errors`` defaults to `True`.
    """
    return set_hook(
        fn,
        (VALIDATES_SCHEMA, pass_many),
        pass_original=pass_original,
        skip_on_field_errors=skip_on_field_errors,
    )


Instruction:
Write a Python 3 script to
register a method to invoke after serializing an object.

Response:
def post_dump(fn=None, pass_many=False, pass_original=False):
    """Register a method to invoke after serializing an object. The method
    receives the serialized object and returns the processed object.

    By default, receives a single object at a time, transparently handling the ``many``
    argument passed to the Schema. If ``pass_many=True``, the raw data
    (which may be a collection) and the value for ``many`` is passed.

    If ``pass_original=True``, the original data (before serializing) will be passed as
    an additional argument to the method.
    """
    return set_hook(fn, (POST_DUMP, pass_many), pass_original=pass_original)


Instruction:
Create a Python 3 function for
registering a method to invoke after deserializing an object.

Response:
def post_load(fn=None, pass_many=False, pass_original=False):
    """Register a method to invoke after deserializing an object. The method
    receives the deserialized data and returns the processed data.

    By default, receives a single datum at a time, transparently handling the ``many``
    argument passed to the Schema. If ``pass_many=True``, the raw data
    (which may be a collection) and the value for ``many`` is passed.

    If ``pass_original=True``, the original data (before deserializing) will be passed as
    an additional argument to the method.
    """
    return set_hook(fn, (POST_LOAD, pass_many), pass_original=pass_original)


Instruction:
Given the following Python 3 function, write the documentation
def set_hook(fn, key, **kwargs):
    # Allow using this as either a decorator or a decorator factory.
    if fn is None:
        return functools.partial(set_hook, key=key, **kwargs)

    # Set a __marshmallow_hook__ attribute instead of wrapping in some class,
    # because I still want this to end up as a normal (unbound) method.
    try:
        hook_config = fn.__marshmallow_hook__
    except AttributeError:
        fn.__marshmallow_hook__ = hook_config = {}
    # Also save the kwargs for the tagged function on
    # __marshmallow_hook__, keyed by (<tag>, <pass_many>)
    hook_config[key] = kwargs

    return fn

Response: Mark the decorated function as a hook to be picked up later.


Instruction:
Write a Python 3 script to
return a generator over the value and label pairs associated with each choice.

Response:
def options(self, valuegetter=text_type):
        """Return a generator over the (value, label) pairs, where value
        is a string associated with each choice. This convenience method
        is useful to populate, for instance, a form select field.

        :param valuegetter: Can be a callable or a string. In the former case, it must
            be a one-argument callable which returns the value of a
            choice. In the latter case, the string specifies the name
            of an attribute of the choice objects. Defaults to `str()`
            or `unicode()`.
        """
        valuegetter = valuegetter if callable(valuegetter) else attrgetter(valuegetter)
        pairs = zip_longest(self.choices, self.labels, fillvalue='')

        return ((valuegetter(choice), label) for choice, label in pairs)


Instruction:
How would you implement a function in Python 3 that
registers a class to the registry of serializer classes.

Response:
def register(classname, cls):
    """Add a class to the registry of serializer classes. When a class is
    registered, an entry for both its classname and its full, module-qualified
    path are added to the registry.

    Example: ::

        class MyClass:
            pass

        register('MyClass', MyClass)
        # Registry:
        # {
        #   'MyClass': [path.to.MyClass],
        #   'path.to.MyClass': [path.to.MyClass],
        # }

    """
    # Module where the class is located
    module = cls.__module__
    # Full module path to the class
    # e.g. user.schemas.UserSchema
    fullpath = '.'.join([module, classname])
    # If the class is already registered; need to check if the entries are
    # in the same module as cls to avoid having multiple instances of the same
    # class in the registry
    if classname in _registry and not \
            any(each.__module__ == module for each in _registry[classname]):
        _registry[classname].append(cls)
    elif classname not in _registry:
        _registry[classname] = [cls]

    # Also register the full path
    if fullpath not in _registry:
        _registry.setdefault(fullpath, []).append(cls)
    else:
        # If fullpath does exist, replace existing entry
        _registry[fullpath] = [cls]
    return None


Instruction:
Can you generate the documentation for the following Python 3 function
def get_class(classname, all=False):
    try:
        classes = _registry[classname]
    except KeyError:
        raise RegistryError('Class with name {!r} was not found. You may need '
            'to import the class.'.format(classname))
    if len(classes) > 1:
        if all:
            return _registry[classname]
        raise RegistryError('Multiple classes with name {!r} '
            'were found. Please use the full, '
            'module-qualified path.'.format(classname))
    else:
        return _registry[classname][0]

Response: Retrieve a class from the registry.


Instruction:
Write a Python 3 function for
getting the value for a given key from an object.

Response:
def get_value(self, obj, attr, accessor=None, default=missing_):
        """Return the value for a given key from an object.

        :param object obj: The object to get the value from
        :param str attr: The attribute/key in `obj` to get the value from.
        :param callable accessor: A callable used to retrieve the value of `attr` from
            the object `obj`. Defaults to `marshmallow.utils.get_value`.
        """
        # NOTE: Use getattr instead of direct attribute access here so that
        # subclasses aren't required to define `attribute` member
        attribute = getattr(self, 'attribute', None)
        accessor_func = accessor or utils.get_value
        check_key = attr if attribute is None else attribute
        return accessor_func(obj, check_key, default)


Instruction:
Here you have a function in Python 3, explain what it does
def _validate(self, value):
        errors = []
        kwargs = {}
        for validator in self.validators:
            try:
                r = validator(value)
                if not isinstance(validator, Validator) and r is False:
                    self.fail('validator_failed')
            except ValidationError as err:
                kwargs.update(err.kwargs)
                if isinstance(err.messages, dict):
                    errors.append(err.messages)
                else:
                    errors.extend(err.messages)
        if errors:
            raise ValidationError(errors, **kwargs)

Response:
Perform validation on value. Raise a ValidationError if validation
            does not succeed.


Instruction:
Can you create a Python 3 function that
validates missing values. Raise a : exc : ValidationException if value is not a valid value.

Response:
def _validate_missing(self, value):
        """Validate missing values. Raise a :exc:`ValidationError` if
        `value` should be considered missing.
        """
        if value is missing_:
            if hasattr(self, 'required') and self.required:
                self.fail('required')
        if value is None:
            if hasattr(self, 'allow_none') and self.allow_none is not True:
                self.fail('null')


Instruction:
Write a Python 3 function that can
return the value for the given attribute or key from the object.

Response:
def serialize(self, attr, obj, accessor=None, **kwargs):
        """Pulls the value for the given key from the object, applies the
        field's formatting and returns the result.

        :param str attr: The attribute or key to get from the object.
        :param str obj: The object to pull the key from.
        :param callable accessor: Function used to pull values from ``obj``.
        :param dict kwargs': Field-specific keyword arguments.
        :raise ValidationError: In case of formatting problem
        """
        if self._CHECK_ATTRIBUTE:
            value = self.get_value(obj, attr, accessor=accessor)
            if value is missing_ and hasattr(self, 'default'):
                default = self.default
                value = default() if callable(default) else default
            if value is missing_:
                return value
        else:
            value = None
        return self._serialize(value, attr, obj, **kwargs)


Instruction:
How would you explain what the following Python 3 function does
def deserialize(self, value, attr=None, data=None, **kwargs):
        # Validate required fields, deserialize, then validate
        # deserialized value
        self._validate_missing(value)
        if value is missing_:
            _miss = self.missing
            return _miss() if callable(_miss) else _miss
        if getattr(self, 'allow_none', False) is True and value is None:
            return None
        output = self._deserialize(value, attr, data, **kwargs)
        self._validate(output)
        return output

Response: Deserialize the value into a dictionary.


Instruction:
Can you create a Python 3 function that
binds values from its parent schema to the given field.

Response:
def _bind_to_schema(self, field_name, schema):
        """Update field with values from its parent schema. Called by
            :meth:`_bind_field<marshmallow.Schema._bind_field>`.

        :param str field_name: Field name set in schema.
        :param Schema schema: Parent schema.
        """
        self.parent = self.parent or schema
        self.name = self.name or field_name


Instruction:
Can you tell what is the following Python 3 function doing
def root(self):
        ret = self
        while hasattr(ret, 'parent') and ret.parent:
            ret = ret.parent
        return ret if isinstance(ret, SchemaABC) else None

Response: Reference to the root schema that this field belongs to even if it is buried in a List.


Instruction:
Given the following Python 3 function, write the documentation
def schema(self):
        if not self.__schema:
            # Inherit context from parent.
            context = getattr(self.parent, 'context', {})
            if isinstance(self.nested, SchemaABC):
                self.__schema = self.nested
                self.__schema.context.update(context)
            else:
                if isinstance(self.nested, type) and issubclass(self.nested, SchemaABC):
                    schema_class = self.nested
                elif not isinstance(self.nested, basestring):
                    raise ValueError(
                        'Nested fields must be passed a '
                        'Schema, not {}.'.format(self.nested.__class__),
                    )
                elif self.nested == 'self':
                    schema_class = self.parent.__class__
                else:
                    schema_class = class_registry.get_class(self.nested)
                self.__schema = schema_class(
                    many=self.many,
                    only=self.only,
                    exclude=self.exclude,
                    context=context,
                    load_only=self._nested_normalized_option('load_only'),
                    dump_only=self._nested_normalized_option('dump_only'),
                )
        return self.__schema

Response: The nested Schema object.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _validated(self, value):
        if value is None:
            return None
        if isinstance(value, uuid.UUID):
            return value
        try:
            if isinstance(value, bytes) and len(value) == 16:
                return uuid.UUID(bytes=value)
            else:
                return uuid.UUID(value)
        except (ValueError, AttributeError, TypeError):
            self.fail('invalid_uuid')

Response: Format the value or raise a : exc : ValidationException.


Instruction:
Write a Python 3 script for
returning the number value for value given this field s num_type.

Response:
def _format_num(self, value):
        """Return the number value for value, given this field's `num_type`."""
        # (value is True or value is False) is ~5x faster than isinstance(value, bool)
        if value is True or value is False:
            raise TypeError('value must be a Number, not a boolean.')
        return self.num_type(value)


Instruction:
How would you explain what the following Python 3 function does
def _validated(self, value):
        if value is None:
            return None
        try:
            return self._format_num(value)
        except (TypeError, ValueError):
            self.fail('invalid', input=value)
        except OverflowError:
            self.fail('too_large', input=value)

Response: Format the value or raise a : exc : ValidationException.


Instruction:
Make a summary of the following Python 3 code
def _serialize(self, value, attr, obj, **kwargs):
        ret = self._validated(value)
        return (
            self._to_string(ret)
            if (self.as_string and ret not in (None, missing_))
            else ret
        )

Response: Serialize the value into a string if self. as_string = True otherwise return this field s num_type.


Instruction:
Explain what the following Python 3 code does
def _deserialize(self, value, attr, data, **kwargs):
        if not value:  # falsy values are invalid
            self.fail('invalid')
        try:
            return utils.from_iso_time(value)
        except (AttributeError, TypeError, ValueError):
            self.fail('invalid')

Response: Deserialize an ISO8601 - formatted time to a datetime. time object.


Instruction:
Write a Python 3 script for
returning True if val is either a subclass or instance of class_.

Response:
def is_instance_or_subclass(val, class_):
    """Return True if ``val`` is either a subclass or instance of ``class_``."""
    try:
        return issubclass(val, class_)
    except TypeError:
        return isinstance(val, class_)


Instruction:
Write a Python 3 script to
return the RFC822 - formatted representation of a datetime object.

Response:
def local_rfcformat(dt):
    """Return the RFC822-formatted representation of a timezone-aware datetime
    with the UTC offset.
    """
    weekday = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][dt.weekday()]
    month = [
        'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
        'Oct', 'Nov', 'Dec',
    ][dt.month - 1]
    tz_offset = dt.strftime('%z')
    return '%s, %02d %s %04d %02d:%02d:%02d %s' % (
        weekday, dt.day, month,
        dt.year, dt.hour, dt.minute, dt.second, tz_offset,
    )


Instruction:
Can you create a Python 3 function that
returns the RFC822 - formatted representation of a datetime object.

Response:
def rfcformat(dt, localtime=False):
    """Return the RFC822-formatted representation of a datetime object.

    :param datetime dt: The datetime.
    :param bool localtime: If ``True``, return the date relative to the local
        timezone instead of UTC, displaying the proper offset,
        e.g. "Sun, 10 Nov 2013 08:23:45 -0600"
    """
    if not localtime:
        return formatdate(timegm(dt.utctimetuple()))
    else:
        return local_rfcformat(dt)


Instruction:
Write a Python 3 function that can
return the ISO8601 - formatted UTC representation of a datetime object.

Response:
def isoformat(dt, localtime=False, *args, **kwargs):
    """Return the ISO8601-formatted UTC representation of a datetime object."""
    if localtime and dt.tzinfo is not None:
        localized = dt
    else:
        if dt.tzinfo is None:
            localized = UTC.localize(dt)
        else:
            localized = dt.astimezone(UTC)
    return localized.isoformat(*args, **kwargs)


Instruction:
Can you tell what is the following Python 3 function doing
def from_rfc(datestring, use_dateutil=True):
    # Use dateutil's parser if possible
    if dateutil_available and use_dateutil:
        return parser.parse(datestring)
    else:
        parsed = parsedate(datestring)  # as a tuple
        timestamp = time.mktime(parsed)
        return datetime.datetime.fromtimestamp(timestamp)

Response: Parse a RFC822 - formatted datetime string and return a datetime object.


Instruction:
Can you tell what is the following Python 3 function doing
def from_iso_datetime(datetimestring, use_dateutil=True):
    if not _iso8601_datetime_re.match(datetimestring):
        raise ValueError('Not a valid ISO8601-formatted datetime string')
    # Use dateutil's parser if possible
    if dateutil_available and use_dateutil:
        return parser.isoparse(datetimestring)
    else:
        # Strip off timezone info.
        return datetime.datetime.strptime(datetimestring[:19], '%Y-%m-%dT%H:%M:%S')

Response: Parse an ISO8601 - formatted datetime string and return a datetime object.


Instruction:
Can you tell what is the following Python 3 function doing
def from_iso_time(timestring, use_dateutil=True):
    if not _iso8601_time_re.match(timestring):
        raise ValueError('Not a valid ISO8601-formatted time string')
    if dateutil_available and use_dateutil:
        return parser.parse(timestring).time()
    else:
        if len(timestring) > 8:  # has microseconds
            fmt = '%H:%M:%S.%f'
        else:
            fmt = '%H:%M:%S'
        return datetime.datetime.strptime(timestring, fmt).time()

Response:
Parse an ISO8601 - formatted datetime string and return a datetime. time
            object.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_value(dct, key, value):
    if '.' in key:
        head, rest = key.split('.', 1)
        target = dct.setdefault(head, {})
        if not isinstance(target, dict):
            raise ValueError(
                'Cannot set {key} in {head} '
                'due to existing value: {target}'.format(key=key, head=head, target=target),
            )
        set_value(target, rest, value)
    else:
        dct[key] = value

Response: Set a value in a dict.


Instruction:
Implement a Python 3 function for
giving a callable return a tuple of argument names. Handles functools. partial objects and functools. class - based callables.

Response:
def get_func_args(func):
    """Given a callable, return a tuple of argument names. Handles
    `functools.partial` objects and class-based callables.

    .. versionchanged:: 3.0.0a1
        Do not return bound arguments, eg. ``self``.
    """
    if isinstance(func, functools.partial):
        return _signature(func.func)
    if inspect.isfunction(func) or inspect.ismethod(func):
        return _signature(func)
    # Callable class
    return _signature(func.__call__)


Instruction:
Make a summary of the following Python 3 code
def resolve_field_instance(cls_or_instance):
    if isinstance(cls_or_instance, type):
        if not issubclass(cls_or_instance, FieldABC):
            raise FieldInstanceResolutionError
        return cls_or_instance()
    else:
        if not isinstance(cls_or_instance, FieldABC):
            raise FieldInstanceResolutionError
        return cls_or_instance

Response: Return a Schema instance from a Marshmallow Schema class or instance.


Instruction:
Implement a Python 3 function for
converting naive time to local time

Response:
def localize(self, dt, is_dst=False):
        """Convert naive time to local time"""
        if dt.tzinfo is not None:
            raise ValueError('Not naive datetime (tzinfo is already set)')
        return dt.replace(tzinfo=self)


Instruction:
Make a summary of the following Python 3 code
def normalize(self, dt, is_dst=False):
        if dt.tzinfo is self:
            return dt
        if dt.tzinfo is None:
            raise ValueError('Naive time - no tzinfo set')
        return dt.astimezone(self)

Response: Correct the timezone information on the given datetime


Instruction:
Write a Python 3 function for
checking if a username and password combination is valid.

Response:
def check_auth(email, password):
    """Check if a username/password combination is valid.
    """
    try:
        user = User.get(User.email == email)
    except User.DoesNotExist:
        return False
    return password == user.password


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _stash_user(cls, user):
        global _stash
        ret = getattr(_stash, 'user', None)
        _stash.user = user
        return ret

Response: Stashes the user in the _stash dictionary.


Instruction:
Can you tell what is the following Python 3 function doing
def get_email(self, token):
        resp = requests.get(self.emails_url,
                            params={'access_token': token.token})
        emails = resp.json().get('values', [])
        email = ''
        try:
            email = emails[0].get('email')
            primary_emails = [e for e in emails if e.get('is_primary', False)]
            email = primary_emails[0].get('email')
        except (IndexError, TypeError, KeyError):
            return ''
        finally:
            return email

Response: Fetches email address from email API endpoint


Instruction:
Create a Python 3 function to
check whether or not the email address is already verified by allauth scope.

Response:
def is_email_verified(self, request, email):
        """
        Checks whether or not the email address is already verified
        beyond allauth scope, for example, by having accepted an
        invitation before signing up.
        """
        ret = False
        verified_email = request.session.get('account_verified_email')
        if verified_email:
            ret = verified_email.lower() == email.lower()
        return ret


Instruction:
Can you create a Python 3 function that
returns the URL to redirect to after logging in.

Response:
def get_login_redirect_url(self, request):
        """
        Returns the default URL to redirect to after logging in.  Note
        that URLs passed explicitly (e.g. by passing along a `next`
        GET parameter) take precedence over the value returned here.
        """
        assert request.user.is_authenticated
        url = getattr(settings, "LOGIN_REDIRECT_URLNAME", None)
        if url:
            warnings.warn("LOGIN_REDIRECT_URLNAME is deprecated, simply"
                          " use LOGIN_REDIRECT_URL with a URL name",
                          DeprecationWarning)
        else:
            url = settings.LOGIN_REDIRECT_URL
        return resolve_url(url)


Instruction:
Can you create a Python 3 function that
returns the URL to return to after successful e - mail confirmation.

Response:
def get_email_confirmation_redirect_url(self, request):
        """
        The URL to return to after successful e-mail confirmation.
        """
        if request.user.is_authenticated:
            if app_settings.EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL:
                return  \
                    app_settings.EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL
            else:
                return self.get_login_redirect_url(request)
        else:
            return app_settings.EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL


Instruction:
Can you generate the documentation for the following Python 3 function
def populate_username(self, request, user):
        from .utils import user_username, user_email, user_field
        first_name = user_field(user, 'first_name')
        last_name = user_field(user, 'last_name')
        email = user_email(user)
        username = user_username(user)
        if app_settings.USER_MODEL_USERNAME_FIELD:
            user_username(
                user,
                username or self.generate_unique_username([
                    first_name,
                    last_name,
                    email,
                    username,
                    'user']))

Response: Populates the username field of the user model with the user s username.


Instruction:
Write a Python 3 function that can
save a user instance using information provided in the theLogoutForm.

Response:
def save_user(self, request, user, form, commit=True):
        """
        Saves a new `User` instance using information provided in the
        signup form.
        """
        from .utils import user_username, user_email, user_field

        data = form.cleaned_data
        first_name = data.get('first_name')
        last_name = data.get('last_name')
        email = data.get('email')
        username = data.get('username')
        user_email(user, email)
        user_username(user, username)
        if first_name:
            user_field(user, 'first_name', first_name)
        if last_name:
            user_field(user, 'last_name', last_name)
        if 'password1' in data:
            user.set_password(data["password1"])
        else:
            user.set_unusable_password()
        self.populate_username(request, user)
        if commit:
            # Ability not to commit makes it easier to derive from
            # this adapter by adding
            user.save()
        return user


Instruction:
How would you explain what the following Python 3 function does
def clean_username(self, username, shallow=False):
        for validator in app_settings.USERNAME_VALIDATORS:
            validator(username)

        # TODO: Add regexp support to USERNAME_BLACKLIST
        username_blacklist_lower = [ub.lower()
                                    for ub in app_settings.USERNAME_BLACKLIST]
        if username.lower() in username_blacklist_lower:
            raise forms.ValidationError(
                self.error_messages['username_blacklisted'])
        # Skipping database lookups when shallow is True, needed for unique
        # username generation.
        if not shallow:
            from .utils import filter_users_by_username
            if filter_users_by_username(username).exists():
                user_model = get_user_model()
                username_field = app_settings.USER_MODEL_USERNAME_FIELD
                error_message = user_model._meta.get_field(
                    username_field).error_messages.get('unique')
                if not error_message:
                    error_message = self.error_messages['username_taken']
                raise forms.ValidationError(
                    error_message,
                    params={
                        'model_name': user_model.__name__,
                        'field_label': username_field,
                    }
                )
        return username

Response: Validates the username and returns the username that is valid.


Instruction:
Can you write a function in Python 3 where it
validates a password and returns a cleaned version of it.

Response:
def clean_password(self, password, user=None):
        """
        Validates a password. You can hook into this if you want to
        restric the allowed password choices.
        """
        min_length = app_settings.PASSWORD_MIN_LENGTH
        if min_length and len(password) < min_length:
            raise forms.ValidationError(_("Password must be a minimum of {0} "
                                          "characters.").format(min_length))
        validate_password(password, user)
        return password


Instruction:
Given the following Python 3 function, write the documentation
def add_message(self, request, level, message_template,
                    message_context=None, extra_tags=''):
        """
        Wrapper of `django.contrib.messages.add_message`, that reads
        the message text from a template.
        """
        if 'django.contrib.messages' in settings.INSTALLED_APPS:
            try:
                if message_context is None:
                    message_context = {}
                message = render_to_string(message_template,
                                           message_context).strip()
                if message:
                    messages.add_message(request, level, message,
                                         extra_tags=extra_tags)
            except TemplateDoesNotExist:
                pass

Response: Wrapper of django. contrib. messages. add_message that reads the message text from a template and writes it to the internal cache.


Instruction:
Given the following Python 3 function, write the documentation
def confirm_email(self, request, email_address):
        email_address.verified = True
        email_address.set_as_primary(conditional=True)
        email_address.save()

Response: Confirm the email address


Instruction:
Can you create a Python 3 function that
constructs the email confirmation url.

Response:
def get_email_confirmation_url(self, request, emailconfirmation):
        """Constructs the email confirmation (activation) url.

        Note that if you have architected your system such that email
        confirmations are sent outside of the request context `request`
        can be `None` here.
        """
        url = reverse(
            "account_confirm_email",
            args=[emailconfirmation.key])
        ret = build_absolute_uri(
            request,
            url)
        return ret


Instruction:
Can you tell what is the following Python 3 function doing
def authenticate(self, request, **credentials):
        from allauth.account.auth_backends import AuthenticationBackend

        self.pre_authenticate(request, **credentials)
        AuthenticationBackend.unstash_authenticated_user()
        user = authenticate(request, **credentials)
        alt_user = AuthenticationBackend.unstash_authenticated_user()
        user = user or alt_user
        if user and app_settings.LOGIN_ATTEMPTS_LIMIT:
            cache_key = self._get_login_attempts_cache_key(
                request, **credentials)
            cache.delete(cache_key)
        else:
            self.authentication_failed(request, **credentials)
        return user

Response: Only authenticates does not actually login. See login.


Instruction:
Can you generate the documentation for the following Python 3 function
def extract_common_fields(self, data):
        return dict(
            dc=data.get('dc'),
            role=data.get('role'),
            account_name=data.get('accountname'),
            user_id=data.get('user_id'),
            login=data.get('login'),
            login_url=data.get('login_url'),
            api_endpoint=data.get('api_endpoint'),
        )

Response: Extract fields from a metadata query.


Instruction:
Make a summary of the following Python 3 code
def to_dict(self, xml):
        children = list(xml)
        if not children:
            return xml.text
        else:
            out = {}
            for node in list(xml):
                if node.tag in out:
                    if not isinstance(out[node.tag], list):
                        out[node.tag] = [out[node.tag]]
                    out[node.tag].append(self.to_dict(node))
                else:
                    out[node.tag] = self.to_dict(node)
            return out

Response: Convert XML structure to dict recursively


Instruction:
Make a summary of the following Python 3 code
def provider_login_url(parser, token):
    bits = token.split_contents()
    provider_id = bits[1]
    params = token_kwargs(bits[2:], parser, support_legacy=False)
    return ProviderLoginURLNode(provider_id, params)

Response: Return provider login url.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def save_user(self, request, sociallogin, form=None):
        u = sociallogin.user
        u.set_unusable_password()
        if form:
            get_account_adapter().save_user(request, u, form)
        else:
            get_account_adapter().populate_username(request, u)
        sociallogin.save(request)
        return u

Response: Saves a newly signed up social login.


Instruction:
Write a Python 3 script for
populating the User instance with the data.

Response:
def populate_user(self,
                      request,
                      sociallogin,
                      data):
        """
        Hook that can be used to further populate the user instance.

        For convenience, we populate several common fields.

        Note that the user instance being populated represents a
        suggested User instance that represents the social user that is
        in the process of being logged in.

        The User instance need not be completely valid and conflict
        free. For example, verifying whether or not the username
        already exists, is not a responsibility.
        """
        username = data.get('username')
        first_name = data.get('first_name')
        last_name = data.get('last_name')
        email = data.get('email')
        name = data.get('name')
        user = sociallogin.user
        user_username(user, username or '')
        user_email(user, valid_email_or_none(email) or '')
        name_parts = (name or '').partition(' ')
        user_field(user, 'first_name', first_name or name_parts[0])
        user_field(user, 'last_name', last_name or name_parts[2])
        return user


Instruction:
Explain what the following Python 3 code does
def get_connect_redirect_url(self, request, socialaccount):
        assert request.user.is_authenticated
        url = reverse('socialaccount_connections')
        return url

Response: Returns the default URL to redirect to after successfully connecting a social account.


Instruction:
Given the following Python 3 function, write the documentation
def validate_disconnect(self, account, accounts):
        if len(accounts) == 1:
            # No usable password would render the local account unusable
            if not account.user.has_usable_password():
                raise ValidationError(_("Your account has no password set"
                                        " up."))
            # No email address, no password reset
            if app_settings.EMAIL_VERIFICATION \
                    == EmailVerificationMethod.MANDATORY:
                if EmailAddress.objects.filter(user=account.user,
                                               verified=True).count() == 0:
                    raise ValidationError(_("Your account has no verified"
                                            " e-mail address."))

Response: Validate whether or not the socialaccount account can be safely disconnected.


Instruction:
Given the following Python 3 function, write the documentation
def serialize_instance(instance):
    data = {}
    for k, v in instance.__dict__.items():
        if k.startswith('_') or callable(v):
            continue
        try:
            field = instance._meta.get_field(k)
            if isinstance(field, BinaryField):
                v = force_str(base64.b64encode(v))
            elif isinstance(field, FileField):
                if v and not isinstance(v, six.string_types):
                    v = v.name
            # Check if the field is serializable. If not, we'll fall back
            # to serializing the DB values which should cover most use cases.
            try:
                json.dumps(v, cls=DjangoJSONEncoder)
            except TypeError:
                v = field.get_prep_value(v)
                k = SERIALIZED_DB_FIELD_PREFIX + k
        except FieldDoesNotExist:
            pass
        data[k] = v
    return json.loads(json.dumps(data, cls=DjangoJSONEncoder))

Response: Serialize the object to a JSON - encoded version of the object.


Instruction:
Can you generate the documentation for the following Python 3 function
def set_form_field_order(form, field_order):
    if field_order is None:
        return
    fields = OrderedDict()
    for key in field_order:
        try:
            fields[key] = form.fields.pop(key)
        except KeyError:  # ignore unknown fields
            pass
    fields.update(form.fields)  # add remaining fields in original order
    form.fields = fields

Response: Sets the order of the fields in the form.


Instruction:
Here you have a function in Python 3, explain what it does
def build_absolute_uri(request, location, protocol=None):
    from .account import app_settings as account_settings

    if request is None:
        site = Site.objects.get_current()
        bits = urlsplit(location)
        if not (bits.scheme and bits.netloc):
            uri = '{proto}://{domain}{url}'.format(
                proto=account_settings.DEFAULT_HTTP_PROTOCOL,
                domain=site.domain,
                url=location)
        else:
            uri = location
    else:
        uri = request.build_absolute_uri(location)
    # NOTE: We only force a protocol if we are instructed to do so
    # (via the `protocol` parameter, or, if the default is set to
    # HTTPS. The latter keeps compatibility with the debatable use
    # case of running your site under both HTTP and HTTPS, where one
    # would want to make sure HTTPS links end up in password reset
    # mails even while they were initiated on an HTTP password reset
    # form.
    if not protocol and account_settings.DEFAULT_HTTP_PROTOCOL == 'https':
        protocol = account_settings.DEFAULT_HTTP_PROTOCOL
    # (end NOTE)
    if protocol:
        uri = protocol + ':' + uri.partition(':')[2]
    return uri

Response: helper function to build an absolute URI for a single object.


Instruction:
Given the following Python 3 function, write the documentation
def _base_signup_form_class():
    if not app_settings.SIGNUP_FORM_CLASS:
        return _DummyCustomSignupForm
    try:
        fc_module, fc_classname = app_settings.SIGNUP_FORM_CLASS.rsplit('.', 1)
    except ValueError:
        raise exceptions.ImproperlyConfigured('%s does not point to a form'
                                              ' class'
                                              % app_settings.SIGNUP_FORM_CLASS)
    try:
        mod = import_module(fc_module)
    except ImportError as e:
        raise exceptions.ImproperlyConfigured('Error importing form class %s:'
                                              ' "%s"' % (fc_module, e))
    try:
        fc_class = getattr(mod, fc_classname)
    except AttributeError:
        raise exceptions.ImproperlyConfigured('Module "%s" does not define a'
                                              ' "%s" class' % (fc_module,
                                                               fc_classname))
    if not hasattr(fc_class, 'signup'):
        if hasattr(fc_class, 'save'):
            warnings.warn("The custom signup form must offer"
                          " a `def signup(self, request, user)` method",
                          DeprecationWarning)
        else:
            raise exceptions.ImproperlyConfigured(
                'The custom signup form must implement a "signup" method')
    return fc_class

Response: Return the base signup form class that is used by the signup form manager.


Instruction:
Create a Python 3 function to
provide the credentials required to authenticate the user for the specified login.

Response:
def user_credentials(self):
        """
        Provides the credentials required to authenticate the user for
        login.
        """
        credentials = {}
        login = self.cleaned_data["login"]
        if app_settings.AUTHENTICATION_METHOD == AuthenticationMethod.EMAIL:
            credentials["email"] = login
        elif (
                app_settings.AUTHENTICATION_METHOD ==
                AuthenticationMethod.USERNAME):
            credentials["username"] = login
        else:
            if self._is_login_email(login):
                credentials["email"] = login
            credentials["username"] = login
        credentials["password"] = self.cleaned_data["password"]
        return credentials


Instruction:
Can you create a Python 3 function that
parses the FacebookLocales. xml file and builds a dictionary relating every available language to a list of available regions for that language and a default region.

Response:
def _build_locale_table(filename_or_file):
    """
    Parses the FacebookLocales.xml file and builds a dict relating every
    available language ('en, 'es, 'zh', ...) with a list of available regions
    for that language ('en' -> 'US', 'EN') and an (arbitrary) default region.
    """
    # Require the XML parser module only if we want the default mapping
    from xml.dom.minidom import parse

    dom = parse(filename_or_file)

    reps = dom.getElementsByTagName('representation')
    locs = map(lambda r: r.childNodes[0].data, reps)

    locale_map = {}
    for loc in locs:
        lang, _, reg = loc.partition('_')
        lang_map = locale_map.setdefault(lang, {'regs': [], 'default': reg})
        lang_map['regs'].append(reg)

    # Default region overrides (arbitrary)
    locale_map['en']['default'] = 'US'
    # Special case: Use es_ES for Spain and es_LA for everything else
    locale_map['es']['default'] = 'LA'
    locale_map['zh']['default'] = 'CN'
    locale_map['fr']['default'] = 'FR'
    locale_map['pt']['default'] = 'PT'

    return locale_map


Instruction:
Can you implement a function in Python 3 that
returns a callable that returns the default locale for the current FB.

Response:
def get_default_locale_callable():
    """
    Wrapper function so that the default mapping is only built when needed
    """
    exec_dir = os.path.dirname(os.path.realpath(__file__))
    xml_path = os.path.join(exec_dir, 'data', 'FacebookLocales.xml')

    fb_locales = _build_locale_table(xml_path)

    def default_locale(request):
        """
        Guess an appropiate FB locale based on the active Django locale.
        If the active locale is available, it is returned. Otherwise,
        it tries to return another locale with the same language. If there
        isn't one avaible, 'en_US' is returned.
        """
        chosen = 'en_US'
        language = get_language()
        if language:
            locale = to_locale(language)
            lang, _, reg = locale.partition('_')

            lang_map = fb_locales.get(lang)
            if lang_map is not None:
                if reg in lang_map['regs']:
                    chosen = lang + '_' + reg
                else:
                    chosen = lang + '_' + lang_map['default']
        return chosen

    return default_locale


Instruction:
Can you tell what is the following Python 3 function doing
def EMAIL_REQUIRED(self):
        from allauth.account import app_settings as account_settings
        return self._setting("EMAIL_REQUIRED", account_settings.EMAIL_REQUIRED)

Response: Returns a boolean value that indicates whether the user is required to hand over an e - mail address when signing up


Instruction:
Create a Python 3 function to
get the value of EMAIL_VERIFICATION

Response:
def EMAIL_VERIFICATION(self):
        """
        See e-mail verification method
        """
        from allauth.account import app_settings as account_settings
        return self._setting("EMAIL_VERIFICATION",
                             account_settings.EMAIL_VERIFICATION)


Instruction:
Can you write a function in Python 3 where it
returns a string representation of a social account. Includes the name of the user.

Response:
def to_str(self):
        '''
        Returns string representation of a social account. Includes the name
        of the user.
        '''
        dflt = super(DataportenAccount, self).to_str()
        return '%s (%s)' % (
            self.account.extra_data.get('name', ''),
            dflt,
        )


Instruction:
Write a Python 3 function that can
even when email verification is not mandatory during signup, there may be circumstances during which you really want to prevent unverified users to proceed. This decorator ensures the user is authenticated and has a verified email address. If the former is not the case then the behavior is identical to that of the standard `login_required` decorator. If the latter does not hold, email verification mails are automatically resend and the user is presented with a page informing them they needs to verify their email address.

Response:
def verified_email_required(function=None,
                            login_url=None,
                            redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Even when email verification is not mandatory during signup, there
    may be circumstances during which you really want to prevent
    unverified users to proceed. This decorator ensures the user is
    authenticated and has a verified email address. If the former is
    not the case then the behavior is identical to that of the
    standard `login_required` decorator. If the latter does not hold,
    email verification mails are automatically resend and the user is
    presented with a page informing them they needs to verify their email
    address.
    """
    def decorator(view_func):
        @login_required(redirect_field_name=redirect_field_name,
                        login_url=login_url)
        def _wrapped_view(request, *args, **kwargs):
            if not EmailAddress.objects.filter(user=request.user,
                                               verified=True).exists():
                send_email_confirmation(request, request.user)
                return render(request,
                              'account/verified_email_required.html')
            return view_func(request, *args, **kwargs)
        return _wrapped_view

    if function:
        return decorator(function)
    return decorator


Instruction:
Write a Python 3 script for
removing empty keys from params.

Response:
def _strip_empty_keys(self, params):
        """Added because the Dropbox OAuth2 flow doesn't
        work when scope is passed in, which is empty.
        """
        keys = [k for k, v in params.items() if v == '']
        for key in keys:
            del params[key]


Instruction:
Make a summary of the following Python 3 code
def int_to_base36(i):
    if six.PY2:
        char_set = '0123456789abcdefghijklmnopqrstuvwxyz'
        if i < 0:
            raise ValueError("Negative base36 conversion input.")
        if not isinstance(i, six.integer_types):
            raise TypeError("Non-integer base36 conversion input.")
        if i < 36:
            return char_set[i]
        b36 = ''
        while i != 0:
            i, n = divmod(i, 36)
            b36 = char_set[n] + b36
    else:
        from django.utils.http import int_to_base36
        b36 = int_to_base36(i)
    return b36

Response: Convert an integer to base36.


Instruction:
Implement a Python 3 function for
saving a new account.

Response:
def save(self, request, connect=False):
        """
        Saves a new account. Note that while the account is new,
        the user may be an existing one (when connecting accounts)
        """
        assert not self.is_existing
        user = self.user
        user.save()
        self.account.user = user
        self.account.save()
        if app_settings.STORE_TOKENS and self.token:
            self.token.account = self.account
            self.token.save()
        if connect:
            # TODO: Add any new email addresses automatically?
            pass
        else:
            setup_user_email(request, user, self.email_addresses)


Instruction:
Here you have a function in Python 3, explain what it does
def extract_common_fields(self, data):
        email = None
        for curr_email in data.get("emails", []):
            email = email or curr_email.get("email")
            if curr_email.get("verified", False) and \
                    curr_email.get("primary", False):
                email = curr_email.get("email")

        return dict(
            email=email,
            id=data.get('id'),
            name=data.get('name'),
            first_name=data.get('first_name'),
            last_name=data.get('last_name'),
            image_url=data.get('image_url')
        )

Response: Extract fields from a basic user query.


Instruction:
Given the following Python 3 function, write the documentation
def complete_login(self, request, app, token, **kwargs):
        '''
        Arguments:
            request - The get request to the callback URL
                        /accounts/dataporten/login/callback.
            app - The corresponding SocialApp model instance
            token - A token object with access token given in token.token
        Returns:
            Should return a dict with user information intended for parsing
            by the methods of the DataportenProvider view, i.e.
            extract_uid(), extract_extra_data(), and extract_common_fields()
        '''
        # The athentication header
        headers = {'Authorization': 'Bearer ' + token.token}

        # Userinfo endpoint, for documentation see:
        # https://docs.dataporten.no/docs/oauth-authentication/
        userinfo_response = requests.get(
            self.profile_url,
            headers=headers,
        )
        # Raise exception for 4xx and 5xx response codes
        userinfo_response.raise_for_status()

        # The endpoint returns json-data and it needs to be decoded
        extra_data = userinfo_response.json()['user']

        # Finally test that the audience property matches the client id
        # for validification reasons, as instructed by the Dataporten docs
        # if the userinfo-response is used for authentication
        if userinfo_response.json()['audience'] != app.client_id:
            raise ProviderException(
                'Dataporten returned a user with an audience field \
                 which does not correspond to the client id of the \
                 application.'
                )

        return self.get_provider().sociallogin_from_response(
            request,
            extra_data,
        )

Response: Complete the login process for the given token.


Instruction:
Create a Python 3 function to
dispatch the user to the provider based authentication

Response:
def dispatch(self, request):
        """
        View to handle final steps of OAuth based authentication where the user
        gets redirected back to from the service provider
        """
        login_done_url = reverse(self.adapter.provider_id + "_callback")
        client = self._get_client(request, login_done_url)
        if not client.is_valid():
            if 'denied' in request.GET:
                error = AuthError.CANCELLED
            else:
                error = AuthError.UNKNOWN
            extra_context = dict(oauth_client=client)
            return render_authentication_error(
                request,
                self.adapter.provider_id,
                error=error,
                extra_context=extra_context)
        app = self.adapter.get_provider().get_app(request)
        try:
            access_token = client.get_access_token()
            token = SocialToken(
                app=app,
                token=access_token['oauth_token'],
                # .get() -- e.g. Evernote does not feature a secret
                token_secret=access_token.get('oauth_token_secret', ''))
            login = self.adapter.complete_login(request,
                                                app,
                                                token,
                                                response=access_token)
            login.token = token
            login.state = SocialLogin.unstash_state(request)
            return complete_social_login(request, login)
        except OAuthError as e:
            return render_authentication_error(
                request,
                self.adapter.provider_id,
                exception=e)


Instruction:
Write a Python 3 script for
extracting the object at path from the data dictionary.

Response:
def extract_from_dict(data, path):
    """
    Navigate `data`, a multidimensional array (list or dictionary), and returns
    the object at `path`.
    """
    value = data
    try:
        for key in path:
            value = value[key]
        return value
    except (KeyError, IndexError, TypeError):
        return ''


Instruction:
Can you create a Python 3 function that
extracts the email address from the data.

Response:
def _extract_email(data):
    """
    {'elements': [{'handle': 'urn:li:emailAddress:319371470',
               'handle~': {'emailAddress': 'raymond.penners@intenct.nl'}}]}
    """
    ret = ''
    elements = data.get('elements', [])
    if len(elements) > 0:
        ret = elements[0].get('handle~', {}).get('emailAddress', '')
    return ret


Instruction:
Write a Python 3 function that can
obtain a temporary request token and to the request token and to the request token session.

Response:
def _get_request_token(self):
        """
        Obtain a temporary request token to authorize an access token and to
        sign the request to obtain the access token
        """
        if self.request_token is None:
            get_params = {}
            if self.parameters:
                get_params.update(self.parameters)
            get_params['oauth_callback'] \
                = self.request.build_absolute_uri(self.callback_url)
            rt_url = self.request_token_url + '?' + urlencode(get_params)
            oauth = OAuth1(self.consumer_key,
                           client_secret=self.consumer_secret)
            response = requests.post(url=rt_url, auth=oauth)
            if response.status_code not in [200, 201]:
                raise OAuthError(
                    _('Invalid response while obtaining request token'
                      ' from "%s".') % get_token_prefix(
                          self.request_token_url))
            self.request_token = dict(parse_qsl(response.text))
            self.request.session['oauth_%s_request_token' % get_token_prefix(
                self.request_token_url)] = self.request_token
        return self.request_token


Instruction:
Explain what the following Python 3 code does
def get_access_token(self):
        if self.access_token is None:
            request_token = self._get_rt_from_session()
            oauth = OAuth1(
                self.consumer_key,
                client_secret=self.consumer_secret,
                resource_owner_key=request_token['oauth_token'],
                resource_owner_secret=request_token['oauth_token_secret'])
            at_url = self.access_token_url
            # Passing along oauth_verifier is required according to:
            # http://groups.google.com/group/twitter-development-talk/browse_frm/thread/472500cfe9e7cdb9#
            # Though, the custom oauth_callback seems to work without it?
            oauth_verifier = get_request_param(self.request, 'oauth_verifier')
            if oauth_verifier:
                at_url = at_url + '?' + urlencode(
                    {'oauth_verifier': oauth_verifier})
            response = requests.post(url=at_url, auth=oauth)
            if response.status_code not in [200, 201]:
                raise OAuthError(
                    _('Invalid response while obtaining access token'
                      ' from "%s".') % get_token_prefix(
                          self.request_token_url))
            self.access_token = dict(parse_qsl(response.text))

            self.request.session['oauth_%s_access_token' % get_token_prefix(
                self.request_token_url)] = self.access_token
        return self.access_token

Response: Obtain the access token to access private resources at the API.


Instruction:
Can you implement a function in Python 3 that
returns a HttpResponseRedirect object to redirect the user to the URL the OAuth provider handles authorization.

Response:
def get_redirect(self, authorization_url, extra_params):
        """
        Returns a ``HttpResponseRedirect`` object to redirect the user
        to the URL the OAuth provider handles authorization.
        """
        request_token = self._get_request_token()
        params = {'oauth_token': request_token['oauth_token'],
                  'oauth_callback': self.request.build_absolute_uri(
                      self.callback_url)}
        params.update(extra_params)
        url = authorization_url + '?' + urlencode(params)
        return HttpResponseRedirect(url)


Instruction:
Explain what the following Python 3 code does
def _get_at_from_session(self):
        try:
            return self.request.session['oauth_%s_access_token'
                                        % get_token_prefix(
                                            self.request_token_url)]
        except KeyError:
            raise OAuthError(
                _('No access token saved for "%s".')
                % get_token_prefix(self.request_token_url))

Response: Get the saved access token for private resources from the session.


Instruction:
How would you code a function in Python 3 to
request a URL at url with params being either the POST or GET data.

Response:
def query(self, url, method="GET", params=dict(), headers=dict()):
        """
        Request a API endpoint at ``url`` with ``params`` being either the
        POST or GET data.
        """
        access_token = self._get_at_from_session()
        oauth = OAuth1(
            self.consumer_key,
            client_secret=self.secret_key,
            resource_owner_key=access_token['oauth_token'],
            resource_owner_secret=access_token['oauth_token_secret'])
        response = getattr(requests, method.lower())(url,
                                                     auth=oauth,
                                                     headers=headers,
                                                     params=params)
        if response.status_code != 200:
            raise OAuthError(
                _('No access to private resources at "%s".')
                % get_token_prefix(self.request_token_url))

        return response.text


Instruction:
Can you generate the documentation for the following Python 3 function
def get_next_redirect_url(request, redirect_field_name="next"):
    redirect_to = get_request_param(request, redirect_field_name)
    if not get_adapter(request).is_safe_url(redirect_to):
        redirect_to = None
    return redirect_to

Response: Returns the next URL to redirect to if the request parameter is not passed.


Instruction:
Write a Python 3 script for
getting or sets a user model field.

Response:
def user_field(user, field, *args):
    """
    Gets or sets (optional) user model fields. No-op if fields do not exist.
    """
    if not field:
        return
    User = get_user_model()
    try:
        field_meta = User._meta.get_field(field)
        max_length = field_meta.max_length
    except FieldDoesNotExist:
        if not hasattr(user, field):
            return
        max_length = None
    if args:
        # Setter
        v = args[0]
        if v:
            v = v[0:max_length]
        setattr(user, field, v)
    else:
        # Getter
        return getattr(user, field)


Instruction:
Here you have a function in Python 3, explain what it does
def perform_login(request, user, email_verification,
                  redirect_url=None, signal_kwargs=None,
                  signup=False):
    """
    Keyword arguments:

    signup -- Indicates whether or not sending the
    email is essential (during signup), or if it can be skipped (e.g. in
    case email verification is optional and we are only logging in).
    """
    # Local users are stopped due to form validation checking
    # is_active, yet, adapter methods could toy with is_active in a
    # `user_signed_up` signal. Furthermore, social users should be
    # stopped anyway.
    adapter = get_adapter(request)
    if not user.is_active:
        return adapter.respond_user_inactive(request, user)

    from .models import EmailAddress
    has_verified_email = EmailAddress.objects.filter(user=user,
                                                     verified=True).exists()
    if email_verification == EmailVerificationMethod.NONE:
        pass
    elif email_verification == EmailVerificationMethod.OPTIONAL:
        # In case of OPTIONAL verification: send on signup.
        if not has_verified_email and signup:
            send_email_confirmation(request, user, signup=signup)
    elif email_verification == EmailVerificationMethod.MANDATORY:
        if not has_verified_email:
            send_email_confirmation(request, user, signup=signup)
            return adapter.respond_email_verification_sent(
                request, user)
    try:
        adapter.login(request, user)
        response = HttpResponseRedirect(
            get_login_redirect_url(request, redirect_url))

        if signal_kwargs is None:
            signal_kwargs = {}
        signals.user_logged_in.send(sender=user.__class__,
                                    request=request,
                                    response=response,
                                    user=user,
                                    **signal_kwargs)
        adapter.add_message(
            request,
            messages.SUCCESS,
            'account/messages/logged_in.txt',
            {'user': user})
    except ImmediateHttpResponse as e:
        response = e.response
    return response

Response: Perform login and return a response.


Instruction:
Explain what the following Python 3 code does
def cleanup_email_addresses(request, addresses):
    from .models import EmailAddress
    adapter = get_adapter(request)
    # Let's group by `email`
    e2a = OrderedDict()  # maps email to EmailAddress
    primary_addresses = []
    verified_addresses = []
    primary_verified_addresses = []
    for address in addresses:
        # Pick up only valid ones...
        email = valid_email_or_none(address.email)
        if not email:
            continue
        # ... and non-conflicting ones...
        if (app_settings.UNIQUE_EMAIL and
                EmailAddress.objects.filter(email__iexact=email).exists()):
            continue
        a = e2a.get(email.lower())
        if a:
            a.primary = a.primary or address.primary
            a.verified = a.verified or address.verified
        else:
            a = address
            a.verified = a.verified or adapter.is_email_verified(request,
                                                                 a.email)
            e2a[email.lower()] = a
        if a.primary:
            primary_addresses.append(a)
            if a.verified:
                primary_verified_addresses.append(a)
        if a.verified:
            verified_addresses.append(a)
    # Now that we got things sorted out, let's assign a primary
    if primary_verified_addresses:
        primary_address = primary_verified_addresses[0]
    elif verified_addresses:
        # Pick any verified as primary
        primary_address = verified_addresses[0]
    elif primary_addresses:
        # Okay, let's pick primary then, even if unverified
        primary_address = primary_addresses[0]
    elif e2a:
        # Pick the first
        primary_address = e2a.keys()[0]
    else:
        # Empty
        primary_address = None
    # There can only be one primary
    for a in e2a.values():
        a.primary = primary_address.email.lower() == a.email.lower()
    return list(e2a.values()), primary_address

Response: Takes a list of EmailAddress instances and cleans up the list of EmailAddress objects that are not already in the list of valid e - mail addresses.