"""
requests.utils
~~~~~~~~~~~~~~

This module provides utility functions that are used within Requests
that are also useful for external consumption.
"""

# to_native_string is unused here, but imported here for backwards compatibility

# Ensure that ', ' is used to preserve previous delimiter behavior.

    # provide a proxy_bypass version on Windows without DNS lookups

            # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it
            
            # ProxyOverride is almost always a string
            
        # make a check value list from the registry entry: replace the
        # '<local>' string by the localhost entry and the corresponding
        # canonical entry.
        
        # now check if we match one of the registry values.
        
"""Return True, if the host should be bypassed.

        Checks proxy settings gathered from the environment, if specified,
        or the registry.
        """

            # AttributeError is a surprising exception, seeing as how we've just checked
            # that `hasattr(o, 'fileno')`.  It happens for objects obtained via
            # `Tarfile.extractfile()`, per issue 5229.
            
            # Having used fstat to determine the file length, we need to
            # confirm that this file was opened up in binary mode.
            
            # This can happen in some weird situations, such as when the file
            # is actually a special file descriptor like stdin. In this
            # instance, we don't know what the length is, so set it to zero and
            # let requests chunk it instead.
            
                # StringIO and BytesIO have seek but no usable fileno
                
                    # seek back to current position to support
                    # partially read file-like objects
                    
"""Returns the Requests tuple auth for a given url from netrc."""

                # os.path.expanduser can fail when $HOME is undefined and
                # getpwuid fails. See https://bugs.python.org/issue20164 &
                # https://github.com/psf/requests/issues/1846
                
        # Strip port numbers from netloc. This weird `if...encode`` dance is
        # used for Python 3.2, which doesn't support unicode literals.
        
            # If there was a parsing error or a permissions issue reading the file,
            # we'll just skip netrc auth unless explicitly asked to raise errors.
            
"""Replace nonexistent paths that look like they refer to a member of a zip
    archive with the location of an extracted copy of the target, or else
    just return the provided path unchanged.
    """

        # this is already a valid path, no need to do anything further
        
    # find the first valid part of the provided path and treat that as a zip archive
    # assume the rest of the path is the name of a member in the archive
    
            # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split),
            # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users
            
    # we have a valid zip archive and a valid member of that archive
    
        # use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition
        
"""Take an object and test to see if it can be represented as a
    dictionary. Unless it can not be represented as such, return an
    OrderedDict, e.g.,

    ::

        >>> from_key_val_list([('key', 'val')])
        OrderedDict([('key', 'val')])
        >>> from_key_val_list('string')
        Traceback (most recent call last):
        ...
        ValueError: cannot encode objects that are not 2-tuples
        >>> from_key_val_list({'key': 'val'})

    :rtype: OrderedDict
    """

    dictionary. If it can be, return a list of tuples, e.g.,

    ::

        >>> to_key_val_list([('key', 'val')])
        [('key', 'val')]
        >>> to_key_val_list({'key': 'val'})
        >>> to_key_val_list('string')
        ...

    :rtype: list
    """

"""Parse lists as described by RFC 2068 Section 2.

    In particular, parse comma-separated lists where the elements of
    the list may include quoted-strings.  A quoted-string could
    contain a comma.  A non-quoted string could have quotes in the
    middle.  Quotes are removed automatically after parsing.

    It basically works like :func:`parse_set_header` just that items
    may appear multiple times and case sensitivity is preserved.

    The return value is a standard :class:`list`:

    >>> parse_list_header('token, "quoted value"')
    ['token', 'quoted value']

    To create a header from the :class:`list` again, use the
    :func:`dump_header` function.

    :param value: a string with a list header.
    :return: :class:`list`
    """

"""Parse lists of key, value pairs as described by RFC 2068 Section 2 and
    convert them into a python dict:

    >>> d = parse_dict_header('foo="is a fish", bar="as well"')
    >>> type(d) is dict
    True
    >>> sorted(d.items())
    [('bar', 'as well'), ('foo', 'is a fish')]

    If there is no value for a key it will be `None`:

    >>> parse_dict_header('key_without_value')
    {'key_without_value': None}

    To create a header from the :class:`dict` again, use the

    :param value: a string with a dict header.
    :return: :class:`dict`
    :rtype: dict
    """

r"""Unquotes a header value.  (Reversal of :func:`quote_header_value`).
    This does not use the real unquoting but what browsers are actually
    using for quoting.

    :param value: the header value to unquote.
    :rtype: str
    """

        # this is not the real unquoting, but fixing this so that the
        # RFC is met will result in bugs with internet explorer and
        # probably some other browsers as well.  IE for example is
        # uploading files with "C:\foo\bar.txt" as filename
        
        # if this is a filename and the starting characters look like
        # a UNC path, then just return the value without quotes.  Using the
        # replace sequence below on a UNC path has the effect of turning
        # the leading double slash into a single slash and then
        # _fix_ie_filename() doesn't work correctly.  See #458.
        
"""Returns a key/value dictionary from a CookieJar.

    :param cj: CookieJar object to extract cookies from.
    """

"""Returns a CookieJar from a key/value dictionary.

    :param cj: CookieJar to insert cookies into.
    :param cookie_dict: Dict of key/values to insert into CookieJar.
    :rtype: CookieJar
    """

"""Returns encodings from given content string.

    :param content: bytestring to extract encodings from.
    """

"In requests 3.0, get_encodings_from_content will be removed. For "

"more information, please see the discussion on issue #2266. (This"

"""Returns content type and parameters from given header

    :param header: string
    :return: tuple containing content type and dictionary of
         parameters
    """

"""Returns encodings from given HTTP Header Dict.

    :param headers: dictionary to extract encoding from.
    """

        # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset
        
"""Returns the requested content back in unicode.

    :param r: Response object to get unicode content from.

    Tried:

    1. charset from content-type
    2. fall back and replace all unicode characters

    """

"In requests 3.0, get_unicode_from_response will be removed. For "

"""Un-escape any percent-escape sequences in a URI that are unreserved
    characters. This leaves all reserved, illegal and non-ASCII bytes encoded.

    """

"""Re-quote the given URI.

    This function passes the given URI through an unquote/quote cycle to
    ensure that it is fully and consistently quoted.

    """

        # Unquote only the unreserved characters
        # Then quote only illegal characters (do not quote reserved,
        # unreserved, or '%')
        
        # We couldn't unquote the given URI, so let's try quoting it, but
        # there may be unquoted '%'s in the URI. We need to make sure they're
        # properly quoted so they do not cause issues elsewhere.
        
"""This function allows you to check if an IP belongs to a network subnet

    Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
             returns False if ip = 192.168.1.1 and net = 192.168.100.0/24

    :rtype: bool
    """

"""Converts mask from /xx format to xxx.xxx.xxx.xxx

    Example: if mask is 24 function returns 255.255.255.0

    """

"""
    Very simple check of the cidr format in no_proxy variable.

    """

"""Set the environment variable 'env_name' to 'value'

    Save previous value, yield, and then restore the previous value stored in
    the environment variable 'env_name'.

    If 'value' is None, do nothing"""

"""
    Returns whether we should bypass proxies or not.

    """

    # Prioritize lowercase environment variables over uppercase
    # to keep a consistent behaviour with other http projects (curl, wget).
    
    # First check whether no_proxy is defined. If it is, check that the URL
    # we're getting isn't in the no_proxy list.
    
        # URLs don't always have hostnames, e.g. file:/// urls.
        
        # We need to check whether we match here. We need to see if we match
        # the end of the hostname, both with and without the port.
        
                    # If no_proxy ip was defined in plain IP notation instead of cidr notation &
                    # matches the IP of the index
                    
                    # The URL does match something in no_proxy, so we don't want
                    # to apply the proxies on this URL.
                    
        # parsed.hostname can be `None` in cases such as a file URI.
        
"""
    Return a dict of environment proxies.

    """

"""Select a proxy for the url, if applicable.

    :param url: The url being for the request
    :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
    """

"""This method takes proxy information from a request and configuration
    input to resolve a mapping of target proxies. This will consider settings
    such a NO_PROXY to strip proxy configurations.

    :param request: Request or PreparedRequest
    :param trust_env: Boolean declaring whether to trust environment configs

    """

"""
    Return a string representing the default user agent.

    """

"""Return a list of parsed link headers proxies.

    i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"

    """

# Null bytes; no need to recreate these on each call to guess_json_utf

    # JSON always starts with two ASCII characters, so detection is as
    # easy as counting the nulls and from their location and count
    # determine the encoding. Also detect a BOM, if present.
    
        # Did not detect 2 valid UTF-16 ascii-range characters
    
        # Did not detect a valid UTF-32 ascii-range character
    
"""Given a URL that may or may not have a scheme, prepend the given scheme.
    Does not replace a present scheme with the one provided as an argument.

    """

    # A defect in urlparse determines that there isn't a netloc present in some
    # urls. We previously assumed parsing was overly cautious, and swapped the
    # netloc and path. Due to a lack of tests on the original defect, this is
    # maintained with parse_url for backwards compatibility.
    
        # parse_url doesn't provide the netloc with auth
        # so we'll add it ourselves.
        
"""Given a url with authentication components, extract them into a tuple of
    username,password.

    :rtype: (str,str)
    """

"""Verifies that header parts don't contain leading whitespace
    reserved characters, or return characters.

    :param header: tuple, in the format (name, value).
    """

"""
    Given a url remove the fragment and the authentication part.

    """

"""Move file pointer back to its recorded starting position
    so it can be read again on redirect.
    """

    re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"])

                r"Software\Microsoft\Windows\CurrentVersion\Internet Settings",

            proxyEnable = int(winreg.QueryValueEx(internetSettings, "ProxyEnable")[0])

            proxyOverride = winreg.QueryValueEx(internetSettings, "ProxyOverride")[0]

            test = test.replace("*", r".*")  # change glob sequence

                        "Requests has determined the content-length for this "

                        "request using the binary size of the file: however, the "

                        "file has been opened in text mode (i.e. without the 'b' "

                        "flag in the mode). This may lead to an incorrect "

                        "content-length. In Requests 3.0, support will be removed "

    """Returns the Requests tuple auth for a given url from netrc."""

    if name and isinstance(name, basestring) and name[0] != "<" and name[-1] != ">":

    """Replace nonexistent paths that look like they refer to a member of a zip

    tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename))

    """Take an object and test to see if it can be represented as a

        raise ValueError("cannot encode objects that are not 2-tuples")

    """Parse lists of key, value pairs as described by RFC 2068 Section 2 and

    r"""Unquotes a header value.  (Reversal of :func:`quote_header_value`).

            return value.replace("\\\\", "\\").replace('\\"', '"')

            "In requests 3.0, get_encodings_from_content will be removed. For "

            "more information, please see the discussion on issue #2266. (This"

    charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)

    pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)

    xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')

                key = param[:index_of_equals].strip(items_to_strip)

                value = param[index_of_equals + 1 :].strip(items_to_strip)

    content_type, params = _parse_content_type_header(content_type)

    decoder = codecs.getincrementaldecoder(r.encoding)(errors="replace")

            "In requests 3.0, get_unicode_from_response will be removed. For "

    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~"

    """Un-escape any percent-escape sequences in a URI that are unreserved

                raise InvalidURL(f"Invalid percent-escape sequence: '{h}'")

        return quote(unquote_unreserved(uri), safe=safe_with_percent)

    """This function allows you to check if an IP belongs to a network subnet

    netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0]

    network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask

        return os.environ.get(key) or os.environ.get(key.upper())

        no_proxy = (host for host in no_proxy.replace(" ", "").split(",") if host)

                    if address_in_network(parsed.hostname, proxy_ip):

                if parsed.hostname.endswith(host) or host_with_port.endswith(host):

        return proxies.get(urlparts.scheme, proxies.get("all"))

    """This method takes proxy information from a request and configuration

    if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy):

        environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)

        proxy = environ_proxies.get(scheme, environ_proxies.get("all"))

            link[key.strip(replace_chars)] = value.strip(replace_chars)

_null = "\x00".encode("ascii")  # encoding to ASCII for Python 3

        return "utf-8-sig"  # BOM included, MS style (discouraged)

    if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):

    """Given a URL that may or may not have a scheme, prepend the given scheme.

    return urlunparse((scheme, netloc, path, "", query, fragment))

    """Given a url with authentication components, extract them into a tuple of

        auth = (unquote(parsed.username), unquote(parsed.password))

    """Verifies that header parts don't contain leading whitespace

def _validate_header_part(header, header_part, header_validator_index):

        validator = _HEADER_VALIDATORS_STR[header_validator_index]

        validator = _HEADER_VALIDATORS_BYTE[header_validator_index]

            f"must be of type str or bytes, not {type(header_part)}"

        header_kind = "name" if header_validator_index == 0 else "value"

            f"Invalid leading whitespace, reserved character(s), or return"

            f"character(s) in header {header_kind}: {header_part!r}"

    scheme, netloc, path, params, query, fragment = urlparse(url)

    return urlunparse((scheme, netloc, path, params, query, ""))

    """Move file pointer back to its recorded starting position

                "An error occurred when rewinding request body for redirect."

        raise UnrewindableBodyError("Unable to rewind request body for redirect.")