
    .Ph                     L   d Z ddlZddlZddlZddlmZ  ed          Z ej        d          Z	d ej
        D             Z ej        d          Zi dd	d
dddddddddddddddddddddddd d!d"d#d$d%d&d'i d(d)d*d+d,dd-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdDddIdJdKdLdMddddN
Zh dOZ edP          Z edQ          Zeez  Zeez  Zeez
  Zeez   edR          z  Zeez
  Zeez   edS          z  Zeez
  Zee edT          z
  z  Zeez
  Z G dU dVe          ZdWZdX Z ej        dY          Zdd\Z d] Z! e!e          Z" e!e          Z# e!e          Z$ e!e          Z%dd_Z&dd`Z'ddaZ(ddbZ)ddeZ*df Z+ddgZ,dh Z- G di dj          Z. G dk dl          Z/	 ddmlm0Z0 nG# e1$ r? ddl2Z2 G dn doe2j3                  Z4e2j5        j6        j7        Z7e2j5        j6        j8        Z8dp Z0Y nw xY wdq Z9dr Z: e:ds          Z;d^efdtZ<	 ddul=m>Z>m?Z?m@Z@ ddvlAmBZB 	 dwdxlCmDZD  eDdyz          ZEn# e1$ r  eF            ZEY nw xY w eGd{          \  ZHZIZJZKZLZM G d| d}eN          ZO	 dwd~lPmOZO n# e1$ r Y nw xY weOZQ G d deO          ZRdS )a  :mod:`urlutils` is a module dedicated to one of software's most
versatile, well-aged, and beloved data structures: the URL, also known
as the `Uniform Resource Locator`_.

Among other things, this module is a full reimplementation of URLs,
without any reliance on the :mod:`urlparse` or :mod:`urllib` standard
library modules. The centerpiece and top-level interface of urlutils
is the :class:`URL` type. Also featured is the :func:`find_all_links`
convenience function. Some low-level functions and constants are also
below.

The implementations in this module are based heavily on `RFC 3986`_ and
`RFC 3987`_, and incorporates details from several other RFCs and `W3C
documents`_.

.. _Uniform Resource Locator: https://en.wikipedia.org/wiki/Uniform_Resource_Locator
.. _RFC 3986: https://tools.ietf.org/html/rfc3986
.. _RFC 3987: https://tools.ietf.org/html/rfc3987
.. _W3C documents: https://www.w3.org/TR/uri-clarification/

    N)	normalizezB~-._0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzz~^((?P<scheme>[^:/?#]+):)?((?P<_netloc_sep>//)(?P<authority>[^/?#]*))?(?P<path>[^?#]*)(\?(?P<query>[^#]*))?(#(?P<fragment>.*))?c           
          i | ][}t           j        D ]L}||z                       d           t          t	          ||z   d                                        d          M\S )ascii   charmap)string	hexdigitsencodechrint).0abs      P/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/boltons/urlutils.py
<dictcomp>r   F   s}     F F FF4DF F/0 a%((SQ^^$$++I66F F F F    z([ -]+)acapi  afpi$  dictiD
  dns5   fileftp   giti$  gopherF   httpP   httpsi  imap   ippiw  ippsirc   ircsi)  ldapi  ldapsi|  mmsi  msrpi'  msrpsmtqpi  nfso   nntpw   nntpsi3  popn   prosperoi  redisi  rsyncii  rtspi*  rtspsiB  rtspui  sftp   smbi  snmp   ij     i  i     )
sshsteamsvntelnetventrilovncwaiswswssxmpp>   geosiptelurnblobdatanewssipsaboutmagnetmailtopkcs11bitcoinz:/?#[]@z!$&'()*+,;=z:@z/?z&=+c                       e Zd ZdZdS )URLParseErrorzException inheriting from :exc:`ValueError`, raised when failing to
    parse a URL. Mostly raised on invalid ports and IPv6 addresses.
    N)__name__
__module____qualname____doc__ r   r   rZ   rZ   q   s          	Dr   rZ   utf8c                 n    	 t          |           S # t          $ r t          | t                    cY S w xY w)N)encoding)strUnicodeDecodeErrorDEFAULT_ENCODING)objs    r   
to_unicoderg   {   sG    33xx 3 3 33!12222223s     44z\b((?:([\w-]+):(/{1,3})|www[.])(?:(?:(?:[^\s&()<>]|&amp;|&quot;)*(?:[^!"#$%'()*+,.:;<=>?@\[\]^`{|}~\s]))|(?:\((?:[^\s&()]|&amp;|&quot;)*\)))+)Fr_   c                    t          |           } d\  }}}g j        fd}t                              |           D ]}|                    d          |                    d          }}||k     r|r | ||                    |}	 |                    d          }	t          |	          }
|
j        s,|rt          |dz   |	z             }
n || ||                    |r|
j        |vr || ||                    n |
           # t          $ r |r || ||                    Y w xY w|r| |d         }|r ||           S )al  This function uses heuristics to searches plain text for strings
    that look like URLs, returning a :class:`list` of :class:`URL`
    objects. It supports limiting the accepted schemes, and returning
    interleaved text as well.

    >>> find_all_links('Visit https://boltons.rtfd.org!')
    [URL(u'https://boltons.rtfd.org')]
    >>> find_all_links('Visit https://boltons.rtfd.org!', with_text=True)
    [u'Visit ', URL(u'https://boltons.rtfd.org'), u'!']

    Args:
       text (str): The text to search.

       with_text (bool): Whether or not to interleave plaintext blocks
          with the returned URL objects. Having all tokens can be
          useful for transforming the text, e.g., replacing links with
          HTML equivalents. Defaults to ``False``.

       default_scheme (str): Many URLs are written without the scheme
          component. This function can match a reasonable subset of
          those, provided *default_scheme* is set to a string. Set to
          ``False`` to disable matching scheme-less URLs. Defaults to
          ``'https'``.

       schemes (list): A list of strings that a URL's scheme must
          match in order to be included in the results. Defaults to
          empty, which matches all schemes.

    .. note:: Currently this function does not support finding IPv6
      addresses or URLs with netloc-less schemes, like mailto.

    )r   NNc                 |    r-t          d         t                    rdxx         | z  cc<   d S  |            d S N)
isinstancerc   )t_addrets    r   	_add_textz!find_all_links.<locals>._add_text   sJ     	:c"gs++ 	GGGqLGGGGGDGGGGGr      r   z://N)
rg   append_FIND_ALL_URL_REfinditerstartendgroupURLschemerZ   )text	with_textdefault_schemeschemesprev_endru   rv   rp   matchcur_url_textcur_urltailrn   ro   s               @@r   find_all_linksr      s   B dD(HeS
C:D      "**400 + +[[^^UYYq\\se	Dhun%&&&	+ ;;q>>L,''G> ! !.5"8<"GHHGGId59o... 7>88	$uSy/****W 	+ 	+ 	+  +	$uSy/***		+  HII 	IdOOOJs   AD"*DD/.D/c                     i }t          t          d          t          d                    D ]1\  }}t          |          }|| v r|x||<   ||<   #d|dx||<   ||<   2|S )N   %02X)zipranger   )
safe_charsro   ivcs        r   _make_quote_mapr      s{    
C E#JJc

++ * *1FF
??CFSVV)!kkk)CFSVVJr   Tc                     |rOt          dt          |                                         d          }d                    d |D                       S d                    d | D                       S )z8
    Percent-encode a single segment of a URL path.
    NFCr`    c                 (    g | ]}t           |         S r_   )_PATH_PART_QUOTE_MAPr   r   s     r   
<listcomp>z#quote_path_part.<locals>.<listcomp>   s    AAAA,Q/AAAr   c                 >    g | ]}|t           v rt          |         n|S r_   )_PATH_DELIMSr   r   rm   s     r   r   z#quote_path_part.<locals>.<listcomp>   s=     $ $ $ 01L/@/@(++a $ $ $r   r   rg   r
   joinrz   
full_quotebytestrs      r   quote_path_partr      s      CE:d#3#344;;FCCwwAAAAABBB77 $ $"$ $ $ % % %r   c                     |rOt          dt          |                                         d          }d                    d |D                       S d                    d | D                       S )z<
    Percent-encode a single query string key or value.
    r   r`   r   c                 (    g | ]}t           |         S r_   )_QUERY_PART_QUOTE_MAPr   s     r   r   z$quote_query_part.<locals>.<listcomp>   s    BBBQ-a0BBBr   c                 >    g | ]}|t           v rt          |         n|S r_   )_QUERY_DELIMSr   r   s     r   r   z$quote_query_part.<locals>.<listcomp>   s=     $ $ $ 12]0B0B)!,, $ $ $r   r   r   s      r   quote_query_partr      s      DE:d#3#344;;FCCwwBB'BBBCCC77 $ $"$ $ $ % % %r   c                     |rOt          dt          |                                         d          }d                    d |D                       S d                    d | D                       S )zyQuote the fragment part of the URL. Fragments don't have
    subdelimiters, so the whole URL fragment can be passed.
    r   r`   r   c                 (    g | ]}t           |         S r_   )_FRAGMENT_QUOTE_MAPr   s     r   r   z'quote_fragment_part.<locals>.<listcomp>  s    @@@1+A.@@@r   c                 >    g | ]}|t           v rt          |         n|S r_   )_FRAGMENT_DELIMSr   r   s     r   r   z'quote_fragment_part.<locals>.<listcomp>  s>     $ $ $ /03C.C.C'** $ $ $r   r   r   s      r   quote_fragment_partr      s      BE:d#3#344;;FCCww@@@@@AAA77 $ $"$ $ $ % % %r   c                     |rOt          dt          |                                         d          }d                    d |D                       S d                    d | D                       S )zQuote special characters in either the username or password
    section of the URL. Note that userinfo in URLs is considered
    deprecated in many circles (especially browsers), and support for
    percent-encoded userinfo can be spotty.
    r   r`   r   c                 (    g | ]}t           |         S r_   )_USERINFO_PART_QUOTE_MAPr   s     r   r   z'quote_userinfo_part.<locals>.<listcomp>  s    EEE03EEEr   c                 >    g | ]}|t           v rt          |         n|S r_   )_USERINFO_DELIMSr   r   s     r   r   z'quote_userinfo_part.<locals>.<listcomp>  s?     + + + ! 458H3H3H,Q//+ + +r   r   r   s      r   quote_userinfo_partr     s      GE:d#3#344;;FCCwwEEWEEEFFF77 + +%)+ + + , , ,r   utf-8replacec                 x   d| vr	| j          | S |d}|d}t                               |           }|d         g}|j        }t          dt	          |          d          D ]H} |t          ||                                       ||                      |||dz                       Id                    |          S )	a  Percent-decode a string, by replacing %xx escapes with their
    single-character equivalent. The optional *encoding* and *errors*
    parameters specify how to decode percent-encoded sequences into
    Unicode characters, as accepted by the :meth:`bytes.decode()` method.  By
    default, percent-encoded sequences are decoded with UTF-8, and
    invalid sequences are replaced by a placeholder character.

    >>> unquote(u'abc%20def')
    u'abc def'
    r   Nr   r   r   rq      r   )split	_ASCII_RErr   r   lenunquote_to_bytesdecoder   )r   rb   errorsbitsresrr   r   s          r   unquoter     s     &~??6""D7)CZF1c$ii##  Q((//&AABBBtAE{773<<r   c                    | s	| j          dS t          | t                    r | j        d          }  | j         d          }t	          |          dk    r| S |d         g}|j        }|dd         D ]Z}	  |t          |dd                              ||dd                    5# t          $ r  |d            ||           Y Ww xY wd                    |          S )z,unquote_to_bytes('abc%20def') -> b'abc def'.r   r      %rq   r   Nr   )	r   rl   rc   r
   r   rr   _HEX_CHAR_MAPKeyErrorr   )r   r   r   rr   items        r   r   r   0  s     s&# (w''6<D
4yyA~~7)CZFQRR  	F=bqb*+++F48 	 	 	F4LLLF4LLLLL	 88C==s   31B%% CCc                 :   |                                  } |1	 t          |          }n # t          $ r t          d|          w xY w|du r|t          | <   nD|du r/|t          d|z            t                              |            n|t          d          dS )a  Registers new scheme information, resulting in correct port and
    slash behavior from the URL object. There are dozens of standard
    schemes preregistered, so this function is mostly meant for
    proprietary internal customizations or stopgaps on missing
    standards information. If a scheme seems to be missing, please
    `file an issue`_!

    Args:
        text (str): Text representing the scheme.
           (the 'http' in 'http://hatnote.com')
        uses_netloc (bool): Does the scheme support specifying a
           network host? For instance, "http" does, "mailto" does not.
        default_port (int): The default port, if any, for netloc-using
           schemes.

    .. _file an issue: https://github.com/mahmoud/boltons/issues
    Nz+default_port expected integer or None, not TFz>unexpected default port while specifying non-netloc scheme: %rz)uses_netloc expected True, False, or None)lowerr   
ValueErrorSCHEME_PORT_MAPNO_NETLOC_SCHEMESadd)rz   uses_netlocdefault_ports      r   register_schemer   K  s    $ ::<<D	0|,,LL 	0 	0 	0* ,/ 0 0 0	0 d ,			# 68DE F F Fd####		 DEEE
Fs	   ( Ac                     g }| D ]V}|dk    r	|dk    r2|r/t          |          dk    s|d         r|                                 A|                    |           Wt          | dd                   dgdgfv r|                    d           |S )zNormalize the URL path by resolving segments of '.' and '..',
    resulting in a dot-free path.  See RFC 3986 section 5.2.4, Remove
    Dot Segments.
    .z..rq   r   rk   Nr   )r   r3   rr   list)
path_partsro   parts      r   resolve_path_partsr   r  s     C  3;;T\\ C1A			JJtJrssO#//

2Jr   c                   &    e Zd ZdZd ZddZd ZdS )cachedpropertya  The ``cachedproperty`` is used similar to :class:`property`, except
    that the wrapped method is only called once. This is commonly used
    to implement lazy attributes.

    After the property has been accessed, the value is stored on the
    instance itself, using the same name as the cachedproperty. This
    allows the cache to be cleared with :func:`delattr`, or through
    manipulating the object's ``__dict__``.
    c                 >    t          |d          | _        || _        d S )Nr^   )getattrr^   func)selfr   s     r   __init__zcachedproperty.__init__  s    tY//			r   Nc                 `    || S |                      |          x}|j        | j         j        <   |S N)r   __dict__r[   )r   rf   objtypevalues       r   __get__zcachedproperty.__get__  s1    ;K3799S>>ATY/0r   c                 6    | j         j        }d| d| j         dS )N<z func=>)	__class__r[   r   r   cns     r   __repr__zcachedproperty.__repr__  s'    ^$)2))TY))))r   r   )r[   r\   r]   r^   r   r   r   r_   r   r   r   r     sP              * * * * *r   r   c                       e Zd ZdZdZddZe	 	 dd            Zed             Z	e	Z
ed	             Zej        d
             Zed             Zed             ZddZd ZddZddZd Zd Zd Zd Zd ZdS )rx   a}  The URL is one of the most ubiquitous data structures in the
    virtual and physical landscape. From blogs to billboards, URLs are
    so common, that it's easy to overlook their complexity and
    power.

    There are 8 parts of a URL, each with its own semantics and
    special characters:

      * :attr:`~URL.scheme`
      * :attr:`~URL.username`
      * :attr:`~URL.password`
      * :attr:`~URL.host`
      * :attr:`~URL.port`
      * :attr:`~URL.path`
      * :attr:`~URL.query_params` (query string parameters)
      * :attr:`~URL.fragment`

    Each is exposed as an attribute on the URL object. RFC 3986 offers
    this brief structural summary of the main URL components::

        foo://user:pass@example.com:8042/over/there?name=ferret#nose
        \_/   \_______/ \_________/ \__/\_________/ \_________/ \__/
         |        |          |        |      |           |        |
       scheme  userinfo     host     port   path       query   fragment

    And here's how that example can be manipulated with the URL type:

    >>> url = URL('foo://example.com:8042/over/there?name=ferret#nose')
    >>> print(url.host)
    example.com
    >>> print(url.get_authority())
    example.com:8042
    >>> print(url.qp['name'])  # qp is a synonym for query_params
    ferret

    URL's approach to encoding is that inputs are decoded as much as
    possible, and data remains in this decoded state until re-encoded
    using the :meth:`~URL.to_text()` method. In this way, it's similar
    to Python's current approach of encouraging immediate decoding of
    bytes to text.

    Note that URL instances are mutable objects. If an immutable
    representation of the URL is desired, the string from
    :meth:`~URL.to_text()` may be used. For an immutable, but
    almost-as-featureful, URL object, check out the `hyperlink
    package`_.

    .. _hyperlink package: https://github.com/mahmoud/hyperlink

    )
ry   r   usernamepasswordfamilyhostportpathquery_paramsfragmentr   c                 F   t           }|rt          |t                    r|                                }n^t          |t                    rI	 |                    t                    }n-# t          $ r }t          dt          d|d          d }~ww xY wt          |          }d}|d         p|| _
        |d         p|| _        d|d         p|v rt          |d                   n	|d         p|| _        d|d	         p|v rt          |d	                   n	|d	         p|| _        |d
         | _        |d         s|| _        n^	 |d                             d          | _        | j                            d          | _        n# t$          $ r |d         | _        Y nw xY w|d         | _        t)          d |d         p|                    d          D                       | _        |d         p|| _        d|d         p|v rt          |d                   n	|d         p|| _        d S )Nzexpected text or zI-encoded bytes. try decoding the url bytes and passing the result. (got: )r   ry   _netloc_sepr   r   r   r   r   r   idnar   c                 8    g | ]}d |v rt          |          n|S r   r   r   ps     r   r   z URL.__init__.<locals>.<listcomp>   s<     !C !C !C1saxxQ !C !C !Cr   r   /queryr   )DEFAULT_PARSED_URLrl   rx   to_textbytesr   re   rd   rZ   	parse_urlry   r   r   r   r   r   r   r
   UnicodeEncodeErrorr   tupler   r   _queryr   )r   urludude_es        r   r   zURL.__init__  s      	 #s## 	CkkmmC'' CC**%566CC) C C C'- ,<+;+;SSS)B C C CC
 3Bl(bm,2BzN$8b99 !J000?A*~?SQS 	  BzN$8b99 !J000?A*~?SQS 	l&z 	5DII5vJ--g66	 !I,,V44		 & ' ' 'vJ			'
 vJ	 !C !C%'Z%52$<$<S$A$A!C !C !C D Dk'RBzN$8b99 !J000?A*~?SQS 	 	s*   
A% %
B/B

B? E? ?FFNr_   c	                      |             }	||	_         ||	_        t          |          pd|	_        |	j                            |           ||	_        ||	_        ||	_        ||	_	        |	S )a(  Build a new URL from parts. Note that the respective arguments are
        not in the order they would appear in a URL:

        Args:
           scheme (str): The scheme of a URL, e.g., 'http'
           host (str): The host string, e.g., 'hatnote.com'
           path_parts (tuple): The individual text segments of the
             path, e.g., ('post', '123')
           query_params (dict): An OMD, dict, or list of (key, value)
             pairs representing the keys and values of the URL's query
             parameters.
           fragment (str): The fragment of the URL, e.g., 'anchor1'
           port (int): The integer port of URL, automatic defaults are
             available for registered schemes.
           username (str): The username for the userinfo part of the URL.
           password (str): The password for the userinfo part of the URL.

        Note that this method does relatively little
        validation. :meth:`URL.to_text()` should be used to check if
        any errors are produced while composing the final textual URL.
        r   )
ry   r   r   r   r   updater   r   r   r   )
clsry   r   r   r   r   r   r   r   ro   s
             r   
from_partszURL.from_parts  si    0 cee
z**3e---
r   c                 @    t                               | j                  S )a?  The parsed form of the query string of the URL, represented as a
        :class:`~dictutils.OrderedMultiDict`. Also available as the
        handy alias ``qp``.

        >>> url = URL('http://boltons.readthedocs.io/?utm_source=doctest&python=great')
        >>> url.qp.keys()
        [u'utm_source', u'python']
        )QueryParamDict	from_textr   r   s    r   r   zURL.query_params-  s     ''444r   c                 J    d                     d | j        D                       S )zThe URL's path, in text form.r   c                 0    g | ]}t          |d           S )Fr   r   r   s     r   r   zURL.path.<locals>.<listcomp>>  s5     4 4 4 )u=== 4 4 4r   )r   r   r  s    r   r   zURL.path;  s8     xx 4 4#'?4 4 4 5 5 	5r   c                     t          d t          |                              d          D                       | _        d S )Nc                 8    g | ]}d |v rt          |          n|S r   r   r   s     r   r   zURL.path.<locals>.<listcomp>C  s@     !L !L !L%& 03axxQ !L !L !Lr   r   )r   rg   r   r   )r   	path_texts     r   r   zURL.pathA  sQ     !L !L*4Y*?*?*E*Ec*J*J!L !L !L M Mr   c                     | j         }| j        t          v rdS | j        t          v rdS | j                            d          d         t          v rdS |S )a1  Whether or not a URL uses :code:`:` or :code:`://` to separate the
        scheme from the rest of the URL depends on the scheme's own
        standard definition. There is no way to infer this behavior
        from other parts of the URL. A scheme either supports network
        locations or it does not.

        The URL type's approach to this is to check for explicitly
        registered schemes, with common schemes like HTTP
        preregistered. This is the same approach taken by
        :mod:`urlparse`.

        URL adds two additional heuristics if the scheme as a whole is
        not registered. First, it attempts to check the subpart of the
        scheme after the last ``+`` character. This adds intuitive
        behavior for schemes like ``git+ssh``. Second, if a URL with
        an unrecognized scheme is loaded, it will maintain the
        separator it sees.

        >>> print(URL('fakescheme://test.com').to_text())
        fakescheme://test.com
        >>> print(URL('mockscheme:hello:world').to_text())
        mockscheme:hello:world

        TF+rk   )r   ry   r   r   r   )r   defaults     r   r   zURL.uses_netlocG  s[    4 ";/))4;+++5;S!!"%884r   c                     	 t           | j                 S # t          $ r; t                               | j                            d          d                   cY S w xY w)ac  Return the default port for the currently-set scheme. Returns
        ``None`` if the scheme is unrecognized. See
        :func:`register_scheme` above. If :attr:`~URL.port` matches
        this value, no port is emitted in the output of
        :meth:`~URL.to_text()`.

        Applies the same '+' heuristic detailed in :meth:`URL.uses_netloc`.
        r  rk   )r   ry   r   getr   r  s    r   r   zURL.default_portj  sc    	C"4;// 	C 	C 	C"&&t{'8'8'='=b'ABBBBB	Cs    AAATc                     t          | j                  | _        |r<| j                                        | _        | j                                        | _        dS )aR  Resolve any "." and ".." references in the path, as well as
        normalize scheme and host casing. To turn off case
        normalization, pass ``with_case=False``.

        More information can be found in `Section 6.2.2 of RFC 3986`_.

        .. _Section 6.2.2 of RFC 3986: https://tools.ietf.org/html/rfc3986#section-6.2.2
        N)r   r   ry   r   r   )r   	with_cases     r   r   zURL.normalizey  sJ     -T_== 	*+++--DK	))DIr   c           
         d}t          |t                    st          |          |}}|j        r|j        r|t          |          n|S |j        }|j        ra|j                            d          rt          |j                  }nOt          | j        dd                   t          |j                  z   }nt          | j                  }|s| j        }| 	                    |j        p| j        |j        p| j        |j
        p| j
        |||j        |j        p| j        |j        p| j                  }|                                 |S )az  Factory method that returns a _new_ :class:`URL` based on a given
        destination, *dest*. Useful for navigating those relative
        links with ease.

        The newly created :class:`URL` is normalized before being returned.

        >>> url = URL('http://boltons.readthedocs.io')
        >>> url.navigate('en/latest/')
        URL(u'http://boltons.readthedocs.io/en/latest/')

        Args:
           dest (str): A string or URL object representing the destination

        More information can be found in `Section 5 of RFC 3986`_.

        .. _Section 5 of RFC 3986: https://tools.ietf.org/html/rfc3986#section-5
        Nr   rk   )ry   r   r   r   r   r   r   r   )rl   rx   ry   r   r   r   
startswithr   r   r	  r   r   r   r   r   )r   dest	orig_destr   new_path_partsro   s         r   navigatezURL.navigate  sP   $ 	$$$ 	.!$ii)D; 	<49 	< !* 13t999t;(9 		1y##C(( 7!%do!6!6!%docrc&:!;!;!%do!6!6"7 "$/22N 1#0ooT[%?DK#'9#9	#'9#9	)7+7'+}'+}'E'+}'E  G G 	
r   Fc                    g }|j         }| j        rY|rW |t          | j                             | j        r( |d            |t          | j                              |d           | j        r| j        t          j        k    r' |d            || j                    |d           nI|r7 || j                            d          	                    d                     n || j                   | j
        r8| j
        | j        k    r( |d            |t          | j
                             d                    |          S )a  Used by URL schemes that have a network location,
        :meth:`~URL.get_authority` combines :attr:`username`,
        :attr:`password`, :attr:`host`, and :attr:`port` into one
        string, the *authority*, that is used for
        connecting to a network-accessible resource.

        Used internally by :meth:`~URL.to_text()` and can be useful
        for labeling connections.

        >>> url = URL('ftp://user@ftp.debian.org:2121/debian/README')
        >>> print(url.get_authority())
        ftp.debian.org:2121
        >>> print(url.get_authority(with_userinfo=True))
        user@ftp.debian.org:2121

        Args:
           full_quote (bool): Whether or not to apply IDNA encoding.
              Defaults to ``False``.
           with_userinfo (bool): Whether or not to include username
              and password, technically part of the
              authority. Defaults to ``False``.

        :@[]r   r   r   )rr   r   r   r   r   r   socketAF_INET6r
   r   r   r   rc   r   )r   r   with_userinfopartsrn   s        r   get_authorityzURL.get_authority  sU   0 |= 	] 	D$T]33444} 9S			(77888DIII9 	%{fo--S			TYS				  TY%%f--44W==>>>>TYy %TY$*;;;S			S^^$$$wwu~~r   c                    | j         }d                    fd| j        D                       }|                     d          }| j                                      }t          | j                  }g }|j        }|r ||            |d           |r |d            ||           n"|r |dd	         dk    r| j	        r |d           |r(|r|r|dd
         dk    r |d            ||           |r |d            ||           |r |d            ||           d                    |          S )a~  Render a string representing the current state of the URL
        object.

        >>> url = URL('http://listen.hatnote.com')
        >>> url.fragment = 'en'
        >>> print(url.to_text())
        http://listen.hatnote.com#en

        By setting the *full_quote* flag, the URL can either be fully
        quoted or minimally quoted. The most common characteristic of
        an encoded-URL is the presence of percent-encoded text (e.g.,
        %60).  Unquoted URLs are more readable and suitable
        for display, whereas fully-quoted URLs are more conservative
        and generally necessary for sending over the network.
        r   c                 2    g | ]}t          |           S )r  r  )r   r   r   s     r   r   zURL.to_text.<locals>.<listcomp>  s6     4 4 4 )zBBB 4 4 4r   T)r   r)  r  r#  z//Nr   rq   ?#r   )
ry   r   r   r+  r   r   r   r   rr   r   )	r   r   ry   r   	authorityquery_stringr   r*  rn   s	    `       r   r   zURL.to_text  s     xx 4 4 4 4#'?4 4 4 5 5&&*59 ' ; ;	(00J0GG&t}LLL| 	DLLLDIII 	DJJJDOOOO 	bqbT))d.>)DJJJ 	 ) RaRCS			 DJJJ 	DIIID 	DIIIDNNNwwu~~r   c                 N    | j         j        }| d|                                 dS )N(r   )r   r[   r   r   s     r   r   zURL.__repr__  s+    ^$**t||~~****r   c                 *    |                                  S r   r   r  s    r   __str__zURL.__str__      ||~~r   c                 *    |                                  S r   r5  r  s    r   __unicode__zURL.__unicode__   r7  r   c                 f    | j         D ](}t          | |          t          ||d           k    s dS )dS )NFT)
_cmp_attrsr   )r   otherattrs      r   __eq__z
URL.__eq__#  sF    O 	 	D4&&'%t*D*DDDuu Etr   c                     | |k     S r   r_   r   r<  s     r   __ne__z
URL.__ne__)  s    5=  r   r  )NNr_   r_   r   NNNT)FFF)r[   r\   r]   r^   r;  r   classmethodr	  r   r   qppropertyr   setterr   r   r   r!  r+  r   r   r6  r9  r>  rA  r_   r   r   rx   rx     s       1 1hPJ, , , ,\ LNCG" " " ["H 	5 	5 ^	5 
B5 5 X5
 
[  [
     X D C C XC    / / /b- - - -^. . . .`+ + +      ! ! ! ! !r   rx   )	inet_ptonc                   n    e Zd Zdej        fdej        fdej        dz  fdej        dz  fdej        fgZdS )		_sockaddr	sa_family__pad1	ipv4_addr   	ipv6_addrr   __pad2N)	r[   r\   r]   ctypesc_shortc_ushortc_bytec_ulong_fields_r_   r   r   rJ  rJ  3  sQ         &.1v/ &-!"34 &-""45v~.	0r   rJ  c           	         t                      }|                    d          }| |_        t          j        t          j        |                    }t          || d t          j        |          t          j        |                    dk    r t          t          j	                              | t          j        k    rt          j        |j        d          S | t          j        k    rt          j        |j        d          S t          d          )Nr   r   rN  r   zunknown address family)rJ  r
   rK  rQ  c_intsizeofWSAStringToAddressAbyrefOSErrorFormatErrorr'  AF_INET	string_atrM  r(  rO  )address_family	ip_stringaddr	addr_sizes       r   rH  rH  =  s    {{$$W--	'Lt!4!455	y.$T@R@RTZT`ajTkTkllpqqq&,..///V^++#DNA666V_,,#DNB777.///r   c                    | sdS d| v rd| d         k    rtd| d         k    rh| dd         } 	 t          t          j        |            t          j        }|| fS # t          $ r}t	          d| d	|d
          d}~wt
          $ r Y nw xY w	 t          t          j        |            t          j        }n# t          t
          f$ r d}Y nw xY w|| fS )a      Low-level function used to parse the host portion of a URL.

    Returns a tuple of (family, host) where *family* is a
    :mod:`socket` module constant or ``None``, and host is a string.

    >>> parse_host('googlewebsite.com') == (None, 'googlewebsite.com')
    True
    >>> parse_host('[::1]') == (socket.AF_INET6, '::1')
    True
    >>> parse_host('192.168.1.1') == (socket.AF_INET, '192.168.1.1')
    True

    Odd doctest formatting above due to py3's switch from int to enums
    for :mod:`socket` constants.

    )Nr   r#  r%  r   r&  rk   rq   zinvalid IPv6 host: z (r   N)rH  r'  r(  r\  rZ   r   r^  )r   r   ses      r   
parse_hostrf  M  s    $  x
d{{sd1g~~#b//AbDz	 fot,,, _F4<  	I 	I 	I Gd G G G G GHHH! 	 	 	D	
 &.$'''  '(    4<s/   A 
B A66BB
B1 1CCc                    t          |           } t                              |           }	 |                                }n # t          $ r t          d| z            w xY w|d         }dd|}}}|r4|                    d          \  }}}|r|                    d          \  }}	}d\  }
}|r|                    d          \  }
}}|r|
rL|
d         dk    r@d	|v r<|                    d	          \  }}	}|
dz   |z   d	z   }
|r|d         dk    r
|d
d         }	 t          |          }n&# t          $ r |rt          d|z            d}Y nw xY wt          |
          \  }}
||d<   ||d<   ||d<   |
|d<   ||d<   |S )a+      Used to parse the text for a single URL into a dictionary, used
    internally by the :class:`URL` type.

    Note that "URL" has a very narrow, standards-based
    definition. While :func:`parse_url` may raise
    :class:`URLParseError` under a very limited number of conditions,
    such as non-integer port, a surprising number of strings are
    technically valid URLs. For instance, the text ``"url"`` is a
    valid URL, because it is a relative path.

    In short, do not expect this function to validate form inputs or
    other more colloquial usages of URLs.

    >>> res = parse_url('http://127.0.0.1:3000/?a=1')
    >>> sorted(res.keys())  # res is a basic dictionary
    ['_netloc_sep', 'authority', 'family', 'fragment', 'host', 'password', 'path', 'port', 'query', 'scheme', 'username']
    zcould not parse url: %rr0  Nr$  r#  NNr   r%  r&  rq   z!expected integer for port, not %rr   r   r   r   r   )rc   _URL_REr   	groupdictAttributeErrorrZ   
rpartition	partitionr   r   rf  )url_textumgsau_textuserpwhostinfouserinfosep_r   r   port_str
host_rightr   s                  r   r   r   u  s   & 8}}H	x	 	 BB\\^^ B B B5@AAAB oGtWh"D 2")"4"4S"9"9#x 	2",,S11KD!RJD$ &0055c8 	 ,Q33(??*2*<*<S*A*A'
AxczJ.4 ,s 2 2'|H8}}    4'(K*2)3 4 4 4	 d##LFDBzNBzNBxLBvJBvJIs   A   AD% % EEr   c                 X   d |                      d          D             }g }|D ]}|s|                    d          \  }}}|s|rd}n&t          |                    dd                    }|r#t          |                    dd                    }|                    ||f           |S )zD
    Converts a query string into a list of (key, value) pairs.
    c                 B    g | ]}|                     d           D ]}|S );)r   )r   s1s2s      r   r   zparse_qsl.<locals>.<listcomp>  s/    @@@B"((3--@@BR@@@@r   &=Nr   )r   rm  r   r   rr   )	qskeep_blank_valuesrb   pairsro   pairkeyrw  r   s	            r   	parse_qslr    s     A@"((3--@@@E
C ! ! 	s++Q 	  ckk#s++,, 	5EMM#s3344E

C<    Jr   )KeysView
ValuesView	ItemsView)zip_longestrq   )make_sentinel_MISSING)var_name   c                       e Zd ZdZ fdZ fdZd Zd Zd Zd Z	 fdZ
 fd	Zd0 fd	Zef fd	Z fdZef fd	Zd Zed0d            Zd Zd Z fdZ fdZ fdZd Zd Zd ZefdZef fd	Zeef fd	Zd Zd Z d1dZ!d1d Z"d1d!Z#d1d"Z$d2d#Z%d2 fd$	Z&d% Z' fd&Z(d1d'Z)d1d(Z*d1d)Z+d* Z, fd+Z-d, Z.d- Z/d. Z0d/ Z1 xZ2S )3OrderedMultiDicta	  A MultiDict is a dictionary that can have multiple values per key
    and the OrderedMultiDict (OMD) is a MultiDict that retains
    original insertion order. Common use cases include:

      * handling query strings parsed from URLs
      * inverting a dictionary to create a reverse index (values to keys)
      * stacking data from multiple dictionaries in a non-destructive way

    The OrderedMultiDict constructor is identical to the built-in
    :class:`dict`, and overall the API constitutes an intuitive
    superset of the built-in type:

    >>> omd = OrderedMultiDict()
    >>> omd['a'] = 1
    >>> omd['b'] = 2
    >>> omd.add('a', 3)
    >>> omd.get('a')
    3
    >>> omd.getlist('a')
    [1, 3]

    Some non-:class:`dict`-like behaviors also make an appearance,
    such as support for :func:`reversed`:

    >>> list(reversed(omd))
    ['b', 'a']

    Note that unlike some other MultiDicts, this OMD gives precedence
    to the most recent value added. ``omd['a']`` refers to ``3``, not
    ``1``.

    >>> omd
    OrderedMultiDict([('a', 1), ('b', 2), ('a', 3)])
    >>> omd.poplast('a')
    3
    >>> omd
    OrderedMultiDict([('a', 1), ('b', 2)])
    >>> omd.pop('a')
    1
    >>> omd
    OrderedMultiDict([('b', 2)])

    If you want a safe-to-modify or flat dictionary, use
    :meth:`OrderedMultiDict.todict()`.

    >>> from pprint import pprint as pp  # preserve printed ordering
    >>> omd = OrderedMultiDict([('a', 1), ('b', 2), ('a', 3)])
    >>> pp(omd.todict())
    {'a': 3, 'b': 2}
    >>> pp(omd.todict(multi=True))
    {'a': [1, 3], 'b': [2]}

    With ``multi=False``, items appear with the keys in to original
    insertion order, alongside the most-recently inserted value for
    that key.

    >>> OrderedMultiDict([('a', 1), ('b', 2), ('a', 3)]).items(multi=False)
    [('a', 3), ('b', 2)]

    .. warning::

       ``dict(omd)`` changed behavior `in Python 3.7
       <https://bugs.python.org/issue34320>`_ due to changes made to
       support the transition from :class:`collections.OrderedDict` to
       the built-in dictionary being ordered. Before 3.7, the result
       would be a new dictionary, with values that were lists, similar
       to ``omd.todict(multi=True)`` (but only shallow-copy; the lists
       were direct references to OMD internal structures). From 3.7
       onward, the values became singular, like
       ``omd.todict(multi=False)``. For reliable cross-version
       behavior, just use :meth:`~OrderedMultiDict.todict()`.

    c                 r    t                                          |           }|                                 |S r   )super__new__	_clear_ll)r  r   kwro   r   s       r   r  zOrderedMultiDict.__new__*  s*    ggooc""
r   c                 0   t          |          dk    r+t          | j        j        dt          |                    t	                                                       |r|                     |d                    |r|                     |           d S d S )Nrq   z" expected at most 1 argument, got r   )r   	TypeErrorr   r[   r  r   update_extendr  )r   argskwargsr   s      r   r   zOrderedMultiDict.__init__/  s    t99q==#~666D			C D D D 	(tAw''' 	 KK	  	 r   c                 H    t          |                     d                    S )NTmultir   	iteritemsr  s    r   __getstate__zOrderedMultiDict.__getstate__:  s    DNNN..///r   c                 X    |                                   |                     |           d S r   )clearr  )r   states     r   __setstate__zOrderedMultiDict.__setstate__=  s)    

5!!!!!r   c                     	 | j         }n # t          $ r i x}| _         g | _        Y nw xY w|                                 | j        | j        d g| j        d d <   d S r   )_maprk  rootr  )r   r  s     r   r  zOrderedMultiDict._clear_llA  so    	9DD 	 	 	!!D49DIII	 	

	49d3	!!!s   
 ''c                     | j         }| j                            |g           }|t                   }||||g}|x|t          <   |t          <   |                    |           d S r   )r  r  
setdefaultPREVNEXTrr   )r   kr   r  cellslastcells          r   _insertzOrderedMultiDict._insertJ  sa    y	$$Q++DzdAq!"&&T
T$ZTr   c                     t                                          |g           }|                     ||           |                    |           dS )zaAdd a single value *v* under a key *k*. Existing values under *k*
        are preserved.
        N)r  r  r  rr   )r   r  r   valuesr   s       r   r   zOrderedMultiDict.addR  sJ     ##Ar**Qar   c                     |sdS | j         }t                                          |g           }|D ]} |||           |                    |           dS )a  Add an iterable of values underneath a specific key, preserving
        any values already under that key.

        >>> omd = OrderedMultiDict([('a', -1)])
        >>> omd.addlist('a', range(3))
        >>> omd
        OrderedMultiDict([('a', -1), ('a', 0), ('a', 1), ('a', 2)])

        Called ``addlist`` for consistency with :meth:`getlist`, but
        tuples and other sequences and iterables work.
        N)r  r  r  extend)r   r  r   self_insertr  subvr   s         r   addlistzOrderedMultiDict.addlistZ  sn      	Fl##Ar** 	! 	!DK4    ar   Nc                 V    t                                          ||g          d         S )a  Return the value for key *k* if present in the dictionary, else
        *default*. If *default* is not given, ``None`` is returned.
        This method never raises a :exc:`KeyError`.

        To get all values under a key, use :meth:`OrderedMultiDict.getlist`.
        rk   )r  r  r   r  r  r   s      r   r  zOrderedMultiDict.getn  s$     ww{{1wi((,,r   c                     	 t                                          |          dd         S # t          $ r |t          u rg cY S |cY S w xY w)zGet all values for key *k* as a list, if *k* is in the
        dictionary, else *default*. The list returned is a copy and
        can be safely mutated. If *default* is not given, an empty
        :class:`list` is returned.
        N)r  __getitem__r   r  r  s      r   getlistzOrderedMultiDict.getlistw  sa    	77&&q))!!!,, 	 	 	(""			NNN	s   (, AAAc                 p    t                                                       |                                  dS )zEmpty the dictionary.N)r  r  r  )r   r   s    r   r  zOrderedMultiDict.clear  s*    r   c                 v    t                                          |          s|t          u rdn|| |<   | |         S )zIf key *k* is in the dictionary, return its value. If not, insert
        *k* with a value of *default* and return *default*. *default*
        defaults to ``None``. See :meth:`dict.setdefault` for more
        information.
        N)r  __contains__r  r  s      r   r  zOrderedMultiDict.setdefault  s?     ww##A&& 	?%11ddwDGAwr   c                 T    |                      |                     d                    S )z(Return a shallow copy of the dictionary.Tr  r   r  r  s    r   copyzOrderedMultiDict.copy  s"    ~~dnn4n88999r   c                 2     | fd|D                       S )zCreate a dictionary from a list of keys, with all the values
        set to *default*, or ``None`` if *default* is not set.
        c                     g | ]}|fS r_   r_   )r   r  r  s     r   r   z-OrderedMultiDict.fromkeys.<locals>.<listcomp>  s    ///QQL///r   r_   )r  keysr  s     `r   fromkeyszOrderedMultiDict.fromkeys  s*    
 s////$///000r   c                    || u rdS | j         }t          |t                    r5|D ]	}|| v r| |= 
|                    d          D ]\  }} |||           nt	          t          |dd                    r#|                                D ]}||         | |<   n?t                      }|j         }|D ]'\  }}||vr|| v r| |=  ||            |||           (|D ]}||         | |<   dS )zAdd items from a dictionary or iterable (and/or keyword arguments),
        overwriting values under an existing key. See
        :meth:`dict.update` for more details.
        NTr  r  )r   rl   r  r  callabler   r  set)r   EFself_addr  r   seenseen_adds           r   r  zOrderedMultiDict.update  sH    99F8a)** 	    99Q$//  1Aga..// 
	VVXX  A$Q 55DxH  1D==Q$YYQHQKKKA 	 	AdDGGr   c                 H   | u r"t                                                    }n_t          t                    r                    d          }n3t          d          r!fd                                D             }n}| j        }|D ]\  }} |||           dS )zAdd items from a dictionary, iterable, and/or keyword
        arguments without overwriting existing items present in the
        dictionary. Like :meth:`update`, but adds to existing keys
        instead of overwriting them.
        Tr  r  c              3   ,   K   | ]}||         fV  d S r   r_   )r   r  r  s     r   	<genexpr>z1OrderedMultiDict.update_extend.<locals>.<genexpr>  s+      44aAaD	444444r   N)iteritemsrl   r  r  hasattrr  r   )r   r  r  iteratorr  r  r   s    `     r   r  zOrderedMultiDict.update_extend  s     99AGGIIHH+,, 	{{{..HHQ 	444416688444HHH8 	 	DAqHQNNNN	 	r   c                     t                                          |          r|                     |           |                     ||           t                                          ||g           d S r   )r  r  _remove_allr  __setitem__)r   r  r   r   s      r   r  zOrderedMultiDict.__setitem__  sg    77"" 	 QQAs#####r   c                 R    t                                          |          d         S rj   )r  r  r   r  r   s     r   r  zOrderedMultiDict.__getitem__  s     ww""1%%b))r   c                 t    t                                          |           |                     |           d S r   )r  __delitem__r  r  s     r   r  zOrderedMultiDict.__delitem__  s5    Ar   c                 L   | |u rdS 	 t          |          t          |           k    rdS n# t          $ r Y dS w xY wt          |t                    r|                     d          }|                    d          }t          ||d          }|D ]\  \  }}\  }}||k    s||k    r dS t          |t                    t          u rt          |t                    t          u sdS dS t          |d          r,| D ]'}	 ||         | |         k     # t          $ r Y  dS w xY wdS dS )NTFr  rh  )	fillvaluer  )
r   r  rl   r  r  r  nextr  r  r   )	r   r<  selfiotherizipped_itemsselfkselfvotherkothervs	            r   r>  zOrderedMultiDict.__eq__  s}   5==4	5zzSYY&&u ' 	 	 	55	e-.. 	NNN..E__4_00F&ufMMML4@ ! !0 0F??evoo 55 '6x((H44FH--99u4UF## 	 ! !!%LDK/// ! ! ! 555!4us    + 
99=D
DDc                     | |k     S r   r_   r@  s     r   rA  zOrderedMultiDict.__ne__  s    EM""r   c                 0    |                      |           | S r   )r  r@  s     r   __ior__zOrderedMultiDict.__ior__  s    Er   c                     	 |                      |          d         S # t          $ r |t          u rt          |          Y nw xY w|S )zRemove all values under key *k*, returning the most-recently
        inserted value. Raises :exc:`KeyError` if the key is not
        present and no *default* is provided.
        rk   )popallr   r  )r   r  r  s      r   r3   zOrderedMultiDict.pop   s]    
	";;q>>"%% 	" 	" 	"(""qkk! #"	" s    "AAc                     t                      }|                    |          r|                     |           |t          u r|                    |          S |                    ||          S )zRemove all values under key *k*, returning them in the form of
        a list. Raises :exc:`KeyError` if the key is not present and no
        *default* is provided.
        )r  r  r  r  r3   )r   r  r  
super_selfr   s       r   r  zOrderedMultiDict.popall  si    
 WW
""1%% 	 Qh>>!$$$~~a)))r   c                    |t           u rJ| r| j        t                   t                   }n*|t           u rt	          dt          |           z            |S 	 |                     |           n*# t          $ r |t           u rt	          |          |cY S w xY wt                                          |          }|	                                }|s!t                      
                    |           |S )aE  Remove and return the most-recently inserted value under the key
        *k*, or the most-recently inserted key if *k* is not
        provided. If no values remain under *k*, it will be removed
        from the OMD.  Raises :exc:`KeyError` if *k* is not present in
        the dictionary, or the dictionary is empty.
        zempty %r)r  r  r  KEYr   type_remover  r  r3   r  )r   r  r  r  r   r   s        r   poplastzOrderedMultiDict.poplast  s     == IdOC(h&&":T

#:;;;	LLOOOO 	 	 	(""qkk!NNN	 $$Q''JJLL 	#GG"""s   A, ,$BBc                     | j         |         }|                                }|t                   |t                   c|t                   t          <   |t                   t          <   |s
| j         |= d S d S r   r  r3   r  r  r   r  r  r  s       r   r  zOrderedMultiDict._remove2  s_    1zz||-1$Zd*T
4$t*T* 		!	 	r   c                     | j         |         }|rW|                                }|t                   |t                   c|t                   t          <   |t                   t          <   |W| j         |= d S r   r  r  s       r   r  zOrderedMultiDict._remove_all9  sc    1 	H::<<D15dT$Z.DJtd4j.  	H IaLLLr   Fc              #      K   | j         }|t                   }|r5||ur/|t                   |t                   fV  |t                   }||u-dS dS |                                 D ]}|| |         fV  dS )zIterate over the OMD's items in insertion order. By default,
        yields only the most-recently inserted value for each key. Set
        *multi* to ``True`` to get all inserted items.
        N)r  r  r  VALUEiterkeys)r   r  r  currr  s        r   r  zOrderedMultiDict.iteritems@  s      
 yDz 	%d""3ie,,,,Dz d"""""" }} % %49n$$$$% %r   c              #     K   | j         }|t                   }|r(||ur"|t                   V  |t                   }||u dS dS t                      }|j        }||ur3|t                   }||vr ||           |V  |t                   }||u1dS dS )zIterate over the OMD's keys in insertion order. By default, yields
        each key once, according to the most recent insertion. Set
        *multi* to ``True`` to get all keys, including duplicates, in
        insertion order.
        N)r  r  r  r  r   )r   r  r  r  yieldedyielded_addr  s          r   r  zOrderedMultiDict.iterkeysO  s       yDz 	"d""3iDz d"""""" eeG!+Kd""IG##KNNNGGGDz d""""""r   c              #   J   K   |                      |          D ]	\  }}|V  
dS )zIterate over the OMD's values in insertion order. By default,
        yields the most-recently inserted value per unique key.  Set
        *multi* to ``True`` to get all values according to insertion
        order.
        r  N)r  )r   r  r  r   s       r   
itervalueszOrderedMultiDict.itervaluese  s>       NNN// 	 	DAqGGGG	 	r   c                 @     |r fd D             S  fd D             S )ap  Gets a basic :class:`dict` of the items in this dictionary. Keys
        are the same as the OMD, values are the most recently inserted
        values for each key.

        Setting the *multi* arg to ``True`` is yields the same
        result as calling :class:`dict` on the OMD, except that all the
        value lists are copies that can be safely mutated.
        c                 <    i | ]}|                     |          S r_   )r  r   r  r   s     r   r   z+OrderedMultiDict.todict.<locals>.<dictcomp>x  s%    5551At||A555r   c                 "    i | ]}||         S r_   r_   r  s     r   r   z+OrderedMultiDict.todict.<locals>.<dictcomp>y  s    )))q47)))r   r_   r   r  s   ` r   todictzOrderedMultiDict.todictn  sA      	655555555))))D))))r   c                 n    | j         } |t          |                     d          ||                    S )a  Similar to the built-in :func:`sorted`, except this method returns
        a new :class:`OrderedMultiDict` sorted by the provided key
        function, optionally reversed.

        Args:
            key (callable): A callable to determine the sort key of
              each element. The callable should expect an **item**
              (key-value pair tuple).
            reverse (bool): Set to ``True`` to reverse the ordering.

        >>> omd = OrderedMultiDict(zip(range(3), range(3)))
        >>> omd.sorted(reverse=True)
        OrderedMultiDict([(2, 2), (1, 1), (0, 0)])

        Note that the key function receives an **item** (key-value
        tuple), so the recommended signature looks like:

        >>> omd = OrderedMultiDict(zip('hello', 'world'))
        >>> omd.sorted(key=lambda i: i[1])  # i[0] is the key, i[1] is the val
        OrderedMultiDict([('o', 'd'), ('l', 'l'), ('e', 'o'), ('l', 'r'), ('h', 'w')])
        Tr  r  reverse)r   sortedr  )r   r  r	  r  s       r   r
  zOrderedMultiDict.sorted{  s8    , ns6$..t.44#wOOOPPPr   c                    	 t                                                      }n0# t          $ r# t                                                      }Y nw xY wfd|D             }|                                 }|                     d          D ]0}|                    |||                                                    1|S )aH  Returns a copy of the :class:`OrderedMultiDict` with the same keys
        in the same order as the original OMD, but the values within
        each keyspace have been sorted according to *key* and
        *reverse*.

        Args:
            key (callable): A single-argument callable to determine
              the sort key of each element. The callable should expect
              an **item** (key-value pair tuple).
            reverse (bool): Set to ``True`` to reverse the ordering.

        >>> omd = OrderedMultiDict()
        >>> omd.addlist('even', [6, 2])
        >>> omd.addlist('odd', [1, 5])
        >>> omd.add('even', 4)
        >>> omd.add('odd', 3)
        >>> somd = omd.sortedvalues()
        >>> somd.getlist('even')
        [2, 4, 6]
        >>> somd.keys(multi=True) == omd.keys(multi=True)
        True
        >>> omd == somd
        False
        >>> somd
        OrderedMultiDict([('even', 2), ('even', 4), ('odd', 1), ('odd', 3), ('even', 6), ('odd', 5)])

        As demonstrated above, contents and key order are
        retained. Only value order changes.
        c                 >    i | ]\  }}|t          |            S )r  )r
  )r   r  r   r  r	  s      r   r   z1OrderedMultiDict.sortedvalues.<locals>.<dictcomp>  sF     @ @ @#'1a VA3WFFF @ @ @r   Tr  )r  r  rk  r  r   r  r   r3   )r   r  r	  superself_iteritemssorted_val_mapro   r  r   s    ``    r   sortedvalueszOrderedMultiDict.sortedvalues  s    <	2"'''"3"3"5"5 	2 	2 	2"'''--//	2@ @ @ @ @+>@ @ @nnT** 	0 	0AGGA~a(,,..////
s    & *AAc                 h    |                      d |                     d          D                       S )a  Returns a new :class:`OrderedMultiDict` with values and keys
        swapped, like creating dictionary transposition or reverse
        index.  Insertion order is retained and all keys and values
        are represented in the output.

        >>> omd = OMD([(0, 2), (1, 2)])
        >>> omd.inverted().getlist(2)
        [0, 1]

        Inverting twice yields a copy of the original:

        >>> omd.inverted().inverted()
        OrderedMultiDict([(0, 2), (1, 2)])
        c              3   $   K   | ]\  }}||fV  d S r   r_   r   r  r   s      r   r  z,OrderedMultiDict.inverted.<locals>.<genexpr>  s*      LLAq!fLLLLLLr   Tr  r  r  s    r   invertedzOrderedMultiDict.inverted  s3     ~~LLd1K1KLLLLLLr   c                 n    t                      j        |                     fd| D                       S )zReturns a mapping from key to number of values inserted under that
        key. Like :py:class:`collections.Counter`, but returns a new
        :class:`OrderedMultiDict`.
        c              3   L   K   | ]}|t           |                    fV  d S r   )r   )r   r  super_getitems     r   r  z*OrderedMultiDict.counts.<locals>.<genexpr>  s:      GGQq#mmA&6&6"7"78GGGGGGr   )r  r  r   )r   r  r   s    @r   countszOrderedMultiDict.counts  s9     +~~GGGG$GGGGGGr   c                 H    t          |                     |                    S )ztReturns a list containing the output of :meth:`iterkeys`.  See
        that method's docs for more details.
        r  )r   r  r  s     r   r  zOrderedMultiDict.keys  s      DMMM..///r   c                 H    t          |                     |                    S )zvReturns a list containing the output of :meth:`itervalues`.  See
        that method's docs for more details.
        r  )r   r   r  s     r   r  zOrderedMultiDict.values  s      DOO%O00111r   c                 H    t          |                     |                    S )zuReturns a list containing the output of :meth:`iteritems`.  See
        that method's docs for more details.
        r  r  r  s     r   r  zOrderedMultiDict.items  s      DNNN//000r   c                 *    |                                  S r   )r  r  s    r   __iter__zOrderedMultiDict.__iter__  s    }}r   c              #   ,  K   | j         }|t                   }i }|j        }t                      j        }||ur\|t
                   } ||          } ||d          t          |          k    r|V  ||xx         dz  cc<   |t                   }||uZd S d S )Nrq   )r  r  r  r  r  r  r   )	r   r  r  lengths
lengths_sd
get_valuesr  valsr   s	           r   __reversed__zOrderedMultiDict.__reversed__  s      yDz'
WW(
$S	A:a==Dz!Q3t99,,AJJJ!OJJJ:D $r   c                     | j         j        }d                    d |                     d          D                       }| d| dS )Nz, c                 6    g | ]\  }}t          ||f          S r_   )reprr  s      r   r   z-OrderedMultiDict.__repr__.<locals>.<listcomp>  s&    MMM$!Qq!fMMMr   Tr  z([z]))r   r[   r   r  )r   r   kvss      r   r   zOrderedMultiDict.__repr__  sQ    ^$iiMM$..t.2L2LMMMNNr   c                      t          |           S )zBOMD.viewkeys() -> a set-like object providing a view on OMD's keys)r  r  s    r   viewkeyszOrderedMultiDict.viewkeys  s    ~~r   c                      t          |           S )z>OMD.viewvalues() -> an object providing a view on OMD's values)r  r  s    r   
viewvalueszOrderedMultiDict.viewvalues  s    $r   c                      t          |           S )zDOMD.viewitems() -> a set-like object providing a view on OMD's items)r  r  s    r   	viewitemszOrderedMultiDict.viewitems	  s    r   r   rC  )NF)3r[   r\   r]   r^   r  r   r  r  r  r  r   r  r  r  r  r  r  r  rD  r  r  r  r  r  r  r>  rA  r  r3   r  r  r  r  r  r  r   r  r
  r  r  r  r  r  r  r  r"  r   r(  r*  r,  __classcell__)r   s   @r   r  r    s       H HR    
	  	  	  	  	 0 0 0" " "4 4 4          (- - - - - - "*          
 %-      : : : 1 1 1 [1  <  &$ $ $ $ $* * * * *      :# # #   & 
 
 
 
 !) 
* 
* 
* 
* 
* 
* !(      4    % % % %" " " ",   * * * *Q Q Q Q2( ( ( ( ( (TM M M"H H H H H0 0 0 02 2 2 21 1 1 1           
             r   r  )r  c                   0    e Zd ZdZed             ZddZdS )r  ao  A subclass of :class:`~dictutils.OrderedMultiDict` specialized for
    representing query string values. Everything is fully unquoted on
    load and all parsed keys and values are strings by default.

    As the name suggests, multiple values are supported and insertion
    order is preserved.

    >>> qp = QueryParamDict.from_text(u'key=val1&key=val2&utm_source=rtd')
    >>> qp.getlist('key')
    [u'val1', u'val2']
    >>> qp['key']
    u'val2'
    >>> qp.add('key', 'val3')
    >>> qp.to_text()
    'key=val1&key=val2&utm_source=rtd&key=val3'

    See :class:`~dictutils.OrderedMultiDict` for more API features.
    c                 :    t          |d          } | |          S )zP
        Parse *query_string* and return a new :class:`QueryParamDict`.
        T)r  )r  )r  r1  r  s      r   r  zQueryParamDict.from_text,  s$    
 ,$???s5zzr   Fc                 d   g }|                      d          D ]\  }}t          t          |          |          }||                    |           ;t          t          |          |          }|                    d                    ||f                     d                    |          S )z
        Render and return a query string.

        Args:
           full_quote (bool): Whether or not to percent-quote special
              characters or leave them decoded for readability.
        Tr  r  Nr  r  )r  r   rg   rr   r   )r   r   ret_listr  r   r  vals          r   r   zQueryParamDict.to_text4  s     NNN.. 	6 	6DAq":a==ZHHHCy$$$$&z!}}LLL#s 4 45555xx!!!r   NrC  )r[   r\   r]   r^   rD  r  r   r_   r   r   r  r    sM         &   [" " " " " "r   r  )Fr    r_   rB  )r   r   rh  )Sr^   rer'  r   unicodedatar   	frozenset_UNRESERVED_CHARScompileri  r	   r   r   r   r   _GEN_DELIMS_SUB_DELIMS_ALL_DELIMS_USERINFO_SAFEr   r  
_PATH_SAFEr   _FRAGMENT_SAFEr   _QUERY_SAFEr   r   rZ   re   rg   rs   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rx   rH  ImportErrorrQ  	StructurerJ  windllws2_32rZ  WSAAddressToStringArf  r   r   r  collections.abcr  r  r  	itertoolsr  	typeutilsr  r  objectr   r  r  r  r  SPREVSNEXTr   r  	dictutilsOMDr  r_   r   r   <module>rL     s;  > , 
			   ! ! ! ! ! ! I ; < <  "* - . .F F *F F F BJ'((	
D63 
Ds 
DFD 
D% 
D4
D!&
D,14
D9A2
D2
D&
D-3S
D:?
D 3
D !&s
D -3D
D ;A#
D C	
D 
D "'	
D /5d	
D =DT	
D
 4
D
 "'
D
 .4S
D
 ;B3
D #
D  *4
D 29$
D AH
D 3
D !(
D /6t
D >DR
D #
D  &s
D 
D 46"$tbd
D 
D 
D/ / /  i	""i&&K'"[0/ ,ss4yy8
Z'"Z/##d));/ .33u::"==k)	 	 	 	 	J 	 	 	  3 3 3 2:  t  u  u I I I IX
 
 
 +?>:: &z22 '44 %on55 % % % %% % % %% % % %
, 
, 
, 
,   6  6$ $ $ $N  .* * * * * * * *2H! H! H! H! H! H! H! H!V0        0 0 0MMM0 0 0 0 0F$ 0 0 0 !-.B -.B0 0 0 0 00<% % %P= = =@ Yr]]  %)3C    ,
 < ; ; ; ; ; ; ; ; ; ! ! ! ! ! !((((((}j111HH   vxxHHH (-uQxx $dCuk k k k kt k k k^	+++++++ 	 	 	D	 ," ," ," ," ,"% ," ," ," ," ,"s7   G	 	AHH9I IIJ	 	JJ