Warning: chmod(): Operation not permitted in /var/www/hopeinstoughton_www/wp-content/plugins/simple-universal-google-analytics/main.php on line 8
[0] in function chmod in /var/www/hopeinstoughton_www/wp-content/plugins/simple-universal-google-analytics/main.php on line 8
[1] in function include_once in /var/www/hopeinstoughton_www/wp-settings.php on line 560
[2] in function require_once in /var/www/hopeinstoughton_www/wp-config.php on line 85
[3] in function require_once in /var/www/hopeinstoughton_www/wp-load.php on line 50
[4] in function require_once in /var/www/hopeinstoughton_www/wp-blog-header.php on line 13
[5] in function require in /var/www/hopeinstoughton_www/index.php on line 17
403WebShell
403Webshell
Server IP : 94.177.8.99  /  Your IP : 216.73.217.165
Web Server : Apache/2.4.58 (Ubuntu)
System : Linux aries 6.8.0-134-generic #134-Ubuntu SMP PREEMPT_DYNAMIC Fri Jun 26 18:43:11 UTC 2026 x86_64
User : www-data ( 33)
PHP Version : 8.1.34
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : OFF
Directory :  /nuitka/eggshell.build/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /nuitka/eggshell.build/__bytecode.const
�����nuitka.constants.Serialization��BlobData���)��N}�(�data�Bo��@sRdZdZdddddddd	d
ddd
dddddgZddlZddlZddlZzddl	m	Z
mZWn$ek
r~dd�Z
dd�ZYnXdZ
dZdZdZdZdZd ZGd!d"�d"e�Zd#d$�ZGd%d�de�ZGd&d�de�ZGd'd	�d	e�ZGd(d�de�ZGd)d
�d
e�Zd*d+�ZGd,d�de�ZGd-d�de�ZGd.d�de�Z Gd/d0�d0e �Z!Gd1d2�d2e �Z"Gd3d4�d4e"�Z#Gd5d6�d6e"�Z$Gd7d8�d8e �Z%Gd9d:�d:e �Z&Gd;d<�d<e �Z'Gd=d>�d>e �Z(Gd?d@�d@e �Z)GdAdB�dBe �Z*GdCdD�dDe%�Z+GdEd�de�Z,GdFd�de�Z-GdGdH�dHe�Z.GdIdJ�dJe.�Z/GdKdL�dLe/�Z0GdMd�dee.�Z1dS)Na�
Command-line parsing library

This module is an optparse-inspired command-line parsing library that:

    - handles both optional and positional arguments
    - produces highly informative usage messages
    - supports parsers that dispatch to sub-parsers

The following is a simple usage example that sums integers from the
command-line and writes the result to a file::

    parser = argparse.ArgumentParser(
        description='sum the integers at the command line')
    parser.add_argument(
        'integers', metavar='int', nargs='+', type=int,
        help='an integer to be summed')
    parser.add_argument(
        '--log', default=sys.stdout, type=argparse.FileType('w'),
        help='the file where the sum should be written')
    args = parser.parse_args()
    args.log.write('%s' % sum(args.integers))
    args.log.close()

The module contains the following public classes:

    - ArgumentParser -- The main entry point for command-line parsing. As the
        example above shows, the add_argument() method is used to populate
        the parser with actions for optional and positional arguments. Then
        the parse_args() method is invoked to convert the args at the
        command-line into an object with attributes.

    - ArgumentError -- The exception raised by ArgumentParser objects when
        there are errors with the parser's actions. Errors raised while
        parsing the command-line are caught by ArgumentParser and emitted
        as command-line messages.

    - FileType -- A factory for defining types of files to be created. As the
        example above shows, instances of FileType are typically passed as
        the type= argument of add_argument() calls.

    - Action -- The base class for parser actions. Typically actions are
        selected by passing strings like 'store_true' or 'append_const' to
        the action= argument of add_argument(). However, for greater
        customization of ArgumentParser actions, subclasses of Action may
        be defined and passed as the action= argument.

    - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
        ArgumentDefaultsHelpFormatter -- Formatter classes which
        may be passed as the formatter_class= argument to the
        ArgumentParser constructor. HelpFormatter is the default,
        RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
        not to change the formatting for help text, and
        ArgumentDefaultsHelpFormatter adds information about argument defaults
        to the help.

All other classes in this module are considered implementation details.
(Also note that HelpFormatter and RawDescriptionHelpFormatter are only
considered public as object names -- the API of the formatter objects is
still considered an implementation detail.)
z1.1�ArgumentParser�
ArgumentError�ArgumentTypeError�FileType�
HelpFormatter�ArgumentDefaultsHelpFormatter�RawDescriptionHelpFormatter�RawTextHelpFormatter�MetavarTypeHelpFormatter�	Namespace�Action�ONE_OR_MORE�OPTIONAL�PARSER�	REMAINDER�SUPPRESS�ZERO_OR_MORE�N)�gettext�ngettextcCs|S�N�)�messagerr�/usr/lib/python3.8/argparse.py�_^srcCs|dkr|S|SdS�N�r)�singular�plural�nrrrr`srz==SUPPRESS==�?�*�+zA...�...Z_unrecognized_argsc@s(eZdZdZdd�Zdd�Zdd�ZdS)	�_AttributeHolderaAbstract base class that provides __repr__.

    The __repr__ method returns a string in the format::
        ClassName(attr=name, attr=name, ...)
    The attributes are determined either by a class-level attribute,
    '_kwarg_names', or by inspecting the instance __dict__.
    cCs�t|�j}g}i}|��D]}|�t|��q|��D],\}}|��rZ|�d||f�q6|||<q6|rz|�dt|��d|d�|�fS)N�%s=%rz**%s�%s(%s)�, )�type�__name__�	_get_args�append�repr�_get_kwargs�isidentifier�join)�self�	type_name�arg_strings�	star_args�arg�name�valuerrr�__repr__|s

z_AttributeHolder.__repr__cCst|j���Sr)�sorted�__dict__�items�r/rrrr,�sz_AttributeHolder._get_kwargscCsgSrrr:rrrr)�sz_AttributeHolder._get_argsN)r(�
__module__�__qualname__�__doc__r6r,r)rrrrr#ssr#cCs6|dkrgSt|�tkr$|dd�Sddl}|�|�S)Nr)r'�list�copy)r9r?rrr�_copy_items�sr@c@s�eZdZdZd;dd�Zdd�Zd	d
�ZGdd�de�Zd
d�Z	dd�Z
dd�Zdd�Zd<dd�Z
dd�Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�Zd5d6�Zd7d8�Zd9d:�ZdS)=rz�Formatter for generating usage messages and argument help strings.

    Only the name of this class is considered a public API. All the methods
    provided by the class are considered an implementation detail.
    ��NcCs�|dkr@zddl}|��j}|d8}Wntk
r>d}YnX||_||_t|t|d|d��|_||_	d|_
d|_d|_|�
|d�|_|j|_t�dtj�|_t�d�|_dS)NrrA�F�z\s+z\n\n\n+)�shutil�get_terminal_size�columns�ImportError�_prog�_indent_increment�min�max�_max_help_position�_width�_current_indent�_level�_action_max_length�_Section�
_root_section�_current_section�_re�compile�ASCII�_whitespace_matcher�_long_break_matcher)r/�prog�indent_increment�max_help_position�width�_shutilrrr�__init__�s(

�zHelpFormatter.__init__cCs"|j|j7_|jd7_dSr)rOrJrPr:rrr�_indent�szHelpFormatter._indentcCs4|j|j8_|jdks"td��|jd8_dS)NrzIndent decreased below 0.r)rOrJ�AssertionErrorrPr:rrr�_dedent�szHelpFormatter._dedentc@seZdZddd�Zdd�ZdS)zHelpFormatter._SectionNcCs||_||_||_g|_dSr)�	formatter�parent�headingr9)r/rcrdrerrrr_�szHelpFormatter._Section.__init__cCs�|jdk	r|j��|jj}|dd�|jD��}|jdk	rD|j��|sLdS|jtk	rz|jdk	rz|jj}d|d|jf}nd}|d||dg�S)NcSsg|]\}}||��qSrr)�.0�func�argsrrr�
<listcomp>�sz6HelpFormatter._Section.format_help.<locals>.<listcomp>�z%*s%s:
�
)	rdrcr`�_join_partsr9rbrerrO)r/r.�	item_help�current_indentrerrr�format_help�s



z"HelpFormatter._Section.format_help)N)r(r;r<r_rorrrrrR�s
rRcCs|jj�||f�dSr)rTr9r*)r/rgrhrrr�	_add_item�szHelpFormatter._add_itemcCs0|��|�||j|�}|�|jg�||_dSr)r`rRrTrpro)r/re�sectionrrr�
start_section�szHelpFormatter.start_sectioncCs|jj|_|��dSr)rTrdrbr:rrr�end_section�s
zHelpFormatter.end_sectioncCs$|tk	r |dk	r |�|j|g�dSr)rrp�_format_text)r/�textrrr�add_textszHelpFormatter.add_textcCs&|tk	r"||||f}|�|j|�dSr)rrp�
_format_usage)r/�usage�actions�groups�prefixrhrrr�	add_usageszHelpFormatter.add_usagecCsv|jtk	rr|j}||�g}|�|�D]}|�||��q$tdd�|D��}||j}t|j|�|_|�|j	|g�dS)NcSsg|]}t|��qSr��len�rf�srrrrisz.HelpFormatter.add_argument.<locals>.<listcomp>)
�helpr�_format_action_invocation�_iter_indented_subactionsr*rLrOrQrp�_format_action)r/�action�get_invocation�invocations�	subaction�invocation_length�
action_lengthrrr�add_arguments


�zHelpFormatter.add_argumentcCs|D]}|�|�qdSr)r�)r/ryr�rrr�
add_argumentsszHelpFormatter.add_argumentscCs.|j��}|r*|j�d|�}|�d�d}|S)N�

rk)rSrorY�sub�strip)r/r�rrrro%s

zHelpFormatter.format_helpcCsd�dd�|D��S)NrjcSsg|]}|r|tk	r|�qSr)r)rf�partrrrri-s�z-HelpFormatter._join_parts.<locals>.<listcomp>)r.)r/�part_stringsrrrrl,s
�zHelpFormatter._join_partscs6|dkrtd�}|dk	r,|t|jd�}�n�|dkrL|sLdt|jd�}�n�|dk�r*dt|jd�}g}g}|D] }|jr�|�|�qr|�|�qr|j}	|	|||�}
d�dd�||
fD��}|j|j�t	|�t	|��k�r*d}|	||�}|	||�}
t
�||�}t
�||
�}d�|�|k�s&t�d�|�|
k�s:t�d�fdd	�	}t	|�t	|�d
�k�r�dt	|�t	|�d}|�r�||g|||�}|�
|||��n |�r�||g|||�}n|g}nZdt	|�}||}|||�}t	|�dk�rg}|�
|||��|�
|||��|g|}d�|�}d
||fS)Nzusage: �rZz%(prog)s� cSsg|]}|r|�qSrrrrrrriMsz/HelpFormatter._format_usage.<locals>.<listcomp>z%\(.*?\)+(?=\s|$)|\[.*?\]+(?=\s|$)|\S+cs�g}g}|dk	rt|�d}nt|�d}|D]Z}|dt|��krn|rn|�|d�|��g}t|�d}|�|�|t|�d7}q.|r�|�|d�|��|dk	r�|dt|�d�|d<|S)Nrr�r)r~r*r.)�parts�indentr{�lines�line�line_lenr���
text_widthrr�	get_linesas"
z.HelpFormatter._format_usage.<locals>.get_linesg�?rrkz%s%s

)N)r�dictrI�option_stringsr*�_format_actions_usager.rNrOr~rU�findallra�extend)r/rxryrzr{rZ�	optionals�positionalsr��format�action_usage�part_regexp�	opt_usage�	pos_usage�	opt_parts�	pos_partsr�r�r�r�rr�rrw1s\
�




zHelpFormatter._format_usagec	Cs�t�}i}|D�]}z|�|jd�}Wntk
r@YqYqX|t|j�}|||�|jkr|jD]}|�|�qh|js�||kr�||d7<nd||<||kr�||d7<nd||<nF||kr�||d7<nd||<||k�r||d7<nd||<t|d|�D]}	d	||	<�qqg}
t|�D�]"\}	}|j	t
k�r�|
�d�|�|	�d	k�rr|�
|	�n"|�|	d�d	k�rX|�
|	d�n�|j�s�|�|�}|�||�}||k�r�|ddk�r�|d
dk�r�|dd
�}|
�|�nf|jd}
|jdk�rd|
}n"|�|�}|�||�}d|
|f}|j�sN||k�rNd
|}|
�|��q6t|dd�D]}	||	g|
|	|	�<�qhd�dd�|
D��}d}d}t�d|d|�}t�d|d|�}t�d||fd|�}t�dd|�}|��}|S)Nrz [�[�]z (�(�)r�|����%s�%s %s�[%s]T)�reverser�cSsg|]}|dk	r|�qSrr)rf�itemrrrri�sz7HelpFormatter._format_actions_usage.<locals>.<listcomp>z[\[(]z[\])]z(%s) z\1� (%s)z%s *%srjz\(([^|]*)\))�set�index�_group_actions�
ValueErrorr~�add�required�range�	enumerater�rr*�get�popr��#_get_default_metavar_for_positional�_format_args�nargs�!_get_default_metavar_for_optionalr7r.rUr�r�)r/ryrz�
group_actions�inserts�group�start�endr��ir��defaultr��
option_string�args_stringru�open�closerrrr��sz










z#HelpFormatter._format_actions_usagecCsFd|kr|t|jd�}t|j|jd�}d|j}|�|||�dS)Nz%(prog)r��r�r�)r�rIrLrNrO�
_fill_text)r/rur�r�rrrrt�s

zHelpFormatter._format_textc
Cs:t|jd|j�}t|j|d�}||jd}|�|�}|jsV|jd|f}d|}n@t|�|kr~|jd||f}d|}d}n|jd|f}d|}|}|g}|jr�|�	|�}	|�
|	|�}
|�d|d|
df�|
dd�D]}|�d|d|f�q�n|�d��s|�d�|�
|�D]}|�|�|���q|�|�S)	NrAr�rjz%*s%s
z	%*s%-*s  rrrk)rKrQrMrLrNrOr�r�r~�_expand_help�_split_linesr*�endswithr�r�rl)
r/r��
help_position�
help_width�action_width�
action_header�tup�indent_firstr��	help_text�
help_linesr�r�rrrr��s8
�



zHelpFormatter._format_actioncCs�|js&|�|�}|�||�d�\}|Sg}|jdkrB|�|j�n4|�|�}|�||�}|jD]}|�d||f�q^d�|�SdS)Nrrr�r&)	r�r��_metavar_formatterr�r�r�r�r*r.)r/r�r��metavarr�r�r�rrrr�.s



z'HelpFormatter._format_action_invocationcsP|jdk	r|j�n.|jdk	r<dd�|jD�}dd�|��n|��fdd�}|S)NcSsg|]}t|��qSr��str)rf�choicerrrriJsz4HelpFormatter._metavar_formatter.<locals>.<listcomp>z{%s}�,cst�t�r�S�f|SdSr)�
isinstance�tuple)�
tuple_size��resultrrr�Os
z0HelpFormatter._metavar_formatter.<locals>.format)r��choicesr.)r/r��default_metavar�choice_strsr�rr�rr�Fs

z HelpFormatter._metavar_formattercCs�|�||�}|jdkr$d|d�}n�|jtkr<d|d�}n�|jtkrTd|d�}n�|jtkrld|d�}n�|jtkr|d}nt|jtkr�d|d�}n\|jtkr�d	}nLzd
d�t|j�D�}Wnt	k
r�t
d�d�YnXd
�|�||j�}|S)Nr�rr�z
[%s [%s ...]]rAz%s [%s ...]r"z%s ...rjcSsg|]}d�qS)r�r)rfrrrrrihsz.HelpFormatter._format_args.<locals>.<listcomp>zinvalid nargs valuer�)r�r�r
rrrrrr��	TypeErrorr�r.)r/r�r��get_metavarr��formatsrrrr�Vs*






zHelpFormatter._format_argscCs�tt|�|jd�}t|�D]}||tkr||=qt|�D] }t||d�r:||j||<q:|�d�dk	r�d�dd�|dD��}||d<|�	|�|S)Nr�r(r�r&cSsg|]}t|��qSrr�)rf�crrrriwsz.HelpFormatter._expand_help.<locals>.<listcomp>)
r��varsrIr>r�hasattrr(r�r.�_get_help_string)r/r��paramsr4�choices_strrrrr�nszHelpFormatter._expand_helpccs@z
|j}Wntk
rYnX|��|�EdH|��dSr)�_get_subactions�AttributeErrorr`rb)r/r��get_subactionsrrrr�{s
z'HelpFormatter._iter_indented_subactionscCs&|j�d|���}ddl}|�||�S)Nr�r)rXr�r��textwrap�wrap)r/rur]r�rrrr��szHelpFormatter._split_linescCs,|j�d|���}ddl}|j||||d�S)Nr�r)�initial_indent�subsequent_indent)rXr�r�r��fill)r/rur]r�r�rrrr��s�zHelpFormatter._fill_textcCs|jSr)r��r/r�rrrr��szHelpFormatter._get_help_stringcCs
|j��Sr)�dest�upperr�rrrr��sz/HelpFormatter._get_default_metavar_for_optionalcCs|jSr)r�r�rrrr��sz1HelpFormatter._get_default_metavar_for_positional)rArBN)N) r(r;r<r=r_r`rb�objectrRrprrrsrvr|r�r�rorlrwr�rtr�r�r�r�r�r�r�r�r�r�r�rrrrr�s>�
"
`g/

c@seZdZdZdd�ZdS)rz�Help message formatter which retains any formatting in descriptions.

    Only the name of this class is considered a public API. All the methods
    provided by the class are considered an implementation detail.
    cs d��fdd�|jdd�D��S)Nrjc3s|]}�|VqdSrr)rfr��r�rr�	<genexpr>�sz9RawDescriptionHelpFormatter._fill_text.<locals>.<genexpr>T)�keepends)r.�
splitlines)r/rur]r�rr�rr��sz&RawDescriptionHelpFormatter._fill_textN)r(r;r<r=r�rrrrr�sc@seZdZdZdd�ZdS)rz�Help message formatter which retains formatting of all help text.

    Only the name of this class is considered a public API. All the methods
    provided by the class are considered an implementation detail.
    cCs|��Sr)r)r/rur]rrrr��sz!RawTextHelpFormatter._split_linesN)r(r;r<r=r�rrrrr�sc@seZdZdZdd�ZdS)rz�Help message formatter which adds default values to argument help.

    Only the name of this class is considered a public API. All the methods
    provided by the class are considered an implementation detail.
    cCs>|j}d|jkr:|jtk	r:ttg}|js2|j|kr:|d7}|S)Nz
%(default)z (default: %(default)s))r�r�rr
rr�r�)r/r�r��defaulting_nargsrrrr��s

z.ArgumentDefaultsHelpFormatter._get_help_stringN)r(r;r<r=r�rrrrr�sc@s eZdZdZdd�Zdd�ZdS)r	aHelp message formatter which uses the argument 'type' as the default
    metavar value (instead of the argument 'dest')

    Only the name of this class is considered a public API. All the methods
    provided by the class are considered an implementation detail.
    cCs|jjSr�r'r(r�rrrr��sz:MetavarTypeHelpFormatter._get_default_metavar_for_optionalcCs|jjSrrr�rrrr��sz<MetavarTypeHelpFormatter._get_default_metavar_for_positionalN)r(r;r<r=r�r�rrrrr	�scCsN|dkrdS|jrd�|j�S|jdtfkr2|jS|jdtfkrF|jSdSdS)N�/)r�r.r�rr�)�argumentrrr�_get_action_name�src@s eZdZdZdd�Zdd�ZdS)rz�An error from creating or using an argument (optional or positional).

    The string value of this exception is the message, augmented with
    information about the argument that caused it.
    cCst|�|_||_dSr)r�
argument_namer)r/rrrrrr_�s
zArgumentError.__init__cCs(|jdkrd}nd}|t|j|jd�S)Nz%(message)sz'argument %(argument_name)s: %(message)s)rr)rr�r)r/r�rrr�__str__�s
�zArgumentError.__str__N)r(r;r<r=r_r	rrrrr�sc@seZdZdZdS)rz@An error from trying to convert a command line string to a type.N)r(r;r<r=rrrrr�sc@s,eZdZdZd
dd�Zdd�Zddd	�ZdS)ra\	Information about how to convert command line strings to Python objects.

    Action objects are used by an ArgumentParser to represent the information
    needed to parse a single argument from one or more strings from the
    command line. The keyword arguments to the Action constructor are also
    all attributes of Action instances.

    Keyword Arguments:

        - option_strings -- A list of command-line option strings which
            should be associated with this action.

        - dest -- The name of the attribute to hold the created object(s)

        - nargs -- The number of command-line arguments that should be
            consumed. By default, one argument will be consumed and a single
            value will be produced.  Other values include:
                - N (an integer) consumes N arguments (and produces a list)
                - '?' consumes zero or one arguments
                - '*' consumes zero or more arguments (and produces a list)
                - '+' consumes one or more arguments (and produces a list)
            Note that the difference between the default and nargs=1 is that
            with the default, a single value will be produced, while with
            nargs=1, a list containing a single value will be produced.

        - const -- The value to be produced if the option is specified and the
            option uses an action that takes no values.

        - default -- The value to be produced if the option is not specified.

        - type -- A callable that accepts a single string argument, and
            returns the converted value.  The standard Python types str, int,
            float, and complex are useful examples of such callables.  If None,
            str is used.

        - choices -- A container of values that should be allowed. If not None,
            after a command-line argument has been converted to the appropriate
            type, an exception will be raised if it is not a member of this
            collection.

        - required -- True if the action must always be specified at the
            command line. This is only meaningful for optional command-line
            arguments.

        - help -- The help string describing the argument.

        - metavar -- The name to be used for the option's argument with the
            help string. If None, the 'dest' value will be used as the name.
    NFcCs@||_||_||_||_||_||_||_||_|	|_|
|_	dSr�
r�r�r��constr�r'r�r�r�r��r/r�r�r�rr�r'r�r�r�r�rrrr_5szAction.__init__c	s(ddddddddd	g	}�fd
d�|D�S)Nr�r�r�rr�r'r�r�r�csg|]}|t�|�f�qSr��getattr�rfr4r:rrriWsz&Action._get_kwargs.<locals>.<listcomp>r�r/�namesrr:rr,Ks�zAction._get_kwargscCsttd���dS)Nz.__call__() not defined)�NotImplementedErrorr�r/�parser�	namespace�valuesr�rrr�__call__YszAction.__call__)NNNNNFNN)N)r(r;r<r=r_r,rrrrrrs5�
cs(eZdZd�fdd�	Zddd�Z�ZS)	�_StoreActionNFcsT|dkrtd��|dk	r,|tkr,tdt��tt|�j|||||||||	|
d�
dS)Nrz�nargs for store actions must be != 0; if you have nothing to store, actions such as store true or store const may be more appropriate� nargs must be %r to supply constr
)r�r
�superrr_r��	__class__rrr__s 
�z_StoreAction.__init__cCst||j|�dSr)�setattrr�rrrrr|sz_StoreAction.__call__)NNNNNFNN)N�r(r;r<r_r�
__classcell__rrrrr]s�rcs(eZdZd�fdd�	Zddd�Z�ZS)	�_StoreConstActionNFc	s"tt|�j||d||||d�dS)Nr)r�r�r�rr�r�r�)rr r_�r/r�r�rr�r�r�r�rrrr_�s
�z_StoreConstAction.__init__cCst||j|j�dSr)rr�rrrrrr�sz_StoreConstAction.__call__)NFNN)Nrrrrrr �s�r cseZdZd�fdd�	Z�ZS)�_StoreTrueActionFNcs tt|�j||d|||d�dS)NT�r�r�rr�r�r�)rr"r_�r/r�r�r�r�r�rrrr_�s
�z_StoreTrueAction.__init__)FFN�r(r;r<r_rrrrrr"�s�r"cseZdZd�fdd�	Z�ZS)�_StoreFalseActionTFNcs tt|�j||d|||d�dS)NFr#)rr&r_r$rrrr_�s
�z_StoreFalseAction.__init__)TFNr%rrrrr&�s�r&cs(eZdZd�fdd�	Zddd�Z�ZS)	�
_AppendActionNFcsT|dkrtd��|dk	r,|tkr,tdt��tt|�j|||||||||	|
d�
dS)Nrz�nargs for append actions must be != 0; if arg strings are not supplying the value to append, the append const action may be more appropriaterr
)r�r
rr'r_rrrrr_�s 
�z_AppendAction.__init__cCs2t||jd�}t|�}|�|�t||j|�dSr)rr�r@r*r�r/rrrr�r9rrrr�s
z_AppendAction.__call__)NNNNNFNN)Nrrrrrr'�s�r'cs(eZdZd�fdd�	Zddd�Z�ZS)	�_AppendConstActionNFc
s$tt|�j||d|||||d�dS)Nr)r�r�r�rr�r�r�r�)rr)r_r!rrrr_�s
�z_AppendConstAction.__init__cCs4t||jd�}t|�}|�|j�t||j|�dSr)rr�r@r*rrr(rrrr�sz_AppendConstAction.__call__)NFNN)Nrrrrrr)�s�r)cs(eZdZd�fdd�	Zddd�Z�ZS)	�_CountActionNFcs tt|�j||d|||d�dS)Nr)r�r�r�r�r�r�)rr*r_r$rrrr_�s
�z_CountAction.__init__cCs0t||jd�}|dkrd}t||j|d�dS�Nrr)rr�r)r/rrrr��countrrrr
sz_CountAction.__call__)NFN)Nrrrrrr*�s
�r*cs.eZdZeedf�fdd�	Zddd�Z�ZS)�_HelpActionNcstt|�j|||d|d�dS�Nr)r�r�r�r�r�)rr-r_)r/r�r�r�r�rrrr_s
�z_HelpAction.__init__cCs|��|��dSr)�
print_help�exitrrrrrsz_HelpAction.__call__)N�r(r;r<rr_rrrrrrr-s
�r-cs0eZdZdeedf�fdd�	Zddd�Z�ZS)�_VersionActionNz&show program's version number and exitcs$tt|�j|||d|d�||_dSr.)rr2r_�version)r/r�r3r�r�r�rrrr_&s
�z_VersionAction.__init__cCsD|j}|dkr|j}|��}|�|�|�|��tj�|��dSr)r3�_get_formatterrv�_print_messagero�_sys�stdoutr0)r/rrrr�r3rcrrrr4s
z_VersionAction.__call__)Nr1rrrrr2$s�r2csPeZdZGdd�de�Zedddf�fdd�	Zdd�Zd	d
�Zd
dd�Z	�Z
S)�_SubParsersActioncseZdZ�fdd�Z�ZS)z&_SubParsersAction._ChoicesPseudoActioncs@|}}|r|dd�|�7}ttj|�}|jg|||d�dS)Nr�r&)r�r�r�r�)r.rr8�_ChoicesPseudoActionr_)r/r4�aliasesr�r�r��suprrrr_Bs
�z/_SubParsersAction._ChoicesPseudoAction.__init__r%rrrrr9@sr9FNc	s<||_||_i|_g|_tt|�j||t|j|||d�dS)N)r�r�r�r�r�r�r�)�_prog_prefix�
_parser_class�_name_parser_map�_choices_actionsrr8r_r)r/r�rZ�parser_classr�r�r�r�rrrr_Js	
�z_SubParsersAction.__init__cKs�|�d�dkr d|j|f|d<|�dd�}d|krX|�d�}|�|||�}|j�|�|jf|�}||j|<|D]}||j|<qr|S)NrZr�r:rr�)r�r<r�r9r?r*r=r>)r/r4�kwargsr:r��
choice_actionr�aliasrrr�
add_parseras

z_SubParsersAction.add_parsercCs|jSr)r?r:rrrr�xsz!_SubParsersAction._get_subactionscCs�|d}|dd�}|jtk	r,t||j|�z|j|}Wn<tk
rv|d�|j�d�}td�|}t||��YnX|�|d�\}	}t	|	��
�D]\}
}t||
|�q�|r�t	|��tg�t
|t��|�dS)Nrrr&)�parser_namer�z5unknown parser %(parser_name)r (choices: %(choices)s))r�rrr>�KeyErrorr.rr�parse_known_argsr�r9�
setdefault�_UNRECOGNIZED_ARGS_ATTRrr�)r/rrrr�rEr1rh�msg�subnamespace�keyr5rrrr{s$

�	z_SubParsersAction.__call__)N)r(r;r<rr9rr_rDr�rrrrrrr8>s�r8c@seZdZddd�ZdS)�
_ExtendActionNcCs2t||jd�}t|�}|�|�t||j|�dSr)rr�r@r�rr(rrrr�s
z_ExtendAction.__call__)N)r(r;r<rrrrrrM�srMc@s*eZdZdZddd�Zdd�Zd	d
�ZdS)ra�Factory for creating file object types

    Instances of FileType are typically passed as type= arguments to the
    ArgumentParser add_argument() method.

    Keyword Arguments:
        - mode -- A string indicating how the file is to be opened. Accepts the
            same values as the builtin open() function.
        - bufsize -- The file's desired buffer size. Accepts the same values as
            the builtin open() function.
        - encoding -- The file's encoding. Accepts the same values as the
            builtin open() function.
        - errors -- A string indicating how encoding and decoding errors are to
            be handled. Accepts the same value as the builtin open() function.
    �rr�NcCs||_||_||_||_dSr)�_mode�_bufsize�	_encoding�_errors)r/�mode�bufsize�encoding�errorsrrrr_�szFileType.__init__c
Cs�|dkr>d|jkrtjSd|jkr(tjStd�|j}t|��zt||j|j|j|j	�WSt
k
r�}z"||d�}td�}t||��W5d}~XYnXdS)N�-rN�wzargument "-" with mode %r)�filename�errorz$can't open '%(filename)s': %(error)s)rOr6�stdinr7rr�r�rPrQrR�OSErrorr)r/�stringrJ�erhrrrrr�s

�
zFileType.__call__cCsT|j|jf}d|jfd|jfg}d�dd�|D�dd�|D��}dt|�j|fS)NrUrVr&cSsg|]}|dkrt|��qS)r�)r+)rfr3rrrri�sz%FileType.__repr__.<locals>.<listcomp>cSs$g|]\}}|dk	rd||f�qS)Nr$r)rf�kwr3rrrri�s�r%)rOrPrQrRr.r'r()r/rhrA�args_strrrrr6�s�zFileType.__repr__)rNr�NN)r(r;r<r=r_rr6rrrrr�s
c@s(eZdZdZdd�Zdd�Zdd�ZdS)	r
z�Simple object for storing attributes.

    Implements equality by attribute names and values, and provides a simple
    string representation.
    cKs|D]}t||||�qdSr)r)r/rAr4rrrr_�szNamespace.__init__cCst|t�stSt|�t|�kSr)r�r
�NotImplementedr�)r/�otherrrr�__eq__�s
zNamespace.__eq__cCs
||jkSr)r8)r/rLrrr�__contains__�szNamespace.__contains__N)r(r;r<r=r_rcrdrrrrr
�scs�eZdZ�fdd�Zdd�Zd&dd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zd'dd�Zdd�Zd d!�Zd"d#�Zd$d%�Z�ZS)(�_ActionsContainercstt|���||_||_||_||_i|_|�ddt	�|�ddt	�|�ddt
�|�ddt�|�ddt�|�ddt
�|�ddt�|�ddt�|�dd	t�|�dd
t�|�ddt�|�ddt�|��g|_i|_g|_g|_i|_t�d
�|_g|_dS)Nr��store�store_const�
store_true�store_falser*�append_constr,r�r3�parsersr�z^-\d+$|^-\d*\.\d+$)rrer_�description�argument_default�prefix_chars�conflict_handler�_registries�registerrr r"r&r'r)r*r-r2r8rM�_get_handler�_actions�_option_string_actions�_action_groups�_mutually_exclusive_groups�	_defaultsrUrV�_negative_number_matcher�_has_negative_number_optionals)r/rlrnrmrorrrr_�s4z_ActionsContainer.__init__cCs|j�|i�}|||<dSr)rprH)r/�
registry_namer5r��registryrrrrq(sz_ActionsContainer.registerNcCs|j|�||�Sr)rpr�)r/rzr5r�rrr�
_registry_get,sz_ActionsContainer._registry_getcKs2|j�|�|jD]}|j|kr||j|_qdSr)rw�updatersr�r�)r/rAr�rrr�set_defaults2s

z_ActionsContainer.set_defaultscCs8|jD]"}|j|kr|jdk	r|jSq|j�|d�Sr)rsr�r�rwr�)r/r�r�rrr�get_default;s
z_ActionsContainer.get_defaultcOsD|j}|r&t|�dkrH|dd|krH|r:d|kr:td��|j||�}n|j||�}d|kr�|d}||jkr~|j||d<n|jdk	r�|j|d<|�|�}t|�s�td|f��|f|�}|�	d|j
|j
�}t|�s�td	|f��|tkr�td
|f��t|d��r:z|�
��|d�Wntk
�r8td��YnX|�|�S)
z�
        add_argument(dest, ..., name=value, ...)
        add_argument(option_string, option_string, ..., name=value, ...)
        rrr�z+dest supplied twice for positional argumentr�Nzunknown action "%s"r'�%r is not callablez<%r is a FileType class object, instance of it must be passedr4z,length of metavar tuple does not match nargs)rnr~r��_get_positional_kwargs�_get_optional_kwargsrwrm�_pop_action_class�callabler|r'rr�r4r�r��_add_action)r/rhrA�charsr��action_classr��	type_funcrrrr�Es:	 




�z_ActionsContainer.add_argumentcOs t|f|�|�}|j�|�|Sr)�_ArgumentGrouprur*)r/rhrAr�rrr�add_argument_groupxsz$_ActionsContainer.add_argument_groupcKst|f|�}|j�|�|Sr)�_MutuallyExclusiveGrouprvr*)r/rAr�rrr�add_mutually_exclusive_group}sz._ActionsContainer.add_mutually_exclusive_groupcCs`|�|�|j�|�||_|jD]}||j|<q"|jD]"}|j�|�r8|js8|j�d�q8|S)NT)	�_check_conflictrsr*�	containerr�rtrx�matchry)r/r�r�rrrr��s


z_ActionsContainer._add_actioncCs|j�|�dSr)rs�remover�rrr�_remove_action�sz _ActionsContainer._remove_actioncCs�i}|jD].}|j|kr.td�}t||j��|||j<q
i}|jD]D}|j|krn|j|j|j|jd�||j<|jD]}||j||<qtqD|jD]&}|j	|j
d�}|jD]}|||<q�q�|jD]}|�||��
|�q�dS)Nz.cannot merge actions - two groups are named %r)�titlerlro)r�)rur�rr�r�rlror�rvr�r�rsr�r�)r/r��title_group_mapr�rJ�	group_mapr��mutex_grouprrr�_add_container_actions�s0



�

�

z(_ActionsContainer._add_container_actionscKs^d|krtd�}t|��|�d�ttfkr2d|d<|�d�tkrPd|krPd|d<t||gd�S)Nr�z1'required' is an invalid argument for positionalsr�Tr��r�r�)rr�r�r
rr�)r/r�rArJrrrr��sz(_ActionsContainer._get_positional_kwargsc	Os�g}g}|D]n}|d|jkr>||jd�}td�}t||��|�|�|d|jkrt|�dkr|d|jkr|�|�q|�dd�}|dkr�|r�|d}n|d}|�|j�}|s�td�}t||��|�dd�}t|||d	�S)
Nr)�optionrnzNinvalid option string %(option)r: must start with a character %(prefix_chars)rrr�z%dest= is required for options like %rrWrr�)	rnrr�r*r~r��lstrip�replacer�)	r/rhrAr��long_option_stringsr�rJr��dest_option_stringrrrr��s2�

z&_ActionsContainer._get_optional_kwargscCs|�d|�}|�d||�S)Nr�)r�r|)r/rAr�r�rrrr��sz#_ActionsContainer._pop_action_classcCsFd|j}zt||�WStk
r@td�}t||j��YnXdS)Nz_handle_conflict_%sz%invalid conflict_resolution value: %r)rorr�rr�)r/�handler_func_namerJrrrrr�s
z_ActionsContainer._get_handlercCsLg}|jD]&}||jkr
|j|}|�||f�q
|rH|��}|||�dSr)r�rtr*rr)r/r��confl_optionalsr��confl_optionalrorrrr�s


z!_ActionsContainer._check_conflictcCs6tddt|��}d�dd�|D��}t|||��dS)Nzconflicting option string: %szconflicting option strings: %sr&cSsg|]\}}|�qSrr)rfr�r�rrrris�z<_ActionsContainer._handle_conflict_error.<locals>.<listcomp>)rr~r.r)r/r��conflicting_actionsr�conflict_stringrrr�_handle_conflict_errors�
�z(_ActionsContainer._handle_conflict_errorcCs>|D]4\}}|j�|�|j�|d�|js|j�|�qdSr)r�r�rtr�r�r�)r/r�r�r�rrr�_handle_conflict_resolves
z*_ActionsContainer._handle_conflict_resolve)N)N)r(r;r<r_rqr|r~rr�r�r�r�r�r�r�r�r�rrr�r�r�rrrrrre�s$5
	
3($
		recs6eZdZd�fdd�	Z�fdd�Z�fdd�Z�ZS)	r�Ncs�|j}|d|j�|d|j�|d|j�tt|�j}|fd|i|��||_g|_|j	|_	|j
|_
|j|_|j|_|j
|_
|j|_dS)Nrornrmrl)rHrornrmrr�r_r�r�rprsrtrwryrv)r/r�r�rlrAr}�
super_initrrrr_+s�z_ArgumentGroup.__init__cs tt|��|�}|j�|�|Sr)rr�r�r�r*r�rrrr�Asz_ArgumentGroup._add_actioncs tt|��|�|j�|�dSr)rr�r�r�r�r�rrrr�Fsz_ArgumentGroup._remove_action)NN�r(r;r<r_r�r�rrrrrr�)sr�cs.eZdZd�fdd�	Zdd�Zdd�Z�ZS)	r�Fcs tt|��|�||_||_dSr)rr�r_r��
_container)r/r�r�rrrr_Msz _MutuallyExclusiveGroup.__init__cCs2|jrtd�}t|��|j�|�}|j�|�|S)Nz-mutually exclusive arguments must be optional)r�rr�r�r�r�r*)r/r�rJrrrr�Rsz#_MutuallyExclusiveGroup._add_actioncCs|j�|�|j�|�dSr)r�r�r�r�r�rrrr�Zsz&_MutuallyExclusiveGroup._remove_action)Fr�rrrrr�Ksr�cs*eZdZdZddddgeddddddf�fdd�	Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dAdd�ZdBdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�ZdCd&d'�ZdDd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Zd2d3�Zd4d5�ZdEd6d7�ZdFd8d9�ZdGd:d;�ZdHd=d>�Z d?d@�Z!�Z"S)Ira�Object for parsing command line strings into Python objects.

    Keyword Arguments:
        - prog -- The name of the program (default: sys.argv[0])
        - usage -- A usage message (default: auto-generated from arguments)
        - description -- A description of what the program does
        - epilog -- Text following the argument descriptions
        - parents -- Parsers whose arguments should be copied into this one
        - formatter_class -- HelpFormatter class for printing help messages
        - prefix_chars -- Characters that prefix optional arguments
        - fromfile_prefix_chars -- Characters that prefix files containing
            additional arguments
        - argument_default -- The default value for all arguments
        - conflict_handler -- String indicating how to handle conflicts
        - add_help -- Add a -h/-help option
        - allow_abbrev -- Allow long options to be abbreviated unambiguously
    NrWrZTc
	s"tt|�j}
|
|||	|
d�|dkr6tj�tjd�}||_||_	||_
||_||_||_
||_|j}|td��|_|td��|_d|_dd�}|�dd|�d|kr�dn|d}|j
r�|j|d	|d
ddttd�d
�|D]<}|�|�z
|j}Wntk
�rYq�X|j�|�q�dS)N)rlrnrmrorzpositional argumentszoptional argumentscSs|Srr)r]rrr�identity�sz)ArgumentParser.__init__.<locals>.identityr'rW�hrAr�zshow this help message and exit)r�r�r�)rrr_�_os�path�basenamer6�argvrZrx�epilog�formatter_class�fromfile_prefix_chars�add_help�allow_abbrevr�r�_positionals�
_optionals�_subparsersrqr�rr�rwr�r})r/rZrxrlr��parentsr�rnr�rmror�r��	superinit�	add_groupr��default_prefixrd�defaultsrrrr_rsJ�
�

zArgumentParser.__init__cs"ddddddg}�fdd�|D�S)	NrZrxrlr�ror�csg|]}|t�|�f�qSrr
rr:rrri�sz.ArgumentParser._get_kwargs.<locals>.<listcomp>rrrr:rr,�s�zArgumentParser._get_kwargsc	Ks�|jdk	r|�td��|�dt|��d|ks8d|krht|�dd��}t|�dd��}|�||�|_n|j|_|�d�dkr�|�	�}|�
�}|j}|�|j
||d�|����|d<|�|d�}|fd	gi|��}|j�|�|S)
Nz(cannot have multiple subparser argumentsr@r�rlZsubcommandsrZrjrkr�)r�rZrrHr'r�r�r�r�r4�_get_positional_actionsrvr|rxror�r�r�)	r/rAr�rlrcr�rz�
parsers_classr�rrr�add_subparsers�s$
zArgumentParser.add_subparserscCs$|jr|j�|�n|j�|�|Sr)r�r�r�r�r�rrrr��szArgumentParser._add_actioncCsdd�|jD�S)NcSsg|]}|jr|�qSr�r��rfr�rrrri�s�z8ArgumentParser._get_optional_actions.<locals>.<listcomp>�rsr:rrr�_get_optional_actions�s�z$ArgumentParser._get_optional_actionscCsdd�|jD�S)NcSsg|]}|js|�qSrr�r�rrrri�s�z:ArgumentParser._get_positional_actions.<locals>.<listcomp>r�r:rrrr��s�z&ArgumentParser._get_positional_actionscCs4|�||�\}}|r0td�}|�|d�|��|S�Nzunrecognized arguments: %sr�)rGrrZr.�r/rhrr�rJrrr�
parse_args�s
zArgumentParser.parse_argscCs|dkrtjdd�}nt|�}|dkr.t�}|jD]4}|jtk	r4t||j�s4|jtk	r4t	||j|j�q4|j
D] }t||�spt	|||j
|�qpz>|�||�\}}t|t�r�|�
t|t��t|t�||fWStk
�rt��d}|�t|��YnXdSr)r6r�r>r
rsr�rr�r�rrw�_parse_known_argsrIr�r�delattrr�exc_inforZr�)r/rhrr�r��errrrrrG�s,







zArgumentParser.parse_known_argscs�	jdk	r�	����i��	jD]R}|j}t|j�D]<\}}��|g�}|�|d|��|�||dd��q2qi�g}t��}	t|	�D]^\}}
|
dkr�|�d�|	D]}
|�d�q�q��	�	|
�}|dkr�d}n|�|<d}|�|�q�d�
|��t��t��d�����	fdd�	������	�fd	d
�}
�	�������	�fdd�}g�d
�
��r`t
��}nd}�
|k�r�t�
fdd��D��}�
|k�r�|�
�}|�
k�r�|�
�qdn|�
�
�k�r҈�
|�}��|�|�
|
�
��
�qd|�
�}���|d��g}�	jD]|}|�k�r|j�r(|�t|��nT|jdk	�rt|jt��rt�|j��r|jt�|j�k�rt�|j�	�||j���q|�r��	�td�d�
|���	jD]X}|j�r�|jD]}|�k�r��q��q�dd�|jD�}td�}�	�|d�
|���q���fS)Nr�--rW�A�Orjcs|��|���||�}||jk	rb��|���|g�D]*}|�kr6td�}t|�}t|||��q6|tk	rx|��||�dS)Nznot allowed with argument %s)r��_get_valuesr�r�rrrr)r��argument_stringsr��argument_values�conflict_actionrJ�action_name)�action_conflictsr�seen_actions�seen_non_default_actionsr/rr�take_actionLs


z5ArgumentParser._parse_known_args.<locals>.take_actioncs��|}|\}}}�j}g}|dkr:���|�|dS|dk	�r||d�}�j}|dkr�|d|kr�|�|g|f�|d}	|	|d}|dd�p�d}
�j}||kr�||}|
}ntd�}t|||��nB|dkr�|d}
|g}|�|||f��q\ntd�}t|||��q|d}�|d�}|||�}||}
�||
�}|�|||f��q\q|�sft�|D]\}}}�|||��qj|
S)Nrr�rzignored explicit argument %r)�_match_argumentr*rnrtrrra)�start_index�option_tupler�r��explicit_arg�match_argument�
action_tuples�	arg_countr��char�new_explicit_arg�
optionals_maprJ�stoprhr��selected_patterns)r1�arg_strings_pattern�extras�option_string_indicesr/r�rr�consume_optionalasN




z:ArgumentParser._parse_known_args.<locals>.consume_optionalcsn�j}�|d�}|�|�}t�|�D]*\}}�|||�}||7}�||�q&�t|�d��dd�<|Sr)�_match_arguments_partial�zipr~)r��
match_partial�selected_pattern�
arg_countsr�r�rh)r1r�r�r/r�rr�consume_positionals�s
z=ArgumentParser._parse_known_args.<locals>.consume_positionalsrr�csg|]}|�kr|�qSrr)rfr�)r�rrri�s�z4ArgumentParser._parse_known_args.<locals>.<listcomp>z(the following arguments are required: %sr&cSsg|]}|jtk	rt|��qSr)r�rrr�rrrri
s
�z#one of the arguments %s is requiredr�)N)r��_read_args_from_filesrvr�r�rHr��iterr*�_parse_optionalr.r�r�rLrKrsr�rr�r�r�r�r�rr�
_get_valuerZr)r/r1rr�r�r��mutex_action�	conflicts�arg_string_pattern_parts�arg_strings_iter�
arg_stringr��patternr�r��max_option_string_index�next_option_string_index�positionals_end_index�strings�
stop_index�required_actionsr�r�rrJr)r�r1r�r�rr�r�r�r�r/r�r�rr�s�





J

�






�
���
�



�z ArgumentParser._parse_known_argsc
Cs�g}|D]�}|r|d|jkr*|�|�qzdt|dd���J}g}|����D]}|�|�D]}|�|�q\qN|�|�}|�|�W5QRXWqtk
r�t	�
�d}|�t|��YqXq|Sr+)
r�r*r��readr�convert_arg_line_to_argsr�r�r\r6r�rZr�)r/r1�new_arg_stringsr��	args_file�arg_liner3r�rrrr�s 
z$ArgumentParser._read_args_from_filescCs|gSrr)r/r�rrrr�-sz'ArgumentParser.convert_arg_line_to_argscCsz|�|�}t�||�}|dkrldtd�ttd�ttd�i}|�|j�}|dkrbtdd|j�|j}t	||��t
|�d��S)Nzexpected one argumentzexpected at most one argumentzexpected at least one argumentzexpected %s argumentzexpected %s argumentsr)�_get_nargs_patternrUr�rr
rr�r�rrr~r�)r/r�r��
nargs_patternr��nargs_errorsrJrrrr�0s(
���
zArgumentParser._match_argumentcsrg}tt|�dd�D]X}|d|�}d��fdd�|D��}t�||�}|dk	r|�dd�|��D��qnq|S)Nrr�rjcsg|]}��|��qSr)r�r�r:rrriLs�z;ArgumentParser._match_arguments_partial.<locals>.<listcomp>cSsg|]}t|��qSrr})rfr]rrrriPs)r�r~r.rUr�r�rz)r/ryr�r�r��
actions_slicer�r�rr:rr�Fs�z'ArgumentParser._match_arguments_partialc
Cs|sdS|d|jkrdS||jkr8|j|}||dfSt|�dkrHdSd|kr~|�dd�\}}||jkr~|j|}|||fS|�|�}t|�dkr�d�dd�|D��}||d�}td�}|�||�nt|�dkr�|\}	|	S|j�	|�r�|j
s�dSd	|k�rdSd|dfS)
Nrr�=r&cSsg|]\}}}|�qSrr)rfr�r�r�rrrrius�z2ArgumentParser._parse_optional.<locals>.<listcomp>)r��matchesz4ambiguous option: %(option)s could match %(matches)sr�)rnrtr~�split�_get_option_tuplesr.rrZrxr�ry)
r/r�r�r�r��
option_tuples�optionsrhrJr�rrrr�Vs>







�

zArgumentParser._parse_optionalc
Cs0g}|j}|d|kr�|d|kr�|jr~d|krB|�dd�\}}n|}d}|jD],}|�|�rP|j|}|||f}|�|�qPn�|d|k�r|d|k�r|}d}|dd�}|dd�}	|jD]T}||kr�|j|}|||	f}|�|�q�|�|�r�|j|}|||f}|�|�q�n|�td�|�|S)NrrrrAzunexpected option string: %s)rnr�rrt�
startswithr*rZr)
r/r�r�r��
option_prefixr�r�r��short_option_prefix�short_explicit_argrrrr�s:









z!ArgumentParser._get_option_tuplescCs�|j}|dkrd}nf|tkr"d}nX|tkr0d}nJ|tkr>d}n<|tkrLd}n.|tkrZd}n |tkrhd}ndd	�d
|�}|jr�|�	d	d�}|�	dd�}|S)
Nz(-*A-*)z(-*A?-*)z	(-*[A-]*)z
(-*A[A-]*)z([-AO]*)z(-*A[-AO]*)z(-*-*)z(-*%s-*)z-*r�rjrW)
r�r
rrrrrr.r�r�)r/r�r�rrrrr��s(z!ArgumentParser._get_nargs_patterncCs4|�||�\}}|r0td�}|�|d�|��|Sr�)�parse_known_intermixed_argsrrZr.r�rrr�parse_intermixed_args�s
z$ArgumentParser.parse_intermixed_argsc	s�|���dd��D�}|r,td|dj���fdd�|jD�rHtd���zN|j}z�|jdkrp|��dd�|_�D] }|j|_t	|_|j|_t	|_qt|�
||�\}}�D]J}t||j�r�t
||j�gkr�ddlm}|d	|j|f�t||j�q�W5�D]}|j|_|j|_q�X|��}zJ|D]}|j|_d
|_�q$|jD]}	|	j|	_d
|	_�q@|�
||�\}}
W5|D]}|j|_�qn|jD]}	|	j|	_�q�XW5||_X||
fS)NcSsg|]}|jttfkr|�qSr)r�rrr�rrrri	s�z>ArgumentParser.parse_known_intermixed_args.<locals>.<listcomp>z3parse_intermixed_args: positional arg with nargs=%srcs&g|]}|jD]}|�kr|j�qqSr)r�r�)rfr�r��r�rrri		s
�z;parse_intermixed_args: positional in mutuallyExclusiveGroup�)�warnzDo not expect %s in %sF)r�r�r�rvrx�
save_nargs�save_defaultr��format_usagerrGr�r�r�warningsrr�r��
save_requiredr�)r/rhr�a�
save_usager��remaining_argsrr�r�r�rrrr
�s`
�
��


�
z*ArgumentParser.parse_known_intermixed_argscs��jttfkr2z|�d�Wntk
r0YnX|sz�jtkrz�jrN�j}n�j}t	|t
�rv���|�}���|��n|s��jt
kr��js��jdk	r��j}n|}���|�n�t|�dkr�jdtfkr�|\}���|�}���|�n��jtk�r��fdd�|D�}np�jtk�r@��fdd�|D�}���|d�n>�jtk�rRt}n,��fdd�|D�}|D]}���|��qj|S)Nr�rcsg|]}���|��qSr�r��rf�v�r�r/rrrif	sz.ArgumentParser._get_values.<locals>.<listcomp>csg|]}���|��qSrrrrrrrij	srcsg|]}���|��qSrrrrrrris	s)r�rrr�r�r
r�rr�r�r�r��_check_valuerr~r)r/r�r1r5r�rrrrr�B	sD
�
zArgumentParser._get_valuesc	Cs�|�d|j|j�}t|�s0td�}t|||��z||�}Wn�tk
r~t|jdt|j��}tt	�
�d�}t||��YnLttfk
r�t|jdt|j��}||d�}td�}t|||��YnX|S)Nr'r�r(r)r'r5z!invalid %(type)s value: %(value)r)
r|r'r�rrrrr+r�r6r�r�r�)r/r�r�r�rJr�r4rhrrrr�z	s 
zArgumentParser._get_valuecCsF|jdk	rB||jkrB|d�tt|j��d�}td�}t|||��dS)Nr&)r5r�z3invalid choice: %(value)r (choose from %(choices)s))r�r.�mapr+rr)r/r�r5rhrJrrrr�	s�zArgumentParser._check_valuecCs$|��}|�|j|j|j�|��Sr)r4r|rxrsrvro)r/rcrrrr�	s
�zArgumentParser.format_usagecCst|��}|�|j|j|j�|�|j�|jD]0}|�|j	�|�|j�|�
|j�|��q.|�|j
�|��Sr)r4r|rxrsrvrvrlrurrr�r�r�rsr�ro)r/rc�action_grouprrrro�	s�

zArgumentParser.format_helpcCs|j|jd�S)Nr�)r�rZr:rrrr4�	szArgumentParser._get_formattercCs"|dkrtj}|�|��|�dSr)r6r7r5r�r/�filerrr�print_usage�	szArgumentParser.print_usagecCs"|dkrtj}|�|��|�dSr)r6r7r5ror!rrrr/�	szArgumentParser.print_helpcCs |r|dkrtj}|�|�dSr)r6�stderr�write)r/rr"rrrr5�	szArgumentParser._print_messagercCs |r|�|tj�t�|�dSr)r5r6r$r0)r/�statusrrrrr0�	szArgumentParser.exitcCs0|�tj�|j|d�}|�dtd�|�dS)z�error(message: string)

        Prints a usage message incorporating the message to stderr and
        exits.

        If you override this in a subclass, it should not return -- it
        should either exit or raise an exception.
        )rZrrAz%(prog)s: error: %(message)s
N)r#r6r$rZr0r)r/rrhrrrrZ�	s	zArgumentParser.error)NN)NN)NN)NN)N)N)N)rN)#r(r;r<r=rr_r,r�r�r�r�r�rGr�r�r�r�r�r�rr�rr
r�r�rrror4r#r/r5r0rZrrrrrr_sV�@

#w:-1

M8


	
)2r=�__version__�__all__�osr��rerU�sysr6rrrrHrr
rrrrrIr�r#r@rrrrr	r�	Exceptionrrrrr r"r&r'r)r*r-r2r8rMrr
rer�r�rrrrr�<module>s�=�~
	[#&]7:"��name��bytecode of module 'argparse'�u��b.��h)��N}�(hB��@sdZddlZddlTddlTddlTddlTddlTddlTddlTddl	Tddl
TddlTddlTddl
TddlTddl
mZejejejejejejeje	je
jejeje
jejZejdkr�ddlTeej7ZnddlTeej7ZdS)z'The asyncio package, tracking PEP 3156.�N�)�*)�_all_tasks_compat�win32)�__doc__�sys�base_events�
coroutines�events�
exceptions�futures�locks�	protocols�runners�queues�streams�
subprocess�tasks�
transportsr�__all__�platform�windows_events�unix_events�rr�&/usr/lib/python3.8/asyncio/__init__.py�<module>sZ��������	�
���
�h�bytecode of module 'asyncio'�u��b.���h)��N}�(hB<��@s�dZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlZddlZzddlZWnek
r�dZYnXddlmZddlmZddlmZddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddl m!Z!dZ"dZ#dZ$e%e	d�Z&dZ'e(�Z)dd�Z*dd�Z+dd�Z,d+dd�Z-d,dd�Z.dd �Z/e%e	d!��r�d"d#�Z0nd$d#�Z0Gd%d&�d&ej1�Z2Gd'd(�d(ej3�Z4Gd)d*�d*ej5�Z6dS)-a�Base implementation of event loop.

The event loop can be broken up into a multiplexer (the part
responsible for notifying us of I/O events) and the event loop proper,
which wraps a multiplexer with functionality for scheduling callbacks,
immediately or at a given time in the future.

Whenever a public API takes a callback, subsequent positional
arguments will be passed to the callback if/when it is called.  This
avoids the proliferation of trivial lambdas implementing closures.
Keyword arguments for the callback are not supported; this is a
conscious design decision, leaving the door open for keyword arguments
to modify the meaning of the API call itself.
�N�)�	constants)�
coroutines)�events)�
exceptions)�futures)�	protocols)�sslproto)�	staggered)�tasks)�
transports)�trsock)�logger)�
BaseEventLoop�dg�?�AF_INET6i�QcCs0|j}tt|dd�tj�r$t|j�St|�SdS)N�__self__)�	_callback�
isinstance�getattrr�Task�reprr�str)�handle�cb�r�)/usr/lib/python3.8/asyncio/base_events.py�_format_handleJs
rcCs(|tjkrdS|tjkrdSt|�SdS)Nz<pipe>z<stdout>)�
subprocess�PIPE�STDOUTr)�fdrrr�_format_pipeSs


r"cCsLttd�std��n4z|�tjtjd�Wntk
rFtd��YnXdS)N�SO_REUSEPORTz)reuse_port not supported by socket modulerzTreuse_port not supported by socket module, SO_REUSEPORT defined but not implemented.)�hasattr�socket�
ValueError�
setsockopt�
SOL_SOCKETr#�OSError��sockrrr�_set_reuseport\s

r,c		Cs�ttd�sdS|dtjtjhks(|dkr,dS|tjkr>tj}n|tjkrPtj}ndS|dkrbd}nXt|t�rz|dkrzd}n@t|t�r�|dkr�d}n(zt	|�}Wnt
tfk
r�YdSX|tjkr�tj
g}tr�|�tj�n|g}t|t�r�|�d�}d|k�rdS|D]t}zVt�||�t�rJ|tjk�rJ|||d||||ffWS|||d||ffWSWntk
�rzYnX�q
dS)N�	inet_ptonr���idna�%)r$r%�IPPROTO_TCP�IPPROTO_UDP�SOCK_STREAM�
SOCK_DGRAMr�bytesr�int�	TypeErrorr&�	AF_UNSPEC�AF_INET�	_HAS_IPv6�appendr�decoder-r))	�host�port�family�type�proto�flowinfo�scopeid�afs�afrrr�_ipaddr_infogsN
�






rGcCs�t��}|D]*}|d}||kr(g||<||�|�qt|���}g}|dkr||�|dd|d��|dd|d�=|�dd�tj�tj	|��D��|S)z-Interleave list of addrinfo tuples by family.rrNcss|]}|dk	r|VqdS�Nr)�.0�arrr�	<genexpr>�s�z(_interleave_addrinfos.<locals>.<genexpr>)
�collections�OrderedDictr<�list�values�extend�	itertools�chain�
from_iterable�zip_longest)�	addrinfos�first_address_family_count�addrinfos_by_family�addrr@�addrinfos_lists�	reorderedrrr�_interleave_addrinfos�s"
��r[cCs4|��s"|��}t|ttf�r"dSt�|���dSrH)�	cancelled�	exceptionr�
SystemExit�KeyboardInterruptr�	_get_loop�stop)�fut�excrrr�_run_until_complete_cb�s
rd�TCP_NODELAYcCs@|jtjtjhkr<|jtjkr<|jtjkr<|�tjtj	d�dS�Nr)
r@r%r:rrAr4rBr2r'rer*rrr�_set_nodelay�s
�
�rgcCsdSrHrr*rrrrg�sc@sTeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�ZdS)�_SendfileFallbackProtocolcCsht|tj�std��||_|��|_|��|_|j	|_
|��|�|�|j
r^|jj
��|_nd|_dS)Nz.transport should be _FlowControlMixin instance)rr�_FlowControlMixinr8�
_transport�get_protocol�_proto�
is_reading�_should_resume_reading�_protocol_paused�_should_resume_writing�
pause_reading�set_protocol�_loop�
create_future�_write_ready_fut)�self�transprrr�__init__�s


z"_SendfileFallbackProtocol.__init__c�s2|j��rtd��|j}|dkr$dS|IdHdS)NzConnection closed by peer)rj�
is_closing�ConnectionErrorru)rvrbrrr�drain�s
z_SendfileFallbackProtocol.draincCstd��dS)Nz?Invalid state: connection should have been established already.��RuntimeError)rv�	transportrrr�connection_made�sz)_SendfileFallbackProtocol.connection_madecCs@|jdk	r0|dkr$|j�td��n|j�|�|j�|�dS)NzConnection is closed by peer)ru�
set_exceptionrzrl�connection_lost)rvrcrrrr��s
�z)_SendfileFallbackProtocol.connection_lostcCs |jdk	rdS|jj��|_dSrH)rurjrsrt�rvrrr�
pause_writing�s
z'_SendfileFallbackProtocol.pause_writingcCs$|jdkrdS|j�d�d|_dS)NF)ru�
set_resultr�rrr�resume_writing�s
z(_SendfileFallbackProtocol.resume_writingcCstd��dS�Nz'Invalid state: reading should be pausedr|)rv�datarrr�
data_received�sz'_SendfileFallbackProtocol.data_receivedcCstd��dSr�r|r�rrr�eof_receivedsz&_SendfileFallbackProtocol.eof_receivedc�sF|j�|j�|jr|j��|jdk	r2|j��|jrB|j��dSrH)	rjrrrlrn�resume_readingru�cancelrpr�r�rrr�restores


z!_SendfileFallbackProtocol.restoreN)�__name__�
__module__�__qualname__rxr{rr�r�r�r�r�r�rrrrrh�srhc@sxeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
edd��Zdd�Z
dd�Zdd�Zdd�ZdS)�ServercCs@||_||_d|_g|_||_||_||_||_d|_d|_	dS)NrF)
rs�_sockets�
_active_count�_waiters�_protocol_factory�_backlog�_ssl_context�_ssl_handshake_timeout�_serving�_serving_forever_fut)rv�loop�sockets�protocol_factory�ssl_context�backlog�ssl_handshake_timeoutrrrrxszServer.__init__cCsd|jj�d|j�d�S)N�<z	 sockets=�>)�	__class__r�r�r�rrr�__repr__ szServer.__repr__cCs |jdk	st�|jd7_dSrf)r��AssertionErrorr�r�rrr�_attach#szServer._attachcCs<|jdkst�|jd8_|jdkr8|jdkr8|��dS)Nrr)r�r�r��_wakeupr�rrr�_detach'szServer._detachcCs,|j}d|_|D]}|��s|�|�qdSrH)r��doner�)rv�waiters�waiterrrrr�-s
zServer._wakeupc	CsJ|jr
dSd|_|jD].}|�|j�|j�|j||j||j|j�qdS)NT)	r�r��listenr�rs�_start_servingr�r�r�)rvr+rrrr�4s
�zServer._start_servingcCs|jSrH)rsr�rrr�get_loop>szServer.get_loopcCs|jSrH)r�r�rrr�
is_servingAszServer.is_servingcCs"|jdkrdStdd�|jD��S)Nrcss|]}t�|�VqdSrH)r
�TransportSocket)rI�srrrrKHsz!Server.sockets.<locals>.<genexpr>)r��tupler�rrrr�Ds
zServer.socketscCsn|j}|dkrdSd|_|D]}|j�|�qd|_|jdk	rX|j��sX|j��d|_|jdkrj|��dS)NFr)	r�rs�
_stop_servingr�r�r�r�r�r�)rvr�r+rrr�closeJs
�

zServer.closec�s"|��tjd|jd�IdHdS)Nr�r�)r�r�sleeprsr�rrr�
start_serving]szServer.start_servingc	�s�|jdk	rtd|�d���|jdkr4td|�d���|��|j��|_zLz|jIdHWn6tjk
r�z|��|�	�IdHW5�XYnXW5d|_XdS)Nzserver z, is already being awaited on serve_forever()z
 is closed)
r�r}r�r�rsrtr�CancelledErrorr��wait_closedr�rrr�
serve_forevercs 

�
zServer.serve_foreverc�s<|jdks|jdkrdS|j��}|j�|�|IdHdSrH)r�r�rsrtr<)rvr�rrrr�xs

zServer.wait_closedN)r�r�r�rxr�r�r�r�r�r�r��propertyr�r�r�r�r�rrrrr�s


r�c@sPeZdZdd�Zdd�Zdd�Zdd�d	d
�Zdd�Zd
d�Zd�ddd�dd�Z	d�ddddddd�dd�Z
d�dd�Zd�dd�Zd�dd�Z
d�dd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�Zd5d6�Zejfd7d8�Zd9d:�Zd;d<�Zdd=�d>d?�Z dd=�d@dA�Z!dd=�dBdC�Z"dDdE�Z#dFdG�Z$dHdI�Z%dd=�dJdK�Z&dLdM�Z'dNdO�Z(dPdQ�Z)dRdRdRdRdS�dTdU�Z*d�dVdW�Z+d�ddX�dYdZ�Z,d[d\�Z-d]d^�Z.d_d`�Z/d�dadb�Z0d�ddRdRdRdddddddc�
ddde�Z1d�dfdg�Z2d�ddX�dhdi�Z3djdk�Z4dldm�Z5ddddn�dodp�Z6d�dRdRdRe7ddddq�drds�Z8dRe9j:dRdRdS�dtdu�Z;dvdw�Z<d�e9j=e9j>ddxddddddy�	dzd{�Z?ddd|�d}d~�Z@dd��ZAd�d��ZBd�d��ZCeDjEeDjEeDjEdddRdddd��	d�d��ZFeDjEeDjEeDjEdddRdddd��	d�d��ZGd�d��ZHd�d��ZId�d��ZJd�d��ZKd�d��ZLd�d��ZMd�d��ZNd�d��ZOd�d��ZPd�d��ZQd�d��ZRdS)�rcCs�d|_d|_d|_t��|_g|_d|_d|_d|_	t
�d�j|_
d|_|�t���d|_d|_d|_d|_d|_t��|_d|_dS)NrF�	monotonicg�������?)�_timer_cancelled_count�_closed�	_stoppingrL�deque�_ready�
_scheduled�_default_executor�
_internal_fds�
_thread_id�time�get_clock_info�
resolution�_clock_resolution�_exception_handler�	set_debugr�_is_debug_mode�slow_callback_duration�_current_handle�
_task_factory�"_coroutine_origin_tracking_enabled�&_coroutine_origin_tracking_saved_depth�weakref�WeakSet�
_asyncgens�_asyncgens_shutdown_calledr�rrrrx�s$

zBaseEventLoop.__init__c	Cs.d|jj�d|���d|���d|���d�	S)Nr�z	 running=z closed=z debug=r�)r�r��
is_running�	is_closed�	get_debugr�rrrr��s,�zBaseEventLoop.__repr__cCstj|d�S)z,Create a Future object attached to the loop.r�)r�Futurer�rrrrt�szBaseEventLoop.create_futureN)�namecCsN|��|jdkr2tj|||d�}|jrJ|jd=n|�||�}t�||�|S)zDSchedule a coroutine object.

        Return a task object.
        N)r�r����)�
_check_closedr�rr�_source_traceback�_set_task_name)rv�coror��taskrrr�create_task�s

zBaseEventLoop.create_taskcCs"|dk	rt|�std��||_dS)awSet a task factory that will be used by loop.create_task().

        If factory is None the default task factory will be set.

        If factory is a callable, it should have a signature matching
        '(loop, coro)', where 'loop' will be a reference to the active
        event loop, 'coro' will be a coroutine object.  The callable
        must return a Future.
        Nz'task factory must be a callable or None)�callabler8r�)rv�factoryrrr�set_task_factory�s
zBaseEventLoop.set_task_factorycCs|jS)z<Return a task factory, or None if the default one is in use.)r�r�rrr�get_task_factory�szBaseEventLoop.get_task_factory)�extra�servercCst�dS)zCreate socket transport.N��NotImplementedError)rvr+�protocolr�r�r�rrr�_make_socket_transport�sz$BaseEventLoop._make_socket_transportFT)�server_side�server_hostnamer�r�r��call_connection_madecCst�dS)zCreate SSL transport.Nr�)rv�rawsockr��
sslcontextr�r�r�r�r�r�r�rrr�_make_ssl_transport�sz!BaseEventLoop._make_ssl_transportcCst�dS)zCreate datagram transport.Nr�)rvr+r��addressr�r�rrr�_make_datagram_transport�sz&BaseEventLoop._make_datagram_transportcCst�dS)zCreate read pipe transport.Nr��rv�piper�r�r�rrr�_make_read_pipe_transport�sz'BaseEventLoop._make_read_pipe_transportcCst�dS)zCreate write pipe transport.Nr�r�rrr�_make_write_pipe_transport�sz(BaseEventLoop._make_write_pipe_transportc	
�st�dS)zCreate subprocess transport.Nr�)
rvr��args�shell�stdin�stdout�stderr�bufsizer��kwargsrrr�_make_subprocess_transport�sz(BaseEventLoop._make_subprocess_transportcCst�dS)z�Write a byte to self-pipe, to wake up the event loop.

        This may be called from a different thread.

        The subclass is responsible for implementing the self-pipe.
        Nr�r�rrr�_write_to_self�szBaseEventLoop._write_to_selfcCst�dS)zProcess selector events.Nr�)rv�
event_listrrr�_process_events�szBaseEventLoop._process_eventscCs|jrtd��dS)NzEvent loop is closed)r�r}r�rrrr��szBaseEventLoop._check_closedcCs*|j�|�|��s&|�|j|���dSrH)r��discardr��call_soon_threadsafer��aclose�rv�agenrrr�_asyncgen_finalizer_hook�sz&BaseEventLoop._asyncgen_finalizer_hookcCs.|jrtjd|�d�t|d�|j�|�dS)Nzasynchronous generator z3 was scheduled after loop.shutdown_asyncgens() call��source)r��warnings�warn�ResourceWarningr��addrrrr�_asyncgen_firstiter_hooks
�z&BaseEventLoop._asyncgen_firstiter_hookc�s�d|_t|j�sdSt|j�}|j��tjdd�|D�d|d��IdH}t||�D]*\}}t|t	�rT|�
d|��||d��qTdS)z,Shutdown all active asynchronous generators.TNcSsg|]}|���qSr)r)rI�agrrr�
<listcomp>sz4BaseEventLoop.shutdown_asyncgens.<locals>.<listcomp>)�return_exceptionsr�z;an error occurred during closing of asynchronous generator )�messager]�asyncgen)r��lenr�rN�clearr�gather�zipr�	Exception�call_exception_handler)rv�
closing_agens�results�resultrrrr�shutdown_asyncgenss"


�
�z BaseEventLoop.shutdown_asyncgenscCs(|��rtd��t��dk	r$td��dS)Nz"This event loop is already runningz7Cannot run the event loop while another loop is running)r�r}r�_get_running_loopr�rrr�_check_running&s�zBaseEventLoop._check_runningc	Cs�|��|��|�|j�t��|_t��}tj	|j
|jd�z t
�|�|��|jrLq^qLW5d|_d|_t
�d�|�d�tj	|�XdS)zRun until stop() is called.)�	firstiter�	finalizerFN)r�r�_set_coroutine_origin_tracking�_debug�	threading�	get_identr��sys�get_asyncgen_hooks�set_asyncgen_hooksrrr�r�_set_running_loop�	_run_once)rv�old_agen_hooksrrr�run_forever-s$
�


zBaseEventLoop.run_foreverc	Cs�|��|��t�|�}tj||d�}|r4d|_|�t�z<z|�
�Wn*|rp|��rp|��sp|�
��YnXW5|�	t�X|��s�td��|��S)a\Run until the Future is done.

        If the argument is a coroutine, it is wrapped in a Task.

        WARNING: It would be disastrous to call run_until_complete()
        with the same coroutine twice -- it would wrap it in two
        different Tasks and that can't be good.

        Return the Future's result, or raise its exception.
        r�Fz+Event loop stopped before Future completed.)r�rr�isfuturer�
ensure_future�_log_destroy_pending�add_done_callbackrd�remove_done_callbackr,r�r\r]r}r)rv�future�new_taskrrr�run_until_completeDs"
z BaseEventLoop.run_until_completecCs
d|_dS)z�Stop running the event loop.

        Every callback already scheduled will still run.  This simply informs
        run_forever to stop looping after a complete iteration.
        TN)r�r�rrrrajszBaseEventLoop.stopcCsj|��rtd��|jrdS|jr,t�d|�d|_|j��|j��|j	}|dk	rfd|_	|j
dd�dS)z�Close the event loop.

        This clears the queues and shuts down the executor,
        but does not wait for the executor to finish.

        The event loop must not be running.
        z!Cannot close a running event loopNzClose %rTF)�wait)r�r}r�r#r�debugr�rr�r��shutdown�rv�executorrrrr�rs

zBaseEventLoop.closecCs|jS)z*Returns True if the event loop was closed.)r�r�rrrr��szBaseEventLoop.is_closedcCs0|��s,|d|��t|d�|��s,|��dS)Nzunclosed event loop r)r�rr�r�)rv�_warnrrr�__del__�szBaseEventLoop.__del__cCs
|jdk	S)z*Returns True if the event loop is running.N)r�r�rrrr��szBaseEventLoop.is_runningcCst��S)z�Return the time according to the event loop's clock.

        This is a float expressed in seconds since an epoch, but the
        epoch, precision, accuracy and drift are unspecified and may
        differ per event loop.
        )r�r�r�rrrr��szBaseEventLoop.time)�contextcGs2|j|��||f|�d|i�}|jr.|jd=|S)a8Arrange for a callback to be called at a given time.

        Return a Handle: an opaque object with a cancel() method that
        can be used to cancel the call.

        The delay can be an int or float, expressed in seconds.  It is
        always relative to the current time.

        Each callback will be called exactly once.  If two callbacks
        are scheduled for exactly the same time, it undefined which
        will be called first.

        Any positional arguments after the callback will be passed to
        the callback when it is called.
        r<r�)�call_atr�r�)rv�delay�callbackr<r��timerrrr�
call_later�s�zBaseEventLoop.call_latercGsZ|��|jr"|��|�|d�t�|||||�}|jrB|jd=t�|j	|�d|_	|S)z|Like call_later(), but uses an absolute time.

        Absolute time corresponds to the event loop's time() method.
        r=r�T)
r�r#�
_check_thread�_check_callbackr�TimerHandler��heapq�heappushr�)rv�whenr?r<r�r@rrrr=�szBaseEventLoop.call_atcGsB|��|jr"|��|�|d�|�|||�}|jr>|jd=|S)aTArrange for a callback to be called as soon as possible.

        This operates as a FIFO queue: callbacks are called in the
        order in which they are registered.  Each callback will be
        called exactly once.

        Any positional arguments after the callback will be passed to
        the callback when it is called.
        �	call_soonr�)r�r#rBrC�
_call_soonr��rvr?r<r�rrrrrH�s
zBaseEventLoop.call_sooncCsDt�|�st�|�r$td|�d���t|�s@td|�d|����dS)Nzcoroutines cannot be used with z()z"a callable object was expected by z(), got )r�iscoroutine�iscoroutinefunctionr8r�)rvr?�methodrrrrC�s
�
��zBaseEventLoop._check_callbackcCs.t�||||�}|jr|jd=|j�|�|S)Nr�)r�Handler�r�r<)rvr?r�r<rrrrrI�s
zBaseEventLoop._call_sooncCs,|jdkrdSt��}||jkr(td��dS)aoCheck that the current thread is the thread running the event loop.

        Non-thread-safe methods of this class make this assumption and will
        likely behave incorrectly when the assumption is violated.

        Should only be called when (self._debug == True).  The caller is
        responsible for checking this condition for performance reasons.
        NzMNon-thread-safe operation invoked on an event loop other than the current one)r�r$r%r})rv�	thread_idrrrrB�s	

�zBaseEventLoop._check_threadcGsB|��|jr|�|d�|�|||�}|jr6|jd=|��|S)z"Like call_soon(), but thread-safe.rr�)r�r#rCrIr�r�rJrrrr�sz"BaseEventLoop.call_soon_threadsafecGsZ|��|jr|�|d�|dkr@|j}|dkr@tj��}||_tj|j|f|��|d�S)N�run_in_executorr�)	r�r#rCr��
concurrentr�ThreadPoolExecutor�wrap_future�submit)rvr9�funcr�rrrrPs
�zBaseEventLoop.run_in_executorcCs&t|tjj�st�dtd�||_dS)Nz{Using the default executor that is not an instance of ThreadPoolExecutor is deprecated and will be prohibited in Python 3.9�)rrQrrRr
r�DeprecationWarningr�r8rrr�set_default_executors�z"BaseEventLoop.set_default_executorcCs�|�d|��g}|r$|�d|���|r8|�d|���|rL|�d|���|r`|�d|���d�|�}t�d|�|��}t�||||||�}	|��|}
d|�d	|
d
d�d|	��}|
|jkr�t�|�n
t�|�|	S)
N�:zfamily=ztype=zproto=zflags=�, zGet address info %szGetting address info z took g@�@z.3fzms: )	r<�joinrr6r�r%�getaddrinfor��info)rvr>r?r@rArB�flags�msg�t0�addrinfo�dtrrr�_getaddrinfo_debugs&


z BaseEventLoop._getaddrinfo_debugr�r@rArBr^c
�s2|jr|j}ntj}|�d|||||||�IdHSrH)r#rcr%r\rP)rvr>r?r@rArBr^�getaddr_funcrrrr\2s�zBaseEventLoop.getaddrinfoc�s|�dtj||�IdHSrH)rPr%�getnameinfo)rv�sockaddrr^rrrrf<s�zBaseEventLoop.getnameinfo)�fallbackc
�s�|jr|��dkrtd��|�||||�z|�||||�IdHWStjk
rl}z
|s\�W5d}~XYnX|�||||�IdHS)Nrzthe socket must be non-blocking)r#�
gettimeoutr&�_check_sendfile_params�_sock_sendfile_nativer�SendfileNotAvailableError�_sock_sendfile_fallback)rvr+�file�offset�countrhrcrrr�
sock_sendfile@s��zBaseEventLoop.sock_sendfilec�st�d|�d���dS)Nz-syscall sendfile is not available for socket z and file {file!r} combination�rrl�rvr+rnrorprrrrkNs
�z#BaseEventLoop._sock_sendfile_nativec

�s�|r|�|�|rt|tj�ntj}t|�}d}zt|rNt|||�}|dkrNq�t|�d|�}|�d|j|�IdH}	|	szq�|�	||d|	��IdH||	7}q2|W�S|dkr�t|d�r�|�||�XdS)Nr�seek)
rt�minr�!SENDFILE_FALLBACK_READBUFFER_SIZE�	bytearrayr$�
memoryviewrP�readinto�sock_sendall)
rvr+rnrorp�	blocksize�buf�
total_sent�view�readrrrrmUs,
��
z%BaseEventLoop._sock_sendfile_fallbackcCs�dt|dd�krtd��|jtjks,td��|dk	rbt|t�sLtd�|���|dkrbtd�|���t|t�sztd�|���|dkr�td�|���dS)N�b�modez$file should be opened in binary modez+only SOCK_STREAM type sockets are supportedz+count must be a positive integer (got {!r})rz0offset must be a non-negative integer (got {!r}))	rr&rAr%r4rr7r8�formatrsrrrrjos2
��
����z$BaseEventLoop._check_sendfile_paramsc�s@g}|�|�|\}}}}}	d}
z�tj|||d�}
|
�d�|dk	r�|D]r\}}}}}z|
�|�Wq�WqHtk
r�}z0d|�d|j����}
t|j|
�}|�|�W5d}~XYqHXqH|���|�	|
|	�IdH|
WStk
�r}z"|�|�|
dk	�r
|
�
��W5d}~XYn |
dk	�r4|
�
��YnXdS)z$Create, bind and connect one socket.N�r@rArBFz*error while attempting to bind on address �: )r<r%�setblocking�bindr)�strerror�lower�errno�pop�sock_connectr�)rvr�	addr_info�local_addr_infos�
my_exceptionsr@�type_rB�_r�r+�laddrrcr_rrr�
_connect_sock�s:



�


zBaseEventLoop._connect_sock)
�sslr@rBr^r+�
local_addrr�r��happy_eyeballs_delay�
interleavec
	�sl|
dk	r|std��|
dkr0|r0|s,td��|}
|dk	rD|sDtd��|dk	rX|
dkrXd}
|dk	sj|dk	�r�|dk	rztd���j||f|tj||�d�IdH}|s�td��|	dk	r܈j|	|tj||�d�IdH��s�td��nd�|
r�t||
�}g�|dk�rH|D]D}z ���|��IdH}W�qvWntk
�r@Y�qYnX�qn.tj���fd	d
�|D�|�d�IdH\}}}|dk�r dd
��D��t	��dk�r��d�nJt
�d��t�fdd
��D���r҈d�td�d�
dd
��D�����n.|dk�rtd��|jtjk�r td|�����j||||
|d�IdH\}}�j�rd|�d�}t�d|||||�||fS)a�Connect to a TCP server.

        Create a streaming transport connection to a given Internet host and
        port: socket family AF_INET or socket.AF_INET6 depending on host (or
        family if specified), socket type SOCK_STREAM. protocol_factory must be
        a callable returning a protocol instance.

        This method is a coroutine which will try to establish the connection
        in the background.  When successful, the coroutine returns a
        (transport, protocol) pair.
        Nz+server_hostname is only meaningful with sslz:You must set server_hostname when using ssl without a host�1ssl_handshake_timeout is only meaningful with sslr�8host/port and sock can not be specified at the same time�r@rArBr^r��!getaddrinfo() returned empty listc3s |]}t��j�|��VqdSrH)�	functools�partialr�)rIra)r�laddr_infosrvrrrK�s��z2BaseEventLoop.create_connection.<locals>.<genexpr>r�cSsg|]}|D]}|�qqSrr)rI�subrcrrrr�sz3BaseEventLoop.create_connection.<locals>.<listcomp>rc3s|]}t|��kVqdSrH�r�rIrc)�modelrrrKszMultiple exceptions: {}rZcss|]}t|�VqdSrHr�r�rrrrK
sz5host and port was not specified and no sock specified�"A Stream Socket was expected, got )r�r%z%r connected to %s:%r: (%r, %r))r&�_ensure_resolvedr%r4r)r[r�r
�staggered_racerr�allr�r[rA�_create_connection_transportr#�get_extra_inforr6)rvr�r>r?r�r@rBr^r+r�r�r�r�r��infosrar�r~r�r)rr�r�rvr�create_connection�s�����


�
��

�
���
�zBaseEventLoop.create_connectionc	�s�|�d�|�}|��}|rHt|t�r*dn|}	|j|||	||||d�}
n|�|||�}
z|IdHWn|
���YnX|
|fS)NF�r�r�r�)r�rtr�boolr�r�r�)rvr+r�r�r�r�r�r�r�r�r~rrrr�%s*
�z*BaseEventLoop._create_connection_transportc
�s�|��rtd��t|dtjj�}|tjjkr:td|����|tjjkr�z|�||||�IdHWStj	k
r�}z
|sx�W5d}~XYnX|s�td|����|�
||||�IdHS)a�Send a file to transport.

        Return the total number of bytes which were sent.

        The method uses high-performance os.sendfile if available.

        file must be a regular file object opened in binary mode.

        offset tells from where to start reading the file. If specified,
        count is the total number of bytes to transmit as opposed to
        sending the file until EOF is reached. File position is updated on
        return or also in case of error in which case file.tell()
        can be used to figure out the number of bytes
        which were sent.

        fallback set to True makes asyncio to manually read and send
        the file when the platform does not support the sendfile syscall
        (e.g. Windows or SSL socket on Unix).

        Raise SendfileNotAvailableError if the system does not support
        sendfile syscall and fallback is False.
        zTransport is closing�_sendfile_compatiblez(sendfile is not supported for transport NzHfallback is disabled and native sendfile is not supported for transport )ryr}rr�
_SendfileMode�UNSUPPORTED�
TRY_NATIVE�_sendfile_nativerrl�_sendfile_fallback)rvr~rnrorprhr�rcrrr�sendfile?s4�����zBaseEventLoop.sendfilec�st�d��dS)Nz!sendfile syscall is not supportedrr)rvrwrnrorprrrr�ns�zBaseEventLoop._sendfile_nativec
�s�|r|�|�|rt|d�nd}t|�}d}t|�}z�|rXt|||�}|dkrX|W�bSt|�d|�}	|�d|j|	�IdH}
|
s�|W�0S|�	�IdH|�
|	d|
��||
7}q6W5|dkr�t|d�r�|�||�|��IdHXdS)Ni@rrt)rtrurwrhr$r�rxrPryr{�write)rvrwrnrorpr{r|r}rBr~rrrrr�rs*
z BaseEventLoop._sendfile_fallbackr�c
�s�tdkrtd��t|tj�s*td|����t|dd�sFtd|�d���|��}tj|||||||dd�}|�	�|�
|�|�|j|�}	|�|j
�}
z|IdHWn.tk
r�|��|	��|
���YnX|jS)	zzUpgrade transport to TLS.

        Return a new transport that *protocol* should start using
        immediately.
        Nz"Python ssl module is not availablez@sslcontext is expected to be an instance of ssl.SSLContext, got �_start_tls_compatibleFz
transport z  is not supported by start_tls())r�r�)r�r}r�
SSLContextr8rrtr	�SSLProtocolrqrrrHrr��
BaseExceptionr�r��_app_transport)rvr~r�r�r�r�r�r��ssl_protocol�
conmade_cb�	resume_cbrrr�	start_tls�sB	�
��
zBaseEventLoop.start_tls)r@rBr^�
reuse_address�
reuse_port�allow_broadcastr+c �s|
dk	r�|
jtjkr"td|
�����s>�s>|s>|s>|s>|s>|	r~t��||||||	d�}d�dd�|��D��}td|�d���|
�d	�d}
�n�s��s�|d
kr�td��||fdff}�n�ttd
��r�|tj	k�r���fD]}|dk	r�t
|t�s�td��qڈ�rx�d
dk�rxz"t
�t�
��j��r.t���WnFtk
�rFYn2tk
�rv}zt�d�|�W5d}~XYnX||f��fff}n�i}d
�fd�ffD]�\}}|dk	�r�t
|t��r�t|�dk�s�td��|j||tj|||d�IdH}|�std��|D]:\}}}}}||f}||k�r0ddg||<||||<�q�q���fdd�|��D�}|�sjtd��g}|tk	�r�|�r�td��ntjdtdd�|D]�\\}}\}}d}
d}
zxtj|tj|d�}
|�r�t|
�|	�r�|
�tj tj!d�|
�d	���r|
�"|���r*|	�s&|�#|
|�IdH|}
Wn^tk
�rl}z |
dk	�rR|
�$�|�%|�W5d}~XYn&|
dk	�r�|
�$��YnX�q��q�|d
�|�}|�&�}|�'|
||
|�}|j(�r��r�t�)d��||�nt�*d�||�z|IdHWn|�$��YnX||fS)zCreate datagram connection.NzA UDP Socket was expected, got )r��remote_addrr@rBr^r�r�r�rZcss$|]\}}|r|�d|��VqdS)�=Nr)rI�k�vrrrrK�sz9BaseEventLoop.create_datagram_endpoint.<locals>.<genexpr>zKsocket modifier keyword arguments can not be used when sock is specified. (�)Frzunexpected address family)NN�AF_UNIXzstring is expected)r�z2Unable to check or remove stale UNIX socket %r: %rrrVz2-tuple is expectedr�r�cs8g|]0\}}�r|ddks�r,|ddks||f�qS)rNrr)rI�key�	addr_pair�r�r�rrr�s�z:BaseEventLoop.create_datagram_endpoint.<locals>.<listcomp>zcan not get address informationz~Passing `reuse_address=True` is no longer supported, as the usage of SO_REUSEPORT in UDP poses a significant security concern.zdThe *reuse_address* parameter has been deprecated as of 3.5.10 and is scheduled for removal in 3.11.)�
stacklevelr�z@Datagram endpoint local_addr=%r remote_addr=%r created: (%r, %r)z2Datagram endpoint remote_addr=%r created: (%r, %r))+rAr%r5r&�dictr[�itemsr�r$r�rrr8�stat�S_ISSOCK�os�st_mode�remove�FileNotFoundErrorr)r�errorr�rr�r��_unsetr
rrWr,r'r(�SO_BROADCASTr�r�r�r<rtr�r#r]r6) rvr�r�r�r@rBr^r�r�r�r+�opts�problems�r_addr�addr_pairs_inforX�err�
addr_infos�idxr��famr��pror�r�r�
local_address�remote_addressrcr�r�r~rr�r�create_datagram_endpoint�s*�������
�

��
��
�

����




���z&BaseEventLoop.create_datagram_endpointc
�s\|dd�\}}t|||||f|dd���}	|	dk	r<|	gS|j||||||d�IdHSdS)NrVrd)rGr\)
rvr�r@rArBr^r�r>r?r]rrrr�Ls�zBaseEventLoop._ensure_resolvedc�s8|j||f|tj||d�IdH}|s4td|�d���|S)N)r@rAr^r�zgetaddrinfo(z) returned empty list)r�r%r4r))rvr>r?r@r^r�rrr�_create_server_getaddrinfoXs�z(BaseEventLoop._create_server_getaddrinfor)	r@r^r+r�r�r�r�r�r�c	�s�t|t�rtd��|dk	r*|dkr*td��|dk	s<�dk	�r"|dk	rLtd��|	dkrhtjdkoftjdk}	g}
|dkr|dg}n$t|t�s�t|t	j
j�s�|g}n|}����fdd	�|D�}tj
|d
�i�IdH}ttj�|��}d}�z|D�]}|\}}}}}zt�|||�}Wn8tjk
�rH�j�r@tjd|||d
d�Yq�YnX|
�|�|	�rl|�tjtjd
�|
�rzt|�t�r�|tjk�r�ttd��r�|�tj tj!d
�z|�"|�Wq�t#k
�r�}z t#|j$d||j%�&�f�d�W5d}~XYq�Xq�d
}W5|�s|
D]}|���qXn4|dk�r4td��|j'tj(k�rPtd|����|g}
|
D]}|�)d��qZt*�|
||||�}|�r�|�+�tj,d�d�IdH�j�r�t�-d|�|S)a1Create a TCP server.

        The host parameter can be a string, in that case the TCP server is
        bound to host and port.

        The host parameter can also be a sequence of strings and in that case
        the TCP server is bound to all hosts of the sequence. If a host
        appears multiple times (possibly indirectly e.g. when hostnames
        resolve to the same IP address), the server is only bound once to that
        host.

        Return a Server object which can be used to stop the service.

        This method is a coroutine.
        z*ssl argument must be an SSLContext or NoneNr�r��posix�cygwinr/csg|]}�j|���d��qS))r@r^)r�)rIr>�r@r^r?rvrrr�s�
�z/BaseEventLoop.create_server.<locals>.<listcomp>r�Fz:create_server() failed to create socket.socket(%r, %r, %r)T��exc_info�IPPROTO_IPV6z0error while attempting to bind on address %r: %sz)Neither host/port nor sock were specifiedr�rr�z
%r is serving).rr�r8r&r�r�r&�platformrrL�abc�Iterablerr�setrQrRrSr�r%r�r#r�warningr<r'r(�SO_REUSEADDRr,r;rr$r��IPV6_V6ONLYr�r)r�r�r�rAr4r�r�r�r�r])rvr�r>r?r@r^r+r�r�r�r�r�r�r��hosts�fsr��	completed�resrF�socktyperB�	canonname�sar�r�rr�r�
create_server`s�
��
��
�

������
�zBaseEventLoop.create_server)r�r�c�sv|jtjkrtd|����|dk	r.|s.td��|j|||dd|d�IdH\}}|jrn|�d�}t�d|||�||fS)	aHandle an accepted connection.

        This is used by servers that accept connections outside of
        asyncio but that use asyncio to handle connections.

        This method is a coroutine.  When completed, the coroutine
        returns a (transport, protocol) pair.
        r�Nr�r/T)r�r�r%z%r handled: (%r, %r))	rAr%r4r&r�r#r�rr6)rvr�r+r�r�r~r�rrr�connect_accepted_socket�s$��
z%BaseEventLoop.connect_accepted_socketc�sd|�}|��}|�|||�}z|IdHWn|���YnX|jr\t�d|��||�||fS)Nz Read pipe %r connected: (%r, %r))rtr�r�r#rr6�fileno�rvr�r�r�r�r~rrr�connect_read_pipe�s�zBaseEventLoop.connect_read_pipec�sd|�}|��}|�|||�}z|IdHWn|���YnX|jr\t�d|��||�||fS)Nz!Write pipe %r connected: (%r, %r))rtr�r�r#rr6r�r�rrr�connect_write_pipes�z BaseEventLoop.connect_write_pipecCs�|g}|dk	r"|�dt|����|dk	rJ|tjkrJ|�dt|����n8|dk	rf|�dt|����|dk	r�|�dt|����t�d�|��dS)Nzstdin=zstdout=stderr=zstdout=zstderr=� )r<r"rr rr6r[)rvr_r�r�r�r]rrr�_log_subprocessszBaseEventLoop._log_subprocess)	r�r�r��universal_newlinesr�r��encoding�errors�textc	�s�t|ttf�std��|r"td��|s.td��|dkr>td��|rJtd��|	dk	rZtd��|
dk	rjtd��|�}
d}|jr�d	|}|�||||�|j|
|d
||||f|�IdH}|jr�|dk	r�t�d||�||
fS)Nzcmd must be a string� universal_newlines must be Falsezshell must be Truer�bufsize must be 0�text must be False�encoding must be None�errors must be Nonezrun shell command %rT�%s: %r)	rr6rr&r#r�r�rr])rvr��cmdr�r�r�r�r�r�rrrr�r��	debug_logr~rrr�subprocess_shellsB��
zBaseEventLoop.subprocess_shellc	�s�|rtd��|rtd��|dkr(td��|r4td��|	dk	rDtd��|
dk	rTtd��|f|}|�}d}|jr�d|��}|�||||�|j||d	||||f|
�IdH}|jr�|dk	r�t�d
||�||fS)Nrzshell must be Falserrrrrzexecute program Fr)r&r#r�r�rr])rvr��programr�r�r�r�r�r�rrrr�r��
popen_argsr�r
r~rrr�subprocess_execCs@

��
zBaseEventLoop.subprocess_execcCs|jS)zKReturn an exception handler, or None if the default one is in use.
        )r�r�rrr�get_exception_handleresz#BaseEventLoop.get_exception_handlercCs(|dk	rt|�std|����||_dS)a�Set handler as the new event loop exception handler.

        If handler is None, the default exception handler will
        be set.

        If handler is a callable object, it should have a
        signature matching '(loop, context)', where 'loop'
        will be a reference to the active event loop, 'context'
        will be a dict object (see `call_exception_handler()`
        documentation for details about context).
        Nz+A callable object or None is expected, got )r�r8r�)rv�handlerrrr�set_exception_handlerjsz#BaseEventLoop.set_exception_handlerc	Cs|�d�}|sd}|�d�}|dk	r6t|�||jf}nd}d|kr`|jdk	r`|jjr`|jj|d<|g}t|�D]�}|dkr|qn||}|dkr�d	�t�|��}d
}||�	�7}n2|dkr�d	�t�|��}d}||�	�7}nt
|�}|�|�d|���qntj
d
�|�|d�dS)aEDefault exception handler.

        This is called when an exception occurs and no exception
        handler is set, and can be called by a custom exception
        handler that wants to defer to the default behavior.

        This default handler logs the error message and other
        context-dependent information.  In debug mode, a truncated
        stack trace is also appended showing where the given object
        (e.g. a handle or future or task) was created, if any.

        The context parameter has the same meaning as in
        `call_exception_handler()`.
        rz!Unhandled exception in event loopr]NF�source_tracebackZhandle_traceback>r]rr/z+Object created at (most recent call last):
z+Handle created at (most recent call last):
r��
r�)�getrA�
__traceback__r�r��sortedr[�	traceback�format_list�rstriprr<rr�)	rvr<rr]r��	log_linesr��value�tbrrr�default_exception_handler{s<

���z'BaseEventLoop.default_exception_handlercCs�|jdkrVz|�|�Wq�ttfk
r2�Yq�tk
rRtjddd�Yq�Xn�z|�||�Wn�ttfk
r��Ynttk
r�}zVz|�d||d��Wn:ttfk
r��Yn"tk
r�tjddd�YnXW5d}~XYnXdS)aDCall the current event loop's exception handler.

        The context argument is a dict containing the following keys:

        - 'message': Error message;
        - 'exception' (optional): Exception object;
        - 'future' (optional): Future instance;
        - 'task' (optional): Task instance;
        - 'handle' (optional): Handle instance;
        - 'protocol' (optional): Protocol instance;
        - 'transport' (optional): Transport instance;
        - 'socket' (optional): Socket instance;
        - 'asyncgen' (optional): Asynchronous generator that caused
                                 the exception.

        New keys maybe introduced in the future.

        Note: do not overload this method in an event loop subclass.
        For custom exception handling, use the
        `set_exception_handler()` method.
        Nz&Exception in default exception handlerTr�z$Unhandled error in exception handler)rr]r<zeException in default exception handler while handling an unexpected error in custom exception handler)r�rr^r_r�rr�)rvr<rcrrrr�s4
���z$BaseEventLoop.call_exception_handlercCs>t|tj�std��|jrdSt|tj�r.t�|j�|�dS)z3Add a Handle to _scheduled (TimerHandle) or _ready.zA Handle is required hereN)rrrNr��
_cancelledrDr�r<�rvrrrr�
_add_callback�s
zBaseEventLoop._add_callbackcCs|�|�|��dS)z6Like _add_callback() but called from a signal handler.N)r r�rrrr�_add_callback_signalsafe�s
z&BaseEventLoop._add_callback_signalsafecCs|jr|jd7_dS)z3Notification that a TimerHandle has been cancelled.rN)r�r�rrrr�_timer_handle_cancelled�sz%BaseEventLoop._timer_handle_cancelledc	Cs�t|j�}|tkr`|j|tkr`g}|jD]}|jr<d|_q*|�|�q*t�|�||_d|_n4|jr�|jdjr�|jd8_t�	|j�}d|_q`d}|j
s�|jr�d}n*|jr�|jdj}t
td||���t�}|j�|�}|�|�|��|j}|j�r:|jd}|j|k�r�q:t�	|j�}d|_|j
�|�q�t|j
�}t|�D]|}	|j
��}|j�rf�qL|j�r�zD||_|��}
|��|��|
}||jk�r�t�dt|�|�W5d|_Xn|���qLd}dS)z�Run one full iteration of the event loop.

        This calls all currently ready callbacks, polls for I/O,
        schedules the resulting callbacks, and finally schedules
        'call_later' callbacks.
        FrrNzExecuting %s took %.3f seconds)rr��_MIN_SCHEDULED_TIMER_HANDLESr��%_MIN_CANCELLED_TIMER_HANDLES_FRACTIONrr<rE�heapify�heappopr�r��_whenru�maxr��MAXIMUM_SELECT_TIMEOUT�	_selector�selectrr��range�popleftr#r��_runr�rr�r)rv�sched_count�
new_scheduledr�timeoutrGr�end_time�ntodo�ir`rbrrrr*�sj
��





�
zBaseEventLoop._run_oncecCsHt|�t|j�krdS|r2t��|_t�tj�nt�|j�||_dSrH)r�r�r&�#get_coroutine_origin_tracking_depthr��#set_coroutine_origin_tracking_depthr�DEBUG_STACK_DEPTH�rv�enabledrrrr"Fs���z,BaseEventLoop._set_coroutine_origin_trackingcCs|jSrH)r#r�rrrr�UszBaseEventLoop.get_debugcCs ||_|��r|�|j|�dSrH)r#r�rr"r8rrrr�XszBaseEventLoop.set_debug)N)N)NNN)NN)NN)N)r)rN)N)NN)FN)rN)NN)NN)Sr�r�r�rxr�rtr�r�r�r�r�r�r�r�r�r�rr�rrrrr,r4rar�r�r
rr;r�r�rAr=rHrCrIrBrrPrXrcr\rfrqrkrmrjr�r�r�r�r�r�r�r�r�r%r4r�r�r9�
AI_PASSIVEr�r�r�r�r�rrrrrrrrr r!r"r*r"r�r�rrrrr�sF���
�
�
�
�
		&	
	�

�
%���
�/�/���	��w��%�"29Nr)rr)r)7�__doc__rL�collections.abc�concurrent.futuresrQr�rErQr�r%r�rr$r�rr&r
r�r��ImportErrorr/rrrrrrr	r
rrr
�logr�__all__r#r$r$r;r)�objectr�rr"r,rGr[rdrg�Protocolrh�AbstractServerr��AbstractEventLooprrrrr�<module>sd

		
;


Do�h�(bytecode of module 'asyncio.base_events'�u��b.���h)��N}�(hBZ�@sRdZddlZddlmZddlmZdZdZdZd	d
�Z	dd�Z
e�Zd
d�Z
dS)��N)�	get_ident�)�format_helpers�PENDING�	CANCELLED�FINISHEDcCst|jd�o|jdk	S)z�Check for a Future.

    This returns True when obj is a Future instance or is advertising
    itself as duck-type compatible by setting _asyncio_future_blocking.
    See comment in Future for more details.
    �_asyncio_future_blockingN)�hasattr�	__class__r	)�objrr�*/usr/lib/python3.8/asyncio/base_futures.py�isfutures�rcCs�t|�}|sd}dd�}|dkr2||dd�}n`|dkr`d�||dd�||dd��}n2|dkr�d�||dd�|d||d	d��}d
|�d�S)�#helper function for Future.__repr__�cSst�|d�S)Nr)r�_format_callback_source)�callbackrrr
�	format_cbsz$_format_callbacks.<locals>.format_cbrr�z{}, {}z{}, <{} more>, {}���zcb=[�])�len�format)�cb�sizerrrr
�_format_callbackss&�rc	Cs�|j��g}|jtkr�|jdk	r4|�d|j���nTt|�t�f}|tkrPd}n(t�|�zt
�|j�}W5t�	|�X|�d|���|j
r�|�t|j
��|jr�|jd}|�d|d�d|d	���|S)
rNz
exception=z...zresult=rzcreated at r�:r)�_state�lower�	_FINISHED�
_exception�append�idr�
_repr_running�add�discard�reprlib�repr�_result�
_callbacksr�_source_traceback)�future�info�key�result�framerrr
�_future_repr_info7s$



r0)�__all__r&�_threadrrr�_PENDING�
_CANCELLEDrrr�setr#r0rrrr
�<module>s�h�)bytecode of module 'asyncio.base_futures'�u��b.���$h)��N}�(hB�$�@sxddlZddlZddlZddlmZddlmZddlmZGdd�dej�Z	Gdd	�d	ej
�ZGd
d�deej�Z
dS)�N�)�	protocols)�
transports)�loggercs�eZdZd0�fdd�	Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	e
jfdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Z�ZS)1�BaseSubprocessTransportNc
	s&t��|
�d|_||_||_d|_d|_d|_g|_t	�
�|_i|_d|_
|tjkr`d|jd<|tjkrtd|jd<|tjkr�d|jd<z"|jf||||||d�|��Wn|���YnX|jj|_|j|jd<|j���rt|ttf�r�|}n|d}t�d||j�|j�|�|	��dS)NFrr�)�args�shell�stdin�stdout�stderr�bufsize�
subprocesszprocess %r created: pid %s)�super�__init__�_closed�	_protocol�_loop�_proc�_pid�_returncode�
_exit_waiters�collections�deque�_pending_calls�_pipes�	_finishedr�PIPE�_start�close�pid�_extra�	get_debug�
isinstance�bytes�strr�debug�create_task�_connect_pipes)
�self�loop�protocolrr	r
rrr
�waiter�extra�kwargs�program��	__class__��-/usr/lib/python3.8/asyncio/base_subprocess.pyrsL






��

�z BaseSubprocessTransport.__init__cCs|jjg}|jr|�d�|jdk	r6|�d|j���|jdk	rT|�d|j���n |jdk	rj|�d�n
|�d�|j�d�}|dk	r�|�d|j���|j�d�}|j�d	�}|dk	r�||kr�|�d
|j���n6|dk	r�|�d|j���|dk	�r|�d|j���d
�	d�
|��S)N�closedzpid=zreturncode=�runningznot startedrzstdin=rrzstdout=stderr=zstdout=zstderr=z<{}>� )r1�__name__r�appendrrr�get�pipe�format�join)r)�infor
rrr2r2r3�__repr__7s,






z BaseSubprocessTransport.__repr__cKst�dS�N)�NotImplementedError)r)rr	r
rrr
r.r2r2r3rTszBaseSubprocessTransport._startcCs
||_dSr?�r)r)r+r2r2r3�set_protocolWsz$BaseSubprocessTransport.set_protocolcCs|jSr?rA�r)r2r2r3�get_protocolZsz$BaseSubprocessTransport.get_protocolcCs|jSr?)rrCr2r2r3�
is_closing]sz"BaseSubprocessTransport.is_closingcCs�|jr
dSd|_|j��D]}|dkr(q|j��q|jdk	r�|jdkr�|j��dkr�|j�	�rlt
�d|�z|j��Wnt
k
r�YnXdS)NTz$Close running child process: kill %r)rr�valuesr:rrr�pollrr"r�warning�kill�ProcessLookupError)r)�protor2r2r3r`s$
��
zBaseSubprocessTransport.closecCs&|js"|d|��t|d�|��dS)Nzunclosed transport )�source)r�ResourceWarningr)r)�_warnr2r2r3�__del__{szBaseSubprocessTransport.__del__cCs|jSr?)rrCr2r2r3�get_pid�szBaseSubprocessTransport.get_pidcCs|jSr?)rrCr2r2r3�get_returncode�sz&BaseSubprocessTransport.get_returncodecCs||jkr|j|jSdSdSr?)rr:)r)�fdr2r2r3�get_pipe_transport�s
z*BaseSubprocessTransport.get_pipe_transportcCs|jdkrt��dSr?)rrJrCr2r2r3�_check_proc�s
z#BaseSubprocessTransport._check_proccCs|��|j�|�dSr?)rTr�send_signal)r)�signalr2r2r3rU�sz#BaseSubprocessTransport.send_signalcCs|��|j��dSr?)rTr�	terminaterCr2r2r3rW�sz!BaseSubprocessTransport.terminatecCs|��|j��dSr?)rTrrIrCr2r2r3rI�szBaseSubprocessTransport.killc	
�spz�j}�j}|jdk	rB|��fdd�|j�IdH\}}|�jd<|jdk	rv|��fdd�|j�IdH\}}|�jd<|jdk	r�|��fdd�|j�IdH\}}|�jd<�jdk	s�t	�|�
�jj���jD]\}}|j
|f|��q�d�_Wn\t
tfk
�r�Yn`tk
�rL}z"|dk	�r<|���s<|�|�W5d}~XYn X|dk	�rl|���sl|�d�dS)Ncs
t�d�S)Nr)�WriteSubprocessPipeProtor2rCr2r3�<lambda>��z8BaseSubprocessTransport._connect_pipes.<locals>.<lambda>rcs
t�d�S)Nr��ReadSubprocessPipeProtor2rCr2r3rY�rZrcs
t�d�S)Nrr[r2rCr2r3rY�rZr)rrr
�connect_write_piperr�connect_read_piperr�AssertionError�	call_soonr�connection_made�
SystemExit�KeyboardInterrupt�
BaseException�	cancelled�
set_exception�
set_result)	r)r,�procr*�_r:�callback�data�excr2rCr3r(�sB

�


�


�

z&BaseSubprocessTransport._connect_pipescGs2|jdk	r|j�||f�n|jj|f|��dSr?)rr8rr`)r)�cbrkr2r2r3�_call�s
zBaseSubprocessTransport._callcCs|�|jj||�|��dSr?)rnr�pipe_connection_lost�_try_finish)r)rRrlr2r2r3�_pipe_connection_lost�sz-BaseSubprocessTransport._pipe_connection_lostcCs|�|jj||�dSr?)rnr�pipe_data_received)r)rRrkr2r2r3�_pipe_data_received�sz+BaseSubprocessTransport._pipe_data_receivedcCs�|dk	st|��|jdks$t|j��|j��r<t�d||�||_|jjdkrV||j_|�|j	j
�|��|jD]}|�
�sr|�|�qrd|_dS)Nz%r exited with return code %r)r_rrr"rr=r�
returncodernr�process_exitedrprrerg)r)rtr,r2r2r3�_process_exited�s

z'BaseSubprocessTransport._process_exitedc�s0|jdk	r|jS|j��}|j�|�|IdHS)zdWait until the process exit and return the process return code.

        This method is a coroutine.N)rr�
create_futurerr8)r)r,r2r2r3�_wait�s


zBaseSubprocessTransport._waitcCsH|jr
t�|jdkrdStdd�|j��D��rDd|_|�|jd�dS)Ncss|]}|dk	o|jVqdSr?)�disconnected)�.0�pr2r2r3�	<genexpr>�s�z6BaseSubprocessTransport._try_finish.<locals>.<genexpr>T)rr_r�allrrFrn�_call_connection_lostrCr2r2r3rp�s

�z#BaseSubprocessTransport._try_finishcCs*z|j�|�W5d|_d|_d|_XdSr?)rrr�connection_lost�r)rlr2r2r3r~�s
z-BaseSubprocessTransport._call_connection_lost)NN)r7�
__module__�__qualname__rr>rrBrDrEr�warnings�warnrOrPrQrSrTrUrWrIr(rnrqrsrvrxrpr~�
__classcell__r2r2r0r3r
s2�+&	rc@s<eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
S)rXcCs||_||_d|_d|_dS)NF)rhrRr:ry)r)rhrRr2r2r3rsz!WriteSubprocessPipeProto.__init__cCs
||_dSr?)r:)r)�	transportr2r2r3rasz(WriteSubprocessPipeProto.connection_madecCs d|jj�d|j�d|j�d�S)N�<z fd=z pipe=�>)r1r7rRr:rCr2r2r3r>
sz!WriteSubprocessPipeProto.__repr__cCs d|_|j�|j|�d|_dS)NT)ryrhrqrRr�r2r2r3r
sz(WriteSubprocessPipeProto.connection_lostcCs|jj��dSr?)rhr�
pause_writingrCr2r2r3r�sz&WriteSubprocessPipeProto.pause_writingcCs|jj��dSr?)rhr�resume_writingrCr2r2r3r�sz'WriteSubprocessPipeProto.resume_writingN)	r7r�r�rrar>rr�r�r2r2r2r3rX�srXc@seZdZdd�ZdS)r\cCs|j�|j|�dSr?)rhrsrR)r)rkr2r2r3�
data_receivedsz%ReadSubprocessPipeProto.data_receivedN)r7r�r�r�r2r2r2r3r\sr\)rrr��rr�logr�SubprocessTransportr�BaseProtocolrX�Protocolr\r2r2r2r3�<module>sv��h�,bytecode of module 'asyncio.base_subprocess'�u��b.���h)��N}�(hB��@sDddlZddlZddlmZddlmZdd�Zdd�Zd	d
�ZdS)�N�)�base_futures)�
coroutinescCsnt�|�}|jrd|d<|�dd|���t�|j�}|�dd|�d��|jdk	rj|�dd	|j���|S)
NZ
cancellingrrzname=%r�zcoro=<�>�z	wait_for=)	r�_future_repr_info�_must_cancel�insert�get_namer�_format_coroutine�_coro�_fut_waiter)�task�info�coro�r�(/usr/lib/python3.8/asyncio/base_tasks.py�_task_repr_infos

rcCs�g}t|jd�r|jj}n0t|jd�r0|jj}nt|jd�rF|jj}nd}|dk	r�|dk	r�|dk	rt|dkrlq�|d8}|�|�|j}qR|��nH|jdk	r�|jj	}|dk	r�|dk	r�|dkr�q�|d8}|�|j
�|j}q�|S)N�cr_frame�gi_frame�ag_framerr)�hasattrr
rrr�append�f_back�reverse�
_exception�
__traceback__�tb_frame�tb_next)r�limit�frames�f�tbrrr�_task_get_stacks6





r$cCs�g}t�}|j|d�D]Z}|j}|j}|j}|j}	||krN|�|�t�|�t�	|||j
�}
|�|||	|
f�q|j}|s�t
d|��|d�n2|dk	r�t
d|�d�|d�nt
d|�d�|d�tj||d�|dk	r�t�|j|�D]}
t
|
|dd�q�dS)	N)r z
No stack for )�filezTraceback for z (most recent call last):z
Stack for �)r%�end)�set�	get_stack�f_lineno�f_code�co_filename�co_name�add�	linecache�
checkcache�getline�	f_globalsrr�print�	traceback�
print_list�format_exception_only�	__class__)rr r%�extracted_list�checkedr"�lineno�co�filename�name�line�excrrr�_task_print_stack<s,

r@)r/r4r&rrrr$r@rrrr�<module>s#�h�'bytecode of module 'asyncio.base_tasks'�u��b.��vh)��N}�(hB5�@s2ddlZdZdZdZdZdZGdd�dej�ZdS)	�N���
gN@ic@s$eZdZe��Ze��Ze��ZdS)�
_SendfileModeN)�__name__�
__module__�__qualname__�enum�auto�UNSUPPORTED�
TRY_NATIVE�FALLBACK�rr�'/usr/lib/python3.8/asyncio/constants.pyrsr)r	�!LOG_THRESHOLD_FOR_CONNLOST_WRITES�ACCEPT_RETRY_DELAY�DEBUG_STACK_DEPTH�SSL_HANDSHAKE_TIMEOUT�!SENDFILE_FALLBACK_READBUFFER_SIZE�Enumrrrrr�<module>s�h�&bytecode of module 'asyncio.constants'�u��b.��0h)��N}�(hB��@s�dZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZddl
mZddl
m
Z
ddlmZdd	�Ze�ZGd
d�d�Zdd
�Ze�Zdd�ZejejejjefZe�Zdd�Zdd�ZdS))�	coroutine�iscoroutinefunction�iscoroutine�N�)�base_futures)�	constants)�format_helpers)�loggercCs"tjjp tjjo ttj�d��S)NZPYTHONASYNCIODEBUG)�sys�flags�dev_mode�ignore_environment�bool�os�environ�get�rr�(/usr/lib/python3.8/asyncio/coroutines.py�_is_debug_modes�rc@s�eZdZddd�Zdd�Zdd�Zdd	�Zd
d�Zddd
�Zdd�Z	e
dd��Ze
dd��Ze
dd��Z
dd�Ze
dd��Zdd�ZdS)�CoroWrapperNcCsZt�|�st�|�st|��||_||_t�t�	d��|_
t|dd�|_t|dd�|_
dS)Nr�__name__�__qualname__)�inspect�isgeneratorr�AssertionError�gen�funcr�
extract_stackr
�	_getframe�_source_traceback�getattrrr)�selfrrrrr�__init__'szCoroWrapper.__init__cCsJt|�}|jr4|jd}|d|d�d|d��7}d|jj�d|�d�S)	N���z
, created at r�:r�<� �>)�_format_coroutiner�	__class__r)r!�	coro_repr�framerrr�__repr__/s

zCoroWrapper.__repr__cCs|S�Nr�r!rrr�__iter__7szCoroWrapper.__iter__cCs|j�d�Sr-�r�sendr.rrr�__next__:szCoroWrapper.__next__cCs|j�|�Sr-r0)r!�valuerrrr1=szCoroWrapper.sendcCs|j�|||�Sr-)r�throw)r!�typer3�	tracebackrrrr4@szCoroWrapper.throwcCs
|j��Sr-)r�closer.rrrr7CszCoroWrapper.closecCs|jjSr-)r�gi_framer.rrrr8FszCoroWrapper.gi_framecCs|jjSr-)r�
gi_runningr.rrrr9JszCoroWrapper.gi_runningcCs|jjSr-)r�gi_coder.rrrr:NszCoroWrapper.gi_codecCs|Sr-rr.rrr�	__await__RszCoroWrapper.__await__cCs|jjSr-)r�gi_yieldfromr.rrrr<UszCoroWrapper.gi_yieldfromcCs�t|dd�}t|dd�}|dk	r||jdkr||�d�}t|dd�}|rrd�t�|��}|dtj�d	�7}||��7}t�	|�dS)
Nrr8r#z was never yielded fromrr�zB
Coroutine object created at (most recent call last, truncated to z last lines):
)
r �f_lasti�joinr6�format_listr�DEBUG_STACK_DEPTH�rstripr	�error)r!rr+�msg�tbrrr�__del__Ys
zCoroWrapper.__del__)N)NN)r�
__module__rr"r,r/r2r1r4r7�propertyr8r9r:r;r<rFrrrrr$s"





rcsztjdtdd�t���r�St���r.��nt����fdd���t�	���t
sX�}nt�����fdd��}t|_|S)z�Decorator to mark coroutines.

    If the coroutine is not yielded from before it is destroyed,
    an error message is logged.
    zN"@coroutine" decorator is deprecated since Python 3.8, use "async def" instead�)�
stacklevelc?sr�||�}t�|�s(t�|�s(t|t�r4|EdH}n:z
|j}Wntk
rRYnXt|tj	j
�rn|�EdH}|Sr-)r�isfuturerr�
isinstancerr;�AttributeError�collections�abc�	Awaitable)�args�kw�res�
await_meth�rrr�corozs
�
zcoroutine.<locals>.corocs@t�||��d�}|jr |jd=t�dd�|_t�dd�|_|S)NrUr#rr)rrr rr)rQ�kwds�w�rVrrr�wrapper�szcoroutine.<locals>.wrapper)�warnings�warn�DeprecationWarningrr�isgeneratorfunction�	functools�wraps�typesr�_DEBUG�
_is_coroutine)rrZrrYrris"�


rcCst�|�pt|dd�tkS)z6Return True if func is a decorated coroutine function.rcN)rrr rcrUrrrr�s
�rcCs@t|�tkrdSt|t�r8tt�dkr4t�t|��dSdSdS)z)Return True if obj is a coroutine object.T�dFN)r5�_iscoroutine_typecacherL�_COROUTINE_TYPES�len�add)�objrrrr�s
rc
stt|�st�t|t���fdd�}dd�}d}t|d�rF|jrF|j}nt|d�r\|jr\|j}||�}|s~||�rz|�d�S|Sd}t|d�r�|jr�|j}nt|d	�r�|jr�|j}|j	p�d
}d}��r0|j
dk	�r0t�|j
��s0t
�|j
�}|dk	r�|\}}|dk�r|�d|�d
|��}	n|�d|�d
|��}	n@|dk	�rV|j}|�d|�d
|��}	n|j}|�d|�d
|��}	|	S)Ncs`�rt�|jdi�St|d�r,|jr,|j}n*t|d�rD|jrD|j}ndt|�j�d�}|�d�S)Nrrrr%z without __name__>z())r�_format_callbackr�hasattrrrr5)rV�	coro_name��is_corowrapperrr�get_name�sz#_format_coroutine.<locals>.get_namecSsHz|jWStk
rBz|jWYStk
r<YYdSXYnXdS)NF)�
cr_runningrMr9)rVrrr�
is_running�sz%_format_coroutine.<locals>.is_running�cr_coder:z runningr8�cr_framez<empty co_filename>rz done, defined at r$z running, defined at z running at )rrrLrrkrrr:r8rs�co_filenamerrr^r�_get_function_source�f_lineno�co_firstlineno)
rVrorq�	coro_coderl�
coro_frame�filename�lineno�sourcer*rrmrr(�sL
	

�
�

r() �__all__�collections.abcrNr_rrr
r6rar[r=rrr�logr	rrbrr�objectrcr�
CoroutineType�
GeneratorTyperO�	Coroutinerf�setrerr(rrrr�<module>s2E8��h�'bytecode of module 'asyncio.coroutines'�u��b.���mh)��N}�(hB�m�@s|dZdZddlZddlZddlZddlZddlZddlZddlm	Z	ddlm
Z
Gdd�d�ZGd	d
�d
e�ZGdd�d�Z
Gd
d�d�ZGdd�d�ZGdd�de�Zdae��ZGdd�dej�Ze�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Z d)d*�Z!eZ"eZ#eZ$eZ%zdd+l&mZmZmZmZWne'k
�rfYnXeZ(eZ)eZ*eZ+dS),z!Event loop and event loop policy.)�AbstractEventLoopPolicy�AbstractEventLoop�AbstractServer�Handle�TimerHandle�get_event_loop_policy�set_event_loop_policy�get_event_loop�set_event_loop�new_event_loop�get_child_watcher�set_child_watcher�_set_running_loop�get_running_loop�_get_running_loop�N�)�format_helpers)�
exceptionsc@sFeZdZdZdZddd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dS)rz1Object returned by callback registration methods.)�	_callback�_args�
_cancelled�_loop�_source_traceback�_repr�__weakref__�_contextNcCs\|dkrt��}||_||_||_||_d|_d|_|j��rRt	�
t�d��|_
nd|_
dS)NFr)�contextvars�copy_contextrrrrrr�	get_debugr�
extract_stack�sys�	_getframer)�self�callback�args�loop�context�r'�$/usr/lib/python3.8/asyncio/events.py�__init__ s
�zHandle.__init__cCsl|jjg}|jr|�d�|jdk	r:|�t�|j|j��|jrh|jd}|�d|d�d|d���|S)N�	cancelled���zcreated at r�:r)	�	__class__�__name__r�appendrr�_format_callback_sourcerr)r"�info�framer'r'r(�
_repr_info/s


�
zHandle._repr_infocCs(|jdk	r|jS|��}d�d�|��S)Nz<{}>� )rr3�format�join)r"r1r'r'r(�__repr__;s
zHandle.__repr__cCs0|js,d|_|j��r t|�|_d|_d|_dS�NT)rrr�reprrrr�r"r'r'r(�cancelAs

z
Handle.cancelcCs|jS�N)rr:r'r'r(r*LszHandle.cancelledc
Cs�z|jj|jf|j��Wn|ttfk
r4�Yndtk
r�}zFt�|j|j�}d|��}|||d�}|j	rz|j	|d<|j
�|�W5d}~XYnXd}dS)NzException in callback )�message�	exception�handle�source_traceback)r�runrr�
SystemExit�KeyboardInterrupt�
BaseExceptionrr0rr�call_exception_handler)r"�exc�cb�msgr&r'r'r(�_runOs$�
�
zHandle._run)N)r.�
__module__�__qualname__�__doc__�	__slots__r)r3r7r;r*rIr'r'r'r(rs
rcs�eZdZdZddgZd�fdd�	Z�fdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Zdd�Z
�fdd�Zdd�Z�ZS)rz7Object returned by timed callback registration methods.�
_scheduled�_whenNcs<|dk	st�t��||||�|jr,|jd=||_d|_dS)Nr+F)�AssertionError�superr)rrOrN)r"�whenr#r$r%r&�r-r'r(r)hszTimerHandle.__init__cs0t���}|jrdnd}|�|d|j���|S)N�rzwhen=)rQr3r�insertrO)r"r1�posrSr'r(r3ps
zTimerHandle._repr_infocCs
t|j�Sr<)�hashrOr:r'r'r(�__hash__vszTimerHandle.__hash__cCs|j|jkSr<�rO�r"�otherr'r'r(�__lt__yszTimerHandle.__lt__cCs|j|jkrdS|�|�Sr8�rO�__eq__rZr'r'r(�__le__|szTimerHandle.__le__cCs|j|jkSr<rYrZr'r'r(�__gt__�szTimerHandle.__gt__cCs|j|jkrdS|�|�Sr8r]rZr'r'r(�__ge__�szTimerHandle.__ge__cCs>t|t�r:|j|jko8|j|jko8|j|jko8|j|jkStSr<)�
isinstancerrOrrr�NotImplementedrZr'r'r(r^�s

�
�
�zTimerHandle.__eq__cCs|�|�}|tkrtS|Sr<)r^rc)r"r[�equalr'r'r(�__ne__�s
zTimerHandle.__ne__cs |js|j�|�t���dSr<)rr�_timer_handle_cancelledrQr;r:rSr'r(r;�szTimerHandle.cancelcCs|jS)z�Return a scheduled callback time.

        The time is an absolute timestamp, using the same time
        reference as loop.time().
        rYr:r'r'r(rR�szTimerHandle.when)N)r.rJrKrLrMr)r3rXr\r_r`rar^rer;rR�
__classcell__r'r'rSr(rcsrc@sPeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�ZdS)rz,Abstract server returned by create_server().cCst�dS)z5Stop serving.  This leaves existing connections open.N��NotImplementedErrorr:r'r'r(�close�szAbstractServer.closecCst�dS)z4Get the event loop the Server object is attached to.Nrhr:r'r'r(�get_loop�szAbstractServer.get_loopcCst�dS)z3Return True if the server is accepting connections.Nrhr:r'r'r(�
is_serving�szAbstractServer.is_servingc�st�dS)z�Start accepting connections.

        This method is idempotent, so it can be called when
        the server is already being serving.
        Nrhr:r'r'r(�
start_serving�szAbstractServer.start_servingc�st�dS)z�Start accepting connections until the coroutine is cancelled.

        The server is closed when the coroutine is cancelled.
        Nrhr:r'r'r(�
serve_forever�szAbstractServer.serve_foreverc�st�dS)z*Coroutine to wait until service is closed.Nrhr:r'r'r(�wait_closed�szAbstractServer.wait_closedc�s|Sr<r'r:r'r'r(�
__aenter__�szAbstractServer.__aenter__c�s|��|��IdHdSr<)rjro)r"rFr'r'r(�	__aexit__�szAbstractServer.__aexit__N)r.rJrKrLrjrkrlrmrnrorprqr'r'r'r(r�src@sVeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�dd�Zd d!�Zd"d#�Zd$d%�Zd&d&d&d&d'�d(d)�Zdud*d+�Zdvdd&d&d&ddddddd,�
d-d.�Zdwejejdd/ddddd0d1�	d2d3�Zdxd0d4�d5d6�Zd7ddd8�d9d:�Zdyddddd;�d<d=�Zdzdd/ddd0d>�d?d@�Zd{d&d&d&dddddA�dBdC�Z dDdE�Z!dFdG�Z"e#j$e#j$e#j$dH�dIdJ�Z%e#j$e#j$e#j$dH�dKdL�Z&dMdN�Z'dOdP�Z(dQdR�Z)dSdT�Z*dUdV�Z+dWdX�Z,dYdZ�Z-d[d\�Z.d]d^�Z/d|dd4�d_d`�Z0dadb�Z1dcdd�Z2dedf�Z3dgdh�Z4didj�Z5dkdl�Z6dmdn�Z7dodp�Z8dqdr�Z9dsdt�Z:dS)}rzAbstract event loop.cCst�dS)z*Run the event loop until stop() is called.Nrhr:r'r'r(�run_forever�szAbstractEventLoop.run_forevercCst�dS)zpRun the event loop until a Future is done.

        Return the Future's result, or raise its exception.
        Nrh)r"�futurer'r'r(�run_until_complete�sz$AbstractEventLoop.run_until_completecCst�dS)z�Stop the event loop as soon as reasonable.

        Exactly how soon that is may depend on the implementation, but
        no more I/O callbacks should be scheduled.
        Nrhr:r'r'r(�stop�szAbstractEventLoop.stopcCst�dS)z3Return whether the event loop is currently running.Nrhr:r'r'r(�
is_running�szAbstractEventLoop.is_runningcCst�dS)z*Returns True if the event loop was closed.Nrhr:r'r'r(�	is_closed�szAbstractEventLoop.is_closedcCst�dS)z�Close the loop.

        The loop should not be running.

        This is idempotent and irreversible.

        No other methods should be called after this one.
        Nrhr:r'r'r(rj�s	zAbstractEventLoop.closec�st�dS)z,Shutdown all active asynchronous generators.Nrhr:r'r'r(�shutdown_asyncgens�sz$AbstractEventLoop.shutdown_asyncgenscCst�dS)z3Notification that a TimerHandle has been cancelled.Nrh)r"r?r'r'r(rf�sz)AbstractEventLoop._timer_handle_cancelledcGs|jd|f|��S)Nr)�
call_later�r"r#r$r'r'r(�	call_soonszAbstractEventLoop.call_sooncGst�dSr<rh)r"�delayr#r$r'r'r(ryszAbstractEventLoop.call_latercGst�dSr<rh)r"rRr#r$r'r'r(�call_atszAbstractEventLoop.call_atcCst�dSr<rhr:r'r'r(�timeszAbstractEventLoop.timecCst�dSr<rhr:r'r'r(�
create_futureszAbstractEventLoop.create_futureN)�namecCst�dSr<rh)r"�coror�r'r'r(�create_taskszAbstractEventLoop.create_taskcGst�dSr<rhrzr'r'r(�call_soon_threadsafesz&AbstractEventLoop.call_soon_threadsafecGst�dSr<rh)r"�executor�funcr$r'r'r(�run_in_executorsz!AbstractEventLoop.run_in_executorcCst�dSr<rh)r"r�r'r'r(�set_default_executorsz&AbstractEventLoop.set_default_executorr)�family�type�proto�flagsc�st�dSr<rh)r"�host�portr�r�r�r�r'r'r(�getaddrinfo#szAbstractEventLoop.getaddrinfoc�st�dSr<rh)r"�sockaddrr�r'r'r(�getnameinfo'szAbstractEventLoop.getnameinfo)
�sslr�r�r��sock�
local_addr�server_hostname�ssl_handshake_timeout�happy_eyeballs_delay�
interleavec
�st�dSr<rh)r"�protocol_factoryr�r�r�r�r�r�r�r�r�r�r�r�r'r'r(�create_connection*sz#AbstractEventLoop.create_connection�dT)	r�r�r��backlogr��
reuse_address�
reuse_portr�rmc	
�st�dS)adA coroutine which creates a TCP server bound to host and port.

        The return value is a Server object which can be used to stop
        the service.

        If host is an empty string or None all interfaces are assumed
        and a list of multiple sockets will be returned (most likely
        one for IPv4 and another one for IPv6). The host parameter can also be
        a sequence (e.g. list) of hosts to bind to.

        family can be set to either AF_INET or AF_INET6 to force the
        socket to use IPv4 or IPv6. If not set it will be determined
        from host (defaults to AF_UNSPEC).

        flags is a bitmask for getaddrinfo().

        sock can optionally be specified in order to use a preexisting
        socket object.

        backlog is the maximum number of queued connections passed to
        listen() (defaults to 100).

        ssl can be set to an SSLContext to enable SSL over the
        accepted connections.

        reuse_address tells the kernel to reuse a local socket in
        TIME_WAIT state, without waiting for its natural timeout to
        expire. If not specified will automatically be set to True on
        UNIX.

        reuse_port tells the kernel to allow this endpoint to be bound to
        the same port as other existing endpoints are bound to, so long as
        they all set this flag when being created. This option is not
        supported on Windows.

        ssl_handshake_timeout is the time in seconds that an SSL server
        will wait for completion of the SSL handshake before aborting the
        connection. Default is 60s.

        start_serving set to True (default) causes the created server
        to start accepting connections immediately.  When set to False,
        the user should await Server.start_serving() or Server.serve_forever()
        to make the server to start accepting connections.
        Nrh)
r"r�r�r�r�r�r�r�r�r�r�r�rmr'r'r(�
create_server3s3zAbstractEventLoop.create_server)�fallbackc�st�dS)zRSend a file through a transport.

        Return an amount of sent bytes.
        Nrh)r"�	transport�file�offset�countr�r'r'r(�sendfilehszAbstractEventLoop.sendfileF)�server_sider�r�c�st�dS)z|Upgrade a transport to TLS.

        Return a new transport that *protocol* should start using
        immediately.
        Nrh)r"r��protocol�
sslcontextr�r�r�r'r'r(�	start_tlsps	zAbstractEventLoop.start_tls)r�r�r�r�c�st�dSr<rh)r"r��pathr�r�r�r�r'r'r(�create_unix_connection{sz(AbstractEventLoop.create_unix_connection)r�r�r�r�rmc�st�dS)a�A coroutine which creates a UNIX Domain Socket server.

        The return value is a Server object, which can be used to stop
        the service.

        path is a str, representing a file systsem path to bind the
        server socket to.

        sock can optionally be specified in order to use a preexisting
        socket object.

        backlog is the maximum number of queued connections passed to
        listen() (defaults to 100).

        ssl can be set to an SSLContext to enable SSL over the
        accepted connections.

        ssl_handshake_timeout is the time in seconds that an SSL server
        will wait for the SSL handshake to complete (defaults to 60s).

        start_serving set to True (default) causes the created server
        to start accepting connections immediately.  When set to False,
        the user should await Server.start_serving() or Server.serve_forever()
        to make the server to start accepting connections.
        Nrh)r"r�r�r�r�r�r�rmr'r'r(�create_unix_server�sz$AbstractEventLoop.create_unix_server)r�r�r�r�r��allow_broadcastr�c�st�dS)a�A coroutine which creates a datagram endpoint.

        This method will try to establish the endpoint in the background.
        When successful, the coroutine returns a (transport, protocol) pair.

        protocol_factory must be a callable returning a protocol instance.

        socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on
        host (or family if specified), socket type SOCK_DGRAM.

        reuse_address tells the kernel to reuse a local socket in
        TIME_WAIT state, without waiting for its natural timeout to
        expire. If not specified it will automatically be set to True on
        UNIX.

        reuse_port tells the kernel to allow this endpoint to be bound to
        the same port as other existing endpoints are bound to, so long as
        they all set this flag when being created. This option is not
        supported on Windows and some UNIX's. If the
        :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
        capability is unsupported.

        allow_broadcast tells the kernel to allow this endpoint to send
        messages to the broadcast address.

        sock can optionally be specified in order to use a preexisting
        socket object.
        Nrh)r"r�r��remote_addrr�r�r�r�r�r�r�r'r'r(�create_datagram_endpoint�s!z*AbstractEventLoop.create_datagram_endpointc�st�dS)aRegister read pipe in event loop. Set the pipe to non-blocking mode.

        protocol_factory should instantiate object with Protocol interface.
        pipe is a file-like object.
        Return pair (transport, protocol), where transport supports the
        ReadTransport interface.Nrh�r"r��piper'r'r(�connect_read_pipe�sz#AbstractEventLoop.connect_read_pipec�st�dS)aRegister write pipe in event loop.

        protocol_factory should instantiate object with BaseProtocol interface.
        Pipe is file-like object already switched to nonblocking.
        Return pair (transport, protocol), where transport support
        WriteTransport interface.Nrhr�r'r'r(�connect_write_pipe�sz$AbstractEventLoop.connect_write_pipe)�stdin�stdout�stderrc�st�dSr<rh)r"r��cmdr�r�r��kwargsr'r'r(�subprocess_shell�sz"AbstractEventLoop.subprocess_shellc�st�dSr<rh)r"r�r�r�r�r$r�r'r'r(�subprocess_exec�sz!AbstractEventLoop.subprocess_execcGst�dSr<rh�r"�fdr#r$r'r'r(�
add_reader�szAbstractEventLoop.add_readercCst�dSr<rh�r"r�r'r'r(�
remove_reader�szAbstractEventLoop.remove_readercGst�dSr<rhr�r'r'r(�
add_writer�szAbstractEventLoop.add_writercCst�dSr<rhr�r'r'r(�
remove_writer�szAbstractEventLoop.remove_writerc�st�dSr<rh)r"r��nbytesr'r'r(�	sock_recvszAbstractEventLoop.sock_recvc�st�dSr<rh)r"r��bufr'r'r(�sock_recv_intosz AbstractEventLoop.sock_recv_intoc�st�dSr<rh)r"r��datar'r'r(�sock_sendallszAbstractEventLoop.sock_sendallc�st�dSr<rh)r"r��addressr'r'r(�sock_connectszAbstractEventLoop.sock_connectc�st�dSr<rh)r"r�r'r'r(�sock_acceptszAbstractEventLoop.sock_acceptc�st�dSr<rh)r"r�r�r�r�r�r'r'r(�
sock_sendfileszAbstractEventLoop.sock_sendfilecGst�dSr<rh)r"�sigr#r$r'r'r(�add_signal_handlersz$AbstractEventLoop.add_signal_handlercCst�dSr<rh)r"r�r'r'r(�remove_signal_handlersz'AbstractEventLoop.remove_signal_handlercCst�dSr<rh)r"�factoryr'r'r(�set_task_factorysz"AbstractEventLoop.set_task_factorycCst�dSr<rhr:r'r'r(�get_task_factory"sz"AbstractEventLoop.get_task_factorycCst�dSr<rhr:r'r'r(�get_exception_handler'sz'AbstractEventLoop.get_exception_handlercCst�dSr<rh)r"�handlerr'r'r(�set_exception_handler*sz'AbstractEventLoop.set_exception_handlercCst�dSr<rh�r"r&r'r'r(�default_exception_handler-sz+AbstractEventLoop.default_exception_handlercCst�dSr<rhr�r'r'r(rE0sz(AbstractEventLoop.call_exception_handlercCst�dSr<rhr:r'r'r(r5szAbstractEventLoop.get_debugcCst�dSr<rh)r"�enabledr'r'r(�	set_debug8szAbstractEventLoop.set_debug)r)NN)NN)rN)N)N)NN)rN);r.rJrKrLrrrtrurvrwrjrxrfr{ryr}r~rr�r�r�r�r�r�r��socket�	AF_UNSPEC�
AI_PASSIVEr�r�r�r�r�r�r�r��
subprocess�PIPEr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rErr�r'r'r'r(r�s��
��
��5�	�����!��%
���rc@s8eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�ZdS)
rz-Abstract policy for accessing the event loop.cCst�dS)a:Get the event loop for the current context.

        Returns an event loop object implementing the BaseEventLoop interface,
        or raises an exception in case no event loop has been set for the
        current context and the current policy does not specify to create one.

        It should never return None.Nrhr:r'r'r(r?sz&AbstractEventLoopPolicy.get_event_loopcCst�dS)z3Set the event loop for the current context to loop.Nrh�r"r%r'r'r(r	Isz&AbstractEventLoopPolicy.set_event_loopcCst�dS)z�Create and return a new event loop object according to this
        policy's rules. If there's need to set this loop as the event loop for
        the current context, set_event_loop must be called explicitly.Nrhr:r'r'r(r
Msz&AbstractEventLoopPolicy.new_event_loopcCst�dS)z$Get the watcher for child processes.Nrhr:r'r'r(rUsz)AbstractEventLoopPolicy.get_child_watchercCst�dS)z$Set the watcher for child processes.Nrh)r"�watcherr'r'r(rYsz)AbstractEventLoopPolicy.set_child_watcherN)	r.rJrKrLrr	r
rrr'r'r'r(r<s
rc@sFeZdZdZdZGdd�dej�Zdd�Zdd�Z	d	d
�Z
dd�ZdS)
�BaseDefaultEventLoopPolicya�Default policy implementation for accessing the event loop.

    In this policy, each thread has its own event loop.  However, we
    only automatically create an event loop by default for the main
    thread; other threads by default have no event loop.

    Other policies may have different rules (e.g. a single global
    event loop, or automatically creating an event loop per thread, or
    using some other notion of context to which an event loop is
    associated).
    Nc@seZdZdZdZdS)z!BaseDefaultEventLoopPolicy._LocalNF)r.rJrKr�_set_calledr'r'r'r(�_Localmsr�cCs|��|_dSr<)r��_localr:r'r'r(r)qsz#BaseDefaultEventLoopPolicy.__init__cCsX|jjdkr2|jjs2tt��tj�r2|�|���|jjdkrPt	dt��j
��|jjS)zvGet the event loop for the current context.

        Returns an instance of EventLoop or raises an exception.
        Nz,There is no current event loop in thread %r.)r�rr�rb�	threading�current_thread�_MainThreadr	r
�RuntimeErrorr�r:r'r'r(rts���z)BaseDefaultEventLoopPolicy.get_event_loopcCs*d|j_|dkst|t�st�||j_dS)zSet the event loop.TN)r�r�rbrrPrr�r'r'r(r	�sz)BaseDefaultEventLoopPolicy.set_event_loopcCs|��S)zvCreate a new event loop.

        You must call set_event_loop() to make this the current event
        loop.
        )�
_loop_factoryr:r'r'r(r
�sz)BaseDefaultEventLoopPolicy.new_event_loop)r.rJrKrLr�r��localr�r)rr	r
r'r'r'r(r�^sr�c@seZdZdZdS)�_RunningLoop)NNN)r.rJrK�loop_pidr'r'r'r(r��sr�cCst�}|dkrtd��|S)zrReturn the running event loop.  Raise a RuntimeError if there is none.

    This function is thread-specific.
    Nzno running event loop)rr��r%r'r'r(r�srcCs&tj\}}|dk	r"|t��kr"|SdS)z�Return the running event loop or None.

    This is a low-level function intended to be used by event loops.
    This function is thread-specific.
    N)�
_running_loopr��os�getpid)�running_loop�pidr'r'r(r�s
rcCs|t��ft_dS)z�Set the running event loop.

    This is a low-level function intended to be used by event loops.
    This function is thread-specific.
    N)r�r�r�r�r�r'r'r(r
�sr
c	Cs.t� tdkr ddlm}|�aW5QRXdS)Nr��DefaultEventLoopPolicy)�_lock�_event_loop_policy�r�r�r'r'r(�_init_event_loop_policy�sr�cCstdkrt�tS)z"Get the current event loop policy.N)r�r�r'r'r'r(r�srcCs|dkst|t�st�|adS)zZSet the current event loop policy.

    If policy is None, the default policy is restored.N)rbrrPr�)�policyr'r'r(r�srcCst�}|dk	r|St���S)aGReturn an asyncio event loop.

    When called from a coroutine or a callback (e.g. scheduled with call_soon
    or similar API), this function will always return the running event loop.

    If there is no running event loop set, the function will return
    the result of `get_event_loop_policy().get_event_loop()` call.
    N)rrr)�current_loopr'r'r(r�s
rcCst��|�dS)zCEquivalent to calling get_event_loop_policy().set_event_loop(loop).N)rr	r�r'r'r(r	�sr	cCs
t���S)z?Equivalent to calling get_event_loop_policy().new_event_loop().)rr
r'r'r'r(r
�sr
cCs
t���S)zBEquivalent to calling get_event_loop_policy().get_child_watcher().)rrr'r'r'r(r�srcCst��|�S)zMEquivalent to calling
    get_event_loop_policy().set_child_watcher(watcher).)rr)r�r'r'r(r�sr)rr
rr),rL�__all__rr�r�r�r r�r�rrrrrrrr�r��Lockr�r�r�r�rrr
r�rrrr	r
rr�_py__get_running_loop�_py__set_running_loop�_py_get_running_loop�_py_get_event_loop�_asyncio�ImportError�_c__get_running_loop�_c__set_running_loop�_c_get_running_loop�_c_get_event_loopr'r'r'r(�<module>sXJ@*q"9
	�h�#bytecode of module 'asyncio.events'�u��b.��'
h)��N}�(hB�	�@sldZdZGdd�de�ZGdd�de�ZGdd�de�ZGdd	�d	e�ZGd
d�de	�Z
Gdd
�d
e�ZdS)zasyncio exceptions.)�CancelledError�InvalidStateError�TimeoutError�IncompleteReadError�LimitOverrunError�SendfileNotAvailableErrorc@seZdZdZdS)rz!The Future or Task was cancelled.N��__name__�
__module__�__qualname__�__doc__�rr�(/usr/lib/python3.8/asyncio/exceptions.pyr	src@seZdZdZdS)rz*The operation exceeded the given deadline.Nrrrrr
r
src@seZdZdZdS)rz+The operation is not allowed in this state.Nrrrrr
rsrc@seZdZdZdS)rz~Sendfile syscall is not available.

    Raised if OS does not support sendfile syscall for given socket or
    file type.
    Nrrrrr
rsrcs(eZdZdZ�fdd�Zdd�Z�ZS)rz�
    Incomplete read error. Attributes:

    - partial: read bytes string before the end of stream was reached
    - expected: total number of expected bytes (or None if unknown)
    cs@|dkrdnt|�}t��t|��d|�d��||_||_dS)N�	undefinedz bytes read on a total of z expected bytes)�repr�super�__init__�len�partial�expected)�selfrr�
r_expected��	__class__rr
r$szIncompleteReadError.__init__cCst|�|j|jffS�N)�typerr�rrrr
�
__reduce__+szIncompleteReadError.__reduce__�rr	r
rrr�
__classcell__rrrr
rsrcs(eZdZdZ�fdd�Zdd�Z�ZS)rz�Reached the buffer limit while looking for a separator.

    Attributes:
    - consumed: total number of to be consumed bytes.
    cst��|�||_dSr)rr�consumed)r�messagerrrr
r5szLimitOverrunError.__init__cCst|�|jd|jffS)N�)r�argsrrrrr
r9szLimitOverrunError.__reduce__rrrrr
r/srN)r�__all__�
BaseExceptionr�	Exceptionrr�RuntimeErrorr�EOFErrorrrrrrr
�<module>s�h�'bytecode of module 'asyncio.exceptions'�u��b.��R	h)��N}�(hB	�@sdddlZddlZddlZddlZddlZddlmZdd�Zdd�Zdd	�Z	ddd�Z
dd
d�ZdS)�N�)�	constantscCsVt�|�}t�|�r&|j}|j|jfSt|tj�r<t	|j
�St|tj�rRt	|j
�SdS�N)�inspect�unwrap�
isfunction�__code__�co_filename�co_firstlineno�
isinstance�	functools�partial�_get_function_source�func�
partialmethod)r�code�r�,/usr/lib/python3.8/asyncio/format_helpers.pyr
s



rcCs8t||d�}t|�}|r4|d|d�d|d��7}|S)Nz at r�:r)�_format_callbackr)r�args�	func_repr�sourcerrr�_format_callback_sources
rcCsHg}|r|�dd�|D��|r8|�dd�|��D��d�d�|��S)z�Format function arguments and keyword arguments.

    Special case for a single parameter: ('hello',) is formatted as ('hello').
    css|]}t�|�VqdSr��reprlib�repr)�.0�argrrr�	<genexpr>&sz*_format_args_and_kwargs.<locals>.<genexpr>css&|]\}}|�dt�|���VqdS)�=Nr)r�k�vrrrr(sz({})z, )�extend�items�format�join)r�kwargsr$rrr�_format_args_and_kwargssr(�cCs�t|tj�r.t||�|}t|j|j|j|�St|d�rF|j	rF|j	}n t|d�r^|j
r^|j
}nt|�}|t||�7}|r�||7}|S)N�__qualname__�__name__)rrr
r(rrr�keywords�hasattrr*r+r)rrr'�suffixrrrrr,srcCsD|dkrt��j}|dkr tj}tjjt�|�|dd�}|�	�|S)zlReplacement for traceback.extract_stack() that only does the
    necessary work for asyncio debug mode.
    NF)�limit�lookup_lines)
�sys�	_getframe�f_backr�DEBUG_STACK_DEPTH�	traceback�StackSummary�extract�
walk_stack�reverse)�fr/�stackrrr�
extract_stack>s
�r<)r))NN)rrrr1r5r)rrrr(rr<rrrr�<module>s
�h�+bytecode of module 'asyncio.format_helpers'�u��b.���+h)��N}�(hB�+�@s�dZdZddlZddlZddlZddlZddlmZddlm	Z	ddlm
Z
ddlmZejZej
Z
ejZejZejdZGd	d
�d
�ZeZdd�Zd
d�Zdd�Zdd�Zdd�Zdd�Zdd�dd�ZzddlZWnek
r�YnXejZZdS)z.A Future class similar to the one in PEP 3148.)�Future�wrap_future�isfuture�N�)�base_futures)�events)�
exceptions)�format_helpersc@s�eZdZdZeZdZdZdZdZ	dZ
dZdd�dd�Ze
jZdd�Zd	d
�Zedd��Zejd
d��Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�dd�Zdd �Zd!d"�Zd#d$�Zd%d&�Z e Z!dS)'ra,This class is *almost* compatible with concurrent.futures.Future.

    Differences:

    - This class is not thread-safe.

    - result() and exception() do not take a timeout argument and
      raise an exception when the future isn't done yet.

    - Callbacks registered with add_done_callback() are always called
      via the event loop's call_soon().

    - This class is not compatible with the wait() and as_completed()
      methods in the concurrent.futures package.

    (In Python 3.4 or later we may be able to unify the implementations.)
    NF��loopcCs@|dkrt��|_n||_g|_|j��r<t�t�d��|_	dS)z�Initialize the future.

        The optional event_loop argument allows explicitly setting the event
        loop object used by the future. If it's not provided, the future uses
        the default event loop.
        Nr)
r�get_event_loop�_loop�
_callbacks�	get_debugr	�
extract_stack�sys�	_getframe�_source_traceback��selfr�r�%/usr/lib/python3.8/asyncio/futures.py�__init__Ds
�zFuture.__init__cCsd�|jjd�|����S)Nz<{} {}>� )�format�	__class__�__name__�join�
_repr_info�rrrr�__repr__Vs
�zFuture.__repr__cCsF|js
dS|j}|jj�d�||d�}|jr6|j|d<|j�|�dS)Nz exception was never retrieved)�message�	exception�future�source_traceback)�_Future__log_traceback�
_exceptionrrrr
�call_exception_handler)r�exc�contextrrr�__del__Zs�
zFuture.__del__cCs|jS�N)r%rrrr�_log_tracebackjszFuture._log_tracebackcCst|�rtd��d|_dS)Nz'_log_traceback can only be set to FalseF)�bool�
ValueErrorr%)r�valrrrr,nscCs|j}|dkrtd��|S)z-Return the event loop the Future is bound to.Nz!Future object is not initialized.)r
�RuntimeErrorrrrr�get_looptszFuture.get_loopcCs&d|_|jtkrdSt|_|��dS)z�Cancel the future and schedule callbacks.

        If the future is already done or cancelled, return False.  Otherwise,
        change the future's state to cancelled, schedule the callbacks and
        return True.
        FT)r%�_state�_PENDING�
_CANCELLED�_Future__schedule_callbacksrrrr�cancel{s
z
Future.cancelcCsH|jdd�}|sdSg|jdd�<|D]\}}|jj|||d�q(dS)z�Internal: Ask the event loop to call all callbacks.

        The callbacks are scheduled to be called as soon as possible. Also
        clears the callback list.
        N�r))rr
�	call_soon)r�	callbacks�callback�ctxrrr�__schedule_callbacks�szFuture.__schedule_callbackscCs
|jtkS)z(Return True if the future was cancelled.)r2r4rrrr�	cancelled�szFuture.cancelledcCs
|jtkS)z�Return True if the future is done.

        Done means either that a result / exception are available, or that the
        future was cancelled.
        )r2r3rrrr�done�szFuture.donecCs@|jtkrtj�|jtkr$t�d��d|_|jdk	r:|j�|jS)aReturn the result this future represents.

        If the future has been cancelled, raises CancelledError.  If the
        future's result isn't yet available, raises InvalidStateError.  If
        the future is done and has an exception set, this exception is raised.
        zResult is not ready.FN)	r2r4r�CancelledError�	_FINISHED�InvalidStateErrorr%r&�_resultrrrr�result�s



z
Future.resultcCs0|jtkrtj�|jtkr$t�d��d|_|jS)a&Return the exception that was set on this future.

        The exception (or None if no exception was set) is returned only if
        the future is done.  If the future has been cancelled, raises
        CancelledError.  If the future isn't done yet, raises
        InvalidStateError.
        zException is not set.F)r2r4rr?r@rAr%r&rrrrr"�s


zFuture.exceptionr7cCsB|jtkr|jj|||d�n |dkr.t��}|j�||f�dS)z�Add a callback to be run when the future becomes done.

        The callback is called with a single argument - the future object. If
        the future is already done when this is called, the callback is
        scheduled with call_soon.
        r7N)r2r3r
r8�contextvars�copy_contextr�append)r�fnr)rrr�add_done_callback�s

zFuture.add_done_callbackcs<�fdd�|jD�}t|j�t|�}|r8||jdd�<|S)z}Remove all instances of a callback from the "call when done" list.

        Returns the number of callbacks removed.
        cs g|]\}}|�kr||f�qSrr)�.0�fr;�rGrr�
<listcomp>�s�z/Future.remove_done_callback.<locals>.<listcomp>N)r�len)rrG�filtered_callbacks�
removed_countrrKr�remove_done_callback�s
�zFuture.remove_done_callbackcCs8|jtkr t�|j�d|����||_t|_|��dS)z�Mark the future done and set its result.

        If the future is already done when this method is called, raises
        InvalidStateError.
        �: N)r2r3rrArBr@r5)rrCrrr�
set_result�s

zFuture.set_resultcCsb|jtkr t�|j�d|����t|t�r0|�}t|�tkrDtd��||_t	|_|�
�d|_dS)z�Mark the future done and set an exception.

        If the future is already done when this method is called, raises
        InvalidStateError.
        rQzPStopIteration interacts badly with generators and cannot be raised into a FutureTN)r2r3rrA�
isinstance�type�
StopIteration�	TypeErrorr&r@r5r%)rr"rrr�
set_exception�s

zFuture.set_exceptionccs,|��sd|_|V|��s$td��|��S)NTzawait wasn't used with future)r>�_asyncio_future_blockingr0rCrrrr�	__await__szFuture.__await__)"r�
__module__�__qualname__�__doc__r3r2rBr&r
rrXr%rr�_future_repr_inforr r*�propertyr,�setterr1r6r5r=r>rCr"rHrPrRrWrY�__iter__rrrrrs:

rcCs,z
|j}Wntk
rYnX|�S|jSr+)r1�AttributeErrorr
)�futr1rrr�	_get_loops
rccCs|��rdS|�|�dS)z?Helper setting the result only if the future was not cancelled.N)r=rR)rbrCrrr�_set_result_unless_cancelledsrdcCsXt|�}|tjjkr tj|j�S|tjjkr8tj|j�S|tjjkrPtj|j�S|SdSr+)rT�
concurrent�futuresr?r�args�TimeoutErrorrA)r(�	exc_classrrr�_convert_future_exc#srjcCs^|��st�|��r|��|��s(dS|��}|dk	rH|�t|��n|��}|�	|�dS)z8Copy state from a future to a concurrent.futures.Future.N)
r>�AssertionErrorr=r6�set_running_or_notify_cancelr"rWrjrCrR)re�sourcer"rCrrr�_set_concurrent_future_state/srncCsl|��st�|��rdS|��r$t�|��r6|��n2|��}|dk	rV|�t|��n|��}|�|�dS)zqInternal helper to copy state from another Future.

    The other Future may be a concurrent.futures.Future.
    N)	r>rkr=r6r"rWrjrCrR)rm�destr"rCrrr�_copy_future_state>s
rpcs�t��st�tjj�std��t��s<t�tjj�s<td��t��rLt��nd�t��r`t��nd�dd�����fdd�}����fdd	�}��|���|�dS)
aChain two futures so that when one completes, so does the other.

    The result (or exception) of source will be copied to destination.
    If destination is cancelled, source gets cancelled too.
    Compatible with both asyncio.Future and concurrent.futures.Future.
    z(A future is required for source argumentz-A future is required for destination argumentNcSs"t|�rt||�n
t||�dSr+)rrprn)r#�otherrrr�
_set_statebsz!_chain_future.<locals>._set_statecs2|��r.�dks��kr"���n���j�dSr+)r=r6�call_soon_threadsafe)�destination)�	dest_looprm�source_looprr�_call_check_cancelhs
z)_chain_future.<locals>._call_check_cancelcsJ���r�dk	r���rdS�dks,��kr8��|�n����|�dSr+)r=�	is_closedrs)rm)rrrurtrvrr�_call_set_stateos��z&_chain_future.<locals>._call_set_state)rrSrerfrrVrcrH)rmrtrwryr)rrrurtrmrvr�
_chain_futureRs��	
rzr
cCsNt|�r|St|tjj�s(td|����|dkr8t��}|��}t	||�|S)z&Wrap concurrent.futures.Future object.z+concurrent.futures.Future is expected, got N)
rrSrerfrrkrr�
create_futurerz)r#r�
new_futurerrrr|s�
r)r\�__all__�concurrent.futuresrerD�loggingr�rrrr	rr3r4r@�DEBUG�STACK_DEBUGr�	_PyFuturercrdrjrnrprzr�_asyncio�ImportError�_CFuturerrrr�<module>s:
q*
�h�$bytecode of module 'asyncio.futures'�u��b.��@h)��N}�(hB�?�@s�dZdZddlZddlZddlZddlmZddlmZddlmZddlm	Z	Gd	d
�d
�Z
Gdd�d�ZGd
d�de�ZGdd�d�Z
Gdd�de�ZGdd�de�ZGdd�de�ZdS)zSynchronization primitives.)�Lock�Event�	Condition�	Semaphore�BoundedSemaphore�N�)�events)�futures)�
exceptions)�
coroutinesc@s(eZdZdZdd�Zdd�Zdd�ZdS)	�_ContextManagera\Context manager.

    This enables the following idiom for acquiring and releasing a
    lock around a block:

        with (yield from lock):
            <block>

    while failing loudly when accidentally using:

        with lock:
            <block>

    Deprecated, use 'async with' statement:
        async with lock:
            <block>
    cCs
||_dS�N)�_lock)�self�lock�r�#/usr/lib/python3.8/asyncio/locks.py�__init__"sz_ContextManager.__init__cCsdSr
r�rrrr�	__enter__%sz_ContextManager.__enter__cGsz|j��W5d|_XdSr
)r�release�r�argsrrr�__exit__*sz_ContextManager.__exit__N)�__name__�
__module__�__qualname__�__doc__rrrrrrrrsrc@sReZdZdd�Zdd�Zejdd��Zej	e_	dd�Z
d	d
�Zdd�Zd
d�Z
dS)�_ContextManagerMixincCstd��dS)Nz9"yield from" should be used as context manager expression)�RuntimeErrorrrrrr2s�z_ContextManagerMixin.__enter__cGsdSr
rrrrrr6sz_ContextManagerMixin.__exit__ccs&tjdtdd�|��EdHt|�S)NzD'with (yield from lock)' is deprecated use 'async with lock' instead���
stacklevel)�warnings�warn�DeprecationWarning�acquirerrrrr�__iter__;s�z_ContextManagerMixin.__iter__c�s|��IdHt|�Sr
)r&rrrrr�
__acquire_ctxUsz"_ContextManagerMixin.__acquire_ctxcCstjdtdd�|����S)Nz='with await lock' is deprecated use 'async with lock' insteadr r!)r#r$r%�!_ContextManagerMixin__acquire_ctx�	__await__rrrrr*Ys
�z_ContextManagerMixin.__await__c�s|��IdHdSr
)r&rrrr�
__aenter__`sz_ContextManagerMixin.__aenter__c�s|��dSr
)r)r�exc_type�exc�tbrrr�	__aexit__fsz_ContextManagerMixin.__aexit__N)rrrrr�types�	coroutiner'r�
_is_coroutiner)r*r+r/rrrrr1s
rcsNeZdZdZdd�dd�Z�fdd�Zdd	�Zd
d�Zdd
�Zdd�Z	�Z
S)ra�Primitive lock objects.

    A primitive lock is a synchronization primitive that is not owned
    by a particular coroutine when locked.  A primitive lock is in one
    of two states, 'locked' or 'unlocked'.

    It is created in the unlocked state.  It has two basic methods,
    acquire() and release().  When the state is unlocked, acquire()
    changes the state to locked and returns immediately.  When the
    state is locked, acquire() blocks until a call to release() in
    another coroutine changes it to unlocked, then the acquire() call
    resets it to locked and returns.  The release() method should only
    be called in the locked state; it changes the state to unlocked
    and returns immediately.  If an attempt is made to release an
    unlocked lock, a RuntimeError will be raised.

    When more than one coroutine is blocked in acquire() waiting for
    the state to turn to unlocked, only one coroutine proceeds when a
    release() call resets the state to unlocked; first coroutine which
    is blocked in acquire() is being processed.

    acquire() is a coroutine and should be called with 'await'.

    Locks also support the asynchronous context management protocol.
    'async with lock' statement should be used.

    Usage:

        lock = Lock()
        ...
        await lock.acquire()
        try:
            ...
        finally:
            lock.release()

    Context manager usage:

        lock = Lock()
        ...
        async with lock:
             ...

    Lock objects can be tested for locking state:

        if not lock.locked():
           await lock.acquire()
        else:
           # lock is acquired
           ...

    N��loopcCs:d|_d|_|dkr t��|_n||_tjdtdd�dS�NF�[The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.r r!)�_waiters�_lockedr�get_event_loop�_loopr#r$r%�rr4rrrr�s�z
Lock.__init__csLt���}|jrdnd}|jr2|�dt|j���}d|dd��d|�d�S�	N�locked�unlocked�
, waiters:�<r���� [�]>)�super�__repr__r8r7�len�r�res�extra��	__class__rrrE�s

z
Lock.__repr__cCs|jS)z Return True if lock is acquired.)r8rrrrr=�szLock.lockedc	�s�|js.|jdks$tdd�|jD��r.d|_dS|jdkrBt��|_|j��}|j�|�z"z|IdHW5|j�|�XWn&t	j
k
r�|js�|���YnXd|_dS)z�Acquire a lock.

        This method blocks until the lock is unlocked, then sets it to
        locked and returns True.
        Ncss|]}|��VqdSr
)�	cancelled)�.0�wrrr�	<genexpr>�szLock.acquire.<locals>.<genexpr>T)r8r7�all�collections�dequer:�
create_future�append�remover
�CancelledError�_wake_up_first�r�futrrrr&�s&�


zLock.acquirecCs"|jrd|_|��ntd��dS)aGRelease a lock.

        When the lock is locked, reset it to unlocked, and return.
        If any other coroutines are blocked waiting for the lock to become
        unlocked, allow exactly one of them to proceed.

        When invoked on an unlocked lock, a RuntimeError is raised.

        There is no return value.
        FzLock is not acquired.N)r8rWrrrrrr�s
zLock.releasecCsJ|js
dSztt|j��}Wntk
r2YdSX|��sF|�d�dS)z*Wake up the first waiter if it isn't done.NT)r7�next�iter�
StopIteration�done�
set_resultrXrrrrW�szLock._wake_up_first)rrrrrrEr=r&rrW�
__classcell__rrrJrrjs5 rcsNeZdZdZdd�dd�Z�fdd�Zdd	�Zd
d�Zdd
�Zdd�Z	�Z
S)ra#Asynchronous equivalent to threading.Event.

    Class implementing event objects. An event manages a flag that can be set
    to true with the set() method and reset to false with the clear() method.
    The wait() method blocks until the flag is true. The flag is initially
    false.
    Nr3cCs>t��|_d|_|dkr$t��|_n||_tjdt	dd�dSr5)
rQrRr7�_valuerr9r:r#r$r%r;rrrrs
�zEvent.__init__csLt���}|jrdnd}|jr2|�dt|j���}d|dd��d|�d�S)	N�setZunsetr?r@rrArBrC)rDrEr`r7rFrGrJrrrEs

zEvent.__repr__cCs|jS)z5Return True if and only if the internal flag is true.�r`rrrr�is_setszEvent.is_setcCs.|js*d|_|jD]}|��s|�d�qdS)z�Set the internal flag to true. All coroutines waiting for it to
        become true are awakened. Coroutine that call wait() once the flag is
        true will not block at all.
        TN)r`r7r]r^rXrrrras

z	Event.setcCs
d|_dS)z�Reset the internal flag to false. Subsequently, coroutines calling
        wait() will block until set() is called to set the internal flag
        to true again.FNrbrrrr�clear"szEvent.clearc	�sF|jr
dS|j��}|j�|�z|IdHW�dS|j�|�XdS)z�Block until the internal flag is true.

        If the internal flag is true on entry, return True
        immediately.  Otherwise, block until another coroutine calls
        set() to set the flag to true, then return True.
        TN)r`r:rSr7rTrUrXrrr�wait(s

z
Event.wait)rrrrrrErcrardrer_rrrJrr�srcsReZdZdZddd�dd�Z�fdd�Zdd	�Zd
d�Zdd
d�Zdd�Z	�Z
S)raAsynchronous equivalent to threading.Condition.

    This class implements condition variable objects. A condition variable
    allows one or more coroutines to wait until they are notified by another
    coroutine.

    A new Lock object is created and used as the underlying lock.
    Nr3cCs~|dkrt��|_n||_tjdtdd�|dkr>t|d�}n|j|jk	rRtd��||_|j	|_	|j
|_
|j|_t�
�|_dS)Nr6r r!r3z"loop argument must agree with lock)rr9r:r#r$r%r�
ValueErrorrr=r&rrQrRr7)rrr4rrrrEs �zCondition.__init__csNt���}|��rdnd}|jr4|�dt|j���}d|dd��d|�d�Sr<)rDrEr=r7rFrGrJrrrE[s

zCondition.__repr__c�s�|��std��|��z@|j��}|j�	|�z|IdHW�W�dS|j�
|�XW5d}z|��IdHWq�Wq^tjk
r�d}Yq^Xq^|r�tj�XdS)a�Wait until notified.

        If the calling coroutine has not acquired the lock when this
        method is called, a RuntimeError is raised.

        This method releases the underlying lock, and then blocks
        until it is awakened by a notify() or notify_all() call for
        the same condition variable in another coroutine.  Once
        awakened, it re-acquires the lock and returns True.
        zcannot wait on un-acquired lockFNT)r=rrr&r
rVr:rSr7rTrU)rrLrYrrrrebs$

zCondition.waitc�s$|�}|s |��IdH|�}q|S)z�Wait until a predicate becomes true.

        The predicate should be a callable which result will be
        interpreted as a boolean value.  The final predicate value is
        the return value.
        N)re)r�	predicate�resultrrr�wait_for�s
zCondition.wait_forrcCsJ|��std��d}|jD]*}||kr*qF|��s|d7}|�d�qdS)aBy default, wake up one coroutine waiting on this condition, if any.
        If the calling coroutine has not acquired the lock when this method
        is called, a RuntimeError is raised.

        This method wakes up at most n of the coroutines waiting for the
        condition variable; it is a no-op if no coroutines are waiting.

        Note: an awakened coroutine does not actually return from its
        wait() call until it can reacquire the lock. Since notify() does
        not release the lock, its caller should.
        z!cannot notify on un-acquired lockrrFN)r=rr7r]r^)r�n�idxrYrrr�notify�s
zCondition.notifycCs|�t|j��dS)aWake up all threads waiting on this condition. This method acts
        like notify(), but wakes up all waiting threads instead of one. If the
        calling thread has not acquired the lock when this method is called,
        a RuntimeError is raised.
        N)rlrFr7rrrr�
notify_all�szCondition.notify_all)N)r)rrrrrrErerirlrmr_rrrJrr;s	%
rcsPeZdZdZddd�dd�Z�fdd�Zd	d
�Zdd�Zd
d�Zdd�Z	�Z
S)raA Semaphore implementation.

    A semaphore manages an internal counter which is decremented by each
    acquire() call and incremented by each release() call. The counter
    can never go below zero; when acquire() finds that it is zero, it blocks,
    waiting until some other thread calls release().

    Semaphores also support the context management protocol.

    The optional argument gives the initial value for the internal
    counter; it defaults to 1. If the value given is less than 0,
    ValueError is raised.
    rNr3cCsN|dkrtd��||_t��|_|dkr4t��|_n||_tj	dt
dd�dS)Nrz$Semaphore initial value must be >= 0r6r r!)rfr`rQrRr7rr9r:r#r$r%�r�valuer4rrrr�s
�zSemaphore.__init__csVt���}|��rdn
d|j��}|jr<|�dt|j���}d|dd��d|�d�S)	Nr=zunlocked, value:r?r@rrArBrC)rDrEr=r`r7rFrGrJrrrE�s

zSemaphore.__repr__cCs,|jr(|j��}|��s|�d�dSqdSr
)r7�popleftr]r^)r�waiterrrr�
_wake_up_next�s


zSemaphore._wake_up_nextcCs
|jdkS)z:Returns True if semaphore can not be acquired immediately.rrbrrrrr=�szSemaphore.lockedc�st|jdkrb|j��}|j�|�z|IdHWq|��|jdkrX|��sX|���YqXq|jd8_dS)a5Acquire a semaphore.

        If the internal counter is larger than zero on entry,
        decrement it by one and return True immediately.  If it is
        zero on entry, block, waiting until some other coroutine has
        called release() to make it larger than 0, and then return
        True.
        rNrT)r`r:rSr7rT�cancelrLrrrXrrrr&�s	


zSemaphore.acquirecCs|jd7_|��dS)z�Release a semaphore, incrementing the internal counter by one.
        When it was zero on entry and another coroutine is waiting for it to
        become larger than zero again, wake up that coroutine.
        rN)r`rrrrrrr�szSemaphore.release)r)rrrrrrErrr=r&rr_rrrJrr�s
rcs4eZdZdZd	dd��fdd�Z�fdd�Z�ZS)
rz�A bounded semaphore implementation.

    This raises ValueError in release() if it would increase the value
    above the initial value.
    rNr3cs.|rtjdtdd�||_t�j||d�dS)Nr6r r!r3)r#r$r%�_bound_valuerDrrnrJrrr
s�zBoundedSemaphore.__init__cs"|j|jkrtd��t���dS)Nz(BoundedSemaphore released too many times)r`rtrfrDrrrJrrrszBoundedSemaphore.release)r)rrrrrrr_rrrJrrs	r)r�__all__rQr0r#�rr	r
rrrrrrrrrrrr�<module>s "9DzN�h�"bytecode of module 'asyncio.locks'�u��b.��
h)��N}�(hC��@sdZddlZe�e�ZdS)zLogging configuration.�N)�__doc__�logging�	getLogger�__package__�logger�rr�!/usr/lib/python3.8/asyncio/log.py�<module>s�h� bytecode of module 'asyncio.log'�u��b.���!h)��N}�(hB�!�@sbdZdZGdd�d�ZGdd�de�ZGdd�de�ZGdd	�d	e�ZGd
d�de�Zdd
�ZdS)zAbstract Protocol base classes.)�BaseProtocol�Protocol�DatagramProtocol�SubprocessProtocol�BufferedProtocolc@s4eZdZdZdZdd�Zdd�Zdd�Zd	d
�ZdS)raCommon base class for protocol interfaces.

    Usually user implements protocols that derived from BaseProtocol
    like Protocol or ProcessProtocol.

    The only case when BaseProtocol should be implemented directly is
    write-only transport like write pipe
    �cCsdS)z�Called when a connection is made.

        The argument is the transport representing the pipe connection.
        To receive data, wait for data_received() calls.
        When the connection is closed, connection_lost() is called.
        Nr)�self�	transportrr�'/usr/lib/python3.8/asyncio/protocols.py�connection_madeszBaseProtocol.connection_madecCsdS)z�Called when the connection is lost or closed.

        The argument is an exception object or None (the latter
        meaning a regular EOF is received or the connection was
        aborted or closed).
        Nr�r�excrrr	�connection_lostszBaseProtocol.connection_lostcCsdS)aCalled when the transport's buffer goes over the high-water mark.

        Pause and resume calls are paired -- pause_writing() is called
        once when the buffer goes strictly over the high-water mark
        (even if subsequent writes increases the buffer size even
        more), and eventually resume_writing() is called once when the
        buffer size reaches the low-water mark.

        Note that if the buffer size equals the high-water mark,
        pause_writing() is not called -- it must go strictly over.
        Conversely, resume_writing() is called when the buffer size is
        equal or lower than the low-water mark.  These end conditions
        are important to ensure that things go as expected when either
        mark is zero.

        NOTE: This is the only Protocol callback that is not called
        through EventLoop.call_soon() -- if it were, it would have no
        effect when it's most needed (when the app keeps writing
        without yielding until pause_writing() is called).
        Nr�rrrr	�
pause_writing%szBaseProtocol.pause_writingcCsdS)zvCalled when the transport's buffer drains below the low-water mark.

        See pause_writing() for details.
        Nrrrrr	�resume_writing;szBaseProtocol.resume_writingN)	�__name__�
__module__�__qualname__�__doc__�	__slots__r
r
rrrrrr	r	s	rc@s$eZdZdZdZdd�Zdd�ZdS)ranInterface for stream protocol.

    The user should implement this interface.  They can inherit from
    this class but don't need to.  The implementations here do
    nothing (they don't raise exceptions).

    When the user wants to requests a transport, they pass a protocol
    factory to a utility function (e.g., EventLoop.create_connection()).

    When the connection is made successfully, connection_made() is
    called with a suitable transport object.  Then data_received()
    will be called 0 or more times with data (bytes) received from the
    transport; finally, connection_lost() will be called exactly once
    with either an exception object or None as an argument.

    State machine of calls:

      start -> CM [-> DR*] [-> ER?] -> CL -> end

    * CM: connection_made()
    * DR: data_received()
    * ER: eof_received()
    * CL: connection_lost()
    rcCsdS)zTCalled when some data is received.

        The argument is a bytes object.
        Nr)r�datarrr	�
data_received^szProtocol.data_receivedcCsdS�z�Called when the other end calls write_eof() or equivalent.

        If this returns a false value (including None), the transport
        will close itself.  If it returns a true value, closing the
        transport is up to the protocol.
        Nrrrrr	�eof_receiveddszProtocol.eof_receivedN)rrrrrrrrrrr	rBsrc@s,eZdZdZdZdd�Zdd�Zdd�Zd	S)
ra�Interface for stream protocol with manual buffer control.

    Important: this has been added to asyncio in Python 3.7
    *on a provisional basis*!  Consider it as an experimental API that
    might be changed or removed in Python 3.8.

    Event methods, such as `create_server` and `create_connection`,
    accept factories that return protocols that implement this interface.

    The idea of BufferedProtocol is that it allows to manually allocate
    and control the receive buffer.  Event loops can then use the buffer
    provided by the protocol to avoid unnecessary data copies.  This
    can result in noticeable performance improvement for protocols that
    receive big amounts of data.  Sophisticated protocols can allocate
    the buffer only once at creation time.

    State machine of calls:

      start -> CM [-> GB [-> BU?]]* [-> ER?] -> CL -> end

    * CM: connection_made()
    * GB: get_buffer()
    * BU: buffer_updated()
    * ER: eof_received()
    * CL: connection_lost()
    rcCsdS)aPCalled to allocate a new receive buffer.

        *sizehint* is a recommended minimal size for the returned
        buffer.  When set to -1, the buffer size can be arbitrary.

        Must return an object that implements the
        :ref:`buffer protocol <bufferobjects>`.
        It is an error to return a zero-sized buffer.
        Nr)r�sizehintrrr	�
get_buffer�szBufferedProtocol.get_buffercCsdS)z�Called when the buffer was updated with the received data.

        *nbytes* is the total number of bytes that were written to
        the buffer.
        Nr)r�nbytesrrr	�buffer_updated�szBufferedProtocol.buffer_updatedcCsdSrrrrrr	r�szBufferedProtocol.eof_receivedN)rrrrrrrrrrrr	rms
rc@s$eZdZdZdZdd�Zdd�ZdS)rz Interface for datagram protocol.rcCsdS)z&Called when some datagram is received.Nr)rr�addrrrr	�datagram_received�sz"DatagramProtocol.datagram_receivedcCsdS)z~Called when a send or receive operation raises an OSError.

        (Other than BlockingIOError or InterruptedError.)
        Nrrrrr	�error_received�szDatagramProtocol.error_receivedN)rrrrrrr rrrr	r�src@s,eZdZdZdZdd�Zdd�Zdd�Zd	S)
rz,Interface for protocol for subprocess calls.rcCsdS)z�Called when the subprocess writes data into stdout/stderr pipe.

        fd is int file descriptor.
        data is bytes object.
        Nr)r�fdrrrr	�pipe_data_received�sz%SubprocessProtocol.pipe_data_receivedcCsdS)z�Called when a file descriptor associated with the child process is
        closed.

        fd is the int file descriptor that was closed.
        Nr)rr!rrrr	�pipe_connection_lost�sz'SubprocessProtocol.pipe_connection_lostcCsdS)z"Called when subprocess has exited.Nrrrrr	�process_exited�sz!SubprocessProtocol.process_exitedN)rrrrrr"r#r$rrrr	r�s
rcCs�t|�}|r�|�|�}t|�}|s*td��||krL||d|�<|�|�dS|d|�|d|�<|�|�||d�}t|�}qdS)Nz%get_buffer() returned an empty buffer)�lenr�RuntimeErrorr)�protor�data_len�buf�buf_lenrrr	�_feed_data_to_buffered_proto�s


r+N)r�__all__rrrrrr+rrrr	�<module>s9+9�h�&bytecode of module 'asyncio.protocols'�u��b.��� h)��N}�(hB� �@s�dZddlZddlZddlZddlmZddlmZGdd�de�ZGdd	�d	e�Z	Gd
d�d�Z
Gdd
�d
e
�ZGdd�de
�ZdS))�Queue�
PriorityQueue�	LifoQueue�	QueueFull�
QueueEmpty�N�)�events)�locksc@seZdZdZdS)rz;Raised when Queue.get_nowait() is called on an empty Queue.N��__name__�
__module__�__qualname__�__doc__�rr�$/usr/lib/python3.8/asyncio/queues.pyrsrc@seZdZdZdS)rzDRaised when the Queue.put_nowait() method is called on a full Queue.Nr
rrrrrsrc@s�eZdZdZd)dd�dd�Zdd�Zd	d
�Zdd�Zd
d�Zdd�Z	dd�Z
dd�Zdd�Ze
dd��Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�ZdS)*raA queue, useful for coordinating producer and consumer coroutines.

    If maxsize is less than or equal to zero, the queue size is infinite. If it
    is an integer greater than 0, then "await put()" will block when the
    queue reaches maxsize, until an item is removed by get().

    Unlike the standard library Queue, you can reliably know this Queue's size
    with qsize(), since your single-threaded asyncio application won't be
    interrupted between calling qsize() and doing an operation on the Queue.
    rN��loopcCsp|dkrt��|_n||_tjdtdd�||_t��|_	t��|_
d|_tj
|d�|_|j��|�|�dS)Nz[The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.�)�
stacklevelrr)r�get_event_loop�_loop�warnings�warn�DeprecationWarning�_maxsize�collections�deque�_getters�_putters�_unfinished_tasksr	�Event�	_finished�set�_init)�self�maxsizerrrr�__init__!s�


zQueue.__init__cCst��|_dS�N)rr�_queue�r$r%rrrr#6szQueue._initcCs
|j��Sr')r(�popleft�r$rrr�_get9sz
Queue._getcCs|j�|�dSr'�r(�append�r$�itemrrr�_put<sz
Queue._putcCs&|r"|��}|��s|�d�q"qdSr')r*�done�
set_result)r$�waiters�waiterrrr�_wakeup_nextAs

zQueue._wakeup_nextcCs(dt|�j�dt|�d�d|���d�S)N�<z at z#x� �>)�typer�id�_formatr+rrr�__repr__IszQueue.__repr__cCsdt|�j�d|���d�S)Nr7r8r9)r:rr<r+rrr�__str__Lsz
Queue.__str__cCs~d|j��}t|dd�r,|dt|j���7}|jrH|dt|j��d�7}|jrd|dt|j��d�7}|jrz|d|j��7}|S)Nzmaxsize=r(z _queue=z
 _getters[�]z
 _putters[z tasks=)r�getattr�listr(r�lenrr)r$�resultrrrr<Osz
Queue._formatcCs
t|j�S)zNumber of items in the queue.)rBr(r+rrr�qsize[szQueue.qsizecCs|jS)z%Number of items allowed in the queue.)rr+rrrr%_sz
Queue.maxsizecCs|jS)z3Return True if the queue is empty, False otherwise.�r(r+rrr�emptydszQueue.emptycCs |jdkrdS|��|jkSdS)z�Return True if there are maxsize items in the queue.

        Note: if the Queue was initialized with maxsize=0 (the default),
        then full() is never True.
        rFN)rrDr+rrr�fullhs
z
Queue.fullc�s�|��r�|j��}|j�|�z|IdHWq|��z|j�|�Wntk
r`YnX|��s~|��s~|�	|j��YqXq|�
|�S)z�Put an item into the queue.

        Put an item into the queue. If the queue is full, wait until a free
        slot is available before adding item.
        N)rGr�
create_futurerr.�cancel�remove�
ValueError�	cancelledr6�
put_nowait)r$r0�putterrrr�putss

z	Queue.putcCs>|��rt�|�|�|jd7_|j��|�|j�dS)zyPut an item into the queue without blocking.

        If no free slot is immediately available, raise QueueFull.
        rN)rGrr1rr!�clearr6rr/rrrrM�s

zQueue.put_nowaitc�s�|��r�|j��}|j�|�z|IdHWq|��z|j�|�Wntk
r`YnX|��s~|��s~|�	|j��YqXq|�
�S)zoRemove and return an item from the queue.

        If queue is empty, wait until an item is available.
        N)rFrrHrr.rIrJrKrLr6�
get_nowait)r$�getterrrr�get�s

z	Queue.getcCs$|��rt�|��}|�|j�|S)z�Remove and return an item from the queue.

        Return an item if one is immediately available, else raise QueueEmpty.
        )rFrr,r6rr/rrrrQ�s
zQueue.get_nowaitcCs8|jdkrtd��|jd8_|jdkr4|j��dS)a$Indicate that a formerly enqueued task is complete.

        Used by queue consumers. For each get() used to fetch a task,
        a subsequent call to task_done() tells the queue that the processing
        on the task is complete.

        If a join() is currently blocking, it will resume when all items have
        been processed (meaning that a task_done() call was received for every
        item that had been put() into the queue).

        Raises ValueError if called more times than there were items placed in
        the queue.
        rz!task_done() called too many timesrN)rrKr!r"r+rrr�	task_done�s


zQueue.task_donec�s|jdkr|j��IdHdS)aBlock until all items in the queue have been gotten and processed.

        The count of unfinished tasks goes up whenever an item is added to the
        queue. The count goes down whenever a consumer calls task_done() to
        indicate that the item was retrieved and all work on it is complete.
        When the count of unfinished tasks drops to zero, join() unblocks.
        rN)rr!�waitr+rrr�join�s
z
Queue.join)r)rrr
rr&r#r,r1r6r=r>r<rD�propertyr%rFrGrOrMrSrQrTrVrrrrrs(
rc@s4eZdZdZdd�Zejfdd�Zejfdd�Z	dS)	rz�A subclass of Queue; retrieves entries in priority order (lowest first).

    Entries are typically tuples of the form: (priority number, data).
    cCs
g|_dSr'rEr)rrrr#�szPriorityQueue._initcCs||j|�dSr'rE)r$r0�heappushrrrr1�szPriorityQueue._putcCs
||j�Sr'rE)r$�heappoprrrr,�szPriorityQueue._getN)
rrr
rr#�heapqrXr1rYr,rrrrr�src@s(eZdZdZdd�Zdd�Zdd�ZdS)	rzEA subclass of Queue that retrieves most recently added entries first.cCs
g|_dSr'rEr)rrrr#�szLifoQueue._initcCs|j�|�dSr'r-r/rrrr1�szLifoQueue._putcCs
|j��Sr')r(�popr+rrrr,�szLifoQueue._getN)rrr
rr#r1r,rrrrr�sr)
�__all__rrZr�rr	�	Exceptionrrrrrrrrr�<module>sK�h�#bytecode of module 'asyncio.queues'�u��b.���h)��N}�(hB��@sBdZddlmZddlmZddlmZdd�dd�Zd	d
�ZdS))�run�)�
coroutines)�events)�tasksN)�debugcCs�t��dk	rtd��t�|�s,td�|���t��}z*t�|�|dk	rR|�
|�|�|�W�Szt
|�|�|���W5t�d�|�	�XXdS)a�Execute the coroutine and return the result.

    This function runs the passed coroutine, taking care of
    managing the asyncio event loop and finalizing asynchronous
    generators.

    This function cannot be called when another asyncio event loop is
    running in the same thread.

    If debug is True, the event loop will be run in debug mode.

    This function always creates a new event loop and closes it at the end.
    It should be used as a main entry point for asyncio programs, and should
    ideally only be called once.

    Example:

        async def main():
            await asyncio.sleep(1)
            print('hello')

        asyncio.run(main())
    Nz8asyncio.run() cannot be called from a running event loopz"a coroutine was expected, got {!r})r�_get_running_loop�RuntimeErrorr�iscoroutine�
ValueError�format�new_event_loop�set_event_loop�close�_cancel_all_tasks�run_until_complete�shutdown_asyncgens�	set_debug)�mainr�loop�r�%/usr/lib/python3.8/asyncio/runners.pyrs"�



rcCsvt�|�}|sdS|D]}|��q|�tj||dd���|D]0}|��rNq@|��dk	r@|�d|��|d��q@dS)NT)r�return_exceptionsz1unhandled exception during asyncio.run() shutdown)�message�	exception�task)r�	all_tasks�cancelr�gather�	cancelledr�call_exception_handler)r�	to_cancelrrrrr6s"

��r)�__all__�rrrrrrrrr�<module>s
.�h�$bytecode of module 'asyncio.runners'�u��b.��,th)��N}�(hB�s�@s.dZdZddlZddlZddlZddlZddlZddlZddlZzddl	Z	Wne
k
rddZ	YnXddlmZddlm
Z
ddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZdd�Zdd�ZGdd�dej�ZGdd�dejej�ZGdd�de�ZGdd�de�ZdS)z�Event loop using a selector and related classes.

A selector is a "notify-when-ready" multiplexer.  For a subclass which
also includes support for signal handling, see the unix_events sub-module.
)�BaseSelectorEventLoop�N�)�base_events)�	constants)�events)�futures)�	protocols)�sslproto)�
transports)�trsock)�loggercCs8z|�|�}Wntk
r$YdSXt|j|@�SdS�NF)�get_key�KeyError�boolr)�selector�fd�event�key�r�-/usr/lib/python3.8/asyncio/selector_events.py�_test_selector_event s
rcCs tdk	rt|tj�rtd��dS)Nz"Socket cannot be of type SSLSocket)�ssl�
isinstance�	SSLSocket�	TypeError)�sockrrr�_check_ssl_socket+srcs�eZdZdZdS�fdd�	ZdTddd�dd�ZdUddddejd	�d
d�ZdVdd
�Z	�fdd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdddejfdd�Zdddejfdd�Zddejfdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�Zd5d6�Zd7d8�Zd9d:�Zd;d<�Z d=d>�Z!d?d@�Z"dAdB�Z#dCdD�Z$dEdF�Z%dGdH�Z&dIdJ�Z'dKdL�Z(dMdN�Z)dOdP�Z*dQdR�Z+�Z,S)WrzJSelector event loop.

    See events.EventLoop for API specification.
    NcsFt���|dkrt��}t�d|jj�||_|�	�t
��|_dS)NzUsing selector: %s)
�super�__init__�	selectors�DefaultSelectorr�debug�	__class__�__name__�	_selector�_make_self_pipe�weakref�WeakValueDictionary�_transports)�selfr�r#rrr6s
zBaseSelectorEventLoop.__init__��extra�servercCst||||||�S�N)�_SelectorSocketTransport)r*r�protocol�waiterr-r.rrr�_make_socket_transport@s
�z,BaseSelectorEventLoop._make_socket_transportF)�server_side�server_hostnamer-r.�ssl_handshake_timeoutc	Cs0tj|||||||	d�}
t|||
||d�|
jS)N)r6r,)r	�SSLProtocolr0�_app_transport)r*�rawsockr1�
sslcontextr2r4r5r-r.r6�ssl_protocolrrr�_make_ssl_transportEs��z)BaseSelectorEventLoop._make_ssl_transportcCst||||||�Sr/)�_SelectorDatagramTransport)r*rr1�addressr2r-rrr�_make_datagram_transportRs
�z.BaseSelectorEventLoop._make_datagram_transportcsL|��rtd��|��rdS|��t���|jdk	rH|j��d|_dS)Nz!Cannot close a running event loop)�
is_running�RuntimeError�	is_closed�_close_self_piper�closer%�r*r+rrrDWs


zBaseSelectorEventLoop.closecCsB|�|j���|j��d|_|j��d|_|jd8_dS)Nr)�_remove_reader�_ssock�filenorD�_csock�
_internal_fdsrErrrrCbs

z&BaseSelectorEventLoop._close_self_pipecCsNt��\|_|_|j�d�|j�d�|jd7_|�|j��|j�dS)NFr)	�socket�
socketpairrGrI�setblockingrJ�_add_readerrH�_read_from_selfrErrrr&js
z%BaseSelectorEventLoop._make_self_pipecCsdSr/r�r*�datarrr�_process_self_datarsz(BaseSelectorEventLoop._process_self_datacCsXz"|j�d�}|sWqT|�|�Wqtk
r:YqYqtk
rPYqTYqXqdS)Ni)rG�recvrR�InterruptedError�BlockingIOErrorrPrrrrOusz%BaseSelectorEventLoop._read_from_selfcCsN|j}|dkrdSz|�d�Wn(tk
rH|jrDtjddd�YnXdS)N�z3Fail to write a null byte into the self-pipe socketT��exc_info)rI�send�OSError�_debugrr")r*�csockrrr�_write_to_self�s�z$BaseSelectorEventLoop._write_to_self�dc
Cs"|�|��|j||||||�dSr/)rNrH�_accept_connection)r*�protocol_factoryrr:r.�backlogr6rrr�_start_serving�s�z$BaseSelectorEventLoop._start_servingc
Cst|�D]�}z0|��\}}	|jr0t�d||	|�|�d�Wn�tttfk
rZYdSt	k
r�}
zd|
j
t
jt
jt
j
t
jfkr�|�d|
t�|�d��|�|���|�tj|j||||||�n�W5d}
~
XYqXd|	i}|�||||||�}|�|�qdS)Nz#%r got a new connection from %r: %rFz&socket.accept() out of system resource)�message�	exceptionrK�peername)�range�acceptr[rr"rMrUrT�ConnectionAbortedErrorrZ�errno�EMFILE�ENFILE�ENOBUFS�ENOMEM�call_exception_handlerr�TransportSocketrFrH�
call_laterr�ACCEPT_RETRY_DELAYrb�_accept_connection2�create_task)
r*r`rr:r.rar6�_�conn�addr�excr-rgrrrr_�sV�����z(BaseSelectorEventLoop._accept_connectionc
�s�d}d}zt|�}|��}	|r8|j||||	d|||d�}n|j|||	||d�}z|	IdHWntk
rx|���YnXWntttfk
r��Yn\tk
r�}
z>|jr�d|
d�}|dk	r�||d<|dk	r�||d<|�|�W5d}
~
XYnXdS)NT)r2r4r-r.r6)r2r-r.z3Error on transport creation for incoming connection)rcrdr1�	transport)	�
create_futurer<r3�
BaseExceptionrD�
SystemExit�KeyboardInterruptr[rn)r*r`rur-r:r.r6r1rxr2rw�contextrrrrr�sP���z)BaseSelectorEventLoop._accept_connection2c
Cs�|}t|t�sJzt|���}Wn*tttfk
rHtd|���d�YnXz|j|}Wntk
rlYnX|��s�t	d|�d|����dS)NzInvalid file object: zFile descriptor z is used by transport )
r�intrH�AttributeErrorr�
ValueErrorr)r�
is_closingrA)r*rrHrxrrr�_ensure_fd_no_transport�s
�z-BaseSelectorEventLoop._ensure_fd_no_transportc		Gs�|��t�|||d�}z|j�|�}Wn*tk
rR|j�|tj|df�Yn>X|j|j	}\}}|j�
||tjB||f�|dk	r�|��dSr/)�
_check_closedr�Handler%rr�registerr �
EVENT_READrQ�modify�cancel�	r*r�callback�args�handler�mask�reader�writerrrrrNs�
�z!BaseSelectorEventLoop._add_readercCs�|��rdSz|j�|�}Wntk
r2YdSX|j|j}\}}|tjM}|sd|j�|�n|j�	||d|f�|dk	r�|�
�dSdSdS�NFT)rBr%rrrrQr r��
unregisterr�r��r*rrr�r�r�rrrrFsz$BaseSelectorEventLoop._remove_readerc		Gs�|��t�|||d�}z|j�|�}Wn*tk
rR|j�|tjd|f�Yn>X|j|j	}\}}|j�
||tjB||f�|dk	r�|��dSr/)r�rr�r%rrr�r �EVENT_WRITErQr�r�r�rrr�_add_writer%s�
�z!BaseSelectorEventLoop._add_writercCs�|��rdSz|j�|�}Wntk
r2YdSX|j|j}\}}|tjM}|sd|j�|�n|j�	|||df�|dk	r�|�
�dSdSdS)�Remove a writer callback.FNT)rBr%rrrrQr r�r�r�r�r�rrr�_remove_writer4sz$BaseSelectorEventLoop._remove_writercGs|�|�|j||f|��S)zAdd a reader callback.)r�rN�r*rr�r�rrr�
add_readerKs
z BaseSelectorEventLoop.add_readercCs|�|�|�|�S)zRemove a reader callback.)r�rF�r*rrrr�
remove_readerPs
z#BaseSelectorEventLoop.remove_readercGs|�|�|j||f|��S)zAdd a writer callback..)r�r�r�rrr�
add_writerUs
z BaseSelectorEventLoop.add_writercCs|�|�|�|�S)r�)r�r�r�rrr�
remove_writerZs
z#BaseSelectorEventLoop.remove_writerc	�s�t|�|jr"|��dkr"td��z|�|�WSttfk
rFYnX|��}|��}|�	||j
|||�|�t�
|j|��|IdHS)z�Receive data from the socket.

        The return value is a bytes object representing the data received.
        The maximum amount of data to be received at once is specified by
        nbytes.
        r�the socket must be non-blockingN)rr[�
gettimeoutr�rSrUrTryrHr��
_sock_recv�add_done_callback�	functools�partial�_sock_read_done)r*r�n�futrrrr�	sock_recv_s�zBaseSelectorEventLoop.sock_recvcCs|�|�dSr/)r��r*rr�rrrr�tsz%BaseSelectorEventLoop._sock_read_donec
Cs�|��rdSz|�|�}Wn\ttfk
r4YdSttfk
rL�Yn6tk
rv}z|�|�W5d}~XYnX|�|�dSr/)	�donerSrUrTr{r|rz�
set_exception�
set_result)r*r�rr�rQrwrrrr�wsz BaseSelectorEventLoop._sock_recvc	�s�t|�|jr"|��dkr"td��z|�|�WSttfk
rFYnX|��}|��}|�	||j
|||�|�t�
|j|��|IdHS)z�Receive data from the socket.

        The received data is written into *buf* (a writable buffer).
        The return value is the number of bytes written.
        rr�N)rr[r�r��	recv_intorUrTryrHr��_sock_recv_intor�r�r�r�)r*r�bufr�rrrr�sock_recv_into�s�z$BaseSelectorEventLoop.sock_recv_intoc
Cs�|��rdSz|�|�}Wn\ttfk
r4YdSttfk
rL�Yn6tk
rv}z|�|�W5d}~XYnX|�|�dSr/)	r�r�rUrTr{r|rzr�r�)r*r�rr��nbytesrwrrrr��sz%BaseSelectorEventLoop._sock_recv_intoc	�s�t|�|jr"|��dkr"td��z|�|�}Wnttfk
rLd}YnX|t|�kr^dS|��}|�	�}|�
t�|j
|��|�||j||t|�|g�|IdHS)a�Send data to the socket.

        The socket must be connected to a remote socket. This method continues
        to send data from data until either all data has been sent or an
        error occurs. None is returned on success. On error, an exception is
        raised, and there is no way to determine how much data, if any, was
        successfully processed by the receiving end of the connection.
        rr�N)rr[r�r�rYrUrT�lenryrHr�r�r��_sock_write_doner��
_sock_sendall�
memoryview)r*rrQr�r�rrrr�sock_sendall�s&	
��z"BaseSelectorEventLoop.sock_sendallc
Cs�|��rdS|d}z|�||d��}Wnbttfk
rDYdSttfk
r\�Yn2tk
r�}z|�|�WY�dSd}~XYnX||7}|t|�kr�|�	d�n||d<dS)Nr)
r�rYrUrTr{r|rzr�r�r�)r*r�r�view�pos�startr�rwrrrr��s 
z#BaseSelectorEventLoop._sock_sendallc�s�t|�|jr"|��dkr"td��ttd�r8|jtjkrf|j||j|j	|d�IdH}|d\}}}}}|�
�}|�|||�|IdHS)zTConnect to a remote socket at address.

        This method is a coroutine.
        rr��AF_UNIX)�family�proto�loopN)rr[r�r��hasattrrKr�r��_ensure_resolvedr�ry�
_sock_connect)r*rr>�resolvedrtr�rrr�sock_connect�s�z"BaseSelectorEventLoop.sock_connectc
Cs�|��}z|�|�Wn�ttfk
rV|�t�|j|��|�||j	|||�YnNt
tfk
rn�Yn6tk
r�}z|�
|�W5d}~XYnX|�d�dSr/)rH�connectrUrTr�r�r�r�r��_sock_connect_cbr{r|rzr�r�)r*r�rr>rrwrrrr��s�z#BaseSelectorEventLoop._sock_connectcCs|�|�dSr/)r�r�rrrr�sz&BaseSelectorEventLoop._sock_write_donec
Cs�|��rdSz,|�tjtj�}|dkr6t|d|����WnZttfk
rPYnNtt	fk
rh�Yn6t
k
r�}z|�|�W5d}~XYnX|�d�dS)NrzConnect call failed )
r��
getsockoptrK�
SOL_SOCKET�SO_ERRORrZrUrTr{r|rzr�r�)r*r�rr>�errrwrrrr�sz&BaseSelectorEventLoop._sock_connect_cbc�sBt|�|jr"|��dkr"td��|��}|�|d|�|IdHS)aWAccept a connection.

        The socket must be bound to an address and listening for connections.
        The return value is a pair (conn, address) where conn is a new socket
        object usable to send and receive data on the connection, and address
        is the address bound to the socket on the other end of the connection.
        rr�FN)rr[r�r�ry�_sock_accept)r*rr�rrr�sock_acceptsz!BaseSelectorEventLoop.sock_acceptc
Cs�|��}|r|�|�|��r"dSz|��\}}|�d�Wnnttfk
rh|�||j|d|�YnRt	t
fk
r��Yn:tk
r�}z|�|�W5d}~XYnX|�
||f�dSr�)rHr�r�rgrMrUrTr�r�r{r|rzr�r�)r*r��
registeredrrrur>rwrrrr�*s
z"BaseSelectorEventLoop._sock_acceptc	�sp|j|j=|��}|��|��IdHz |j|j|||dd�IdHW�S|��|r^|��||j|j<XdS)NF)�fallback)	r)�_sock_fd�
is_reading�
pause_reading�_make_empty_waiter�_reset_empty_waiter�resume_reading�
sock_sendfile�_sock)r*�transp�file�offset�countr�rrr�_sendfile_native<s
�z&BaseSelectorEventLoop._sendfile_nativecCs�|D]v\}}|j|j}\}}|tj@rL|dk	rL|jrB|�|�n
|�|�|tj@r|dk	r|jrp|�|�q|�|�qdSr/)	�fileobjrQr r��
_cancelledrF�
_add_callbackr�r�)r*�
event_listrr�r�r�r�rrr�_process_eventsJs
z%BaseSelectorEventLoop._process_eventscCs|�|���|��dSr/)rFrHrD)r*rrrr�
_stop_servingXsz#BaseSelectorEventLoop._stop_serving)N)N)N)NNN)-r$�
__module__�__qualname__�__doc__rr3r�SSL_HANDSHAKE_TIMEOUTr<r?rDrCr&rRrOr]rbr_rrr�rNrFr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r��
__classcell__rrr+rr0s~
����
�
	�
.�
)rcs�eZdZdZeZdZd�fdd�	Zdd�Zdd�Z	d	d
�Z
dd�Zd
d�Zdd�Z
ejfdd�Zddd�Zdd�Zdd�Zdd�Zdd�Z�ZS) �_SelectorTransportiNcs�t��||�t�|�|jd<z|��|jd<Wntk
rNd|jd<YnXd|jkr�z|��|jd<Wn tj	k
r�d|jd<YnX||_
|��|_d|_
|�|�||_|��|_d|_d|_|jdk	r�|j��||j|j<dS)NrKZsocknamereFr)rrrro�_extra�getsocknamerZ�getpeernamerK�errorr�rHr��_protocol_connected�set_protocol�_server�_buffer_factory�_buffer�
_conn_lost�_closing�_attachr))r*r�rr1r-r.r+rrris,





z_SelectorTransport.__init__cCs�|jjg}|jdkr |�d�n|jr0|�d�|�d|j���|jdk	r�|j��s�t|jj	|jt
j�}|rz|�d�n
|�d�t|jj	|jt
j�}|r�d}nd}|�
�}|�d|�d	|�d
��d�d�|��S)
N�closed�closingzfd=zread=pollingz	read=idle�pollingZidlezwrite=<z
, bufsize=�>z<{}>� )r#r$r��appendr�r��_looprBrr%r r�r��get_write_buffer_size�format�join)r*�infor��state�bufsizerrr�__repr__�s0


�
�z_SelectorTransport.__repr__cCs|�d�dSr/)�_force_closerErrr�abort�sz_SelectorTransport.abortcCs||_d|_dS�NT)�	_protocolr��r*r1rrrr��sz_SelectorTransport.set_protocolcCs|jSr/)rrErrr�get_protocol�sz_SelectorTransport.get_protocolcCs|jSr/)r�rErrrr��sz_SelectorTransport.is_closingcCsT|jr
dSd|_|j�|j�|jsP|jd7_|j�|j�|j�|jd�dS�NTr)	r�r�rFr�r�r�r��	call_soon�_call_connection_lostrErrrrD�sz_SelectorTransport.closecCs,|jdk	r(|d|��t|d�|j��dS)Nzunclosed transport )�source)r��ResourceWarningrD)r*�_warnrrr�__del__�s
z_SelectorTransport.__del__�Fatal error on transportcCsNt|t�r(|j��r@tjd||dd�n|j�||||jd��|�|�dS)Nz%r: %sTrW)rcrdrxr1)	rrZr��	get_debugrr"rnrr�)r*rwrcrrr�_fatal_error�s

�z_SelectorTransport._fatal_errorcCsd|jr
dS|jr(|j��|j�|j�|jsBd|_|j�|j�|jd7_|j�|j	|�dSr)
r�r��clearr�r�r�r�rFrr�r*rwrrrr��s
z_SelectorTransport._force_closecCsVz|jr|j�|�W5|j��d|_d|_d|_|j}|dk	rP|��d|_XdSr/)r�rDrr�r��_detachr��connection_lost)r*rwr.rrrr�s
z(_SelectorTransport._call_connection_lostcCs
t|j�Sr/)r�r�rErrrr��sz(_SelectorTransport.get_write_buffer_sizecGs"|jr
dS|jj||f|��dSr/)r�r�rNr�rrrrN�sz_SelectorTransport._add_reader)NN)r)r$r�r��max_size�	bytearrayr�r�rr�r�r�rr�rD�warnings�warnr
r
r�rr�rNr�rrr+rr�]s 

r�cs�eZdZdZejjZd#�fdd�	Z�fdd�Z	dd�Z
d	d
�Zdd�Zd
d�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Z�fdd�Zdd �Zd!d"�Z�ZS)$r0TNcs~d|_t��|||||�d|_d|_d|_t�|j�|j	�
|jj|�|j	�
|j
|j|j�|dk	rz|j	�
tj|d�dSr
)�_read_ready_cbrr�_eof�_paused�
_empty_waiterr�_set_nodelayr�r�rr�connection_maderNr��_read_readyr�_set_result_unless_cancelled)r*r�rr1r2r-r.r+rrr�s 
�
�z!_SelectorSocketTransport.__init__cs.t|tj�r|j|_n|j|_t��|�dSr/)rr�BufferedProtocol�_read_ready__get_bufferr�_read_ready__data_receivedrr�rr+rrr�	s
z%_SelectorSocketTransport.set_protocolcCs|jo|jSr/)rr�rErrrr�sz#_SelectorSocketTransport.is_readingcCs>|js|jrdSd|_|j�|j�|j��r:t�d|�dS)NTz%r pauses reading)r�rr�rFr�rrr"rErrrr�s
z&_SelectorSocketTransport.pause_readingcCs@|js|jsdSd|_|�|j|j�|j��r<t�d|�dS)NFz%r resumes reading)	r�rrNr�rr�rrr"rErrrr�s
z'_SelectorSocketTransport.resume_readingcCs|��dSr/)rrErrrr$sz$_SelectorSocketTransport._read_readyc
Cs`|jr
dSz |j�d�}t|�s(td��WnLttfk
rD�Yn4tk
rv}z|�|d�WY�dSd}~XYnXz|j	�
|�}Wndttfk
r�YdSttfk
r��Yn4tk
r�}z|�|d�WY�dSd}~XYnX|�s|�
�dSz|j�|�WnJttfk
�r,�Yn0tk
�rZ}z|�|d�W5d}~XYnXdS)N���z%get_buffer() returned an empty bufferz/Fatal error: protocol.get_buffer() call failed.�$Fatal read error on socket transportz3Fatal error: protocol.buffer_updated() call failed.)r�r�
get_bufferr�rAr{r|rzr
r�r�rUrT�_read_ready__on_eof�buffer_updated)r*r�rwr�rrrr'sF��z0_SelectorSocketTransport._read_ready__get_bufferc
Cs�|jr
dSz|j�|j�}Wndttfk
r6YdSttfk
rN�Yn4tk
r�}z|�	|d�WY�dSd}~XYnX|s�|�
�dSz|j�|�WnFttfk
r��Yn.tk
r�}z|�	|d�W5d}~XYnXdS)Nr"z2Fatal error: protocol.data_received() call failed.)
r�r�rSrrUrTr{r|rzr
r$r�
data_received)r*rQrwrrrr Ls.�z3_SelectorSocketTransport._read_ready__data_receivedc
Cs�|j��rt�d|�z|j��}WnLttfk
r>�Yn4tk
rp}z|�	|d�WY�dSd}~XYnX|r�|j�
|j�n|��dS)Nz%r received EOFz1Fatal error: protocol.eof_received() call failed.)
r�rrr"r�eof_receivedr{r|rzr
rFr�rD)r*�	keep_openrwrrrr$es
�z,_SelectorSocketTransport._read_ready__on_eofc
Cs6t|tttf�s$tdt|�j����|jr2td��|j	dk	rDtd��|sLdS|j
rz|j
tjkrht
�d�|j
d7_
dS|j�sz|j�|�}Wnbttfk
r�Ynbttfk
r��YnJtk
r�}z|�|d�WY�dSd}~XYnX||d�}|�sdS|j�|j|j�|j�|�|��dS)N�/data argument must be a bytes-like object, not z%Cannot call write() after write_eof()z(unable to write; sendfile is in progress�socket.send() raised exception.r�%Fatal write error on socket transport)r�bytesrr�r�typer$rrArr�r�!LOG_THRESHOLD_FOR_CONNLOST_WRITESr�warningr�r�rYrUrTr{r|rzr
r�r�r��_write_ready�extend�_maybe_pause_protocol)r*rQr�rwrrr�writezs:

z_SelectorSocketTransport.writec
Cs(|jstd��|jrdSz|j�|j�}Wn�ttfk
rBYn�ttfk
rZ�Yn�t	k
r�}z>|j
�|j�|j�
�|�|d�|jdk	r�|j�|�W5d}~XYnpX|r�|jd|�=|��|j�s$|j
�|j�|jdk	r�|j�d�|j�r|�d�n|j�r$|j�tj�dS)NzData should not be emptyr+)r��AssertionErrorr�r�rYrUrTr{r|rzr�r�r�rr
rr��_maybe_resume_protocolr�r�rr�shutdownrK�SHUT_WR)r*r�rwrrrr0�s4


z%_SelectorSocketTransport._write_readycCs.|js|jrdSd|_|js*|j�tj�dSr)r�rr�r�r6rKr7rErrr�	write_eof�s
z"_SelectorSocketTransport.write_eofcCsdSrrrErrr�
can_write_eof�sz&_SelectorSocketTransport.can_write_eofcs*t��|�|jdk	r&|j�td��dS)NzConnection is closed by peer)rrrr��ConnectionErrorrr+rrr�s

�z._SelectorSocketTransport._call_connection_lostcCs6|jdk	rtd��|j��|_|js0|j�d�|jS)NzEmpty waiter is already set)rrAr�ryr�r�rErrrr��s
z+_SelectorSocketTransport._make_empty_waitercCs
d|_dSr/)rrErrrr��sz,_SelectorSocketTransport._reset_empty_waiter)NNN)r$r�r��_start_tls_compatibler�
_SendfileMode�
TRY_NATIVE�_sendfile_compatiblerr�r�r�r�rrr r$r3r0r8r9rr�r�r�rrr+rr0�s*�%'r0csFeZdZejZd�fdd�	Zdd�Zdd�Zd
dd	�Z	d
d�Z
�ZS)r=Ncs^t��||||�||_|j�|jj|�|j�|j|j|j	�|dk	rZ|j�t
j|d�dSr/)rr�_addressr�rrrrNr�rrr)r*r�rr1r>r2r-r+rrr�s
�
�z#_SelectorDatagramTransport.__init__cCstdd�|jD��S)Ncss|]\}}t|�VqdSr/)r�)�.0rQrtrrr�	<genexpr>�szC_SelectorDatagramTransport.get_write_buffer_size.<locals>.<genexpr>)�sumr�rErrrr��sz0_SelectorDatagramTransport.get_write_buffer_sizec
Cs�|jr
dSz|j�|j�\}}Wn�ttfk
r8Yn�tk
rd}z|j�|�W5d}~XYnTt	t
fk
r|�Yn<tk
r�}z|�|d�W5d}~XYnX|j�
||�dS)Nz&Fatal read error on datagram transport)r�r��recvfromrrUrTrZr�error_receivedr{r|rzr
�datagram_received�r*rQrvrwrrrr�sz&_SelectorDatagramTransport._read_readyc
Cs�t|tttf�s$tdt|�j����|s,dS|jrV|d|jfkrPtd|j����|j}|j	r�|jr�|j	t
jkrxt�
d�|j	d7_	dS|j�slz,|jdr�|j�|�n|j�||�WdSttfk
r�|j�|j|j�Yn�tk
�r}z|j�|�WY�dSd}~XYnPttfk
�r6�Yn6tk
�rj}z|�|d�WY�dSd}~XYnX|j� t|�|f�|�!�dS)Nr)z!Invalid address: must be None or r*rre�'Fatal write error on datagram transport)"rr,rr�rr-r$r?r�r�rr.rr/r�r�r�rY�sendtorUrTr�r�r��
_sendto_readyrZrrDr{r|rzr
r�r2rFrrrrH�sH
�

�z!_SelectorDatagramTransport.sendtoc
Cs|jr�|j��\}}z*|jdr.|j�|�n|j�||�Wqttfk
rj|j�||f�Yq�Yqt	k
r�}z|j
�|�WY�dSd}~XYqtt
fk
r��Yqtk
r�}z|�|d�WY�dSd}~XYqXq|��|j�s|j�|j�|j�r|�d�dS)NrerG)r��popleftr�r�rYrHrUrT�
appendleftrZrrDr{r|rzr
r5r�r�r�r�rrFrrrrI*s2
�z(_SelectorDatagramTransport._sendto_ready)NNN)N)r$r�r��collections�dequer�rr�rrHrIr�rrr+rr=�s�

+r=)r��__all__rLrir�r rKrr'r�ImportError�rrrrrr	r
r�logrrr�
BaseEventLoopr�_FlowControlMixin�	Transportr�r0r=rrrr�<module>sF
1�o�h�,bytecode of module 'asyncio.selector_events'�u��b.���Th)��N}�(hBbT�@s�ddlZddlZzddlZWnek
r4dZYnXddlmZddlmZddlmZddlmZddl	m
Z
dd	�Zd
ZdZ
dZd
ZGdd�de�ZGdd�dejej�ZGdd�dej�ZdS)�N�)�base_events)�	constants)�	protocols)�
transports)�loggercCs"|rtd��t��}|sd|_|S)Nz(Server side SSL needs a valid SSLContextF)�
ValueError�ssl�create_default_context�check_hostname)�server_side�server_hostname�
sslcontext�r�&/usr/lib/python3.8/asyncio/sslproto.py�_create_transport_contextsrZ	UNWRAPPEDZDO_HANDSHAKEZWRAPPED�SHUTDOWNc@s~eZdZdZdZddd�Zedd��Zedd	��Zed
d��Z	edd
��Z
ddd�Zddd�Zdd�Z
ddd�Zddd�ZdS)�_SSLPipeaAn SSL "Pipe".

    An SSL pipe allows you to communicate with an SSL/TLS protocol instance
    through memory buffers. It can be used to implement a security layer for an
    existing connection where you don't have access to the connection's file
    descriptor, or for some reason you don't want to use it.

    An SSL pipe can be in "wrapped" and "unwrapped" mode. In unwrapped mode,
    data is passed through untransformed. In wrapped mode, application level
    data is encrypted to SSL record level data and vice versa. The SSL record
    level is the lowest level in the SSL protocol suite and is what travels
    as-is over the wire.

    An SslPipe initially is in "unwrapped" mode. To start SSL, call
    do_handshake(). To shutdown SSL again, call unwrap().
    iNcCsH||_||_||_t|_t��|_t��|_d|_	d|_
d|_d|_dS)a�
        The *context* argument specifies the ssl.SSLContext to use.

        The *server_side* argument indicates whether this is a server side or
        client side transport.

        The optional *server_hostname* argument can be used to specify the
        hostname you are connecting to. You may only specify this parameter if
        the _ssl module supports Server Name Indication (SNI).
        NF)
�_context�_server_side�_server_hostname�
_UNWRAPPED�_stater	�	MemoryBIO�	_incoming�	_outgoing�_sslobj�
_need_ssldata�
_handshake_cb�_shutdown_cb)�self�contextrr
rrr�__init__8s

z_SSLPipe.__init__cCs|jS)z*The SSL context passed to the constructor.)r�r rrrr!Nsz_SSLPipe.contextcCs|jS)z^The internal ssl.SSLObject instance.

        Return None if the pipe is not wrapped.
        )rr#rrr�
ssl_objectSsz_SSLPipe.ssl_objectcCs|jS)zgWhether more record level data is needed to complete a handshake
        that is currently in progress.)rr#rrr�need_ssldata[sz_SSLPipe.need_ssldatacCs
|jtkS)zj
        Whether a security layer is currently in effect.

        Return False during handshake.
        )r�_WRAPPEDr#rrr�wrappedasz_SSLPipe.wrappedcCsb|jtkrtd��|jj|j|j|j|jd�|_	t
|_||_|jddd�\}}t
|�dks^t�|S)aLStart the SSL handshake.

        Return a list of ssldata. A ssldata element is a list of buffers

        The optional *callback* argument can be used to install a callback that
        will be called when the handshake is complete. The callback will be
        called with None if successful, else an exception instance.
        z"handshake in progress or completed)rr
�T)�only_handshaker)rr�RuntimeErrorr�wrap_biorrrrr�
_DO_HANDSHAKEr�feed_ssldata�len�AssertionError�r �callback�ssldata�appdatarrr�do_handshakejs	
�z_SSLPipe.do_handshakecCsj|jtkrtd��|jtkr$td��|jttfks6t�t|_||_|�d�\}}|gksf|dgksft�|S)a1Start the SSL shutdown sequence.

        Return a list of ssldata. A ssldata element is a list of buffers

        The optional *callback* argument can be used to install a callback that
        will be called when the shutdown is complete. The callback will be
        called without arguments.
        zno security layer presentzshutdown in progressr()	rrr*�	_SHUTDOWNr&r,r/rr-r0rrr�shutdowns	

z_SSLPipe.shutdowncCs2|j��|�d�\}}|gks.|dgks.t�dS)z�Send a potentially "ragged" EOF.

        This method will raise an SSL_ERROR_EOF exception if the EOF is
        unexpected.
        r(N)r�	write_eofr-r/)r r2r3rrr�feed_eof�s
z_SSLPipe.feed_eofFc
Cs�|jtkr"|r|g}ng}g|fSd|_|r8|j�|�g}g}z�|jtkrz|j��t|_|j	rl|�	d�|rz||fWS|jtkr�|j�
|j�}|�|�|s�q�q�nJ|jt
kr�|j��d|_t|_|jr�|��n|jtkr�|�|j�
��Wnztjtjfk
�rl}zRt|dd�}|tjtjtjfk�rP|jtk�rN|j	�rN|�	|��|tjk|_W5d}~XYnX|jj�r�|�|j�
��||fS)a�Feed SSL record level data into the pipe.

        The data must be a bytes instance. It is OK to send an empty bytes
        instance. This can be used to get ssldata for a handshake initiated by
        this endpoint.

        Return a (ssldata, appdata) tuple. The ssldata element is a list of
        buffers containing SSL data that needs to be sent to the remote SSL.

        The appdata element is a list of buffers containing plaintext data that
        needs to be forwarded to the application. The appdata list may contain
        an empty buffer indicating an SSL "close_notify" alert. This alert must
        be acknowledged by calling shutdown().
        FN�errno)rrrr�writer,rr4r&r�read�max_size�appendr5�unwraprr	�SSLError�CertificateError�getattr�SSL_ERROR_WANT_READ�SSL_ERROR_WANT_WRITE�SSL_ERROR_SYSCALLr�pending)r �datar)r3r2�chunk�exc�	exc_errnorrrr-�sZ










�

z_SSLPipe.feed_ssldatarc
Cs4d|krt|�ksnt�|jtkrT|t|�krD||d�g}ng}|t|�fSg}t|�}d|_z(|t|�kr�||j�||d��7}Wnhtj	k
r�}zHt
|dd�}|jdkr�tj}|_
|tjtjtjfkrڂ|tjk|_W5d}~XYnX|jj�r|�|j���|t|�k�s,|jr`�q,q`||fS)aFeed plaintext data into the pipe.

        Return an (ssldata, offset) tuple. The ssldata element is a list of
        buffers containing record level data that needs to be sent to the
        remote SSL instance. The offset is the number of plaintext bytes that
        were processed, which may be less than the length of data.

        NOTE: In case of short writes, this call MUST be retried with the SAME
        buffer passed into the *data* argument (i.e. the id() must be the
        same). This is an OpenSSL requirement. A further particularity is that
        a short write will always have offset == 0, because the _ssl module
        does not enable partial writes. And even though the offset is zero,
        there will still be encrypted data in ssldata.
        rNFr9ZPROTOCOL_IS_SHUTDOWN)r.r/rr�
memoryviewrrr:r	r?rA�reasonrBr9rCrDrrEr=r;)r rF�offsetr2�viewrHrIrrr�feed_appdata�s6

�
z_SSLPipe.feed_appdata)N)N)N)F)r)�__name__�
__module__�__qualname__�__doc__r<r"�propertyr!r$r%r'r4r6r8r-rNrrrrr$s 








Krc@s�eZdZejjZdd�Zd"dd�Zdd�Z	dd	�Z
d
d�Zdd
�Ze
jfdd�Zdd�Zdd�Zdd�Zd#dd�Zdd�Zedd��Zdd�Zdd�Zd d!�ZdS)$�_SSLProtocolTransportcCs||_||_d|_dS)NF)�_loop�
_ssl_protocol�_closed)r �loop�ssl_protocolrrrr"!sz_SSLProtocolTransport.__init__NcCs|j�||�S)z#Get optional transport information.)rV�_get_extra_info�r �name�defaultrrr�get_extra_info'sz$_SSLProtocolTransport.get_extra_infocCs|j�|�dS�N)rV�_set_app_protocol)r �protocolrrr�set_protocol+sz"_SSLProtocolTransport.set_protocolcCs|jjSr_)rV�
_app_protocolr#rrr�get_protocol.sz"_SSLProtocolTransport.get_protocolcCs|jSr_)rWr#rrr�
is_closing1sz _SSLProtocolTransport.is_closingcCsd|_|j��dS)a
Close the transport.

        Buffered data will be flushed asynchronously.  No more data
        will be received.  After all buffered data is flushed, the
        protocol's connection_lost() method will (eventually) called
        with None as its argument.
        TN)rWrV�_start_shutdownr#rrr�close4sz_SSLProtocolTransport.closecCs&|js"|d|��t|d�|��dS)Nzunclosed transport )�source)rW�ResourceWarningrg)r �_warnrrr�__del__?sz_SSLProtocolTransport.__del__cCs |jj}|dkrtd��|��S)Nz*SSL transport has not been initialized yet)rV�
_transportr*�
is_reading)r �trrrrrmDsz _SSLProtocolTransport.is_readingcCs|jj��dS)z�Pause the receiving end.

        No data will be passed to the protocol's data_received()
        method until resume_reading() is called.
        N)rVrl�
pause_readingr#rrrroJsz#_SSLProtocolTransport.pause_readingcCs|jj��dS)z�Resume the receiving end.

        Data received will once again be passed to the protocol's
        data_received() method.
        N)rVrl�resume_readingr#rrrrpRsz$_SSLProtocolTransport.resume_readingcCs|jj�||�dS)a�Set the high- and low-water limits for write flow control.

        These two values control when to call the protocol's
        pause_writing() and resume_writing() methods.  If specified,
        the low-water limit must be less than or equal to the
        high-water limit.  Neither value can be negative.

        The defaults are implementation-specific.  If only the
        high-water limit is given, the low-water limit defaults to an
        implementation-specific value less than or equal to the
        high-water limit.  Setting high to zero forces low to zero as
        well, and causes pause_writing() to be called whenever the
        buffer becomes non-empty.  Setting low to zero causes
        resume_writing() to be called only once the buffer is empty.
        Use of zero for either limit is generally sub-optimal as it
        reduces opportunities for doing I/O and computation
        concurrently.
        N)rVrl�set_write_buffer_limits)r �high�lowrrrrqZsz-_SSLProtocolTransport.set_write_buffer_limitscCs|jj��S)z,Return the current size of the write buffer.)rVrl�get_write_buffer_sizer#rrrrtosz+_SSLProtocolTransport.get_write_buffer_sizecCs
|jjjSr_)rVrl�_protocol_pausedr#rrrrussz&_SSLProtocolTransport._protocol_pausedcCs<t|tttf�s$tdt|�j����|s,dS|j�|�dS)z�Write some data bytes to the transport.

        This does not block; it buffers the data and arranges for it
        to be sent out asynchronously.
        z+data: expecting a bytes-like instance, got N)	�
isinstance�bytes�	bytearrayrJ�	TypeError�typerOrV�_write_appdata�r rFrrrr:xs
z_SSLProtocolTransport.writecCsdS)zAReturn True if this transport supports write_eof(), False if not.Frr#rrr�
can_write_eof�sz#_SSLProtocolTransport.can_write_eofcCs|j��d|_dS)z�Close the transport immediately.

        Buffered data will be lost.  No more data will be received.
        The protocol's connection_lost() method will (eventually) be
        called with None as its argument.
        TN)rV�_abortrWr#rrr�abort�s
z_SSLProtocolTransport.abort)N)NN)rOrPrQr�
_SendfileMode�FALLBACK�_sendfile_compatibler"r^rbrdrerg�warnings�warnrkrmrorprqrtrSrur:r}rrrrrrTs$



rTc@s�eZdZdZd,dd�Zdd�Zd-d	d
�Zdd�Zd
d�Zdd�Z	dd�Z
dd�Zdd�Zd.dd�Z
dd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd/d&d'�Zd(d)�Zd*d+�ZdS)0�SSLProtocolz�SSL protocol.

    Implementation of SSL on top of a socket using incoming and outgoing
    buffers which are ssl.MemoryBIO objects.
    FNTc		Cs�tdkrtd��|dkr tj}n|dkr6td|����|sDt||�}||_|rZ|sZ||_nd|_||_t	|d�|_
t��|_
d|_||_||_|�|�t|j|�|_d|_d|_d|_d|_d|_||_||_dS)Nzstdlib ssl module not availablerz7ssl_handshake_timeout should be a positive number, got )rF)r	r*r�SSL_HANDSHAKE_TIMEOUTrrrr�_sslcontext�dict�_extra�collections�deque�_write_backlog�_write_buffer_size�_waiterrUr`rT�_app_transport�_sslpipe�_session_established�
_in_handshake�_in_shutdownrl�_call_connection_made�_ssl_handshake_timeout)	r rX�app_protocolr�waiterrr
�call_connection_made�ssl_handshake_timeoutrrrr"�s@��

zSSLProtocol.__init__cCs||_t|tj�|_dSr_)rcrvr�BufferedProtocol�_app_protocol_is_buffer)r r�rrrr`�s
�zSSLProtocol._set_app_protocolcCsD|jdkrdS|j��s:|dk	r.|j�|�n|j�d�d|_dSr_)r��	cancelled�
set_exception�
set_result�r rHrrr�_wakeup_waiter�s

zSSLProtocol._wakeup_waitercCs&||_t|j|j|j�|_|��dS)zXCalled when the low-level connection is made.

        Start the SSL handshake.
        N)rlrr�rrr��_start_handshake)r �	transportrrr�connection_made�s�zSSLProtocol.connection_madecCsn|jr d|_|j�|jj|�n|jdk	r2d|j_d|_d|_t|dd�rT|j	�
�|�|�d|_d|_dS)z�Called when the low-level connection is lost or closed.

        The argument is an exception object or None (the latter
        meaning a regular EOF is received or the connection was
        aborted or closed).
        FNT�_handshake_timeout_handle)
r�rU�	call_soonrc�connection_lostr�rWrlrAr��cancelr�r�r�rrrr��s


zSSLProtocol.connection_lostcCs|j��dS)z\Called when the low-level transport's buffer goes over
        the high-water mark.
        N)rc�
pause_writingr#rrrr��szSSLProtocol.pause_writingcCs|j��dS)z^Called when the low-level transport's buffer drains below
        the low-water mark.
        N)rc�resume_writingr#rrrr�szSSLProtocol.resume_writingcCs"|jdkrdSz|j�|�\}}WnLttfk
r<�Yn4tk
rn}z|�|d�WY�dSd}~XYnX|D]}|j�|�qt|D]�}|�rz&|jr�t	�
|j|�n|j�|�WnPttfk
r��Yn8tk
�r
}z|�|d�WY�dSd}~XYnXq�|�
��qq�dS)zXCalled when some SSL data is received.

        The argument is a bytes object.
        NzSSL error in data receivedz/application protocol failed to receive SSL data)r�r-�
SystemExit�KeyboardInterrupt�
BaseException�_fatal_errorrlr:r�r�_feed_data_to_buffered_protorc�
data_receivedrf)r rFr2r3�erG�exrrrr�s<
��zSSLProtocol.data_receivedcCsTzB|j��rt�d|�|�t�|js@|j	�
�}|r@t�d�W5|j��XdS)aCalled when the other end of the low-level stream
        is half-closed.

        If this returns a false value (including None), the transport
        will close itself.  If it returns a true value, closing the
        transport is up to the protocol.
        z%r received EOFz?returning true from eof_received() has no effect when using sslN)rlrgrU�	get_debugr�debugr��ConnectionResetErrorr�rc�eof_received�warning)r �	keep_openrrrr�-s


zSSLProtocol.eof_receivedcCs4||jkr|j|S|jdk	r,|j�||�S|SdSr_)r�rlr^r[rrrrZCs



zSSLProtocol._get_extra_infocCs.|jr
dS|jr|��nd|_|�d�dS)NTr()r�r�r~r{r#rrrrfKs
zSSLProtocol._start_shutdowncCs.|j�|df�|jt|�7_|��dS)Nr)r�r=r�r.�_process_write_backlogr|rrrr{TszSSLProtocol._write_appdatacCs\|j��r$t�d|�|j��|_nd|_d|_|j�d�|j�	|j
|j�|_|�
�dS)Nz%r starts SSL handshakeT)r(r)rUr�rr��time�_handshake_start_timer�r�r=�
call_laterr��_check_handshake_timeoutr�r�r#rrrr�Ys

��zSSLProtocol._start_handshakecCs*|jdkr&d|j�d�}|�t|��dS)NTz$SSL handshake is taking longer than z! seconds: aborting the connection)r�r�r��ConnectionAbortedError)r �msgrrrr�hs
�z$SSLProtocol._check_handshake_timeoutc
Csd|_|j��|jj}z|dk	r&|�|��}Wnbttfk
rJ�YnJtk
r�}z,t	|t
j�rld}nd}|�||�WY�dSd}~XYnX|j
��r�|j
��|j}t�d||d�|jj||��|��|d�|jr�|j�|j�|��d|_|j
�|j�dS)NFz1SSL handshake failed on verifying the certificatezSSL handshake failedz%r: SSL handshake took %.1f msg@�@)�peercert�cipher�compressionr$T)r�r�r�r�r$�getpeercertr�r�r�rvr	r@r�rUr�r�r�rr�r��updater�r�r�rcr�r�r�r�r�r�)r �
handshake_exc�sslobjr�rHr��dtrrr�_on_handshake_completeqs8

�z"SSLProtocol._on_handshake_completec
CsP|jdks|jdkrdSz�tt|j��D]�}|jd\}}|rR|j�||�\}}n*|rj|j�|j�}d}n|j�|j	�}d}|D]}|j�
|�q�|t|�kr�||f|jd<|jjs�t�|jj
r�|j��q�|jd=|jt|�8_q(Wn^ttfk
�r�YnDtk
�rJ}z$|j�r.|�|�n|�|d�W5d}~XYnXdS)NrrzFatal error on SSL transport)rlr��ranger.r�rNr4r�r6�	_finalizer:r%r/�_pausedrpr�r�r�r�r�r�)r �irFrLr2rGrHrrrr��s<�
z"SSLProtocol._process_write_backlog�Fatal error on transportcCsVt|t�r(|j��r@tjd||dd�n|j�|||j|d��|jrR|j�|�dS)Nz%r: %sT)�exc_info)�message�	exceptionr�ra)	rv�OSErrorrUr�rr��call_exception_handlerrl�_force_close)r rHr�rrrr��s

�zSSLProtocol._fatal_errorcCsd|_|jdk	r|j��dSr_)r�rlrgr#rrrr��s
zSSLProtocol._finalizecCs(z|jdk	r|j��W5|��XdSr_)r�rlrr#rrrr~�s
zSSLProtocol._abort)FNTN)N)N)r�)rOrPrQrRr"r`r�r�r�r�r�r�r�rZrfr{r�r�r�r�r�r�r~rrrrr��s0�
.

&
		)+
r�)r�r�r	�ImportError�rrrr�logrrrr,r&r5�objectr�_FlowControlMixin�	TransportrT�Protocolr�rrrr�<module>s*
y�x�h�%bytecode of module 'asyncio.sslproto'�u��b.��Gh)��N}�(hB�
@s�dZdZddlZddlZddlmZddlmZddlmZddlm	Z	dd	�ej
ejgejfej
eejejejej
eejej
efd
�dd�ZdS)
zFSupport for running coroutines in parallel with staggered start times.)�staggered_race�N�)�events)�
exceptions)�locks)�tasks)�loop)�coro_fns�delayr�returnc		�s��p
t���t|��d�d�g�g�tjtjdd���������fdd�����d��}��|�zfd}|t
��kr�t���IdH\}}t
|�}|D]$}|�
�r�|��s�|��r�|���q�ql���fW�S�D]}|�	�q�XdS)a�Run coroutines with staggered start times and take the first to finish.

    This method takes an iterable of coroutine functions. The first one is
    started immediately. From then on, whenever the immediately preceding one
    fails (raises an exception), or when *delay* seconds has passed, the next
    coroutine is started. This continues until one of the coroutines complete
    successfully, in which case all others are cancelled, or until all
    coroutines fail.

    The coroutines provided should be well-behaved in the following way:

    * They should only ``return`` if completed successfully.

    * They should always raise an exception if they did not complete
      successfully. In particular, if they handle cancellation, they should
      probably reraise, like this::

        try:
            # do work
        except asyncio.CancelledError:
            # undo partially completed work
            raise

    Args:
        coro_fns: an iterable of coroutine functions, i.e. callables that
            return a coroutine object when called. Use ``functools.partial`` or
            lambdas to pass arguments.

        delay: amount of time, in seconds, between starting coroutines. If
            ``None``, the coroutines will run sequentially.

        loop: the event loop to use.

    Returns:
        tuple *(winner_result, winner_index, exceptions)* where

        - *winner_result*: the result of the winning coroutine, or ``None``
          if no coroutines won.

        - *winner_index*: the index of the winning coroutine in
          ``coro_fns``, or ``None`` if no coroutines won. If the winning
          coroutine may return None on success, *winner_index* can be used
          to definitively determine whether any coroutine won.

        - *exceptions*: list of exceptions returned by the coroutines.
          ``len(exceptions)`` is equal to the number of coroutines actually
          started, and the order is the same as in ``coro_fns``. The winning
          coroutine's entry is ``None``.

    N)�previous_failedrc	
�sN|dk	r6t�tj��t�|����IdHW5QRXzt��\}}Wntk
r\YdSXt	�
�}���|��}��|�t
��|dks�t���d�t
��|dks�t�z|�IdH}WnLttfk
r��Ynptk
�r}z|�|<|��W5d}~XYn>X�dk�st�|�|�t��D]\}}||k�r,|���q,dS)N�r)�
contextlib�suppress�exceptions_mod�TimeoutErrorr�wait_for�wait�next�
StopIterationr�Event�create_task�append�len�AssertionError�
SystemExit�KeyboardInterrupt�
BaseException�set�	enumerate�cancel)	r�
this_index�coro_fn�this_failed�	next_task�result�e�i�t�r
�
enum_coro_fnsrr�run_one_coro�
running_tasks�winner_index�
winner_result��'/usr/lib/python3.8/asyncio/staggered.pyr+Rs4 


z$staggered_race.<locals>.run_one_coror)r�get_running_loopr�typing�Optionalrrrrr rrr�done�	cancelled�	exception)	r	r
r�
first_taskr(�
done_countr4�_�dr/r)r0rs,=
�0
r)�__doc__�__all__rr2�rrrrr�Iterable�Callable�	Awaitabler3�float�AbstractEventLoop�Tuple�Any�int�List�	Exceptionrr/r/r/r0�<module>s&�����h�&bytecode of module 'asyncio.staggered'�u��b.���Ph)��N}�(hB�P�@s&dZddlZddlZddlZddlZeed�r6ed7ZddlmZddlmZddlm	Z	dd	lm
Z
dd
lmZddlm
Z
ddlmZd
Zdded�dd�Zd ded�dd�Zeed�r�d!ded�dd�Zd"ded�dd�ZGdd�dej�ZGdd�deej�ZGdd�d�ZGdd�d�ZdS)#)�StreamReader�StreamWriter�StreamReaderProtocol�open_connection�start_server�N�AF_UNIX)�open_unix_connection�start_unix_server�)�
coroutines)�events)�
exceptions)�format_helpers)�	protocols)�logger)�sleepi)�loop�limitc	�st|dkrt��}ntjdtdd�t||d�}t||d��|j�fdd�||f|�IdH\}}t|�||�}||fS)	a�A wrapper for create_connection() returning a (reader, writer) pair.

    The reader returned is a StreamReader instance; the writer is a
    StreamWriter instance.

    The arguments are all the usual arguments to create_connection()
    except protocol_factory; most common are positional host and port,
    with various optional keyword arguments following.

    Additional optional keyword arguments are loop (to set the event loop
    instance to use) and limit (to set the buffer limit passed to the
    StreamReader).

    (If you want to customize the StreamReader and/or
    StreamReaderProtocol classes, just copy the code -- there's
    really nothing special here except some convenience.)
    N�[The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.���
stacklevel�rr�rcs�S�N�r��protocolr�%/usr/lib/python3.8/asyncio/streams.py�<lambda>5�z!open_connection.<locals>.<lambda>)	r�get_event_loop�warnings�warn�DeprecationWarningrr�create_connectionr)	�host�portrr�kwds�reader�	transport�_�writerrrrrs"
�
��rc�sJ�dkrt���ntjdtdd����fdd�}�j|||f|�IdHS)a�Start a socket server, call back for each client connected.

    The first parameter, `client_connected_cb`, takes two parameters:
    client_reader, client_writer.  client_reader is a StreamReader
    object, while client_writer is a StreamWriter object.  This
    parameter can either be a plain callback function or a coroutine;
    if it is a coroutine, it will be automatically converted into a
    Task.

    The rest of the arguments are all the usual arguments to
    loop.create_server() except protocol_factory; most common are
    positional host and port, with various optional keyword arguments
    following.  The return value is the same as loop.create_server().

    Additional optional keyword arguments are loop (to set the event loop
    instance to use) and limit (to set the buffer limit passed to the
    StreamReader).

    The return value is the same as loop.create_server(), i.e. a
    Server object which can be used to stop the service.
    Nrrrcst��d�}t|��d�}|S�Nrr�rr�r)r��client_connected_cbrrrr�factoryXs
�zstart_server.<locals>.factory)rr!r"r#r$�
create_server)r1r&r'rrr(r2rr0rr:s
�rc�sr|dkrt��}ntjdtdd�t||d�}t||d��|j�fdd�|f|�IdH\}}t|�||�}||fS)	z@Similar to `open_connection` but works with UNIX Domain Sockets.Nrrrrrcs�Srrrrrrrpr z&open_unix_connection.<locals>.<lambda>)	rr!r"r#r$rr�create_unix_connectionr)�pathrrr(r)r*r+r,rrrrds 
�
��rc�sH�dkrt���ntjdtdd����fdd�}�j||f|�IdHS)z=Similar to `start_server` but works with UNIX Domain Sockets.Nrrrcst��d�}t|��d�}|Sr-r.r/r0rrr2~s
�z"start_unix_server.<locals>.factory)rr!r"r#r$�create_unix_server)r1r5rrr(r2rr0rr	ts
�r	c@sBeZdZdZddd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)�FlowControlMixina)Reusable flow control logic for StreamWriter.drain().

    This implements the protocol methods pause_writing(),
    resume_writing() and connection_lost().  If the subclass overrides
    these it must call the super methods.

    StreamWriter.drain() must wait for _drain_helper() coroutine.
    NcCs0|dkrt��|_n||_d|_d|_d|_dS�NF)rr!�_loop�_paused�
_drain_waiter�_connection_lost)�selfrrrr�__init__�szFlowControlMixin.__init__cCs*|jr
t�d|_|j��r&t�d|�dS)NTz%r pauses writing)r:�AssertionErrorr9�	get_debugr�debug�r=rrr�
pause_writing�s

zFlowControlMixin.pause_writingcCsP|js
t�d|_|j��r&t�d|�|j}|dk	rLd|_|��sL|�d�dS)NFz%r resumes writing)	r:r?r9r@rrAr;�done�
set_result�r=�waiterrrr�resume_writing�s

zFlowControlMixin.resume_writingcCsVd|_|jsdS|j}|dkr"dSd|_|��r4dS|dkrH|�d�n
|�|�dS�NT)r<r:r;rDrE�
set_exception�r=�excrGrrr�connection_lost�sz FlowControlMixin.connection_lostc�sP|jrtd��|jsdS|j}|dks2|��s2t�|j��}||_|IdHdS)NzConnection lost)r<�ConnectionResetErrorr:r;�	cancelledr?r9�
create_futurerFrrr�
_drain_helper�s
zFlowControlMixin._drain_helpercCst�dSr)�NotImplementedError�r=�streamrrr�_get_close_waiter�sz"FlowControlMixin._get_close_waiter)N)
�__name__�
__module__�__qualname__�__doc__r>rCrHrMrQrUrrrrr7�s	
	r7csfeZdZdZdZd�fdd�	Zedd��Zdd�Z�fd	d
�Z	dd�Z
d
d�Zdd�Zdd�Z
�ZS)ra=Helper class to adapt between Protocol and StreamReader.

    (This is a helper class instead of making StreamReader itself a
    Protocol subclass, because the StreamReader has other potential
    uses, and to prevent the user of the StreamReader to accidentally
    call inappropriate methods of the protocol.)
    Ncsnt�j|d�|dk	r,t�|�|_|j|_nd|_|dk	r@||_d|_d|_d|_	||_
d|_|j�
�|_dS)NrF)�superr>�weakref�ref�_stream_reader_wr�_source_traceback�_strong_reader�_reject_connection�_stream_writer�
_transport�_client_connected_cb�	_over_sslr9rP�_closed)r=�
stream_readerr1r��	__class__rrr>�s
zStreamReaderProtocol.__init__cCs|jdkrdS|��Sr)r]rBrrr�_stream_reader�s
z#StreamReaderProtocol._stream_readercCs�|jr6ddi}|jr|j|d<|j�|�|��dS||_|j}|dk	rT|�|�|�d�dk	|_	|j
dk	r�t||||j�|_|�
||j�}t
�|�r�|j�|�d|_dS)N�messagezpAn open stream was garbage collected prior to establishing network connection; call "stream.close()" explicitly.�source_traceback�
sslcontext)r`r^r9�call_exception_handler�abortrbri�
set_transport�get_extra_infordrcrrar�iscoroutine�create_taskr_)r=r*�contextr)�resrrr�connection_made�s2�


��
z$StreamReaderProtocol.connection_madecsx|j}|dk	r*|dkr |��n
|�|�|j��sV|dkrJ|j�d�n|j�|�t��|�d|_d|_	d|_
dSr)ri�feed_eofrJrerDrErZrMr]rarb)r=rLr)rgrrrM
s


z$StreamReaderProtocol.connection_lostcCs|j}|dk	r|�|�dSr)ri�	feed_data)r=�datar)rrr�
data_receivedsz"StreamReaderProtocol.data_receivedcCs$|j}|dk	r|��|jr dSdS)NFT)rirvrd)r=r)rrr�eof_received sz!StreamReaderProtocol.eof_receivedcCs|jSr)rerSrrrrU+sz&StreamReaderProtocol._get_close_waitercCs"|j}|��r|��s|��dSr)rerDrO�	exception)r=�closedrrr�__del__.szStreamReaderProtocol.__del__)NN)rVrWrXrYr^r>�propertyrirurMryrzrUr}�
__classcell__rrrgrr�s
rc@sveZdZdZdd�Zdd�Zedd��Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dd�Zddd�Zdd�ZdS)ra'Wraps a Transport.

    This exposes write(), writelines(), [can_]write_eof(),
    get_extra_info() and close().  It adds drain() which returns an
    optional Future on which you can wait for flow control.  It also
    adds a transport property which references the Transport
    directly.
    cCsJ||_||_|dks"t|t�s"t�||_||_|j��|_|j�	d�dSr)
rb�	_protocol�
isinstancerr?�_readerr9rP�
_complete_futrE)r=r*rr)rrrrr>@szStreamWriter.__init__cCs@|jjd|j��g}|jdk	r0|�d|j���d�d�|��S)N�
transport=zreader=�<{}>� )rhrVrbr��append�format�join�r=�inforrr�__repr__Js
zStreamWriter.__repr__cCs|jSr)rbrBrrrr*PszStreamWriter.transportcCs|j�|�dSr)rb�write�r=rxrrrr�TszStreamWriter.writecCs|j�|�dSr)rb�
writelinesr�rrrr�WszStreamWriter.writelinescCs
|j��Sr)rb�	write_eofrBrrrr�ZszStreamWriter.write_eofcCs
|j��Sr)rb�
can_write_eofrBrrrr�]szStreamWriter.can_write_eofcCs
|j��Sr)rb�closerBrrrr�`szStreamWriter.closecCs
|j��Sr)rb�
is_closingrBrrrr�cszStreamWriter.is_closingc�s|j�|�IdHdSr)r�rUrBrrr�wait_closedfszStreamWriter.wait_closedNcCs|j�||�Sr)rbrp)r=�name�defaultrrrrpiszStreamWriter.get_extra_infoc�sL|jdk	r |j��}|dk	r |�|j��r8td�IdH|j��IdHdS)zyFlush the write buffer.

        The intended use is to write

          w.write(data)
          await w.drain()
        Nr)r�r{rbr�rr�rQ)r=rLrrr�drainls



zStreamWriter.drain)N)rVrWrXrYr>r�r~r*r�r�r�r�r�r�r�rpr�rrrrr6s	


rc@s�eZdZdZedfdd�Zdd�Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zd&dd�Zd'dd�Zd d!�Zd"d#�Zd$d%�ZdS)(rNcCsv|dkrtd��||_|dkr*t��|_n||_t�|_d|_d|_d|_	d|_
d|_|j��rrt
�t�d��|_dS)NrzLimit cannot be <= 0Fr
)�
ValueError�_limitrr!r9�	bytearray�_buffer�_eof�_waiter�
_exceptionrbr:r@r�
extract_stack�sys�	_getframer^)r=rrrrrr>�s 
�zStreamReader.__init__cCs�dg}|jr"|�t|j��d��|jr2|�d�|jtkrN|�d|j���|jrf|�d|j���|jr~|�d|j���|jr�|�d|j���|j	r�|�d�d	�
d
�|��S)Nrz bytes�eofzlimit=zwaiter=z
exception=r�Zpausedr�r�)r�r��lenr�r��_DEFAULT_LIMITr�r�rbr:r�r�r�rrrr��s 


zStreamReader.__repr__cCs|jSr)r�rBrrrr{�szStreamReader.exceptioncCs0||_|j}|dk	r,d|_|��s,|�|�dSr)r�r�rOrJrKrrrrJ�szStreamReader.set_exceptioncCs*|j}|dk	r&d|_|��s&|�d�dS)z1Wakeup read*() functions waiting for data or EOF.N)r�rOrErFrrr�_wakeup_waiter�s
zStreamReader._wakeup_waitercCs|jdkstd��||_dS)NzTransport already set)rbr?)r=r*rrrro�szStreamReader.set_transportcCs*|jr&t|j�|jkr&d|_|j��dSr8)r:r�r�r�rb�resume_readingrBrrr�_maybe_resume_transport�sz$StreamReader._maybe_resume_transportcCsd|_|��dSrI)r�r�rBrrrrv�szStreamReader.feed_eofcCs|jo|jS)z=Return True if the buffer is empty and 'feed_eof' was called.)r�r�rBrrr�at_eof�szStreamReader.at_eofcCs�|jrtd��|sdS|j�|�|��|jdk	r~|js~t|j�d|jkr~z|j�	�Wnt
k
rvd|_YnXd|_dS)Nzfeed_data after feed_eofrT)r�r?r��extendr�rbr:r�r��
pause_readingrRr�rrrrw�s
��zStreamReader.feed_datac�sf|jdk	rt|�d���|jr&td��|jr<d|_|j��|j��|_z|jIdHW5d|_XdS)zpWait until feed_data() or feed_eof() is called.

        If stream was paused, automatically resume it.
        NzF() called while another coroutine is already waiting for incoming dataz_wait_for_data after EOFF)	r��RuntimeErrorr�r?r:rbr�r9rP)r=�	func_namerrr�_wait_for_data�s	
�
zStreamReader._wait_for_datac
�s�d}t|�}z|�|�IdH}Wn�tjk
rN}z|jWY�Sd}~XYnhtjk
r�}zH|j�||j�r�|jd|j|�=n
|j�	�|�
�t|jd��W5d}~XYnX|S)a�Read chunk of data from the stream until newline (b'
') is found.

        On success, return chunk that ends with newline. If only partial
        line can be read due to EOF, return incomplete line without
        terminating newline. When EOF was reached while no bytes read, empty
        bytes object is returned.

        If limit is reached, ValueError will be raised. In that case, if
        newline was found, complete line including newline will be removed
        from internal buffer. Else, internal buffer will be cleared. Limit is
        compared against part of the line without newline.

        If stream was paused, this function will automatically resume it if
        needed.
        �
Nr)
r��	readuntilr
�IncompleteReadError�partial�LimitOverrunErrorr��
startswith�consumed�clearr�r��args)r=�sep�seplen�line�errr�readline	s
 zStreamReader.readliner�c�s�t|�}|dkrtd��|jdk	r(|j�d}t|j�}|||kr||j�||�}|dkrZq�|d|}||jkr|t�d|��|jr�t	|j�}|j�
�t�|d��|�d�IdHq,||jkr�t�d|��|jd||�}|jd||�=|�
�t	|�S)	aVRead data from the stream until ``separator`` is found.

        On success, the data and separator will be removed from the
        internal buffer (consumed). Returned data will include the
        separator at the end.

        Configured stream limit is used to check result. Limit sets the
        maximal length of data that can be returned, not counting the
        separator.

        If an EOF occurs and the complete separator is still not found,
        an IncompleteReadError exception will be raised, and the internal
        buffer will be reset.  The IncompleteReadError.partial attribute
        may contain the separator partially.

        If the data cannot be read because of over limit, a
        LimitOverrunError exception  will be raised, and the data
        will be left in the internal buffer, so it can be read again.
        rz,Separator should be at least one-byte stringN���r
z2Separator is not found, and chunk exceed the limitr�z2Separator is found, but chunk is longer than limit)r�r�r�r��findr�r
r�r��bytesr�r�r�r�)r=�	separatorr��offset�buflen�isep�chunkrrrr�(s>


�


�zStreamReader.readuntilr�c�s�|jdk	r|j�|dkrdS|dkrVg}|�|j�IdH}|s@qL|�|�q(d�|�S|jsr|jsr|�d�IdHt|jd|��}|jd|�=|�	�|S)a�Read up to `n` bytes from the stream.

        If n is not provided, or set to -1, read until EOF and return all read
        bytes. If the EOF was received and the internal buffer is empty, return
        an empty bytes object.

        If n is zero, return empty bytes object immediately.

        If n is positive, this function try to read `n` bytes, and may return
        less or equal bytes than requested, but at least one byte. If EOF was
        received before any byte is read, this function returns empty byte
        object.

        Returned value is not limited with limit, configured at stream
        creation.

        If stream was paused, this function will automatically resume it if
        needed.
        Nrr �read)
r�r�r�r�r�r�r�r�r�r�)r=�n�blocks�blockrxrrrr��s"

zStreamReader.readc�s�|dkrtd��|jdk	r |j�|dkr,dSt|j�|krr|jr`t|j�}|j��t�||��|�	d�IdHq,t|j�|kr�t|j�}|j��nt|jd|��}|jd|�=|�
�|S)a�Read exactly `n` bytes.

        Raise an IncompleteReadError if EOF is reached before `n` bytes can be
        read. The IncompleteReadError.partial attribute of the exception will
        contain the partial read bytes.

        if n is zero, return empty bytes object.

        Returned value is not limited with limit, configured at stream
        creation.

        If stream was paused, this function will automatically resume it if
        needed.
        rz*readexactly size can not be less than zeroNr �readexactly)r�r�r�r�r�r�r�r
r�r�r�)r=r��
incompleterxrrrr��s&



zStreamReader.readexactlycCs|SrrrBrrr�	__aiter__�szStreamReader.__aiter__c�s|��IdH}|dkrt�|S)Nr )r��StopAsyncIteration)r=�valrrr�	__anext__�szStreamReader.__anext__)r�)r�)rVrWrXr^r�r>r�r{rJr�ror�rvr�rwr�r�r�r�r�r�r�rrrrr�s$	
[
2)r)NN)NN)N)N)�__all__�socketr�r"r[�hasattr�rrr
rr�logr�tasksrr�rrrr	�Protocolr7rrrrrrr�<module>sF
�!�'
��DkP�h�$bytecode of module 'asyncio.streams'�u��b.���h)��N}�(hB��@s�dZddlZddlZddlmZddlmZddlmZddlmZddlm	Z	ej
Z
ejZejZGd	d
�d
ej
ej�ZGdd�d�Zddddejfd
d�Zddddejd�dd�ZdS))�create_subprocess_exec�create_subprocess_shell�N�)�events)�	protocols)�streams)�tasks)�loggercsXeZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Z�ZS)�SubprocessStreamProtocolz0Like StreamReaderProtocol, but for a subprocess.csHt�j|d�||_d|_|_|_d|_d|_g|_|j	�
�|_dS)N��loopF)�super�__init__�_limit�stdin�stdout�stderr�
_transport�_process_exited�	_pipe_fds�_loop�
create_future�
_stdin_closed)�self�limitr��	__class__��(/usr/lib/python3.8/asyncio/subprocess.pyrsz!SubprocessStreamProtocol.__init__cCsn|jjg}|jdk	r&|�d|j���|jdk	rB|�d|j���|jdk	r^|�d|j���d�d�|��S)Nzstdin=zstdout=zstderr=z<{}>� )r�__name__r�appendrr�format�join)r�inforrr�__repr__s



z!SubprocessStreamProtocol.__repr__cCs�||_|�d�}|dk	rDtj|j|jd�|_|j�|�|j�	d�|�d�}|dk	r�tj|j|jd�|_
|j
�|�|j�	d�|�d�}|dk	r�tj||d|jd�|_dS)Nr�rr�r)�protocol�readerr)
r�get_pipe_transportr�StreamReaderrrr�
set_transportrr!r�StreamWriterr)r�	transport�stdout_transport�stderr_transport�stdin_transportrrr�connection_made)s,
�
�
�z(SubprocessStreamProtocol.connection_madecCs:|dkr|j}n|dkr |j}nd}|dk	r6|�|�dS)Nrr')rr�	feed_data)r�fd�datar)rrr�pipe_data_receivedAsz+SubprocessStreamProtocol.pipe_data_receivedcCs�|dkrN|j}|dk	r|��|�|�|dkr>|j�d�n|j�|�dS|dkr^|j}n|dkrn|j}nd}|dk	r�|dkr�|��n
|�|�||j	kr�|j	�
|�|��dS)Nrrr')r�close�connection_lostr�
set_result�
set_exceptionrr�feed_eofr�remove�_maybe_close_transport)rr4�exc�piper)rrr�pipe_connection_lostKs*



z-SubprocessStreamProtocol.pipe_connection_lostcCsd|_|��dS)NT)rr=�rrrr�process_exitedfsz'SubprocessStreamProtocol.process_exitedcCs(t|j�dkr$|jr$|j��d|_dS)Nr)�lenrrrr7rArrrr=js
z/SubprocessStreamProtocol._maybe_close_transportcCs||jkr|jSdS�N)rr)r�streamrrr�_get_close_waiteros
z*SubprocessStreamProtocol._get_close_waiter)
r �
__module__�__qualname__�__doc__rr%r2r6r@rBr=rF�
__classcell__rrrrr
s	

r
c@sjeZdZdd�Zdd�Zedd��Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
ddd�ZdS)�ProcesscCs8||_||_||_|j|_|j|_|j|_|��|_dSrD)r�	_protocolrrrr�get_pid�pid)rr.r(rrrrruszProcess.__init__cCsd|jj�d|j�d�S)N�<r�>)rr rNrArrrr%~szProcess.__repr__cCs
|j��SrD)r�get_returncoderArrr�
returncode�szProcess.returncodec�s|j��IdHS)z?Wait until the process exit and return the process return code.N)r�_waitrArrr�wait�szProcess.waitcCs|j�|�dSrD)r�send_signal)r�signalrrrrU�szProcess.send_signalcCs|j��dSrD)r�	terminaterArrrrW�szProcess.terminatecCs|j��dSrD)r�killrArrrrX�szProcess.killc
�s�|j��}|j�|�|r,t�d|t|��z|j��IdHWn8tt	fk
rx}z|rht�d||�W5d}~XYnX|r�t�d|�|j�
�dS)Nz%%r communicate: feed stdin (%s bytes)z%r communicate: stdin got %rz%r communicate: close stdin)r�	get_debugr�writer	�debugrC�drain�BrokenPipeError�ConnectionResetErrorr7)r�inputr[r>rrr�_feed_stdin�s 
� zProcess._feed_stdinc�sdSrDrrArrr�_noop�sz
Process._noopc�s�|j�|�}|dkr|j}n|dks(t�|j}|j��rV|dkrDdnd}t�d||�|�	�IdH}|j��r�|dkrzdnd}t�d||�|�
�|S)Nr'rrrz%r communicate: read %sz%r communicate: close %s)rr*r�AssertionErrorrrrYr	r[�readr7)rr4r.rE�name�outputrrr�_read_stream�s

zProcess._read_streamNc�s�|dk	r|�|�}n|��}|jdk	r2|�d�}n|��}|jdk	rP|�d�}n|��}tj||||jd�IdH\}}}|��IdH||fS)Nrr'r)	r`rarrfrr�gatherrrT)rr_rrrrrr�communicate�s


�zProcess.communicate)N)r rGrHrr%�propertyrRrTrUrWrXr`rarfrhrrrrrKts	
rKc
�sb�dkrt���ntjdtdd���fdd�}�j||f|||d�|��IdH\}}	t||	��S)N�ZThe loop argument is deprecated since Python 3.8 and scheduled for removal in Python 3.10.r'��
stacklevelcst��d�S�Nr&�r
rr&rr�<lambda>�s�z)create_subprocess_shell.<locals>.<lambda>�rrr)r�get_event_loop�warnings�warn�DeprecationWarning�subprocess_shellrK)
�cmdrrrrr�kwds�protocol_factoryr.r(rr&rr�s$
����r)rrrrrc�sf�dkrt���ntjdtdd���fdd�}�j||f|�|||d�|��IdH\}	}
t|	|
��S)Nrjr'rkcst��d�Srmrnrr&rrro�s�z(create_subprocess_exec.<locals>.<lambda>rp)rrqrrrsrt�subprocess_execrK)�programrrrrr�argsrwrxr.r(rr&rr�s(
�����r)�__all__�
subprocessrr�rrrr�logr	�PIPE�STDOUT�DEVNULL�FlowControlMixin�SubprocessProtocolr
rK�_DEFAULT_LIMITrrrrrr�<module>s.�bV�
��h�'bytecode of module 'asyncio.subprocess'�u��b.��_h)��N}�(hB�^�@svdZdZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZddlm
Z
ddlmZddlmZdd	lmZdd
l
mZe�d�jZdBdd�ZdCd
d�ZdDdd�Zdd�ZGdd�dej�ZeZzddlZWnek
r�YnXejZZdd�dd�Zejj Z ejj!Z!ejj"Z"dde"d�dd�Z#dd�Z$dd�dd�Z%d d!�Z&d"d#�Z'ddd$�d%d&�Z(ej)d'd(��Z*dEdd�d)d*�Z+dd�d+d,�Z,ej)d-d.��Z-ee-_Gd/d0�d0ej.�Z/dd1d2�d3d4�Z0dd�d5d6�Z1d7d8�Z2e
�3�Z4iZ5d9d:�Z6d;d<�Z7d=d>�Z8d?d@�Z9e6Z:e9Z;e7Z<e8Z=z$ddAlm6Z6m9Z9m7Z7m8Z8m4Z4m5Z5Wnek
�r`YnXe6Z>e9Z?e7Z@e8ZAdS)Fz0Support for tasks, coroutines and the scheduler.)�Task�create_task�FIRST_COMPLETED�FIRST_EXCEPTION�
ALL_COMPLETED�wait�wait_for�as_completed�sleep�gather�shield�
ensure_future�run_coroutine_threadsafe�current_task�	all_tasks�_register_task�_unregister_task�_enter_task�_leave_task�N�)�
base_tasks)�
coroutines)�events)�
exceptions)�futures)�
_is_coroutinecCs|dkrt��}t�|�S)z!Return a currently executed task.N)r�get_running_loop�_current_tasks�get��loop�r!�#/usr/lib/python3.8/asyncio/tasks.pyr"srcs^�dkrt���d}ztt�}WqLtk
rF|d7}|dkrB�YqXqLq�fdd�|D�S)z'Return a set of all tasks for the loop.Nrr��cs&h|]}t�|��kr|��s|�qSr!)r�	_get_loop�done��.0�trr!r"�	<setcomp><s�zall_tasks.<locals>.<setcomp>)rr�list�
_all_tasks�RuntimeError�r �i�tasksr!rr"r)srcs^�dkrt���d}ztt�}WqLtk
rF|d7}|dkrB�YqXqLq�fdd�|D�S)Nrrr#csh|]}t�|��kr|�qSr!)rr$r&rr!r"r)Usz$_all_tasks_compat.<locals>.<setcomp>)r�get_event_loopr*r+r,r-r!rr"�_all_tasks_compat@sr1cCs4|dk	r0z
|j}Wntk
r&Yn
X||�dS�N)�set_name�AttributeError)�task�namer3r!r!r"�_set_task_nameXs
r7cs�eZdZdZdZed%dd��Zed&dd��Zddd��fd	d
�
Z�fdd�Z	d
d�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�dd�Zddd�dd�Zdd �Zd'�fd!d"�	Zd#d$�Z�ZS)(rz A coroutine wrapped in a Future.TNcCs(tjdtdd�|dkr t��}t|�S)z�Return the currently running task in an event loop or None.

        By default the current task for the current event loop is returned.

        None is returned when called not in the context of a Task.
        zVTask.current_task() is deprecated since Python 3.7, use asyncio.current_task() instead���
stacklevelN)�warnings�warn�DeprecationWarningrr0r��clsr r!r!r"rts�zTask.current_taskcCstjdtdd�t|�S)z|Return a set of all tasks for an event loop.

        By default all tasks for the current event loop are returned.
        zPTask.all_tasks() is deprecated since Python 3.7, use asyncio.all_tasks() insteadr8r9)r;r<r=r1r>r!r!r"r�s
�zTask.all_tasks)r r6cs�t�j|d�|jr|jd=t�|�s:d|_td|����|dkrRdt���|_n
t	|�|_d|_
d|_||_t
��|_|jj|j|jd�t|�dS)Nr���Fza coroutine was expected, got zTask-��context)�super�__init__�_source_tracebackr�iscoroutine�_log_destroy_pending�	TypeError�_task_name_counter�_name�str�_must_cancel�_fut_waiter�_coro�contextvars�copy_context�_context�_loop�	call_soon�_Task__stepr)�self�coror r6��	__class__r!r"rD�s


z
Task.__init__csF|jtjkr8|jr8|dd�}|jr,|j|d<|j�|�t���dS)Nz%Task was destroyed but it is pending!)r5�message�source_traceback)	�_stater�_PENDINGrGrErR�call_exception_handlerrC�__del__)rUrBrWr!r"r^�s�
zTask.__del__cCs
t�|�Sr2)r�_task_repr_info�rUr!r!r"�
_repr_info�szTask._repr_infocCs|jSr2)rNr`r!r!r"�get_coro�sz
Task.get_corocCs|jSr2)rJr`r!r!r"�get_name�sz
Task.get_namecCst|�|_dSr2)rKrJ)rU�valuer!r!r"r3�sz
Task.set_namecCstd��dS)Nz*Task does not support set_result operation�r,)rU�resultr!r!r"�
set_result�szTask.set_resultcCstd��dS)Nz-Task does not support set_exception operationre)rU�	exceptionr!r!r"�
set_exception�szTask.set_exception)�limitcCst�||�S)a�Return the list of stack frames for this task's coroutine.

        If the coroutine is not done, this returns the stack where it is
        suspended.  If the coroutine has completed successfully or was
        cancelled, this returns an empty list.  If the coroutine was
        terminated by an exception, this returns the list of traceback
        frames.

        The frames are always ordered from oldest to newest.

        The optional limit gives the maximum number of frames to
        return; by default all available frames are returned.  Its
        meaning differs depending on whether a stack or a traceback is
        returned: the newest frames of a stack are returned, but the
        oldest frames of a traceback are returned.  (This matches the
        behavior of the traceback module.)

        For reasons beyond our control, only one stack frame is
        returned for a suspended coroutine.
        )r�_task_get_stack)rUrjr!r!r"�	get_stack�szTask.get_stack)rj�filecCst�|||�S)anPrint the stack or traceback for this task's coroutine.

        This produces output similar to that of the traceback module,
        for the frames retrieved by get_stack().  The limit argument
        is passed to get_stack().  The file argument is an I/O stream
        to which the output is written; by default output is written
        to sys.stderr.
        )r�_task_print_stack)rUrjrmr!r!r"�print_stack�s	zTask.print_stackcCs4d|_|��rdS|jdk	r*|j��r*dSd|_dS)a�Request that this task cancel itself.

        This arranges for a CancelledError to be thrown into the
        wrapped coroutine on the next cycle through the event loop.
        The coroutine then has a chance to clean up or even deny
        the request using try/except/finally.

        Unlike Future.cancel, this does not guarantee that the
        task will be cancelled: the exception might be caught and
        acted upon, delaying cancellation of the task or preventing
        cancellation completely.  The task may also return a value or
        raise a different exception.

        Immediately after this method is called, Task.cancelled() will
        not return True (unless the task was already cancelled).  A
        task will be marked as cancelled when the wrapped coroutine
        terminates with a CancelledError exception (even if cancel()
        was not called).
        FNT)�_log_tracebackr%rM�cancelrLr`r!r!r"rq�s

zTask.cancelc
s�|��rt�d|�d|����|jr>t|tj�s8t��}d|_|j}d|_t|j	|��zfz"|dkrp|�d�}n
|�|�}Wn�t
k
r�}z*|jr�d|_t���nt��|j�W5d}~XY�n�tjk
r�t���Y�n�ttfk
�r}zt��|��W5d}~XY�n�tk
�rL}zt��|�W5d}~XY�npXt|dd�}|dk	�r@t�|�|j	k	�r�td|�d|�d��}|j	j|j||jd�n�|�r||k�r�td	|���}|j	j|j||jd�n8d|_|j|j|jd�||_|j�r>|j���r>d|_n*td
|�d|���}|j	j|j||jd�n||dk�r`|j	j|j|jd�n\t �!|��r�td|�d|���}|j	j|j||jd�n$td
|���}|j	j|j||jd�W5t
|j	|�d}XdS)Nz_step(): already done: z, F�_asyncio_future_blockingzTask z got Future z attached to a different looprAzTask cannot await on itself: z-yield was used instead of yield from in task z with z;yield was used instead of yield from for generator in task zTask got bad yield: )"r%r�InvalidStateErrorrL�
isinstance�CancelledErrorrNrMrrRr�send�throw�
StopIterationrCrqrgrd�KeyboardInterrupt�
SystemExitri�
BaseException�getattrrr$r,rSrTrQrr�add_done_callback�
_Task__wakeup�inspect�isgenerator)rU�excrVrf�blocking�new_excrWr!r"�__steps��  
��
�����
���
zTask.__stepc
CsJz|��Wn,tk
r8}z|�|�W5d}~XYn
X|��d}dSr2)rfr{rT)rU�futurer�r!r!r"�__wakeup[sz
Task.__wakeup)N)N)N)�__name__�
__module__�__qualname__�__doc__rG�classmethodrrrDr^rarbrcr3rgrirlrorqrTr~�
__classcell__r!r!rWr"rbs&
!Tr)r6cCs t��}|�|�}t||�|S)z]Schedule the execution of a coroutine object in a spawn task.

    Return a Task object.
    )rrrr7)rVr6r r5r!r!r"rxs

r)r �timeout�return_whenc�s�t�|�st�|�r(tdt|�j����|s4td��|tt	t
fkrPtd|�����dkrbt���nt
jdtdd��fdd	�t|�D�}t|||��IdHS)
a�Wait for the Futures and coroutines given by fs to complete.

    The fs iterable must not be empty.

    Coroutines will be wrapped in Tasks.

    Returns two sets of Future: (done, pending).

    Usage:

        done, pending = await asyncio.wait(fs)

    Note: This does not raise TimeoutError! Futures that aren't done
    when the timeout occurs are returned in the second set.
    zexpect a list of futures, not z#Set of coroutines/Futures is empty.zInvalid return_when value: N�[The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.r8r9csh|]}t|�d��qS�r�r�r'�frr!r"r)�szwait.<locals>.<setcomp>)r�isfuturerrFrH�typer��
ValueErrorrrrrrr;r<r=�set�_wait)�fsr r�r�r!rr"r�s
�rcGs|��s|�d�dSr2)r%rg)�waiter�argsr!r!r"�_release_waiter�sr�rc
�s�|dkrt��}ntjdtdd�|dkr4|IdHS|dkr�t||d�}|��rX|��St||d�IdHz|��Wn.t	j
k
r�}zt	��|�W5d}~XYn
Xt	���|��}|�
|t|�}t�t|�}t||d�}|�|�z�z|IdHWnPt	j
k
�rF|���r$|��YW�dS|�|�t||d�IdH�YnX|���r^|��W�*S|�|�t||d�IdHt	���W5|��XdS)a�Wait for the single Future or coroutine to complete, with timeout.

    Coroutine will be wrapped in Task.

    Returns result of the Future or coroutine.  When a timeout occurs,
    it cancels the task and raises TimeoutError.  To avoid the task
    cancellation, wrap it in shield().

    If the wait is cancelled, the task is also cancelled.

    This function is a coroutine.
    Nr�r8r9rr)rrr;r<r=rr%rf�_cancel_and_waitrru�TimeoutError�
create_future�
call_laterr��	functools�partialr}rq�remove_done_callback)�futr�r r�r��timeout_handle�cbr!r!r"r�sL

�





rc
�s�|std��|���d�|dk	r.|�|t���t|������fdd�}|D]}|�|�qLz�IdHW5�dk	r|���|D]}|�|�q�Xt�t�}}|D]"}|�	�r�|�
|�q�|�
|�q�||fS)zVInternal helper for wait().

    The fs argument must be a collection of Futures.
    zSet of Futures is empty.NcsZ�d8��dks4�tks4�tkrV|��sV|��dk	rV�dk	rD������sV��d�dS)Nrr)rr�	cancelledrhrqr%rg�r���counterr�r�r�r!r"�_on_completions���
�z_wait.<locals>._on_completion)�AssertionErrorr�r�r��lenr}rqr�r�r%�add)r�r�r�r r�r�r%�pendingr!r�r"r��s*r�c	�sF|��}t�t|�}|�|�z|��|IdHW5|�|�XdS)z<Cancel the *fut* future or task and wait until it completes.N)r�r�r�r�r}r�rq)r�r r�r�r!r!r"r�&s
r�)r r�c#s�t�|�st�|�r(tdt|�j����ddlm}|�d���dkrPt	�
��ntjdt
dd��fd	d
�t|�D��d����fdd�}���fd
d���fdd�}�D]}|���q��r�|dk	r҈�||��tt���D]}|�Vq�dS)a^Return an iterator whose values are coroutines.

    When waiting for the yielded coroutines you'll get the results (or
    exceptions!) of the original Futures (or coroutines), in the order
    in which and as soon as they complete.

    This differs from PEP 3148; the proper way to use this is:

        for f in as_completed(fs):
            result = await f  # The 'await' may raise.
            # Use result.

    If a timeout is specified, the 'await' will raise
    TimeoutError when the timeout occurs before all Futures are done.

    Note: The futures 'f' are not necessarily members of fs.
    z#expect an iterable of futures, not r)�QueuerNr�r8r9csh|]}t|�d��qSr�r�r�rr!r"r)Uszas_completed.<locals>.<setcomp>cs*�D]}|�����d�q���dSr2)r��
put_nowait�clearr�)r�r%�todor!r"�_on_timeoutXs
z!as_completed.<locals>._on_timeoutcs4�sdS��|���|��s0�dk	r0���dSr2)�remover�rqr�)r%r�r�r!r"r�^s

z$as_completed.<locals>._on_completionc�s$���IdH}|dkrtj�|��Sr2)rrr�rfr�)r%r!r"�
_wait_for_onefsz#as_completed.<locals>._wait_for_one)rr�rrFrHr�r��queuesr�rr0r;r<r=r�r}r��ranger�)r�r r�r�r�r�r��_r!)r�r%r r�r�r"r7s*

�rccs
dVdS)z�Skip one event loop run cycle.

    This is a private helper for 'asyncio.sleep()', used
    when the 'delay' is set to 0.  It uses a bare 'yield'
    expression (which Task.__step knows how to handle)
    instead of creating a Future object.
    Nr!r!r!r!r"�__sleep0us	r�c�sr|dkrt�IdH|S|dkr*t��}ntjdtdd�|��}|�|tj	||�}z|IdHW�S|�
�XdS)z9Coroutine that completes after a given time (in seconds).rNr�r8r9)r�rrr;r<r=r�r�r�_set_result_unless_cancelledrq)�delayrfr r��hr!r!r"r	�s$
��r	cCs�t�|�r6|dkrt��}|�|�}|jr2|jd=|St�|�rb|dk	r^|t�|�k	r^t	d��|St
�|�r|tt
|�|d�Std��dS)zmWrap a coroutine or an awaitable in a future.

    If the argument is a Future, it is returned directly.
    Nr@zRThe future belongs to a different loop than the one specified as the loop argumentrz:An asyncio.Future, a coroutine or an awaitable is required)rrFrr0rrErr�r$r�r�isawaitabler�_wrap_awaitablerH)�coro_or_futurer r5r!r!r"r�s



rccs|��EdHS)z�Helper for asyncio.ensure_future().

    Wraps awaitable (an object with __await__) into a coroutine
    that will later be wrapped in a Task by ensure_future().
    N)�	__await__)�	awaitabler!r!r"r��sr�cs.eZdZdZdd��fdd�
Zdd�Z�ZS)�_GatheringFuturez�Helper for gather().

    This overrides cancel() to cancel all the children and act more
    like Task.cancel(), which doesn't immediately mark itself as
    cancelled.
    Nrcst�j|d�||_d|_dS)NrF)rCrD�	_children�_cancel_requested)rU�childrenr rWr!r"rD�sz_GatheringFuture.__init__cCs6|��rdSd}|jD]}|��rd}q|r2d|_|S)NFT)r%r�rqr�)rU�ret�childr!r!r"rq�s
z_GatheringFuture.cancel)r�r�r�r�rDrqr�r!r!rWr"r��sr�F)r �return_exceptionscs�|s<|dkrt��}ntjdtdd�|�����g��S�����fdd�}i}g�d�d�|D]f}||kr�t||d�}|dkr�t�	|�}||k	r�d	|_
�d
7�|||<|�|�n||}��|�qdt
�|d���S)a�Return a future aggregating results from the given coroutines/futures.

    Coroutines will be wrapped in a future and scheduled in the event
    loop. They will not necessarily be scheduled in the same order as
    passed in.

    All futures must share the same event loop.  If all the tasks are
    done successfully, the returned future's result is the list of
    results (in the order of the original sequence, not necessarily
    the order of results arrival).  If *return_exceptions* is True,
    exceptions in the tasks are treated the same as successful
    results, and gathered in the result list; otherwise, the first
    raised exception will be immediately propagated to the returned
    future.

    Cancellation: if the outer Future is cancelled, all children (that
    have not completed yet) are also cancelled.  If any child is
    cancelled, this is treated as if it raised CancelledError --
    the outer Future is *not* cancelled in this case.  (This is to
    prevent the cancellation of one child to cause other children to
    be cancelled.)

    If *return_exceptions* is False, cancelling gather() after it
    has been marked done won't cancel any submitted awaitables.
    For instance, gather can be marked done after propagating an
    exception to the caller, therefore, calling ``gather.cancel()``
    after catching an exception (raised by one of the awaitables) from
    gather won't cancel any other awaitables.
    Nr�r8r9cs��d7����r$|��s |��dS�sd|��rFt��}��|�dS|��}|dk	rd��|�dS��kr�g}�D]8}|��r�t��}n|��}|dkr�|��}|�|�qt�jrĈ�t���n
��	|�dS)Nr)
r%r�rhrrurirf�appendr�rg)r�r��results�res�r��	nfinished�nfuts�outerr�r!r"�_done_callbacks4


zgather.<locals>._done_callbackrrFr)rr0r;r<r=r�rgrrr$rGr}r�r�)r r��coros_or_futuresr��
arg_to_fut�argr�r!r�r"r
�s:
�
1
r
cst|dk	rtjdtdd�t||d�����r0�St���}|����fdd����fdd	�}������|��S)
a.Wait for a future, shielding it from cancellation.

    The statement

        res = await shield(something())

    is exactly equivalent to the statement

        res = await something()

    *except* that if the coroutine containing it is cancelled, the
    task running in something() is not cancelled.  From the POV of
    something(), the cancellation did not happen.  But its caller is
    still cancelled, so the yield-from expression still raises
    CancelledError.  Note: If something() is cancelled by other means
    this will still cancel shield().

    If you want to completely ignore cancellation (not recommended)
    you can combine shield() with a try/except clause, as follows:

        try:
            res = await shield(something())
        except CancelledError:
            res = None
    Nr�r8r9rcs\���r|��s|��dS|��r.���n*|��}|dk	rJ��|�n��|���dSr2)r�rhrqrirgrf)�innerr��r�r!r"�_inner_done_callbackus
z$shield.<locals>._inner_done_callbackcs���s����dSr2)r%r�r�)r�r�r!r"�_outer_done_callback�sz$shield.<locals>._outer_done_callback)	r;r<r=rr%rr$r�r})r�r r�r!)r�r�r�r"rPs�


rcs:t���std��tj������fdd�}��|��S)zsSubmit a coroutine object to a given event loop.

    Return a concurrent.futures.Future to access the result.
    zA coroutine object is requiredc
slzt�t��d���WnNttfk
r2�Yn6tk
rf}z���rT��|��W5d}~XYnXdS)Nr)r�
_chain_futurerrzryr{�set_running_or_notify_cancelri)r��rVr�r r!r"�callback�s
z*run_coroutine_threadsafe.<locals>.callback)rrFrH�
concurrentr�Future�call_soon_threadsafe)rVr r�r!r�r"r
�s



r
cCst�|�dS)z3Register a new task in asyncio as executed by loop.N)r+r��r5r!r!r"r�srcCs4t�|�}|dk	r(td|�d|�d���|t|<dS)NzCannot enter into task z while another task z is being executed.�rrr,�r r5rr!r!r"r�s
rcCs2t�|�}||k	r(td|�d|�d���t|=dS)Nz
Leaving task z! does not match the current task �.r�r�r!r!r"r�s
rcCst�|�dS)zUnregister a task.N)r+�discardr�r!r!r"r�sr)rrrrr+r)N)N)N)N)Br��__all__�concurrent.futuresr�rOr�r�	itertools�typesr;�weakref�rrrrrr�count�__next__rIrrr1r7�	_PyFuturer�_PyTask�_asyncio�ImportError�_CTaskrrrrrr�rr�r�r�	coroutiner�r	rr�r�r�r
rr
�WeakSetr+rrrrr�_py_register_task�_py_unregister_task�_py_enter_task�_py_leave_task�_c_register_task�_c_unregister_task�
_c_enter_task�
_c_leave_taskr!r!r!r"�<module>s�	





#H,>

x?$�h�"bytecode of module 'asyncio.tasks'�u��b.��0h)��N}�(hB�/�@s|dZdZGdd�d�ZGdd�de�ZGdd�de�ZGdd	�d	ee�ZGd
d�de�ZGdd
�d
e�ZGdd�de�ZdS)zAbstract Transport class.)�
BaseTransport�
ReadTransport�WriteTransport�	Transport�DatagramTransport�SubprocessTransportc@sHeZdZdZdZddd�Zddd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dS)rzBase class for transports.��_extraNcCs|dkri}||_dS�Nr)�self�extra�r�(/usr/lib/python3.8/asyncio/transports.py�__init__szBaseTransport.__init__cCs|j�||�S)z#Get optional transport information.)r�get)r
�name�defaultrrr
�get_extra_infoszBaseTransport.get_extra_infocCst�dS)z2Return True if the transport is closing or closed.N��NotImplementedError�r
rrr
�
is_closingszBaseTransport.is_closingcCst�dS)aClose the transport.

        Buffered data will be flushed asynchronously.  No more data
        will be received.  After all buffered data is flushed, the
        protocol's connection_lost() method will (eventually) be
        called with None as its argument.
        Nrrrrr
�closeszBaseTransport.closecCst�dS)zSet a new protocol.Nr)r
�protocolrrr
�set_protocol%szBaseTransport.set_protocolcCst�dS)zReturn the current protocol.Nrrrrr
�get_protocol)szBaseTransport.get_protocol)N)N)�__name__�
__module__�__qualname__�__doc__�	__slots__rrrrrrrrrr
r	s


rc@s,eZdZdZdZdd�Zdd�Zdd�Zd	S)
rz#Interface for read-only transports.rcCst�dS)z*Return True if the transport is receiving.Nrrrrr
�
is_reading3szReadTransport.is_readingcCst�dS)z�Pause the receiving end.

        No data will be passed to the protocol's data_received()
        method until resume_reading() is called.
        Nrrrrr
�
pause_reading7szReadTransport.pause_readingcCst�dS)z�Resume the receiving end.

        Data received will once again be passed to the protocol's
        data_received() method.
        Nrrrrr
�resume_reading?szReadTransport.resume_readingN)rrrrrr r!r"rrrr
r.s
rc@sNeZdZdZdZddd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�ZdS)rz$Interface for write-only transports.rNcCst�dS)a�Set the high- and low-water limits for write flow control.

        These two values control when to call the protocol's
        pause_writing() and resume_writing() methods.  If specified,
        the low-water limit must be less than or equal to the
        high-water limit.  Neither value can be negative.

        The defaults are implementation-specific.  If only the
        high-water limit is given, the low-water limit defaults to an
        implementation-specific value less than or equal to the
        high-water limit.  Setting high to zero forces low to zero as
        well, and causes pause_writing() to be called whenever the
        buffer becomes non-empty.  Setting low to zero causes
        resume_writing() to be called only once the buffer is empty.
        Use of zero for either limit is generally sub-optimal as it
        reduces opportunities for doing I/O and computation
        concurrently.
        Nr�r
�high�lowrrr
�set_write_buffer_limitsMsz&WriteTransport.set_write_buffer_limitscCst�dS)z,Return the current size of the write buffer.Nrrrrr
�get_write_buffer_sizebsz$WriteTransport.get_write_buffer_sizecCst�dS)z�Write some data bytes to the transport.

        This does not block; it buffers the data and arranges for it
        to be sent out asynchronously.
        Nr)r
�datarrr
�writefszWriteTransport.writecCsd�|�}|�|�dS)z�Write a list (or any iterable) of data bytes to the transport.

        The default implementation concatenates the arguments and
        calls write() on the result.
        �N)�joinr))r
�list_of_datar(rrr
�
writelinesns
zWriteTransport.writelinescCst�dS)z�Close the write end after flushing buffered data.

        (This is like typing ^D into a UNIX program reading from stdin.)

        Data may still be received.
        Nrrrrr
�	write_eofwszWriteTransport.write_eofcCst�dS)zAReturn True if this transport supports write_eof(), False if not.Nrrrrr
�
can_write_eof�szWriteTransport.can_write_eofcCst�dS�z�Close the transport immediately.

        Buffered data will be lost.  No more data will be received.
        The protocol's connection_lost() method will (eventually) be
        called with None as its argument.
        Nrrrrr
�abort�szWriteTransport.abort)NN)rrrrrr&r'r)r-r.r/r1rrrr
rHs
		rc@seZdZdZdZdS)raSInterface representing a bidirectional transport.

    There may be several implementations, but typically, the user does
    not implement new transports; rather, the platform provides some
    useful transports that are implemented using the platform's best
    practices.

    The user never instantiates a transport directly; they call a
    utility function, passing it a protocol factory and other
    information necessary to create the transport and protocol.  (E.g.
    EventLoop.create_connection() or EventLoop.create_server().)

    The utility function will asynchronously create a transport and a
    protocol and hook them up by calling the protocol's
    connection_made() method, passing it the transport.

    The implementation here raises NotImplemented for every method
    except writelines(), which calls write() in a loop.
    rN)rrrrrrrrr
r�src@s&eZdZdZdZddd�Zdd�ZdS)	rz(Interface for datagram (UDP) transports.rNcCst�dS)aSend data to the transport.

        This does not block; it buffers the data and arranges for it
        to be sent out asynchronously.
        addr is target socket address.
        If addr is None use target address pointed on transport creation.
        Nr)r
r(�addrrrr
�sendto�szDatagramTransport.sendtocCst�dSr0rrrrr
r1�szDatagramTransport.abort)N)rrrrrr3r1rrrr
r�s

rc@s@eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dS)rrcCst�dS)zGet subprocess id.Nrrrrr
�get_pid�szSubprocessTransport.get_pidcCst�dS)z�Get subprocess returncode.

        See also
        http://docs.python.org/3/library/subprocess#subprocess.Popen.returncode
        Nrrrrr
�get_returncode�sz"SubprocessTransport.get_returncodecCst�dS)z&Get transport for pipe with number fd.Nr)r
�fdrrr
�get_pipe_transport�sz&SubprocessTransport.get_pipe_transportcCst�dS)z�Send signal to subprocess.

        See also:
        docs.python.org/3/library/subprocess#subprocess.Popen.send_signal
        Nr)r
�signalrrr
�send_signal�szSubprocessTransport.send_signalcCst�dS)aLStop the subprocess.

        Alias for close() method.

        On Posix OSs the method sends SIGTERM to the subprocess.
        On Windows the Win32 API function TerminateProcess()
         is called to stop the subprocess.

        See also:
        http://docs.python.org/3/library/subprocess#subprocess.Popen.terminate
        Nrrrrr
�	terminate�szSubprocessTransport.terminatecCst�dS)z�Kill the subprocess.

        On Posix OSs the function sends SIGKILL to the subprocess.
        On Windows kill() is an alias for terminate().

        See also:
        http://docs.python.org/3/library/subprocess#subprocess.Popen.kill
        Nrrrrr
�kill�s	zSubprocessTransport.killN)
rrrrr4r5r7r9r:r;rrrr
r�srcsZeZdZdZdZd�fdd�	Zdd�Zdd	�Zd
d�Zddd
�Z	ddd�Z
dd�Z�ZS)�_FlowControlMixinavAll the logic for (write) flow control in a mix-in base class.

    The subclass must implement get_write_buffer_size().  It must call
    _maybe_pause_protocol() whenever the write buffer size increases,
    and _maybe_resume_protocol() whenever it decreases.  It may also
    override set_write_buffer_limits() (e.g. to specify different
    defaults).

    The subclass constructor must call super().__init__(extra).  This
    will call set_write_buffer_limits().

    The user may call set_write_buffer_limits() and
    get_write_buffer_size(), and their protocol's pause_writing() and
    resume_writing() may be called.
    )�_loop�_protocol_paused�_high_water�
_low_waterNcs0t��|�|dk	st�||_d|_|��dS)NF)�superr�AssertionErrorr=r>�_set_write_buffer_limits)r
r�loop��	__class__rr
rs
z_FlowControlMixin.__init__c
Cs�|��}||jkrdS|js�d|_z|j��WnRttfk
rJ�Yn:tk
r�}z|j�	d|||jd��W5d}~XYnXdS)NTzprotocol.pause_writing() failed��message�	exception�	transportr)
r'r?r>�	_protocol�
pause_writing�
SystemExit�KeyboardInterrupt�
BaseExceptionr=�call_exception_handler)r
�size�excrrr
�_maybe_pause_protocols 
�z'_FlowControlMixin._maybe_pause_protocolc
Cs�|jr||��|jkr|d|_z|j��WnRttfk
rB�Yn:tk
rz}z|j�	d|||jd��W5d}~XYnXdS)NFz protocol.resume_writing() failedrG)
r>r'r@rK�resume_writingrMrNrOr=rP)r
rRrrr
�_maybe_resume_protocol!s��z(_FlowControlMixin._maybe_resume_protocolcCs|j|jfSr	)r@r?rrrr
�get_write_buffer_limits1sz)_FlowControlMixin.get_write_buffer_limitscCsj|dkr|dkrd}nd|}|dkr.|d}||krBdksZntd|�d|�d���||_||_dS)Ni��zhigh (z) must be >= low (z) must be >= 0)�
ValueErrorr?r@r#rrr
rC4s�z*_FlowControlMixin._set_write_buffer_limitscCs|j||d�|��dS)N)r$r%)rCrSr#rrr
r&Dsz)_FlowControlMixin.set_write_buffer_limitscCst�dSr	rrrrr
r'Hsz'_FlowControlMixin.get_write_buffer_size)NN)NN)NN)
rrrrrrrSrUrVrCr&r'�
__classcell__rrrEr
r<�s

r<N)	r�__all__rrrrrrr<rrrr
�<module>s%F6�h�'bytecode of module 'asyncio.transports'�u��b.��Q!h)��N}�(hB!�@s"ddlZddlZGdd�d�ZdS)�Nc@s�eZdZdZdZejd�dd�Zdd�Zedd	��Z	ed
d��Z
edd
��Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Zd2d3�Zd4d5�Zd6d7�Z d8d9�Z!d:d;�Z"d<d=�Z#d>d?�Z$d@dA�Z%dBdC�Z&dDdE�Z'dFdG�Z(dHdI�Z)dJdK�Z*dLdM�Z+dNdO�Z,dPdQ�Z-dRdS�Z.dTdU�Z/dVdW�Z0dXdY�Z1dZd[�Z2d\S)]�TransportSocketz�A socket-like wrapper for exposing real transport sockets.

    These objects can be safely returned by APIs like
    `transport.get_extra_info('socket')`.  All potentially disruptive
    operations (like "socket.close()") are banned.
    ��_sock)�sockcCs
||_dS�Nr)�selfr�r�$/usr/lib/python3.8/asyncio/trsock.py�__init__szTransportSocket.__init__cCstjd|�d�t|d�dS)NzUsing z� on sockets returned from get_extra_info('socket') will be prohibited in asyncio 3.9. Please report your use case to bugs.python.org.)�source)�warnings�warn�DeprecationWarning)r�whatrrr	�_nas

�zTransportSocket._nacCs|jjSr)r�family�rrrr	rszTransportSocket.familycCs|jjSr)r�typerrrr	rszTransportSocket.typecCs|jjSr)r�protorrrr	r"szTransportSocket.protocCs�d|���d|j�d|j�d|j��}|��dkr�z|��}|rN|�d|��}Wntjk
rfYnXz|��}|r�|�d|��}Wntjk
r�YnX|�d�S)	Nz<asyncio.TransportSocket fd=z	, family=z, type=z, proto=���z, laddr=z, raddr=�>)�filenorrr�getsockname�socket�error�getpeername)r�s�laddr�raddrrrr	�__repr__&s $�zTransportSocket.__repr__cCstd��dS)Nz/Cannot serialize asyncio.TransportSocket object)�	TypeErrorrrrr	�__getstate__=szTransportSocket.__getstate__cCs
|j��Sr)rrrrrr	r@szTransportSocket.filenocCs
|j��Sr)r�duprrrr	r"CszTransportSocket.dupcCs
|j��Sr)r�get_inheritablerrrr	r#FszTransportSocket.get_inheritablecCs|j�|�dSr)r�shutdown)r�howrrr	r$IszTransportSocket.shutdowncOs|jj||�Sr)r�
getsockopt�r�args�kwargsrrr	r&NszTransportSocket.getsockoptcOs|jj||�dSr)r�
setsockoptr'rrr	r*QszTransportSocket.setsockoptcCs
|j��Sr)rrrrrr	rTszTransportSocket.getpeernamecCs
|j��Sr)rrrrrr	rWszTransportSocket.getsocknamecCs
|j��Sr)r�
getsockbynamerrrr	r+ZszTransportSocket.getsockbynamecCs|�d�|j��S)Nzaccept() method)rr�acceptrrrr	r,]s
zTransportSocket.acceptcOs|�d�|jj||�S)Nzconnect() method)rr�connectr'rrr	r-as
zTransportSocket.connectcOs|�d�|jj||�S)Nzconnect_ex() method)rr�
connect_exr'rrr	r.es
zTransportSocket.connect_excOs|�d�|jj||�S)Nz
bind() method)rr�bindr'rrr	r/is
zTransportSocket.bindcOs|�d�|jj||�S)Nzioctl() method)rr�ioctlr'rrr	r0ms
zTransportSocket.ioctlcOs|�d�|jj||�S)Nzlisten() method)rr�listenr'rrr	r1qs
zTransportSocket.listencCs|�d�|j��S)Nzmakefile() method)rr�makefilerrrr	r2us
zTransportSocket.makefilecOs|�d�|jj||�S)Nzsendfile() method)rr�sendfiler'rrr	r3ys
zTransportSocket.sendfilecCs|�d�|j��S)Nzclose() method)rr�closerrrr	r4}s
zTransportSocket.closecCs|�d�|j��S)Nzdetach() method)rr�detachrrrr	r5�s
zTransportSocket.detachcOs|�d�|jj||�S)Nzsendmsg_afalg() method)rr�
sendmsg_afalgr'rrr	r6�s
zTransportSocket.sendmsg_afalgcOs|�d�|jj||�S)Nzsendmsg() method)rr�sendmsgr'rrr	r7�s
zTransportSocket.sendmsgcOs|�d�|jj||�S)Nzsendto() method)rr�sendtor'rrr	r8�s
zTransportSocket.sendtocOs|�d�|jj||�S)Nz
send() method)rr�sendr'rrr	r9�s
zTransportSocket.sendcOs|�d�|jj||�S)Nzsendall() method)rr�sendallr'rrr	r:�s
zTransportSocket.sendallcOs|�d�|jj||�S)Nzset_inheritable() method)rr�set_inheritabler'rrr	r;�s
zTransportSocket.set_inheritablecCs|�d�|j�|�S)Nzshare() method)rr�share)r�
process_idrrr	r<�s
zTransportSocket.sharecOs|�d�|jj||�S)Nzrecv_into() method)rr�	recv_intor'rrr	r>�s
zTransportSocket.recv_intocOs|�d�|jj||�S)Nzrecvfrom_into() method)rr�
recvfrom_intor'rrr	r?�s
zTransportSocket.recvfrom_intocOs|�d�|jj||�S)Nzrecvmsg_into() method)rr�recvmsg_intor'rrr	r@�s
zTransportSocket.recvmsg_intocOs|�d�|jj||�S)Nzrecvmsg() method)rr�recvmsgr'rrr	rA�s
zTransportSocket.recvmsgcOs|�d�|jj||�S)Nzrecvfrom() method)rr�recvfromr'rrr	rB�s
zTransportSocket.recvfromcOs|�d�|jj||�S)Nz
recv() method)rr�recvr'rrr	rC�s
zTransportSocket.recvcCs|dkrdStd��dS)Nrz<settimeout(): only 0 timeout is allowed on transport sockets��
ValueError)r�valuerrr	�
settimeout�s
�zTransportSocket.settimeoutcCsdS)Nrrrrrr	�
gettimeout�szTransportSocket.gettimeoutcCs|sdStd��dS)Nz3setblocking(): transport sockets cannot be blockingrD)r�flagrrr	�setblocking�s
�zTransportSocket.setblockingcCs|�d�|j��S�Nzcontext manager protocol)rr�	__enter__rrrr	rL�s
zTransportSocket.__enter__cGs|�d�|jj|�SrK)rr�__exit__)r�errrrr	rM�s
zTransportSocket.__exit__N)3�__name__�
__module__�__qualname__�__doc__�	__slots__rr
r�propertyrrrrr!rr"r#r$r&r*rrr+r,r-r.r/r0r1r2r3r4r5r6r7r8r9r:r;r<r>r?r@rArBrCrGrHrJrLrMrrrr	rsb


r)rrrrrrr	�<module>s�h�#bytecode of module 'asyncio.trsock'�u��b.��ۙh)��N}�(hB���@s�dZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
mZddl
mZddl
mZddl
mZddl
mZdd	l
mZdd
l
mZddl
mZddl
mZdd
l
mZddlmZdZe
jdkr�ed��dd�ZGdd�dej�ZGdd�dej �Z!Gdd�dej"ej#�Z$Gdd�dej%�Z&Gdd�d�Z'dd�Z(Gd d!�d!e'�Z)Gd"d#�d#e)�Z*Gd$d%�d%e)�Z+Gd&d'�d'e'�Z,Gd(d)�d)e'�Z-Gd*d+�d+ej.�Z/eZ0e/Z1dS),z2Selector event loop for Unix with signal handling.�N�)�base_events)�base_subprocess)�	constants)�
coroutines)�events)�
exceptions)�futures)�selector_events)�tasks)�
transports)�logger)�SelectorEventLoop�AbstractChildWatcher�SafeChildWatcher�FastChildWatcher�MultiLoopChildWatcher�ThreadedChildWatcher�DefaultEventLoopPolicy�win32z+Signals are not really supported on WindowscCsdS)zDummy signal handler.N�)�signum�framerr�)/usr/lib/python3.8/asyncio/unix_events.py�_sighandler_noop*srcs�eZdZdZd)�fdd�	Z�fdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
d*dd�Zd+dd�Zd,dd�Z
dd�Zd-ddddd�dd�Zd.dddddd�dd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Z�ZS)/�_UnixSelectorEventLoopzdUnix event loop.

    Adds signal handling and UNIX Domain Socket support to SelectorEventLoop.
    Ncst��|�i|_dS�N)�super�__init__�_signal_handlers)�self�selector��	__class__rrr5sz_UnixSelectorEventLoop.__init__csZt���t��s.t|j�D]}|�|�qn(|jrVtjd|�d�t	|d�|j�
�dS)NzClosing the loop z@ on interpreter shutdown stage, skipping signal handlers removal��source)r�close�sys�
is_finalizing�listr�remove_signal_handler�warnings�warn�ResourceWarning�clear�r �sigr"rrr&9s
�z_UnixSelectorEventLoop.closecCs|D]}|sq|�|�qdSr)�_handle_signal)r �datarrrr�_process_self_dataGsz)_UnixSelectorEventLoop._process_self_datac
GsLt�|�st�|�rtd��|�|�|��zt�|j�	��Wn2t
tfk
rt}ztt
|���W5d}~XYnXt�|||d�}||j|<zt�|t�t�|d�Wn�tk
�rF}zz|j|=|j�szt�d�Wn4t
tfk
�r}zt�d|�W5d}~XYnX|jtjk�r4td|�d���n�W5d}~XYnXdS)z�Add a handler for a signal.  UNIX only.

        Raise ValueError if the signal number is invalid or uncatchable.
        Raise RuntimeError if there is a problem setting up the handler.
        z3coroutines cannot be used with add_signal_handler()NF����set_wakeup_fd(-1) failed: %s�sig � cannot be caught)r�iscoroutine�iscoroutinefunction�	TypeError�
_check_signal�
_check_closed�signal�
set_wakeup_fd�_csock�fileno�
ValueError�OSError�RuntimeError�strr�Handlerr�siginterruptr
�info�errno�EINVAL)r r0�callback�args�exc�handle�nexcrrr�add_signal_handlerNs2
�

z)_UnixSelectorEventLoop.add_signal_handlercCs8|j�|�}|dkrdS|jr*|�|�n
|�|�dS)z2Internal helper that is the actual signal handler.N)r�get�
_cancelledr*�_add_callback_signalsafe)r r0rMrrrr1{sz%_UnixSelectorEventLoop._handle_signalc
Cs�|�|�z|j|=Wntk
r,YdSX|tjkr@tj}ntj}zt�||�WnBtk
r�}z$|jtj	kr�t
d|�d���n�W5d}~XYnX|js�zt�d�Wn2ttfk
r�}zt
�d|�W5d}~XYnXdS)zwRemove a handler for a signal.  UNIX only.

        Return True if a signal handler was removed, False if not.
        Fr6r7Nr4r5T)r;r�KeyErrorr=�SIGINT�default_int_handler�SIG_DFLrBrHrIrCr>rAr
rG)r r0�handlerrLrrrr*�s(

z,_UnixSelectorEventLoop.remove_signal_handlercCs6t|t�std|����|t��kr2td|����dS)z�Internal helper to validate a signal.

        Raise ValueError if the signal number is invalid or uncatchable.
        Raise RuntimeError if there is a problem setting up the handler.
        zsig must be an int, not zinvalid signal number N)�
isinstance�intr:r=�
valid_signalsrAr/rrrr;�s
z$_UnixSelectorEventLoop._check_signalcCst|||||�Sr)�_UnixReadPipeTransport�r �pipe�protocol�waiter�extrarrr�_make_read_pipe_transport�sz0_UnixSelectorEventLoop._make_read_pipe_transportcCst|||||�Sr)�_UnixWritePipeTransportr\rrr�_make_write_pipe_transport�sz1_UnixSelectorEventLoop._make_write_pipe_transportc	

�s�t����}
|
��std��|��}t||||||||f||d�|	��}|
�|��|j|�z|IdHWnDt	t
fk
r��Yn,tk
r�|��|�
�IdH�YnXW5QRX|S)NzRasyncio.get_child_watcher() is not activated, subprocess support is not installed.)r_r`)r�get_child_watcher�	is_activerC�
create_future�_UnixSubprocessTransport�add_child_handler�get_pid�_child_watcher_callback�
SystemExit�KeyboardInterrupt�
BaseExceptionr&�_wait)
r r^rK�shell�stdin�stdout�stderr�bufsizer`�kwargs�watcherr_�transprrr�_make_subprocess_transport�s8

���
�z1_UnixSelectorEventLoop._make_subprocess_transportcCs|�|j|�dSr)�call_soon_threadsafe�_process_exited)r �pid�
returncodervrrrrj�sz._UnixSelectorEventLoop._child_watcher_callback)�ssl�sock�server_hostname�ssl_handshake_timeoutc	�s |dkst|t�st�|r,|dkrLtd��n |dk	r<td��|dk	rLtd��|dk	r�|dk	rdtd��t�|�}t�tjtjd�}z |�	d�|�
||�IdHWq�|���Yq�Xn@|dkr�td��|jtjks�|j
tjkr�td|����|�	d�|j|||||d	�IdH\}}||fS)
Nz/you have to pass server_hostname when using sslz+server_hostname is only meaningful with ssl�1ssl_handshake_timeout is only meaningful with ssl�3path and sock can not be specified at the same timerFzno path and sock were specified�.A UNIX Domain Stream Socket was expected, got )r)rXrD�AssertionErrorrA�os�fspath�socket�AF_UNIX�SOCK_STREAM�setblocking�sock_connectr&�family�type�_create_connection_transport)	r �protocol_factory�pathr|r}r~r�	transportr^rrr�create_unix_connection�sT���



��
�z-_UnixSelectorEventLoop.create_unix_connection�dT)r}�backlogr|r�
start_servingc
�s�t|t�rtd��|dk	r&|s&td��|dk	�rH|dk	r@td��t�|�}t�tjtj�}|ddkr�z t	�
t�	|�j�r�t�|�WnBt
k
r�Yn0tk
r�}zt�d||�W5d}~XYnXz|�|�Wnltk
�r0}	z8|��|	jtjk�rd|�d�}
ttj|
�d�n�W5d}	~	XYn|���YnXn<|dk�rZtd	��|jtjk�sv|jtjk�r�td
|����|�d�t�||g||||�}|�r�|��tjd|d�IdH|S)
Nz*ssl argument must be an SSLContext or Noner�r�r)r�z2Unable to check or remove stale UNIX socket %r: %rzAddress z is already in usez-path was not specified, and no sock specifiedr�F)�loop)rX�boolr:rAr�r�r�r�r��stat�S_ISSOCK�st_mode�remove�FileNotFoundErrorrBr
�error�bindr&rH�
EADDRINUSEr�r�r�r�Server�_start_servingr�sleep)r r�r�r}r�r|rr��errrL�msg�serverrrr�create_unix_serversn
�
�
�

�
��
�z)_UnixSelectorEventLoop.create_unix_serverc
�s�z
tjWn,tk
r6}zt�d��W5d}~XYnXz|��}Wn2ttjfk
rv}zt�d��W5d}~XYnXzt�|�j	}Wn,t
k
r�}zt�d��W5d}~XYnX|r�|n|}	|	s�dS|��}
|�|
d|||||	d�|
IdHS)Nzos.sendfile() is not availableznot a regular filer)
r��sendfile�AttributeErrorr�SendfileNotAvailableErrorr@�io�UnsupportedOperation�fstat�st_sizerBrf�_sock_sendfile_native_impl)r r}�file�offset�countrLr@r��fsize�	blocksize�futrrr�_sock_sendfile_nativeJs2
��z,_UnixSelectorEventLoop._sock_sendfile_nativec	Cs,|��}	|dk	r|�|�|��r4|�|||�dS|rd||}|dkrd|�|||�|�|�dSzt�|	|||�}
W�nDttfk
r�|dkr�|�	||�|�
|	|j||	||||||�
Y�nbtk
�rj}z�|dk	�r|j
t
jk�rt|�tk	�rtdt
j�}||_|}|dk�rBt�d�}
|�|||�|�|
�n|�|||�|�|�W5d}~XYn�ttfk
�r��Yn�tk
�r�}z|�|||�|�|�W5d}~XYnjX|
dk�r�|�|||�|�|�nD||
7}||
7}|dk�r
|�	||�|�
|	|j||	||||||�
dS)Nrzsocket is not connectedzos.sendfile call failed)r@�
remove_writer�	cancelled�_sock_sendfile_update_filepos�
set_resultr�r��BlockingIOError�InterruptedError�_sock_add_cancellation_callback�
add_writerr�rBrH�ENOTCONNr��ConnectionError�	__cause__rr��
set_exceptionrkrlrm)r r��
registered_fdr}r@r�r�r��
total_sent�fd�sentrL�new_excr�rrrr�as�

�


�
��
�

�z1_UnixSelectorEventLoop._sock_sendfile_native_implcCs|dkrt�||tj�dS�Nr)r��lseek�SEEK_SET)r r@r�r�rrrr��sz4_UnixSelectorEventLoop._sock_sendfile_update_fileposcs��fdd�}|�|�dS)Ncs&|��r"���}|dkr"��|�dS)Nr4)r�r@r�)r�r��r r}rr�cb�szB_UnixSelectorEventLoop._sock_add_cancellation_callback.<locals>.cb)�add_done_callback)r r�r}r�rr�rr��sz6_UnixSelectorEventLoop._sock_add_cancellation_callback)N)NN)NN)N)N)N)�__name__�
__module__�__qualname__�__doc__rr&r3rOr1r*r;rarcrwrjr�r�r�r�r�r��
__classcell__rrr"rr/sH-
 �
�
�
��.��CFrcs�eZdZdZd�fdd�	Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Ze
jfdd�Zddd�Zdd�Zdd�Z�ZS) r[iNcs�t��|�||jd<||_||_|��|_||_d|_d|_	t
�|j�j}t
�|�s�t
�|�s�t
�|�s�d|_d|_d|_td��t
�|jd�|j�|jj|�|j�|jj|j|j�|dk	r�|j�tj|d�dS)Nr]Fz)Pipe transport is for pipes/sockets only.)rr�_extra�_loop�_piper@�_fileno�	_protocol�_closing�_pausedr�r�r�r��S_ISFIFOr��S_ISCHRrA�set_blocking�	call_soon�connection_made�_add_reader�_read_readyr	�_set_result_unless_cancelled)r r�r]r^r_r`�moder"rrr�s:


���
�z_UnixReadPipeTransport.__init__cCs�|jjg}|jdkr |�d�n|jr0|�d�|�d|j���t|jdd�}|jdk	r�|dk	r�t�	||jt
j�}|r�|�d�q�|�d�n |jdk	r�|�d�n
|�d�d�d	�
|��S)
N�closed�closing�fd=�	_selector�polling�idle�open�<{}>� )r#r�r��appendr�r��getattrr�r
�_test_selector_event�	selectors�
EVENT_READ�format�join)r rGr!r�rrr�__repr__�s(


�

z_UnixReadPipeTransport.__repr__c
Cs�zt�|j|j�}WnDttfk
r,Yn�tk
rX}z|�|d�W5d}~XYn^X|rl|j�	|�nJ|j
��r�t�
d|�d|_|j
�|j�|j
�|jj�|j
�|jd�dS)Nz"Fatal read error on pipe transport�%r was closed by peerT)r��readr��max_sizer�r�rB�_fatal_errorr��
data_receivedr��	get_debugr
rGr��_remove_readerr��eof_received�_call_connection_lost)r r2rLrrrr��s
z"_UnixReadPipeTransport._read_readycCs>|js|jrdSd|_|j�|j�|j��r:t�d|�dS)NTz%r pauses reading)r�r�r�r�r�r�r
�debug�r rrr�
pause_reading�s
z$_UnixReadPipeTransport.pause_readingcCsB|js|jsdSd|_|j�|j|j�|j��r>t�d|�dS)NFz%r resumes reading)	r�r�r�r�r�r�r�r
r�r�rrr�resume_readings
z%_UnixReadPipeTransport.resume_readingcCs
||_dSr�r��r r^rrr�set_protocol
sz#_UnixReadPipeTransport.set_protocolcCs|jSrrr�rrr�get_protocolsz#_UnixReadPipeTransport.get_protocolcCs|jSr�r�r�rrr�
is_closingsz!_UnixReadPipeTransport.is_closingcCs|js|�d�dSr)r��_closer�rrrr&sz_UnixReadPipeTransport.closecCs,|jdk	r(|d|��t|d�|j��dS�Nzunclosed transport r$�r�r-r&�r �_warnrrr�__del__s
z_UnixReadPipeTransport.__del__�Fatal error on pipe transportcCsZt|t�r4|jtjkr4|j��rLtjd||dd�n|j�||||j	d��|�
|�dS�Nz%r: %sT��exc_info)�message�	exceptionr�r^)rXrBrH�EIOr�r�r
r��call_exception_handlerr�r�r rLrrrrr�s
�z#_UnixReadPipeTransport._fatal_errorcCs(d|_|j�|j�|j�|j|�dS�NT)r�r�r�r�r�r��r rLrrrr-sz_UnixReadPipeTransport._closecCs4z|j�|�W5|j��d|_d|_d|_XdSr�r�r&r�r��connection_lostrrrrr�2s
z,_UnixReadPipeTransport._call_connection_lost)NN)r)r�r�r�r�rr�r�r�r�rrrr&r+r,rr�rr�r�rrr"rr[�s
r[cs�eZdZd%�fdd�	Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zejfdd�Zdd�Zd&dd �Zd'd!d"�Zd#d$�Z�ZS)(rbNc
s�t��||�||jd<||_|��|_||_t�|_d|_	d|_
t�|j�j
}t�|�}t�|�}t�|�}	|s�|s�|	s�d|_d|_d|_td��t�|jd�|j�|jj|�|	s�|r�tj�d�s�|j�|jj|j|j�|dk	r�|j�tj|d�dS)Nr]rFz?Pipe transport is only for pipes, sockets and character devices�aix)rrr�r�r@r�r��	bytearray�_buffer�
_conn_lostr�r�r�r�r�r�r�r�rAr�r�r�r�r'�platform�
startswithr�r�r	r�)
r r�r]r^r_r`r��is_char�is_fifo�	is_socketr"rrr?s:




�
�z _UnixWritePipeTransport.__init__cCs�|jjg}|jdkr |�d�n|jr0|�d�|�d|j���t|jdd�}|jdk	r�|dk	r�t�	||jt
j�}|r�|�d�n
|�d�|��}|�d|���n |jdk	r�|�d�n
|�d�d	�
d
�|��S)Nr�r�r�r�r�r�zbufsize=r�r�r�)r#r�r�r�r�r�r�r�r
r�r��EVENT_WRITE�get_write_buffer_sizer�r�)r rGr!r�rsrrrr�ds,


�


z _UnixWritePipeTransport.__repr__cCs
t|j�Sr)�lenrr�rrrr#|sz-_UnixWritePipeTransport.get_write_buffer_sizecCs6|j��rt�d|�|jr*|�t��n|��dS)Nr�)r�r�r
rGrr�BrokenPipeErrorr�rrrr�s

z#_UnixWritePipeTransport._read_readyc
CsRt|tttf�stt|���t|t�r.t|�}|s6dS|jsB|jrj|jtj	krXt
�d�|jd7_dS|j�s8zt
�|j|�}Wntttfk
r�d}YnZttfk
r��YnBtk
r�}z$|jd7_|�|d�WY�dSd}~XYnX|t|�k�rdS|dk�r&t|�|d�}|j�|j|j�|j|7_|��dS)Nz=pipe closed by peer or os.write(pipe, data) raised exception.rr�#Fatal write error on pipe transport)rX�bytesr�
memoryviewr��reprrr�r�!LOG_THRESHOLD_FOR_CONNLOST_WRITESr
�warningrr��writer�r�r�rkrlrmr�r$r��_add_writer�_write_ready�_maybe_pause_protocol)r r2�nrLrrrr,�s8


z_UnixWritePipeTransport.writec
Cs|jstd��zt�|j|j�}Wn�ttfk
r:Yn�ttfk
rR�Yn�t	k
r�}z6|j�
�|jd7_|j�
|j�|�|d�W5d}~XYnhX|t|j�kr�|j�
�|j�
|j�|��|jr�|j�|j�|�d�dS|dk�r|jd|�=dS)NzData should not be emptyrr&r)rr�r�r,r�r�r�rkrlrmr.rr��_remove_writerr�r$�_maybe_resume_protocolr�r�r�)r r0rLrrrr.�s,



z$_UnixWritePipeTransport._write_readycCsdSrrr�rrr�
can_write_eof�sz%_UnixWritePipeTransport.can_write_eofcCsB|jr
dS|jst�d|_|js>|j�|j�|j�|jd�dSr)	r�r�r�rr�r�r�r�r�r�rrr�	write_eof�s
z!_UnixWritePipeTransport.write_eofcCs
||_dSrrrrrrr�sz$_UnixWritePipeTransport.set_protocolcCs|jSrrr�rrrr�sz$_UnixWritePipeTransport.get_protocolcCs|jSrrr�rrrr�sz"_UnixWritePipeTransport.is_closingcCs|jdk	r|js|��dSr)r�r�r4r�rrrr&�sz_UnixWritePipeTransport.closecCs,|jdk	r(|d|��t|d�|j��dSrrr	rrrr�s
z_UnixWritePipeTransport.__del__cCs|�d�dSr)rr�rrr�abort�sz_UnixWritePipeTransport.abortrcCsNt|t�r(|j��r@tjd||dd�n|j�||||jd��|�|�dSr
)	rXrBr�r�r
r�rr�rrrrrr��s

�z$_UnixWritePipeTransport._fatal_errorcCsFd|_|jr|j�|j�|j��|j�|j�|j�|j|�dSr)	r�rr�r1r�r.r�r�r�rrrrr�s
z_UnixWritePipeTransport._closecCs4z|j�|�W5|j��d|_d|_d|_XdSrrrrrrr��s
z-_UnixWritePipeTransport._call_connection_lost)NN)r)N)r�r�r�rr�r#r�r,r.r3r4rrrr&r+r,rr5r�rr�r�rrr"rrb<s"%	#	

rbc@seZdZdd�ZdS)rgc		Ks�d}|tjkrt��\}}zPtj|f||||d|d�|��|_|dk	rh|��t|��d|d�|j_	d}W5|dk	r�|��|��XdS)NF)rorprqrr�universal_newlinesrs�wb)�	buffering)
�
subprocess�PIPEr��
socketpairr&�Popen�_procr��detachrp)	r rKrorprqrrrsrt�stdin_wrrr�_starts.
���z_UnixSubprocessTransport._startN)r�r�r�r@rrrrrg	srgc@sHeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dS)raHAbstract base class for monitoring child processes.

    Objects derived from this class monitor a collection of subprocesses and
    report their termination or interruption by a signal.

    New callbacks are registered with .add_child_handler(). Starting a new
    process must be done within a 'with' block to allow the watcher to suspend
    its activity until the new process if fully registered (this is needed to
    prevent a race condition in some implementations).

    Example:
        with watcher:
            proc = subprocess.Popen("sleep 1")
            watcher.add_child_handler(proc.pid, callback)

    Notes:
        Implementations of this class must be thread-safe.

        Since child watcher objects may catch the SIGCHLD signal and call
        waitpid(-1), there should be only one active object per process.
    cGs
t��dS)aRegister a new child handler.

        Arrange for callback(pid, returncode, *args) to be called when
        process 'pid' terminates. Specifying another callback for the same
        process replaces the previous handler.

        Note: callback() must be thread-safe.
        N��NotImplementedError�r rzrJrKrrrrh9s	z&AbstractChildWatcher.add_child_handlercCs
t��dS)z�Removes the handler for process 'pid'.

        The function returns True if the handler was successfully removed,
        False if there was nothing to remove.NrA�r rzrrr�remove_child_handlerDsz)AbstractChildWatcher.remove_child_handlercCs
t��dS)z�Attach the watcher to an event loop.

        If the watcher was previously attached to an event loop, then it is
        first detached before attaching to the new loop.

        Note: loop may be None.
        NrA�r r�rrr�attach_loopLsz AbstractChildWatcher.attach_loopcCs
t��dS)zlClose the watcher.

        This must be called to make sure that any underlying resource is freed.
        NrAr�rrrr&VszAbstractChildWatcher.closecCs
t��dS)z�Return ``True`` if the watcher is active and is used by the event loop.

        Return True if the watcher is installed and ready to handle process exit
        notifications.

        NrAr�rrrre]szAbstractChildWatcher.is_activecCs
t��dS)zdEnter the watcher's context and allow starting new processes

        This function must return selfNrAr�rrr�	__enter__fszAbstractChildWatcher.__enter__cCs
t��dS)zExit the watcher's contextNrA�r �a�b�crrr�__exit__lszAbstractChildWatcher.__exit__N)r�r�r�r�rhrErGr&rerHrMrrrrr"s
	rcCs2t�|�rt�|�St�|�r*t�|�S|SdSr)r��WIFSIGNALED�WTERMSIG�	WIFEXITED�WEXITSTATUS)�statusrrr�_compute_returncodeqs



rSc@sDeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)�BaseChildWatchercCsd|_i|_dSr)r��
_callbacksr�rrrr�szBaseChildWatcher.__init__cCs|�d�dSr)rGr�rrrr&�szBaseChildWatcher.closecCs|jdk	o|j��Sr)r��
is_runningr�rrrre�szBaseChildWatcher.is_activecCs
t��dSrrA)r �expected_pidrrr�_do_waitpid�szBaseChildWatcher._do_waitpidcCs
t��dSrrAr�rrr�_do_waitpid_all�sz BaseChildWatcher._do_waitpid_allcCs~|dkst|tj�st�|jdk	r<|dkr<|jr<t�dt�|jdk	rT|j�	t
j�||_|dk	rz|�t
j|j
�|��dS)NzCA loop is being detached from a child watcher with pending handlers)rXr�AbstractEventLoopr�r�rUr+r,�RuntimeWarningr*r=�SIGCHLDrO�	_sig_chldrYrFrrrrG�s�
zBaseChildWatcher.attach_loopc
Cs^z|��WnLttfk
r&�Yn4tk
rX}z|j�d|d��W5d}~XYnXdS)N�$Unknown exception in SIGCHLD handler)rr)rYrkrlrmr�rrrrrr]�s�zBaseChildWatcher._sig_chldN)
r�r�r�rr&rerXrYrGr]rrrrrTsrTcsPeZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
�ZS)rad'Safe' child watcher implementation.

    This implementation avoids disrupting other code spawning processes by
    polling explicitly each process in the SIGCHLD handler instead of calling
    os.waitpid(-1).

    This is a safe solution but it has a significant overhead when handling a
    big number of children (O(n) each time SIGCHLD is raised)
    cs|j��t���dSr)rUr.rr&r�r"rrr&�s
zSafeChildWatcher.closecCs|Srrr�rrrrH�szSafeChildWatcher.__enter__cCsdSrrrIrrrrM�szSafeChildWatcher.__exit__cGs||f|j|<|�|�dSr)rUrXrCrrrrh�sz"SafeChildWatcher.add_child_handlercCs*z|j|=WdStk
r$YdSXdS�NTF�rUrSrDrrrrE�s
z%SafeChildWatcher.remove_child_handlercCst|j�D]}|�|�q
dSr�r)rUrXrDrrrrY�sz SafeChildWatcher._do_waitpid_allcCs�|dkst�zt�|tj�\}}Wn(tk
rJ|}d}t�d|�Yn.X|dkrXdSt|�}|j�	�rxt�
d||�z|j�|�\}}Wn.t
k
r�|j�	�r�tjd|dd�YnX|||f|��dS)Nr��8Unknown child process pid %d, will report returncode 255�$process %s exited with returncode %s�'Child watcher got an unexpected pid: %rTr)r�r��waitpid�WNOHANG�ChildProcessErrorr
r+rSr�r�r�rU�poprS)r rWrzrRr{rJrKrrrrX�s6�

�
�zSafeChildWatcher._do_waitpid)r�r�r�r�r&rHrMrhrErYrXr�rrr"rr�s
rcsTeZdZdZ�fdd�Z�fdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
�ZS)raW'Fast' child watcher implementation.

    This implementation reaps every terminated processes by calling
    os.waitpid(-1) directly, possibly breaking other code spawning processes
    and waiting for their termination.

    There is no noticeable overhead when handling a big number of children
    (O(1) each time a child terminates).
    cs$t���t��|_i|_d|_dSr�)rr�	threading�Lock�_lock�_zombies�_forksr�r"rrrs

zFastChildWatcher.__init__cs"|j��|j��t���dSr)rUr.rmrr&r�r"rrr&s

zFastChildWatcher.closec
Cs0|j� |jd7_|W5QR�SQRXdS)Nr)rlrnr�rrrrHszFastChildWatcher.__enter__c	Cs^|j�B|jd8_|js"|js0W5QR�dSt|j�}|j��W5QRXt�d|�dS)Nrz5Caught subprocesses termination from unknown pids: %s)rlrnrmrDr.r
r+)r rJrKrL�collateral_victimsrrrrMs
�zFastChildWatcher.__exit__c	Gst|jstd��|j�Fz|j�|�}Wn.tk
rT||f|j|<YW5QR�dSXW5QRX|||f|��dS)NzMust use the context manager)rnr�rlrmrirSrU)r rzrJrKr{rrrrh'sz"FastChildWatcher.add_child_handlercCs*z|j|=WdStk
r$YdSXdSr_r`rDrrrrE5s
z%FastChildWatcher.remove_child_handlerc	Cs�zt�dtj�\}}Wntk
r,YdSX|dkr:dSt|�}|j��z|j�|�\}}WnNtk
r�|j	r�||j
|<|j��r�t
�d||�YW5QR�qd}YnX|j��r�t
�d||�W5QRX|dkr�t
�d||�q|||f|��qdS)Nr4rz,unknown process %s exited with returncode %srdz8Caught subprocess termination from unknown pid: %d -> %d)r�rfrgrhrSrlrUrirSrnrmr�r�r
r�r+)r rzrRr{rJrKrrrrY<s@

�

��z FastChildWatcher._do_waitpid_all)r�r�r�r�rr&rHrMrhrErYr�rrr"rr�s	rc@sheZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�ZdS)ra~A watcher that doesn't require running loop in the main thread.

    This implementation registers a SIGCHLD signal handler on
    instantiation (which may conflict with other code that
    install own handler for this signal).

    The solution is safe but it has a significant overhead when
    handling a big number of processes (*O(n)* each time a
    SIGCHLD is received).
    cCsi|_d|_dSr)rU�_saved_sighandlerr�rrrrzszMultiLoopChildWatcher.__init__cCs
|jdk	Sr)rpr�rrrre~szMultiLoopChildWatcher.is_activecCsT|j��|jdkrdSt�tj�}||jkr:t�d�nt�tj|j�d|_dS)Nz+SIGCHLD handler was changed by outside code)	rUr.rpr=�	getsignalr\r]r
r+)r rWrrrr&�s


zMultiLoopChildWatcher.closecCs|Srrr�rrrrH�szMultiLoopChildWatcher.__enter__cCsdSrr�r �exc_type�exc_val�exc_tbrrrrM�szMultiLoopChildWatcher.__exit__cGs&t��}|||f|j|<|�|�dSr)r�get_running_looprUrX)r rzrJrKr�rrrrh�sz'MultiLoopChildWatcher.add_child_handlercCs*z|j|=WdStk
r$YdSXdSr_r`rDrrrrE�s
z*MultiLoopChildWatcher.remove_child_handlercCsN|jdk	rdSt�tj|j�|_|jdkr<t�d�tj|_t�tjd�dS)NzaPrevious SIGCHLD handler was set by non-Python code, restore to default handler on watcher close.F)rpr=r\r]r
r+rVrFrFrrrrG�s


z!MultiLoopChildWatcher.attach_loopcCst|j�D]}|�|�q
dSrrarDrrrrY�sz%MultiLoopChildWatcher._do_waitpid_allc	Cs�|dkst�zt�|tj�\}}Wn,tk
rN|}d}t�d|�d}YnX|dkr\dSt|�}d}z|j�	|�\}}}Wn$t
k
r�tjd|dd�YnHX|��r�t�d||�n.|r�|��r�t�
d	||�|j|||f|��dS)
NrrbrcFTrer�%Loop %r that handles pid %r is closedrd)r�r�rfrgrhr
r+rSrUrirS�	is_closedr�r�rx)	r rWrzrRr{�	debug_logr�rJrKrrrrX�s<�
��z!MultiLoopChildWatcher._do_waitpidc	CsLz|��Wn:ttfk
r&�Yn"tk
rFtjddd�YnXdS)Nr^Tr)rYrkrlrmr
r+)r rrrrrr]�szMultiLoopChildWatcher._sig_chldN)r�r�r�r�rrer&rHrMrhrErGrYrXr]rrrrrgs%rc@sneZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	e
jfdd�Zdd�Z
dd�Zdd�Zdd�ZdS)raAThreaded child watcher implementation.

    The watcher uses a thread per process
    for waiting for the process finish.

    It doesn't require subscription on POSIX signal
    but a thread creation is not free.

    The watcher has O(1) complexity, its performance doesn't depend
    on amount of spawn processes.
    cCst�d�|_i|_dSr�)�	itertoolsr��_pid_counter�_threadsr�rrrr�szThreadedChildWatcher.__init__cCsdSrrr�rrrre�szThreadedChildWatcher.is_activecCs|��dSr)�
_join_threadsr�rrrr&�szThreadedChildWatcher.closecCs.dd�t|j���D�}|D]}|��qdS)z%Internal: Join all non-daemon threadscSsg|]}|��r|js|�qSr)�is_alive�daemon��.0�threadrrr�
<listcomp>�s�z6ThreadedChildWatcher._join_threads.<locals>.<listcomp>N)r)r|�valuesr�)r �threadsr�rrrr}�sz"ThreadedChildWatcher._join_threadscCs|Srrr�rrrrHszThreadedChildWatcher.__enter__cCsdSrrrrrrrrMszThreadedChildWatcher.__exit__cCs6dd�t|j���D�}|r2||j�d�t|d�dS)NcSsg|]}|��r|�qSr)r~r�rrrr�	s�z0ThreadedChildWatcher.__del__.<locals>.<listcomp>z0 has registered but not finished child processesr$)r)r|r�r#r-)r r
r�rrrrs�zThreadedChildWatcher.__del__cGsFt��}tj|jdt|j���||||fdd�}||j|<|��dS)Nzwaitpid-T)�target�namerKr)	rrvrj�ThreadrX�nextr{r|�start)r rzrJrKr�r�rrrrhs
�
z&ThreadedChildWatcher.add_child_handlercCsdSrrrDrrrrEsz)ThreadedChildWatcher.remove_child_handlercCsdSrrrFrrrrGsz ThreadedChildWatcher.attach_loopcCs�|dkst�zt�|d�\}}Wn(tk
rH|}d}t�d|�Yn Xt|�}|��rht�d||�|�	�r�t�d||�n|j
|||f|��|j�|�dS)Nrrbrcrdrw)
r�r�rfrhr
r+rSr�r�rxrxr|ri)r r�rWrJrKrzrRr{rrrrX"s(�
�z ThreadedChildWatcher._do_waitpidN)r�r�r�r�rrer&r}rHrMr+r,rrhrErGrXrrrrr�s	rcsHeZdZdZeZ�fdd�Zdd�Z�fdd�Zdd	�Z	d
d�Z
�ZS)�_UnixDefaultEventLoopPolicyz:UNIX event loop policy with a watcher for child processes.cst���d|_dSr)rr�_watcherr�r"rrrAs
z$_UnixDefaultEventLoopPolicy.__init__c	CsHtj�8|jdkr:t�|_tt��tj�r:|j�|j	j
�W5QRXdSr)rrlr�rrXrj�current_thread�_MainThreadrG�_localr�r�rrr�
_init_watcherEs
�z)_UnixDefaultEventLoopPolicy._init_watchercs6t��|�|jdk	r2tt��tj�r2|j�|�dS)z�Set the event loop.

        As a side effect, if a child watcher was set before, then calling
        .set_event_loop() from the main thread will call .attach_loop(loop) on
        the child watcher.
        N)r�set_event_loopr�rXrjr�r�rGrFr"rrr�Ms

�z*_UnixDefaultEventLoopPolicy.set_event_loopcCs|jdkr|��|jS)z~Get the watcher for child processes.

        If not yet set, a ThreadedChildWatcher object is automatically created.
        N)r�r�r�rrrrd[s
z-_UnixDefaultEventLoopPolicy.get_child_watchercCs4|dkst|t�st�|jdk	r*|j��||_dS)z$Set the watcher for child processes.N)rXrr�r�r&)r rurrr�set_child_watcheres

z-_UnixDefaultEventLoopPolicy.set_child_watcher)r�r�r�r�r�
_loop_factoryrr�r�rdr�r�rrr"rr�=s
r�)2r�rHr�rzr�r�r=r�r�r9r'rjr+�rrrrrrr	r
rr�logr
�__all__r�ImportErrorr�BaseSelectorEventLoopr�
ReadTransportr[�_FlowControlMixin�WriteTransportrb�BaseSubprocessTransportrgrrSrTrrrr�BaseDefaultEventLoopPolicyr�rrrrrr�<module>s`	
	�NO5Ji}Y3�h�(bytecode of module 'asyncio.unix_events'�u��b.���h)��N}�(hCt�@sdS)N�rrr�)/usr/lib/python3.8/concurrent/__init__.py�<module>��h�bytecode of module 'concurrent'�u��b.���h)��N}�(hBD�@sTdZdZddlmZmZmZmZmZmZm	Z	m
Z
mZmZm
Z
dZdd�Zdd�Zd	S)
z?Execute computations asynchronously using threads or processes.z"Brian Quinlan (brian@sweetapp.com)�)�FIRST_COMPLETED�FIRST_EXCEPTION�
ALL_COMPLETED�CancelledError�TimeoutError�InvalidStateError�BrokenExecutor�Future�Executor�wait�as_completed)rrrrrrr	r
rr�ProcessPoolExecutor�ThreadPoolExecutorcCstdS)N)�
__author__�__doc__)�__all__�rr�1/usr/lib/python3.8/concurrent/futures/__init__.py�__dir__$srcCsP|dkrddlm}|a|S|dkr8ddlm}|a|Stdt�d|����dS)Nr
�)r
r)rzmodule z has no attribute )�processr
�threadr�AttributeError�__name__)�name�pe�terrr�__getattr__(srN)rr�concurrent.futures._baserrrrrrrr	r
rrrrrrrrr�<module>s
4�h�'bytecode of module 'concurrent.futures'�u��b.���Uh)��N}�(hB�U�
@spdZddlZddlZddlZddlZdZdZdZdZdZ	dZ
d	Zd
ZdZ
e	e
eee
gZe	de
d
edede
diZe�d�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd �d e�ZGd!d"�d"e�Zd#d$�Zd%d&�Zd3d'd(�Ze� d)d*�Z!defd+d,�Z"Gd-d.�d.e�Z#Gd/d0�d0e�Z$Gd1d2�d2e%�Z&dS)4z"Brian Quinlan (brian@sweetapp.com)�N�FIRST_COMPLETED�FIRST_EXCEPTION�
ALL_COMPLETED�
_AS_COMPLETED�PENDING�RUNNING�	CANCELLED�CANCELLED_AND_NOTIFIED�FINISHED�pending�running�	cancelled�finishedzconcurrent.futuresc@seZdZdZdS)�Errorz-Base class for all future-related exceptions.N��__name__�
__module__�__qualname__�__doc__�rr�./usr/lib/python3.8/concurrent/futures/_base.pyr,src@seZdZdZdS)�CancelledErrorzThe Future was cancelled.Nrrrrrr0src@seZdZdZdS)�TimeoutErrorz*The operation exceeded the given deadline.Nrrrrrr4src@seZdZdZdS)�InvalidStateErrorz+The operation is not allowed in this state.Nrrrrrr8src@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)�_Waiterz;Provides the event that wait() and as_completed() block on.cCst��|_g|_dS�N)�	threading�Event�event�finished_futures��selfrrr�__init__>s
z_Waiter.__init__cCs|j�|�dSr�r�append�r!�futurerrr�
add_resultBsz_Waiter.add_resultcCs|j�|�dSrr#r%rrr�
add_exceptionEsz_Waiter.add_exceptioncCs|j�|�dSrr#r%rrr�
add_cancelledHsz_Waiter.add_cancelledN)rrrrr"r'r(r)rrrrr<s
rcsDeZdZdZ�fdd�Z�fdd�Z�fdd�Z�fdd	�Z�ZS)
�_AsCompletedWaiterzUsed by as_completed().cstt|���t��|_dSr)�superr*r"r�Lock�lockr ��	__class__rrr"Nsz_AsCompletedWaiter.__init__c	s0|j� tt|��|�|j��W5QRXdSr)r-r+r*r'r�setr%r.rrr'Rsz_AsCompletedWaiter.add_resultc	s0|j� tt|��|�|j��W5QRXdSr)r-r+r*r(rr0r%r.rrr(Wsz _AsCompletedWaiter.add_exceptionc	s0|j� tt|��|�|j��W5QRXdSr)r-r+r*r)rr0r%r.rrr)\sz _AsCompletedWaiter.add_cancelled)	rrrrr"r'r(r)�
__classcell__rrr.rr*Ks
r*cs8eZdZdZ�fdd�Z�fdd�Z�fdd�Z�ZS)�_FirstCompletedWaiterz*Used by wait(return_when=FIRST_COMPLETED).cst��|�|j��dSr)r+r'rr0r%r.rrr'dsz _FirstCompletedWaiter.add_resultcst��|�|j��dSr)r+r(rr0r%r.rrr(hsz#_FirstCompletedWaiter.add_exceptioncst��|�|j��dSr)r+r)rr0r%r.rrr)lsz#_FirstCompletedWaiter.add_cancelled)rrrrr'r(r)r1rrr.rr2asr2csLeZdZdZ�fdd�Zdd�Z�fdd�Z�fdd	�Z�fd
d�Z�Z	S)�_AllCompletedWaiterz<Used by wait(return_when=FIRST_EXCEPTION and ALL_COMPLETED).cs$||_||_t��|_t���dSr)�num_pending_calls�stop_on_exceptionrr,r-r+r")r!r4r5r.rrr"ss
z_AllCompletedWaiter.__init__c	Cs4|j�$|jd8_|js&|j��W5QRXdS)N�)r-r4rr0r rrr�_decrement_pending_callsysz,_AllCompletedWaiter._decrement_pending_callscst��|�|��dSr)r+r'r7r%r.rrr'sz_AllCompletedWaiter.add_resultcs*t��|�|jr|j��n|��dSr)r+r(r5rr0r7r%r.rrr(�sz!_AllCompletedWaiter.add_exceptioncst��|�|��dSr)r+r)r7r%r.rrr)�sz!_AllCompletedWaiter.add_cancelled)
rrrrr"r7r'r(r)r1rrr.rr3psr3c@s(eZdZdZdd�Zdd�Zdd�ZdS)	�_AcquireFutureszDA context manager that does an ordered acquire of Future conditions.cCst|td�|_dS)N)�key)�sorted�id�futures)r!r<rrrr"�sz_AcquireFutures.__init__cCs|jD]}|j��qdSr)r<�
_condition�acquirer%rrr�	__enter__�s
z_AcquireFutures.__enter__cGs|jD]}|j��qdSr)r<r=�release)r!�argsr&rrr�__exit__�s
z_AcquireFutures.__exit__N)rrrrr"r?rBrrrrr8�sr8cCs�|tkrt�}nZ|tkr t�}nJtdd�|D��}|tkrHt|dd�}n"|tkr^t|dd�}ntd|��|D]}|j	�
|�qn|S)Ncss|]}|jttfkVqdSr��_stater	r
��.0�frrr�	<genexpr>�sz._create_and_install_waiters.<locals>.<genexpr>T)r5FzInvalid return condition: %r)rr*rr2�sumrr3r�
ValueError�_waitersr$)�fs�return_when�waiter�
pending_countrGrrr�_create_and_install_waiters�s�rPc	csP|rL|d}|D]}|�|�q|j�|j�|�W5QRX~|��VqdS)a~
    Iterate on the list *fs*, yielding finished futures one by one in
    reverse order.
    Before yielding a future, *waiter* is removed from its waiters
    and the future is removed from each set in the collection of sets
    *ref_collect*.

    The aim of this function is to avoid keeping stale references after
    the future is yielded and before the iterator resumes.
    ���N)�remover=rK�pop)rLrN�ref_collectrG�futures_setrrr�_yield_finished_futures�srVc	csB|dk	r|t��}t|�}t|�}t|��*tdd�|D��}||}t|t�}W5QRXt|�}z�t|||fd�EdH|�r|dkr�d}n(|t��}|dkr�tdt|�|f��|j
�|�|j�|j}g|_|j
��W5QRX|��t||||fd�EdHq|W5|D]$}|j�|j	�
|�W5QRX�qXdS)anAn iterator over the given futures that yields each as it completes.

    Args:
        fs: The sequence of Futures (possibly created by different Executors) to
            iterate over.
        timeout: The maximum number of seconds to wait. If None, then there
            is no limit on the wait time.

    Returns:
        An iterator that yields the given Futures as they complete (finished or
        cancelled). If any given Futures are duplicated, they will be returned
        once.

    Raises:
        TimeoutError: If the entire result iterator could not be generated
            before the given timeout.
    Ncss |]}|jttfkr|VqdSrrCrErrrrH�s�zas_completed.<locals>.<genexpr>)rTrz%d (of %d) futures unfinished)�time�	monotonicr0�lenr8rPr�listr=rKrRrVrr�waitr-r�clear�reverse)	rL�timeout�end_time�
total_futuresrrrNrG�wait_timeoutrrr�as_completed�sL
�����rb�DoneAndNotDoneFuturesz
done not_donec
Cs
t|���tdd�|D��}t|�|}|tkrJ|rJt||�W5QR�S|tkr~|r~tdd�|D��r~t||�W5QR�St|�t|�kr�t||�W5QR�St||�}W5QRX|j�	|�|D]"}|j
�|j�|�W5QRXq�|�
|j�t|t|�|�S)aWait for the futures in the given sequence to complete.

    Args:
        fs: The sequence of Futures (possibly created by different Executors) to
            wait upon.
        timeout: The maximum number of seconds to wait. If None, then there
            is no limit on the wait time.
        return_when: Indicates when this function should return. The options
            are:

            FIRST_COMPLETED - Return when any future finishes or is
                              cancelled.
            FIRST_EXCEPTION - Return when any future finishes by raising an
                              exception. If no future raises an exception
                              then it is equivalent to ALL_COMPLETED.
            ALL_COMPLETED -   Return when all futures finish or are cancelled.

    Returns:
        A named 2-tuple of sets. The first set, named 'done', contains the
        futures that completed (is finished or cancelled) before the wait
        completed. The second set, named 'not_done', contains uncompleted
        futures.
    css |]}|jttfkr|VqdSrrCrErrrrH!s�zwait.<locals>.<genexpr>css&|]}|��s|��dk	r|VqdSr)r
�	exceptionrErrrrH(s�)r8r0rrcr�anyrYrPrr[r=rKrR�updater)rLr^rM�done�not_donerNrGrrrr[s"
r[c@s�eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zddd�Z
d dd�Zdd�Zdd�Zdd�ZdS)!�Futurez5Represents the result of an asynchronous computation.cCs,t��|_t|_d|_d|_g|_g|_dS)z8Initializes the future. Should not be called by clients.N)	r�	Conditionr=rrD�_result�
_exceptionrK�_done_callbacksr rrrr"<s
zFuture.__init__c	Cs>|jD]2}z||�Wqtk
r6t�d|�YqXqdS)N�!exception calling callback for %r)rm�	Exception�LOGGERrd)r!�callbackrrr�_invoke_callbacksEs

zFuture._invoke_callbacksc
Cs�|j��|jtkrx|jrHd|jjt|�t|j|jjjfW5QR�Sd|jjt|�t|j|jjjfW5QR�Sd|jjt|�t|jfW5QR�SQRXdS)Nz<%s at %#x state=%s raised %s>z <%s at %#x state=%s returned %s>z<%s at %#x state=%s>)	r=rDr
rlr/rr;�_STATE_TO_DESCRIPTION_MAPrkr rrr�__repr__Ls(
���zFuture.__repr__c	Csf|j�N|jttfkr$W5QR�dS|jttfkr@W5QR�dSt|_|j��W5QRX|��dS)z�Cancel the future if possible.

        Returns True if the future was cancelled, False otherwise. A future
        cannot be cancelled if it is running or has already completed.
        FT)r=rDrr
rr	�
notify_allrrr rrr�cancel`sz
Future.cancelc
Cs,|j�|jttfkW5QR�SQRXdS)z(Return True if the future was cancelled.N)r=rDrr	r rrrr
sszFuture.cancelledc
Cs(|j�|jtkW5QR�SQRXdS)z1Return True if the future is currently executing.N)r=rDrr rrrrxszFuture.runningc
Cs.|j�|jtttfkW5QR�SQRXdS)z>Return True of the future was cancelled or finished executing.N)r=rDrr	r
r rrrrg}szFuture.donecCs$|jrz
|j�W5d}Xn|jSdSr)rlrkr rrr�__get_result�s

zFuture.__get_resultc	Csn|j�0|jtttfkr2|j�|�W5QR�dSW5QRXz||�Wn tk
rht�	d|�YnXdS)a%Attaches a callable that will be called when the future finishes.

        Args:
            fn: A callable that will be called with this future as its only
                argument when the future completes or is cancelled. The callable
                will always be called by a thread in the same process in which
                it was added. If the future has already completed or been
                cancelled then the callable will be called immediately. These
                callables are called in the order that they were added.
        Nrn)
r=rDrr	r
rmr$rorprd)r!�fnrrr�add_done_callback�szFuture.add_done_callbackNc
Cs�z�|j��|jttfkr t��n"|jtkrB|��W5QR�W�ZS|j�|�|jttfkrdt��n(|jtkr�|��W5QR�W�St��W5QRXW5d}XdS)aBReturn the result of the call that the future represents.

        Args:
            timeout: The number of seconds to wait for the result if the future
                isn't done. If None, then there is no limit on the wait time.

        Returns:
            The result of the call that the future represents.

        Raises:
            CancelledError: If the future was cancelled.
            TimeoutError: If the future didn't finish executing before the given
                timeout.
            Exception: If the call raised then that exception will be raised.
        N)	r=rDrr	rr
�_Future__get_resultr[r�r!r^rrr�result�s

z
Future.resultc
Cs�|j�||jttfkrt��n|jtkr:|jW5QR�S|j�|�|jttfkr\t��n"|jtkrx|jW5QR�St��W5QRXdS)aUReturn the exception raised by the call that the future represents.

        Args:
            timeout: The number of seconds to wait for the exception if the
                future isn't done. If None, then there is no limit on the wait
                time.

        Returns:
            The exception raised by the call that the future represents or None
            if the call completed without raising.

        Raises:
            CancelledError: If the future was cancelled.
            TimeoutError: If the future didn't finish executing before the given
                timeout.
        N)	r=rDrr	rr
rlr[rr{rrrrd�s

zFuture.exceptionc	Cs�|j�t|jtkr<t|_|jD]}|�|�qW5QR�dS|jtkrZt|_W5QR�dSt�	dt
|�|j�td��W5QRXdS)a�Mark the future as running or process any cancel notifications.

        Should only be used by Executor implementations and unit tests.

        If the future has been cancelled (cancel() was called and returned
        True) then any threads waiting on the future completing (though calls
        to as_completed() or wait()) are notified and False is returned.

        If the future was not cancelled then it is put in the running state
        (future calls to running() will return True) and True is returned.

        This method should be called by Executor implementations before
        executing the work associated with this future. If this method returns
        False then the work should not be executed.

        Returns:
            False if the Future was cancelled, True otherwise.

        Raises:
            RuntimeError: if this method was already called or if set_result()
                or set_exception() was called.
        FTz!Future %s in unexpected state: %szFuture in unexpected stateN)r=rDrr	rKr)rrrp�criticalr;�RuntimeError)r!rNrrr�set_running_or_notify_cancel�s


�z#Future.set_running_or_notify_cancelc	Csl|j�T|jttthkr*td�|j|���||_t|_|jD]}|�	|�q<|j�
�W5QRX|��dS)z�Sets the return value of work associated with the future.

        Should only be used by Executor implementations and unit tests.
        �{}: {!r}N)r=rDrr	r
r�formatrkrKr'rurr)r!r|rNrrr�
set_result
s
zFuture.set_resultc	Csl|j�T|jttthkr*td�|j|���||_t|_|jD]}|�	|�q<|j�
�W5QRX|��dS)z�Sets the result of the future as being the given exception.

        Should only be used by Executor implementations and unit tests.
        r�N)r=rDrr	r
rr�rlrKr(rurr)r!rdrNrrr�
set_exceptions
zFuture.set_exception)N)N)rrrrr"rrrtrvr
rrgrzryr|rdrr�r�rrrrri9s	

#
"(ric@sHeZdZdZdd�Zde_ddd�dd	�Zddd�Zd
d�Zdd�Z	dS)�ExecutorzCThis is an abstract base class for concrete asynchronous executors.cOs\t|�dkrnD|std��n6d|kr>ddl}|jdtdd�ntdt|�d	��t��dS)
a Submits a callable to be executed with the given arguments.

        Schedules the callable to be executed as fn(*args, **kwargs) and returns
        a Future instance representing the execution of the callable.

        Returns:
            A Future representing the given call.
        �z:descriptor 'submit' of 'Executor' object needs an argumentrxrNz.Passing 'fn' as keyword argument is deprecated)�
stacklevelz6submit expected at least 1 positional argument, got %dr6)rY�	TypeError�warnings�warn�DeprecationWarning�NotImplementedError)rA�kwargsr�rrr�submit.s	
�
�zExecutor.submitz($self, fn, /, *args, **kwargs)Nr6)r^�	chunksizecsB�dk	r�t�����fdd�t|�D�����fdd�}|�S)a}Returns an iterator equivalent to map(fn, iter).

        Args:
            fn: A callable that will take as many arguments as there are
                passed iterables.
            timeout: The maximum number of seconds to wait. If None, then there
                is no limit on the wait time.
            chunksize: The size of the chunks the iterable will be broken into
                before being passed to a child process. This argument is only
                used by ProcessPoolExecutor; it is ignored by
                ThreadPoolExecutor.

        Returns:
            An iterator equivalent to: map(func, *iterables) but the calls may
            be evaluated out-of-order.

        Raises:
            TimeoutError: If the entire result iterator could not be generated
                before the given timeout.
            Exception: If fn(*args) raises for any values.
        Ncsg|]}�j�f|���qSr)r�)rFrA)rxr!rr�
<listcomp>`sz Executor.map.<locals>.<listcomp>c	3s\zB����r@�dkr&�����Vq
�����t���Vq
W5�D]}|��qHXdSr)rvr]rSr|rWrX)r&)r_rLr^rr�result_iteratordsz%Executor.map.<locals>.result_iterator)rWrX�zip)r!rxr^r��	iterablesr�r)r_rxrLr!r^r�mapGs

zExecutor.mapTcCsdS)a�Clean-up the resources associated with the Executor.

        It is safe to call this method several times. Otherwise, no other
        methods can be called after this one.

        Args:
            wait: If True then shutdown will not return until all running
                futures have finished executing and the resources used by the
                executor have been reclaimed.
        Nr)r!r[rrr�shutdownsszExecutor.shutdowncCs|Srrr rrrr?�szExecutor.__enter__cCs|jdd�dS)NT)r[F)r�)r!�exc_type�exc_val�exc_tbrrrrB�szExecutor.__exit__)T)
rrrrr��__text_signature__r�r�r?rBrrrrr�+s,

r�c@seZdZdZdS)�BrokenExecutorzR
    Raised when a executor has become non-functional after a severe failure.
    Nrrrrrr��sr�)N)'�
__author__�collections�loggingrrWrrrrrrrr	r
�_FUTURE_STATESrs�	getLoggerrprorrrr�objectrr*r2r3r8rPrVrb�
namedtuplercr[rir�r~r�rrrr�<module>sh�	�	

>�1s]�h�-bytecode of module 'concurrent.futures._base'�u��b.���Oh)��N}�(hB<O�@s�dZdZddlZddlZddlmZddlZddlmZddlZ	ddl
ZddlmZddl
Z
ddlZddlmZddlZddlZddlZe��ZdaGd	d
�d
�Zdd�Zd
ZdZGdd�de�ZGdd�d�Zdd�ZGdd�de�Z Gdd�de�Z!Gdd�de�Z"Gdd�de�Z#dd�Z$dd �Z%d1d!d"�Z&d#d$�Z'd%d&�Z(d'd(�Z)da*da+d)d*�Z,d+d,�Z-Gd-d.�d.ej.�Z/Gd/d0�d0ej0�Z1e�2e�dS)2a-	Implements ProcessPoolExecutor.

The following diagram and text describe the data-flow through the system:

|======================= In-process =====================|== Out-of-process ==|

+----------+     +----------+       +--------+     +-----------+    +---------+
|          |  => | Work Ids |       |        |     | Call Q    |    | Process |
|          |     +----------+       |        |     +-----------+    |  Pool   |
|          |     | ...      |       |        |     | ...       |    +---------+
|          |     | 6        |    => |        |  => | 5, call() | => |         |
|          |     | 7        |       |        |     | ...       |    |         |
| Process  |     | ...      |       | Local  |     +-----------+    | Process |
|  Pool    |     +----------+       | Worker |                      |  #1..n  |
| Executor |                        | Thread |                      |         |
|          |     +----------- +     |        |     +-----------+    |         |
|          | <=> | Work Items | <=> |        | <=  | Result Q  | <= |         |
|          |     +------------+     |        |     +-----------+    |         |
|          |     | 6: call()  |     |        |     | ...       |    |         |
|          |     |    future  |     |        |     | 4, result |    |         |
|          |     | ...        |     |        |     | 3, except |    |         |
+----------+     +------------+     +--------+     +-----------+    +---------+

Executor.submit() called:
- creates a uniquely numbered _WorkItem and adds it to the "Work Items" dict
- adds the id of the _WorkItem to the "Work Ids" queue

Local worker thread:
- reads work ids from the "Work Ids" queue and looks up the corresponding
  WorkItem from the "Work Items" dict: if the work item has been cancelled then
  it is simply removed from the dict, otherwise it is repackaged as a
  _CallItem and put in the "Call Q". New _CallItems are put in the "Call Q"
  until "Call Q" is full. NOTE: the size of the "Call Q" is kept small because
  calls placed in the "Call Q" can no longer be cancelled with Future.cancel().
- reads _ResultItems from "Result Q", updates the future stored in the
  "Work Items" dict and deletes the dict entry

Process #1..n:
- reads _CallItems from "Call Q", executes the calls, and puts the resulting
  _ResultItems in "Result Q"
z"Brian Quinlan (brian@sweetapp.com)�N)�_base)�Full)�Queue)�partialFc@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
�
_ThreadWakeupcCstjdd�\|_|_dS)NF)�duplex)�mp�Pipe�_reader�_writer��self�r�0/usr/lib/python3.8/concurrent/futures/process.py�__init__Rsz_ThreadWakeup.__init__cCs|j��|j��dS�N)r�closer
rrrrrUs
z_ThreadWakeup.closecCs|j�d�dS)N�)r�
send_bytesrrrr�wakeupYsz_ThreadWakeup.wakeupcCs|j��r|j��qdSr)r
�poll�
recv_bytesrrrr�clear\s
z_ThreadWakeup.clearN)�__name__�
__module__�__qualname__rrrrrrrrrQsrcCs@datt���}|D]\}}|��q|D]\}}|��q*dS�NT)�_global_shutdown�list�_threads_wakeups�itemsr�join)r �_�
thread_wakeup�trrr�_python_exitas
r%��=c@seZdZdd�Zdd�ZdS)�_RemoteTracebackcCs
||_dSr��tb)r
r*rrrrzsz_RemoteTraceback.__init__cCs|jSrr)rrrr�__str__|sz_RemoteTraceback.__str__N)rrrrr+rrrrr(ysr(c@seZdZdd�Zdd�ZdS)�_ExceptionWithTracebackcCs0t�t|�||�}d�|�}||_d||_dS)N�z

"""
%s""")�	traceback�format_exception�typer!�excr*)r
r1r*rrrr�s
z _ExceptionWithTraceback.__init__cCst|j|jffSr)�_rebuild_excr1r*rrrr�
__reduce__�sz"_ExceptionWithTraceback.__reduce__N)rrrrr3rrrrr,sr,cCst|�|_|Sr)r(�	__cause__)r1r*rrrr2�s
r2c@seZdZdd�ZdS)�	_WorkItemcCs||_||_||_||_dSr)�future�fn�args�kwargs)r
r6r7r8r9rrrr�sz_WorkItem.__init__N�rrrrrrrrr5�sr5c@seZdZddd�ZdS)�_ResultItemNcCs||_||_||_dSr)�work_id�	exception�result)r
r<r=r>rrrr�sz_ResultItem.__init__)NNr:rrrrr;�sr;c@seZdZdd�ZdS)�	_CallItemcCs||_||_||_||_dSr)r<r7r8r9)r
r<r7r8r9rrrr�sz_CallItem.__init__Nr:rrrrr?�sr?cs.eZdZdZd�fdd�	Z�fdd�Z�ZS)�
_SafeQueuez=Safe Queue set exception to the future object linked to a jobrcs||_t�j||d�dS)N)�ctx)�pending_work_items�superr)r
�max_sizerArB��	__class__rrr�sz_SafeQueue.__init__cslt|t�rZt�t|�||j�}td�d�|���|_	|j
�|jd�}|dk	rh|j
�|�nt��||�dS)Nz

"""
{}"""r-)�
isinstancer?r.r/r0�
__traceback__r(�formatr!r4rB�popr<r6�
set_exceptionrC�_on_queue_feeder_error)r
�e�objr*�	work_itemrErrrL�s
z!_SafeQueue._on_queue_feeder_error)r)rrr�__doc__rrL�
__classcell__rrrErr@�sr@cgs,t|�}tt�||��}|s dS|VqdS)z, Iterates over zip()ed iterables in chunks. N)�zip�tuple�	itertools�islice)�	chunksize�	iterables�it�chunkrrr�_get_chunks�s
rZcs�fdd�|D�S)z� Processes a chunk of an iterable passed to map.

    Runs the function passed to map() on a chunk of the
    iterable passed to map.

    This function is run in a separate process.

    csg|]}�|��qSrr)�.0r8�r7rr�
<listcomp>�sz"_process_chunk.<locals>.<listcomp>r)r7rYrr\r�_process_chunk�s	r^c
Cs^z|�t|||d��Wn@tk
rX}z"t||j�}|�t||d��W5d}~XYnXdS)z.Safely send back the given result or exception)r>r=�r=N)�putr;�
BaseExceptionr,rH)�result_queuer<r>r=rMr1rrr�_sendback_result�s
�rcc
Cs�|dk	r<z||�Wn&tk
r:tjjddd�YdSX|jdd�}|dkrb|�t���dSz|j|j	|j
�}Wn>tk
r�}z t||j�}t
||j|d�W5d}~XYnXt
||j|d�~~q<dS)a�Evaluates calls from call_queue and places the results in result_queue.

    This worker is run in a separate process.

    Args:
        call_queue: A ctx.Queue of _CallItems that will be read and
            evaluated by the worker.
        result_queue: A ctx.Queue of _ResultItems that will written
            to by the worker.
        initializer: A callable initializer, or None
        initargs: A tuple of args for the initializer
    NzException in initializer:T)�exc_info��blockr_)r>)rar�LOGGER�critical�getr`�os�getpidr7r8r9r,rHrcr<)�
call_queuerb�initializer�initargs�	call_item�rrMr1rrr�_process_worker�s$
"rqcCsv|��rdSz|jdd�}Wntjk
r4YdSX||}|j��rh|jt||j|j	|j
�dd�q||=qqdS)aMFills call_queue with _WorkItems from pending_work_items.

    This function never blocks.

    Args:
        pending_work_items: A dict mapping work ids to _WorkItems e.g.
            {5: <_WorkItem...>, 6: <_WorkItem...>, ...}
        work_ids: A queue.Queue of work ids e.g. Queue([5, 6, ...]). Work ids
            are consumed and the corresponding _WorkItems from
            pending_work_items are transformed into _CallItems and put in
            call_queue.
        call_queue: A multiprocessing.Queue that will be filled with _CallItems
            derived from _WorkItems.
    NFreT)�fullri�queue�Emptyr6�set_running_or_notify_cancelr`r?r7r8r9)rB�work_idsrlr<rOrrr�_add_call_item_to_queue�s"
��rwc
sJd��fdd�}��fdd�}|j}	|j}
|	|
g}t||��dd����D�}tj�||�}
d}d}|	|
kr�z|	��}d	}Wq�tk
r�}zt�	t
|�||j�}W5d}~XYq�Xn|
|
kr�d	}d}|��|�rl|���dk	r�d
�_
d�_d�td�}|dk	�r tdd
�|��d��|_|��D]\}}|j�|�~�q(|�����D]}|���qR|�dSt|t��r�|��s�t���|�}|����s�|�dSnL|dk	�r�|�|jd�}|dk	�r�|j�r�|j�|j�n|j�|j�~~|��|��r@z&�dk	�rd�_|�s&|�WdSWntk
�r>YnXd�q2dS)a,Manages the communication between this process and the worker processes.

    This function is run in a local thread.

    Args:
        executor_reference: A weakref.ref to the ProcessPoolExecutor that owns
            this thread. Used to determine if the ProcessPoolExecutor has been
            garbage collected and that this function can exit.
        process: A list of the ctx.Process instances used as
            workers.
        pending_work_items: A dict mapping work ids to _WorkItems e.g.
            {5: <_WorkItem...>, 6: <_WorkItem...>, ...}
        work_ids_queue: A queue.Queue of work ids e.g. Queue([5, 6, ...]).
        call_queue: A ctx.Queue that will be filled with _CallItems
            derived from _WorkItems for processing by the process workers.
        result_queue: A ctx.SimpleQueue of _ResultItems generated by the
            process workers.
        thread_wakeup: A _ThreadWakeup to allow waking up the
            queue_manager_thread from the main Thread and avoid deadlocks
            caused by permanently locked queues.
    Ncstp�dkp�jSr)r�_shutdown_threadr)�executorrr�
shutting_down@s�z/_queue_management_worker.<locals>.shutting_downc	s�tdd����D��}|}d}||kr�|dkr�t||�D]6}z��d�|d7}Wq:tk
rnYqrYq:Xq:tdd����D��}q������D]}|��q�dS)Ncss|]}|��VqdSr��is_alive�r[�prrr�	<genexpr>FszD_queue_management_worker.<locals>.shutdown_worker.<locals>.<genexpr>rr&css|]}|��VqdSrr{r}rrrrRs)�sum�values�range�
put_nowaitrrr!)�n_children_alive�n_children_to_stop�n_sentinels_sent�ir~)rl�	processesrr�shutdown_workerDs
z1_queue_management_worker.<locals>.shutdown_workercSsg|]
}|j�qSr)�sentinelr}rrrr]isz,_queue_management_worker.<locals>.<listcomp>TFzKA child process terminated abruptly, the process pool is not usable anymorez^A process in the process pool was terminated abruptly while the future was running or pending.z
'''
r-z''') r
rwr�r�
connection�wait�recvrar.r/r0rHr�_brokenrx�BrokenProcessPoolr(r!r4r r6rK�	terminaterG�int�AssertionErrorrJr<r=�
set_resultr>r)�executor_referencer�rB�work_ids_queuerlrbr#rzr��
result_reader�
wakeup_reader�readers�worker_sentinels�ready�cause�	is_broken�result_itemrM�bper<rOr~r)rlryr�r�_queue_management_worker"s��	(
�




r�c	Csjtrtrtt��dazt�d�}Wnttfk
r<YdSX|dkrJdS|dkrVdSd|att��dS)NT�SC_SEM_NSEMS_MAX����z@system provides too few semaphores (%d available, 256 necessary))�_system_limits_checked�_system_limited�NotImplementedErrorrj�sysconf�AttributeError�
ValueError)�	nsems_maxrrr�_check_system_limits�s �r�ccs&|D]}|��|r|��VqqdS)z�
    Specialized implementation of itertools.chain.from_iterable.
    Each item in *iterable* should be a list.  This function is
    careful not to keep references to yielded objects.
    N)�reverserJ)�iterable�elementrrr�_chain_from_iterable_of_lists�sr�c@seZdZdZdS)r�zy
    Raised when a process in a ProcessPoolExecutor terminated abruptly
    while a future was in the running state.
    N)rrrrPrrrrr��sr�csteZdZddd�Zdd�Zdd�Zd	d
�Zejjj	e_	ejjj
e_
ddd��fd
d�
Zddd�Zejjj
e_
�Z
S)�ProcessPoolExecutorNrcCst�|dkr6t��pd|_tjdkrntt|j�|_n8|dkrHtd��n tjdkrh|tkrhtdt����||_|dkr~t	�
�}||_|dk	r�t|�s�t
d��||_||_d|_i|_d|_t��|_d|_d|_i|_|jt}t||j|jd	�|_d
|j_|��|_t� �|_!t"�|_#dS)aSInitializes a new ProcessPoolExecutor instance.

        Args:
            max_workers: The maximum number of processes that can be used to
                execute the given calls. If None or not given then as many
                worker processes will be created as the machine has processors.
            mp_context: A multiprocessing context to launch the workers. This
                object should provide SimpleQueue, Queue and Process.
            initializer: A callable used to initialize worker processes.
            initargs: A tuple of arguments to pass to the initializer.
        Nr&�win32rz"max_workers must be greater than 0zmax_workers must be <= zinitializer must be a callableF)rDrArBT)$r�rj�	cpu_count�_max_workers�sys�platform�min�_MAX_WINDOWS_WORKERSr�r�get_context�_mp_context�callable�	TypeError�_initializer�	_initargs�_queue_management_thread�
_processesrx�	threading�Lock�_shutdown_lockr��_queue_count�_pending_work_items�EXTRA_QUEUED_CALLSr@�_call_queue�
_ignore_epipe�SimpleQueue�
_result_queuersr�	_work_idsr�_queue_management_thread_wakeup)r
�max_workers�
mp_contextrmrn�
queue_sizerrrr�sP

�

��

�

zProcessPoolExecutor.__init__c	Csv|jdkrr|jfdd�}|��tjtt�||�|j|j	|j
|j|j|jfdd�|_d|j_
|j��|jt|j<dS)NcSstj�d�|��dS)Nz?Executor collected: triggering callback for QueueManager wakeup)r�util�debugr)r"r#rrr�
weakref_cbBszFProcessPoolExecutor._start_queue_management_thread.<locals>.weakref_cbZQueueManagerThread)�targetr8�nameT)r�r��_adjust_process_countr��Threadr��weakref�refr�r�r�r�r��daemon�startr)r
r�rrr�_start_queue_management_thread=s(
�

��

�z2ProcessPoolExecutor._start_queue_management_threadcCsPtt|j�|j�D]8}|jjt|j|j|j	|j
fd�}|��||j|j<qdS)N)r�r8)
r��lenr�r�r��Processrqr�r�r�r�r��pid)r
r"r~rrrr�Xs��z)ProcessPoolExecutor._adjust_process_countc
Os
t|�dkr|^}}}nV|s&td��nHd|krZ|�d�}|^}}ddl}|jdtdd�ntdt|�d��|j��|jr�t|j��|j	r�t
d	��tr�t
d
��t�
�}t||||�}||j|j<|j�|j�|jd7_|j��|��|W5QR�SQRXdS)N�zEdescriptor 'submit' of 'ProcessPoolExecutor' object needs an argumentr7rz.Passing 'fn' as keyword argument is deprecated)�
stacklevelz6submit expected at least 1 positional argument, got %dr&z*cannot schedule new futures after shutdownz6cannot schedule new futures after interpreter shutdown)r�r�rJ�warnings�warn�DeprecationWarningr�r�r�rx�RuntimeErrorrr�Futurer5r�r�r�r`r�rr�)r8r9r
r7r��f�wrrr�submitcs<

�
�

zProcessPoolExecutor.submitr&)�timeoutrVcs:|dkrtd��t�jtt|�t|d|i�|d�}t|�S)ajReturns an iterator equivalent to map(fn, iter).

        Args:
            fn: A callable that will take as many arguments as there are
                passed iterables.
            timeout: The maximum number of seconds to wait. If None, then there
                is no limit on the wait time.
            chunksize: If greater than one, the iterables will be chopped into
                chunks of size chunksize and submitted to the process pool.
                If set to one, the items in the list will be sent one at a time.

        Returns:
            An iterator equivalent to: map(func, *iterables) but the calls may
            be evaluated out-of-order.

        Raises:
            TimeoutError: If the entire result iterator could not be generated
                before the given timeout.
            Exception: If fn(*args) raises for any values.
        r&zchunksize must be >= 1.rV)r�)r�rC�maprr^rZr�)r
r7r�rVrW�resultsrErrr��s�zProcessPoolExecutor.mapTc	Cs�|j�d|_W5QRX|jr6|j��|r6|j��d|_|jdk	rd|j��|r^|j��d|_d|_	d|_
|jr�|j��d|_dSr)r�rxr�r�rr!r�r�join_threadr�r�)r
r�rrr�shutdown�s"





zProcessPoolExecutor.shutdown)NNNr)T)rrrrr�r�r�r�Executor�__text_signature__rPr�r�rQrrrErr��s�
K$
r�)NN)3rP�
__author__�atexitrj�concurrent.futuresrrsr�multiprocessingr�multiprocessing.connection�multiprocessing.queuesrr�r��	functoolsrrTr�r.�WeakKeyDictionaryrrrr%r�r��	Exceptionr(r,r2�objectr5r;r?r@rZr^rcrqrwr�r�r�r�r��BrokenExecutorr�r�r��registerrrrr�<module>sV*
		

)&!P�h�/bytecode of module 'concurrent.futures.process'�u��b.���h)��N}�(hB��@s�dZdZddlZddlmZddlZddlZddlZddlZddl	Z	e�
�Zdadd�Z
e�e
�Gdd	�d	e�Zd
d�ZGdd
�d
ej�ZGdd�dej�ZdS)zImplements ThreadPoolExecutor.z"Brian Quinlan (brian@sweetapp.com)�N)�_baseFcCsBdatt���}|D]\}}|�d�q|D]\}}|��q,dS�NT)�	_shutdown�list�_threads_queues�items�put�join)r�t�q�r�//usr/lib/python3.8/concurrent/futures/thread.py�_python_exit!src@seZdZdd�Zdd�ZdS)�	_WorkItemcCs||_||_||_||_dS�N)�future�fn�args�kwargs)�selfrrrrrrr
�__init__.sz_WorkItem.__init__c
Csf|j��sdSz|j|j|j�}Wn2tk
rT}z|j�|�d}W5d}~XYnX|j�|�dSr)r�set_running_or_notify_cancelrrr�
BaseException�
set_exception�
set_result)r�result�excrrr
�run4s
z
_WorkItem.runN)�__name__�
__module__�__qualname__rrrrrr
r-srcCs�|dk	rRz||�Wn<tk
rPtjjddd�|�}|dk	rJ|��YdSXzx|jdd�}|dk	r�|��~|�}|dk	r�|j��~qT|�}t	s�|dks�|j	r�|dk	r�d|_	|�
d�WdS~qTWn$tk
r�tjjddd�YnXdS)NzException in initializer:T)�exc_info)�blockzException in worker)rr�LOGGER�critical�_initializer_failed�getr�_idle_semaphore�releaserr)�executor_reference�
work_queue�initializer�initargs�executor�	work_itemrrr
�_workerBs8

r/c@seZdZdZdS)�BrokenThreadPoolzR
    Raised when a worker thread in a ThreadPoolExecutor failed initializing.
    N)rrr �__doc__rrrr
r0msr0c@sfeZdZe��jZddd�Zdd�Ze	j
jje_e	j
jje_dd	�Z
d
d�Zdd
d�Ze	j
jje_dS)�ThreadPoolExecutorN�rcCs�|dkrtdt��pdd�}|dkr.td��|dk	rFt|�sFtd��||_t��|_	t
�d�|_t
�|_d|_d|_t
��|_|p�d	|��|_||_||_dS)
a�Initializes a new ThreadPoolExecutor instance.

        Args:
            max_workers: The maximum number of threads that can be used to
                execute the given calls.
            thread_name_prefix: An optional name prefix to give our threads.
            initializer: A callable used to initialize worker threads.
            initargs: A tuple of arguments to pass to the initializer.
        N� ��rz"max_workers must be greater than 0zinitializer must be a callableFzThreadPoolExecutor-%d)�min�os�	cpu_count�
ValueError�callable�	TypeError�_max_workers�queue�SimpleQueue�_work_queue�	threading�	Semaphorer'�set�_threads�_brokenr�Lock�_shutdown_lock�_counter�_thread_name_prefix�_initializer�	_initargs)r�max_workers�thread_name_prefixr+r,rrr
rxs$


�zThreadPoolExecutor.__init__c
Os�t|�dkr|^}}}nV|s&td��nHd|krZ|�d�}|^}}ddl}|jdtdd�ntdt|�d��|j�f|jr�t|j��|j	r�t
d	��t	r�t
d
��t��}t
||||�}|j�|�|��|W5QR�SQRXdS)N�zDdescriptor 'submit' of 'ThreadPoolExecutor' object needs an argumentrrz.Passing 'fn' as keyword argument is deprecated)�
stacklevelz6submit expected at least 1 positional argument, got %dr5z*cannot schedule new futures after shutdownz6cannot schedule new futures after interpreter shutdown)�lenr<�pop�warnings�warn�DeprecationWarningrGrEr0r�RuntimeErrorr�Futurerr@r�_adjust_thread_count)rrrrrR�f�wrrr
�submit�s6

�
�
zThreadPoolExecutor.submitcCs�|jjdd�rdS|jfdd�}t|j�}||jkr�d|jp>||f}tj|t	t
�||�|j|j|j
fd�}d|_|��|j�|�|jt|<dS)Nr)�timeoutcSs|�d�dSr)r)�_rrrr
�
weakref_cb�sz;ThreadPoolExecutor._adjust_thread_count.<locals>.weakref_cbz%s_%d)�name�targetrT)r'�acquirer@rPrDr=rIrA�Threadr/�weakref�refrJrK�daemon�start�addr)rr]�num_threads�thread_namer
rrr
rW�s&


�
��z'ThreadPoolExecutor._adjust_thread_countc	Csb|j�Rd|_z|j��}Wntjk
r6YqTYnX|dk	r|j�t|j��qW5QRXdS)NzBA thread initializer failed, the thread pool is not usable anymore)	rGrEr@�
get_nowaitr>�Emptyrrr0)rr.rrr
r%�s
z&ThreadPoolExecutor._initializer_failedTc	Cs@|j�d|_|j�d�W5QRX|r<|jD]}|��q.dSr)rGrr@rrDr	)r�waitr
rrr
�shutdown�s
zThreadPoolExecutor.shutdown)Nr3Nr)T)rrr �	itertools�count�__next__rHrrZr�Executor�__text_signature__r1rWr%rlrrrr
r2ss
�
& 
r2)r1�
__author__�atexit�concurrent.futuresrrmr>rArbr8�WeakKeyDictionaryrrr�register�objectrr/�BrokenExecutorr0rpr2rrrr
�<module>s 	
+�h�.bytecode of module 'concurrent.futures.thread'�u��b.���h)��N}�(hBL�@shdZddlTddlZddlZdd�Zdd�ZzeWn e	k
rTdd	lmZYnXd
d�Z
de
_dS)
z�curses

The main package for curses support for Python.  Normally used by importing
the package, and perhaps a particular module inside it.

   import curses
   from curses import textpad
   curses.initscr()
   ...

�)�*NcCspddl}ddl}ttj�dd�tj��d�|�	�}|j
��D],\}}|dd�dks^|dkr>t|||�q>|S)NrZTERM�unknown)�term�fd�ZACS_)�LINESZCOLS)
�_curses�curses�	setupterm�_os�environ�get�_sys�
__stdout__�fileno�initscr�__dict__�items�setattr)rr	�stdscr�key�value�r�%/usr/lib/python3.8/curses/__init__.pyrs�rcCs@ddl}ddl}|��}t|d�r*|j|_t|d�r<|j|_|S)Nr�COLORS�COLOR_PAIRS)rr	�start_color�hasattrrr)rr	�retvalrrrr*s

r�)�has_keyc	Os�|r|^}}n<d|kr:|�d�}ddl}|jdtdd�ntdt|���zHt�}t�t
�|�d	�z
t�WnYnX||f|�|�W�Sdt�kr�|�d�t�t	�t
�XdS)
aWrapper function that initializes curses and calls another function,
    restoring normal keyboard/screen behavior on error.
    The callable object 'func' is then passed the main window 'stdscr'
    as its first argument, followed by any other arguments passed to
    wrapper().
    �funcrNz0Passing 'func' as keyword argument is deprecated�)�
stacklevelz7wrapper expected at least 1 positional argument, got %drr)�pop�warnings�warn�DeprecationWarning�	TypeError�len�locals�keypad�echo�nocbreak�endwinr�noecho�cbreakr)�args�kwdsr!r%rrrr�wrapper?s6

��



r3z(func, /, *args, **kwds))�__doc__r�osr�sysrrrr �	NameErrorr3�__text_signature__rrrr�<module>s
2�h�bytecode of module 'curses'�u��b.���h)��N}�(hB��*@sddlZejdejdejdejdejdejdejdejd	ej	d
ej
dejdejd
ej
dejdejdejdejdejdejdejdejdejdejdejdejdejdejdejdejdejdejd ej d!ej!d"ej"d#ej#d$ej$d%ej%d&ej&d'ej'd(ej(d)ej)d*ej*d+ej+d,ej,d-ej-d.ej.d/ej/d0ej0d1ej1d2ej2d3ej3d4ej4d5ej5d6ej6d7ej7d8ej8d9ej9d:ej:d;ej;d<ej<d=ej=d>ej>d?ej?d@ej@dAejAdBejBdCejCdDejDdEejEdFejFdGejGdHejHdIejIdJejJdKejKdLejLdMejMdNejNdOejOdPejPdQejQdRejRdSejSdTejTdUejUdVejVdWejWdXejXdYejYdZejZd[ej[d\ej\d]ej]d^ej^d_ej_d`ej`daejadbejbdcejcddejddeejedfejfdgejgdhejhdiejidjejjdkejkdlejldmejmdnejndoejodpejpdqejqdrejrdsejsdtejtduejudvejvdwejwdxejxdyejydzejzd{ej{d|ej|d}ej}d~ej~dejd�ej�d�ej�d�ej�d�ej�d�ej�d�ej�d�ej�d�ej�d�ej�d�ej�d�ej�d�ej�d�ej�d�ej�d�ej�d�ej�d�ej�d�ej�d�ej�d�ej�d�ej�d�ej�d�i�Z�d�d��Z�e�d�k�rzVgZ�e���e����D]<Z�e��e��Z�e�e��Z�e�e�k�r�e���d�e��e��e�e�f��q�W5e���e�D]Z�e�e���qXdS)��NZka1Zka3Zkb2ZkbsZkbegZkcbtZkc1Zkc3ZkcanZktbcZkclrZkcloZkcmdZkcpyZkcrtZkctabZkdch1Zkdl1Zkcud1ZkrmirZkendZkentZkelZkedZkextZkf0Zkf1Zkf10Zkf11Zkf12Zkf13Zkf14Zkf15Zkf16Zkf17Zkf18Zkf19Zkf2Zkf20Zkf21Zkf22Zkf23Zkf24Zkf25Zkf26Zkf27Zkf28Zkf29Zkf3Zkf30Zkf31Zkf32Zkf33Zkf34Zkf35Zkf36Zkf37Zkf38Zkf39Zkf4Zkf40Zkf41Zkf42Zkf43Zkf44Zkf45Zkf46Zkf47Zkf48Zkf49Zkf5Zkf50Zkf51Zkf52Zkf53Zkf54Zkf55Zkf56Zkf57Zkf58Zkf59Zkf6Zkf60Zkf61Zkf62Zkf63Zkf7Zkf8Zkf9ZkfndZkhlpZkhomeZkich1Zkil1Zkcub1ZkllZkmrkZkmsgZkmovZknxtZknpZkopnZkoptZkppZkprvZkprtZkrdoZkrefZkrfrZkrplZkrstZkresZkcuf1ZksavZkBEGZkCANZkCMDZkCPYZkCRTZkDCZkDLZksltZkENDZkEOLZkEXT�kindZkFNDZkHLPZkHOMZkICZkLFTZkMSGZkMOVZkNXTZkOPTZkPRVZkPRTZkriZkRDOZkRPLZkRITZkRESZkSAVZkSPDZkhtsZkUNDZkspdZkundZkcuu1cCs>t|t�rt|�}t�|�}|dkr(dSt�|�r6dSdSdS)NFT)�
isinstance�str�ord�_capability_names�get�_curses�tigetstr)�ch�capability_name�r�$/usr/lib/python3.8/curses/has_key.py�has_key�s


r�__main__z)Mismatch for key %s, system=%i, Python=%i)�r�KEY_A1�KEY_A3�KEY_B2�
KEY_BACKSPACE�KEY_BEG�KEY_BTAB�KEY_C1�KEY_C3�
KEY_CANCEL�	KEY_CATAB�	KEY_CLEAR�	KEY_CLOSE�KEY_COMMAND�KEY_COPY�
KEY_CREATE�KEY_CTAB�KEY_DC�KEY_DL�KEY_DOWN�KEY_EIC�KEY_END�	KEY_ENTER�KEY_EOL�KEY_EOS�KEY_EXIT�KEY_F0�KEY_F1�KEY_F10�KEY_F11�KEY_F12�KEY_F13�KEY_F14�KEY_F15�KEY_F16�KEY_F17�KEY_F18�KEY_F19�KEY_F2�KEY_F20�KEY_F21�KEY_F22�KEY_F23�KEY_F24�KEY_F25�KEY_F26�KEY_F27�KEY_F28�KEY_F29�KEY_F3�KEY_F30�KEY_F31�KEY_F32�KEY_F33�KEY_F34�KEY_F35�KEY_F36�KEY_F37�KEY_F38�KEY_F39�KEY_F4�KEY_F40�KEY_F41�KEY_F42�KEY_F43�KEY_F44�KEY_F45�KEY_F46�KEY_F47�KEY_F48�KEY_F49�KEY_F5�KEY_F50�KEY_F51�KEY_F52�KEY_F53�KEY_F54�KEY_F55�KEY_F56�KEY_F57�KEY_F58�KEY_F59�KEY_F6�KEY_F60�KEY_F61�KEY_F62�KEY_F63�KEY_F7�KEY_F8�KEY_F9�KEY_FIND�KEY_HELP�KEY_HOME�KEY_IC�KEY_IL�KEY_LEFT�KEY_LL�KEY_MARK�KEY_MESSAGE�KEY_MOVE�KEY_NEXT�	KEY_NPAGE�KEY_OPEN�KEY_OPTIONS�	KEY_PPAGE�KEY_PREVIOUS�	KEY_PRINT�KEY_REDO�
KEY_REFERENCE�KEY_REFRESH�KEY_REPLACE�KEY_RESTART�
KEY_RESUME�	KEY_RIGHT�KEY_SAVE�KEY_SBEG�KEY_SCANCEL�KEY_SCOMMAND�	KEY_SCOPY�KEY_SCREATE�KEY_SDC�KEY_SDL�
KEY_SELECT�KEY_SEND�KEY_SEOL�	KEY_SEXIT�KEY_SF�	KEY_SFIND�	KEY_SHELP�	KEY_SHOME�KEY_SIC�	KEY_SLEFT�KEY_SMESSAGE�	KEY_SMOVE�	KEY_SNEXT�KEY_SOPTIONS�
KEY_SPREVIOUS�
KEY_SPRINT�KEY_SR�	KEY_SREDO�KEY_SREPLACE�
KEY_SRIGHT�
KEY_SRSUME�	KEY_SSAVE�KEY_SSUSPEND�KEY_STAB�	KEY_SUNDO�KEY_SUSPEND�KEY_UNDO�KEY_UPrr�__name__�endwin�L�i�print�initscr�keys�key�system�python�append�keynamerrrr
�<module>sx��


��h�#bytecode of module 'curses.has_key'�u��b.���h)��N}�(hB��@sNdZddddddddd	d
ddd
ddddgZdd�Zdd
�Zdd
�Zdd�ZdS)z?A package for parsing, handling, and generating email messages.�
base64mime�charset�encoders�errors�
feedparser�	generator�header�	iterators�message�message_from_file�message_from_binary_file�message_from_string�message_from_bytes�mime�parser�
quoprimime�utilscOsddlm}|||��|�S)zvParse a string into a Message object model.

    Optional _class and strict are passed to the Parser constructor.
    ���Parser)�email.parserr�parsestr)�s�args�kwsr�r�$/usr/lib/python3.8/email/__init__.pyr scOsddlm}|||��|�S)z|Parse a bytes string into a Message object model.

    Optional _class and strict are passed to the Parser constructor.
    r��BytesParser)rr�
parsebytes)rrrrrrrr
(scOsddlm}|||��|�S)z�Read a file and parse its contents into a Message object model.

    Optional _class and strict are passed to the Parser constructor.
    rr)rr�parse)�fprrrrrrr
0scOsddlm}|||��|�S)z�Read a binary file and parse its contents into a Message object model.

    Optional _class and strict are passed to the Parser constructor.
    rr)rrr)r rrrrrrr8sN)�__doc__�__all__rr
r
rrrrr�<module>s,��h�bytecode of module 'email'�u��b.��jh)��N}�(hB&�@s�dZddlZddlZddlZddlZddlmZmZddlm	Z	ddddd	d
ddgZ
e�e�d
�j
dd��Zdd�ZGdd�de�Ze�Zdeed�<dd�Zdd	�Zdd�Zdd�Zdd
�Zeed�Zdd�Zeed�Zeed�Zddd�ZdS) z� Routines for manipulating RFC2047 encoded words.

This is currently a package-private API, but will be considered for promotion
to a public API if there is demand.

�N)�
ascii_letters�digits)�errors�decode_q�encode_q�decode_b�encode_b�len_q�len_b�decode�encodes=([a-fA-F0-9]{2})cCst�|�d����S)N�)�bytes�fromhex�groupr)�m�r�*/usr/lib/python3.8/email/_encoded_words.py�<lambda>A�rcCs|�dd�}t|�gfS)N�_� )�replace�_q_byte_subber)�encodedrrrrCsc@s,eZdZde�d�e�d�Zdd�ZdS)�	_QByteMaps-!*+/�asciicCs.||jkrt|�||<nd�|�||<||S)Nz={:02X})�safe�chr�format)�self�keyrrr�__missing__Ms
z_QByteMap.__missing__N)�__name__�
__module__�__qualname__rrrrr"rrrrrIsr�_� cCsd�dd�|D��S)N�css|]}t|VqdS�N)�_q_byte_map��.0�xrrr�	<genexpr>Zszencode_q.<locals>.<genexpr>)�join��bstringrrrrYscCstdd�|D��S)Ncss|]}tt|�VqdSr))�lenr*r+rrrr.]szlen_q.<locals>.<genexpr>)�sumr0rrrr	\scCs�t|�d}|r ddd|�nd}z&tj||dd�|rDt��gngfWStjk
�r�ztj|dd�t��gfWYStjk
r�z,tj|ddd�t��t��gfWYYStjk
r�|t��gfYYYSXYnXYnXdS)N�s===rT)�validateFs==)	r2�base64�	b64decoder�InvalidBase64PaddingDefect�binascii�Error�InvalidBase64CharactersDefect�InvalidBase64LengthDefect)r�pad_err�missing_paddingrrrrds(��
��cCst�|��d�S)Nr)r6�	b64encoderr0rrrr�scCs&tt|�d�\}}|d|r dndS)N�r4r)�divmodr2)r1�groups_of_3�leftoverrrrr
�s)�q�bc	
Cs�|�d�\}}}}}|�d�\}}}|��}|�dd�}t||�\}}z|�|�}Wnvtk
r�|�t�	d�
|���|�|d�}YnBtk
r�|�dd�}|��dkr�|�t�d�
|���YnX||||fS)a�Decode encoded word and return (string, charset, lang, defects) tuple.

    An RFC 2047/2243 encoded word has the form:

        =?charset*lang?cte?encoded_string?=

    where '*lang' may be omitted but the other parts may not be.

    This function expects exactly such a string (that is, it does not check the
    syntax and may raise errors if the string is not well formed), and returns
    the encoded_string decoded first from its Content Transfer Encoding and
    then from the resulting bytes into unicode using the specified charset.  If
    the cte-decoded string does not successfully decode using the specified
    character set, a defect is added to the defects list and the unknown octets
    are replaced by the unicode 'unknown' character \uFDFF.

    The specified charset and language are returned.  The default for language,
    which is rarely if ever encountered, is the empty string.

    �?�*r�surrogateescapez:Encoded word contains bytes not decodable using {} charset�unknown-8bitz<Unknown charset {} in encoded word; decoded as unknown bytes)
�split�	partition�lowerr�
_cte_decodersr�UnicodeError�appendr�UndecodableBytesDefectr�LookupError�CharsetError)	�ewr&�charset�cte�
cte_string�langr1�defects�stringrrrr�s&���utf-8r(cCs||dkr|�dd�}n
|�|�}|dkrTtd|�}td|�}||dkrPdnd}t||�}|rld|}d	�||||�S)
aEncode string using the CTE encoding that produces the shorter result.

    Produces an RFC 2047/2243 encoded word of the form:

        =?charset*lang?cte?encoded_string?=

    where '*lang' is omitted unless the 'lang' parameter is given a value.
    Optional argument charset (defaults to utf-8) specifies the charset to use
    to encode the string to binary before CTE encoding it.  Optional argument
    'encoding' is the cte specifier for the encoding that should be used ('q'
    or 'b'); if it is None (the default) the encoding which produces the
    shortest encoded sequence is used, except that 'q' is preferred if it is up
    to five characters longer.  Optional argument 'lang' (default '') gives the
    RFC 2243 language string to specify in the encoded word.

    rIrrHNrDrE�rGz=?{}{}?{}?{}?=)r�_cte_encode_length�
_cte_encodersr)rYrT�encodingrWr1�qlen�blenrrrrr�s
)rZNr()�__doc__�rer6r9�	functoolsrYrr�emailr�__all__�partial�compile�subrr�dictrr*�ordrr	rrr
rMrr]r\rrrrr�<module>sL)��&�+���h�)bytecode of module 'email._encoded_words'�u��b.��h)��N}�(hB-8�	@s�dZddlZddlZddlZddlmZddlmZddlm	Z
ddlmZddlmZe
d�Zee
d	�BZe
d
�ZeeBZee
d�Zee
d�Zee
d
�Be
d�ZeeBZee
d�BZeeBZee
d�Zdd�Ze�dejejB�ZGdd�de�ZGdd�de�Z Gdd�de�Z!Gdd�de�Z"Gdd�de�Z#Gdd�de �Z$Gdd �d e�Z%Gd!d"�d"e�Z&Gd#d$�d$e�Z'Gd%d&�d&e�Z(Gd'd(�d(e(�Z)Gd)d*�d*e �Z*Gd+d,�d,e�Z+Gd-d.�d.e�Z,Gd/d0�d0e�Z-Gd1d2�d2e�Z.Gd3d4�d4e�Z/Gd5d6�d6e�Z0Gd7d8�d8e�Z1Gd9d:�d:e�Z2Gd;d<�d<e�Z3Gd=d>�d>e�Z4Gd?d@�d@e�Z5GdAdB�dBe�Z6GdCdD�dDe�Z7GdEdF�dFe�Z8GdGdH�dHe�Z9GdIdJ�dJe�Z:GdKdL�dLe"�Z;GdMdN�dNe�Z<GdOdP�dPe�Z=GdQdR�dRe�Z>GdSdT�dTe�Z?GdUdV�dVe?�Z@GdWdX�dXe�ZAGdYdZ�dZe�ZBGd[d\�d\e�ZCGd]d^�d^e�ZDGd_d`�d`e�ZEGdadb�dbeE�ZFGdcdd�ddeE�ZGGdedf�dfe�ZHGdgdh�dhe�ZIGdidj�dje�ZJGdkdl�dleJ�ZKGdmdn�dneK�ZLGdodp�dpe�ZMGdqdr�dreN�ZOGdsdt�dteO�ZPGdudv�dveO�ZQGdwdx�dxeP�ZRGdydz�dzejS�ZTeQdd{�ZUeQd|d}�ZVeQd~d�ZWe�d��Xd��Ye���jZZ[e�d��Xe�\d��Ye����j]Z^e�d��j_Z`e�d��Xe�\d��Ye����j]Zae�d��Xe�\d��Ye����j]Zbe�d��Xe�\d��Ye����j]Zcd�d��Zdd�d��Zed�d��Zfd�d��Zgd�d��Zhd�d��Zid�d��Zjd�d��Zkd�d��Zld�d��Zmd�d��Znd�d��Zod�d��Zpd�d��Zqd�d��Zrd�d��Zsd�d��Ztd�d��Zud�d��Zvd�d��Zwd�d��Zxd�d��Zyd�d��Zzd�d��Z{d�d��Z|d�d��Z}d�d��Z~d�d��Zd�d��Z�d�d��Z�d�d��Z�d�dÄZ�d�dńZ�d�dDŽZ�d�dɄZ�d�d˄Z�d�d̈́Z�d�dτZ�d�dфZ�d�dӄZ�d�dՄZ�d�dׄZ�d�dلZ�d�dۄZ�d�d݄Z�d�d߄Z�d�d�Z�d�d�Z�d�d�Z�d�d�Z�d�d�Z�d�d�Z�d�d�Z�d�d�Z�d�d�Z�d�d�Z�d�d��Z�d�d��Z�dS)�alHeader value parser implementing various email-related RFC parsing rules.

The parsing methods defined in this module implement various email related
parsing rules.  Principal among them is RFC 5322, which is the followon
to RFC 2822 and primarily a clarification of the former.  It also implements
RFC 2047 encoded word decoding.

RFC 5322 goes to considerable trouble to maintain backward compatibility with
RFC 822 in the parse phase, while cleaning up the structure on the generation
phase.  This parser supports correct RFC 5322 generation by tagging white space
as folding white space only when folding is allowed in the non-obsolete rule
sets.  Actually, the parser is even more generous when accepting input than RFC
5322 mandates, following the spirit of Postel's Law, which RFC 5322 encourages.
Where possible deviations from the standard are annotated on the 'defects'
attribute of tokens that deviate.

The general structure of the parser follows RFC 5322, and uses its terminology
where there is a direct correspondence.  Where the implementation requires a
somewhat different structure than that used by the formal grammar, new terms
that mimic the closest existing terms are used.  Thus, it really helps to have
a copy of RFC 5322 handy when studying this code.

Input to the parser is a string that has already been unfolded according to
RFC 5322 rules.  According to the RFC this unfolding is the very first step, and
this parser leaves the unfolding step to a higher level message parser, which
will have already detected the line breaks that need unfolding while
determining the beginning and end of each header.

The output of the parser is a TokenList object, which is a list subclass.  A
TokenList is a recursive data structure.  The terminal nodes of the structure
are Terminal objects, which are subclasses of str.  These do not correspond
directly to terminal objects in the formal grammar, but are instead more
practical higher level combinations of true terminals.

All TokenList and Terminal objects have a 'value' attribute, which produces the
semantically meaningful value of that part of the parse subtree.  The value of
all whitespace tokens (no matter how many sub-tokens they may contain) is a
single space, as per the RFC rules.  This includes 'CFWS', which is herein
included in the general class of whitespace tokens.  There is one exception to
the rule that whitespace tokens are collapsed into single spaces in values: in
the value of a 'bare-quoted-string' (a quoted-string with no leading or
trailing whitespace), any whitespace that appeared between the quotation marks
is preserved in the returned value.  Note that in all Terminal strings quoted
pairs are turned into their unquoted values.

All TokenList and Terminal objects also have a string value, which attempts to
be a "canonical" representation of the RFC-compliant form of the substring that
produced the parsed subtree, including minimal use of quoted pair quoting.
Whitespace runs are not collapsed.

Comment tokens also have a 'content' attribute providing the string found
between the parens (including any nested comments) with whitespace preserved.

All TokenList and Terminal objects have a 'defects' attribute which is a
possibly empty list all of the defects found while creating the token.  Defects
may appear on any token in the tree, and a composite list of all defects in the
subtree is available through the 'all_defects' attribute of any node.  (For
Terminal notes x.defects == x.all_defects.)

Each object in a parse tree is called a 'token', and each has a 'token_type'
attribute that gives the name from the RFC 5322 grammar that it represents.
Not all RFC 5322 nodes are produced, and there is one non-RFC 5322 node that
may be produced: 'ptext'.  A 'ptext' is a string of printable ascii characters.
It is returned in place of lists of (ctext/quoted-pair) and
(qtext/quoted-pair).

XXX: provide complete list of token types.
�N)�	hexdigits)�
itemgetter)�_encoded_words)�errors)�utilsz 	�(z
()<>@,:;.\"[]�.z."(z/?=z*'%�%cCs dt|��dd��dd�dS)N�"�\�\\z\")�str�replace��value�r�0/usr/lib/python3.8/email/_header_value_parser.py�quote_string`srz�
   =\?            # literal =?
   [^?]*          # charset
   \?             # literal ?
   [qQbB]         # literal 'q' or 'b', case insensitive
   \?             # literal ?
  .*?             # encoded word
  \?=             # literal ?=
cs�eZdZdZdZdZ�fdd�Zdd�Z�fdd�Ze	d	d
��Z
e	dd��Zd
d�Ze	dd��Z
e	dd��Zdd�Zddd�Zddd�Zddd�Z�ZS)�	TokenListNTcst�j||�g|_dS�N)�super�__init__�defects)�self�args�kw��	__class__rrryszTokenList.__init__cCsd�dd�|D��S)N�css|]}t|�VqdSr�r
��.0�xrrr�	<genexpr>~sz$TokenList.__str__.<locals>.<genexpr>��join�rrrr�__str__}szTokenList.__str__csd�|jjt����S�Nz{}({})��formatr�__name__r�__repr__r&rrrr,�s
�zTokenList.__repr__cCsd�dd�|D��S)Nrcss|]}|jr|jVqdSrrr rrrr#�sz"TokenList.value.<locals>.<genexpr>r$r&rrrr�szTokenList.valuecCstdd�|D�|j�S)Ncss|]}|jVqdSr)�all_defectsr rrrr#�sz(TokenList.all_defects.<locals>.<genexpr>)�sumrr&rrrr-�szTokenList.all_defectscCs|d��S�Nr)�startswith_fwsr&rrrr0�szTokenList.startswith_fwscCstdd�|D��S)zATrue if all top level tokens of this part may be RFC2047 encoded.css|]}|jVqdSr)�
as_ew_allowed)r!�partrrrr#�sz*TokenList.as_ew_allowed.<locals>.<genexpr>)�allr&rrrr1�szTokenList.as_ew_allowedcCsg}|D]}|�|j�q|Sr)�extend�comments)rr5�tokenrrrr5�szTokenList.commentscCst||d�S)N��policy)�_refold_parse_tree�rr8rrr�fold�szTokenList.foldrcCst|j|d��dS)N��indent)�print�ppstr�rr=rrr�pprint�szTokenList.pprintcCsd�|j|d��S)N�
r<)r%�_ppr@rrrr?�szTokenList.ppstrccszd�||jj|j�V|D]4}t|d�s:|d�|�Vq|�|d�EdHq|jrdd�|j�}nd}d�||�VdS)Nz{}{}/{}(rCz*    !! invalid element in token list: {!r}z    z Defects: {}rz{}){})r*rr+�
token_type�hasattrrCr)rr=r6�extrarrrrC�s�
�
z
TokenList._pp)r)r)r)r+�
__module__�__qualname__rD�syntactic_break�ew_combine_allowedrr'r,�propertyrr-r0r1r5r;rAr?rC�
__classcell__rrrrrss&





rc@s$eZdZedd��Zedd��ZdS)�WhiteSpaceTokenListcCsdS�N� rr&rrrr�szWhiteSpaceTokenList.valuecCsdd�|D�S)NcSsg|]}|jdkr|j�qS)�comment)rD�contentr rrr�
<listcomp>�s
z0WhiteSpaceTokenList.comments.<locals>.<listcomp>rr&rrrr5�szWhiteSpaceTokenList.commentsN)r+rGrHrKrr5rrrrrM�s
rMc@seZdZdZdS)�UnstructuredTokenList�unstructuredN�r+rGrHrDrrrrrS�srSc@seZdZdZdS)�Phrase�phraseNrUrrrrrV�srVc@seZdZdZdS)�Word�wordNrUrrrrrX�srXc@seZdZdZdS)�CFWSList�cfwsNrUrrrrrZ�srZc@seZdZdZdS)�Atom�atomNrUrrrrr\�sr\c@seZdZdZdZdS)�Tokenr6FN)r+rGrHrD�encode_as_ewrrrrr^�sr^c@seZdZdZdZdZdZdS)�EncodedWord�encoded-wordN)r+rGrHrD�cte�charset�langrrrrr`�sr`c@s4eZdZdZedd��Zedd��Zedd��ZdS)	�QuotedString�
quoted-stringcCs"|D]}|jdkr|jSqdS�N�bare-quoted-string�rDr�rr"rrrrQ�s
zQuotedString.contentcCs>g}|D]*}|jdkr&|�t|��q|�|j�qd�|�S)Nrhr)rD�appendr
rr%)r�resr"rrr�quoted_value�s
zQuotedString.quoted_valuecCs"|D]}|jdkr|jSqdSrgri�rr6rrr�stripped_value�s
zQuotedString.stripped_valueN)r+rGrHrDrKrQrmrorrrrre�s

	rec@s$eZdZdZdd�Zedd��ZdS)�BareQuotedStringrhcCstd�dd�|D���S)Nrcss|]}t|�VqdSrrr rrrr#sz+BareQuotedString.__str__.<locals>.<genexpr>)rr%r&rrrr'�szBareQuotedString.__str__cCsd�dd�|D��S)Nrcss|]}t|�VqdSrrr rrrr#sz)BareQuotedString.value.<locals>.<genexpr>r$r&rrrrszBareQuotedString.valueN)r+rGrHrDr'rKrrrrrrp�srpc@s8eZdZdZdd�Zdd�Zedd��Zedd	��Zd
S)�CommentrPcs(d�tdg�fdd��D�dggg��S)Nrrcsg|]}��|��qSr)�quoter r&rrrRsz#Comment.__str__.<locals>.<listcomp>�))r%r.r&rr&rr's��zComment.__str__cCs2|jdkrt|�St|��dd��dd��dd�S)NrPrrrz\(rsz\))rDr
r)rrrrrrrs
��z
Comment.quotecCsd�dd�|D��S)Nrcss|]}t|�VqdSrrr rrrr#sz"Comment.content.<locals>.<genexpr>r$r&rrrrQszComment.contentcCs|jgSr)rQr&rrrr5szComment.commentsN)	r+rGrHrDr'rrrKrQr5rrrrrqs
rqc@s4eZdZdZedd��Zedd��Zedd��ZdS)	�AddressListzaddress-listcCsdd�|D�S)NcSsg|]}|jdkr|�qS)�address�rDr rrrrR's
z)AddressList.addresses.<locals>.<listcomp>rr&rrr�	addresses%szAddressList.addressescCstdd�|D�g�S)Ncss|]}|jdkr|jVqdS�ruN�rD�	mailboxesr rrrr#+s
�z(AddressList.mailboxes.<locals>.<genexpr>�r.r&rrrrz)s
��zAddressList.mailboxescCstdd�|D�g�S)Ncss|]}|jdkr|jVqdSrx�rD�
all_mailboxesr rrrr#0s
�z,AddressList.all_mailboxes.<locals>.<genexpr>r{r&rrrr}.s
��zAddressList.all_mailboxesN)r+rGrHrDrKrwrzr}rrrrrt!s

rtc@s4eZdZdZedd��Zedd��Zedd��ZdS)	�AddressrucCs|djdkr|djSdS)Nr�group�rD�display_namer&rrrr�8szAddress.display_namecCs4|djdkr|dgS|djdkr*gS|djS�Nr�mailbox�invalid-mailboxryr&rrrrz=s

zAddress.mailboxescCs:|djdkr|dgS|djdkr0|dgS|djSr�r|r&rrrr}Es


zAddress.all_mailboxesN)r+rGrHrDrKr�rzr}rrrrr~4s

r~c@s(eZdZdZedd��Zedd��ZdS)�MailboxList�mailbox-listcCsdd�|D�S)NcSsg|]}|jdkr|�qS)r�rvr rrrrRSs
z)MailboxList.mailboxes.<locals>.<listcomp>rr&rrrrzQszMailboxList.mailboxescCsdd�|D�S)NcSsg|]}|jdkr|�qS))r�r�rvr rrrrRWs
�z-MailboxList.all_mailboxes.<locals>.<listcomp>rr&rrrr}UszMailboxList.all_mailboxesN�r+rGrHrDrKrzr}rrrrr�Ms

r�c@s(eZdZdZedd��Zedd��ZdS)�	GroupList�
group-listcCs |r|djdkrgS|djS�Nrr�ryr&rrrrz_szGroupList.mailboxescCs |r|djdkrgS|djSr�r|r&rrrr}eszGroupList.all_mailboxesNr�rrrrr�[s

r�c@s4eZdZdZedd��Zedd��Zedd��ZdS)	�GrouprcCs|djdkrgS|djS�N�r�ryr&rrrrzpszGroup.mailboxescCs|djdkrgS|djSr�r|r&rrrr}vszGroup.all_mailboxescCs
|djSr/)r�r&rrrr�|szGroup.display_nameN)r+rGrHrDrKrzr}r�rrrrr�ls

r�c@sLeZdZdZedd��Zedd��Zedd��Zedd	��Zed
d��Z	dS)
�NameAddr�	name-addrcCst|�dkrdS|djS�N�r)�lenr�r&rrrr��szNameAddr.display_namecCs
|djS�N�����
local_partr&rrrr��szNameAddr.local_partcCs
|djSr���domainr&rrrr��szNameAddr.domaincCs
|djSr�)�router&rrrr��szNameAddr.routecCs
|djSr���	addr_specr&rrrr��szNameAddr.addr_specN�
r+rGrHrDrKr�r�r�r�r�rrrrr��s



r�c@s@eZdZdZedd��Zedd��Zedd��Zedd	��Zd
S)�	AngleAddrz
angle-addrcCs"|D]}|jdkr|jSqdS�N�	addr-spec)rDr�rjrrrr��s
zAngleAddr.local_partcCs"|D]}|jdkr|jSqdSr��rDr�rjrrrr��s
zAngleAddr.domaincCs"|D]}|jdkr|jSqdS)N�	obs-route)rD�domainsrjrrrr��s
zAngleAddr.routecCs<|D]2}|jdkr|jr"|jSt|j�|jSqdS)Nr�z<>)rDr�r�rrjrrrr��s

zAngleAddr.addr_specN)	r+rGrHrDrKr�r�r�r�rrrrr��s


r�c@seZdZdZedd��ZdS)�ObsRouter�cCsdd�|D�S)NcSsg|]}|jdkr|j�qSr�r�r rrrrR�s
z$ObsRoute.domains.<locals>.<listcomp>rr&rrrr��szObsRoute.domainsN)r+rGrHrDrKr�rrrrr��sr�c@sLeZdZdZedd��Zedd��Zedd��Zedd	��Zed
d��Z	dS)
�Mailboxr�cCs|djdkr|djSdS�Nrr�r�r&rrrr��szMailbox.display_namecCs
|djSr/r�r&rrrr��szMailbox.local_partcCs
|djSr/r�r&rrrr��szMailbox.domaincCs|djdkr|djSdSr�)rDr�r&rrrr��sz
Mailbox.routecCs
|djSr/r�r&rrrr��szMailbox.addr_specNr�rrrrr��s



r�c@s,eZdZdZedd��ZeZZZZ	dS)�InvalidMailboxr�cCsdSrrr&rrrr��szInvalidMailbox.display_nameNr�rrrrr��s
r�cs(eZdZdZdZe�fdd��Z�ZS)�Domainr�Fcsd�t�j���S�Nr�r%rr�splitr&rrrr��sz
Domain.domain)r+rGrHrDr1rKr�rLrrrrr��sr�c@seZdZdZdS)�DotAtom�dot-atomNrUrrrrr��sr�c@seZdZdZdZdS)�DotAtomTextz
dot-atom-textTN�r+rGrHrDr1rrrrr��sr�c@seZdZdZdZdS)�
NoFoldLiteralzno-fold-literalFNr�rrrrr�sr�c@sDeZdZdZdZedd��Zedd��Zedd��Zed	d
��Z	dS)�AddrSpecr�FcCs
|djSr/r�r&rrrr�
szAddrSpec.local_partcCst|�dkrdS|djS)N�r�)r�r�r&rrrr�szAddrSpec.domaincCs<t|�dkr|djS|dj��|dj|dj��S)Nr�rr�r�)r�r�rstrip�lstripr&rrrrs
zAddrSpec.valuecCsLt|j�}t|�t|t�kr*t|j�}n|j}|jdk	rH|d|jS|S)N�@)�setr�r��
DOT_ATOM_ENDSrr�)r�nameset�lprrrr�s

zAddrSpec.addr_specN)
r+rGrHrDr1rKr�r�rr�rrrrr�s


r�c@seZdZdZdZdS)�ObsLocalPartzobs-local-partFNr�rrrrr�&sr�cs4eZdZdZdZedd��Ze�fdd��Z�ZS)�DisplayNamezdisplay-nameFcCs�t|�}t|�dkr|jS|djdkr4|�d�n*|ddjdkr^t|ddd��|d<|djdkrv|��n*|ddjdkr�t|ddd��|d<|jS)Nrr[r�r�)rr�rrD�pop)rrlrrrr�1s
zDisplayName.display_namecs�d}|jrd}n|D]}|jdkrd}qt|�dkr�|r�d}}|djdks`|ddjdkrdd}|djdks�|ddjdkr�d}|t|j�|St�jSdS)	NFTrfrrr[rOr�)rrDr�rr�rr)rrrr"�pre�postrrrrBs
  zDisplayName.value)	r+rGrHrDrJrKr�rrLrrrrr�,s
r�c@s,eZdZdZdZedd��Zedd��ZdS)�	LocalPartz
local-partFcCs&|djdkr|djS|djSdS)Nrrf)rDrmrr&rrrr[s
zLocalPart.valuecCs�tg}t}d}|dtgD]�}|jdkr,q|r\|jdkr\|djdkr\t|dd��|d<t|t�}|r�|jdkr�|djdkr�|�t|dd���n
|�|�|d}|}qt|dd��}|jS)NFrr[�dotr�r�)�DOTrDr�
isinstancerkr)rrl�last�
last_is_tl�tok�is_tlrrrr�bs(
�
�
zLocalPart.local_partN)r+rGrHrDr1rKrr�rrrrr�Vs
r�cs4eZdZdZdZe�fdd��Zedd��Z�ZS)�
DomainLiteralzdomain-literalFcsd�t�j���Sr�r�r&rrrr�szDomainLiteral.domaincCs"|D]}|jdkr|jSqdS)N�ptextrirjrrr�ip�s
zDomainLiteral.ip)	r+rGrHrDr1rKr�r�rLrrrrr�zsr�c@seZdZdZdZdZdS)�MIMEVersionzmime-versionN)r+rGrHrD�major�minorrrrrr��sr�c@s4eZdZdZdZdZdZedd��Zedd��Z	dS)	�	Parameter�	parameterF�us-asciicCs|jr|djSdSr�)�	sectioned�numberr&rrr�section_number�szParameter.section_numbercCsf|D]\}|jdkr|jS|jdkr|D]4}|jdkr*|D] }|jdkr<|jSq<q*qdS)Nrrfrhr)rDrornrrr�param_value�s




zParameter.param_valueN)
r+rGrHrDr��extendedrcrKr�r�rrrrr��s
r�c@seZdZdZdS)�InvalidParameter�invalid-parameterNrUrrrrr��sr�c@seZdZdZedd��ZdS)�	Attribute�	attributecCs$|D]}|j�d�r|jSqdS)N�attrtext)rD�endswithrrnrrrro�szAttribute.stripped_valueN�r+rGrHrDrKrorrrrr��sr�c@seZdZdZdZdS)�Section�sectionN)r+rGrHrDr�rrrrr��sr�c@seZdZdZedd��ZdS)�ValuercCs2|d}|jdkr|d}|j�d�r,|jS|jS)Nrr[r�)rfr�zextended-attribute)rDr�rorrnrrrro�s
�zValue.stripped_valueNr�rrrrr��sr�c@s(eZdZdZdZedd��Zdd�ZdS)�MimeParameters�mime-parametersFc
cs�i}|D]T}|j�d�sq|djdkr*q|dj��}||krHg||<||�|j|f�q|��D�]~\}}t|td�d�}|dd}|j	}|j
s�t|�dkr�|dddkr�|ddj�t
�d��|dd�}g}d}|D]�\}	}
|	|k�r(|
j
�s|
j�t
�d��q�n|
j�t
�d��|d7}|
j}|
j
�r�ztj�|�}Wn&tk
�rttjj|d	d
�}YnRXz|�|d�}Wn"tk
�r�|�dd�}YnXt�|��r�|
j�t
���|�|�q�d
�|�}||fVqfdS)Nr�rr�)�keyr�z.duplicate parameter name; duplicate(s) ignoredz+duplicate parameter name; duplicate ignoredz(inconsistent RFC2231 parameter numberingzlatin-1)�encoding�surrogateescaper�r)rDr�r�striprkr��items�sortedrrcr�r�rr�InvalidHeaderDefectr��urllib�parse�unquote_to_bytes�UnicodeEncodeError�unquote�decode�LookupErrorr�_has_surrogates�UndecodableBytesDefectr%)r�paramsr6�name�parts�first_paramrc�value_parts�ir��paramrrrrr��s`�

�
�
zMimeParameters.paramscCsTg}|jD].\}}|r.|�d�|t|���q
|�|�q
d�|�}|rPd|SdS)N�{}={}z; rOr)r�rkr*rr%)rr�r�rrrrr's
zMimeParameters.__str__N)r+rGrHrDrIrKr�r'rrrrr��s

Er�c@seZdZdZedd��ZdS)�ParameterizedHeaderValueFcCs&t|�D]}|jdkr|jSqiS)Nr�)�reversedrDr�rnrrrr�-s
zParameterizedHeaderValue.paramsN)r+rGrHrIrKr�rrrrr�'sr�c@seZdZdZdZdZdZdS)�ContentTypezcontent-typeF�text�plainN)r+rGrHrDr1�maintype�subtyperrrrr�5sr�c@seZdZdZdZdZdS)�ContentDispositionzcontent-dispositionFN)r+rGrHrDr1�content_dispositionrrrrr�<sr�c@seZdZdZdZdZdS)�ContentTransferEncodingzcontent-transfer-encodingF�7bitN)r+rGrHrDr1rbrrrrrBsrc@seZdZdZdZdS)�HeaderLabelzheader-labelFNr�rrrrrHsrc@seZdZdZdZdd�ZdS)�MsgIDzmsg-idFcCst|�|jSr)r
�linesepr:rrrr;Qsz
MsgID.foldN)r+rGrHrDr1r;rrrrrMsrc@seZdZdZdS)�	MessageIDz
message-idNrUrrrrrVsrc@seZdZdZdS)�InvalidMessageIDzinvalid-message-idNrUrrrrrZsrc@seZdZdZdS)�Header�headerNrUrrrrr^srcsreZdZdZdZdZ�fdd�Z�fdd�Zdd�Ze	dd	��Z
d�fdd�	Zd
d�Ze	dd��Z
dd�Z�ZS)�TerminalTcst��||�}||_g|_|Sr)r�__new__rDr)�clsrrDrrrrrlszTerminal.__new__csd�|jjt����Sr(r)r&rrrr,rszTerminal.__repr__cCst|jjd|j�dS)N�/)r>rr+rDr&rrrrAuszTerminal.pprintcCs
t|j�Sr)�listrr&rrrr-xszTerminal.all_defectsrc	s2d�||jj|jt���|js"dn
d�|j��gS)Nz
{}{}/{}({}){}rz {})r*rr+rDrr,rr@rrrrC|s�zTerminal._ppcCsdSrrr&rrr�pop_trailing_ws�szTerminal.pop_trailing_wscCsgSrrr&rrrr5�szTerminal.commentscCst|�|jfSr)r
rDr&rrr�__getnewargs__�szTerminal.__getnewargs__)r)r+rGrHr1rJrIrr,rArKr-rCrr5rrLrrrrr
fs
	
r
c@s eZdZedd��Zdd�ZdS)�WhiteSpaceTerminalcCsdSrNrr&rrrr�szWhiteSpaceTerminal.valuecCsdS)NTrr&rrrr0�sz!WhiteSpaceTerminal.startswith_fwsN�r+rGrHrKrr0rrrrr�s
rc@s eZdZedd��Zdd�ZdS)�
ValueTerminalcCs|Srrr&rrrr�szValueTerminal.valuecCsdS)NFrr&rrrr0�szValueTerminal.startswith_fwsNrrrrrr�s
rc@s eZdZedd��Zdd�ZdS)�EWWhiteSpaceTerminalcCsdSr�rr&rrrr�szEWWhiteSpaceTerminal.valuecCsdSr�rr&rrrr'�szEWWhiteSpaceTerminal.__str__N)r+rGrHrKrr'rrrrr�s
rc@seZdZdZdS)�_InvalidEwErrorz1Invalid encoded word found while parsing headers.N)r+rGrH�__doc__rrrrr�srr��,�list-separatorr�zroute-component-markerz([{}]+)rz[^{}]+z[\x00-\x20\x7F]cCs>t|�}|r|j�t�|��t�|�r:|j�t�d��dS)z@If input token contains ASCII non-printables, register a defect.z*Non-ASCII characters found in header tokenN)�_non_printable_finderrrkr�NonPrintableDefectrr�r�)�xtext�non_printablesrrr�_validate_xtext�s

�rcCs�t|d�^}}g}d}d}tt|��D]L}||dkrJ|rDd}d}nd}q&|rTd}n|||krdq||�||�q&|d}d�|�d�||d�g|�|fS)akScan printables/quoted-pairs until endchars and return unquoted ptext.

    This function turns a run of qcontent, ccontent-without-comments, or
    dtext-with-quoted-printables into a single string by unquoting any
    quoted printables.  It returns the string, the remaining value, and
    a flag that is True iff there were any quoted printables decoded.

    r�FrTrN)�
_wsp_splitter�ranger�rkr%)r�endchars�fragment�	remainder�vchars�escape�had_qp�posrrr�_get_ptext_to_endchars�s$	r'cCs.|��}t|dt|�t|��d�}||fS)z�FWS = 1*WSP

    This isn't the RFC definition.  We're using fws to represent tokens where
    folding can be done, but when we are parsing the *un*folding has already
    been done so we don't need to watch out for CRLF.

    N�fws)r�rr�)r�newvaluer(rrr�get_fwssr*c
	Cs�t�}|�d�s t�d�|���|dd��dd�^}}||dd�krXt�d�|���d�|�}t|�dkr�|dtkr�|dtkr�|�	d	�dkr�|�dd�^}}|d|}t|���dkr�|j
�t�d
��||_
d�|�}zt�d|d�\}}}}	Wn*ttfk
�r*td�|j
���YnX||_||_|j
�|	�|�r�|dtk�rrt|�\}
}|�|
��qDt|d�^}}t|d�}t|�|�|�d�|�}�qD|�r�|dtk�r�|j
�t�d
��||fS)zE encoded-word = "=?" charset "?" encoding "?" encoded-text "?="

    �=?z"expected encoded word but found {}r�Nz?=r�rr�?zwhitespace inside encoded wordz!encoded word format invalid: '{}'�vtextz.missing trailing whitespace after encoded-word)r`�
startswithr�HeaderParseErrorr*r�r%r�r�countrrkr�rb�_ewr��
ValueError�KeyErrorrrcrdr4�WSPr*rrr)
r�ewr�r"�remstr�restr�rcrdrr6�charsr-rrr�get_encoded_wordsd
��

�
��
�

�




�r9cCsFt�}|�rB|dtkr0t|�\}}|�|�qd}|�d�r�zt|�\}}Wn,tk
rfd}Yn�tjk
rzYnrXd}t	|�dkr�|dj
dkr�|j�t�d��d}|r�t	|�dkr�|d	j
d
kr�t
|dd�|d<|�|�qt|d�^}}|�rt�|��r|�d�^}}t|d�}t|�|�|�d�|�}q|S)
aOunstructured = (*([FWS] vchar) *WSP) / obs-unstruct
       obs-unstruct = *((*LF *CR *(obs-utext) *LF *CR)) / FWS)
       obs-utext = %d0 / obs-NO-WS-CTL / LF / CR

       obs-NO-WS-CTL is control characters except WSP/CR/LF.

    So, basically, we have printable runs, plus control characters or nulls in
    the obsolete syntax, separated by whitespace.  Since RFC 2047 uses the
    obsolete syntax in its specification, but requires whitespace on either
    side of the encoded words, I can see no reason to need to separate the
    non-printable-non-whitespace from the printable runs if they occur, so we
    parse this into xtext tokens separated by WSP tokens.

    Because an 'unstructured' value must by definition constitute the entire
    value, this 'get' routine does not return a remaining value, only the
    parsed TokenList.

    rTr+Fr�r(z&missing whitespace before encoded wordr����rar-r)rSr4r*rkr.r9rrr/r�rDrr�rr�rfc2047_matcher�search�	partitionrrr%)rrTr6�valid_ew�have_wsr�r"r-rrr�get_unstructured?sJ


��


r@cCs*t|d�\}}}t|d�}t|�||fS)actext = <printable ascii except \ ( )>

    This is not the RFC ctext, since we are handling nested comments in comment
    and unquoting quoted-pairs here.  We allow anything except the '()'
    characters, but if we find any ASCII other than the RFC defined printable
    ASCII, a NonPrintableDefect is added to the token's defects list.  Since
    quoted pairs are converted to their unquoted values, what is returned is
    a 'ptext' token.  In this case it is a WhiteSpaceTerminal, so it's value
    is ' '.

    z()r�)r'rr�rr��_rrr�get_qp_ctext�s
rCcCs*t|d�\}}}t|d�}t|�||fS)aoqcontent = qtext / quoted-pair

    We allow anything except the DQUOTE character, but if we find any ASCII
    other than the RFC defined printable ASCII, a NonPrintableDefect is
    added to the token's defects list.  Any quoted pairs are converted to their
    unquoted values, so what is returned is a 'ptext' token.  In this case it
    is a ValueTerminal.

    r
r�)r'rrrArrr�get_qcontent�s

rDcCsNt|�}|st�d�|���|��}|t|�d�}t|d�}t|�||fS)z�atext = <matches _atext_matcher>

    We allow any non-ATOM_ENDS in atext, but add an InvalidATextDefect to
    the token's defects list if we find non-atext characters.
    zexpected atext but found '{}'N�atext)�_non_atom_end_matcherrr/r*rr�rr)r�mrErrr�	get_atext�s�
rHcCsr|ddkrt�d�|���t�}|dd�}|rT|ddkrTt|�\}}|�|�|�rB|ddk�rB|dtkr�t|�\}}n�|dd�dk�r*d}z&t|�\}}|j	�t�
d	��d
}Wn"tjk
r�t|�\}}YnX|�r6t|�dk�r6|djdk�r6|d
jdk�r6t
|dd�|d<nt|�\}}|�|�qT|�sb|j	�t�
d��||fS||dd�fS)z�bare-quoted-string = DQUOTE *([FWS] qcontent) [FWS] DQUOTE

    A quoted-string without the leading or trailing white space.  Its
    value is the text between the quote marks, with whitespace
    preserved and quoted pairs decoded.
    rr
zexpected '"' but found '{}'r�Nr�r+Fz!encoded word inside quoted stringTr�r(r:raz"end of header inside quoted string)rr/r*rprDrkr4r*r9rr�r�rDr)r�bare_quoted_stringr6r>rrr�get_bare_quoted_string�sL�

���

�rJcCs�|r |ddkr t�d�|���t�}|dd�}|r�|ddkr�|dtkr\t|�\}}n&|ddkrvt|�\}}nt|�\}}|�|�q2|s�|j	�t�
d��||fS||dd�fS)z�comment = "(" *([FWS] ccontent) [FWS] ")"
       ccontent = ctext / quoted-pair / comment

    We handle nested comments here, and quoted-pair in our qp-ctext routine.
    rrzexpected '(' but found '{}'r�Nrszend of header inside comment)rr/r*rqr4r*�get_commentrCrkrr�)rrPr6rrrrK�s&�
�rKcCsPt�}|rH|dtkrH|dtkr0t|�\}}nt|�\}}|�|�q||fS)z,CFWS = (1*([FWS] comment) [FWS]) / FWS

    r)rZ�CFWS_LEADERr4r*rKrk)rr[r6rrr�get_cfws�srMcCspt�}|r,|dtkr,t|�\}}|�|�t|�\}}|�|�|rh|dtkrht|�\}}|�|�||fS)z�quoted-string = [CFWS] <bare-quoted-string> [CFWS]

    'bare-quoted-string' is an intermediate class defined by this
    parser and not by the RFC grammar.  It is the quoted string
    without any attached CFWS.
    r)rerLrMrkrJ)r�
quoted_stringr6rrr�get_quoted_strings


rOcCs�t�}|r,|dtkr,t|�\}}|�|�|rL|dtkrLt�d�|���|�d�r�zt	|�\}}Wq�tjk
r�t
|�\}}Yq�Xnt
|�\}}|�|�|r�|dtkr�t|�\}}|�|�||fS)zPatom = [CFWS] 1*atext [CFWS]

    An atom could be an rfc2047 encoded word.
    rzexpected atom but found '{}'r+)r\rLrMrk�	ATOM_ENDSrr/r*r.r9rH)rr]r6rrr�get_atoms&
�


rQcCs�t�}|r|dtkr&t�d�|���|rt|dtkrtt|�\}}|�|�|r&|ddkr&|�t�|dd�}q&|dtkr�t�d�d|���||fS)z( dot-text = 1*atext *("." 1*atext)

    rz8expected atom at a start of dot-atom-text but found '{}'rr�Nr�z4expected atom at end of dot-atom-text but found '{}')r�rPrr/r*rHrkr�)r�
dot_atom_textr6rrr�get_dot_atom_text0s �

�rScCs�t�}|dtkr(t|�\}}|�|�|�d�rhzt|�\}}Wqttjk
rdt|�\}}YqtXnt|�\}}|�|�|r�|dtkr�t|�\}}|�|�||fS)z� dot-atom = [CFWS] dot-atom-text [CFWS]

    Any place we can have a dot atom, we could instead have an rfc2047 encoded
    word.
    rr+)	r�rLrMrkr.r9rr/rS)r�dot_atomr6rrr�get_dot_atomCs



rUcCs�|dtkrt|�\}}nd}|s,t�d��|ddkrFt|�\}}n*|dtkrdt�d�|���nt|�\}}|dk	r�|g|dd�<||fS)a�word = atom / quoted-string

    Either atom or quoted-string may start with CFWS.  We have to peel off this
    CFWS first to determine which type of word to parse.  Afterward we splice
    the leading CFWS, if any, into the parsed sub-token.

    If neither an atom or a quoted-string is found before the next special, a
    HeaderParseError is raised.

    The token returned is either an Atom or a QuotedString, as appropriate.
    This means the 'word' level of the formal grammar is not represented in the
    parse tree; this is because having that extra layer when manipulating the
    parse tree is more confusing than it is helpful.

    rNz5Expected 'atom' or 'quoted-string' but found nothing.r
z1Expected 'atom' or 'quoted-string' but found '{}')rLrMrr/rO�SPECIALSr*rQ)r�leaderr6rrr�get_word\s"��rXcCs�t�}zt|�\}}|�|�Wn(tjk
rH|j�t�d��YnX|r�|dtkr�|ddkr�|�t�|j�t�	d��|dd�}qJzt|�\}}WnDtjk
r�|dt
kr�t|�\}}|j�t�	d��n�YnX|�|�qJ||fS)a� phrase = 1*word / obs-phrase
        obs-phrase = word *(word / "." / CFWS)

    This means a phrase can be a sequence of words, periods, and CFWS in any
    order as long as it starts with at least one word.  If anything other than
    words is detected, an ObsoleteHeaderDefect is added to the token's defect
    list.  We also accept a phrase that starts with CFWS followed by a dot;
    this is registered as an InvalidHeaderDefect, since it is not supported by
    even the obsolete grammar.

    zphrase does not start with wordrrzperiod in 'phrase'r�Nzcomment found without atom)rVrXrkrr/rr��PHRASE_ENDSr��ObsoleteHeaderDefectrLrM)rrWr6rrr�
get_phrase~s4
�

�
�r[cCsvt�}d}|dtkr"t|�\}}|s6t�d�|���zt|�\}}Wn^tjk
r�zt|�\}}Wn6tjk
r�|ddkr�|dtkr��t	�}YnXYnX|dk	r�|g|dd�<|�
|�|�r4|ddks�|dtk�r4tt|�|�\}}|j
dk�r|j�
t�d��n|j�
t�d��||d<z|j�d�Wn(tk
�rl|j�
t�d	��YnX||fS)
z= local-part = dot-atom / quoted-string / obs-local-part

    Nrz"expected local-part but found '{}'r�invalid-obs-local-partz<local-part is not dot-atom, quoted-string, or obs-local-partz,local-part is not a dot-atom (contains CFWS)�asciiz)local-part contains non-ASCII characters))r�rLrMrr/r*rUrXrYrrk�get_obs_local_partr
rDrr�rZr�encoder��NonASCIILocalPartDefect)rr�rWr6�obs_local_partrrr�get_local_part�sJ�
 
�
�
�rbcCs�t�}d}|�r(|ddks*|dtk�r(|ddkrj|rL|j�t�d��|�t�d}|dd�}q
nD|ddkr�|�t|dd	��|dd�}|j�t�d
��d}q
|r�|djdkr�|j�t�d
��zt	|�\}}d}Wn4tj
k
�r|dtk�r
�t|�\}}YnX|�|�q
|djdk�sX|djdk�rj|djdk�rj|j�t�d��|djdk�s�|djdk�r�|djdk�r�|j�t�d��|j�r�d|_||fS)z' obs-local-part = word *("." word)
    Frrrzinvalid repeated '.'Tr�N�misplaced-specialz/'\' character outside of quoted-string/ccontentr�r�zmissing '.' between wordsr[z!Invalid leading '.' in local partr:z"Invalid trailing '.' in local partr\)
r�rYrrkrr�r�rrDrXr/rLrM)rra�last_non_ws_was_dotr6rrrr^�sj 
�
�
�
���
���
�r^cCs@t|d�\}}}t|d�}|r0|j�t�d��t|�||fS)a dtext = <printable ascii except \ [ ]> / obs-dtext
        obs-dtext = obs-NO-WS-CTL / quoted-pair

    We allow anything except the excluded characters, but if we find any
    ASCII other than the RFC defined printable ASCII, a NonPrintableDefect is
    added to the token's defects list.  Quoted pairs are converted to their
    unquoted values, so what is returned is a ptext token, in this case a
    ValueTerminal.  If there were quoted-printables, an ObsoleteHeaderDefect is
    added to the returned token's defect list.

    z[]r�z(quoted printable found in domain-literal)r'rrrkrrZr)rr�r%rrr�	get_dtext�s

�recCs,|rdS|�t�d��|�tdd��dS)NFz"end of input inside domain-literal�]�domain-literal-endT)rkrr�r)r�domain_literalrrr�_check_for_early_dl_ends�ricCsjt�}|dtkr(t|�\}}|�|�|s6t�d��|ddkrRt�d�|���|dd�}t||�rp||fS|�tdd��|dt	kr�t
|�\}}|�|�t|�\}}|�|�t||�r�||fS|dt	kr�t
|�\}}|�|�t||�r�||fS|ddk�rt�d	�|���|�tdd
��|dd�}|�rb|dtk�rbt|�\}}|�|�||fS)zB domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]

    rzexpected domain-literal�[z6expected '[' at start of domain-literal but found '{}'r�Nzdomain-literal-startrfz4expected ']' at end of domain-literal but found '{}'rg)r�rLrMrkrr/r*rirr4r*re)rrhr6rrr�get_domain_literalsH

�





�
rkcCsrt�}d}|dtkr"t|�\}}|s6t�d�|���|ddkrvt|�\}}|dk	rd|g|dd�<|�|�||fSzt|�\}}Wn"tjk
r�t	|�\}}YnX|r�|ddkr�t�d��|dk	r�|g|dd�<|�|�|�rj|ddk�rj|j
�t�d��|djd	k�r*|d|dd�<|�rj|ddk�rj|�t
�t	|d
d��\}}|�|��q*||fS)z] domain = dot-atom / domain-literal / obs-domain
        obs-domain = atom *("." atom))

    Nrzexpected domain but found '{}'rjr�zInvalid Domainrz(domain is not a dot-atom (contains CFWS)r�r�)r�rLrMrr/r*rkrkrUrQrrZrDr�)rr�rWr6rrr�
get_domain=sD�



�
rlcCs|t�}t|�\}}|�|�|r,|ddkrF|j�t�d��||fS|�tdd��t|dd��\}}|�|�||fS)z( addr-spec = local-part "@" domain

    rr�z#addr-spec local part with no domain�address-at-symbolr�N)r�rbrkrrr�rrl)rr�r6rrr�
get_addr_speccs

�
rncCs�t�}|rj|ddks"|dtkrj|dtkrFt|�\}}|�|�q|ddkr|�t�|dd�}q|rz|ddkr�t�d�|���|�t�t	|dd��\}}|�|�|�r>|ddk�r>|�t�|dd�}|s�q>|dtk�rt|�\}}|�|�|ddkr�|�t�t	|dd��\}}|�|�q�|�sNt�d��|ddk�rlt�d	�|���|�t
dd
��||dd�fS)z� obs-route = obs-domain-list ":"
        obs-domain-list = *(CFWS / ",") "@" domain *("," [CFWS] ["@" domain])

        Returns an obs-route token with the appropriate sub-tokens (that is,
        there is no obs-domain-list in the parse tree).
    rrr�Nr�z(expected obs-route domain but found '{}'z%end of header while parsing obs-route�:z4expected ':' marking end of obs-route but found '{}'zend-of-obs-route-marker)r�rLrMrk�
ListSeparatorrr/r*�RouteComponentMarkerrlr)r�	obs_router6rrr�
get_obs_routessF
�





�rscCs�t�}|dtkr(t|�\}}|�|�|r8|ddkrHt�d�|���|�tdd��|dd�}|ddkr�|�tdd��|j�t�	d	��|dd�}||fSzt
|�\}}Wnztjk
�r0z"t|�\}}|j�t�d
��Wn(tjk
�rt�d�|���YnX|�|�t
|�\}}YnX|�|�|�r^|ddk�r^|dd�}n|j�t�	d��|�tdd��|�r�|dtk�r�t|�\}}|�|�||fS)
z� angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / obs-angle-addr
        obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS]

    r�<z"expected angle-addr but found '{}'zangle-addr-startr�N�>zangle-addr-endznull addr-spec in angle-addrz*obsolete route specification in angle-addrz.expected addr-spec or obs-route but found '{}'z"missing trailing '>' on angle-addr)
r�rLrMrkrr/r*rrr�rnrsrZ)r�
angle_addrr6rrr�get_angle_addr�sT
�
�
�
�



�
rwcCs<t�}t|�\}}|�|dd��|jdd�|_||fS)z� display-name = phrase

    Because this is simply a name-rule, we don't return a display-name
    token containing a phrase, but rather a display-name token with
    the content of the phrase.

    N)r�r[r4r)rr�r6rrr�get_display_name�s
rxcCs�t�}d}|dtkr6t|�\}}|s6t�d�|���|ddkr�|dtkr^t�d�|���t|�\}}|s~t�d�|���|dk	r�|g|ddd�<d}|�|�t	|�\}}|dk	r�|g|dd�<|�|�||fS)z, name-addr = [display-name] angle-addr

    Nrz!expected name-addr but found '{}'rt)
r�rLrMrr/r*rYrxrkrw)r�	name_addrrWr6rrr�
get_name_addr�s6���

rzcCs�t�}zt|�\}}WnNtjk
rdzt|�\}}Wn&tjk
r^t�d�|���YnXYnXtdd�|jD��r�d|_|�	|�||fS)z& mailbox = name-addr / addr-spec

    zexpected mailbox but found '{}'css|]}t|tj�VqdSr)r�rr�r rrrr#s�zget_mailbox.<locals>.<genexpr>r�)
r�rzrr/rnr*�anyr-rDrk)rr�r6rrr�get_mailbox�s ��
r|cCsdt�}|r\|d|kr\|dtkrD|�t|dd��|dd�}qt|�\}}|�|�q||fS)z� Read everything up to one of the chars in endchars.

    This is outside the formal grammar.  The InvalidMailbox TokenList that is
    returned acts like a Mailbox, but the data attributes are None.

    rrcr�N)r�rYrkrr[)rr �invalid_mailboxr6rrr�get_invalid_mailboxs�r~cCs�t�}|�r�|ddk�r�zt|�\}}|�|�W�ntjk
�r<d}|dtkr�t|�\}}|rv|ddkr�|�|�|j�t�d��n@t	|d�\}}|dk	r�|g|dd�<|�|�|j�t�
d��nb|ddkr�|j�t�d��nBt	|d�\}}|dk	�r|g|dd�<|�|�|j�t�
d��YnX|�r�|ddk�r�|d}d	|_t	|d�\}}|�|�|j�t�
d��|r|ddkr|�t
�|d
d�}q||fS)aJ mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list
        obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS])

    For this routine we go outside the formal grammar in order to improve error
    handling.  We recognize the end of the mailbox list only at the end of the
    value or at a ';' (the group terminator).  This is so that we can turn
    invalid mailboxes into InvalidMailbox tokens and continue parsing any
    remaining valid mailboxes.  We also allow all mailbox entries to be null,
    and this condition is handled appropriately at a higher level.

    r�;Nz,;zempty element in mailbox-listzinvalid mailbox in mailbox-listrr�r�r�)r�r|rkrr/rLrMrrZr~r�rDr4rp)r�mailbox_listr6rWr�rrr�get_mailbox_listsX

�

�
�


�

�
r�cCst�}|s$|j�t�d��||fSd}|r�|dtkr�t|�\}}|sl|j�t�d��|�|�||fS|ddkr�|�|�||fSt|�\}}t|j	�dkr�|dk	r�|�|�|�
|�|j�t�d��||fS|dk	r�|g|dd�<|�|�||fS)zg group-list = mailbox-list / CFWS / obs-group-list
        obs-group-list = 1*([CFWS] ",") [CFWS]

    zend of header before group-listNrzend of header in group-listrzgroup-list with empty entries)r�rrkrr�rLrMr�r�r}r4rZ)r�
group_listrWr6rrr�get_group_listWs>
�
�




�
r�cCs t�}t|�\}}|r"|ddkr2t�d�|���|�|�|�tdd��|dd�}|r�|ddkr�|�tdd��||dd�fSt|�\}}|�|�|s�|j�t�	d	��n|ddkr�t�d
�|���|�tdd��|dd�}|�r|dt
k�rt|�\}}|�|�||fS)z7 group = display-name ":" [group-list] ";" [CFWS]

    rroz8expected ':' at end of group display name but found '{}'zgroup-display-name-terminatorr�Nrzgroup-terminatorzend of header in groupz)expected ';' at end of group but found {})r�rxrr/r*rkrr�rr�rLrM)rrr6rrr�	get_group|s8�


��
r�cCsxt�}zt|�\}}WnNtjk
rdzt|�\}}Wn&tjk
r^t�d�|���YnXYnX|�|�||fS)a� address = mailbox / group

    Note that counter-intuitively, an address can be either a single address or
    a list of addresses (a group).  This is why the returned Address object has
    a 'mailboxes' attribute which treats a single address as a list of length
    one.  When you need to differentiate between to two cases, extract the single
    element, which is either a mailbox or a group token.

    zexpected address but found '{}')r~r�rr/r|r*rk)rrur6rrr�get_address�s�
r�c
Cs�t�}|�r�zt|�\}}|�|�W�n tjk
�rH}z�d}|dtkr�t|�\}}|rj|ddkr�|�|�|j�t�d��nFt	|d�\}}|dk	r�|g|dd�<|�t
|g��|j�t�d��nh|ddkr�|j�t�d��nHt	|d�\}}|dk	�r|g|dd�<|�t
|g��|j�t�d��W5d}~XYnX|�r�|ddk�r�|dd}d|_t	|d�\}}|�
|�|j�t�d��|r|�tdd	��|d
d�}q||fS)a� address_list = (address *("," address)) / obs-addr-list
        obs-addr-list = *([CFWS] ",") address *("," [address / CFWS])

    We depart from the formal grammar here by continuing to parse until the end
    of the input, assuming the input to be entirely composed of an
    address-list.  This is always true in email parsing, and allows us
    to skip invalid addresses to parse additional valid ones.

    Nrrz"address-list entry with no contentzinvalid address in address-listzempty element in address-listr�r�rr�)rtr�rkrr/rLrMrrZr~r~r�rDr4r)r�address_listr6�errrWr�rrr�get_address_list�sX


�
�
�

�

�r�cCs�t�}|st�d�|���|ddkr6t�d�|���|�tdd��|dd�}t|�\}}|�|�|rx|ddkr�t�d	�|���|�tdd
��||dd�fS)z& no-fold-literal = "[" *dtext "]"
    z'expected no-fold-literal but found '{}'rrjz;expected '[' at the start of no-fold-literal but found '{}'zno-fold-literal-startr�Nrfz9expected ']' at the end of no-fold-literal but found '{}'zno-fold-literal-end)r�rr/r*rkrre)r�no_fold_literalr6rrr�get_no_fold_literal�s.���
��r�cCs�t�}|r,|dtkr,t|�\}}|�|�|r<|ddkrLt�d�|���|�tdd��|dd�}zt|�\}}Wn`tjk
r�z"t	|�\}}|j
�t�d��Wn&tjk
r�t�d�|���YnXYnX|�|�|r�|dd	k�r@|j
�t�d
��|�r8|ddk�r8|�tdd��|dd�}||fS|�td	d
��|dd�}zt|�\}}Wn�tjk
�rzt
|�\}}Wnrtjk
�r}zPz"t|�\}}|j
�t�d��Wn(tjk
�r�t�d�|���YnXW5d}~XYnXYnX|�|�|�r6|ddk�r6|dd�}n|j
�t�d��|�tdd��|�r�|dtk�r�t|�\}}|�|�||fS)z�msg-id = [CFWS] "<" id-left '@' id-right  ">" [CFWS]
       id-left = dot-atom-text / obs-id-left
       id-right = dot-atom-text / no-fold-literal / obs-id-right
       no-fold-literal = "[" *dtext "]"
    rrtzexpected msg-id but found '{}'zmsg-id-startr�Nzobsolete id-left in msg-idz4expected dot-atom-text or obs-id-left but found '{}'r�zmsg-id with no id-rightruz
msg-id-endrmzobsolete id-right in msg-idzFexpected dot-atom-text, no-fold-literal or obs-id-right but found '{}'zmissing trailing '>' on msg-id)rrLrMrkrr/r*rrSr^rrZr�r�rl)r�msg_idr6�errr�
get_msg_ids~
�
�
��

�
�
��"

�
r�c
Cs�t�}zt|�\}}|�|�WnLtjk
rl}z,t|�}t|�}|j�t�d�	|���W5d}~XYnX|r�|j�t�d�	|���|S)z2message-id      =   "Message-ID:" msg-id CRLF
    zInvalid msg-id: {!r}NzUnexpected {!r})
rr�rkrr/r@rrr�r*)r�
message_idr6�exrrr�parse_message_idIs�
�r�cCs�t�}|s |j�t�d��|S|dtkrXt|�\}}|�|�|sX|j�t�d��d}|r�|ddkr�|dtkr�||d7}|dd�}q\|��s�|j�t�d�	|���|�t
|d	��nt|�|_|�t
|d
��|�r|dtk�rt|�\}}|�|�|�r|ddk�rT|jdk	�r:|j�t�d��|�rP|�t
|d	��|S|�t
dd��|dd�}|�r�|dtk�r�t|�\}}|�|�|�s�|jdk	�r�|j�t�d��|Sd}|�r�|dtk�r�||d7}|dd�}�q�|���s*|j�t�d
�	|���|�t
|d	��nt|�|_
|�t
|d
��|�rn|dtk�rnt|�\}}|�|�|�r�|j�t�d��|�t
|d	��|S)zE mime-version = [CFWS] 1*digit [CFWS] "." [CFWS] 1*digit [CFWS]

    z%Missing MIME version number (eg: 1.0)rz0Expected MIME version number but found only CFWSrrr�Nz1Expected MIME major version number but found {!r}r�digitsz0Incomplete MIME version; found only major numberzversion-separatorz1Expected MIME minor version number but found {!r}z'Excess non-CFWS text after MIME version)r�rrkr�HeaderMissingRequiredValuerLrM�isdigitr�r*r�intr�r�)r�mime_versionr6r�rrr�parse_mime_versiones�
�

�
�


�

�

�


�r�cCsdt�}|r\|ddkr\|dtkrD|�t|dd��|dd�}qt|�\}}|�|�q||fS)z� Read everything up to the next ';'.

    This is outside the formal grammar.  The InvalidParameter TokenList that is
    returned acts like a Parameter, but the data attributes are None.

    rrrcr�N)r�rYrkrr[)r�invalid_parameterr6rrr�get_invalid_parameter�s�r�cCsNt|�}|st�d�|���|��}|t|�d�}t|d�}t|�||fS)a8ttext = <matches _ttext_matcher>

    We allow any non-TOKEN_ENDS in ttext, but add defects to the token's
    defects list if we find non-ttext characters.  We also register defects for
    *any* non-printables even though the RFC doesn't exclude all of them,
    because we follow the spirit of RFC 5322.

    zexpected ttext but found '{}'N�ttext)�_non_token_end_matcherrr/r*rr�rr)rrGr�rrr�	get_ttext�s	�
r�cCs�t�}|r,|dtkr,t|�\}}|�|�|rL|dtkrLt�d�|���t|�\}}|�|�|r�|dtkr�t|�\}}|�|�||fS)z�token = [CFWS] 1*ttext [CFWS]

    The RFC equivalent of ttext is any US-ASCII chars except space, ctls, or
    tspecials.  We also exclude tabs even though the RFC doesn't.

    The RFC implies the CFWS but is not explicit about it in the BNF.

    r�expected token but found '{}')	r^rLrMrk�
TOKEN_ENDSrr/r*r�)r�mtokenr6rrr�	get_token�s	
�

r�cCsNt|�}|st�d�|���|��}|t|�d�}t|d�}t|�||fS)aQattrtext = 1*(any non-ATTRIBUTE_ENDS character)

    We allow any non-ATTRIBUTE_ENDS in attrtext, but add defects to the
    token's defects list if we find non-attrtext characters.  We also register
    defects for *any* non-printables even though the RFC doesn't exclude all of
    them, because we follow the spirit of RFC 5322.

    z expected attrtext but found {!r}Nr�)�_non_attribute_end_matcherrr/r*rr�rr�rrGr�rrr�get_attrtext�s	�
r�cCs�t�}|r,|dtkr,t|�\}}|�|�|rL|dtkrLt�d�|���t|�\}}|�|�|r�|dtkr�t|�\}}|�|�||fS)aH [CFWS] 1*attrtext [CFWS]

    This version of the BNF makes the CFWS explicit, and as usual we use a
    value terminal for the actual run of characters.  The RFC equivalent of
    attrtext is the token characters, with the subtraction of '*', "'", and '%'.
    We include tab in the excluded set just as we do for token.

    rr�)	r�rLrMrk�ATTRIBUTE_ENDSrr/r*r��rr�r6rrr�
get_attribute�s	
�

r�cCsNt|�}|st�d�|���|��}|t|�d�}t|d�}t|�||fS)z�attrtext = 1*(any non-ATTRIBUTE_ENDS character plus '%')

    This is a special parsing routine so that we get a value that
    includes % escapes as a single string (which we decode as a single
    string later).

    z)expected extended attrtext but found {!r}N�extended-attrtext)�#_non_extended_attribute_end_matcherrr/r*rr�rrr�rrr�get_extended_attrtext	s�
r�cCs�t�}|r,|dtkr,t|�\}}|�|�|rL|dtkrLt�d�|���t|�\}}|�|�|r�|dtkr�t|�\}}|�|�||fS)z� [CFWS] 1*extended_attrtext [CFWS]

    This is like the non-extended version except we allow % characters, so that
    we can pick up an encoded value as a single string.

    rr�)	r�rLrMrk�EXTENDED_ATTRIBUTE_ENDSrr/r*r�r�rrr�get_extended_attribute!	s
�

r�cCs�t�}|r|ddkr&t�d�|���|�tdd��|dd�}|rR|d��sbt�d�|���d}|r�|d��r�||d7}|dd�}qf|dd	kr�|d	kr�|j�t�d
��t	|�|_
|�t|d��||fS)a6 '*' digits

    The formal BNF is more complicated because leading 0s are not allowed.  We
    check for that and add a defect.  We also assume no CFWS is allowed between
    the '*' and the digits, though the RFC is not crystal clear on that.
    The caller should already have dealt with leading CFWS.

    r�*zExpected section but found {}zsection-markerr�Nz$Expected section number but found {}r�0z'section number has an invalid leading 0r�)r�rr/r*rkrr�r�InvalidHeaderErrorr�r�)rr�r�rrr�get_section7	s,	��
�
r�cCs�t�}|st�d��d}|dtkr0t|�\}}|sDt�d�|���|ddkr^t|�\}}nt|�\}}|dk	r�|g|dd�<|�|�||fS)z  quoted-string / attribute

    z&Expected value but found end of stringNrz Expected value but found only {}r
)	r�rr/rLrMr*rOr�rk)r�vrWr6rrr�	get_valueU	s"
�
r�cCs�t�}t|�\}}|�|�|r,|ddkrL|j�t�d�|���||fS|ddkr�z t|�\}}d|_|�|�Wntj	k
r�YnX|s�t�	d��|ddkr�|�t
dd��|dd	�}d|_|dd
kr�t�	d��|�t
d
d��|dd	�}d	}|�r,|dtk�r,t
|�\}}|�|�d	}|}|j�rF|�rF|dd
k�rFt|�\}}|j}d}|jdk�r�|�r�|ddk�r�d}n$t|�\}}	|	�r�|	ddk�r�d}n(zt|�\}}	WnYnX|	�s�d}|�r0|j�t�d��|�|�|D](}
|
jdk�rg|
d	d	�<|
}�q*�q|}nd	}|j�t�d��|�r`|ddk�r`d	}nt|�\}}|j�r�|jdk�r�|�r�|ddk�r�|�|�|d	k	�r�|�r�t|��|}||fS|j�t�d��|�s
|j�t�d��|�|�|d	k�r�||fSn�|d	k	�rN|D]}
|
jdk�r�q2�q|
jdk|�|
�|
j|_|ddk�rlt�	d�|���|�t
dd��|dd	�}|�r�|ddk�r�t|�\}}|�|�|j|_|�r�|ddk�r�t�	d�|���|�t
dd��|dd	�}|d	k	�rrt�}|�rl|dtk�r,t|�\}}n2|dd
k�rRt
d
d�}|dd	�}nt|�\}}|�|��q
|}nt|�\}}|�|�|d	k	�r�|�r�t|��|}||fS)aY attribute [section] ["*"] [CFWS] "=" value

    The CFWS is implied by the RFC but not made explicit in the BNF.  This
    simplified form of the BNF from the RFC is made to conform with the RFC BNF
    through some extra checks.  We do it this way because it makes both error
    recovery and working with the resulting parse tree easier.
    rrz)Parameter contains name ({}) but no valuer�TzIncomplete parameterzextended-parameter-markerr�N�=zParameter not followed by '='�parameter-separatorr
F�'z5Quoted string value for extended parameter is invalidrhzZParameter marked as extended but appears to have a quoted string value that is non-encodedzcApparent initial-extended-value but attribute was not marked as extended or was not initial sectionz(Missing required charset/lang delimitersr�r�z=Expected RFC2231 char/lang encoding delimiter, but found {!r}zRFC2231-delimiterz;Expected RFC2231 char/lang encoding delimiter, but found {}ZDQUOTE)r�r�rkrrr�r*r�r�r/rr�rLrMrOror�r�r�rDr��AssertionErrorrrcrdr�r4r*rD)rr�r6rWr"�appendto�qstring�inner_value�
semi_validr7�tr�rrr�
get_parameterk	s�
�



�


�


�
�






�
�



r�c
Csjt�}|�rfzt|�\}}|�|�Wn�tjk
r�}z�d}|dtkrVt|�\}}|sp|�|�|WY�xS|ddkr�|dk	r�|�|�|j�t�d��n@t	|�\}}|r�|g|dd�<|�|�|j�t�d�
|���W5d}~XYnX|�rD|ddk�rD|d}d|_t	|�\}}|�|�|j�t�d�
|���|r|�t
dd	��|d
d�}q|S)a! parameter *( ";" parameter )

    That BNF is meant to indicate this routine should only be called after
    finding and handling the leading ';'.  There is no corresponding rule in
    the formal RFC grammar, but it is more convenient for us for the set of
    parameters to be treated as its own TokenList.

    This is 'parse' routine because it consumes the remaining value, but it
    would never be called to parse a full header.  Instead it is called to
    parse everything after the non-parameter value of a specific MIME header.

    Nrrzparameter entry with no contentzinvalid parameter {!r}r�r�z)parameter with invalid trailing text {!r}r�r�)r�r�rkrr/rLrMrr�r�r*rDr4r)r�mime_parametersr6r�rWr�rrr�parse_mime_parameters�	sJ



�

�

�r�cCs�|rV|ddkrV|dtkr>|�t|dd��|dd�}qt|�\}}|�|�q|s^dS|�tdd��|�t|dd���dS)zBDo our best to find the parameters in an invalid MIME header

    rrrcr�Nr�)rYrkrr[r�)�	tokenlistrr6rrr�_find_mime_parameters-
sr�c
Cs�t�}d}|s$|j�t�d��|Szt|�\}}Wn<tjk
rp|j�t�d�|���t	||�|YSX|�|�|r�|ddkr�|j�t�d��|r�t	||�|S|j
����|_
|�tdd��|dd	�}zt|�\}}Wn>tjk
�r*|j�t�d
�|���t	||�|YSX|�|�|j
����|_|�sP|S|ddk�r�|j�t�d�|���|`
|`t	||�|S|�tdd
��|�t|dd	���|S)z� maintype "/" subtype *( ";" parameter )

    The maintype and substype are tokens.  Theoretically they could
    be checked against the official IANA list + x-token, but we
    don't do that.
    Fz"Missing content type specificationz(Expected content maintype but found {!r}rr
zInvalid content typezcontent-type-separatorr�Nz'Expected content subtype but found {!r}rz<Only parameters are valid after content type, but found {!r}r�)r�rrkrr�r�r/r�r*r�rr��lowerr�rr�r�)r�ctype�recoverr6rrr�parse_content_type_header=
sd
�
�



�

�



��
r�c
Cs�t�}|s |j�t�d��|Szt|�\}}Wn<tjk
rl|j�t�d�|���t	||�|YSX|�|�|j
����|_
|s�|S|ddkr�|j�t�d�|���t	||�|S|�tdd��|�t|dd���|S)	z* disposition-type *( ";" parameter )

    zMissing content dispositionz+Expected content disposition but found {!r}rrzCOnly parameters are valid after content disposition, but found {!r}r�r�N)r�rrkrr�r�r/r�r*r�rr�r�rrr�)r�disp_headerr6rrr� parse_content_disposition_headerv
s:
�
�



��
r�c
Cs�t�}|s |j�t�d��|Szt|�\}}Wn.tjk
r^|j�t�d�|���YnX|�|�|j	�
���|_|s�|S|r�|j�t�d��|dt
kr�|�t|dd��|dd�}q�t|�\}}|�|�q�|S)z mechanism

    z!Missing content transfer encodingz1Expected content transfer encoding but found {!r}z*Extra text after content transfer encodingrrcr�N)rrrkrr�r�r/r�r*rr�r�rbrYrr[)r�
cte_headerr6rrr�&parse_content_transfer_encoding_header�
s4
�
�

�r�cCsDd}|r@|dr@|ddtkr@|dd}|ddd�|d<|S)Nrr�)r4)�lines�wsprrr�_steal_trailing_WSP_if_exists�
s
r�cCs�|jp
tj}|jrdnd}dg}d}d}d}tdd�}t|�}	|	�r�|	�d�}
|
|kr`|d8}q>t|
�}|
jd	kr�t	|�t
@r�d
}z|�|�|}Wn6tk
r�t
dd�|
jD��r�d
}nd}d
}YnX|
jdkr�t|
|||�q>|�r�|�s�|
j�spd}d}|
j�rp|
j|d�dt|j��}
|j|
k�rpt|
�|t|d�k�r^t|�}|�|�|d|
7<q>t|
d��s�t|
�|	}	nt|||||
j|�}d}q>t|�|t|d�k�r�|d|7<q>|
j�rt|�d|k�rt|�}|�s|
���r|�||�d}q>t|
d��sNt|
�}|
j�sD|d7}|�|�||	}	q>|
j�rn|�sn|	�d|
�d
}q>t|�}|�s�|
���r�|�||�q>|d|7<q>|j�|�|jS)zLReturn string of contents of parse_tree folded according to RFC rules.

    �utf-8r�rNrF�wrap_as_ew_blockedr�r�Tcss|]}t|tj�VqdSr)r�rr�r rrrr#�
s�z%_refold_parse_tree.<locals>.<genexpr>�unknown-8bitr�r7r�r_)�max_line_length�sys�maxsize�utf8r
rr�r
rDr�rVr_r�r{r-�_fold_mime_parametersr1rIr;r�rr�rkrE�_fold_as_ewrJr0�insertr%)�
parse_treer8�maxlenr�r��last_ewr��
want_encoding�end_ew_not_allowedr�r2�tstrrc�encoded_part�newline�newpartsrrrr9�
s�


�



��
r9cCs�|dk	r<|r<tt|d|d�|��}|dd|�|d<|dtkr�|d}|dd�}t|d�|krz|�t|��|d|7<d}|dtkr�|d}|dd�}|dkr�t|d�n|}|dkr�dn|}	t|	�d}
|
d|kr�t�d	��|�r�|t|d�}||
}|dk�r,|�d
�q�|d|�}
tj	|
|	d�}t|�|}|dk�r�|
dd�}
tj	|
|	d�}t|�|}�qR|d|7<|t|
�d�}|r�|�d
�t|d�}q�|d|7<|�r�|SdS)a�Fold string to_encode into lines as encoded word, combining if allowed.
    Return the new value for last_ew, or None if ew_combine_allowed is False.

    If there is already an encoded word in the last line of lines (indicated by
    a non-None value for last_ew) and ew_combine_allowed is true, decode the
    existing ew, combine it with to_encode, and re-encode.  Otherwise, encode
    to_encode.  In either case, split to_encode as necessary so that the
    encoded segments fit within maxlen.

    Nr�rr�rr�r��z3max_line_length is too small to fit an encoded wordrO)rc)
r
r@r4r�rkr�rr/r1r_)�	to_encoder�r�r�rJrc�leading_wsp�trailing_wsp�new_last_ew�	encode_as�
chrome_len�remaining_space�
text_space�to_encode_word�encoded_word�excessrrrr�1sT��



r�c	Cs�|jD�]�\}}|d���d�s2|dd7<|}d}z|�|�d}Wn0tk
r|d}t�|�rtd}d}nd}YnX|r�tjj	|d	|d
�}	d�
|||	�}
nd�
|t|��}
t|d�t|
�d
|kr�|dd|
|d<qn"t|
�d|k�r
|�
d|
�qd}|d}|rt|�tt|��dt|�}
||
dk�rLd}||
d}}|d|�}tjj	|d	|d
�}	t|	�|k�r��q�|d
8}�q\|�
d�
||||	��d	}|d
7}||d�}|�r|dd7<�qqdS)a>Fold TokenList 'part' into the 'lines' list as mime parameters.

    Using the decoded list of parameters and values, format them according to
    the RFC rules, including using RFC2231 encoding if the value cannot be
    expressed in 'encoding' and/or the parameter+value is too long to fit
    within 'maxlen'.

    r�r�strictFTr�r�r�r)�saferz
{}*={}''{}r�r�rOr�rz''r��NNz {}*{}*={}{})r�r�r�r_r�rr�r�r�rrr*rr�rkr
)r2r�r�r�r�rrc�
error_handler�encoding_required�
encoded_valuer�r��extra_chromer��
splitpoint�maxchars�partialrrrr�rsn


� ��r�)�r�rer�r��stringr�operatorr�emailrr1rrr�r4rLrVrPr�rY�	TSPECIALSr��	ASPECIALSr�r�r�compile�VERBOSE�	MULTILINEr;rrrMrSrVrXrZr\r^r`rerprqrtr~r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rrrrrrr
r
rrrr/rr�rprqr*r%r�rr$�matchrF�findallrr�r�r�rr'r*r9r@rCrDrHrJrKrMrOrQrSrUrXr[rbr^rerirkrlrnrsrwrxrzr|r~r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r9r�r�rrrr�<module>s.E
�C"	
!*$
V	+





����
1C+
"&'/'&).9%7ED49/gA�:�h�/bytecode of module 'email._header_value_parser'�u��b.���0h)��N}�(hB�0�@s�dZddddgZddlZddlZdZdZd	Zd
ddd
dddddddddddddddddddd gZd!d"d#d$d%d&d'gZddddd(d)d*d(d+d*d,d+d-d,d.�Z	d/d�Z
d0d1�Zd2d�Zd3d�Z
d4d�ZGd5d6�d6�ZGd7d8�d8e�ZdS)9zcEmail address parsing code.

Lifted directly from rfc822.py.  This should eventually be rewritten.
�	mktime_tz�	parsedate�parsedate_tz�quote�N� �z, �jan�feb�mar�apr�may�jun�jul�aug�sep�oct�nov�dec�january�february�march�april�june�july�august�	september�october�november�december�mon�tue�wed�thu�fri�sat�sunip���i���i���i����iD���i��)�UT�UTC�GMT�Z�AST�ADT�EST�EDT�CST�CDT�MST�MDT�PST�PDTcCs,t|�}|sdS|ddkr$d|d<t|�S)zQConvert a date string to a time tuple.

    Accounts for military timezones.
    N�	r)�
_parsedate_tz�tuple)�data�res�r9�&/usr/lib/python3.8/email/_parseaddr.pyr-sc
Cs�|sdS|��}|d�d�s.|d��tkr6|d=n.|d�d�}|dkrd|d|dd�|d<t|�dkr�|d�d�}t|�dkr�||dd�}t|�dkr�|d}|�d�}|d	kr�|�d�}|dkr�|d|�||d�g|dd�<n
|�d
�t|�dk�rdS|dd�}|\}}}}}|��}|tk�rX||��}}|tk�rXdSt�	|�d}|dk�rx|d8}|d	dk�r�|dd	�}|�d
�}|dk�r�||}}|d	dk�r�|dd	�}|d�
��s�||}}|d	dk�r�|dd	�}|�d
�}t|�dk�r"|\}	}
d}n~t|�dk�r<|\}	}
}ndt|�dk�r�d|dk�r�|d�d�}t|�dk�r�|\}	}
d}nt|�dk�r�|\}	}
}ndSz,t|�}t|�}t|	�}	t|
�}
t|�}Wntk
�r�YdSX|dk�r|dk�r|d7}n|d7}d}|�
�}|tk�r,t|}n>zt|�}Wntk
�rNYnX|dk�rj|�d��rjd}|�r�|dk�r�d	}
|}nd}
|
|dd|dd}||||	|
|ddd	|g
S)a�Convert date to extended time tuple.

    The last (additional) element is the time zone offset in seconds, except if
    the timezone was specified as -0000.  In that case the last element is
    None.  This indicates a UTC timestamp that explicitly declaims knowledge of
    the source timezone, as opposed to a +0000 timestamp that indicates the
    source timezone really was UTC.

    Nr�,���-��+���r���:��0�.�d�Dili�i�<)�split�endswith�lower�	_daynames�rfind�len�find�append�_monthnames�index�isdigit�int�
ValueError�upper�
_timezones�
startswith)r7�i�stuff�s�dd�mm�yy�tm�tz�thh�tmm�tss�tzoffset�tzsignr9r9r:r59s�


"














r5cCs&t|�}t|t�r|dd�S|SdS)z&Convert a time string to a time tuple.Nr4)r�
isinstancer6�r7�tr9r9r:r�s
cCs<|ddkr"t�|dd�d�St�|�}||dSdS)zETurn a 10-tuple as returned by parsedate_tz() into a POSIX timestamp.r4N�)rA)�time�mktime�calendar�timegmrir9r9r:r�s
cCs|�dd��dd�S)z�Prepare string to be used in a quoted string.

    Turns backslash and double quote characters into quoted pairs.  These
    are the only characters that need to be quoted inside a quoted string.
    Does not add the surrounding double quotes.
    �\z\\�"z\")�replace)�strr9r9r:r�sc@s|eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
ddd�Zdd�Zdd�Z
dd�Zddd�Zdd�ZdS) �
AddrlistClassaAddress parser class by Ben Escoto.

    To understand what this class does, it helps to have a copy of RFC 2822 in
    front of you.

    Note: this class interface is deprecated and may be removed in the future.
    Use email.utils.AddressList instead.
    cCsZd|_d|_d|_d|_|j|j|_|j|j|j|_|j�dd�|_||_g|_	dS)z�Initialize a new instance.

        `field' is an unparsed address header field, containing
        one or more addresses.
        z()<>@,:;."[]rz 	z
rGrN)
�specials�pos�LWS�CR�FWS�atomendsrr�
phraseends�field�commentlist��selfr|r9r9r:�__init__�szAddrlistClass.__init__cCs�g}|jt|j�kr�|j|j|jdkr\|j|jdkrL|�|j|j�|jd7_q|j|jdkr�|j�|���qq�qt�|�S)z&Skip white space and extract comments.z

r<�()	rvrPr|rwrRr}�
getcomment�EMPTYSTRING�join)r�wslistr9r9r:�gotonext�szAddrlistClass.gotonextcCs:g}|jt|j�kr6|��}|r*||7}q|�d�q|S)zVParse all addresses.

        Returns a list containing all of the addresses.
        )rr)rvrPr|�
getaddressrR)r�result�adr9r9r:�getaddrlist�s
zAddrlistClass.getaddrlistcCs�g|_|��|j}|j}|��}|��g}|jt|j�kr\|rXt�|j�|dfg}�n\|j|jdkr�||_||_|��}t�|j�|fg}�n"|j|jdk�rg}t|j�}|jd7_|jt|j�k�r�|��|j|k�r|j|jdk�r|jd7_�q�||�	�}q�n�|j|jdk�rx|�
�}|j�rft�|�dd�|j�d	|fg}nt�|�|fg}n@|�r�t�|j�|dfg}n"|j|j|jk�r�|jd7_|��|jt|j�k�r�|j|jd
k�r�|jd7_|S)zParse the next address.rz.@rDr<�;�<z (r�)r;)r}r�rv�
getphraselistrPr|�SPACEr��getaddrspecr��getrouteaddrru)r�oldpos�oldcl�plist�
returnlist�addrspec�fieldlen�	routeaddrr9r9r:r�sX

���$zAddrlistClass.getaddresscCs�|j|jdkrdSd}|jd7_|��d}|jt|j�kr�|rT|��d}n~|j|jdkrv|jd7_q�n\|j|jdkr�|jd7_d}n8|j|jd	kr�|jd7_n|��}|jd7_q�|��q2|S)
z�Parse a route address (Return-path value).

        This method just skips all the route stuff and returns the addrspec.
        r�NFr<r�>�@TrD)r|rvr�rP�	getdomainr�)r�expectroute�adlistr9r9r:r�?s.
zAddrlistClass.getrouteaddrcCsTg}|��|jt|j�kr�d}|j|jdkrf|rH|d��sH|��|�d�|jd7_d}nd|j|jdkr�|�dt|����n<|j|j|j	kr�|r�|d��s�|��q�n|�|�
��|��}|r|r|�|�q|jt|j�k�s
|j|jdk�rt�|�S|�d�|jd7_|��|�
�}|�sFtSt�|�|S)	zParse an RFC 2822 addr-spec.TrGrAr<Frqz"%s"r�)r�rvrPr|�strip�poprRr�getquoterz�getatomr�r�r�)r�aslist�preserve_ws�ws�domainr9r9r:r�_s:
$

zAddrlistClass.getaddrspeccCs�g}|jt|j�kr�|j|j|jkr6|jd7_q|j|jdkrX|j�|���q|j|jdkrx|�|���q|j|jdkr�|jd7_|�d�q|j|jdkr�tS|j|j|j	kr�q�q|�|�
��qt�|�S)z-Get the complete domain name from an address.r<r��[rGr�)rvrPr|rwr}rRr��getdomainliteralr�rzr�r�)r�sdlistr9r9r:r��s"zAddrlistClass.getdomainTcCs�|j|j|krdSdg}d}|jd7_|jt|j�kr�|rX|�|j|j�d}np|j|j|krz|jd7_q�nN|r�|j|jdkr�|�|���q,n(|j|jdkr�d}n|�|j|j�|jd7_q,t�|�S)a�Parse a header fragment delimited by special characters.

        `beginchar' is the start character for the fragment.
        If self is not looking at an instance of `beginchar' then
        getdelimited returns the empty string.

        `endchars' is a sequence of allowable end-delimiting characters.
        Parsing stops when one of these is encountered.

        If `allowcomments' is non-zero, embedded RFC 2822 comments are allowed
        within the parsed fragment.
        rFr<r�rpT)r|rvrPrRr�r�r�)r�	beginchar�endchars�
allowcomments�slistrr9r9r:�getdelimited�s(
zAddrlistClass.getdelimitedcCs|�ddd�S)z1Get a quote-delimited fragment from self's field.rqz"
F�r��rr9r9r:r��szAddrlistClass.getquotecCs|�ddd�S)z7Get a parenthesis-delimited fragment from self's field.r�z)
Tr�r�r9r9r:r��szAddrlistClass.getcommentcCsd|�ddd�S)z!Parse an RFC 2822 domain-literal.z[%s]r�z]
Fr�r�r9r9r:r��szAddrlistClass.getdomainliteralNcCsddg}|dkr|j}|jt|j�krZ|j|j|kr8qZn|�|j|j�|jd7_qt�|�S)aParse an RFC 2822 atom.

        Optional atomends specifies a different set of end token delimiters
        (the default is to use self.atomends).  This is used e.g. in
        getphraselist() since phrase endings must not include the `.' (which
        is legal in phrases).rNr<)rzrvrPr|rRr�r�)rrz�atomlistr9r9r:r��szAddrlistClass.getatomcCs�g}|jt|j�kr�|j|j|jkr6|jd7_q|j|jdkrV|�|���q|j|jdkrx|j�|���q|j|j|jkr�q�q|�|�	|j��q|S)z�Parse a sequence of RFC 2822 phrases.

        A phrase is a sequence of words, which are in turn either RFC 2822
        atoms or quoted-strings.  Phrases are canonicalized by squeezing all
        runs of continuous whitespace into one space.
        r<rqr�)
rvrPr|ryrRr�r}r�r{r�)rr�r9r9r:r��szAddrlistClass.getphraselist)T)N)�__name__�
__module__�__qualname__�__doc__r�r�r�r�r�r�r�r�r�r�r�r�r�r9r9r9r:rt�s	; &
%
rtc@sHeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dS)�AddressListz@An AddressList encapsulates a list of parsed RFC 2822 addresses.cCs&t�||�|r|��|_ng|_dS�N)rtr�r��addresslistr~r9r9r:r��szAddressList.__init__cCs
t|j�Sr�)rPr�r�r9r9r:�__len__szAddressList.__len__cCs>td�}|jdd�|_|jD]}||jkr|j�|�q|Sr��r�r�rR�r�other�newaddr�xr9r9r:�__add__s

zAddressList.__add__cCs&|jD]}||jkr|j�|�q|Sr�)r�rR�rr�r�r9r9r:�__iadd__
s

zAddressList.__iadd__cCs.td�}|jD]}||jkr|j�|�q|Sr�r�r�r9r9r:�__sub__s


zAddressList.__sub__cCs&|jD]}||jkr|j�|�q|Sr�)r��remover�r9r9r:�__isub__s

zAddressList.__isub__cCs
|j|Sr�)r�)rrTr9r9r:�__getitem__#szAddressList.__getitem__N)r�r�r�r�r�r�r�r�r�r�r�r9r9r9r:r��s	r�)r��__all__rlrnr�r��
COMMASPACErSrNrYrr5rrrrtr�r9r9r9r:�<module>sd���	u	

/�h�%bytecode of module 'email._parseaddr'�u��b.��:h)��N}�(hB�9�@s�dZddlZddlmZddlmZddlmZdddgZGd	d
�d
�Z	dd�Z
d
d�ZGdd�de	ejd�Z
eGdd�de
��Ze�ZdS)zwPolicy framework for the email package.

Allows fine grained feature control of how the package parses and emits data.
�N)�header)�charset)�_has_surrogates�Policy�Compat32�compat32cs@eZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Z�Z	S)�_PolicyBasea�Policy Object basic framework.

    This class is useless unless subclassed.  A subclass should define
    class attributes with defaults for any values that are to be
    managed by the Policy object.  The constructor will then allow
    non-default values to be set for these attributes at instance
    creation time.  The instance will be callable, taking these same
    attributes keyword arguments, and returning a new instance
    identical to the called instance except for those values changed
    by the keyword arguments.  Instances may be added, yielding new
    instances with any non-default values from the right hand
    operand overriding those in the left hand operand.  That is,

        A + B == A(<non-default values of B>)

    The repr of an instance can be used to reconstruct the object
    if and only if the repr of the values can be used to reconstruct
    those values.

    csH|��D]:\}}t||�r.tt|��||�qtd�||jj���qdS)z�Create new Policy, possibly overriding some defaults.

        See class docstring for a list of overridable attributes.

        �*{!r} is an invalid keyword argument for {}N)	�items�hasattr�superr�__setattr__�	TypeError�format�	__class__�__name__)�self�kw�name�value�r��'/usr/lib/python3.8/email/_policybase.py�__init__)s
��z_PolicyBase.__init__cCs*dd�|j��D�}d�|jjd�|��S)NcSsg|]\}}d�||��qS)z{}={!r})r)�.0rrrrr�
<listcomp>8s�z(_PolicyBase.__repr__.<locals>.<listcomp>z{}({})z, )�__dict__r
rrr�join)r�argsrrr�__repr__7s�z_PolicyBase.__repr__cKsr|j�|j�}|j��D]\}}t�|||�q|��D]4\}}t||�s^td�||jj	���t�|||�q8|S)z�Return a new instance with specified attributes changed.

        The new instance has the same attribute values as the current object,
        except for the changes passed in as keyword arguments.

        r	)
r�__new__rr
�objectr
rrrr)rr�	newpolicy�attrrrrr�clone<s
��z_PolicyBase.clonecCs,t||�rd}nd}t|�|jj|���dS)Nz'{!r} object attribute {!r} is read-onlyz!{!r} object has no attribute {!r})r�AttributeErrorrrr)rrr�msgrrrr
Ns
z_PolicyBase.__setattr__cCs|jf|j�S)z�Non-default values from right operand override those from left.

        The object returned is a new instance of the subclass.

        )r$r)r�otherrrr�__add__Usz_PolicyBase.__add__)
r�
__module__�__qualname__�__doc__rrr$r
r(�
__classcell__rrrrrsrcCs,|�dd�d}|�dd�d}|d|S)N�
�r)�rsplit�split)�doc�	added_docrrr�_append_doc^sr3cCs�|jr(|j�d�r(t|jdj|j�|_|j��D]V\}}|jr2|j�d�r2dd�|jD�D]*}tt||�d�}|r\t||j�|_q2q\q2|S)N�+rcss |]}|��D]
}|VqqdS)N)�mro)r�base�crrr�	<genexpr>hs
z%_extend_docstrings.<locals>.<genexpr>r+)r+�
startswithr3�	__bases__rr
�getattr)�clsrr#r7r1rrr�_extend_docstringscsr=c@s�eZdZdZdZdZdZdZdZdZ	dd�Z
d	d
�Zdd�Ze
jd
d��Ze
jdd��Ze
jdd��Ze
jdd��Ze
jdd��ZdS)raI	Controls for how messages are interpreted and formatted.

    Most of the classes and many of the methods in the email package accept
    Policy objects as parameters.  A Policy object contains a set of values and
    functions that control how input is interpreted and how output is rendered.
    For example, the parameter 'raise_on_defect' controls whether or not an RFC
    violation results in an error being raised or not, while 'max_line_length'
    controls the maximum length of output lines when a Message is serialized.

    Any valid attribute may be overridden when a Policy is created by passing
    it as a keyword argument to the constructor.  Policy objects are immutable,
    but a new Policy object can be created with only certain values changed by
    calling the Policy instance with keyword arguments.  Policy objects can
    also be added, producing a new Policy object in which the non-default
    attributes set in the right hand operand overwrite those specified in the
    left operand.

    Settable attributes:

    raise_on_defect     -- If true, then defects should be raised as errors.
                           Default: False.

    linesep             -- string containing the value to use as separation
                           between output lines.  Default '\n'.

    cte_type            -- Type of allowed content transfer encodings

                           7bit  -- ASCII only
                           8bit  -- Content-Transfer-Encoding: 8bit is allowed

                           Default: 8bit.  Also controls the disposition of
                           (RFC invalid) binary data in headers; see the
                           documentation of the binary_fold method.

    max_line_length     -- maximum length of lines, excluding 'linesep',
                           during serialization.  None or 0 means no line
                           wrapping is done.  Default is 78.

    mangle_from_        -- a flag that, when True escapes From_ lines in the
                           body of the message by putting a `>' in front of
                           them. This is used when the message is being
                           serialized by a generator. Default: True.

    message_factory     -- the class to use to create new message objects.
                           If the value is None, the default is Message.

    Fr-�8bit�NNcCs|jr
|�|�||�dS)aZBased on policy, either raise defect or call register_defect.

            handle_defect(obj, defect)

        defect should be a Defect subclass, but in any case must be an
        Exception subclass.  obj is the object on which the defect should be
        registered if it is not raised.  If the raise_on_defect is True, the
        defect is raised as an error, otherwise the object and the defect are
        passed to register_defect.

        This method is intended to be called by parsers that discover defects.
        The email package parsers always call it with Defect instances.

        N)�raise_on_defect�register_defect�r�obj�defectrrr�
handle_defect�szPolicy.handle_defectcCs|j�|�dS)a�Record 'defect' on 'obj'.

        Called by handle_defect if raise_on_defect is False.  This method is
        part of the Policy API so that Policy subclasses can implement custom
        defect handling.  The default implementation calls the append method of
        the defects attribute of obj.  The objects used by the email package by
        default that get passed to this method will always have a defects
        attribute with an append method.

        N)�defects�appendrBrrrrA�szPolicy.register_defectcCsdS)a[Return the maximum allowed number of headers named 'name'.

        Called when a header is added to a Message object.  If the returned
        value is not 0 or None, and there are already a number of headers with
        the name 'name' equal to the value returned, a ValueError is raised.

        Because the default behavior of Message's __setitem__ is to append the
        value to the list of headers, it is easy to create duplicate headers
        without realizing it.  This method allows certain headers to be limited
        in the number of instances of that header that may be added to a
        Message programmatically.  (The limit is not observed by the parser,
        which will faithfully produce as many headers as exist in the message
        being parsed.)

        The default implementation returns None for all header names.
        Nr)rrrrr�header_max_count�szPolicy.header_max_countcCst�dS)aZGiven a list of linesep terminated strings constituting the lines of
        a single header, return the (name, value) tuple that should be stored
        in the model.  The input lines should retain their terminating linesep
        characters.  The lines passed in by the email package may contain
        surrogateescaped binary data.
        N��NotImplementedError)r�sourcelinesrrr�header_source_parse�szPolicy.header_source_parsecCst�dS)z�Given the header name and the value provided by the application
        program, return the (name, value) that should be stored in the model.
        NrI�rrrrrr�header_store_parse�szPolicy.header_store_parsecCst�dS)awGiven the header name and the value from the model, return the value
        to be returned to the application program that is requesting that
        header.  The value passed in by the email package may contain
        surrogateescaped binary data if the lines were parsed by a BytesParser.
        The returned value should not contain any surrogateescaped data.

        NrIrMrrr�header_fetch_parse�s	zPolicy.header_fetch_parsecCst�dS)a�Given the header name and the value from the model, return a string
        containing linesep characters that implement the folding of the header
        according to the policy controls.  The value passed in by the email
        package may contain surrogateescaped binary data if the lines were
        parsed by a BytesParser.  The returned value should not contain any
        surrogateescaped data.

        NrIrMrrr�fold�s
zPolicy.foldcCst�dS)a%Given the header name and the value from the model, return binary
        data containing linesep characters that implement the folding of the
        header according to the policy controls.  The value passed in by the
        email package may contain surrogateescaped binary data.

        NrIrMrrr�fold_binaryszPolicy.fold_binary)rr)r*r+r@�linesep�cte_type�max_line_length�mangle_from_�message_factoryrErArH�abc�abstractmethodrLrNrOrPrQrrrrrps(0

	



)�	metaclassc@sLeZdZdZdZdd�Zdd�Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�ZdS)rz�+
    This particular policy is the backward compatibility Policy.  It
    replicates the behavior of the email package version 5.1.
    TcCs0t|t�s|St|�r(tj|tj|d�S|SdS)N�r�header_name)�
isinstance�strrr�Header�_charset�UNKNOWN8BITrMrrr�_sanitize_headers

�zCompat32._sanitize_headercCs>|d�dd�\}}|�d�d�|dd��}||�d�fS)a:+
        The name is parsed as everything up to the ':' and returned unmodified.
        The value is determined by stripping leading whitespace off the
        remainder of the first line, joining all subsequent lines together, and
        stripping any trailing carriage return or linefeed characters.

        r�:r.z 	�Nz
)r0�lstripr�rstrip)rrKrrrrrrL%szCompat32.header_source_parsecCs||fS)z>+
        The name and value are returned unmodified.
        rrMrrrrN1szCompat32.header_store_parsecCs|�||�S)z�+
        If the value contains binary data, it is converted into a Header object
        using the unknown-8bit charset.  Otherwise it is returned unmodified.
        )rarMrrrrO7szCompat32.header_fetch_parsecCs|j||dd�S)a+
        Headers are folded using the Header folding algorithm, which preserves
        existing line breaks in the value, and wraps each resulting line to the
        max_line_length.  Non-ASCII binary data are CTE encoded using the
        unknown-8bit charset.

        T��sanitize)�_foldrMrrrrP>sz
Compat32.foldcCs"|j|||jdkd�}|�dd�S)a�+
        Headers are folded using the Header folding algorithm, which preserves
        existing line breaks in the value, and wraps each resulting line to the
        max_line_length.  If cte_type is 7bit, non-ascii binary data is CTE
        encoded using the unknown-8bit charset.  Otherwise the original source
        header is used, with its existing line breaks and/or binary data.

        �7bitrf�ascii�surrogateescape)rhrS�encode)rrr�foldedrrrrQHs	zCompat32.fold_binarycCs�g}|�d|�t|t�r\t|�rL|r<tj|tj|d�}qZ|�|�d}q`tj||d�}n|}|dk	r�d}|jdk	r||j}|�|j	|j
|d��|�|j
�d�|�S)Nz%s: rZ)r[r)rR�
maxlinelenrc)rGr\r]rrr^r_r`rTrlrRr)rrrrg�parts�hrnrrrrhTs(
�


zCompat32._foldN)rr)r*r+rUrarLrNrOrPrQrhrrrrrs
)r+rW�emailrrr_�email.utilsr�__all__rr3r=�ABCMetarrrrrrr�<module>s �L
 f�h�&bytecode of module 'email._policybase'�u��b.���h)��N}�(hB��@stdZddddddgZddlmZdd	lmZmZd
ZdZdZ	d
Z
dd�Zddd�Zdefdd�Z
dd�ZeZeZdS)a�Base64 content transfer encoding per RFCs 2045-2047.

This module handles the content transfer encoding method defined in RFC 2045
to encode arbitrary 8-bit data using the three 8-bit bytes in four 7-bit
characters encoding known as Base64.

It is used in the MIME standards for email to attach images, audio, and text
using some 8-bit character sets to messages.

This module provides an interface to encode and decode both headers and bodies
with Base64 encoding.

RFC 2045 defines a method for including character set information in an
`encoded-word' in a header.  This method is commonly used for 8-bit real names
in To:, From:, Cc:, etc. fields, as well as Subject: lines.

This module does not do the line wrapping or end-of-line character conversion
necessary for proper internationalized headers; it only does dumb encoding and
decoding.  To deal with the various line wrapping issues, use the email.header
module.
�body_decode�body_encode�decode�decodestring�
header_encode�
header_length�)�	b64encode)�
b2a_base64�
a2b_base64z
�
��cCs*tt|�d�\}}|d}|r&|d7}|S)z6Return the length of s when it is encoded with base64.��)�divmod�len)�	bytearray�groups_of_3�leftover�n�r�&/usr/lib/python3.8/email/base64mime.pyr2s
�
iso-8859-1cCs6|sdSt|t�r|�|�}t|��d�}d||fS)z�Encode a single header line with Base64 encoding in a given charset.

    charset names the character set to use to encode the header.  It defaults
    to iso-8859-1.  Base64 encoding is defined in RFC 2045.
    r�asciiz=?%s?b?%s?=)�
isinstance�str�encoderr)�header_bytes�charset�encodedrrrr=s

�LcCs~|s|Sg}|dd}tdt|�|�D]J}t||||���d�}|�t�rh|tkrh|dd�|}|�|�q(t�|�S)a1Encode a string with base64.

    Each line will be wrapped at, at most, maxlinelen characters (defaults to
    76 characters).

    Each line of encoded text will end with eol, which defaults to "\n".  Set
    this to "\r\n" if you will be using the result of this function directly
    in an email.
    rrrrN���)	�rangerr	r�endswith�NL�append�EMPTYSTRING�join)�s�
maxlinelen�eol�encvec�
max_unencoded�i�encrrrrLs
cCs.|s
t�St|t�r"t|�d��St|�SdS)z�Decode a raw base64 string, returning a bytes object.

    This function does not parse a full MIME header value encoded with
    base64 (like =?iso-8859-1?b?bmloISBuaWgh?=) -- please use the high
    level email.header class for that functionality.
    zraw-unicode-escapeN)�bytesrrr
r)�stringrrrrfs

N)r)�__doc__�__all__�base64r�binasciir	r
�CRLFr$r&�MISC_LENrrrrrrrrrr�<module>s&�

�h�%bytecode of module 'email.base64mime'�u��b.���,h)��N}�(hB�,�@srddddgZddlmZddlZddlZddlmZddlmZd	Z	d
Z
dZdZd
Z
dZdZe	e	dfe	e	dfe	e	dfe	e	dfe	e	dfe	e	dfe	e	dfe	e	dfe	e	dfe	e	dfe	e	dfe	e	dfde
e
dfe
e
dfe
ddfe
ddfe
ddfe
e
dfee
dfd�Zddddddddddddddddddddddd d
d!�Zd"d#dd$�Zd+d%d�Zd&d�Zd'd�Zd(d)�ZGd*d�d�ZdS),�Charset�	add_alias�add_charset�	add_codec�)�partialN)�errors)�encode_7or8bit�����us-asciizunknown-8bit�)NNN�iso-2022-jp�utf-8)�
iso-8859-1�
iso-8859-2�
iso-8859-3�
iso-8859-4�
iso-8859-9�iso-8859-10�iso-8859-13�iso-8859-14�iso-8859-15�iso-8859-16zwindows-1252�visciir
�big5�gb2312�euc-jp�	shift_jisrzkoi8-rrrrrrrrrrrrzks_c_5601-1987rzeuc-kr)�latin_1zlatin-1�latin_2zlatin-2�latin_3zlatin-3�latin_4zlatin-4�latin_5zlatin-5�latin_6zlatin-6�latin_7zlatin-7�latin_8zlatin-8�latin_9zlatin-9�latin_10zlatin-10�cp949�euc_jp�euc_kr�ascii�eucgb2312_cn�big5_tw)rrr
cCs"|tkrtd��|||ft|<dS)a>Add character set properties to the global registry.

    charset is the input character set, and must be the canonical name of a
    character set.

    Optional header_enc and body_enc is either Charset.QP for
    quoted-printable, Charset.BASE64 for base64 encoding, Charset.SHORTEST for
    the shortest of qp or base64 encoding, or None for no encoding.  SHORTEST
    is only valid for header_enc.  It describes how message headers and
    message bodies in the input charset are to be encoded.  Default is no
    encoding.

    Optional output_charset is the character set that the output should be
    in.  Conversions will proceed from input charset, to Unicode, to the
    output charset when the method Charset.convert() is called.  The default
    is to output in the same character set as the input.

    Both input_charset and output_charset must have Unicode codec entries in
    the module's charset-to-codec mapping; use add_codec(charset, codecname)
    to add codecs the module does not know about.  See the codecs module's
    documentation for more information.
    z!SHORTEST not allowed for body_encN)�SHORTEST�
ValueError�CHARSETS)�charset�
header_enc�body_enc�output_charset�r7�#/usr/lib/python3.8/email/charset.pyrmscCs|t|<dS)z�Add a character set alias.

    alias is the alias name, e.g. latin-1
    canonical is the character set's canonical name, e.g. iso-8859-1
    N)�ALIASES)�alias�	canonicalr7r7r8r�scCs|t|<dS)a$Add a codec that map characters in the given charset to/from Unicode.

    charset is the canonical name of a character set.  codecname is the name
    of a Python codec, as appropriate for the second argument to the unicode()
    built-in, or to the encode() method of a Unicode string.
    N)�	CODEC_MAP)r3�	codecnamer7r7r8r�scCs"|tkr|�dd�S|�|�SdS)Nr-�surrogateescape)�UNKNOWN8BIT�encode)�string�codecr7r7r8�_encode�srCc@s\eZdZdZefdd�Zdd�Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dS)ra@	Map character sets to their email properties.

    This class provides information about the requirements imposed on email
    for a specific character set.  It also provides convenience routines for
    converting between character sets, given the availability of the
    applicable codecs.  Given a character set, it will do its best to provide
    information on how to use that character set in an email in an
    RFC-compliant way.

    Certain character sets must be encoded with quoted-printable or base64
    when used in email headers or bodies.  Certain character sets must be
    converted outright, and are not allowed in email.  Instances of this
    module expose the following information about a character set:

    input_charset: The initial character set specified.  Common aliases
                   are converted to their `official' email names (e.g. latin_1
                   is converted to iso-8859-1).  Defaults to 7-bit us-ascii.

    header_encoding: If the character set must be encoded before it can be
                     used in an email header, this attribute will be set to
                     Charset.QP (for quoted-printable), Charset.BASE64 (for
                     base64 encoding), or Charset.SHORTEST for the shortest of
                     QP or BASE64 encoding.  Otherwise, it will be None.

    body_encoding: Same as header_encoding, but describes the encoding for the
                   mail message's body, which indeed may be different than the
                   header encoding.  Charset.SHORTEST is not allowed for
                   body_encoding.

    output_charset: Some character sets must be converted before they can be
                    used in email headers or bodies.  If the input_charset is
                    one of them, this attribute will contain the name of the
                    charset output will be converted to.  Otherwise, it will
                    be None.

    input_codec: The name of the Python codec used to convert the
                 input_charset to Unicode.  If no conversion codec is
                 necessary, this attribute will be None.

    output_codec: The name of the Python codec used to convert Unicode
                  to the output_charset.  If no conversion codec is necessary,
                  this attribute will have the same value as the input_codec.
    cCs�z$t|t�r|�d�n
t|d�}Wntk
rBt�|��YnX|��}t�||�|_	t
�|j	ttdf�\}}}|s~|j	}||_
||_t�||�|_t�|j	|j	�|_t�|j|j�|_dS)Nr-)�
isinstance�strr@�UnicodeErrorr�CharsetError�lowerr9�get�
input_charsetr2r0�BASE64�header_encoding�
body_encodingr6r<�input_codec�output_codec)�selfrJ�henc�benc�convr7r7r8�__init__�s,
�
��zCharset.__init__cCs
|j��S�N)rJrH�rPr7r7r8�__repr__�szCharset.__repr__cCst|�t|���kSrU)rErH)rP�otherr7r7r8�__eq__�szCharset.__eq__cCs2|jtkst�|jtkrdS|jtkr*dStSdS)aPReturn the content-transfer-encoding used for body encoding.

        This is either the string `quoted-printable' or `base64' depending on
        the encoding used, or it is a function in which case you should call
        the function with a single argument, the Message object being
        encoded.  The function should then set the Content-Transfer-Encoding
        header itself to whatever is appropriate.

        Returns "quoted-printable" if self.body_encoding is QP.
        Returns "base64" if self.body_encoding is BASE64.
        Returns conversion function otherwise.
        zquoted-printable�base64N)rMr0�AssertionError�QPrKrrVr7r7r8�get_body_encoding�s


zCharset.get_body_encodingcCs|jp
|jS)z�Return the output character set.

        This is self.output_charset if that is not None, otherwise it is
        self.input_charset.
        )r6rJrVr7r7r8�get_output_charsetszCharset.get_output_charsetcCs6|jpd}t||�}|�|�}|dkr*|S|�||�S)a�Header-encode a string by converting it first to bytes.

        The type of encoding (base64 or quoted-printable) will be based on
        this charset's `header_encoding`.

        :param string: A unicode string for the header.  It must be possible
            to encode this string to bytes using the character set's
            output codec.
        :return: The encoded string, with RFC 2047 chrome.
        r
N)rOrC�_get_encoder�
header_encode)rPrArB�header_bytes�encoder_moduler7r7r8r`s


zCharset.header_encodecCs|jpd}t||�}|�|�}t|j|d�}|��}t|�t}g}	g}
t|�|}|D]�}|
�	|�t
�|
�}
|�t|
|��}||krX|
�
�|	s�|
s�|	�	d�n.|	r�dnd}t
�|
�}t||�}|	�	||��|g}
t|�|}qXt
�|
�}t||�}|	�	||��|	S)afHeader-encode a string by converting it first to bytes.

        This is similar to `header_encode()` except that the string is fit
        into maximum line lengths as given by the argument.

        :param string: A unicode string for the header.  It must be possible
            to encode this string to bytes using the character set's
            output codec.
        :param maxlengths: Maximum line length iterator.  Each element
            returned from this iterator will provide the next maximum line
            length.  This parameter is used as an argument to built-in next()
            and should never be exhausted.  The maximum line lengths should
            not count the RFC 2047 chrome.  These line lengths are only a
            hint; the splitter does the best it can.
        :return: Lines of encoded strings, each with RFC 2047 chrome.
        r
)r3N� r)rOrCr_rr`r^�len�RFC2047_CHROME_LEN�next�append�EMPTYSTRING�join�
header_length�pop)rPrA�
maxlengthsrBrarb�encoderr3�extra�lines�current_line�maxlen�	character�	this_line�length�	separator�joined_liner7r7r8�header_encode_lines*s6








zCharset.header_encode_linescCs`|jtkrtjS|jtkr tjS|jtkrXtj�|�}tj�|�}||krPtjStjSndSdSrU)rLrK�email�
base64mimer\�
quoprimimer0rj)rPra�len64�lenqpr7r7r8r_hs


zCharset._get_encodercCs�|s|S|jtkr4t|t�r(|�|j�}tj�|�S|jt	krjt|t�rT|�|j�}|�
d�}tj�|�St|t�r�|�|j��
d�}|SdS)avBody-encode a string by converting it first to bytes.

        The type of encoding (base64 or quoted-printable) will be based on
        self.body_encoding.  If body_encoding is None, we assume the
        output charset is a 7bit encoding, so re-encoding the decoded
        string using the ascii codec produces the correct string version
        of the content.
        �latin1r-N)rMrKrDrEr@r6rxry�body_encoder\�decoderz)rPrAr7r7r8r~ws	





zCharset.body_encodeN)�__name__�
__module__�__qualname__�__doc__�DEFAULT_CHARSETrTrWrYr]r^r`rwr_r~r7r7r7r8r�s+!>)NNN)�__all__�	functoolsr�email.base64mimerx�email.quoprimimer�email.encodersrr\rKr0rer�r?rhr2r9r<rrrrCrr7r7r7r8�<module>s��� ��
	
�h�"bytecode of module 'email.charset'�u��b.���h)��N}�(hB��@s.ddlZddlZddlZddlZddlmZGdd�d�Ze�Zd%dd�Ze�	de�d	d
�Z
d��D]Ze�	ee
�qfdd
�Z
d��D]Ze�	dee
�q�dd�Ze�	de�dd�Zdd�Zdd�Zdd�Zd&dd�Ze�ee�d'd d!�Ze�ejje�d(d#d$�ZeeefD]Ze�ee��qdS))�N)�
quoprimimec@s<eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
S)�ContentManagercCsi|_i|_dS�N)�get_handlers�set_handlers)�self�r�*/usr/lib/python3.8/email/contentmanager.py�__init__	szContentManager.__init__cCs||j|<dSr)r)r�key�handlerrrr	�add_get_handler
szContentManager.add_get_handlercOs||��}||jkr(|j||f|�|�S|��}||jkrP|j||f|�|�Sd|jkrp|jd|f|�|�St|��dS)N�)�get_content_typer�get_content_maintype�KeyError)r�msg�args�kw�content_type�maintyperrr	�get_contents


zContentManager.get_contentcCs||j|<dSr)r)r�typekeyrrrr	�add_set_handlerszContentManager.add_set_handlercOs>|��dkrtd��|�||�}|��|||f|�|�dS)N�	multipartz"set_content not valid on multipart)r�	TypeError�_find_set_handler�
clear_content)rr�objrrrrrr	�set_contents
zContentManager.set_contentc	Cs�d}t|�jD]�}||jkr*|j|S|j}t|dd�}|rNd�||f�n|}|dkr^|}||jkrv|j|S||jkr�|j|S|j}||jkr|j|Sqd|jkr�|jdSt|��dS)N�
__module__r�.)�type�__mro__r�__qualname__�getattr�join�__name__r)	rrr�full_path_for_error�typ�qname�modname�	full_path�namerrr	r's&





z ContentManager._find_set_handlerN)	r'r r$r
r
rrrrrrrr	rs	r�replacecCs&|jdd�}|�dd�}|j||d�S)NT��decode�charset�ASCII)�errors)�get_payload�	get_paramr0)rr3�contentr1rrr	�get_text_content@sr7�textcCs|jdd�S)NTr/�r4�rrrr	�get_non_text_contentGsr;zaudio image video applicationcCs
|�d�S�Nrr9r:rrr	�get_message_contentMsr=zrfc822 external-bodyzmessage/cCst|�d��Sr<)�bytesr4r:rrr	�%get_and_fixup_unknown_message_contentSsr?�messagec
s�d�||f�|d<|r�t|dd�s<|j��fdd�|D�}z(|D]}|jrV|jd�|||j<qBWn@tjjk
r�}ztd�	|j
|jd���|�W5d}~XYnXdS)	N�/zContent-Typerr-csg|]}�j��|g���qSr)�header_factory�header_source_parse)�.0�header��mprr	�
<listcomp>ds�z _prepare_set.<locals>.<listcomp>zInvalid header: {})�policy)r&�hasattrrI�defectsr-�emailr3�HeaderDefect�
ValueError�format�fold)rr�subtype�headersrE�excrrFr	�_prepare_set_s$
�
��rTcCsx|dkr|dk	rd}|dk	r$||d<|dk	r>|jd|ddd�|dk	rN||d<|dk	rt|��D]\}}|�||�q^dS)N�
attachmentzContent-Disposition�filenameT)rEr.z
Content-ID)�	set_param�items)r�dispositionrV�cid�paramsr�valuerrr	�
_finalize_setps�r]cCsVg}|dd}tdt|�|�D]*}||||�}|�t�|��d��q d�|�S)N��r�asciir)�range�len�append�binascii�
b2a_base64r0r&)�data�max_line_length�
encoded_lines�unencoded_bytes_per_line�i�thislinerrr	�_encode_base64�srlcs�|�|���}|j�d���fdd�}dd�}|dkr�tdd�|D�dd	�|jkr�zd
||��d�fWStk
rzYnX|jdkr�d||��dd�fS||dd
��}t�	|�d�|j�}t
�|�}	t|�t|	�kr�d}nd}t|�d
kr�||fS|d
k�r||��d�}
nj|dk�r,||��dd�}
nN|dk�rPt�	||��d�|j�}
n*|dk�rlt
||�|j�}
ntd�|���||
fS)Nr`cs��|��Sr�r&��lines��lineseprr	�
embedded_body��z#_encode_text.<locals>.embedded_bodycSsd�|�dS)N�
rmrnrrr	�normal_body�rsz!_encode_text.<locals>.normal_bodycss|]}t|�VqdSr)rb)rD�xrrr	�	<genexpr>�sz_encode_text.<locals>.<genexpr>r)�default�7bit�8bit�surrogateescape�
zlatin-1�base64�quoted-printablez$Unknown content transfer encoding {})�encode�
splitlinesrq�maxrgr0�UnicodeDecodeError�cte_typer�body_encoderdrerbrlrNrO)�stringr1�cterIrorrru�sniff�sniff_qp�sniff_base64rfrrpr	�_encode_text�sD
�



�
r��plain�utf-8c
Csdt|d||	�t||||j�\}}
|�|
�|jdtjj�||�dd�||d<t	|||||�dS)Nr8r1T)r.�Content-Transfer-Encoding)
rTr�rI�set_payloadrWrLr1�ALIASES�getr])rr�rQr1r�rYrVrZr[rR�payloadrrr	�set_text_content�s
�r��rfc822c		Cs�|dkrtd��|dkr@|dkr.td�|���|dkr:dn|}n0|dkrd|dkr^td	�|���d
}n|dkrpd
}t|d||�|�|g�||d<t|||||�dS)
N�partialz4message/partial is not supported for Message objectsr�)Nryrz�binaryz*message/rfc822 parts do not support cte={}rzz
external-body)Nryz1message/external-body parts do not support cte={}ryr@r�)rNrOrTr�r])	rr@rQr�rYrVrZr[rRrrr	�set_message_content�s(��r�r}c

Cs�t||||	�|dkr(t||jjd�}nN|dkrNtj|dddd�}|�d�}n(|dkrb|�d�n|d	krv|�dd
�}|�|�||d<t	|||||�dS)Nr})rgr~FT)�istextrE�	quotetabsr`ry)rzr�r{r�)
rTrlrIrgrd�b2a_qpr0rr�r])
rrfrrQr�rYrVrZr[rRrrr	�set_bytes_content�s
r�)r.)r�r�NNNNNN)r�NNNNNN)r}NNNNN)rd�
email.charsetrL�
email.message�email.errorsrr�raw_data_managerr7r
r;�splitrr=rQr?rTr]rlr�r�r�strr�r@�Messager�r>�	bytearray�
memoryviewr)rrrr	�<module>s^6
�	'�
�
�
�h�)bytecode of module 'email.contentmanager'�u��b.��zh)��N}�(hB<�@sTdZddddgZddlmZddlmZdd	�Zd
d�Z	dd�Z
dd�Zd
d�ZdS)z Encodings and related functions.�encode_7or8bit�
encode_base64�encode_noop�
encode_quopri�)�encodebytes)�encodestringcCst|dd�}|�dd�S)NT)�	quotetabs� s=20)�
_encodestring�replace)�s�enc�r�$/usr/lib/python3.8/email/encoders.py�_qencodesrcCs0|jdd�}tt|�d�}|�|�d|d<dS)zlEncode the message's payload in Base64.

    Also, add an appropriate Content-Transfer-Encoding header.
    T��decode�ascii�base64�Content-Transfer-EncodingN)�get_payload�str�_bencode�set_payload��msg�orig�encdatarrrrs
cCs*|jdd�}t|�}|�|�d|d<dS)zvEncode the message's payload in quoted-printable.

    Also, add an appropriate Content-Transfer-Encoding header.
    Trzquoted-printablerN)rrrrrrrr&s
cCsX|jdd�}|dkr d|d<dSz|�d�Wntk
rJd|d<Yn
Xd|d<dS)z9Set the Content-Transfer-Encoding header to 7bit or 8bit.TrN�7bitrr�8bit)rr�UnicodeError)rrrrrr2scCsdS)zDo nothing.Nr)rrrrrDsN)
�__doc__�__all__rrr�quoprirr
rrrrrrrrr�<module>s��h�#bytecode of module 'email.encoders'�u��b.��=h)��N}�(hB�@s�dZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGd	d
�d
ee�ZGdd�de�ZGd
d�de	�Z
Gdd�de
�ZGdd�de
�ZGdd�de
�Z
Gdd�de
�ZGdd�de
�ZGdd�de
�ZeZGdd�de
�ZGdd�de
�ZGdd �d e
�ZGd!d"�d"e
�ZGd#d$�d$e
�ZGd%d&�d&e
�ZGd'd(�d(e
�ZGd)d*�d*e�ZGd+d,�d,e�ZGd-d.�d.e�ZGd/d0�d0e�ZGd1d2�d2e�Zd3S)4z email package exception classes.c@seZdZdZdS)�MessageErrorz+Base class for errors in the email package.N��__name__�
__module__�__qualname__�__doc__�rr�"/usr/lib/python3.8/email/errors.pyrsrc@seZdZdZdS)�MessageParseErrorz&Base class for message parsing errors.Nrrrrrr	sr	c@seZdZdZdS)�HeaderParseErrorzError while parsing headers.Nrrrrrr
sr
c@seZdZdZdS)�
BoundaryErrorz#Couldn't find terminating boundary.Nrrrrrrsrc@seZdZdZdS)�MultipartConversionErrorz(Conversion to a multipart is prohibited.Nrrrrrrsrc@seZdZdZdS)�CharsetErrorzAn illegal charset was given.Nrrrrrr
sr
cs"eZdZdZd�fdd�	Z�ZS)�
MessageDefectz Base class for a message defect.Ncs|dk	rt��|�||_dS�N)�super�__init__�line)�selfr��	__class__rrr$szMessageDefect.__init__)N�rrrrr�
__classcell__rrrrr!src@seZdZdZdS)�NoBoundaryInMultipartDefectzBA message claimed to be a multipart but had no boundary parameter.Nrrrrrr)src@seZdZdZdS)�StartBoundaryNotFoundDefectz+The claimed start boundary was never found.Nrrrrrr,src@seZdZdZdS)�CloseBoundaryNotFoundDefectzEA start boundary was found, but not the corresponding close boundary.Nrrrrrr/src@seZdZdZdS)�#FirstHeaderLineIsContinuationDefectz;A message had a continuation line as its first header line.Nrrrrrr2src@seZdZdZdS)�MisplacedEnvelopeHeaderDefectz?A 'Unix-from' header was found in the middle of a header block.Nrrrrrr5src@seZdZdZdS)� MissingHeaderBodySeparatorDefectzEFound line with no leading whitespace and no colon before blank line.Nrrrrrr8src@seZdZdZdS)�!MultipartInvariantViolationDefectz?A message claimed to be a multipart but no subparts were found.Nrrrrrr=src@seZdZdZdS)�-InvalidMultipartContentTransferEncodingDefectzEAn invalid content transfer encoding was set on the multipart itself.Nrrrrrr@src@seZdZdZdS)�UndecodableBytesDefectz0Header contained bytes that could not be decodedNrrrrrr Csr c@seZdZdZdS)�InvalidBase64PaddingDefectz/base64 encoded sequence had an incorrect lengthNrrrrrr!Fsr!c@seZdZdZdS)�InvalidBase64CharactersDefectz=base64 encoded sequence had characters not in base64 alphabetNrrrrrr"Isr"c@seZdZdZdS)�InvalidBase64LengthDefectz4base64 encoded sequence had invalid length (1 mod 4)Nrrrrrr#Lsr#cs eZdZdZ�fdd�Z�ZS)�HeaderDefectzBase class for a header defect.cst�j||�dSr)rr)r�args�kwrrrrTszHeaderDefect.__init__rrrrrr$Qsr$c@seZdZdZdS)�InvalidHeaderDefectz+Header is not valid, message gives details.Nrrrrrr'Wsr'c@seZdZdZdS)�HeaderMissingRequiredValuez(A header that must have a value had noneNrrrrrr(Zsr(cs(eZdZdZ�fdd�Zdd�Z�ZS)�NonPrintableDefectz8ASCII characters outside the ascii-printable range foundcst��|�||_dSr)rr�non_printables)rr*rrrr`szNonPrintableDefect.__init__cCsd�|j�S)Nz6the following ASCII non-printables found in header: {})�formatr*)rrrr�__str__ds�zNonPrintableDefect.__str__)rrrrrr,rrrrrr)]sr)c@seZdZdZdS)�ObsoleteHeaderDefectz0Header uses syntax declared obsolete by RFC 5322Nrrrrrr-hsr-c@seZdZdZdS)�NonASCIILocalPartDefectz(local_part contains non-ASCII charactersNrrrrrr.ksr.N)r�	Exceptionrr	r
r�	TypeErrorrr
�
ValueErrorrrrrrrr�MalformedHeaderDefectrrr r!r"r#r$r'r(r)r-r.rrrr�<module>s4�h�!bytecode of module 'email.errors'�u��b.���)h)��N}�(hB�)�@s�dZddgZddlZddlmZddlmZddlmZddl	m
Z
e�d	�Ze�d
�Z
e�d�Ze�d
�Ze�d�Zd
ZdZe�ZGdd�de�ZGdd�d�ZGdd�de�ZdS)aFeedParser - An email feed parser.

The feed parser implements an interface for incrementally parsing an email
message, line by line.  This has advantages for certain applications, such as
those reading email messages off a socket.

FeedParser.feed() is the primary interface for pushing new data into the
parser.  It returns when there's nothing more it can do with the available
data.  When you have no more data to push into the parser, call .close().
This completes the parsing and returns the root message object.

The other advantage of this parser is that it will never raise a parsing
exception.  Instead, when it finds something unexpected, it adds a 'defect' to
the current message.  Defects are just instances that live on the message
object's .defects attribute.
�
FeedParser�BytesFeedParser�N)�errors)�compat32)�deque)�StringIOz
\r\n|\r|\nz(\r\n|\r|\n)z(\r\n|\r|\n)\Zz%^(From |[\041-\071\073-\176]*:|[\t ])��
c@s`eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dS)�BufferedSubFileakA file-ish object that can have new data loaded into it.

    You can also push and pop line-matching predicates onto a stack.  When the
    current predicate matches the current line, a false EOF response
    (i.e. empty string) is returned instead.  This lets the parser adhere to a
    simple abstraction -- it parses until EOF closes the current message.
    cCs$tdd�|_t�|_g|_d|_dS)Nr)�newlineF)r�_partialr�_lines�	_eofstack�_closed��self�r�&/usr/lib/python3.8/email/feedparser.py�__init__5szBufferedSubFile.__init__cCs|j�|�dS�N)r�append)r�predrrr�push_eof_matcher@sz BufferedSubFile.push_eof_matchercCs
|j��Sr)r�poprrrr�pop_eof_matcherCszBufferedSubFile.pop_eof_matchercCs<|j�d�|�|j���|j�d�|j��d|_dS)NrT)r�seek�	pushlines�	readlines�truncaterrrrr�closeFs

zBufferedSubFile.closecCsL|js|jrdStS|j��}t|j�D]}||�r(|j�|�dSq(|S�Nr)r
r�NeedMoreData�popleft�reversedr�
appendleft)r�line�ateofrrr�readlineNs
zBufferedSubFile.readlinecCs|tk	st�|j�|�dSr)r!�AssertionErrorr
r$�rr%rrr�
unreadline`szBufferedSubFile.unreadlinecCsx|j�|�d|kr d|kr dS|j�d�|j��}|j�d�|j��|d�d�sj|j�|���|�|�dS)z$Push some new data into this object.r	�
Nr���)r�writerrr�endswithrr)r�data�partsrrr�pushes

zBufferedSubFile.pushcCs|j�|�dSr)r
�extend)r�linesrrrrzszBufferedSubFile.pushlinescCs|Srrrrrr�__iter__}szBufferedSubFile.__iter__cCs|��}|dkrt�|Sr )r'�
StopIterationr)rrr�__next__�szBufferedSubFile.__next__N)�__name__�
__module__�__qualname__�__doc__rrrrr'r*r1rr4r6rrrrr
-sr
c@s`eZdZdZded�dd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dS)rzA feed-style parser of email.N��policycCs�||_d|_|dkr<|jdkr2ddlm}||_qn|j|_n2||_z||jd�Wntk
rld|_YnXt�|_g|_	|�
�j|_d|_
d|_d|_dS)a_factory is called with no arguments to create a new message obj

        The policy keyword specifies a policy object that controls a number of
        aspects of the parser's operation.  The default policy maintains
        backward compatibility.

        FNr)�Messager;T)r<�_old_style_factory�message_factory�
email.messager=�_factory�	TypeErrorr
�_input�	_msgstack�	_parsegenr6�_parse�_cur�_last�_headersonly)rrAr<r=rrrr�s$

zFeedParser.__init__cCs
d|_dS)NT)rIrrrr�_set_headersonly�szFeedParser._set_headersonlycCs|j�|�|��dS)zPush more data into the parser.N)rCr1�_call_parse�rr/rrr�feed�szFeedParser.feedcCs&z|��Wntk
r YnXdSr)rFr5rrrrrK�szFeedParser._call_parsecCsR|j��|��|��}|jr$t�|��dkrN|��sNt�	�}|j
�||�|S)z<Parse all remaining data and return the root message object.�	multipart)rCrrK�_pop_messagerDr(�get_content_maintype�is_multipartr�!MultipartInvariantViolationDefectr<�
handle_defect)r�root�defectrrrr�s

�zFeedParser.closecCsn|jr|��}n|j|jd�}|jr<|j��dkr<|�d�|jrR|jd�|�|j�|�||_||_	dS)Nr;zmultipart/digestzmessage/rfc822r,)
r>rAr<rG�get_content_type�set_default_typerD�attachrrH)r�msgrrr�_new_message�s

zFeedParser._new_messagecCs(|j��}|jr|jd|_nd|_|S)Nr,)rDrrG)r�retvalrrrrO�s

zFeedParser._pop_messageccs$|��g}|jD]Z}|tkr&tVqt�|�sbt�|�s^t��}|j�	|j
|�|j�|�qn|�|�q|�
|�|jr�g}|j��}|tkr�tVq�|dkr�q�|�|�q�|j
�t�|��dS|j
��dk�r�|j�tj�|��D]}|tk�rtVq��qq�|��}|j��|j��}|tk�rDtV�q�qD�q|j��}|tk�rjtV�qD�qj�qD|dk�rx�q�|j�|�q�dS|j
��dk�r�|��D] }|tk�r�tV�q��qĐq�|��dS|j
��dk�r�|j
��}|dk�rRt��}|j�	|j
|�g}|jD]$}|tk�r.tV�q|�|��q|j
�t�|��dSt|j
�dd����dk�r�t��}|j�	|j
|�d|}t� d	t�!|�d
�}	d}
g}d}d}
|j��}|tk�r�tV�q�|dk�r�q�|	�|�}|�r�|�"d
��rd}
|�"d�}�q�|
�rr|�r^|d}t#�$|�}|�rP|dt%|�"d���|d<t�|�|j
_&d}
|j�|��q�|j��}|tk�r�tV�qr|	�|�}|�sr|j�|��q��qr|j�|	j�|��D] }|tk�r�tV�q��q�q�|j'��dk�rT|j'j(}|dk�rd|j'_(n:|dk	�r�t#�$|�}|�r�t%|�"d��}|d|�|j'_(nD|j'j)}t*|t��r�t#�$|�}|�r�|dt%|�"d���}||j'_)|j��|��|j
|_'n|
�s�t+�|�|��q�|
�r4t�,�}|j�	|j
|�|j
�t�|��g}|jD]}|tk�rtV�q�qt�|�|j
_(dS|
�sVt�-�}|j�	|j
|�dS|�rddg}ng}|jD]$}|tk�r�tV�qn|�|��qn|�r�|d}t.�|�}|�r�|t%|�"d��d�|d<t�|�|j
_(dSg}|jD]$}|tk�rtV�q�|�|��q�|j
�t�|��dS)Nrzmessage/delivery-status�messagerNzcontent-transfer-encoding�8bit)�7bitr]�binaryz--z(?P<sep>z4)(?P<end>--)?(?P<ws>[ \t]*)(?P<linesep>\r\n|\r|\n)?$TF�end�linesepr,r)/rZrCr!�headerRE�match�NLCREr� MissingHeaderBodySeparatorDefectr<rSrGr*r�_parse_headersrIr'�set_payload�EMPTYSTRING�joinrVrrErOrrP�get_boundary�NoBoundaryInMultipartDefect�str�get�lower�-InvalidMultipartContentTransferEncodingDefect�re�compile�escape�group�	NLCRE_eol�search�len�preamblerH�epilogue�_payload�
isinstancer(�StartBoundaryNotFoundDefect�CloseBoundaryNotFoundDefect�	NLCRE_bol)r�headersr%rUr3r[rY�boundary�	separator�
boundaryre�capturing_preamblerwra�close_boundary_seen�mo�lastline�eolmorxr`�payload�	firstline�bolmorrrrE�sb

















���

























zFeedParser._parsegenc	Csjd}g}t|�D�]8\}}|ddkrR|sFt�|�}|j�|j|�q|�|�q|rt|jj|j�|��dg}}|�	d�r�|dkr�t
�|�}|r�|dt|�
d���}|j�|�qn<|t|�dkr�|j�|�dSt�|�}|jj�|�q|�d�}|dk�r&t�d�}|jj�|�q|dk�s8td��|d|�}|g}q|�rf|jj|j�|��dS)	Nrrz 	zFrom ��:zMissing header name.z3_parse_headers fed line with no : and no leading WS)�	enumerater�#FirstHeaderLineIsContinuationDefectr<rSrGr�set_raw�header_source_parse�
startswithrtrurvrs�set_unixfromrCr*�MisplacedEnvelopeHeaderDefect�defects�find�InvalidHeaderDefectr()	rr3�
lastheader�	lastvalue�linenor%rUr��irrrrf�sH








zFeedParser._parse_headers)N)r7r8r9r:rrrJrMrKrrZrOrErfrrrrr�s

~cs eZdZdZ�fdd�Z�ZS)rz(Like FeedParser, but feed accepts bytes.cst��|�dd��dS)N�ascii�surrogateescape)�superrM�decoderL��	__class__rrrMszBytesFeedParser.feed)r7r8r9r:rM�
__classcell__rrr�rrs)r:�__all__rp�emailr�email._policybaser�collectionsr�iorrqrdr}rt�NLCRE_crackrbrh�NL�objectr!r
rrrrrr�<module>s(




[�h�%bytecode of module 'email.feedparser'�u��b.��1h)��N}�(hB�0�@s�dZdddgZddlZddlZddlZddlZddlmZddlm	Z	m
Z
ddlmZd	Z
d
Ze�d�Ze�dej�ZGd
d�d�ZGdd�de�ZdZGdd�de�Zeeejd��ZdeZejZdS)z:Classes to generate plain text from a message object tree.�	Generator�DecodedGenerator�BytesGenerator�N)�deepcopy)�StringIO�BytesIO)�_has_surrogates�_�
z
\r\n|\r|\nz^From c@s�eZdZdZd'dd�dd�Zdd�Zd(d	d
�Zdd�Zd
d�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�ZeZdd�Zdd�Zdd �Zd!d"�Zed)d#d$��Zed%d&��ZdS)*rz�Generates output from a Message object tree.

    This basic generator writes the message to the given file object as plain
    text.
    N��policycCs6|dkr|dkrdn|j}||_||_||_||_dS)a�Create the generator for message flattening.

        outfp is the output file-like object for writing the message to.  It
        must have a write() method.

        Optional mangle_from_ is a flag that, when True (the default if policy
        is not set), escapes From_ lines in the body of the message by putting
        a `>' in front of them.

        Optional maxheaderlen specifies the longest length for a non-continued
        header.  When a header line is longer (in characters, with tabs
        expanded to 8 spaces) than maxheaderlen, the header will split as
        defined in the Header class.  Set maxheaderlen to zero to disable
        header wrapping.  The default is 78, as recommended (but not required)
        by RFC 2822.

        The policy keyword specifies a policy object that controls a number of
        aspects of the generator's operation.  If no policy is specified,
        the policy associated with the Message object passed to the
        flatten method is used.

        NT)�mangle_from_�_fp�
_mangle_from_�maxheaderlenr)�self�outfpr
rr�r�%/usr/lib/python3.8/email/generator.py�__init__$szGenerator.__init__cCs|j�|�dS�N)r�write�r�srrrrDszGenerator.writeFcCs�|jdkr|jn|j}|dk	r*|j|d�}|jdk	rB|j|jd�}|j|_|�|j�|_d|_|�|j�|_|j}|j}zL||_||_|r�|�	�}|s�dt
�t
�
��}|�||j�|�
|�W5||_||_XdS)a�Print the message object tree rooted at msg to the output file
        specified when the Generator instance was created.

        unixfrom is a flag that forces the printing of a Unix From_ delimiter
        before the first object in the message tree.  If the original message
        has no From_ delimiter, a `standard' one is crafted.  By default, this
        is False to inhibit the printing of any From_ delimiter.

        Note that for subobjects, no From_ line is printed.

        linesep specifies the characters used to indicate a new line in
        the output.  The default value is determined by the policy specified
        when the Generator instance was created or, if none was specified,
        from the policy associated with the msg.

        N)�linesep��max_line_length�zFrom nobody )r�clonerr�_NL�_encode�_encoded_NL�_EMPTY�_encoded_EMPTY�get_unixfrom�time�ctimer�_write)r�msg�unixfromrr�old_gen_policy�old_msg_policy�ufromrrr�flattenHs,
zGenerator.flattencCs|j||jd|jd�S)z1Clone this generator with the exact same options.Nr)�	__class__rr)r�fprrrrys
�zGenerator.clonecCst�Sr)r�rrrr�_new_buffer�szGenerator._new_buffercCs|Srrrrrrr �szGenerator._encodecCsT|sdSt�|�}|dd�D]}|�|�|�|j�q|drP|�|d�dS)N���)�NLCRE�splitrr)r�lines�linerrr�_write_lines�s

zGenerator._write_linescCs�|j}z"d|_|��|_}|�|�W5||_|j}|`X|r�t|�}|�d�dkrd|d|d<n|�d|d�|�d|d�t|dd�}|dkr�|�|�n||�|j�	|�
��dS)N�content-transfer-encodingr�Content-Transfer-Encoding�content-type��_write_headers)r�
_munge_cter1�	_dispatchr�get�replace_header�getattrr<r�getvalue)rr(�oldfp�	munge_cte�sfp�methrrrr'�s&zGenerator._writecCst|��}|��}t�||f��dd�}t|d|d�}|dkrh|�dd�}t|d|d�}|dkrh|j}||�dS)N�-r	Z_handle_)�get_content_maintype�get_content_subtype�
UNDERSCORE�join�replacerA�
_writeBody)rr(�main�sub�specificrF�genericrrrr>�szGenerator._dispatchcCs6|��D]\}}|�|j�||��q|�|j�dSr)�	raw_itemsrr�foldr�rr(�h�vrrrr<�szGenerator._write_headerscCs�|��}|dkrdSt|t�s.tdt|���t|j�r~|�d�}|dk	r~t|�}|d=|�	||�|��}|d|df|_
|jr�t�
d|�}|�|�dS)Nzstring payload expected: %s�charsetr8r:�>From )�get_payload�
isinstance�str�	TypeError�typer�_payload�	get_paramr�set_payloadr=r�fcrerOr7)rr(�payloadrWrrr�_handle_text�s$


�zGenerator._handle_textcCs�g}|��}|dkrg}n(t|t�r2|�|�dSt|t�sB|g}|D]6}|��}|�|�}|j|d|jd�|�	|�
��qF|��}|s�|j�
|�}|�|�}|�|�|jdk	r�|jr�t�d|j�}	n|j}	|�|	�|�|j�|�d||j�|�r|j�|�d��|D],}
|�|jd||j�|j�|
��q|�|jd|d|j�|jdk	�r�|j�r�t�d|j�}n|j}|�|�dS)NF�r)rrXz--r)rYrZr[r�listr1rr-r�appendrB�get_boundaryr!rK�_make_boundary�set_boundary�preamblerrarOr7r�pop�epilogue)rr(�msgtexts�subparts�partr�g�boundary�alltextrj�	body_partrlrrr�_handle_multipartsJ







zGenerator._handle_multipartcCs0|j}|jdd�|_z|�|�W5||_XdS)Nrr)rrrt)rr(�prrr�_handle_multipart_signed<s
z"Generator._handle_multipart_signedcCs�g}|��D]t}|��}|�|�}|j|d|jd�|��}|�|j�}|rv|d|jkrv|�	|j�
|dd���q|�	|�q|j�|j�
|��dS)NFrdr2)
rYr1rr-rrBr4r!r#rfrKrr)rr(�blocksrorrp�textr5rrr�_handle_message_delivery_statusGs
z)Generator._handle_message_delivery_statuscCs^|��}|�|�}|j}t|t�rD|j|�d�d|jd�|��}n
|�	|�}|j
�|�dS)NrFrd)r1rr^rZrer-rYrrBr rr)rr(rrprbrrr�_handle_message\s




zGenerator._handle_messagecCsvt�tj�}dt|d}|dkr(|S|}d}|�dt�|�dtj�}|�	|�sXqr|dt
|�}|d7}q0|S)Nz===============z==rz^--z(--)?$�.r;)�random�	randrange�sys�maxsize�_fmt�_compile_re�re�escape�	MULTILINE�searchr[)�clsrx�tokenrq�b�counter�crerrrrhus

zGenerator._make_boundarycCst�||�Sr)r��compile�r�r�flagsrrrr��szGenerator._compile_re)NN)FN)N)�__name__�
__module__�__qualname__�__doc__rrr-rr1r r7r'r>r<rcrMrtrvryrz�classmethodrhr�rrrrrs.	� 
1'
:csPeZdZdZdd�Zdd�Zdd�Zdd	�Z�fd
d�ZeZ	e
dd
��Z�ZS)ra�Generates a bytes version of a Message object tree.

    Functionally identical to the base Generator except that the output is
    bytes and not string.  When surrogates were used in the input to encode
    bytes, these are decoded back to bytes for output.  If the policy has
    cte_type set to 7bit, then the message is transformed such that the
    non-ASCII bytes are properly content transfer encoded, using the charset
    unknown-8bit.

    The outfp object must accept bytes in its write method.
    cCs|j�|�dd��dS)N�ascii�surrogateescape)rr�encoderrrrr�szBytesGenerator.writecCst�Sr)rr0rrrr1�szBytesGenerator._new_buffercCs
|�d�S�Nr�)r�rrrrr �szBytesGenerator._encodecCs8|��D]\}}|j�|j�||��q|�|j�dSr)rRrrr�fold_binaryrrTrrrr<�szBytesGenerator._write_headerscs\|jdkrdSt|j�rH|jjdksH|jr:t�d|j�|_|�|j�ntt	|��
|�dS)N�7bitrX)r^rr�cte_typerrarOr7�superrrc)rr(�r.rrrc�s
zBytesGenerator._handle_textcCst�|�d�|�Sr�)r�r�r�r�rrrr��szBytesGenerator._compile_re)
r�r�r�r�rr1r r<rcrMr�r��
__classcell__rrr�rr�s
zD[Non-text (%(type)s) part of message omitted, filename %(filename)s]c@s(eZdZdZddd�dd�Zdd�ZdS)	rz�Generates a text representation of a message.

    Like the Generator base class, except that non-text parts are substituted
    with a format string representing the part.
    NrcCs.tj|||||d�|dkr$t|_n||_dS)a�Like Generator.__init__() except that an additional optional
        argument is allowed.

        Walks through all subparts of a message.  If the subpart is of main
        type `text', then it prints the decoded payload of the subpart.

        Otherwise, fmt is a format string that is used instead of the message
        payload.  fmt is expanded with the following keywords (in
        %(keyword)s format):

        type       : Full MIME type of the non-text part
        maintype   : Main MIME type of the non-text part
        subtype    : Sub-MIME type of the non-text part
        filename   : Filename of the non-text part
        description: Description associated with the non-text part
        encoding   : Content transfer encoding of the non-text part

        The default value for fmt is None, meaning

        [Non-text (%(type)s) part of message omitted, filename %(filename)s]
        rN)rr�_FMTr�)rrr
r�fmtrrrrr�s�zDecodedGenerator.__init__cCs�|��D]v}|��}|dkr2t|jdd�|d�q|dkr<qt|j|��|��|��|�d�|�dd�|�d	d
�d�|d�qdS)NrxF)�decode)�file�	multipartz
[no filename]zContent-Descriptionz[no description]r9z
[no encoding])r]�maintype�subtype�filename�description�encoding)	�walkrH�printrYr��get_content_typerI�get_filenamer?)rr(ror�rrrr>�s(���	�zDecodedGenerator._dispatch)NNN)r�r�r�r�rr>rrrrr�s
�r;z%%0%dd)r��__all__r�r~r%r|�copyr�iorr�email.utilsrrJ�NLr�r3r�rarrr�r�len�reprr�_widthr�rhrrrr�<module>s*

t3;�h�$bytecode of module 'email.generator'�u��b.��c@h)��N}�(hB'@�@s�dZdddgZddlZddlZddlZddlZddlmZddlm	Z
e
jZdZd	Z
d
ZdZdZd
ZdZed�Zed�Ze�dejejB�Ze�d�Ze�d�ZejjZdd�Zddd�ZGdd�d�ZGdd�d�Z Gdd�de!�Z"dS)z+Header encoding and decoding functionality.�Header�
decode_header�make_header�N)�HeaderParseError)�charset�
� � z        ��Nz 	�us-asciizutf-8ai
  =\?                   # literal =?
  (?P<charset>[^?]*?)   # non-greedy up to the next ? is the charset
  \?                    # literal ?
  (?P<encoding>[qQbB])  # either a "q" or a "b", case insensitive
  \?                    # literal ?
  (?P<encoded>.*?)      # non-greedy up to the next ?= is the encoded string
  \?=                   # literal ?=
  z[\041-\176]+:$z
\n[^ \t]+:c	Cs�t|d�rdd�|jD�St�|�s.|dfgSg}|��D]�}t�|�}d}|r:|�d�}|rj|��}d}|r~|�|ddf�|rL|�d��	�}|�d��	�}|�d�}|�|||f�qLq:g}	t
|�D]J\}
}|
dkr�|dr�||
d	dr�||
dd��r�|	�|
d�q�t|	�D]}||=�qg}
|D]�\}}}|dk�rV|
�||f�n�|d
k�r|t
j�|�}|
�||f�n~|dk�r�t|�d}|�r�|d
dd|�7}zt
j�|�}Wn tjk
�r�td��YnX|
�||f�ntd|���q2g}d}}|
D]v\}}t|t��r,t|d�}|dk�r@|}|}nB||k�rb|�||f�|}|}n |dk�rz|t|7}n||7}�q|�||f�|S)a;Decode a message header value without converting charset.

    Returns a list of (string, charset) pairs containing each of the decoded
    parts of the header.  Charset is None for non-encoded parts of the header,
    otherwise a lower-case string containing the name of the character set
    specified in the encoded string.

    header may be a string that may or may not contain RFC2047 encoded words,
    or it may be a Header object.

    An email.errors.HeaderParseError may be raised when certain decoding error
    occurs (e.g. a base64 decoding exception).
    �_chunkscSs(g|] \}}t�|t|��t|�f�qS�)�_charset�_encode�str)�.0�stringrrr�"/usr/lib/python3.8/email/header.py�
<listcomp>Ms�z!decode_header.<locals>.<listcomp>NTrF���q�b�z===zBase64 decoding errorzUnexpected encoding: zraw-unicode-escape)�hasattrr
�ecre�search�
splitlines�split�pop�lstrip�append�lower�	enumerate�isspace�reversed�email�
quoprimime�
header_decode�len�
base64mime�decode�binascii�Errorr�AssertionError�
isinstancer�bytes�BSPACE)�header�words�line�parts�first�	unencodedr�encoding�encoded�droplist�n�w�d�
decoded_words�encoded_string�word�paderr�	collapsed�	last_word�last_charsetrrrr=s|
�




4







cCsFt|||d�}|D].\}}|dk	r4t|t�s4t|�}|�||�q|S)a�Create a Header from a sequence of pairs as returned by decode_header()

    decode_header() takes a header value string and returns a sequence of
    pairs of the format (decoded_string, charset) where charset is the string
    name of the character set.

    This function takes one of those sequence of pairs and returns a Header
    instance.  Optional maxlinelen, header_name, and continuation_ws are as in
    the Header constructor.
    )�
maxlinelen�header_name�continuation_wsN)rr0�Charsetr")�decoded_seqrFrGrH�h�srrrrr�s�c@sJeZdZddd�Zdd�Zdd	�Zdd
d�Zdd
�Zddd�Zdd�Z	dS)rNr�strictcCs||dkrt}nt|t�s t|�}||_||_g|_|dk	rH|�|||�|dkrTt}||_|dkrjd|_	nt
|�d|_	dS)aDCreate a MIME-compliant header that can contain many character sets.

        Optional s is the initial header value.  If None, the initial header
        value is not set.  You can later append to the header with .append()
        method calls.  s may be a byte string or a Unicode string, but see the
        .append() documentation for semantics.

        Optional charset serves two purposes: it has the same meaning as the
        charset argument to the .append() method.  It also sets the default
        character set for all subsequent .append() calls that omit the charset
        argument.  If charset is not provided in the constructor, the us-ascii
        charset is used both as s's initial charset and as the default for
        subsequent .append() calls.

        The maximum line length can be specified explicitly via maxlinelen. For
        splitting the first line to a shorter value (to account for the field
        header which isn't included in s, e.g. `Subject') pass in the name of
        the field in header_name.  The default maxlinelen is 78 as recommended
        by RFC 2822.

        continuation_ws must be RFC 2822 compliant folding whitespace (usually
        either a space or a hard tab) which will be prepended to continuation
        lines.

        errors is passed through to the .append() call.
        Nrr)�USASCIIr0rIr�_continuation_wsr
r"�
MAXLINELEN�_maxlinelen�
_headerlenr*)�selfrLrrFrGrH�errorsrrr�__init__�s
zHeader.__init__c	Cs�|��g}d}d}|jD]�\}}|}|tjkrH|�dd�}|�dd�}|r�|o\|�|d�}|dkr�|dkr�|s�|�t�d}n|dkr�|s�|�t�|o�|�|d�}|}|�|�qt	�
|�S)z&Return the string value of the header.N�ascii�surrogateescape�replacer�Nr���)�
_normalizer
r�UNKNOWN8BIT�encoder,�	_nonctextr"�SPACE�EMPTYSTRING�join)	rS�uchunks�lastcs�	lastspacerr�nextcs�original_bytes�hasspacerrr�__str__�s*


zHeader.__str__cCs|t|�kS�N)r)rS�otherrrr�__eq__sz
Header.__eq__cCs�|dkr|j}nt|t�s"t|�}t|t�sZ|jp4d}|tjkrN|�dd�}n|�||�}|jpbd}|tjkr�z|�||�Wn"t	k
r�|dkr��t
}YnX|j�||f�dS)a.Append a string to the MIME header.

        Optional charset, if given, should be a Charset instance or the name
        of a character set (which will be converted to a Charset instance).  A
        value of None (the default) means that the charset given in the
        constructor is used.

        s may be a byte string or a Unicode string.  If it is a byte string
        (i.e. isinstance(s, str) is false), then charset is the encoding of
        that byte string, and a UnicodeError will be raised if the string
        cannot be decoded with that charset.  If s is a Unicode string, then
        charset is a hint specifying the character set of the characters in
        the string.  In either case, when producing an RFC 2822 compliant
        header using RFC 2047 rules, the string will be encoded using the
        output codec of the charset.  If the string cannot be encoded to the
        output codec, a UnicodeError will be raised.

        Optional `errors' is passed as the errors argument to the decode
        call if s is a byte string.
        NrrW)
rr0rIr�input_codecr\r,�output_codecr]�UnicodeEncodeError�UTF8r
r")rSrLrrT�
input_charset�output_charsetrrrr"	s$






z
Header.appendcCs|��p|dkS)z=True if string s is not a ctext character of RFC822.
        )�(�)�\)r%)rSrLrrrr^4szHeader._nonctext�;, 	rcCs�|��|dkr|j}|dkr"d}t|j||j|�}d}d}}|jD�]\}}	|dk	r�|oh|�|d�}|dkr�|r~|	dkr�|��n|	dkr�|s�|��|o�|�|d�}|	}d}|��}
|
r�|�	d|
d|	�n|�	dd|	�|
dd�D]`}|�
�|	jdk	�r"|�	|jd	|��|	�q�|��}|dt
|�t
|��}
|�	|
||	�q�t
|
�dkrF|�
�qF|j�rx|��|�|�}t�|��r�td
�|���|S)a�Encode a message header into an RFC-compliant format.

        There are many issues involved in converting a given string for use in
        an email header.  Only certain character sets are readable in most
        email clients, and as header strings can only contain a subset of
        7-bit ASCII, care must be taken to properly convert and encode (with
        Base64 or quoted-printable) header strings.  In addition, there is a
        75-character length limit on any given encoded header field, so
        line-wrapping must be performed, even with double-byte character sets.

        Optional maxlinelen specifies the maximum length of each generated
        line, exclusive of the linesep string.  Individual lines may be longer
        than maxlinelen if a folding point cannot be found.  The first line
        will be shorter by the length of the header name plus ": " if a header
        name was specified at Header construction time.  The default value for
        maxlinelen is determined at header construction time.

        Optional splitchars is a string containing characters which should be
        given extra weight by the splitting algorithm during normal header
        wrapping.  This is in very rough support of RFC 2822's `higher level
        syntactic breaks':  split points preceded by a splitchar are preferred
        during line splitting, with the characters preferred in the order in
        which they appear in the string.  Space and tab may be included in the
        string to indicate whether preference should be given to one over the
        other as a split point when other split chars do not appear in the line
        being split.  Splitchars does not affect RFC 2047 encoded lines.

        Optional linesep is a string to be used to separate the lines of
        the value.  The default value is the most useful for typical
        Python applications, but it can be set to \r\n to produce RFC-compliant
        line separators when needed.
        Nri@BrYrZFr
rrz8header value appears to contain an embedded header: {!r})r[rQ�_ValueFormatterrRrOr
r^�add_transitionr�feed�newline�header_encodingr!r*�_str�_embedded_headerrr�format)rS�
splitcharsrF�linesep�	formatterrcrgrdrr�linesr5�sline�fws�valuerrrr]9sZ!�
�

�z
Header.encodecCsxg}d}g}|jD]B\}}||kr.|�|�q|dk	rJ|�t�|�|f�|g}|}q|rn|�t�|�|f�||_dSri)r
r"r_ra)rS�chunksrE�
last_chunkrrrrrr[�szHeader._normalize)NNNNrrM)NrM)ruNr)
�__name__�
__module__�__qualname__rUrhrkr"r^r]r[rrrrr�s�
/ 
+
Pc@sTeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�ZdS)rvcCs0||_||_t|�|_||_g|_t|�|_dSri)�_maxlenrOr*�_continuation_ws_len�_splitchars�_lines�_Accumulator�
_current_line)rS�	headerlen�maxlenrHr~rrrrU�s
z_ValueFormatter.__init__cCs|��|�|j�Sri)ryrar�)rSrrrrr{�sz_ValueFormatter._strcCs
|�t�Sri)r{�NL�rSrrrrh�sz_ValueFormatter.__str__cCsv|j��}|dkr|jj|�t|j�dkrh|j��rV|jrV|jdt|j�7<n|j�t|j��|j��dS)N)rr
rrZ)	r�r �pushr*�	is_onlywsr�rr"�reset)rS�end_of_linerrrry�s
z_ValueFormatter.newlinecCs|j�dd�dS)Nrr
)r�r�r�rrrrw�sz_ValueFormatter.add_transitioncCs�|jdkr|�|||j�dS|�||���}z|�d�}Wntk
rRYdSX|dk	rh|�||�z|��}Wntk
r�YdSX|��|j	�
|j|�|D]}|j�
|j|�q�dS�Nr)rz�_ascii_splitr��header_encode_lines�_maxlengthsr �
IndexError�
_append_chunkryr�r�rOr�r")rSr�rr�
encoded_lines�
first_line�	last_liner5rrrrx�s$
z_ValueFormatter.feedccs&|jt|j�V|j|jVqdSri)r�r*r�r�r�rrrr��sz_ValueFormatter._maxlengthscCsft�dtd||�}|dr0dg|dd�<n
|�d�tt|�gd�D]\}}|�||�qLdS)Nz([z]+)rr
r)�rer�FWSr �zip�iterr�)rSr�rr~r6�partrrrr��s
z_ValueFormatter._ascii_splitcCs|j�||�t|j�|jk�r|jD]v}t|j��ddd�D]T}|��rn|j|d}|rn|d|krnq�|j|dd}|r@|d|kr@q�q@q&q�q&|j��\}}|jj	dkr�|�
�|s�d}|j�||�dS|j�|�}|j�
t|j��|j�|�dS)NrrrZr)r�r�r*r�r��range�
part_countr%r �
_initial_sizery�pop_fromr�r"rr�)rSr�r�ch�i�prevpartr��	remainderrrrr��s.
z_ValueFormatter._append_chunkN)r�r�r�rUr{rhryrwrxr�r�r�rrrrrv�s%rvcsjeZdZd�fdd�	Zdd�Zddd�Z�fdd	�Zd
d�Zdd
�Zddd�Z	dd�Z
�fdd�Z�ZS)r�rcs||_t���dSri)r��superrU)rS�initial_size��	__class__rrrUsz_Accumulator.__init__cCs|�||f�dSri)r")rSr�rrrrr�#sz_Accumulator.pushcCs||d�}g||d�<|Srir)rSr��poppedrrrr�&sz_Accumulator.pop_fromcs|��dkrdSt���S)Nr)r
r
)r�r�r r�r�rrr +sz_Accumulator.popcCstdd�|D�|j�S)Ncss"|]\}}t|�t|�VqdSri)r*�rr�r�rrr�	<genexpr>1sz'_Accumulator.__len__.<locals>.<genexpr>)�sumr�r�rrr�__len__0s�z_Accumulator.__len__cCst�dd�|D��S)Ncss |]\}}t�||f�VqdSri�r`rar�rrrr�5s�z'_Accumulator.__str__.<locals>.<genexpr>r�r�rrrrh4s
�z_Accumulator.__str__NcCs"|dkrg}||dd�<d|_dSr�)r�)rS�startvalrrrr�8sz_Accumulator.resetcCs|jdko|pt|���Sr�)r�rr%r�rrrr�>sz_Accumulator.is_onlywscs
t���Sri)r�r�r�r�rrr�Asz_Accumulator.part_count)r)r)N)
r�r�r�rUr�r�r r�rhr�r�r��
__classcell__rrr�rr�s

r�)NNr)#�__doc__�__all__r�r-�email.quoprimimer'�email.base64mime�email.errorsrrrrIr�r_r2�SPACE8r`rPr�rNro�compile�VERBOSE�	MULTILINEr�fcrer|r(�_max_appendrrrrv�listr�rrrr�<module>sF�
�

_�
k�h�!bytecode of module 'email.header'�u��b.��PVh)��N}�(hBV�@szdZddlmZddlmZddlmZddlmZGdd�d�ZGdd	�d	�Z	Gd
d�de
�Zdd
�ZGdd�d�Z
Gdd�de
�ZGdd�d�ZGdd�de�ZGdd�d�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�d�ZGd d!�d!�ZGd"d#�d#e�ZGd$d%�d%e�ZGd&d'�d'�ZGd(d)�d)�Zeeeeeeeeeeeeeeeeeeeed*�ZGd+d,�d,�Zd-S).a;Representing and manipulating email headers via custom objects.

This module provides an implementation of the HeaderRegistry API.
The implementation is designed to flexibly follow RFC5322 rules.

Eventually HeaderRegistry will be a public API, but it isn't yet,
and will probably change some before that happens.

�)�MappingProxyType)�utils)�errors)�_header_value_parserc@s^eZdZddd�Zedd��Zedd��Zed	d
��Zedd��Zd
d�Z	dd�Z
dd�ZdS)�Address�NcCs�d�td||||f��}d|ks(d|kr0td��|dk	r�|s@|rHtd��t�|�\}}|rjtd�||���|jrz|jd�|j}|j	}||_
||_||_dS)	a�Create an object representing a full email address.

        An address can have a 'display_name', a 'username', and a 'domain'.  In
        addition to specifying the username and domain separately, they may be
        specified together by using the addr_spec keyword *instead of* the
        username and domain keywords.  If an addr_spec string is specified it
        must be properly quoted according to RFC 5322 rules; an error will be
        raised if it is not.

        An Address object has display_name, username, domain, and addr_spec
        attributes, all of which are read-only.  The addr_spec and the string
        value of the object are both quoted according to RFC5322 rules, but
        without any Content Transfer Encoding.

        rN�
�
z8invalid arguments; address parts cannot contain CR or LFz=addrspec specified when username and/or domain also specifiedz6Invalid addr_spec; only '{}' could be parsed from '{}'r)
�join�filter�
ValueError�	TypeError�parser�
get_addr_spec�format�all_defects�
local_part�domain�
_display_name�	_username�_domain)�self�display_name�usernamer�	addr_spec�inputs�a_s�rest�r�*/usr/lib/python3.8/email/headerregistry.py�__init__s&�
zAddress.__init__cCs|jS�N�r�rrrrr<szAddress.display_namecCs|jSr!)rr#rrrr@szAddress.usernamecCs|jSr!)rr#rrrrDszAddress.domaincCsTt|j�}t|�t|tj�kr.t�|j�}n|j}|jrH|d|jS|sPdS|S)z�The addr_spec (username@domain) portion of the address, quoted
        according to RFC 5322 rules, but with no Content Transfer Encoding.
        �@�<>)�setr�lenr�
DOT_ATOM_ENDS�quote_stringr)r�nameset�lprrrrHs
zAddress.addr_speccCsd�|jj|j|j|j�S)Nz1{}(display_name={!r}, username={!r}, domain={!r}))r�	__class__�__name__rrrr#rrr�__repr__Xs�zAddress.__repr__cCs^t|j�}t|�t|tj�kr.t�|j�}n|j}|rX|jdkrFdn|j}d�||�S|jS)Nr%rz{} <{}>)r&rr'r�SPECIALSr)rr)rr*�disprrrr�__str__]s
zAddress.__str__cCs8t|�t|�krdS|j|jko6|j|jko6|j|jkS�NF)�typerrr�r�otherrrr�__eq__hs
�
�zAddress.__eq__)rrrN)r-�
__module__�__qualname__r �propertyrrrrr.r1r6rrrrrs
*



rc@sFeZdZddd�Zedd��Zedd��Zdd	�Zd
d�Zdd
�Z	dS)�GroupNcCs||_|rt|�nt�|_dS)aCreate an object representing an address group.

        An address group consists of a display_name followed by colon and a
        list of addresses (see Address) terminated by a semi-colon.  The Group
        is created by specifying a display_name and a possibly empty list of
        Address objects.  A Group can also be used to represent a single
        address that is not in a group, which is convenient when manipulating
        lists that are a combination of Groups and individual Addresses.  In
        this case the display_name should be set to None.  In particular, the
        string representation of a Group whose display_name is None is the same
        as the Address object, if there is one and only one Address object in
        the addresses list.

        N)r�tuple�
_addresses)rr�	addressesrrrr rszGroup.__init__cCs|jSr!r"r#rrrr�szGroup.display_namecCs|jSr!)r<r#rrrr=�szGroup.addressescCsd�|jj|j|j�S)Nz${}(display_name={!r}, addresses={!r})rr,r-rr=r#rrrr.�s
�zGroup.__repr__cCs�|jdkr&t|j�dkr&t|jd�S|j}|dk	r\t|�}t|�t|tj�kr\t�|�}d�dd�|jD��}|r~d|n|}d�	||�S)N�r�, css|]}t|�VqdSr!��str)�.0�xrrr�	<genexpr>�sz Group.__str__.<locals>.<genexpr>� z{}:{};)
rr'r=rAr&rr/r)r
r)rr0r*�adrstrrrrr1�s
z
Group.__str__cCs,t|�t|�krdS|j|jko*|j|jkSr2)r3rr=r4rrrr6�s

�zGroup.__eq__)NN)
r-r7r8r r9rr=r.r1r6rrrrr:ps


r:c@sTeZdZdZdd�Zdd�Zedd��Zedd	��Zd
d�Z	e
dd
��Zdd�ZdS)�
BaseHeadera|Base class for message headers.

    Implements generic behavior and provides tools for subclasses.

    A subclass must define a classmethod named 'parse' that takes an unfolded
    value string and a dictionary as its arguments.  The dictionary will
    contain one key, 'defects', initialized to an empty list.  After the call
    the dictionary must contain two additional keys: parse_tree, set to the
    parse tree obtained from parsing the header, and 'decoded', set to the
    string value of the idealized representation of the data from the value.
    (That is, encoded words are decoded, and values that have canonical
    representations are so represented.)

    The defects key is intended to collect parsing defects, which the message
    parser will subsequently dispose of as appropriate.  The parser should not,
    insofar as practical, raise any errors.  Defects should be added to the
    list instead.  The standard header parsers register defects for RFC
    compliance issues, for obsolete RFC syntax, and for unrecoverable parsing
    errors.

    The parse method may add additional keys to the dictionary.  In this case
    the subclass must define an 'init' method, which will be passed the
    dictionary as its keyword arguments.  The method should use (usually by
    setting them as the value of similarly named attributes) and remove all the
    extra keys added by its parse method, and then use super to call its parent
    class with the remaining arguments and keywords.

    The subclass should also make sure that a 'max_count' attribute is defined
    that is either None or 1. XXX: need to better define this API.

    cCs\dgi}|�||�t�|d�r4t�|d�|d<t�||d�}|d=|j|f|�|S)N�defects�decoded)�parser�_has_surrogates�	_sanitizerA�__new__�init)�cls�name�value�kwdsrrrrrM�szBaseHeader.__new__cCs||_||_||_dSr!)�_name�_parse_tree�_defects)rrP�
parse_treerHrrrrN�szBaseHeader.initcCs|jSr!)rSr#rrrrP�szBaseHeader.namecCs
t|j�Sr!)r;rUr#rrrrH�szBaseHeader.defectscCst|jj|jjt|�f|jfSr!)�_reconstruct_headerr,r-�	__bases__rA�__dict__r#rrr�
__reduce__�s��zBaseHeader.__reduce__cCst�||�Sr!)rArM)rOrQrrr�_reconstruct�szBaseHeader._reconstructc	Cs`t�t�t�|jd�t�dd�g�g�}|jrH|�t�t�dd�g��|�|j�|j	|d�S)atFold header according to policy.

        The parsed representation of the header is folded according to
        RFC5322 rules, as modified by the policy.  If the parse tree
        contains surrogateescaped bytes, the bytes are CTE encoded using
        the charset 'unknown-8bit".

        Any non-ASCII characters in the parse tree are CTE encoded using
        charset utf-8. XXX: make this a policy setting.

        The returned value is an ASCII-only string possibly containing linesep
        characters, and ending with a linesep character.  The string includes
        the header name and the ': ' separator.

        zheader-name�:z
header-seprE�fws)�policy)
r�Header�HeaderLabel�
ValueTerminalrPrT�append�CFWSList�WhiteSpaceTerminal�fold)rr^�headerrrrre�s
���zBaseHeader.foldN)
r-r7r8�__doc__rMrNr9rPrHrZ�classmethodr[rerrrrrG�s 




rGcCst||i��|�Sr!)r3r[)�cls_name�basesrQrrrrW
srWc@s&eZdZdZeej�Zedd��Z	dS)�UnstructuredHeaderNcCs"|�|�|d<t|d�|d<dS)NrVrI)�value_parserrA�rOrQrRrrrrJszUnstructuredHeader.parse)
r-r7r8�	max_count�staticmethodr�get_unstructuredrlrhrJrrrrrks
rkc@seZdZdZdS)�UniqueUnstructuredHeaderr>N�r-r7r8rnrrrrrqsrqcsFeZdZdZdZeej�Ze	dd��Z
�fdd�Zedd��Z
�ZS)	�
DateHeadera�Header whose value consists of a single timestamp.

    Provides an additional attribute, datetime, which is either an aware
    datetime using a timezone, or a naive datetime if the timezone
    in the input string is -0000.  Also accepts a datetime as input.
    The 'value' attribute is the normalized form of the timestamp,
    which means it is the output of format_datetime on the datetime.
    NcCsz|s6|d�t���d|d<d|d<t��|d<dSt|t�rJt�|�}||d<t�	|d�|d<|�
|d�|d<dS)NrH�datetimerrIrV)rbr�HeaderMissingRequiredValuer�	TokenList�
isinstancerAr�parsedate_to_datetime�format_datetimerlrmrrrrJ.s

zDateHeader.parsecs|�d�|_t�j||�dS)Nrt)�pop�	_datetime�superrN�r�args�kw�r,rrrN<szDateHeader.initcCs|jSr!)r{r#rrrrt@szDateHeader.datetime)r-r7r8rgrnrorrprlrhrJrNr9rt�
__classcell__rrr�rrss	


rsc@seZdZdZdS)�UniqueDateHeaderr>Nrrrrrrr�Esr�csPeZdZdZedd��Zedd��Z�fdd�Ze	dd	��Z
e	d
d��Z�ZS)�
AddressHeaderNcCst�|�\}}|rtd��|S)Nzthis should not happen)r�get_address_list�AssertionError)rQ�address_listrrrrlNszAddressHeader.value_parsercCs�t|t�rV|�|�|d<}g}|jD]"}|�t|jdd�|jD���q&t|j	�}n"t
|d�sf|g}dd�|D�}g}||d<||d<d�d	d�|D��|d
<d|kr�|�|d
�|d<dS)NrVcSs*g|]"}t|jpd|jpd|jp"d��qS)r)rrrr)rB�mbrrr�
<listcomp>]s
�
�z'AddressHeader.parse.<locals>.<listcomp>�__iter__cSs&g|]}t|d�std|g�n|�qS)r=N)�hasattrr:�rB�itemrrrr�fs��groupsrHr?cSsg|]}t|��qSrr@r�rrrr�lsrI)rwrArlr=rbr:r�
all_mailboxes�listrr�r
)rOrQrRr�r��addrrHrrrrJTs*


��
�zAddressHeader.parsecs(t|�d��|_d|_t�j||�dS)Nr�)r;rz�_groupsr<r|rNr}r�rrrNpszAddressHeader.initcCs|jSr!)r�r#rrrr�uszAddressHeader.groupscCs&|jdkr tdd�|jD��|_|jS)Ncss|]}|jD]
}|VqqdSr!)r=)rB�group�addressrrrrD|s�z*AddressHeader.addresses.<locals>.<genexpr>)r<r;r�r#rrrr=ys
zAddressHeader.addresses)
r-r7r8rnrorlrhrJrNr9r�r=r�rrr�rr�Js


r�c@seZdZdZdS)�UniqueAddressHeaderr>Nrrrrrrr��sr�c@seZdZedd��ZdS)�SingleAddressHeadercCs(t|j�dkrtd�|j���|jdS)Nr>z9value of single address header {} is not a single addressr)r'r=rrrPr#rrrr��s
�zSingleAddressHeader.addressN)r-r7r8r9r�rrrrr��sr�c@seZdZdZdS)�UniqueSingleAddressHeaderr>Nrrrrrrr��sr�csZeZdZdZeej�Zedd��Z	�fdd�Z
edd��Zedd	��Z
ed
d��Z�ZS)�MIMEVersionHeaderr>cCs�|�|�|d<}t|�|d<|d�|j�|jdkr<dn|j|d<|j|d<|jdk	rtd�|d|d�|d<nd|d<dS)NrVrIrH�major�minorz{}.{}�version)rlrA�extendrr�r�r�rOrQrRrVrrrrJ�s

zMIMEVersionHeader.parsecs6|�d�|_|�d�|_|�d�|_t�j||�dS)Nr�r�r�)rz�_version�_major�_minorr|rNr}r�rrrN�szMIMEVersionHeader.initcCs|jSr!)r�r#rrrr��szMIMEVersionHeader.majorcCs|jSr!)r�r#rrrr��szMIMEVersionHeader.minorcCs|jSr!)r�r#rrrr��szMIMEVersionHeader.version)r-r7r8rnror�parse_mime_versionrlrhrJrNr9r�r�r�r�rrr�rr��s



r�cs8eZdZdZedd��Z�fdd�Zedd��Z�Z	S)�ParameterizedMIMEHeaderr>cCsZ|�|�|d<}t|�|d<|d�|j�|jdkrBi|d<ndd�|jD�|d<dS)NrVrIrH�paramscSs&i|]\}}t�|���t�|��qSr)rrL�lower)rBrPrQrrr�
<dictcomp>�s�z1ParameterizedMIMEHeader.parse.<locals>.<dictcomp>)rlrAr�rr�r�rrrrJ�s

�zParameterizedMIMEHeader.parsecs|�d�|_t�j||�dS)Nr�)rz�_paramsr|rNr}r�rrrN�szParameterizedMIMEHeader.initcCs
t|j�Sr!)rr�r#rrrr��szParameterizedMIMEHeader.params)
r-r7r8rnrhrJrNr9r�r�rrr�rr��s
r�csJeZdZeej�Z�fdd�Zedd��Z	edd��Z
edd��Z�ZS)	�ContentTypeHeadercs2t�j||�t�|jj�|_t�|jj�|_dSr!)	r|rNrrLrT�maintype�	_maintype�subtype�_subtyper}r�rrrN�szContentTypeHeader.initcCs|jSr!)r�r#rrrr��szContentTypeHeader.maintypecCs|jSr!)r�r#rrrr��szContentTypeHeader.subtypecCs|jd|jS)N�/)r�r�r#rrr�content_type�szContentTypeHeader.content_type)
r-r7r8ror�parse_content_type_headerrlrNr9r�r�r�r�rrr�rr��s


r�cs2eZdZeej�Z�fdd�Zedd��Z	�Z
S)�ContentDispositionHeadercs2t�j||�|jj}|dkr"|nt�|�|_dSr!)r|rNrT�content_dispositionrrL�_content_disposition)rr~r�cdr�rrrN�szContentDispositionHeader.initcCs|jSr!)r�r#rrrr��sz,ContentDispositionHeader.content_disposition)r-r7r8ror� parse_content_disposition_headerrlrNr9r�r�rrr�rr��s
r�csBeZdZdZeej�Zedd��Z	�fdd�Z
edd��Z�Z
S)�ContentTransferEncodingHeaderr>cCs2|�|�|d<}t|�|d<|d�|j�dS�NrVrIrH�rlrAr�rr�rrrrJsz#ContentTransferEncodingHeader.parsecs"t�j||�t�|jj�|_dSr!)r|rNrrLrT�cte�_cter}r�rrrNsz"ContentTransferEncodingHeader.initcCs|jSr!)r�r#rrrr�sz!ContentTransferEncodingHeader.cte)r-r7r8rnror�&parse_content_transfer_encoding_headerrlrhrJrNr9r�r�rrr�rr��s

r�c@s&eZdZdZeej�Zedd��Z	dS)�MessageIDHeaderr>cCs2|�|�|d<}t|�|d<|d�|j�dSr�r�r�rrrrJszMessageIDHeader.parseN)
r-r7r8rnror�parse_message_idrlrhrJrrrrr�s
r�)�subject�datezresent-datez	orig-dateZsenderz
resent-sender�toz	resent-to�ccz	resent-ccZbccz
resent-bcc�fromzresent-fromzreply-tozmime-versionzcontent-typezcontent-dispositionzcontent-transfer-encodingz
message-idc@s8eZdZdZeedfdd�Zdd�Zdd�Zd	d
�Z	dS)�HeaderRegistryz%A header_factory and header registry.TcCs&i|_||_||_|r"|j�t�dS)a�Create a header_factory that works with the Policy API.

        base_class is the class that will be the last class in the created
        header class's __bases__ list.  default_class is the class that will be
        used if "name" (see __call__) does not appear in the registry.
        use_default_map controls whether or not the default mapping of names to
        specialized classes is copied in to the registry when the factory is
        created.  The default is True.

        N)�registry�
base_class�
default_class�update�_default_header_map)rr�r��use_default_maprrrr 9s
zHeaderRegistry.__init__cCs||j|��<dS)zLRegister cls as the specialized class for handling "name" headers.

        N)r�r��rrPrOrrr�map_to_typeKszHeaderRegistry.map_to_typecCs,|j�|��|j�}td|j||jfi�S)N�_)r��getr�r�r3r-r�r�rrr�__getitem__QszHeaderRegistry.__getitem__cCs||||�S)a�Create a header instance for header 'name' from 'value'.

        Creates a header instance by creating a specialized class for parsing
        and representing the specified header by combining the factory
        base_class with a specialized class from the registry or the
        default_class, and passing the name and value to the constructed
        class's constructor.

        r)rrPrQrrr�__call__Us
zHeaderRegistry.__call__N)
r-r7r8rgrGrkr r�r�r�rrrrr�5s�
r�N)rg�typesr�emailrrrrrr:rArGrWrkrqrsr�r�r�r�r�r�r�r�r�r�r�r�r�rrrr�<module>sX	`6d'7
%��h�)bytecode of module 'email.headerregistry'�u��b.���h)��N}�(hBp�@sLdZdddgZddlZddlmZdd�Zdd	d�Zddd�Zddd
�ZdS)z1Various types of useful iterators and generators.�body_line_iterator�typed_subpart_iterator�walk�N)�StringIOccs.|V|��r*|��D]}|��EdHqdS)z�Walk over the message tree, yielding each subpart.

    The walk is performed in depth-first order.  This method is a
    generator.
    N)�is_multipart�get_payloadr)�self�subpart�r
�%/usr/lib/python3.8/email/iterators.pyrsFccs6|��D](}|j|d�}t|t�rt|�EdHqdS)z�Iterate over the parts, returning string payloads line-by-line.

    Optional decode (default False) is passed through to .get_payload().
    )�decodeN)rr�
isinstance�strr)�msgrr	�payloadr
r
rr"s
�textccs8|��D]*}|��|kr|dks,|��|kr|VqdS)z�Iterate over the subparts with a given MIME type.

    Use `maintype' as the main MIME type to match against; this defaults to
    "text".  Optional `subtype' is the MIME subtype to match against; if
    omitted, only the main type is matched.
    N)r�get_content_maintype�get_content_subtype)r�maintype�subtyper	r
r
rr-scCs�|dkrtj}d|d}t||��d|d�|rJtd|��|d�n
t|d�|��r||��D]}t|||d|�qddS)	zA handy debugging aidN� ��)�end�filez [%s])r�)�sys�stdout�print�get_content_type�get_default_typerr�
_structure)r�fp�level�include_default�tabr	r
r
rr!;s
r!)F)rN)NrF)	�__doc__�__all__r�iorrrrr!r
r
r
r�<module>s�

�h�$bytecode of module 'email.iterators'�u��b.��#�h)��N}�(hB��@s�dZddgZddlZddlZddlZddlmZmZddlm	Z	ddlm
Z
ddlmZm
Z
dd	lmZdd
lmZejZdZe�d�Zd
d�Zddd�Zdd�Zdd�ZGdd�d�ZGdd�de�ZGdd�de�ZdS)z8Basic message object for the email package object model.�Message�EmailMessage�N)�BytesIO�StringIO)�utils)�errors)�Policy�compat32��charset)�decode_bz; z[ \(\)<>@,;:\\"/\[\]\?=]cCs4t|��d�\}}}|s$|��dfS|��|��fS)N�;)�str�	partition�strip)�param�a�sep�b�r�#/usr/lib/python3.8/email/message.py�_splitparamsrTcCs�|dk	r�t|�dkr�t|t�rL|d7}t�|d|d|d�}d||fSz|�d�Wn6tk
r�|d7}t�|dd	�}d||fYSX|s�t�|�r�d
|t�	|�fSd||fSn|SdS)a~Convenience function to format and return a key=value pair.

    This will quote the value if needed or if quote is true.  If value is a
    three tuple (charset, language, value), it will be encoded according
    to RFC2231 rules.  If it contains non-ascii characters it will likewise
    be encoded according to RFC2231 rules, using the utf-8 charset and
    a null language.
    Nr�*���%s=%s�asciizutf-8�z%s="%s")
�len�
isinstance�tupler�encode_rfc2231�encode�UnicodeEncodeError�	tspecials�search�quote)r�valuer&rrr�_formatparam's	
r(cCs�dt|�}g}|dd�dkr�|dd�}|�d�}|dkrp|�dd|�|�dd|�drp|�d|d�}q6|dkr�t|�}|d|�}d|kr�|�d�}|d|�����d||dd���}|�|���||d�}q|S)Nr
rr�"z\"r�=)r�find�countr�indexr�lower�append)�s�plist�end�f�irrr�_parseparamIs 
(
,r5cCs4t|t�r&|d|dt�|d�fSt�|�SdS)Nrrr)rr r�unquote)r'rrr�
_unquotevalue]s
r7c@s�eZdZdZefdd�Zdd�Zddd	d
�Zdd�Zded
d�Z	dd�Z
dd�Zdd�Zdd�Z
dfdd�Zdgdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zdhd1d2�Zd3d4�Zd5d6�Zdid7d8�Zd9d:�Zd;d<�Z d=d>�Z!d?d@�Z"dAdB�Z#dCdD�Z$dEdF�Z%dGdH�Z&djdKdL�Z'dkdMdN�Z(dldQdR�Z)dmdSdT�Z*dndUdV�Z+dodWdX�Z,dpdYdZ�Z-d[d\�Z.dqd]d^�Z/drd_d`�Z0dadb�Z1ddcl2m3Z3dS)sra�Basic message object.

    A message object is defined as something that has a bunch of RFC 2822
    headers and a payload.  It may optionally have an envelope header
    (a.k.a. Unix-From or From_ header).  If the message is a container (i.e. a
    multipart or a message/rfc822), then the payload is a list of Message
    objects, otherwise it is a string.

    Message objects implement part of the `mapping' interface, which assumes
    there is exactly one occurrence of the header per message.  Some headers
    do in fact appear multiple times (e.g. Received) and for those headers,
    you must use the explicit API to set or get all the headers.  Not all of
    the mapping methods are implemented.
    cCs:||_g|_d|_d|_d|_d|_|_g|_d|_dS)N�
text/plain)	�policy�_headers�	_unixfrom�_payload�_charset�preamble�epilogue�defects�
_default_type)�selfr9rrr�__init__xszMessage.__init__cCs|��S)z9Return the entire formatted message as a string.
        )�	as_string�rBrrr�__str__�szMessage.__str__FrNcCsJddlm}|dkr|jn|}t�}||d||d�}|j||d�|��S)a�Return the entire formatted message as a string.

        Optional 'unixfrom', when true, means include the Unix From_ envelope
        header.  For backward compatibility reasons, if maxheaderlen is
        not specified it defaults to 0, so you must override it explicitly
        if you want a different maxheaderlen.  'policy' is passed to the
        Generator instance used to serialize the message; if it is not
        specified the policy associated with the message instance is used.

        If the message object contains binary data that is not encoded
        according to RFC standards, the non-compliant data will be replaced by
        unicode "unknown character" code points.
        r)�	GeneratorNF)�mangle_from_�maxheaderlenr9��unixfrom)�email.generatorrGr9r�flatten�getvalue)rBrKrIr9rG�fp�grrrrD�s�zMessage.as_stringcCs|��S)z?Return the entire formatted message as a bytes object.
        )�as_bytesrErrr�	__bytes__�szMessage.__bytes__cCsHddlm}|dkr|jn|}t�}||d|d�}|j||d�|��S)aJReturn the entire formatted message as a bytes object.

        Optional 'unixfrom', when true, means include the Unix From_ envelope
        header.  'policy' is passed to the BytesGenerator instance used to
        serialize the message; if not specified the policy associated with
        the message instance is used.
        r)�BytesGeneratorNF)rHr9rJ)rLrSr9rrMrN)rBrKr9rSrOrPrrrrQ�szMessage.as_bytescCst|jt�S)z6Return True if the message consists of multiple parts.)rr<�listrErrr�is_multipart�szMessage.is_multipartcCs
||_dS�N�r;)rBrKrrr�set_unixfrom�szMessage.set_unixfromcCs|jSrVrWrErrr�get_unixfrom�szMessage.get_unixfromcCsF|jdkr|g|_n.z|j�|�Wntk
r@td��YnXdS)z�Add the given payload to the current payload.

        The current payload will always be a list of objects after this method
        is called.  If you want to set the payload to a scalar object, use
        set_payload() instead.
        Nz=Attach is not valid on a message with a non-multipart payload)r<r/�AttributeError�	TypeError)rB�payloadrrr�attach�s

zMessage.attachcCs�|��r(|rdS|dkr|jS|j|S|dk	rNt|jt�sNtdt|j���|j}t|�dd����}t|t�r�t	�
|�r�|�dd�}|s�z|�|�
dd�d�}Wq�tk
r�|�dd�}Yq�Xn2|r�z|�d�}Wntk
r�|�d	�}YnX|�s|S|d
k�rt�|�S|dk�rVtd�|����\}}|D]}|j�||��q<|S|d
k�r�t|�}	t�}
ztj|	|
dd�|
��WStjk
�r�|YSXt|t��r�|S|S)aZReturn a reference to the payload.

        The payload will either be a list object or a string.  If you mutate
        the list object, you modify the message's payload in place.  Optional
        i returns that index into the payload.

        Optional decode is a flag indicating whether the payload should be
        decoded or not, according to the Content-Transfer-Encoding header
        (default is False).

        When True and the message is not a multipart, the payload will be
        decoded if this header's value is `quoted-printable' or `base64'.  If
        some other encoding is used, or the header is missing, or if the
        payload has bogus data (i.e. bogus base64 or uuencoded data), the
        payload is returned as-is.

        If the message is a multipart and the decode flag is True, then None
        is returned.
        NzExpected list, got %szcontent-transfer-encodingrr�surrogateescaper�replace�raw-unicode-escapezquoted-printable�base64�)z
x-uuencode�uuencode�uuezx-uueT)�quiet)rUr<rrTr[�typer�getr.r�_has_surrogatesr"�decode�	get_param�LookupError�UnicodeError�quopri�decodestringr�join�
splitlinesr9�
handle_defectr�uurN�Error)rBr4rir\�cte�bpayloadr'r@�defect�in_file�out_filerrr�get_payload�sV"








zMessage.get_payloadcCspt|d�r:|dkr||_dSt|t�s.t|�}|�|j�}t|d�rT|�dd�|_n||_|dk	rl|�|�dS)z�Set the payload to the given value.

        Optional charset sets the message's default character set.  See
        set_charset() for details.
        r"Nrirr^)�hasattrr<r�Charsetr"�output_charsetri�set_charset)rBr\rrrr�set_payload/s


zMessage.set_payloadcCs|dkr|�d�d|_dSt|t�s.t|�}||_d|krH|�dd�d|krf|jdd|��d�n|�d|���||��kr�|�|j�|_d|k�r|�	�}z||�Wnjt
k
�r|j}|r�z|�d	d
�}Wn tk
r�|�|j
�}YnX|�|�|_|�d|�YnXdS)a�Set the charset of the payload to a given character set.

        charset can be a Charset instance, a string naming a character set, or
        None.  If it is a string it will be converted to a Charset instance.
        If charset is None, the charset parameter will be removed from the
        Content-Type field.  Anything else will generate a TypeError.

        The message will be assumed to be of type text/* encoded with
        charset.input_charset.  It will be converted to charset.output_charset
        and encoded properly, if needed, when generating the plain text
        representation of the message.  MIME headers (MIME-Version,
        Content-Type, Content-Transfer-Encoding) will be added as needed.
        Nr�MIME-Version�1.0�Content-Typer8r
zContent-Transfer-Encodingrr^)�	del_paramr=rr{�
add_header�get_output_charset�	set_param�body_encoder<�get_body_encodingr[r"rlr|)rBrrtr\rrrr}Cs:

�
zMessage.set_charsetcCs|jS)zKReturn the Charset instance associated with the message's payload.
        )r=rErrr�get_charsetrszMessage.get_charsetcCs
t|j�S)z9Return the total number of headers, including duplicates.)rr:rErrr�__len__zszMessage.__len__cCs
|�|�S)a-Get a header value.

        Return None if the header is missing instead of raising an exception.

        Note that if the header appeared multiple times, exactly which
        occurrence gets returned is undefined.  Use get_all() to get all
        the values matching a header field name.
        )rg�rB�namerrr�__getitem__~s	zMessage.__getitem__cCsr|j�|�}|rX|��}d}|jD]4\}}|��|kr"|d7}||kr"td�||���q"|j�|j�||��dS)z�Set the value of a header.

        Note: this does not overwrite an existing header with the same field
        name.  Use __delitem__() first to delete any existing headers.
        rrz/There may be at most {} {} headers in a messageN)r9�header_max_countr.r:�
ValueError�formatr/�header_store_parse)rBr��val�	max_count�lname�found�k�vrrr�__setitem__�s�zMessage.__setitem__cCs@|��}g}|jD]"\}}|��|kr|�||f�q||_dS)zwDelete all occurrences of a header, if present.

        Does not raise an exception if the header is missing.
        N)r.r:r/)rBr��
newheadersr�r�rrr�__delitem__�szMessage.__delitem__cCs|��dd�|jD�kS)NcSsg|]\}}|���qSr)r.��.0r�r�rrr�
<listcomp>�sz(Message.__contains__.<locals>.<listcomp>)r.r:r�rrr�__contains__�szMessage.__contains__ccs|jD]\}}|VqdSrV�r:)rB�fieldr'rrr�__iter__�szMessage.__iter__cCsdd�|jD�S)a.Return a list of all the message's header field names.

        These will be sorted in the order they appeared in the original
        message, or were added to the message, and may contain duplicates.
        Any fields deleted and re-inserted are always appended to the header
        list.
        cSsg|]\}}|�qSrrr�rrrr��sz Message.keys.<locals>.<listcomp>r�rErrr�keys�szMessage.keyscs�fdd��jD�S)a)Return a list of all the message's header values.

        These will be sorted in the order they appeared in the original
        message, or were added to the message, and may contain duplicates.
        Any fields deleted and re-inserted are always appended to the header
        list.
        csg|]\}}�j�||��qSr�r9�header_fetch_parser�rErrr��s�z"Message.values.<locals>.<listcomp>r�rErrEr�values�s
�zMessage.valuescs�fdd��jD�S)a'Get all the message's header fields and values.

        These will be sorted in the order they appeared in the original
        message, or were added to the message, and may contain duplicates.
        Any fields deleted and re-inserted are always appended to the header
        list.
        cs"g|]\}}|�j�||�f�qSrr�r�rErrr��s�z!Message.items.<locals>.<listcomp>r�rErrEr�items�s
�z
Message.itemscCs:|��}|jD]&\}}|��|kr|j�||�Sq|S)z~Get a header value.

        Like __getitem__() but return failobj instead of None when the field
        is missing.
        )r.r:r9r�)rBr��failobjr�r�rrrrg�s
zMessage.getcCs|j�||f�dS)z�Store name and value in the model without modification.

        This is an "internal" API, intended only for use by a parser.
        N)r:r/)rBr�r'rrr�set_raw�szMessage.set_rawcCst|j���S)z�Return the (name, value) header pairs without modification.

        This is an "internal" API, intended only for use by a generator.
        )�iterr:�copyrErrr�	raw_items�szMessage.raw_itemscCsHg}|��}|jD](\}}|��|kr|�|j�||��q|sD|S|S)aQReturn a list of all the values for the named field.

        These will be sorted in the order they appeared in the original
        message, and may contain duplicates.  Any fields deleted and
        re-inserted are always appended to the header list.

        If no such fields exist, failobj is returned (defaults to None).
        )r.r:r/r9r�)rBr�r�r�r�r�rrr�get_all�s	zMessage.get_allcKspg}|��D]<\}}|dkr0|�|�dd��q|�t|�dd�|��q|dk	r^|�d|�t�|�||<dS)u�Extended header setting.

        name is the header field to add.  keyword arguments can be used to set
        additional parameters for the header field, with underscores converted
        to dashes.  Normally the parameter will be added as key="value" unless
        value is None, in which case only the key will be added.  If a
        parameter value contains non-ASCII characters it can be specified as a
        three-tuple of (charset, language, value), in which case it will be
        encoded according to RFC2231 rules.  Otherwise it will be encoded using
        the utf-8 charset and a language of ''.

        Examples:

        msg.add_header('content-disposition', 'attachment', filename='bud.gif')
        msg.add_header('content-disposition', 'attachment',
                       filename=('utf-8', '', Fußballer.ppt'))
        msg.add_header('content-disposition', 'attachment',
                       filename='Fußballer.ppt'))
        N�_�-r)r�r/r_r(�insert�	SEMISPACEro)rB�_name�_value�_params�partsr�r�rrrr�szMessage.add_headercCs\|��}ttt|j��|j�D]0\}\}}|��|kr|j�||�|j|<qXqt|��dS)z�Replace a header.

        Replace the first matching header found in the message, retaining
        header order and case.  If no matching header was found, a KeyError is
        raised.
        N)r.�zip�rangerr:r9r��KeyError)rBr�r�r4r�r�rrr�replace_header!s"zMessage.replace_headercCsHt�}|�d|�}||kr"|��St|�d��}|�d�dkrDdS|S)a0Return the message's content type.

        The returned string is coerced to lower case of the form
        `maintype/subtype'.  If there was no Content-Type header in the
        message, the default type as given by get_default_type() will be
        returned.  Since according to RFC 2045, messages always have a default
        type this will always return a value.

        RFC 2045 defines a message's default type to be text/plain unless it
        appears inside a multipart/digest container, in which case it would be
        message/rfc822.
        �content-typer�/rr8)�objectrg�get_default_typerr.r,)rB�missingr'�ctyperrr�get_content_type4s
zMessage.get_content_typecCs|��}|�d�dS)z�Return the message's main content type.

        This is the `maintype' part of the string returned by
        get_content_type().
        r�r�r��split�rBr�rrr�get_content_maintypeLszMessage.get_content_maintypecCs|��}|�d�dS)z�Returns the message's sub-content type.

        This is the `subtype' part of the string returned by
        get_content_type().
        r�rr�r�rrr�get_content_subtypeUszMessage.get_content_subtypecCs|jS)aReturn the `default' content type.

        Most messages have a default content type of text/plain, except for
        messages that are subparts of multipart/digest containers.  Such
        subparts have a default content type of message/rfc822.
        �rArErrrr�^szMessage.get_default_typecCs
||_dS)z�Set the `default' content type.

        ctype should be either "text/plain" or "message/rfc822", although this
        is not enforced.  The default content type is not stored in the
        Content-Type header.
        Nr�r�rrr�set_default_typegszMessage.set_default_typec		Cs�t�}|�||�}||kr|Sg}t|�D]X}z$|�dd�\}}|��}|��}Wn tk
rr|��}d}YnX|�||f�q*t�|�}|S)Nr*rr)	r�rgr5r�rr�r/r�
decode_params)	rBr��headerr�r'�params�pr�r�rrr�_get_params_preserveps 

zMessage._get_params_preserver�TcCs8t�}|�||�}||kr|S|r0dd�|D�S|SdS)amReturn the message's Content-Type parameters, as a list.

        The elements of the returned list are 2-tuples of key/value pairs, as
        split on the `=' sign.  The left hand side of the `=' is the key,
        while the right hand side is the value.  If there is no `=' sign in
        the parameter the value is the empty string.  The value is as
        described in the get_param() method.

        Optional failobj is the object to return if there is no Content-Type
        header.  Optional header is the header to search instead of
        Content-Type.  If unquote is True, the value is unquoted.
        cSsg|]\}}|t|�f�qSr)r7r�rrrr��sz&Message.get_params.<locals>.<listcomp>N)r�r�)rBr�r�r6r�r�rrr�
get_params�s
zMessage.get_paramscCsN||kr|S|�||�D]0\}}|��|��kr|r@t|�S|Sq|S)a�Return the parameter value if found in the Content-Type header.

        Optional failobj is the object to return if there is no Content-Type
        header, or the Content-Type header has no such parameter.  Optional
        header is the header to search instead of Content-Type.

        Parameter keys are always compared case insensitively.  The return
        value can either be a string, or a 3-tuple if the parameter was RFC
        2231 encoded.  When it's a 3-tuple, the elements of the value are of
        the form (CHARSET, LANGUAGE, VALUE).  Note that both CHARSET and
        LANGUAGE can be None, in which case you should consider VALUE to be
        encoded in the us-ascii charset.  You can usually ignore LANGUAGE.
        The parameter value (either the returned string, or the VALUE item in
        the 3-tuple) is always unquoted, unless unquote is set to False.

        If your application doesn't care whether the parameter was RFC 2231
        encoded, it can turn the return value into a string as follows:

            rawparam = msg.get_param('foo')
            param = email.utils.collapse_rfc2231_value(rawparam)

        )r�r.r7)rBrr�r�r6r�r�rrrrj�s
zMessage.get_paramr�rcCs
t|t�s|r|||f}||kr2|��dkr2d}n
|�|�}|j||d�st|s\t|||�}q�t�|t|||�g�}nbd}|j||d�D]N\}	}
d}|	��|��kr�t|||�}nt|	|
|�}|s�|}q�t�||g�}q�||�|�k�r|r�|�	||�n||=|||<dS)a�Set a parameter in the Content-Type header.

        If the parameter already exists in the header, its value will be
        replaced with the new value.

        If header is Content-Type and has not yet been defined for this
        message, it will be set to "text/plain" and the new parameter and
        value will be appended as per RFC 2045.

        An alternate header can be specified in the header argument, and all
        parameters will be quoted as necessary unless requote is False.

        If charset is specified, the parameter will be encoded according to RFC
        2231.  Optional language specifies the RFC 2231 language, defaulting
        to the empty string.  Both charset and language should be strings.
        r�r8)r�r�r�r6N)
rr r.rgrjr(r�ror�r�)rBrr'r��requoter�languager_r��	old_param�	old_value�append_paramrrrr��s6

��zMessage.set_paramcCs�||krdSd}|j||d�D]@\}}|��|��kr|sHt|||�}qt�|t|||�g�}q||�|�kr|||=|||<dS)a>Remove the given parameter completely from the Content-Type header.

        The header will be re-written in place without the parameter or its
        value. All values will be quoted as necessary unless requote is
        False.  Optional header specifies an alternative to the Content-Type
        header.
        Nrr�)r�r.r(r�rorg)rBrr�r��	new_ctyper�r�rrrr��s
�zMessage.del_paramcCs�|�d�dkst�|��dkr,|d=d|d<||kr@|||<dS|j||d�}||=|||<|dd�D]\}}|�||||�qhdS)	aKSet the main type and subtype for the Content-Type header.

        type must be a string in the form "maintype/subtype", otherwise a
        ValueError is raised.

        This method replaces the Content-Type header, keeping all the
        parameters in place.  If requote is False, this leaves the existing
        header's quoting as is.  Otherwise, the parameters will be quoted (the
        default).

        An alternative header can be specified in the header argument.  When
        the Content-Type header is set, we'll always also add a MIME-Version
        header.
        r�rr�zmime-versionr�rNr�)r,r�r.r�r�)rBrfr�r�r�r�r�rrr�set_typeszMessage.set_typecCsDt�}|�d|d�}||kr*|�d|d�}||kr6|St�|���S)a@Return the filename associated with the payload if present.

        The filename is extracted from the Content-Disposition header's
        `filename' parameter, and it is unquoted.  If that header is missing
        the `filename' parameter, this method falls back to looking for the
        `name' parameter.
        �filename�content-dispositionr�r�)r�rjr�collapse_rfc2231_valuer)rBr�r�r�rrr�get_filename&szMessage.get_filenamecCs,t�}|�d|�}||kr|St�|���S)z�Return the boundary associated with the payload if present.

        The boundary is extracted from the Content-Type header's `boundary'
        parameter, and it is unquoted.
        �boundary)r�rjrr��rstrip)rBr�r�r�rrr�get_boundary6s
zMessage.get_boundarycCst�}|�|d�}||kr$t�d��g}d}|D]:\}}|��dkr\|�dd|f�d}q0|�||f�q0|s�|�dd|f�g}|jD]z\}	}
|	��dkr�g}|D].\}}
|
dkr�|�|�q�|�d||
f�q�t�|�}
|�|j	�
|	|
��q�|�|	|
f�q�||_d	S)
a�Set the boundary parameter in Content-Type to 'boundary'.

        This is subtly different than deleting the Content-Type header and
        adding a new one with a new boundary parameter via add_header().  The
        main difference is that using the set_boundary() method preserves the
        order of the Content-Type header in the original message.

        HeaderParseError is raised if the message has no Content-Type header.
        r�zNo Content-Type header foundFr�z"%s"TrrN)r�r�r�HeaderParseErrorr.r/r:r�ror9r�)rBr�r�r��	newparams�foundp�pk�pvr��hr�r�r�r�rrr�set_boundaryCs2


zMessage.set_boundaryc	Cs�t�}|�d|�}||kr|St|t�rr|dp2d}z|d�d�}t||�}Wn ttfk
rp|d}YnXz|�d�Wntk
r�|YSX|��S)z�Return the charset parameter of the Content-Type header.

        The returned string is always coerced to lower case.  If there is no
        Content-Type header, or if that header has no charset parameter,
        failobj is returned.
        rrzus-asciirr`)	r�rjrr r"rrkrlr.)rBr�r�r�pcharsetrQrrr�get_content_charsetqs 

zMessage.get_content_charsetcs�fdd�|��D�S)a�Return a list containing the charset(s) used in this message.

        The returned list of items describes the Content-Type headers'
        charset parameter for this message and all the subparts in its
        payload.

        Each item will either be a string (the value of the charset parameter
        in the Content-Type header of that part) or the value of the
        'failobj' parameter (defaults to None), if the part does not have a
        main MIME type of "text", or the charset is not defined.

        The list will contain one string for each part of the message, plus
        one for the container message (i.e. self), so that a non-multipart
        message will still return a list of length 1.
        csg|]}|����qSr)r�)r��part�r�rrr��sz(Message.get_charsets.<locals>.<listcomp>��walk)rBr�rr�r�get_charsets�szMessage.get_charsetscCs*|�d�}|dkrdSt|�d��}|S)z�Return the message's content-disposition if it exists, or None.

        The return values can be either 'inline', 'attachment' or None
        according to the rfc2183.
        r�Nr)rgrr.)rBr'�c_drrr�get_content_disposition�s

zMessage.get_content_dispositionr�)FrN)FN)NF)N)N)N)Nr�T)Nr�T)r�TNrF)r�T)r�T)N)N)N)N)4�__name__�
__module__�__qualname__�__doc__r	rCrFrDrRrQrUrXrYr]ryr~r}r�r�r�r�r�r�r�r�r�r�rgr�r�r�r�r�r�r�r�r�r�r�r�rjr�r�r�r�r�r�r�r�r��email.iteratorsr�rrrrrisj


Z
/


				
�
"�
3

 


.


cs�eZdZd2dd�Zd3�fdd�	Zdd�Zd	d
�Zdd�Zd4dd�ZddddhZ	dd�Z
dd�Zdd�dd�Zdd�dd�Z
dd�Zd5dd �Zd6d!d"�Zd7d#d$�Zdd%�d&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Z�ZS)8�MIMEPartNcCs(|dkrddlm}|}t�||�dS)Nr)�default)�email.policyr�rrC)rBr9r�rrrrC�szMIMEPart.__init__Fcs0|dkr|jn|}|dkr |j}t�j||d�S)aReturn the entire formatted message as a string.

        Optional 'unixfrom', when true, means include the Unix From_ envelope
        header.  maxheaderlen is retained for backward compatibility with the
        base Message class, but defaults to None, meaning that the policy value
        for max_line_length controls the header maximum length.  'policy' is
        passed to the Generator instance used to serialize the message; if it
        is not specified the policy associated with the message instance is
        used.
        N)rIr9)r9�max_line_length�superrD)rBrKrIr9��	__class__rrrD�szMIMEPart.as_stringcCs|j|jjdd�d�S)NT)�utf8�r9)rDr9�clonerErrrrF�szMIMEPart.__str__cCs |�d�}|dkrdS|jdkS)Nr�F�
attachment)rg�content_disposition)rBr�rrr�
is_attachment�s
zMIMEPart.is_attachmentc	cs|��rdS|���d�\}}|dkrB||kr>|�|�|fVdS|dkrNdS|dkrz|��D]}|�||�EdHq^dSd|kr�|�d�|fVd}|�d�}|r�|��D]}|d|kr�|}q�q�|dkr�|��}|r�|dnd}|dk	�r|�||�EdHdS)Nr��text�	multipart�related�start�
content-idr)r�r�r�r-�
iter_parts�
_find_bodyrjry)	rBr��preferencelist�maintype�subtype�subpart�	candidater�subpartsrrrr�s6

zMIMEPart._find_body�r��html�plaincCsBt|�}d}|�||�D]$\}}||kr|}|}|dkrq>q|S)aReturn best candidate mime part for display as 'body' of message.

        Do a depth first search, starting with self, looking for the first part
        matching each of the items in preferencelist, and return the part
        corresponding to the first item that has a match, or None if no items
        have a match.  If 'related' is not included in preferencelist, consider
        the root part of any multipart/related encountered as a candidate
        match.  Ignore parts with 'Content-Disposition: attachment'.
        Nr)rr)rBr�	best_prio�body�prior�rrr�get_body�s
zMIMEPart.get_body)r�r)r�r)r�r�)r��alternativec
cs$|���d�\}}|dks"|dkr&dS|��}z|��}Wntk
rPYdSX|dkr�|dkr�|�d�}|r�d}g}|D]"}|�d�|kr�d	}q||�|�q||r�|EdHdS|�d
�|EdHdSg}	|D]L}|���d�\}}||f|j	k�r|�
��s||	k�r|	�|�q�|Vq�dS)aReturn an iterator over the non-main parts of a multipart.

        Skip the first of each occurrence of text/plain, text/html,
        multipart/related, or multipart/alternative in the multipart (unless
        they have a 'Content-Disposition: attachment' header) and include all
        remaining subparts in the returned iterator.  When applied to a
        multipart/related, return all parts except the root part.  Return an
        empty iterator when applied to a multipart/alternative or a
        non-multipart.
        r�r�rNr�rFrTr)r�r�ryr�rZrjrgr/�pop�_body_typesr�)
rBrrr\r�rr��attachmentsr��seenrrr�iter_attachmentssD



��
zMIMEPart.iter_attachmentsccs|��dkr|��EdHdS)z~Return an iterator over all immediate subparts of a multipart.

        Return an empty iterator for a non-multipart.
        r�N)r�ryrErrrr=szMIMEPart.iter_parts)�content_managercOs"|dkr|jj}|j|f|�|�SrV)r9r�get_content�rBr�args�kwrrrrEszMIMEPart.get_contentcOs&|dkr|jj}|j|f|�|�dSrV)r9r�set_contentrrrrrJszMIMEPart.set_contentc
Cs�|��dkr6|��}||f}||kr6td�||���g}g}|jD]4\}}|���d�rj|�||f�qD|�||f�qD|r�t|�|j	d�}	||	_|j
|	_
|	g|_
ng|_
||_d||d<|dk	r�|�d|�dS)Nr�zCannot convert {} to {}�content-r�z
multipart/r�r�)r�r�r�r�r:r.�
startswithr/rfr9r<r�)
rBr�disallowed_subtypesr��existing_subtype�keep_headers�part_headersr�r'r�rrr�_make_multipartOs0
�
zMIMEPart._make_multipartcCs|�dd|�dS)Nr�)r�mixed�r#�rBr�rrr�make_relatedjszMIMEPart.make_relatedcCs|�dd|�dS)Nr)r$r%r&rrr�make_alternativemszMIMEPart.make_alternativecCs|�dd|�dS)Nr$rr%r&rrr�
make_mixedpszMIMEPart.make_mixed)�_dispcOsf|��dks|��|kr(t|d|��t|�|jd�}|j||�|rXd|krX||d<|�|�dS)Nr��make_r�r�zContent-Disposition)r�r��getattrrfr9rr])rB�_subtyper*rrr�rrr�_add_multipartss
�zMIMEPart._add_multipartcOs|jd|�ddi|��dS)Nr�r*�inline)r��r.�rBrrrrr�add_related}szMIMEPart.add_relatedcOs|jd|�|�dS)Nr)rr0r1rrr�add_alternative�szMIMEPart.add_alternativecOs|jd|�ddi|��dS)Nr$r*r�)r$r0r1rrr�add_attachment�szMIMEPart.add_attachmentcCsg|_d|_dSrV�r:r<rErrr�clear�szMIMEPart.clearcCsdd�|jD�|_d|_dS)NcSs&g|]\}}|���d�s||f�qS)r)r.r)r��nr�rrrr��s�z*MIMEPart.clear_content.<locals>.<listcomp>r5rErrr�
clear_content�szMIMEPart.clear_content)N)FNN)r
)N)N)N)r�r�r�rCrDrFr�rrrrrrrr#r'r(r)r.r2r3r4r6r8�
__classcell__rrr�rr��s2

�7



r�cseZdZ�fdd�Z�ZS)rcs"t�j||�d|krd|d<dS)Nrr�)r�rr1r�rrr�szEmailMessage.set_content)r�r�r�rr9rrr�rr�s)NT)r��__all__�rerrrm�iorr�emailrr�email._policybaserr	rr=�email._encoded_wordsrr{r��compiler$rr(r5r7rr�rrrrr�<module>s6


"N`�h�"bytecode of module 'email.message'�u��b.���h)��N}�(hCt�@sdS)N�rrr�)/usr/lib/python3.8/email/mime/__init__.py�<module>��h�bytecode of module 'email.mime'�u��b.��@h)��N}�(hB�@s4dZdgZddlZddlmZGdd�dej�ZdS)�$Base class for MIME specializations.�MIMEBase�N)�messagec@seZdZdZdd�dd�ZdS)rrN��policycKsH|dkrtjj}tjj||d�d||f}|jd|f|�d|d<dS)z�This constructor adds a Content-Type: and a MIME-Version: header.

        The Content-Type: header is taken from the _maintype and _subtype
        arguments.  Additional parameters for this header are taken from the
        keyword arguments.
        Nrz%s/%szContent-Typez1.0zMIME-Version)�emailr�compat32r�Message�__init__�
add_header)�self�	_maintype�_subtyper�_params�ctype�r�%/usr/lib/python3.8/email/mime/base.pyr
szMIMEBase.__init__)�__name__�
__module__�__qualname__�__doc__r
rrrrrs)r�__all__�email.policyrrr	rrrrr�<module>s�h�$bytecode of module 'email.mime.base'�u��b.��h)��N}�(hB��@s*dZdgZddlmZGdd�de�ZdS)�.Base class for MIME multipart/* type messages.�
MIMEMultipart�)�MIMEBasec@s eZdZdZddd�dd�ZdS)rr�mixedN)�policycKsJtj|d|fd|i|��g|_|r8|D]}|�|�q(|rF|�|�dS)a�Creates a multipart/* type message.

        By default, creates a multipart/mixed message, with proper
        Content-Type and MIME-Version headers.

        _subtype is the subtype of the multipart content type, defaulting to
        `mixed'.

        boundary is the multipart boundary string.  By default it is
        calculated as needed.

        _subparts is a sequence of initial subparts for the payload.  It
        must be an iterable object, such as a list.  You can always
        attach new subparts to the message by using the attach() method.

        Additional parameters for the Content-Type header are taken from the
        keyword arguments (or passed into the _params argument).
        �	multipartrN)r�__init__�_payload�attach�set_boundary)�self�_subtype�boundary�	_subpartsr�_params�p�r�*/usr/lib/python3.8/email/mime/multipart.pyrszMIMEMultipart.__init__)rNN)�__name__�
__module__�__qualname__�__doc__rrrrrr
s�N)r�__all__�email.mime.baserrrrrr�<module>s�h�)bytecode of module 'email.mime.multipart'�u��b.��3h)��N}�(hB��@s6dZdgZddlmZddlmZGdd�de�ZdS)z9Base class for MIME type messages that are not multipart.�MIMENonMultipart�)�errors)�MIMEBasec@seZdZdZdd�ZdS)rz0Base class for MIME non-multipart type messages.cCst�d��dS)Nz4Cannot attach additional subparts to non-multipart/*)r�MultipartConversionError)�self�payload�r�-/usr/lib/python3.8/email/mime/nonmultipart.py�attachs�zMIMENonMultipart.attachN)�__name__�
__module__�__qualname__�__doc__r
rrrr	rsN)r�__all__�emailr�email.mime.baserrrrrr	�<module>s�h�,bytecode of module 'email.mime.nonmultipart'�u��b.��Nh)��N}�(hB�@s6dZdgZddlmZddlmZGdd�de�ZdS)z.Class representing text/* type MIME documents.�MIMEText�)�Charset)�MIMENonMultipartc@s eZdZdZddd�dd�ZdS)rz0Class for generating text/* type MIME documents.�plainN)�policycCsf|dkr4z|�d�d}Wntk
r2d}YnXtj|d|fd|idt|�i��|�||�dS)a~Create a text/* type MIME document.

        _text is the string for this message object.

        _subtype is the MIME sub content type, defaulting to "plain".

        _charset is the character set parameter added to the Content-Type
        header.  This defaults to "us-ascii".  Note that as a side-effect, the
        Content-Transfer-Encoding header will also be set.
        Nzus-asciizutf-8�textr�charset)�encode�UnicodeEncodeErrorr�__init__�str�set_payload)�self�_text�_subtype�_charsetr�r�%/usr/lib/python3.8/email/mime/text.pyrs


�zMIMEText.__init__)rN)�__name__�
__module__�__qualname__�__doc__rrrrrrsN)r�__all__�
email.charsetr�email.mime.nonmultipartrrrrrr�<module>s�h�$bytecode of module 'email.mime.text'�u��b.���h)��N}�(hBJ�@s�dZddddddgZddlmZmZdd	lmZmZdd
lm	Z	Gdd�d�Z
Gdd�de
�ZGd
d�d�ZGdd�de�Z
dS)z-A parser of RFC 2822 and MIME email messages.�Parser�HeaderParser�BytesParser�BytesHeaderParser�
FeedParser�BytesFeedParser�)�StringIO�
TextIOWrapper)rr)�compat32c@s0eZdZd
ed�dd�Zddd�Zddd	�ZdS)
rN��policycCs||_||_dS)a�Parser of RFC 2822 and MIME email messages.

        Creates an in-memory object tree representing the email message, which
        can then be manipulated and turned over to a Generator to return the
        textual representation of the message.

        The string must be formatted as a block of RFC 2822 headers and header
        continuation lines, optionally preceded by a `Unix-from' header.  The
        header block is terminated either by the end of the string or by a
        blank line.

        _class is the class to instantiate for new message objects when they
        must be created.  This class must have a constructor that can take
        zero arguments.  Default is Message.Message.

        The policy keyword specifies a policy object that controls a number of
        aspects of the parser's operation.  The default policy maintains
        backward compatibility.

        N)�_classr)�selfr
r�r�"/usr/lib/python3.8/email/parser.py�__init__szParser.__init__FcCs@t|j|jd�}|r|��|�d�}|s,q8|�|�q|��S)a\Create a message structure from the data in a file.

        Reads all the data from the file and returns the root of the message
        structure.  Optional headersonly is a flag specifying whether to stop
        parsing after reading the headers or not.  The default is False,
        meaning it parses the entire contents of the file.
        ri )rr
r�_set_headersonly�read�feed�close)r�fp�headersonly�
feedparser�datarrr�parse)s
zParser.parsecCs|jt|�|d�S)a-Create a message structure from a string.

        Returns the root of the message structure.  Optional headersonly is a
        flag specifying whether to stop parsing after reading the headers or
        not.  The default is False, meaning it parses the entire contents of
        the file.
        �r)rr�r�textrrrr�parsestr;szParser.parsestr)N)F)F)�__name__�
__module__�__qualname__r
rrrrrrrrs
c@s eZdZddd�Zddd�ZdS)	rTcCst�||d�S�NT)rr�rrrrrrrHszHeaderParser.parsecCst�||d�Sr")rrrrrrrKszHeaderParser.parsestrN)T)T)rr r!rrrrrrrGs
c@s(eZdZdd�Zd	dd�Zd
dd�ZdS)rcOst||�|_dS)a�Parser of binary RFC 2822 and MIME email messages.

        Creates an in-memory object tree representing the email message, which
        can then be manipulated and turned over to a Generator to return the
        textual representation of the message.

        The input must be formatted as a block of RFC 2822 headers and header
        continuation lines, optionally preceded by a `Unix-from' header.  The
        header block is terminated either by the end of the input or by a
        blank line.

        _class is the class to instantiate for new message objects when they
        must be created.  This class must have a constructor that can take
        zero arguments.  Default is Message.Message.
        N)r�parser)r�args�kwrrrrQszBytesParser.__init__FcCs0t|ddd�}z|j�||�W�S|��XdS)acCreate a message structure from the data in a binary file.

        Reads all the data from the file and returns the root of the message
        structure.  Optional headersonly is a flag specifying whether to stop
        parsing after reading the headers or not.  The default is False,
        meaning it parses the entire contents of the file.
        �ascii�surrogateescape)�encoding�errorsN)r	�detachr$rr#rrrrcszBytesParser.parsecCs|jddd�}|j�||�S)a2Create a message structure from a byte string.

        Returns the root of the message structure.  Optional headersonly is a
        flag specifying whether to stop parsing after reading the headers or
        not.  The default is False, meaning it parses the entire contents of
        the file.
        �ASCIIr()r*)�decoder$rrrrr�
parsebytesrszBytesParser.parsebytesN)F)F)rr r!rrr.rrrrrOs
c@s eZdZddd�Zddd�ZdS)	rTcCstj||dd�S�NTr)rrr#rrrrszBytesHeaderParser.parsecCstj||dd�Sr/)rr.rrrrr.�szBytesHeaderParser.parsebytesN)T)T)rr r!rr.rrrrr~s
N)�__doc__�__all__�iorr	�email.feedparserrr�email._policybaser
rrrrrrrr�<module>s�7/�h�!bytecode of module 'email.parser'�u��b.���%h)��N}�(hB�%�@s�dZddlZddlZddlmZmZmZmZddlm	Z	ddl
mZddlm
Z
ddlmZdd	d
ddd
ddgZe�d�ZeGdd�de��Ze�Ze`ejdd�Zejdd�Zejddd�Zejdd�ZdS)zcThis will be the home for the policy that hooks in the new
code that adds all the email6 features.
�N)�Policy�Compat32�compat32�_extend_docstrings)�_has_surrogates)�HeaderRegistry)�raw_data_manager)�EmailMessagerrr�EmailPolicy�default�strict�SMTP�HTTPz\n|\rcspeZdZdZeZdZdZe�Z	e
Z�fdd�Zdd�Z
dd	�Zd
d�Zdd
�Zdd�Zdd�Zddd�Z�ZS)r
aQ+
    PROVISIONAL

    The API extensions enabled by this policy are currently provisional.
    Refer to the documentation for details.

    This policy adds new header parsing and folding algorithms.  Instead of
    simple strings, headers are custom objects with custom attributes
    depending on the type of the field.  The folding algorithm fully
    implements RFCs 2047 and 5322.

    In addition to the settable attributes listed above that apply to
    all Policies, this policy adds the following additional attributes:

    utf8                -- if False (the default) message headers will be
                           serialized as ASCII, using encoded words to encode
                           any non-ASCII characters in the source strings.  If
                           True, the message headers will be serialized using
                           utf8 and will not contain encoded words (see RFC
                           6532 for more on this serialization format).

    refold_source       -- if the value for a header in the Message object
                           came from the parsing of some source, this attribute
                           indicates whether or not a generator should refold
                           that value when transforming the message back into
                           stream form.  The possible values are:

                           none  -- all source values use original folding
                           long  -- source values that have any line that is
                                    longer than max_line_length will be
                                    refolded
                           all  -- all values are refolded.

                           The default is 'long'.

    header_factory      -- a callable that takes two arguments, 'name' and
                           'value', where 'name' is a header field name and
                           'value' is an unfolded header field value, and
                           returns a string-like object that represents that
                           header.  A default header_factory is provided that
                           understands some of the RFC5322 header field types.
                           (Currently address fields and date fields have
                           special treatment, while all other fields are
                           treated as unstructured.  This list will be
                           completed before the extension is marked stable.)

    content_manager     -- an object with at least two methods: get_content
                           and set_content.  When the get_content or
                           set_content method of a Message object is called,
                           it calls the corresponding method of this object,
                           passing it the message object as its first argument,
                           and any arguments or keywords that were passed to
                           it as additional arguments.  The default
                           content_manager is
                           :data:`~email.contentmanager.raw_data_manager`.

    F�longcs*d|krt�|dt��t�jf|�dS)N�header_factory)�object�__setattr__r�super�__init__)�self�kw��	__class__��"/usr/lib/python3.8/email/policy.pyr]szEmailPolicy.__init__cCs|j|jS)z�+
        The implementation for this class returns the max_count attribute from
        the specialized header class that would be used to construct a header
        of type 'name'.
        )r�	max_count)r�namerrr�header_max_countdszEmailPolicy.header_max_countcCs>|d�dd�\}}|�d�d�|dd��}||�d�fS)ac+
        The name is parsed as everything up to the ':' and returned unmodified.
        The value is determined by stripping leading whitespace off the
        remainder of the first line, joining all subsequent lines together, and
        stripping any trailing carriage return or linefeed characters.  (This
        is the same as Compat32).

        r�:�z 	�N�
)�split�lstrip�join�rstrip)r�sourcelinesr�valuerrr�header_source_parsevs	zEmailPolicy.header_source_parsecCsVt|d�r$|j��|��kr$||fSt|t�rFt|���dkrFtd��||�||�fS)a�+
        The name is returned unchanged.  If the input value has a 'name'
        attribute and it matches the name ignoring case, the value is returned
        unchanged.  Otherwise the name and value are passed to header_factory
        method, and the resulting custom header object is returned as the
        value.  In this case a ValueError is raised if the input value contains
        CR or LF characters.

        rrzDHeader values may not contain linefeed or carriage return characters)	�hasattrr�lower�
isinstance�str�len�
splitlines�
ValueErrorr�rrr'rrr�header_store_parse�s

zEmailPolicy.header_store_parsecCs*t|d�r|Sd�t�|��}|�||�S)ai+
        If the value has a 'name' attribute, it is returned to unmodified.
        Otherwise the name and the value with any linesep characters removed
        are passed to the header_factory method, and the resulting custom
        header object is returned.  Any surrogateescaped bytes get turned
        into the unicode unknown-character glyph.

        rr )r)r$�linesep_splitterr"rr0rrr�header_fetch_parse�s	
zEmailPolicy.header_fetch_parsecCs|j||dd�S)a+
        Header folding is controlled by the refold_source policy setting.  A
        value is considered to be a 'source value' if and only if it does not
        have a 'name' attribute (having a 'name' attribute means it is a header
        object of some sort).  If a source value needs to be refolded according
        to the policy, it is converted into a custom header object by passing
        the name and the value with any linesep characters removed to the
        header_factory method.  Folding of a custom header object is done by
        calling its fold method with the current policy.

        Source values are split into lines using splitlines.  If the value is
        not to be refolded, the lines are rejoined using the linesep from the
        policy and returned.  The exception is lines containing non-ascii
        binary data.  In that case the value is refolded regardless of the
        refold_source setting, which causes the binary data to be CTE encoded
        using the unknown-8bit charset.

        T��
refold_binary)�_foldr0rrr�fold�szEmailPolicy.foldcCs0|j|||jdkd�}|jr dnd}|�|d�S)a+
        The same as fold if cte_type is 7bit, except that the returned value is
        bytes.

        If cte_type is 8bit, non-ASCII binary data is converted back into
        bytes.  Headers with binary data are not refolded, regardless of the
        refold_header setting, since there is no way to know whether the binary
        data consists of single byte characters or multibyte characters.

        If utf8 is true, headers are encoded to utf8, otherwise to ascii with
        non-ASCII unicode rendered as encoded words.

        �7bitr4�utf8�ascii�surrogateescape)r6�cte_typer9�encode)rrr'�folded�charsetrrr�fold_binary�szEmailPolicy.fold_binarycs�t|d�r|j|d�S|jr"|jntj�|��}|jdkp�|jdko�|rdt|d�t|�d�kp�t�fdd�|d	d�D��}|s�|r�t	|�r�|�
|d
�|��j|d�S|d|j�|�|jS)Nr)�policy�allrr�c3s|]}t|��kVqdS)N)r-)�.0�x��maxlenrr�	<genexpr>�sz$EmailPolicy._fold.<locals>.<genexpr>rr z: )
r)r7�max_line_length�sys�maxsizer.�
refold_sourcer-�anyrrr$�linesep)rrr'r5�lines�refoldrrFrr6�s


 �zEmailPolicy._fold)F)�__name__�
__module__�__qualname__�__doc__r	�message_factoryr9rLrrr�content_managerrrr(r1r3r7r@r6�
__classcell__rrrrr
s:
T)�raise_on_defectr!)rN)rNrI)r9)rT�rerJ�email._policybaserrrr�email.utilsr�email.headerregistryr�email.contentmanagerr�
email.messager	�__all__�compiler2r
rr�clonerr
r�SMTPUTF8rrrr�<module>s4�
@�h�!bytecode of module 'email.policy'�u��b.��.h)��N}�(hB��
@sXdZddddddddd	d
g
ZddlZdd
lmZmZmZdZdZdZ	dd�e
d�D�Zedd�Zedd�Z
de�d�e�d�D]Zee�ee<q�deed�<dD]Zee�e
e<q�dd�Zdd�Zdd�Zdd�Zd,dd �Zd!d
�Zd"d	�Zd-d$d�Ze
dd�Zd%D]Zee�ee<�qd&efd'd�Zefd(d�ZeZeZd)d*�Zd+d�Z dS).aFQuoted-printable content transfer encoding per RFCs 2045-2047.

This module handles the content transfer encoding method defined in RFC 2045
to encode US ASCII-like 8-bit data called `quoted-printable'.  It is used to
safely encode text that is in a character set similar to the 7-bit US ASCII
character set, but that includes some 8-bit characters that are normally not
allowed in email bodies or headers.

Quoted-printable is very space-inefficient for encoding binary files; use the
email.base64mime module for that instead.

This module provides an interface to encode and decode both headers and bodies
with quoted-printable encoding.

RFC 2045 defines a method for including character set information in an
`encoded-word' in a header.  This method is commonly used for 8-bit real names
in To:/From:/Cc: etc. fields, as well as Subject: lines.

This module does not do the line wrapping or end-of-line character
conversion necessary for proper internationalized headers; it only
does dumb encoding and decoding.  To deal with the various line
wrapping issues, use the email.header module.
�body_decode�body_encode�body_length�decode�decodestring�
header_decode�
header_encode�
header_length�quote�unquote�N)�
ascii_letters�digits�	hexdigits�
�
�cCsg|]}d|�qS)z=%02X�)�.0�crr�&/usr/lib/python3.8/email/quoprimime.py�
<listcomp>7sr�s-!*+/�ascii�_� s_ !"#$%&'()*+,-./0123456789:;<>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~	cCst|�t|kS)z>Return True if the octet should be escaped with header quopri.)�chr�_QUOPRI_HEADER_MAP��octetrrr�header_checkJsrcCst|�t|kS)z<Return True if the octet should be escaped with body quopri.)r�_QUOPRI_BODY_MAPrrrr�
body_checkOsr!cCstdd�|D��S)a:Return a header quoted-printable encoding length.

    Note that this does not include any RFC 2047 chrome added by
    `header_encode()`.

    :param bytearray: An array of bytes (a.k.a. octets).
    :return: The length in bytes of the byte array when it is encoded with
        quoted-printable for headers.
    css|]}tt|�VqdS�N)�lenr�rrrrr�	<genexpr>^sz header_length.<locals>.<genexpr>��sum��	bytearrayrrrrTs
cCstdd�|D��S)z�Return a body quoted-printable encoding length.

    :param bytearray: An array of bytes (a.k.a. octets).
    :return: The length in bytes of the byte array when it is encoded with
        quoted-printable for bodies.
    css|]}tt|�VqdSr")r#r r$rrrr%hszbody_length.<locals>.<genexpr>r&r(rrrrascCsft|t�st|�}|s&|�|���n<t|d�t|�|krT|d||7<n|�|���dS)N���)�
isinstance�strr�append�lstripr#)�L�s�maxlen�extrarrr�_max_appendks
r3cCstt|dd�d��S)zDTurn a string in the form =AB to the ASCII character with value 0xab���)r�int�r0rrrr
vscCstt|�Sr")�_QUOPRI_MAP�ord)rrrrr	{s�
iso-8859-1cCs$|sdS|�d��t�}d||fS)a�Encode a single header line with quoted-printable (like) encoding.

    Defined in RFC 2045, this `Q' encoding is similar to quoted-printable, but
    used specifically for email header fields to allow charsets with mostly 7
    bit characters (and some 8 bit) to remain more or less readable in non-RFC
    2045 aware mail clients.

    charset names the character set to use in the RFC 2046 header.  It
    defaults to iso-8859-1.
    r�latin1z=?%s?q?%s?=)r�	translater)�header_bytes�charset�encodedrrrrss
�Lc
Cs�|dkrtd��|s|S|�t�}d|}|d}g}|j}|��D�]}d}t|�d|}	||	kr�||}
||
ddkr�||||
d��|
d}q^||
ddkr�||||
��|
d}q^||||
�d�|
}q^|�rR|ddk�rR||	}|d	k�rt|d�}n(|dk�r,|d|}n|t|d�}|||d�|�qD|||d
��qD|dtk�rz|d�|�|�S)a�Encode with quoted-printable, wrapping at maxlinelen characters.

    Each line of encoded text will end with eol, which defaults to "\n".  Set
    this to "\r\n" if you will be using the result of this function directly
    in an email.

    Each line will be wrapped at, at most, maxlinelen characters before the
    eol string (maxlinelen defaults to 76 characters, the maximum value
    permitted by RFC 2045).  Long lines will have the 'soft line break'
    quoted-printable character "=" appended to them, so the decoded text will
    be identical to the original text.

    The minimum maxlinelen is 4 to have room for a quoted character ("=XX")
    followed by a soft line break.  Smaller values will generate a
    ValueError.

    �zmaxlinelen must be at least 4�=r4r�r*z 	r5Nr)	�
ValueErrorr=�_QUOPRI_BODY_ENCODE_MAPr-�
splitlinesr#r	�CRLF�join)
�body�
maxlinelen�eol�
soft_break�maxlinelen1�encoded_bodyr-�line�start�	laststart�stop�room�qrrrr�sD




cCs|s|Sd}|��D]�}|��}|s.||7}qd}t|�}||kr||}|dkrd||7}|d7}nv|d|kr||d7}q:n^|d|kr�||dtkr�||dtkr�|t|||d��7}|d7}n||7}|d7}||kr:||7}q:q|ddk�r|�|��r|d	d�}|S)
z_Decode a quoted-printable string.

    Lines are separated with eol, which defaults to \n.
    rrrCr4rDr5r*rN)rG�rstripr#rr
�endswith)r@rL�decodedrP�i�nrrrrr�s8
,
cCs|�d�}t|�S)zCTurn a match in the form =AB to the ASCII character with value 0xabr)�groupr
)�matchr0rrr�_unquote_matchs
r]cCs |�dd�}tjdt|tjd�S)aDecode a string encoded with RFC 2045 MIME header `Q' encoding.

    This function does not parse a full MIME header value encoded with
    quoted-printable (like =?iso-8859-1?q?Hello_World?=) -- please use
    the high level email.header class for that functionality.
    rrz=[a-fA-F0-9]{2})�flags)�replace�re�subr]�ASCIIr8rrrr#s)r)r;)!�__doc__�__all__r`�stringrr
rrH�NL�EMPTYSTRING�ranger9rr �encoderrr:rr!rrr3r
r	rrFrrrrr]rrrrr�<module>sR�




O0�h�%bytecode of module 'email.quoprimime'�u��b.��q%h)��N}�(hB6%�@sjdZddddddddd	d
ddd
ddgZddlZddlZddlZddlZddlZddlZddlZ	ddl
mZddl
mZ
ddl
mZddl
mZmZmZddlmZdZdZdZdZdZe�d�Ze�d�Zdd�Zdd �Zd7d"d�Zd#d�Zd$d%�Z d8d'd�Z!d9d(d�Z"d:d)d	�Z#d*d�Z$d+d�Z%d,d�Z&d-d�Z'd;d.d�Z(e�d/ej)�Z*d0d�Z+d<d3d�Z,d=d5d6�Z-dS)>zMiscellaneous utilities.�collapse_rfc2231_value�
decode_params�decode_rfc2231�encode_rfc2231�
formataddr�
formatdate�format_datetime�getaddresses�
make_msgid�	mktime_tz�	parseaddr�	parsedate�parsedate_tz�parsedate_to_datetime�unquote�N)�quote)�AddressList)r
)rr
�
_parsedate_tz)�Charsetz, �z
�'z[][\\()<>@,:;".]z[\\"]cCs*z|��WdStk
r$YdSXdS)z8Return True if s contains surrogate-escaped binary data.FTN)�encode�UnicodeEncodeError)�s�r�!/usr/lib/python3.8/email/utils.py�_has_surrogates3s
rcCs|�dd�}|�dd�S)N�utf-8�surrogateescape�replace)r�decode)�string�original_bytesrrr�	_sanitize@sr#rcCs�|\}}|�d�|r�z|�d�Wn<tk
r`t|t�rFt|�}|�|�}d||fYSXd}t�|�rtd}t�	d|�}d||||fS|S)a�The inverse of parseaddr(), this takes a 2-tuple of the form
    (realname, email_address) and returns the string value suitable
    for an RFC 2822 From, To or Cc header.

    If the first element of pair is false, then the second element is
    returned unmodified.

    The optional charset is the character set that is used to encode
    realname in case realname is not ASCII safe.  Can be an instance of str or
    a Charset-like object which has a header_encode method.  Default is
    'utf-8'.
    �asciiz%s <%s>r�"z\\\g<0>z%s%s%s <%s>)
rr�
isinstance�strr�
header_encode�
specialsre�search�	escapesre�sub)�pair�charset�name�address�encoded_name�quotesrrrrLs 




cCst�|�}t|�}|jS)z7Return a list of (REALNAME, EMAIL) for each fieldvalue.)�
COMMASPACE�join�_AddressList�addresslist)�fieldvalues�all�arrrrns
cCsfddddddddg|d	|d
ddd
dddddddddg|dd|d|d|d|d|fS)Nz"%s, %02d %s %04d %02d:%02d:%02d %s�Mon�Tue�Wed�Thu�Fri�Sat�Sun���Jan�Feb�Mar�Apr�May�Jun�Jul�Aug�Sep�Oct�Nov�Dec�r���r)�	timetuple�zonerrr�_format_timetuple_and_zoneus&�
��rUFcCsR|dkrt��}|s|r,tj�|tjj�}ntj�|�}|rH|��}d}t||�S)a�Returns a date string as specified by RFC 2822, e.g.:

    Fri, 09 Nov 2001 01:08:47 -0000

    Optional timeval if given is a floating point time value as accepted by
    gmtime() and localtime(), otherwise the current time is used.

    Optional localtime is a flag that when True, interprets timeval, and
    returns a date relative to the local timezone instead of UTC, properly
    taking daylight savings time into account.

    Optional argument usegmt means that the timezone is written out as
    an ascii string, not numeric one (so "GMT" instead of "+0000"). This
    is needed for HTTP, and is only used when localtime==False.
    NF)�time�datetime�
fromtimestamp�timezone�utc�utcfromtimestamp�
astimezoner)�timeval�	localtime�usegmt�dtrrrr~scCsV|��}|r2|jdks$|jtjjkr,td��d}n|jdkrBd}n
|�d�}t||�S)a$Turn a datetime into a date string as specified in RFC 2822.

    If usegmt is True, dt must be an aware datetime with an offset of zero.  In
    this case 'GMT' will be rendered instead of the normal +0000 required by
    RFC2822.  This is to support HTTP headers involving date stamps.
    Nz%usegmt option requires a UTC datetime�GMTz-0000z%z)rS�tzinforWrYrZ�
ValueError�strftimerU)r`r_�nowrTrrrr�s

cCs^tt��d�}t��}t�d�}|dkr0d}nd|}|dkrHt��}d|||||f}|S)a{Returns a string suitable for RFC 2822 compliant Message-ID, e.g:

    <142480216486.20800.16526388040877946887@nightshade.la.mastaler.com>

    Optional idstring if given is a string used to strengthen the
    uniqueness of the message id.  Optional domain if given provides the
    portion of the message id after the '@'.  It defaults to the locally
    defined hostname.
    �d�@Nr�.z<%d.%d.%d%s@%s>)�intrV�os�getpid�random�getrandbits�socket�getfqdn)�idstring�domainr]�pid�randint�msgidrrrr	�s

cCsNt|��^}}|dkr(tj|dd��Stj|dd�dt�tj|d��i�S)NrArb��seconds)rrWrY�	timedelta)�data�dtuple�tzrrrr�s�cCst|�j}|sdS|dS)z�
    Parse addr into its constituent realname and email address parts.

    Return a tuple of realname and email address, unless the parse fails, in
    which case return a 2-tuple of ('', '').
    )rrr)r5r6)�addr�addrsrrrr�s
cCs`t|�dkr\|�d�r<|�d�r<|dd��dd��dd�S|�d�r\|�d�r\|dd�S|S)	zRemove quotes from a string.rOr%���z\\�\z\"�<�>)�len�
startswith�endswithr)r'rrrr�scCs&|�td�}t|�dkr"dd|fS|S)z#Decode string according to RFC 2231rBN)�split�TICKr�)r�partsrrrr�s
cCsDtjj|d|pdd�}|dkr*|dkr*|S|dkr6d}d|||fS)z�Encode string according to RFC 2231.

    If neither charset nor language is given, then s is returned as-is.  If
    charset is given but not language, the string is encoded using the empty
    string for language.
    rr$)�safe�encodingNz%s'%s'%s)�urllib�parser)rr.�languagerrrr�sz&^(?P<name>\w+)\*((?P<num>[0-9]+)\*?)?$c
Csl|dd�}g}i}|�d�\}}|�||f�|r�|�d�\}}|�d�rRd}nd}t|�}t�|�}|r�|�dd�\}}|dk	r�t|�}|�|g��|||f�q0|�|dt	|�f�q0|�rh|�
�D]�\}}g}d}	|��|D].\}}
}|�rtj
j|
d	d
�}
d}	|�|
�q�t	t�|��}|	�rTt|�\}}}|�|||d|ff�q�|�|d|f�q�|S)zDecode parameters list according to RFC 2231.

    params is a sequence of 2-tuples containing (param name, string value).
    Nr�*TFr/�numz"%s"zlatin-1)r�)�pop�appendr�r�rfc2231_continuation�match�groupri�
setdefaultr�items�sortr�r��EMPTYSTRINGr4r)
�params�
new_params�rfc2231_paramsr/�value�encoded�mor��
continuations�extendedrr.r�rrrrsD

r�us-asciicCsnt|t�rt|�dkrt|�S|\}}}|dkr4|}t|d�}zt|||�WStk
rht|�YSXdS)NrPzraw-unicode-escape)r&�tupler�r�bytesr'�LookupError)r��errors�fallback_charsetr.r��text�rawbytesrrrr9s

r}c	Cs|dkrtj�tjj���S|jdk	r.|��S|��dd�|f}t�|�}t�	|�}z tj
|jd�}t�||j�}Wn�t
k
r�|tjt�|�dd��}tjo�|jdk}|r�tjntj}|tj
|d�kr�t�|tj|�}n
t�|�}YnX|j|d�S)a�Return local time as an aware datetime object.

    If called without arguments, return current time.  Otherwise *dt*
    argument should be a datetime instance, and it is converted to the
    local time zone according to the system time zone database.  If *dt* is
    naive (that is, dt.tzinfo is None), it is assumed to be in local time.
    In this case, a positive or zero value for *isdst* causes localtime to
    presume initially that summer time (for example, Daylight Saving Time)
    is or is not (respectively) in effect for the specified time.  A
    negative value for *isdst* causes the localtime() function to attempt
    to divine whether summer time is in effect for the specified time.

    Nr}rurAr)rb)rWrerYrZr\rbrSrV�mktimer^rw�	tm_gmtoff�tm_zone�AttributeError�gmtime�daylight�tm_isdst�altzone�tznamer)	r`�isdst�tmrv�localtm�deltarz�dst�gmtoffrrrr^Ss$


r^)r)NFF)F)NN)NN)rr�)Nr}).�__doc__�__all__rj�rerVrlrnrW�urllib.parser��email._parseaddrrrr5r
rr
r�
email.charsetrr3r��UEMPTYSTRING�CRLFr��compiler)r+rr#rrrUrrr	rrrrr�ASCIIr�rrr^rrrr�<module>sp�



"	



�8�
�h� bytecode of module 'email.utils'�u��b.���h)��N}�(hB��@s&ddlmZdgZGdd�de�ZdS)�)�IntEnum�
HTTPStatusc@seZdZdZdAdd�ZdZdZdZdZd	Z	d
Z
dZdZd
Z
dZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZd Z d!Z!d"Z"d#Z#d$Z$d%Z%d&Z&d'Z'd(Z(d)Z)d*Z*d+Z+d,Z,d-Z-d.Z.d/Z/d0Z0d1Z1d2Z2d3Z3d4Z4d5Z5d6Z6d7Z7d8Z8d9Z9d:Z:d;Z;d<Z<d=Z=d>Z>d?Z?d@S)Bra�HTTP status codes and reason phrases

    Status codes from the following RFCs are all observed:

        * RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 2616
        * RFC 6585: Additional HTTP Status Codes
        * RFC 3229: Delta encoding in HTTP
        * RFC 4918: HTTP Extensions for WebDAV, obsoletes 2518
        * RFC 5842: Binding Extensions to WebDAV
        * RFC 7238: Permanent Redirect
        * RFC 2295: Transparent Content Negotiation in HTTP
        * RFC 2774: An HTTP Extension Framework
        * RFC 7725: An HTTP Status Code to Report Legal Obstacles
        * RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2)
    �cCs"t�||�}||_||_||_|S)N)�int�__new__�_value_�phrase�description)�cls�valuerr	�obj�r
�#/usr/lib/python3.8/http/__init__.pyrs
zHTTPStatus.__new__)�d�Continuez!Request received, please continue)�ezSwitching Protocolsz.Switching to new protocol; obey Upgrade header)�f�
Processing)���OKz#Request fulfilled, document follows)���CreatedzDocument created, URL follows)���Acceptedz/Request accepted, processing continues off-line)��zNon-Authoritative InformationzRequest fulfilled from cache)��z
No Contentz"Request fulfilled, nothing follows)��z
Reset Contentz"Clear input form for further input)��zPartial ContentzPartial content follows)��zMulti-Status)��zAlready Reported)��zIM Used)i,zMultiple Choicesz,Object has several resources -- see URI list)i-zMoved Permanently�(Object moved permanently -- see URI list)i.�Found�(Object moved temporarily -- see URI list)i/z	See Otherz'Object moved -- see Method and URL list)i0zNot Modifiedz)Document has not changed since given time)i1z	Use Proxyz@You must use proxy specified in Location to access this resource)i3zTemporary Redirectr#)i4zPermanent Redirectr!)i�zBad Requestz(Bad request syntax or unsupported method)i��Unauthorizedz*No permission -- see authorization schemes)i�zPayment Requiredz"No payment -- see charging schemes)i��	Forbiddenz0Request forbidden -- authorization will not help)i�z	Not FoundzNothing matches the given URI)i�zMethod Not Allowedz-Specified method is invalid for this resource)i�zNot Acceptablez%URI not available in preferred format)i�zProxy Authentication Requiredz7You must authenticate with this proxy before proceeding)i�zRequest Timeoutz"Request timed out; try again later)i��ConflictzRequest conflict)i��Gonez5URI no longer exists and has been permanently removed)i�zLength Requiredz"Client must specify Content-Length)i�zPrecondition Failedz Precondition in headers is false)i�zRequest Entity Too LargezEntity is too large)i�zRequest-URI Too LongzURI is too long)i�zUnsupported Media Typez!Entity body in unsupported format)i�zRequested Range Not SatisfiablezCannot satisfy request range)i�zExpectation Failedz'Expect condition could not be satisfied)i�zMisdirected Requestz(Server is not able to produce a response)i�zUnprocessable Entity)i��Locked)i�zFailed Dependency)i�zUpgrade Required)i�zPrecondition Requiredz8The origin server requires the request to be conditional)i�zToo Many RequestszOThe user has sent too many requests in a given amount of time ("rate limiting"))i�zRequest Header Fields Too LargezVThe server is unwilling to process the request because its header fields are too large)i�zUnavailable For Legal ReasonszOThe server is denying access to the resource as a consequence of a legal demand)i�zInternal Server ErrorzServer got itself in trouble)i�zNot Implementedz&Server does not support this operation)i�zBad Gatewayz+Invalid responses from another server/proxy)i�zService Unavailablez8The server cannot process the request due to a high load)i�zGateway Timeoutz4The gateway server did not receive a timely response)i�zHTTP Version Not SupportedzCannot fulfill request)i�zVariant Also Negotiates)i�zInsufficient Storage)i�z
Loop Detected)i�zNot Extended)i�zNetwork Authentication Requiredz7The client needs to authenticate to gain network accessN)r)@�__name__�
__module__�__qualname__�__doc__r�CONTINUE�SWITCHING_PROTOCOLS�
PROCESSINGr�CREATED�ACCEPTED�NON_AUTHORITATIVE_INFORMATION�
NO_CONTENT�
RESET_CONTENT�PARTIAL_CONTENT�MULTI_STATUS�ALREADY_REPORTED�IM_USED�MULTIPLE_CHOICES�MOVED_PERMANENTLY�FOUND�	SEE_OTHER�NOT_MODIFIED�	USE_PROXY�TEMPORARY_REDIRECT�PERMANENT_REDIRECT�BAD_REQUEST�UNAUTHORIZED�PAYMENT_REQUIRED�	FORBIDDEN�	NOT_FOUND�METHOD_NOT_ALLOWED�NOT_ACCEPTABLE�PROXY_AUTHENTICATION_REQUIRED�REQUEST_TIMEOUT�CONFLICT�GONE�LENGTH_REQUIRED�PRECONDITION_FAILED�REQUEST_ENTITY_TOO_LARGE�REQUEST_URI_TOO_LONG�UNSUPPORTED_MEDIA_TYPE�REQUESTED_RANGE_NOT_SATISFIABLE�EXPECTATION_FAILED�MISDIRECTED_REQUEST�UNPROCESSABLE_ENTITY�LOCKED�FAILED_DEPENDENCY�UPGRADE_REQUIRED�PRECONDITION_REQUIRED�TOO_MANY_REQUESTS�REQUEST_HEADER_FIELDS_TOO_LARGE�UNAVAILABLE_FOR_LEGAL_REASONS�INTERNAL_SERVER_ERROR�NOT_IMPLEMENTED�BAD_GATEWAY�SERVICE_UNAVAILABLE�GATEWAY_TIMEOUT�HTTP_VERSION_NOT_SUPPORTED�VARIANT_ALSO_NEGOTIATES�INSUFFICIENT_STORAGE�
LOOP_DETECTED�NOT_EXTENDED�NETWORK_AUTHENTICATION_REQUIREDr
r
r
rrsz
	N)�enumr�__all__rr
r
r
r�<module>s�h�bytecode of module 'http'�u��b.����h)��N}�(hBK��@sfdZddlZddlZddlZddlZddlZddlZddlZ	ddl
mZdddddd	d
ddd
ddddddddgZdZ
dZdZdZdZdZe��ejj�dd�ejj��D�ZdZdZe�d �jZe�d!�jZe�d"�Z e�d#�Z!d$d%d&hZ"dBd(d)�Z#Gd*d+�d+ej$j%�Z&d,d-�Z'e&fd.d/�Z(Gd0d�dej)�Z*Gd1d�d�Z+zddl,Z,Wne-k
�r`YnXGd2d3�d3e+�Z.e�/d3�Gd4d�de0�Z1Gd5d�de1�Z2Gd6d�de1�Z3Gd7d�de1�Z4Gd8d	�d	e1�Z5Gd9d
�d
e1�Z6Gd:d�de1�Z7Gd;d
�d
e1�Z8Gd<d�de8�Z9Gd=d�de8�Z:Gd>d�de8�Z;Gd?d�de1�Z<Gd@d�de1�Z=GdAd�de>e<�Z?e1Z@dS)Ca�
HTTP/1.1 client library

<intro stuff goes here>
<other stuff, too>

HTTPConnection goes through a number of "states", which define when a client
may legally make another request or fetch the response for a particular
request. This diagram details these state transitions:

    (null)
      |
      | HTTPConnection()
      v
    Idle
      |
      | putrequest()
      v
    Request-started
      |
      | ( putheader() )*  endheaders()
      v
    Request-sent
      |\_____________________________
      |                              | getresponse() raises
      | response = getresponse()     | ConnectionError
      v                              v
    Unread-response                Idle
    [Response-headers-read]
      |\____________________
      |                     |
      | response.read()     | putrequest()
      v                     v
    Idle                  Req-started-unread-response
                     ______/|
                   /        |
   response.read() |        | ( putheader() )*  endheaders()
                   v        v
       Request-started    Req-sent-unread-response
                            |
                            | response.read()
                            v
                          Request-sent

This diagram presents the following rules:
  -- a second request may not be started until {response-headers-read}
  -- a response [object] cannot be retrieved until {request-sent}
  -- there is no differentiation between an unread response body and a
     partially read response body

Note: this enforcement is applied by the HTTPConnection class. The
      HTTPResponse class does not enforce this state machine, which
      implies sophisticated clients may accelerate the request/response
      pipeline. Caution should be taken, though: accelerating the states
      beyond the above pattern may imply knowledge of the server's
      connection-close behavior for certain requests. For example, it
      is impossible to tell whether the server will close the connection
      UNTIL the response headers have been read; this means that further
      requests cannot be placed into the pipeline until it is known that
      the server will NOT be closing the connection.

Logical State                  __state            __response
-------------                  -------            ----------
Idle                           _CS_IDLE           None
Request-started                _CS_REQ_STARTED    None
Request-sent                   _CS_REQ_SENT       None
Unread-response                _CS_IDLE           <response_class>
Req-started-unread-response    _CS_REQ_STARTED    <response_class>
Req-sent-unread-response       _CS_REQ_SENT       <response_class>
�N)�urlsplit�HTTPResponse�HTTPConnection�
HTTPException�NotConnected�UnknownProtocol�UnknownTransferEncoding�UnimplementedFileMode�IncompleteRead�
InvalidURL�ImproperConnectionState�CannotSendRequest�CannotSendHeader�ResponseNotReady�
BadStatusLine�LineTooLong�RemoteDisconnected�error�	responses�Pi��UNKNOWN�IdlezRequest-startedzRequest-sentcCsi|]}||j�qS�)�phrase)�.0�vrr�!/usr/lib/python3.8/http/client.py�
<dictcomp>jsri�ds[^:\s][^:\r\n]*s\n(?![ \t])|\r(?![ \t\n])z[- ]z[-]�PATCH�POST�PUT�datac
Cshz|�d�WStk
rb}z8t|j|j|j|jd|��||j|j�|f�d�W5d}~XYnXdS)z<Call data.encode("latin-1") but show a better error message.�latin-1z`%s (%.20r) is not valid Latin-1. Use %s.encode('utf-8') if you want to send it encoded in UTF-8.N)�encode�UnicodeEncodeError�encoding�object�start�end�title)r"�name�errrrr�_encode�s���r-c@seZdZdd�ZdS)�HTTPMessagecCsj|��d}t|�}g}d}|��D]@}|d|���|krBd}n|dd���sVd}|r$|�|�q$|S)a�Find all header lines matching a given header name.

        Look through the list of headers and find all lines matching a given
        header name (and their continuation lines).  A list of the lines is
        returned, without interpretation.  If the header does not occur, an
        empty list is returned.  If the header occurs multiple times, all
        occurrences are returned.  Case is not important in the header name.

        �:rN�)�lower�len�keys�isspace�append)�selfr+�n�lst�hit�linerrr�getallmatchingheaders�s
z!HTTPMessage.getallmatchingheadersN)�__name__�
__module__�__qualname__r;rrrrr.�sr.cCsXg}|�td�}t|�tkr&td��|�|�t|�tkrHtdt��|dkrqTq|S)z�Reads potential header lines into a list from a file pointer.

    Length of line is limited by _MAXLINE, and number of
    headers is limited by _MAXHEADERS.
    r0�header linezgot more than %d headers��
�
�)�readline�_MAXLINEr2rr5�_MAXHEADERSr)�fp�headersr:rrr�
_read_headers�s
rIcCs,t|�}d�|��d�}tjj|d��|�S)aGParses only RFC2822 headers from a file pointer.

    email Parser wants to see strings rather than bytes.
    But a TextIOWrapper around self.rfile would buffer too many bytes
    from the stream, bytes which we later need to read as bytes.
    So we read the correct bytes here, as bytes, for email Parser
    to parse.

    rC�
iso-8859-1)�_class)rI�join�decode�email�parser�Parser�parsestr)rGrKrH�hstringrrr�
parse_headers�s
rScseZdZd@dd�Zdd�Zdd�Zd	d
�Zdd�Z�fd
d�Z�fdd�Z	dd�Z
dd�ZdAdd�Zdd�Z
dd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�ZdBd(d)�ZdCd*d+�ZdD�fd,d-�	Zd.d/�Zd0d1�Zd2d3�ZdEd4d5�Zd6d7�Zd8d9�Zd:d;�Zd<d=�Zd>d?�Z �Z!S)FrrNcCsR|�d�|_||_||_d|_|_t|_t|_t|_	t|_
t|_t|_t|_
dS)N�rb)�makefilerG�
debuglevel�_methodrH�msg�_UNKNOWN�version�status�reason�chunked�
chunk_left�length�
will_close)r6�sockrV�method�urlrrr�__init__�szHTTPResponse.__init__cCst|j�td�d�}t|�tkr*td��|jdkrBtdt|��|sNt	d��z|�
dd�\}}}WnFtk
r�z|�
dd�\}}d}Wntk
r�d}YnXYnX|�d	�s�|�
�t|��z$t|�}|d
ks�|dkr�t|��Wntk
�rt|��YnX|||fS)Nr0rJzstatus linerzreply:z-Remote end closed connection without response��zHTTP/ri�)�strrGrDrEr2rrV�print�reprr�split�
ValueError�
startswith�_close_connr�int)r6r:rZr[r\rrr�_read_statuss2

zHTTPResponse._read_statusc	Cs�|jdk	rdS|��\}}}|tkr&qHt|j�}|jdkrDtd|�~q||_|_|�	�|_
|dkrnd|_n|�d�r�d|_nt
|��t|j�|_|_|jdkr�|j��D]\}}td|d|�q�|j�d	�}|r�|��d
kr�d|_d|_nd|_|��|_d|_|j�d
�}|�rb|j�sbzt|�|_Wntk
�rLd|_YnX|jdk�rhd|_nd|_|tk�s�|tk�s�d|k�r�dk�s�n|jdk�r�d|_|j�s�|j�s�|jdk�r�d|_dS)Nrzheaders:)zHTTP/1.0zHTTP/0.9�
zHTTP/1.��header:r/�transfer-encodingr]TF�content-lengthr���HEAD)rHro�CONTINUErIrGrVrh�coder[�stripr\rZrlrrSrX�items�getr1r]r^�_check_closer`r_rnrk�
NO_CONTENT�NOT_MODIFIEDrW)	r6rZr[r\�skipped_headers�hdr�val�tr_encr_rrr�begin5sf







�
�
���zHTTPResponse.begincCsv|j�d�}|jdkr.|r*d|��kr*dSdS|j�d�r>dS|rRd|��krRdS|j�d�}|rrd|��krrdSdS)N�
connectionrq�closeTFz
keep-alivezproxy-connection)rHr{rZr1)r6�conn�pconnrrrr|}s
zHTTPResponse._check_closecCs|j}d|_|��dS�N)rGr�)r6rGrrrrm�szHTTPResponse._close_conncs$zt���W5|jr|��XdSr�)rGrm�superr��r6��	__class__rrr��szHTTPResponse.closecst���|jr|j��dSr�)r��flushrGr�r�rrr��s
zHTTPResponse.flushcCsdS)zAlways returns TrueTrr�rrr�readable�szHTTPResponse.readablecCs
|jdkS)z!True if the connection is closed.N)rGr�rrr�isclosed�szHTTPResponse.isclosedcCs�|jdkrdS|jdkr$|��dS|dk	rRt|�}|�|�}t|�d|���S|jr`|��S|j	dkrv|j�
�}n6z|�|j	�}Wntk
r�|���YnXd|_	|��|SdS)NrCrvr)
rGrWrm�	bytearray�readinto�
memoryview�tobytesr]�_readall_chunkedr_�read�
_safe_readr
)r6�amt�br7�srrrr��s*



zHTTPResponse.readcCs�|jdkrdS|jdkr$|��dS|jr4|�|�S|jdk	r^t|�|jkr^t|�d|j�}|j�|�}|s||r||��n&|jdk	r�|j|8_|js�|��|S)z^Read up to len(b) bytes into bytearray b and return the number
        of bytes read.
        Nrrv)	rGrWrmr]�_readinto_chunkedr_r2r�r�)r6r�r7rrrr��s$





zHTTPResponse.readintocCsr|j�td�}t|�tkr$td��|�d�}|dkrB|d|�}zt|d�WStk
rl|���YnXdS)Nr0z
chunk size�;r�)	rGrDrEr2r�findrnrkrm)r6r:�irrr�_read_next_chunk_sizes
z"HTTPResponse._read_next_chunk_sizecCs:|j�td�}t|�tkr$td��|s*q6|dkrq6qdS)Nr0ztrailer liner@)rGrDrEr2r�r6r:rrr�_read_and_discard_trailersz&HTTPResponse._read_and_discard_trailercCsl|j}|sh|dk	r|�d�z|��}Wntk
rDtd��YnX|dkrb|��|��d}||_|S)NrerCr)r^r�r�rkr
r�rm)r6r^rrr�_get_chunk_left s
zHTTPResponse._get_chunk_leftcCsp|jtkst�g}z6|��}|dkr&q>|�|�|��d|_qd�|�WStk
rjtd�|���YnXdS�NrrC)	r]rY�AssertionErrorr�r5r�r^rLr
)r6�valuer^rrrr�8szHTTPResponse._readall_chunkedcCs�|jtkst�d}t|�}zv|��}|dkr2|WSt|�|kr\|�|�}|||_||WS|d|�}|�|�}||d�}||7}d|_qWn(tk
r�tt	|d|����YnXdS)Nr)
r]rYr�r�r�r2�_safe_readintor^r
�bytes)r6r��total_bytes�mvbr^r7�temp_mvbrrrr�Fs$



zHTTPResponse._readinto_chunkedcCs.|j�|�}t|�|kr*t||t|���|S)aRead the number of bytes requested.

        This function should be used when <amt> bytes "should" be present for
        reading. If the bytes are truly not available (due to EOF), then the
        IncompleteRead exception can be used to detect the problem.
        )rGr�r2r
)r6r�r"rrrr�^szHTTPResponse._safe_readcCs:t|�}|j�|�}||kr6tt|d|��||��|S)z2Same as _safe_read, but for reading into a buffer.N)r2rGr�r
r�)r6r�r�r7rrrr�js
zHTTPResponse._safe_readinto���cCs�|jdks|jdkrdS|jr(|�|�S|jdk	rJ|dksD||jkrJ|j}|j�|�}|sh|rh|��n|jdk	r�|jt|�8_|S)zvRead with at most one underlying system call.  If at least one
        byte is buffered, return that instead.
        NrvrCr)rGrWr]�_read1_chunkedr_�read1rmr2)r6r7�resultrrrr�rs


zHTTPResponse.read1cCs4|jdks|jdkrdS|jr(|�|�S|j�|�S)NrvrC)rGrWr]�
_peek_chunked�peek)r6r7rrrr��s

zHTTPResponse.peekcs�|jdks|jdkrdS|jr*t��|�S|jdk	rL|dksF||jkrL|j}|j�|�}|sj|rj|��n|jdk	r�|jt|�8_|S)NrvrCr)rGrWr]r�rDr_rmr2)r6�limitr�r�rrrD�s

zHTTPResponse.readlinecCsd|��}|dks|dkrdSd|kr0|ks6n|}|j�|�}|jt|�8_|s`td��|Sr�)r�rGr�r^r2r
)r6r7r^r�rrrr��szHTTPResponse._read1_chunkedcCsDz|��}Wntk
r"YdSX|dkr0dS|j�|�d|�S)NrC)r�r
rGr�)r6r7r^rrrr��szHTTPResponse._peek_chunkedcCs
|j��Sr�)rG�filenor�rrrr��szHTTPResponse.filenocCsF|jdkrt��|j�|�p|}t|t�s4t|d�s8|Sd�|�SdS)axReturns the value of the header matching *name*.

        If there are multiple matching headers, the values are
        combined into a single string separated by commas and spaces.

        If no matching header is found, returns *default* or None if
        the *default* is not specified.

        If the headers are unknown, raises http.client.ResponseNotReady.

        N�__iter__z, )rHr�get_all�
isinstancerg�hasattrrL)r6r+�defaultrHrrr�	getheader�s
zHTTPResponse.getheadercCs|jdkrt��t|j���S)z&Return list of (header, value) tuples.N)rHr�listrzr�rrr�
getheaders�s
zHTTPResponse.getheaderscCs|Sr�rr�rrrr��szHTTPResponse.__iter__cCs|jS)ajReturns an instance of the class mimetools.Message containing
        meta-information associated with the URL.

        When the method is HTTP, these headers are those returned by
        the server at the head of the retrieved HTML page (including
        Content-Length and Content-Type).

        When the method is FTP, a Content-Length header will be
        present if (as is now usual) the server passed back a file
        length in response to the FTP retrieval request. A
        Content-Type header will be present if the MIME type can be
        guessed.

        When the method is local-file, returned headers will include
        a Date representing the file's last-modified time, a
        Content-Length giving file size, and a Content-Type
        containing a guess at the file's type. See also the
        description of the mimetools module.

        )rHr�rrr�info�szHTTPResponse.infocCs|jS)aZReturn the real URL of the page.

        In some cases, the HTTP server redirects a client to another
        URL. The urlopen() function handles this transparently, but in
        some cases the caller needs to know which URL the client was
        redirected to. The geturl() method can be used to get at this
        redirected URL.

        )rcr�rrr�geturl�s
zHTTPResponse.geturlcCs|jS)zuReturn the HTTP status code that was sent with the response,
        or None if the URL is not an HTTP URL.

        )r[r�rrr�getcode�szHTTPResponse.getcode)rNN)N)r�)r�)r�)N)"r<r=r>rdror�r|rmr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rDr�r�r�r�r�r�r�r�r��
__classcell__rrr�rr�s<	
!H

 "

	

c@s
eZdZdZdZeZeZdZ	dZ
edd��Zedd��Z
d	ejd	d
fdd�Zd7d
d�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd8d d!�Zd9d"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Z d:dd.�d/d0�Z!d	ifdd.�d1d2�Z"d3d4�Z#d5d6�Z$d	S);rrqzHTTP/1.1r0rcCst|tj�S)zFTest whether a file-like object is a text or a binary stream.
        )r��io�
TextIOBase)�streamrrr�
_is_textIOszHTTPConnection._is_textIOcCsf|dkr|��tkrdSdSt|d�r*dSzt|�}|jWStk
rNYnXt|t�rbt|�SdS)aGet the content-length based on the body.

        If the body is None, we set Content-Length: 0 for methods that expect
        a body (RFC 7230, Section 3.3.2). We also set the Content-Length for
        any method if the body is a str or bytes-like object and not a file.
        Nrr�)	�upper�_METHODS_EXPECTING_BODYr�r��nbytes�	TypeErrorr�rgr2)�bodyrb�mvrrr�_get_content_lengths

z"HTTPConnection._get_content_lengthN� cCsn||_||_||_d|_g|_d|_t|_d|_d|_	d|_
i|_|�||�\|_
|_|�|j
�tj|_dSr�)�timeout�source_address�	blocksizera�_buffer�_HTTPConnection__response�_CS_IDLE�_HTTPConnection__staterW�_tunnel_host�_tunnel_port�_tunnel_headers�
_get_hostport�host�port�_validate_host�socket�create_connection�_create_connection)r6r�r�r�r�r�rrrrd4szHTTPConnection.__init__cCs<|jrtd��|�||�\|_|_|r.||_n
|j��dS)aDSet up host and port for HTTP CONNECT tunnelling.

        In a connection that uses HTTP CONNECT tunneling, the host passed to the
        constructor is used as a proxy server that relays all communication to
        the endpoint passed to `set_tunnel`. This done by sending an HTTP
        CONNECT request to the proxy server when the connection is established.

        This method must be called before the HTTP connection has been
        established.

        The headers argument should be a mapping of extra HTTP headers to send
        with the CONNECT request.
        z.Can't set up tunnel for established connectionN)ra�RuntimeErrorr�r�r�r��clear)r6r�r�rHrrr�
set_tunnelJszHTTPConnection.set_tunnelcCs�|dkr�|�d�}|�d�}||kr�zt||dd��}WnHtk
r�||dd�dkrh|j}ntd||dd���YnX|d|�}n|j}|r�|ddkr�|ddkr�|dd�}||fS)	Nr/�]r0rfznonnumeric port: '%s'r�[r�)�rfindrnrk�default_portr)r6r�r�r��jrrrr�bs

zHTTPConnection._get_hostportcCs
||_dSr�)rV)r6�levelrrr�set_debuglevelvszHTTPConnection.set_debuglevelcCs�d|j|jf}|�d�}|�|�|j��D](\}}d||f}|�d�}|�|�q.|�d�|j|j|jd�}|�	�\}}	}
|	t
jjkr�|�
�td|	|
��f��|j�td�}t|�tkr�td	��|s�q�|d
kr�q�|jdkr�td|���q�dS)
NzCONNECT %s:%d HTTP/1.0
�asciiz%s: %s
r#rA�rbzTunnel connection failed: %d %sr0r?r@rrr)r�r�r$�sendr�rz�response_classrarWro�http�
HTTPStatus�OKr��OSErrorryrGrDrEr2rrVrhrM)r6�connect_str�
connect_bytes�headerr��
header_str�header_bytes�responserZrx�messager:rrr�_tunnelys4�



�
zHTTPConnection._tunnelcCsB|�|j|jf|j|j�|_|j�tjtj	d�|j
r>|��dS)z3Connect to the host and port specified in __init__.r0N)r�r�r�r�r�ra�
setsockoptr��IPPROTO_TCP�TCP_NODELAYr�r�r�rrr�connect�s
�zHTTPConnection.connectcCsBt|_z|j}|r d|_|��W5|j}|r<d|_|��XdS)z(Close the connection to the HTTP server.N)r�r�r�r�ra)r6r�rarrrr��szHTTPConnection.closecCs|jdkr |jr|��nt��|jdkr8tdt|��t|d�r�|jdkrTtd�|�|�}|rt|jdkrttd�|�	|j
�}|s�q�|r�|�d�}|j�|�qtdSz|j�|�WnLt
k
�rt|tjj�r�|D]}|j�|�q�nt
dt|���YnXdS)	z�Send `data' to the server.
        ``data`` can be a string object, a bytes object, an array object, a
        file-like object that supports a .read() method, or an iterable object.
        Nrzsend:r��sendIng a read()able�encoding file using iso-8859-1rJz9data should be a bytes-like object or an iterable, got %r)ra�	auto_openr�rrVrhrir�r�r�r�r$�sendallr�r��collections�abc�Iterable�type)r6r"r$�	datablock�drrrr��s8






�zHTTPConnection.sendcCs|j�|�dS)zuAdd a line of output to the current request buffer.

        Assumes that the line does *not* end with \r\n.
        N)r�r5)r6r�rrr�_output�szHTTPConnection._outputccs^|jdkrtd�|�|�}|r2|jdkr2td�|�|j�}|sDqZ|rR|�d�}|Vq2dS)Nrr�r�rJ)rVrhr�r�r�r$)r6r�r$rrrr�_read_readable�s


zHTTPConnection._read_readableFcCs |j�d�d�|j�}|jdd�=|�|�|dk	�rt|d�rN|�|�}nZzt|�WnFtk
r�zt|�}Wn$tk
r�tdt	|���YnXYnX|f}|D]R}|s�|j
dkr�td�q�|r�|jdkr�t
|�d	�d
��d�|d}|�|�q�|�r|jdk�r|�d�dS)
z�Send the currently buffered request and clear the buffer.

        Appends an extra \r\n to the buffer.
        A message_body may be specified, to be appended to the request.
        )rCrCrANr�zAmessage_body should be a bytes-like object or an iterable, got %rrzZero length chunk ignoredrq�Xz
r�s0

)r��extendrLr�r�rr�r��iterrrVrh�	_http_vsnr2r$)r6�message_body�encode_chunkedrX�chunks�chunkrrr�_send_output�s:


�
�zHTTPConnection._send_outputcCs�|jr|j��rd|_|jtkr(t|_n
t|j��|�|�||_|pHd}|�|�d|||j	f}|�
|�|��|jdk�r�|�s�d}|�
d�r�t|�\}}}}}|r�z|�d�}Wntk
r�|�d�}YnX|�d	|�n�|jr�|j}	|j}
n|j}	|j}
z|	�d�}Wn tk
�r4|	�d�}YnX|	�d
�dk�rRd|d
}|
|jk�rl|�d	|�n|�d�}|�d	d||
f�|�s�|�dd�ndS)a`Send a request to the server.

        `method' specifies an HTTP request method, e.g. 'GET'.
        `url' specifies the object being requested, e.g. '/index.html'.
        `skip_host' if True does not add automatically a 'Host:' header
        `skip_accept_encoding' if True does not add automatically an
           'Accept-Encoding:' header
        N�/z%s %s %srqrfr�r��idna�Hostr/r�[�]z%s:%szAccept-Encoding�identity)r�r�r�r��_CS_REQ_STARTEDr
�_validate_methodrW�_validate_path�
_http_vsn_strr�_encode_requestr	rlrr$r%�	putheaderr�r�r�r�r�r�rM)r6rbrc�	skip_host�skip_accept_encoding�request�netloc�nil�
netloc_encr�r��host_encrrr�
putrequest sP






zHTTPConnection.putrequestcCs
|�d�S)Nr�)r$)r6rrrrr�szHTTPConnection._encode_requestcCs,t�|�}|r(td|�d|���d���dS)z&Validate a method name for putrequest.z)method can't contain control characters. � (found at least �)N)�$_contains_disallowed_method_pchar_re�searchrk�group)r6rb�matchrrrr�s

�zHTTPConnection._validate_methodcCs,t�|�}|r(td|�d|���d���dS)zValidate a url for putrequest.�&URL can't contain control characters. r#r$N��!_contains_disallowed_url_pchar_rer&rr')r6rcr(rrrr�s
zHTTPConnection._validate_pathcCs,t�|�}|r(td|�d|���d���dS)z9Validate a host so it doesn't contain control characters.r)r#r$Nr*)r6r�r(rrrr��s
zHTTPConnection._validate_hostcGs�|jtkrt��t|d�r$|�d�}t|�s:td|f��t|�}t|�D]\\}}t|d�rl|�d�||<nt	|t
�r�t|��d�||<t||�rJtd||f��qJd�
|�}|d|}|�|�dS)	zkSend a request header line to the server.

        For example: h.putheader('Accept', 'text/html')
        r$r�zInvalid header name %rr#zInvalid header value %rs
	s: N)r�rrr�r$�_is_legal_header_namerkr��	enumerater�rnrg�_is_illegal_header_valuerLr)r6r��valuesr��	one_valuer�rrrr�s"





zHTTPConnection.putheader�rcCs*|jtkrt|_nt��|j||d�dS)z�Indicate that the last header line has been sent to the server.

        This method sends the request to the server.  The optional message_body
        argument can be used to pass a message body associated with the
        request.
        r1N)r�r�_CS_REQ_SENTrr)r6r
rrrr�
endheaders�s
zHTTPConnection.endheaderscCs|�|||||�dS)z&Send a complete request to the server.N)�
_send_request)r6rbrcr�rHrrrrr�szHTTPConnection.requestcCs�tdd�|D��}i}d|kr&d|d<d|kr6d|d<|j||f|�d|kr�d	|kr�d
}|�||�}|dkr�|dk	r�|jdkr�td|�d
}|�dd�q�|�dt|��nd
}|��D]\}	}
|�|	|
�q�t|t�r�t	|d�}|j
||d�dS)Ncss|]}|��VqdSr�)r1)r�krrr�	<genexpr>�sz/HTTPConnection._send_request.<locals>.<genexpr>r�r0rzaccept-encodingrrtrsFrzUnable to determine size of %rTzTransfer-Encodingr]zContent-Lengthr�r1)�	frozensetr"r�rVrhrrgrzr�r-r3)r6rbrcr�rHr�header_names�skips�content_lengthr�r�rrrr4�s0	


zHTTPConnection._send_requestcCs�|jr|j��rd|_|jtks&|jr0t|j��|jdkrR|j|j|j|jd�}n|j|j|jd�}z\z|�	�Wnt
k
r�|���YnX|jt
ks�t�t|_|jr�|��n||_|WS|���YnXdS)a)Get the response from the server.

        If the HTTPConnection is in the correct state, returns an
        instance of HTTPResponse or of whatever object is returned by
        the response_class variable.

        If a request has not been sent or if a previous response has
        not be handled, ResponseNotReady is raised.  If the HTTP
        response indicates that the connection should be closed, then
        it will be closed before the response is returned.  When the
        connection is closed, the underlying socket is closed.
        Nrr�)r�r�r�r2rrVr�rarWr��ConnectionErrorr�r`rYr�r�)r6r�rrr�getresponses0

�
zHTTPConnection.getresponse)NN)NF)FF)N)%r<r=r>r	rrr��	HTTP_PORTr�r�rV�staticmethodr�r�r��_GLOBAL_DEFAULT_TIMEOUTrdr�r�r�r�r�r�r�rrrr"rrrr�rr3rr4r<rrrrrsL

�

	&
6�
	
�.csHeZdZdZeZdddejdfdddd��fdd�Z�fdd�Z	�Z
S)	�HTTPSConnectionz(This class allows communication via SSL.Nr�)�context�check_hostnamer�cs�tt|�j|||||	d�|dk	s2|dk	s2|dk	rHddl}
|
�dtd�||_||_|dkrtt�	�}|j
dk	rtd|_
|jtjk}|dkr�|j
}|r�|s�td��|s�|r�|�||�|j
dk	r�d|_
||_|dk	r�||j_
dS)N)r�rzTkey_file, cert_file and check_hostname are deprecated, use a custom context instead.reTzMcheck_hostname needs a SSL context with either CERT_OPTIONAL or CERT_REQUIRED)r�r@rd�warnings�warn�DeprecationWarning�key_file�	cert_file�ssl�_create_default_https_context�post_handshake_auth�verify_mode�	CERT_NONErBrk�load_cert_chain�_context)r6r�r�rFrGr�r�rArBr�rC�will_verifyr�rrrdcs<���

zHTTPSConnection.__init__cs6t���|jr|j}n|j}|jj|j|d�|_dS)z(Connect to a host on a given (SSL) port.)�server_hostnameN)r�r�r�r�rN�wrap_socketra)r6rPr�rrr��s

�zHTTPSConnection.connect)r<r=r>�__doc__�
HTTPS_PORTr�r�r?rdr�r�rrr�rr@\s��$r@c@seZdZdS)rN�r<r=r>rrrrr�sc@seZdZdS)rNrTrrrrr�sc@seZdZdS)rNrTrrrrr�sc@seZdZdd�ZdS)rcCs|f|_||_dSr�)�argsrZ)r6rZrrrrd�szUnknownProtocol.__init__N�r<r=r>rdrrrrr�sc@seZdZdS)rNrTrrrrr�sc@seZdZdS)r	NrTrrrrr	�sc@s$eZdZddd�Zdd�ZejZdS)r
NcCs|f|_||_||_dSr�)rU�partial�expected)r6rWrXrrrrd�szIncompleteRead.__init__cCs2|jdk	rd|j}nd}d|jjt|j�|fS)Nz, %i more expectedrfz%s(%i bytes read%s))rXr�r<r2rW)r6�errr�__repr__�s
�zIncompleteRead.__repr__)N)r<r=r>rdrZr'�__str__rrrrr
�s
c@seZdZdS)rNrTrrrrr�sc@seZdZdS)r
NrTrrrrr
�sc@seZdZdS)rNrTrrrrr�sc@seZdZdS)rNrTrrrrr�sc@seZdZdd�ZdS)rcCs|st|�}|f|_||_dSr�)rirUr:r�rrrrd�szBadStatusLine.__init__NrVrrrrr�sc@seZdZdd�ZdS)rcCst�|dt|f�dS)Nz&got more than %d bytes when reading %s)rrdrE)r6�	line_typerrrrd�s�zLineTooLong.__init__NrVrrrrr�sc@seZdZdd�ZdS)rcOs"t�|d�tj|f|�|�dS)Nrf)rrd�ConnectionResetError)r6�pos�kwrrrrd�szRemoteDisconnected.__init__NrVrrrrr�s)r")ArR�email.parserrN�
email.messager�r��rer��collections.abcr��urllib.parser�__all__r=rSrYr�rr2�globals�updater��__members__r/rrErF�compile�	fullmatchr,r&r.r+r%r�r-r��Messager.rIrS�BufferedIOBaserrrH�ImportErrorr@r5�	Exceptionrrrrrr	r
rr
rrrrr]rrrrrr�<module>s�F�



W8
�h� bytecode of module 'http.client'�u��b.����h)��N}�(hBz��@sdZddddddddgZd	d
lZd	d
lZd	d
lZd	d
lZd	d
lZd	d
lZd	d
l	Zd	d
l
Zd	d
lZ
d	dlmZdZd
ad
d�Zee
jj�ZdZdd�ZdZdd�ZdddddddgZddddd d!d"d#d$d%d&d'gZgZeD]Ze�e� ��q�dud(d)�Z!dvd*d+�Z"d
d
d
d
d,�Z#e�$d-ej%�Z&d.d/�Z'd0d1�Z(e�$d2ej%�Z)e�$d3ej*ej%B�Z+e�$d4ej,ej%B�Z-d5d6�Z.e�$d7ej,ej%B�Z/d8d9�Z0d:d;�Z1e�$d<�Z2e�$d=�Z3e�$d>�Z4e�$d?�Z5d@dA�Z6e�$dB�Z7dCdD�Z8dEdF�Z9dGdH�Z:e�$dIej%�Z;dJdK�Z<dLdM�Z=dNdO�Z>dPdQ�Z?e�$dRej%�Z@dSdT�ZAdUdV�ZBdWdX�ZCdYdZ�ZDd[ZEe�$d\�ZFd]d^�ZGd_d`�ZHdadb�ZIdcdd�ZJGded�d�ZKGdfd�d�ZLGdgd�deL�ZMdhdi�ZNdjdk�ZOGdldm�dm�ZPGdnd�d�ZQGdod�deR�ZSGdpd�deQ�ZTdqdr�ZUGdsd�deT�ZVGdtd�deT�ZWd
S)wa�HTTP cookie handling for web clients.

This module has (now fairly distant) origins in Gisle Aas' Perl module
HTTP::Cookies, from the libwww-perl library.

Docstrings, comments and debug strings in this code refer to the
attributes of the HTTP cookie system as cookie-attributes, to distinguish
them clearly from Python attributes.

Class diagram (note that BSDDBCookieJar and the MSIE* classes are not
distributed with the Python standard library, but are available from
http://wwwsearch.sf.net/):

                        CookieJar____
                        /     \      \
            FileCookieJar      \      \
             /    |   \         \      \
 MozillaCookieJar | LWPCookieJar \      \
                  |               |      \
                  |   ---MSIEBase |       \
                  |  /      |     |        \
                  | /   MSIEDBCookieJar BSDDBCookieJar
                  |/
               MSIECookieJar

�Cookie�	CookieJar�CookiePolicy�DefaultCookiePolicy�
FileCookieJar�LWPCookieJar�	LoadError�MozillaCookieJar�N)�timegmFcGs(tsdStsddl}|�d�atj|�S)Nr	zhttp.cookiejar)�debug�logger�logging�	getLogger)�argsr
�r�$/usr/lib/python3.8/http/cookiejar.py�_debug,s
rzQa filename was not supplied (nor was the CookieJar instance initialised with one)cCsJddl}ddl}ddl}|��}|�d|�|��}|jd|dd�dS)Nr	zhttp.cookiejar bug!
%s�)�
stacklevel)�io�warnings�	traceback�StringIO�	print_exc�getvalue�warn)rrr�f�msgrrr�_warn_unhandled_exception:s
ri�cCs�|dd�\}}}}}}|tkr�d|kr4dkr�nnhd|krLdkr�nnPd|krddkr�nn8d|kr|dkr�nn d|kr�dkr�nnt|�SdSdS)	N����r	��;�=)�
EPOCH_YEARr
)�tt�year�month�mday�hour�min�secrrr�_timegmIs&8��
��
��
r.�Mon�Tue�Wed�Thu�Fri�Sat�Sun�Jan�Feb�Mar�Apr�May�Jun�Jul�Aug�Sep�Oct�Nov�DeccCs@|dkrtj��}ntj�|�}d|j|j|j|j|j|jfS)aHReturn a string representing time in seconds since epoch, t.

    If the function is called without an argument, it will use the current
    time.

    The format of the returned string is like "YYYY-MM-DD hh:mm:ssZ",
    representing Universal Time (UTC, aka GMT).  An example of this format is:

    1994-11-24 08:49:37Z

    Nz%04d-%02d-%02d %02d:%02d:%02dZ)	�datetime�utcnow�utcfromtimestampr(r)�dayr+�minute�second��t�dtrrr�	time2isozWs�rKcCsR|dkrtj��}ntj�|�}dt|��|jt|jd|j|j	|j
|jfS)z�Return a string representing time in seconds since epoch, t.

    If the function is called without an argument, it will use the current
    time.

    The format of the returned string is like this:

    Wed, DD-Mon-YYYY HH:MM:SS GMT

    Nz#%s, %02d-%s-%04d %02d:%02d:%02d GMTr )rBrCrD�DAYS�weekdayrE�MONTHSr)r(r+rFrGrHrrr�
time2netscapejs
�rO)�GMT�UTC�UT�Zz^([-+])?(\d\d?):?(\d\d)?$cCsjd}|tkrd}nTt�|�}|rfdt|�d��}|�d�rR|dt|�d��}|�d�dkrf|}|S)Nr	ir��<r �-)�	UTC_ZONES�TIMEZONE_RE�search�int�group)�tz�offset�mrrr�offset_from_tz_string�s

r_c
Cs�t|�}|tjkrdSzt�|���d}Wn^tk
r�zt|�}Wntk
r`YYdSXd|krvdkr�nn|}nYdSYnX|dkr�d}|dkr�d}|dkr�d}t|�}t|�}t|�}t|�}|dk�r6t�t���d}|d}	|}
|||	}|	|
}	t	|	�dk�r6|	dk�r.|d}n|d}t
|||||||f�}|dk	�r�|dk�rdd}|��}t|�}|dk�r�dS||}|S)Nr r!r	i��d�2rQ)
rZrB�MAXYEAR�MONTHS_LOWER�index�lower�
ValueError�time�	localtime�absr.�upperr_)
rE�mon�yr�hrr,r-r\�imon�cur_yrr^�tmprIr]rrr�	_str2time�sV







rqzV^[SMTWF][a-z][a-z], (\d\d) ([JFMASOND][a-z][a-z]) (\d\d\d\d) (\d\d):(\d\d):(\d\d) GMT$z+^(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)[a-z]*,?\s*a�^
    (\d\d?)            # day
       (?:\s+|[-\/])
    (\w+)              # month
        (?:\s+|[-\/])
    (\d+)              # year
    (?:
          (?:\s+|:)    # separator before clock
       (\d\d?):(\d\d)  # hour:min
       (?::(\d\d))?    # optional seconds
    )?                 # optional clock
       \s*
    (?:
       ([-+]?\d{2,4}|(?![APap][Mm]\b)[A-Za-z]+) # timezone
       \s*
    )?
    (?:
       \(\w+\)         # ASCII representation of timezone in parens.
       \s*
    )?$cCs�t�|�}|rl|��}t�|d���d}t|d�|t|d�t|d�t|d�t|d�f}t|�S|�	�}t
�d|d�}dgd	\}}}}}}	}
t�|�}|dk	r�|��\}}}}}}	}
ndSt
||||||	|
�S)
a�Returns time in seconds since epoch of time represented by a string.

    Return value is an integer.

    None is returned if the format of str is unrecognized, the time is outside
    the representable range, or the timezone string is not recognized.  If the
    string contains no timezone, UTC is assumed.

    The timezone in the string may be numerical (like "-0800" or "+0100") or a
    string timezone (like "UTC", "GMT", "BST" or "EST").  Currently, only the
    timezone strings equivalent to UTC (zero offset) are known to the function.

    The function loosely parses the following formats:

    Wed, 09 Feb 1994 22:23:32 GMT       -- HTTP format
    Tuesday, 08-Feb-94 14:15:29 GMT     -- old rfc850 HTTP format
    Tuesday, 08-Feb-1994 14:15:29 GMT   -- broken rfc850 HTTP format
    09 Feb 1994 22:23:32 GMT            -- HTTP format (no weekday)
    08-Feb-94 14:15:29 GMT              -- rfc850 format (no weekday)
    08-Feb-1994 14:15:29 GMT            -- broken rfc850 format (no weekday)

    The parser ignores leading and trailing whitespace.  The time may be
    absent.

    If the year is given with only 2 digits, the function will select the
    century that makes the year closest to the current date.

    r rr	rT���N�)�STRICT_DATE_RErY�groupsrcrdrerZ�floatr.�lstrip�
WEEKDAY_RE�sub�LOOSE_HTTP_DATE_RErq)�textr^�grkr'rErlrmr,r-r\rrr�	http2time�s$



�
ra�^
    (\d{4})              # year
       [-\/]?
    (\d\d?)              # numerical month
       [-\/]?
    (\d\d?)              # day
   (?:
         (?:\s+|[-:Tt])  # separator before clock
      (\d\d?):?(\d\d)    # hour:min
      (?::?(\d\d(?:\.\d*)?))?  # optional seconds (and fractional)
   )?                    # optional clock
      \s*
   (?:
      ([-+]?\d\d?:?(:?\d\d)?
       |Z|z)             # timezone  (Z is "zero meridian", i.e. GMT)
      \s*
   )?$c
Csd|��}dgd\}}}}}}}t�|�}|dk	rL|��\}}}}}}}}	ndSt|||||||�S)av
    As for http2time, but parses the ISO 8601 formats:

    1994-02-03 14:15:29 -0100    -- ISO 8601 format
    1994-02-03 14:15:29          -- zone is optional
    1994-02-03                   -- only date
    1994-02-03T14:15:29          -- Use T as separator
    19940203T141529Z             -- ISO 8601 compact format
    19940203                     -- only date

    Nru)ry�ISO_DATE_RErYrwrq)
r}rErkrlrmr,r-r\r^�_rrr�iso2time+s

r�cCs*|�d�\}}|jd|�|j|d�S)z)Return unmatched part of re.Match object.r	N)�span�string)�match�start�endrrr�	unmatchedLsr�z^\s*([^=\s;,]+)z&^\s*=\s*\"([^\"\\]*(?:\\.[^\"\\]*)*)\"z^\s*=\s*([^\s;,]*)z\\(.)c
Cs0t|t�rt�g}|D�]}|}g}|�rt�|�}|r�t|�}|�d�}t�|�}|rxt|�}|�d�}t�	d|�}n.t
�|�}|r�t|�}|�d�}|��}nd}|�||f�q$|�
��d�r�|�
�dd�}|r�|�|�g}q$t�dd|�\}}	|	dk�std|||f��|}q$|r|�|�q|S)	amParse header values into a list of lists containing key,value pairs.

    The function knows how to deal with ",", ";" and "=" as well as quoted
    values after "=".  A list of space separated tokens are parsed as if they
    were separated by ";".

    If the header_values passed as argument contains multiple values, then they
    are treated as if they were a single value separated by comma ",".

    This means that this function is useful for parsing header fields that
    follow this syntax (BNF as from the HTTP/1.1 specification, but we relax
    the requirement for tokens).

      headers           = #header
      header            = (token | parameter) *( [";"] (token | parameter))

      token             = 1*<any CHAR except CTLs or separators>
      separators        = "(" | ")" | "<" | ">" | "@"
                        | "," | ";" | ":" | "\" | <">
                        | "/" | "[" | "]" | "?" | "="
                        | "{" | "}" | SP | HT

      quoted-string     = ( <"> *(qdtext | quoted-pair ) <"> )
      qdtext            = <any TEXT except <">>
      quoted-pair       = "\" CHAR

      parameter         = attribute "=" value
      attribute         = token
      value             = token | quoted-string

    Each header is represented by a list of key/value pairs.  The value for a
    simple token (not part of a parameter) is None.  Syntactically incorrect
    headers will not necessarily be parsed as you would want.

    This is easier to describe with some examples:

    >>> split_header_words(['foo="bar"; port="80,81"; discard, bar=baz'])
    [[('foo', 'bar'), ('port', '80,81'), ('discard', None)], [('bar', 'baz')]]
    >>> split_header_words(['text/html; charset="iso-8859-1"'])
    [[('text/html', None), ('charset', 'iso-8859-1')]]
    >>> split_header_words([r'Basic realm="\"foo\bar\""'])
    [[('Basic', None), ('realm', '"foobar"')]]

    r z\1N�,z^[=\s;]*rtr	z&split_header_words bug: '%s', '%s', %s)�
isinstance�str�AssertionError�HEADER_TOKEN_RErYr�r[�HEADER_QUOTED_VALUE_RE�HEADER_ESCAPE_REr{�HEADER_VALUE_RE�rstrip�appendry�
startswith�re�subn)
�
header_values�resultr}�	orig_text�pairsr^�name�value�non_junk�
nr_junk_charsrrr�split_header_wordsUsJ-








��r��([\"\\])cCs|g}|D]h}g}|D]F\}}|dk	rPt�d|�sDt�d|�}d|}d||f}|�|�q|r|�d�|��qd�|�S)a�Do the inverse (almost) of the conversion done by split_header_words.

    Takes a list of lists of (key, value) pairs and produces a single header
    value.  Attribute values are quoted if needed.

    >>> join_header_words([[("text/plain", None), ("charset", "iso-8859-1")]])
    'text/plain; charset="iso-8859-1"'
    >>> join_header_words([[("text/plain", None)], [("charset", "iso-8859-1")]])
    'text/plain, charset="iso-8859-1"'

    Nz^\w+$�\\\1z"%s"�%s=%s�; �, )r�rY�HEADER_JOIN_ESCAPE_REr{r��join)�lists�headersr��attr�k�vrrr�join_header_words�sr�cCs0|�d�r|dd�}|�d�r,|dd�}|S)N�"r ���)r��endswith�r}rrr�strip_quotes�s


r�cCs�d}g}|D]�}g}d}t|�d��D]�\}}|��}|�d�\}}	}
|��}|sb|dkr&q�nq&|	rn|
��nd}
|dkr�|��}||kr�|}|dkr�|
dk	r�t|
�}
d}n|d	kr�|
dk	r�tt|
��}
|�||
f�q&|r|s�|�d
�|�|�q|S)a5Ad-hoc parser for Netscape protocol cookie-attributes.

    The old Netscape cookie format for Set-Cookie can for instance contain
    an unquoted "," in the expires field, so we have to use this ad-hoc
    parser instead of split_header_words.

    XXX This may not make the best possible effort to parse all the crap
    that Netscape Cookie headers contain.  Ronald Tschalar's HTTPClient
    parser is probably better, so could do worse than following that if
    this ever gives any trouble.

    Currently, this is also used for parsing RFC 2109 cookies.

    )�expires�domain�path�secure�version�port�max-ageF�;�=r	Nr�Tr�)r��0)�	enumerate�split�strip�	partitionrer�rr�)�
ns_headers�known_attrsr��	ns_headerr��version_set�ii�param�key�sep�val�lcrrr�parse_ns_headers�s>
r�z\.\d+$cCs:t�|�rdS|dkrdS|ddks2|ddkr6dSdS)z*Return True if text is a host domain name.Frtr	�.r�T��IPV4_RErYr�rrr�is_HDNs
r�cCsl|��}|��}||krdSt|�s(dS|�|�}|dksB|dkrFdS|�d�sTdSt|dd��shdSdS)a�Return True if domain A domain-matches domain B, according to RFC 2965.

    A and B may be host domain names or IP addresses.

    RFC 2965, section 1:

    Host names can be specified either as an IP address or a HDN string.
    Sometimes we compare one host name with another.  (Such comparisons SHALL
    be case-insensitive.)  Host A's name domain-matches host B's if

         *  their host name strings string-compare equal; or

         * A is a HDN string and has the form NB, where N is a non-empty
            name string, B has the form .B', and B' is a HDN string.  (So,
            x.y.com domain-matches .Y.com but not Y.com.)

    Note that domain-match is not a commutative operation: a.b.c.com
    domain-matches .c.com, but not the reverse.

    TFr�r	r�r N)rer��rfindr�)�A�B�irrr�domain_matchs

r�cCst�|�rdSdS)zdReturn True if text is a sort-of-like a host domain name.

    For accepting/blocking domains.

    FTr�r�rrr�liberal_is_HDNFs
r�cCs`|��}|��}t|�r t|�s0||kr,dSdS|�d�}|rL|�|�rLdS|s\||kr\dSdS)z\For blocking/accepting domains.

    A and B may be host domain names or IP addresses.

    TFr�)rer�r�r�)r�r��initial_dotrrr�user_domain_matchPs
r�z:\d+$cCsB|��}tj�|�d}|dkr,|�dd�}t�d|d�}|��S)z�Return request-host, as defined by RFC 2965.

    Variation from RFC: returned value is lowercased, for convenient
    comparison.

    r rt�Host)�get_full_url�urllib�parse�urlparse�
get_header�cut_port_rer{re)�request�url�hostrrr�request_hostesr�cCs4t|�}}|�d�dkr,t�|�s,|d}||fS)zzReturn a tuple (request-host, effective request-host name).

    As defined by RFC 2965, except both are lowercased.

    r�r��.local)r��findr�rY)r��erhn�req_hostrrr�eff_request_hostusr�cCs4|��}tj�|�}t|j�}|�d�s0d|}|S)z6Path component of request-URI, as defined by RFC 2965.�/)r�r�r��urlsplit�escape_pathr�r�)r�r��partsr�rrr�request_path�s

r�cCs`|j}|�d�}|dkrX||dd�}zt|�Wq\tk
rTtd|�YdSXnt}|S)N�:r	r znonnumeric port: '%s')r�r�rZrfr�DEFAULT_HTTP_PORT)r�r�r�r�rrr�request_port�s


r�z%/;:@&=+$,!~*'()z%([0-9a-fA-F][0-9a-fA-F])cCsd|�d���S)Nz%%%sr )r[rj)r�rrr�uppercase_escaped_char�sr�cCstj�|t�}t�t|�}|S)zEEscape any invalid characters in HTTP URL, and uppercase all escapes.)r�r��quote�HTTP_PATH_SAFE�ESCAPED_CHAR_REr{r�)r�rrrr��s
r�cCsP|�d�}|dkrL||dd�}|�d�}t|�rL|dksD|dkrLd|S|S)aBReturn reach of host h, as defined by RFC 2965, section 1.

    The reach R of a host name H is defined as follows:

       *  If

          -  H is the host domain name of a host; and,

          -  H has the form A.B; and

          -  A has no embedded (that is, interior) dots; and

          -  B has at least one embedded dot, or B is the string "local".
             then the reach of H is .B.

       *  Otherwise, the reach of H is H.

    >>> reach("www.acme.com")
    '.acme.com'
    >>> reach("acme.com")
    'acme.com'
    >>> reach("acme.local")
    '.local'

    r�r	r N�local)r�r�)�hr��brrr�reach�s

r�cCs$t|�}t|t|j��sdSdSdS)z�

    RFC 2965, section 3.3.6:

        An unverifiable transaction is to a third-party host if its request-
        host U does not domain-match the reach R of the request-host O in the
        origin transaction.

    TFN)r�r�r��origin_req_host)r�r�rrr�is_third_party�s
r�c@sNeZdZdZddd�Zdd�Zddd	�Zd
d�Zddd
�Zdd�Z	dd�Z
dS)ra�HTTP Cookie.

    This class represents both Netscape and RFC 2965 cookies.

    This is deliberately a very simple class.  It just holds attributes.  It's
    possible to construct Cookie instances that don't comply with the cookie
    standards.  CookieJar.make_cookies is the factory function for Cookie
    objects -- it deals with cookie parsing, supplying defaults, and
    normalising to the representation used in this class.  CookiePolicy is
    responsible for checking them to see whether they should be accepted from
    and returned to the server.

    Note that the port may be present in the headers, but unspecified ("Port"
    rather than"Port=80", for example); if this is the case, port is None.

    FcCs�|dk	rt|�}|dk	r$tt|��}|dkr<|dkr<td��||_||_||_||_||_|��|_	||_
||_|	|_|
|_
||_||_|
|_||_||_||_t�|�|_dS)NTz-if port is None, port_specified must be false)rZrxrfr�r�r�r��port_specifiedrer��domain_specified�domain_initial_dotr��path_specifiedr�r��discard�comment�comment_url�rfc2109�copy�_rest)�selfr�r�r�r�r�r�r�r�r�r�r�r�r�r�r��restr�rrr�__init__�s.

zCookie.__init__cCs
||jkS�N�r)rr�rrr�has_nonstandard_attrszCookie.has_nonstandard_attrNcCs|j�||�Sr)r�get)rr��defaultrrr�get_nonstandard_attrszCookie.get_nonstandard_attrcCs||j|<dSrr)rr�r�rrr�set_nonstandard_attr szCookie.set_nonstandard_attrcCs,|dkrt��}|jdk	r(|j|kr(dSdS�NTF)rgr�)r�nowrrr�
is_expired#s
zCookie.is_expiredcCsX|jdkrd}n
d|j}|j||j}|jdk	rFd|j|jf}n|j}d||fS)Nrtr�r�z<Cookie %s for %s>)r�r�r�r�r�)r�p�limit�	namevaluerrr�__str__)s


zCookie.__str__cCslg}dD]$}t||�}|�d|t|�f�q|�dt|j��|�dt|j��d|jjd�|�fS)N)r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�zrest=%sz
rfc2109=%sz%s(%s)r�)�getattrr��reprrr��	__class__�__name__r�)rrr�r�rrr�__repr__3s
zCookie.__repr__)F)N)N)r�
__module__�__qualname__�__doc__rrr
rrrrrrrrr�s�
*


c@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)ra Defines which cookies get accepted from and returned to server.

    May also modify cookies, though this is probably a bad idea.

    The subclass DefaultCookiePolicy defines the standard rules for Netscape
    and RFC 2965 cookies -- override that if you want a customized policy.

    cCs
t��dS)z�Return true if (and only if) cookie should be accepted from server.

        Currently, pre-expired cookies never get this far -- the CookieJar
        class deletes such cookies itself.

        N��NotImplementedError�r�cookier�rrr�set_okKszCookiePolicy.set_okcCs
t��dS)zAReturn true if (and only if) cookie should be returned to server.Nrrrrr�	return_okTszCookiePolicy.return_okcCsdS)zMReturn false if cookies should not be returned, given cookie domain.
        Tr)rr�r�rrr�domain_return_okXszCookiePolicy.domain_return_okcCsdS)zKReturn false if cookies should not be returned, given cookie path.
        Tr)rr�r�rrr�path_return_ok]szCookiePolicy.path_return_okN)rrrrrr r!r"rrrrrBs
	c
@s�eZdZdZdZdZdZdZeeBZdddddddddeddd	f
d
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Zd2d3�Zd4d5�Zd6d7�ZdS)8rzBImplements the standard rules for accepting and returning cookies.r rrrr	NTF)�https�wsscCsv||_||_||_||_||_||_|	|_|
|_||_||_	|
|_
|dk	rVt|�|_nd|_|dk	rlt|�}||_
dS)zAConstructor arguments should be passed as keyword arguments only.Nr)�netscape�rfc2965�rfc2109_as_netscape�hide_cookie2�
strict_domain�strict_rfc2965_unverifiable�strict_ns_unverifiable�strict_ns_domain�strict_ns_set_initial_dollar�strict_ns_set_path�secure_protocols�tuple�_blocked_domains�_allowed_domains)r�blocked_domains�allowed_domainsr%r&r'r(r)r*r+r,r-r.r/rrrrms"zDefaultCookiePolicy.__init__cCs|jS)z4Return the sequence of blocked domains (as a tuple).)r1�rrrrr3�sz#DefaultCookiePolicy.blocked_domainscCst|�|_dS)z$Set the sequence of blocked domains.N)r0r1)rr3rrr�set_blocked_domains�sz'DefaultCookiePolicy.set_blocked_domainscCs |jD]}t||�rdSqdSr)r1r�)rr��blocked_domainrrr�
is_blocked�s

zDefaultCookiePolicy.is_blockedcCs|jS)z=Return None, or the sequence of allowed domains (as a tuple).)r2r5rrrr4�sz#DefaultCookiePolicy.allowed_domainscCs|dk	rt|�}||_dS)z-Set the sequence of allowed domains, or None.N)r0r2)rr4rrr�set_allowed_domains�sz'DefaultCookiePolicy.set_allowed_domainscCs.|jdkrdS|jD]}t||�rdSqdS)NFT)r2r�)rr��allowed_domainrrr�is_not_allowed�s


z"DefaultCookiePolicy.is_not_allowedcCsNtd|j|j�|jdk	st�dD]&}d|}t||�}|||�s"dSq"dS)z�
        If you override .set_ok(), be sure to call this method.  If it returns
        false, so should your subclass (assuming your subclass wants to be more
        strict about which cookies to accept).

        � - checking cookie %s=%sN)r��
verifiabilityr�r�r�r�Zset_ok_FT)rr�r�r�r�rrr��n�fn_name�fnrrrr�s

zDefaultCookiePolicy.set_okcCsZ|jdkrtd|j|j�dS|jdkr:|js:td�dS|jdkrV|jsVtd�dSdS)Nz0   Set-Cookie2 without version attribute (%s=%s)Fr	�$   RFC 2965 cookies are switched off�$   Netscape cookies are switched offT)r�rr�r�r&r%rrrr�set_ok_version�s
�z"DefaultCookiePolicy.set_ok_versioncCsJ|jrFt|�rF|jdkr*|jr*td�dS|jdkrF|jrFtd�dSdS�Nr	z>   third-party RFC 2965 cookie during unverifiable transactionFz>   third-party Netscape cookie during unverifiable transactionT��unverifiabler�r�r*rr+rrrr�set_ok_verifiability�sz(DefaultCookiePolicy.set_ok_verifiabilitycCs0|jdkr,|jr,|j�d�r,td|j�dSdS)Nr	�$z'   illegal name (starts with '$'): '%s'FT)r�r-r�r�rrrrr�set_ok_name�s
�zDefaultCookiePolicy.set_ok_namecCsL|jrHt|�}|jdks(|jdkrH|jrH|�|j|�sHtd|j|�dSdS)Nr	z7   path attribute %s is not a prefix of request path %sFT)r�r�r�r.r"r�r)rrr��req_pathrrr�set_ok_path�s
����zDefaultCookiePolicy.set_ok_pathc
Cs�|�|j�rtd|j�dS|�|j�r8td|j�dS|j�r�t|�\}}|j}|jr�|�d�dkr�|�d�}|�dd|�}|dkr�||dd�}||d|�}	|	�	�dkr�t
|�dkr�td	|�dS|�d�r�|dd�}
n|}
|
�d�dk}|�s|d
k�rtd|�dS|j
dk�rX|�|��sX|�d��sXd|�|��sXtd||�dS|j
dk�sr|j|j@�r�t||��s�td
||�dS|j
dk�s�|j|j@�r�|dt
|��}|�d�dk�r�t�|��s�td||�dSdS)N�"   domain %s is in user block-listF�&   domain %s is not in user allow-listr�rr	r )�coZac�comZeduZorg�netZgovZmilrZZaeroZbiz�catZcoop�info�jobsZmobiZmuseumr��proZtravel�euz&   country-code second level domain %sr�z/   non-local domain %s contains no embedded dotzO   effective request-host %s (even with added initial dot) does not end with %sz5   effective request-host %s does not domain-match %sz.   host prefix %s for domain %s contains a dotT)r8r�rr;r�r�r)�countr�re�lenr�r�r�r�r,�DomainRFC2965Matchr��DomainStrictNoDotsr�rY)
rrr�r�r�r�r��j�tld�sld�undotted_domain�
embedded_dots�host_prefixrrr�
set_ok_domain�s|

�

����
��
���z!DefaultCookiePolicy.set_ok_domainc	Cs�|jr�t|�}|dkrd}nt|�}|j�d�D]@}zt|�Wn"tk
rbtd|�YdSX||kr0q�q0td||j�dSdS)N�80r�z   bad port %s (not numeric)Fz$   request port (%s) not found in %sT)r�r�r�r�r�rZrfr�rrr��req_portrrrr�set_ok_port+s&

�zDefaultCookiePolicy.set_ok_portcCs@td|j|j�dD]&}d|}t||�}|||�sdSqdS)z�
        If you override .return_ok(), be sure to call this method.  If it
        returns false, so should your subclass (assuming your subclass wants to
        be more strict about which cookies to return).

        r<)r�r=r�r�r�r�Z
return_ok_FT)rr�r�rr>rrrr @s	

zDefaultCookiePolicy.return_okcCs<|jdkr|jstd�dS|jdkr8|js8td�dSdS)Nr	rBFrCT)r�r&rr%rrrr�return_ok_versionRsz%DefaultCookiePolicy.return_ok_versioncCsJ|jrFt|�rF|jdkr*|jr*td�dS|jdkrF|jrFtd�dSdSrErFrrrr�return_ok_verifiability[sz+DefaultCookiePolicy.return_ok_verifiabilitycCs"|jr|j|jkrtd�dSdS)Nz(   secure cookie with non-secure requestFT)r��typer/rrrrr�return_ok_securegsz$DefaultCookiePolicy.return_ok_securecCs|�|j�rtd�dSdS)Nz   cookie expiredFT)r�_nowrrrrr�return_ok_expiresmsz%DefaultCookiePolicy.return_ok_expirescCsN|jrJt|�}|dkrd}|j�d�D]}||kr&qJq&td||j�dSdS)Nrbr�z0   request port %s does not match cookie port %sFT)r�r�r�rrcrrr�return_ok_portss�z"DefaultCookiePolicy.return_ok_portcCs�t|�\}}|j}|r*|�d�s*d|}n|}|jdkr^|j|j@r^|js^||kr^td�dS|jdkr�t||�s�td||�dS|jdkr�d|�	|�s�td||�dSdS)Nr�r	zQ   cookie with unspecified domain does not string-compare equal to request domainFzQ   effective request-host name %s does not domain-match RFC 2965 cookie domain %sz;   request-host %s does not match Netscape cookie domain %sT)
r�r�r�r�r,�DomainStrictNonDomainr�rr�r�)rrr�r�r�r��	dotdomainrrr�return_ok_domain�s6


�����z$DefaultCookiePolicy.return_ok_domaincCs�t|�\}}|�d�sd|}|�d�s0d|}|rH|�d�sHd|}n|}|�|�sd|�|�sddS|�|�r|td|�dS|�|�r�td|�dSdS)Nr�FrMrNT)r�r�r�r8rr;)rr�r�r�r�rnrrrr!�s"






z$DefaultCookiePolicy.domain_return_okcCsbtd|�t|�}t|�}||kr&dS|�|�rR|�d�sN|||d�dkrRdStd||�dS)Nz- checking cookie path=%sTr�r z  %s does not path-match %sF)rr�rXr�r�)rr�r�rK�pathlenrrrr"�s

��z"DefaultCookiePolicy.path_return_ok) rrrrrZrmrY�
DomainLiberal�DomainStrictrr3r6r8r4r9r;rrDrHrJrLrarer rfrgrirkrlror!r"rrrrrcsT�
#	;	cCst|���}t|j|�Sr)�sorted�keys�mapr)�adictrtrrr�vals_sorted_by_key�srwc	csVt|�}|D]D}d}z
|jWntk
r2YnXd}t|�EdH|s|VqdS)zBIterates over nested mapping, depth-first, in sorted order by key.FTN)rw�items�AttributeError�
deepvalues)�mapping�values�objrrrrz�s
rzc@seZdZdS)�AbsentN�rrrrrrrr~�sr~c@s�eZdZdZe�d�Ze�d�Ze�d�Ze�d�Z	e�d�Z
e�dej�Zd3d	d
�Z
dd�Zd
d�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd4d%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Z d1d2�Z!dS)5rz�Collection of HTTP cookies.

    You may not need to know about this class: try
    urllib.request.build_opener(HTTPCookieProcessor).open(url).
    z\Wr�z\.?[^.]*z[^.]*z^\.+z^\#LWP-Cookies-(\d+\.\d+)NcCs(|dkrt�}||_t��|_i|_dSr)r�_policy�
_threading�RLock�
_cookies_lock�_cookies�r�policyrrrr�s

zCookieJar.__init__cCs
||_dSr)r�r�rrr�
set_policy�szCookieJar.set_policycCs�g}|j�||�sgStd|�|j|}|��D]T}|j�||�sFq2||}|��D].}|j�||�srtd�qVtd�|�|�qVq2|S)Nz!Checking %s for cookies to returnz   not returning cookiez   it's a match)	r�r!rr�rtr"r|r r�)rr�r��cookies�cookies_by_pathr��cookies_by_namerrrr�_cookies_for_domain�s 

zCookieJar._cookies_for_domaincCs*g}|j��D]}|�|�||��q|S)z2Return a list of cookies to be returned to server.)r�rt�extendr�)rr�r�r�rrr�_cookies_for_requestszCookieJar._cookies_for_requestc	Cs<|jdd�dd�d}g}|D�]}|j}|sHd}|dkrH|�d|�|jdk	rz|j�|j�rz|dkrz|j�d	|j�}n|j}|jdkr�|�|j�n|�d
|j|f�|dkr|j	r�|�d|j
�|j�d��r|j}|j
s�|�d�r�|d
d�}|�d|�|jdk	rd}|j�r,|d|j}|�|�q|S)z�Return a list of cookie-attributes to be returned to server.

        like ['foo="bar"; $Path="/"', ...]

        The $Version attribute is also added when appropriate (currently only
        once per request).

        cSs
t|j�Sr)rXr�)�arrr�<lambda>�z)CookieJar._cookie_attrs.<locals>.<lambda>T)r��reverseFr	z$Version=%sNr�r�z
$Path="%s"r�r z$Domain="%s"z$Portz="%s")�sortr�r�r��non_word_rerY�quote_rer{r�r�r�r�r�r�r�r�)	rr�r��attrsrr�r�r�rrrr�
_cookie_attrssF


��
�
zCookieJar._cookie_attrscCs�td�|j��z�tt���|j_|_|�|�}|�	|�}|r^|�
d�s^|�dd�|��|jj
r�|jjs�|�
d�s�|D]}|jdkr||�dd�q�q|W5|j��X|��dS)z�Add correct Cookie: header to request (urllib.request.Request object).

        The Cookie2 header is also added unless policy.hide_cookie2 is true.

        �add_cookie_headerrr�ZCookie2r z$Version="1"N)rr��acquire�releaserZrgr�rjr�r��
has_header�add_unredirected_headerr�r&r(r��clear_expired_cookies)rr�r�r�rrrrr�Is*



��

zCookieJar.add_cookie_headerc
Cs�g}d}d}|D�]z}|d\}}d}d}	i}
i}|dd�D�]0\}}
|��}||ks`||krd|}||krx|
dkrxd}
||
kr�q>|dkr�|
dkr�td	�d}	�qr|
��}
|d
kr�|r�q>|
dkr�td�q>|dk�r d}zt|
�}
Wn*tk
�rtd
�d}	Y�qrYnXd
}|j|
}
||k�s4||k�rh|
dk�r^|dk�r^td|�d}	�qr|
|
|<q>|
||<q>|	�rzq|�|||
|f�q|S)aReturn list of tuples containing normalised cookie information.

        attrs_set is the list of lists of key,value pairs extracted from
        the Set-Cookie or Set-Cookie2 headers.

        Tuples are name, value, standard, rest, where name and value are the
        cookie name and value, standard is a dictionary containing the standard
        cookie-attributes (discard, secure, version, expires or max-age,
        domain, path and port) and rest is a dictionary containing the rest of
        the cookie-attributes.

        )r�r�)r�r�r�r�r�r�r��
commenturlr	Fr NTr�z%   missing value for domain attributer�zM   missing or invalid value for expires attribute: treating as session cookier�z?   missing or invalid (non-numeric) value for max-age attribute)r�r�r�z!   missing value for %s attribute)rerrZrfrjr�)r�	attrs_set�
cookie_tuples�
boolean_attrs�value_attrs�cookie_attrsr�r��max_age_set�
bad_cookie�standardrr�r�r�rrr�_normalized_cookie_tuplesjsh





�

z#CookieJar._normalized_cookie_tuplescCs&|\}}}}|�dt�}|�dt�}|�dt�}	|�dt�}
|�dd�}|dk	rtzt|�}Wntk
rrYdSX|�dd�}|�dd�}
|�d	d�}|�d
d�}|tk	r�|dkr�d}t|�}nXd}t|�}|�d
�}|dk�r|dkr�|d|�}n|d|d�}t|�dk�rd
}|tk	}d}|�r:t|�	d��}|tk�rVt
|�\}}|}n|�	d��sjd|}d}|	tk	�r�|	dk�r�t|�}	nd}t�
dd|	�}	nd}	|
tk�r�d}
d}
nH|
|jk�rz|�|||�Wntk
�r�YnXtd|||�dSt||||	||||||||
|
|||�S)Nr�r�r�r�r�r�Fr�r�r�rtTr�r�r	r r�z\s+z2Expiring cookie, domain='%s', path='%s', name='%s')rr~rZrfr�r�r�rX�boolr�r�r�r�r{rj�clear�KeyErrorrr)r�tupr�r�r�r�rr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rrr�_cookie_from_cookie_tuple�s�







��z#CookieJar._cookie_from_cookie_tuplecCs6|�|�}g}|D]}|�||�}|r|�|�q|Sr)r�r�r�)rr�r�r�r�r�rrrr�_cookies_from_attrs_set's
z!CookieJar._cookies_from_attrs_setcCsHt|jdd�}|dkr |jj}|D]}|jdkr$d|_|r$d|_q$dS)Nr'r Tr	)rr�r&r�r�)rr��
rfc2109_as_nsrrrr�_process_rfc2109_cookies0s

z"CookieJar._process_rfc2109_cookiesc
Cs:|��}|�dg�}|�dg�}tt���|j_|_|jj}|jj}|sN|rf|sV|rf|s^|rf|sj|sjgSz|�t	|�|�}Wnt
k
r�t�g}YnX|�r6|�r6z|�t|�|�}	Wnt
k
r�t�g}	YnX|�
|	�|�r&i}
|D]}d|
|j|j|jf<q�|
fdd�}t||	�}	|	�r6|�|	�|S)zAReturn sequence of Cookie objects extracted from response object.zSet-Cookie2z
Set-CookieNcSs|j|j|jf}||kSr)r�r�r�)�	ns_cookie�lookupr�rrr�no_matching_rfc2965isz3CookieJar.make_cookies.<locals>.no_matching_rfc2965)rS�get_allrZrgr�rjr&r%r�r��	Exceptionrr�r�r�r�r��filterr�)
r�responser�r��rfc2965_hdrs�ns_hdrsr&r%r��
ns_cookiesr�rr�rrr�make_cookies<s^�������
�



zCookieJar.make_cookiescCsN|j��z2tt���|j_|_|j�||�r:|�|�W5|j��XdS)z-Set a cookie if policy says it's OK to do so.N)	r�r�r�rZrgr�rjr�
set_cookierrrr�set_cookie_if_okss
zCookieJar.set_cookie_if_okcCsl|j}|j��zJ|j|kr&i||j<||j}|j|krDi||j<||j}|||j<W5|j��XdS)z?Set a cookie, without checking whether or not it should be set.N)r�r�r�r�r�r�r�)rr�c�c2�c3rrrr��s






zCookieJar.set_cookiecCsbtd|���|j��z8|�||�D]&}|j�||�r&td|�|�|�q&W5|j��XdS)zAExtract cookies from response, where allowable given the request.zextract_cookies: %sz setting cookie: %sN)	rrSr�r�r�r�r�rr�)rr�r�rrrr�extract_cookies�s

zCookieJar.extract_cookiescCst|dk	r2|dks|dkr td��|j|||=n>|dk	rX|dkrJtd��|j||=n|dk	rj|j|=ni|_dS)a�Clear some cookies.

        Invoking this method without arguments will clear all cookies.  If
        given a single argument, only cookies belonging to that domain will be
        removed.  If given two arguments, cookies belonging to the specified
        path within that domain are removed.  If given three arguments, then
        the cookie with the specified name, path and domain is removed.

        Raises KeyError if no matching cookie exists.

        Nz8domain and path must be given to remove a cookie by namez.domain must be given to remove cookies by path)rfr�)rr�r�r�rrrr��s��
zCookieJar.clearcCsD|j��z(|D]}|jr|�|j|j|j�qW5|j��XdS)z�Discard all session cookies.

        Note that the .save() method won't save session cookies anyway, unless
        you ask otherwise by passing a true ignore_discard argument.

        N)r�r�r�r�r�r�r�r�)rrrrr�clear_session_cookies�s
zCookieJar.clear_session_cookiescCsP|j��z4t��}|D]"}|�|�r|�|j|j|j�qW5|j��XdS)a�Discard all expired cookies.

        You probably don't need to call this method: expired cookies are never
        sent back to the server (provided you're using DefaultCookiePolicy),
        this method is called by CookieJar itself every so often, and the
        .save() method won't save expired cookies anyway (unless you ask
        otherwise by passing a true ignore_expires argument).

        N)	r�r�r�rgrr�r�r�r�)rr
rrrrr��s


zCookieJar.clear_expired_cookiescCs
t|j�Sr)rzr�r5rrr�__iter__�szCookieJar.__iter__cCsd}|D]}|d}q|S)z#Return number of contained cookies.r	r r)rr�rrrr�__len__�s
zCookieJar.__len__cCs2g}|D]}|�t|��qd|jjd�|�fS�Nz<%s[%s]>r�)r�rrrr��r�rrrrrr�szCookieJar.__repr__cCs2g}|D]}|�t|��qd|jjd�|�fSr�)r�r�rrr�r�rrrr�szCookieJar.__str__)N)NNN)"rrrrr��compiler�r��strict_domain_re�	domain_re�dots_re�ASCII�magic_rerr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rrrrrrr�s8





;!a\	7


c@seZdZdS)rNrrrrrr�sc@s8eZdZdZddd�Zd
dd�Zddd	�Zdd
d�ZdS)rz6CookieJar that can be loaded from and saved to a file.NFcCs2t�||�|dk	rt�|�}||_t|�|_dS)z}
        Cookies are NOT loaded from the named file until either the .load() or
        .revert() method is called.

        N)rr�os�fspath�filenamer��	delayload)rr�r�r�rrrr�s

zFileCookieJar.__init__cCs
t��dS)zSave cookies to a file.Nr)rr��ignore_discard�ignore_expiresrrr�save�szFileCookieJar.savec	CsJ|dkr"|jdk	r|j}ntt��t|��}|�||||�W5QRXdS)zLoad cookies from a file.N)r�rf�MISSING_FILENAME_TEXT�open�_really_load�rr�r�r�rrrr�loads

zFileCookieJar.loadcCs�|dkr"|jdk	r|j}ntt��|j��zFt�|j�}i|_z|�	|||�Wnt
k
rn||_�YnXW5|j��XdS)z�Clear all cookies and reload cookies from a saved file.

        Raises LoadError (or OSError) if reversion is not successful; the
        object's state will not be altered if this happens.

        N)r�rfr�r�r�r�r�deepcopyr�r��OSError)rr�r�r��	old_staterrr�revert	s

zFileCookieJar.revert)NFN)NFF)NFF)NFF)rrrrrr�r�r�rrrrr�s


	�cCs |j|jfd|jfd|jfg}|jdk	r8|�d|jf�|jrH|�d�|jrX|�d�|jrh|�d�|j	rx|�d�|j
r�|�d	tt|j
��f�|j
r�|�d
�|jr�|�d|jf�|jr�|�d|jf�t|j���}|D]}|�|t|j|�f�q�|�d
t|j�f�t|g�S)z�Return string representation of Cookie in the LWP cookie file format.

    Actually, the format is extended a bit -- see module docstring.

    r�r�Nr�)�	path_specN)�	port_specN)�
domain_dotN)r�Nr�)r�Nr�r�r�)r�r�r�r�r�r�r�r�r�r�r�rKrxr�r�r�rsrrtr�r�r�)rr�rtr�rrr�lwp_cookie_str$s:
�




�
r�c@s,eZdZdZddd�Zddd�Zd	d
�ZdS)
ra[
    The LWPCookieJar saves a sequence of "Set-Cookie3" lines.
    "Set-Cookie3" is the format used by the libwww-perl library, not known
    to be compatible with any browser, but which is easy to read and
    doesn't lose information about RFC 2965 cookies.

    Additional methods

    as_lwp_str(ignore_discard=True, ignore_expired=True)

    TcCsTt��}g}|D]2}|s |jr q|s0|�|�r0q|�dt|��qd�|dg�S)z�Return cookies as a string of "\n"-separated "Set-Cookie3" headers.

        ignore_discard and ignore_expires: see docstring for FileCookieJar.save

        zSet-Cookie3: %s�
rt)rgr�rr�r�r�)rr�r�r
r�rrrr�
as_lwp_strMs
zLWPCookieJar.as_lwp_strNFc	CsX|dkr"|jdk	r|j}ntt��t|d��"}|�d�|�|�||��W5QRXdS)N�wz#LWP-Cookies-2.0
)r�rfr�r��writer�r�rrrr�]s

zLWPCookieJar.savecCs0|��}|j�|�s$d|}t|��t��}d}d}	d}
�z�|��}|dkrP�q�|�|�s\q<|t|�d���}t|g�D�]f}|d\}
}i}i}|	D]}d||<q�|dd�D]n\}}|dk	r�|�	�}nd}||
ks�||	kr�|}||	k�r|dkr�d	}|||<q�||
k�r|||<q�|||<q�|j
}|d
�}|d�}|dk	�rJt|�}|dk�rXd	}|d�}|�d
�}t|d�|
||d�|d�|||d�|d�|d�|d�|||d�|d�|�}|�s�|j
�r�qz|�s�|�|��r�qz|�|�qzq<WnBtk
�r�Yn,tk
�r*t�td||f��YnXdS)Nz5%r does not look like a Set-Cookie3 (LWP) format filezSet-Cookie3:)r�r�r�r�r�)r�r�r�r�r�r�r�rtr	Fr Tr�r�r�r�r�r�r�r�r�r�r�r�r�z&invalid Set-Cookie3 format file %r: %r)�readliner�rYrrgr�rXr�r�rerr�rr�rr�r�r�r)rrr�r�r��magicrr
�headerr�r��line�datar�r�r�rr�r�r�r�r�r�r�r�r�rrrr�is��










�
�zLWPCookieJar._really_load)TT)NFF)rrrrr�r�r�rrrrr@s

c@s0eZdZdZe�d�ZdZdd�Zd
dd	�Z	dS)ra�

    WARNING: you may want to backup your browser's cookies file if you use
    this class to save cookies.  I *think* it works, but there have been
    bugs in the past!

    This class differs from CookieJar only in the format it uses to save and
    load cookies to and from a file.  This class uses the Mozilla/Netscape
    `cookies.txt' format.  lynx uses this file format, too.

    Don't expect cookies saved while the browser is running to be noticed by
    the browser (in fact, Mozilla on unix will overwrite your saved cookies if
    you change them on disk while it's running; on Windows, you probably can't
    save at all while the browser is running).

    Note that the Mozilla/Netscape format will downgrade RFC2965 cookies to
    Netscape cookies on saving.

    In particular, the cookie version and port number information is lost,
    together with information about whether or not Path, Port and Discard were
    specified by the Set-Cookie2 (or Set-Cookie) header, and whether or not the
    domain as set in the HTTP header started with a dot (yes, I'm aware some
    domains in Netscape files start with a dot and some don't -- trust me, you
    really don't want to know any more about this).

    Note that though Mozilla and Netscape use the same format, they use
    slightly different headers.  The class saves cookies using the Netscape
    header by default (Mozilla can cope with that).

    z#( Netscape)? HTTP Cookie Filezr# Netscape HTTP Cookie File
# http://curl.haxx.se/rfc/cookie_spec.html
# This is a generated file!  Do not edit.

cCstt��}|��}|j�|�s(td|���z|��}|dkr@�q*|�d�rV|dd�}|���d�s,|��dkrrq,|�d�\}}	}
}}}
}|dk}|	dk}	|
dkr�|}
d}|�d�}|	|ks�t	�d	}|dkr�d}d
}t
d|
|dd	||	||
d	|||ddi�}|�s
|j�r
q,|�s|�|��rq,|�
|�q,WnBtk
�rD�Yn,tk
�rnt�td||f��YnXdS)
Nz4%r does not look like a Netscape format cookies filertr�r�)�#rI�	�TRUEr�FTr	z+invalid Netscape format cookies file %r: %r)rgr�r�rYrr�r�r�r�r�rr�rr�r�r�r)rrr�r�r�r
r�r�r�r�r�r�r�r�r�r�r�r�rrrr��st��

��
�
�zMozillaCookieJar._really_loadNFc
Cs�|dkr"|jdk	r|j}ntt��t|d���}|�|j�t��}|D]�}|sV|jrVqF|sf|�|�rfqF|j	rrd}nd}|j
�d�r�d}nd}|jdk	r�t
|j�}	nd}	|jdkr�d}
|j}n|j}
|j}|�d�|j
||j||	|
|g�d�qFW5QRXdS)Nr�r��FALSEr�rtr�r�)r�rfr�r�r�r�rgr�rr�r�r�r�r�r�r�r�r�)rr�r�r�rr
rr�r�r�r�r�rrrr� sH



���zMozillaCookieJar.save)NFF)
rrrrr�r�r�r�r�r�rrrrr�s

A)N)N)Xr�__all__r�rrBr�rg�urllib.parser��urllib.request�	threadingr��http.client�http�calendarr
rrrr��client�	HTTP_PORTr�r�rr&r.rLrNrcr)r�rerKrOrWr�r�rXr_rqrv�Irz�Xr|rr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rrrrwrzr~rr�rrr�rrrrrr�<module>s��
�

8�
�
�8
�!



U
D'


#b!b7x�h�#bytecode of module 'http.cookiejar'�u��b.���;h)��N}�(hB�;�
@stdZddlZddlZdddgZdjZdjZdjZGd	d�de�Z	ej
ejd
ZedZ
dd
�eed��eeee
��D�Ze�ed�ded�di�e�de�e��jZdd�Ze�d�Ze�d�Zdd�Zddddddd gZdd!d"d#d$d%d&d'd(d)d*d+d,g
Zdeefd-d.�ZGd/d0�d0e�Z d1Z!e!d2Z"e�d3e!d4e"d5ej#ej$B�Z%Gd6d�de�Z&Gd7d�de&�Z'dS)8a.

Here's a sample session to show how to use this module.
At the moment, this is the only documentation.

The Basics
----------

Importing is easy...

   >>> from http import cookies

Most of the time you start by creating a cookie.

   >>> C = cookies.SimpleCookie()

Once you've created your Cookie, you can add values just as if it were
a dictionary.

   >>> C = cookies.SimpleCookie()
   >>> C["fig"] = "newton"
   >>> C["sugar"] = "wafer"
   >>> C.output()
   'Set-Cookie: fig=newton\r\nSet-Cookie: sugar=wafer'

Notice that the printable representation of a Cookie is the
appropriate format for a Set-Cookie: header.  This is the
default behavior.  You can change the header and printed
attributes by using the .output() function

   >>> C = cookies.SimpleCookie()
   >>> C["rocky"] = "road"
   >>> C["rocky"]["path"] = "/cookie"
   >>> print(C.output(header="Cookie:"))
   Cookie: rocky=road; Path=/cookie
   >>> print(C.output(attrs=[], header="Cookie:"))
   Cookie: rocky=road

The load() method of a Cookie extracts cookies from a string.  In a
CGI script, you would use this method to extract the cookies from the
HTTP_COOKIE environment variable.

   >>> C = cookies.SimpleCookie()
   >>> C.load("chips=ahoy; vienna=finger")
   >>> C.output()
   'Set-Cookie: chips=ahoy\r\nSet-Cookie: vienna=finger'

The load() method is darn-tootin smart about identifying cookies
within a string.  Escaped quotation marks, nested semicolons, and other
such trickeries do not confuse it.

   >>> C = cookies.SimpleCookie()
   >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
   >>> print(C)
   Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"

Each element of the Cookie also supports all of the RFC 2109
Cookie attributes.  Here's an example which sets the Path
attribute.

   >>> C = cookies.SimpleCookie()
   >>> C["oreo"] = "doublestuff"
   >>> C["oreo"]["path"] = "/"
   >>> print(C)
   Set-Cookie: oreo=doublestuff; Path=/

Each dictionary element has a 'value' attribute, which gives you
back the value associated with the key.

   >>> C = cookies.SimpleCookie()
   >>> C["twix"] = "none for you"
   >>> C["twix"].value
   'none for you'

The SimpleCookie expects that all values should be standard strings.
Just to be sure, SimpleCookie invokes the str() builtin to convert
the value to a string, when the values are set dictionary-style.

   >>> C = cookies.SimpleCookie()
   >>> C["number"] = 7
   >>> C["string"] = "seven"
   >>> C["number"].value
   '7'
   >>> C["string"].value
   'seven'
   >>> C.output()
   'Set-Cookie: number=7\r\nSet-Cookie: string=seven'

Finis.
�N�CookieError�
BaseCookie�SimpleCookie�z; � c@seZdZdS)rN)�__name__�
__module__�__qualname__�r
r
�"/usr/lib/python3.8/http/cookies.pyr�sz!#$%&'*+-.^_`|~:z
 ()/<=>?@[]{}cCsi|]}|d|�qS)z\%03or
)�.0�nr
r
r�
<dictcomp>�s�r��"�\"�\z\\z[%s]+cCs*|dkst|�r|Sd|�t�dSdS)z�Quote a string for use in a cookie header.

    If the string does not need to be double-quoted, then just return the
    string.  Otherwise, surround the string in doublequotes and quote
    (with a \) special characters.
    Nr)�
_is_legal_key�	translate�_Translator��strr
r
r�_quote�srz\\[0-3][0-7][0-7]z[\\].cCsN|dkst|�dkr|S|ddks0|ddkr4|S|dd�}d}t|�}g}d|krf|k�rFnn�t�||�}t�||�}|s�|s�|�||d���qFd}}|r�|�d�}|r�|�d�}|�r|r�||k�r|�|||��|�||d�|d}qP|�|||��|�tt||d|d�d���|d}qPt|�S)N�rr������)	�len�
_OctalPatt�search�
_QuotePatt�append�start�chr�int�	_nulljoin)r�ir
�res�o_match�q_match�j�kr
r
r�_unquote�s6


$
r-�Mon�Tue�Wed�Thu�Fri�Sat�Sun�Jan�Feb�Mar�Apr�May�Jun�Jul�Aug�Sep�Oct�Nov�Decc	CsRddlm}m}|�}|||�\	}}}}	}
}}}
}d|||||||	|
|fS)Nr)�gmtime�timez#%s, %02d %3s %4d %02d:%02d:%02d GMT)rBrA)�future�weekdayname�	monthnamerArB�now�year�month�day�hh�mm�ss�wd�y�zr
r
r�_getdate�s�rPc
@s�eZdZdZdddddddd	d
d�	Zdd
hZdd�Zedd��Zedd��Z	edd��Z
dd�Zd2dd�Zdd�Z
ejZdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd3d*d+�ZeZd,d-�Zd4d.d/�Zd5d0d1�ZdS)6�MorselaCA class to hold ONE (key, value) pair.

    In a cookie, each such pair may have several attributes, so this class is
    used to keep the attributes associated with the appropriate key,value pair.
    This class also includes a coded_value attribute, which is used to hold
    the network representation of the value.
    �expires�Path�Comment�DomainzMax-AgeZSecureZHttpOnly�VersionZSameSite)	rR�path�comment�domain�max-age�secure�httponly�versionZsamesiter[r\cCs0d|_|_|_|jD]}t�||d�qdS)Nr)�_key�_value�_coded_value�	_reserved�dict�__setitem__)�self�keyr
r
r�__init__ s
zMorsel.__init__cCs|jS�N)r^�rdr
r
rre(sz
Morsel.keycCs|jSrg)r_rhr
r
r�value,szMorsel.valuecCs|jSrg)r`rhr
r
r�coded_value0szMorsel.coded_valuecCs2|��}||jkr td|f��t�|||�dS�NzInvalid attribute %r)�lowerrarrbrc)rd�K�Vr
r
rrc4s
zMorsel.__setitem__NcCs.|��}||jkr td|f��t�|||�Srk)rlrarrb�
setdefault)rdre�valr
r
rro:s
zMorsel.setdefaultcCs>t|t�stSt�||�o<|j|jko<|j|jko<|j|jkSrg)�
isinstancerQ�NotImplementedrb�__eq__r_r^r`�rd�morselr
r
rrs@s

�
�
�z
Morsel.__eq__cCs$t�}t�||�|j�|j�|Srg)rQrb�update�__dict__rtr
r
r�copyJszMorsel.copycCsRi}t|���D]0\}}|��}||jkr8td|f��|||<qt�||�dSrk)rb�itemsrlrarrv)rd�values�datarerpr
r
rrvPs

z
Morsel.updatecCs|��|jkSrg)rlra)rdrmr
r
r�
isReservedKeyYszMorsel.isReservedKeycCsH|��|jkrtd|f��t|�s2td|f��||_||_||_dS)Nz Attempt to set a reserved key %rzIllegal key %r)rlrarrr^r_r`)rdrerp�	coded_valr
r
r�set\sz
Morsel.setcCs|j|j|jd�S)N)rerirj�r^r_r`rhr
r
r�__getstate__gs�zMorsel.__getstate__cCs"|d|_|d|_|d|_dS)Nrerirjr)rd�stater
r
r�__setstate__ns

zMorsel.__setstate__�Set-Cookie:cCsd||�|�fS)Nz%s %s)�OutputString)rd�attrs�headerr
r
r�outputssz
Morsel.outputcCsd|jj|��fS)N�<%s: %s>)�	__class__rr�rhr
r
r�__repr__xszMorsel.__repr__cCsd|�|��dd�S)Nz�
        <script type="text/javascript">
        <!-- begin hiding
        document.cookie = "%s";
        // end hiding -->
        </script>
        rr)r��replace)rdr�r
r
r�	js_output{s�zMorsel.js_outputcCs$g}|j}|d|j|jf�|dkr,|j}t|���}|D]�\}}|dkrNq<||krXq<|dkr�t|t�r�|d|j|t|�f�q<|dkr�t|t�r�|d|j||f�q<|dkr�t|t	�r�|d|j|t
|�f�q<||jk�r|�r|t	|j|��q<|d|j||f�q<t|�S)N�%s=%srrRrZz%s=%drX)
r"rerjra�sortedryrqr%rPrr�_flags�_semispacejoin)rdr��resultr"ryrerir
r
rr��s,zMorsel.OutputString)N)Nr�)N)N)rrr	�__doc__rar�rf�propertyrerirjrcrors�object�__ne__rxrvr|r~r�r�r��__str__r�r�r�r
r
r
rrQ�sD�



	


rQz,\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\=z\[\]z�
    \s*                            # Optional whitespace at start of cookie
    (?P<key>                       # Start of group 'key'
    [a	]+?   # Any word of at least one letter
    )                              # End of group 'key'
    (                              # Optional group: there may not be a value.
    \s*=\s*                          # Equal Sign
    (?P<val>                         # Start of group 'val'
    "(?:[^\\"]|\\.)*"                  # Any doublequoted string
    |                                  # or
    \w{3},\s[\w\d\s-]{9,11}\s[\d:]{8}\sGMT  # Special case for "expires" attr
    |                                  # or
    [a-]*      # Any word or empty string
    )                                # End of group 'val'
    )?                             # End of optional value group
    \s*                            # Any number of spaces.
    (\s+|;|$)                      # Ending either at space, semicolon, or EOS.
    c@sneZdZdZdd�Zdd�Zddd�Zd	d
�Zdd�Zddd�Z	e	Z
dd�Zddd�Zdd�Z
efdd�ZdS)rz'A container class for a set of Morsels.cCs||fS)a
real_value, coded_value = value_decode(STRING)
        Called prior to setting a cookie's value from the network
        representation.  The VALUE is the value read from HTTP
        header.
        Override this function to modify the behavior of cookies.
        r
�rdrpr
r
r�value_decode�szBaseCookie.value_decodecCst|�}||fS)z�real_value, coded_value = value_encode(VALUE)
        Called prior to setting a cookie's value from the dictionary
        representation.  The VALUE is the value being assigned.
        Override this function to modify the behavior of cookies.
        r�rdrp�strvalr
r
r�value_encode�szBaseCookie.value_encodeNcCs|r|�|�dSrg)�load)rd�inputr
r
rrf�szBaseCookie.__init__cCs.|�|t��}|�|||�t�|||�dS)z+Private method for setting a cookie's valueN)�getrQr~rbrc)rdre�
real_valuerj�Mr
r
r�__set�szBaseCookie.__setcCs:t|t�rt�|||�n|�|�\}}|�|||�dS)zDictionary style assignment.N)rqrQrbrcr��_BaseCookie__set)rdreri�rval�cvalr
r
rrc�s
zBaseCookie.__setitem__r��
cCs:g}t|���}|D]\}}|�|�||��q|�|�S)z"Return a string suitable for HTTP.)r�ryr"r��join)rdr�r��sepr�ryrerir
r
rr��s
zBaseCookie.outputcCsJg}t|���}|D] \}}|�d|t|j�f�qd|jjt|�fS)Nr�r�)r�ryr"�reprrir�r�
_spacejoin)rd�lryrerir
r
rr��s
zBaseCookie.__repr__cCs6g}t|���}|D]\}}|�|�|��qt|�S)z(Return a string suitable for JavaScript.)r�ryr"r�r&)rdr�r�ryrerir
r
rr�s
zBaseCookie.js_outputcCs4t|t�r|�|�n|��D]\}}|||<qdS)z�Load cookies from a string (presumably HTTP_COOKIE) or
        from a dictionary.  Loading cookies from a dictionary 'd'
        is equivalent to calling:
            map(Cookie.__setitem__, d.keys(), d.values())
        N)rqr�_BaseCookie__parse_stringry)rd�rawdatarerir
r
rr�
s


zBaseCookie.loadcCs�d}t|�}g}d}d}d}d|kr2|k�rnn�|�||�}	|	sJ�q|	�d�|	�d�}
}|	�d�}|
ddkr�|s|q|�||
dd�|f�q|
��tjkr�|s�dS|dkr�|
��tjkr�|�||
df�q�dSn|�||
t	|�f�q|dk	�r|�||
|�
|�f�d}qdSqd}|D]Z\}
}
}|
|k�rP|dk	�sFt�|||
<n,|
|k�s^t�|\}}|�|
||�||
}�q$dS)	NrFrrrerp�$T)
r�match�group�endr"rlrQrar�r-r��AssertionErrorr�)rdr�pattr'r
�parsed_items�morsel_seen�TYPE_ATTRIBUTE�
TYPE_KEYVALUEr�rerir��tpr�r�r
r
r�__parse_stringsJ



zBaseCookie.__parse_string)N)Nr�r�)N)rrr	r�r�r�rfr�rcr�r�r�r�r��_CookiePatternr�r
r
r
rr�s		
	

c@s eZdZdZdd�Zdd�ZdS)rz�
    SimpleCookie supports strings as cookie values.  When setting
    the value using the dictionary assignment notation, SimpleCookie
    calls the builtin str() to convert the value to a string.  Values
    received from HTTP are kept as strings.
    cCst|�|fSrg)r-r�r
r
rr�\szSimpleCookie.value_decodecCst|�}|t|�fSrg)rrr�r
r
rr�_szSimpleCookie.value_encodeN)rrr	r�r�r�r
r
r
rrUs)(r��re�string�__all__r�r&r�r��	Exceptionr�
ascii_letters�digits�_LegalChars�_UnescapedCharsr~�range�map�ordrrv�compile�escape�	fullmatchrrrr!r-�_weekdayname�
_monthnamerPrbrQ�_LegalKeyChars�_LegalValueChars�ASCII�VERBOSEr�rrr
r
r
r�<module>'sr]
��

2�4����
�
�h�!bytecode of module 'http.cookies'�u��b.���h)��N}�(hB��@sdddlZddlmZdd�eej�D�Ze��dd�eD��dZd	Z	d
ej
kr`ej
d
ej
d<dS)�N�)�contextcCsg|]}|�d�s|�qS)�_)�
startswith)�.0�x�r�./usr/lib/python3.8/multiprocessing/__init__.py�
<listcomp>s
r
ccs|]}|ttj|�fVqdS)N)�getattrr�_default_context)r�namerrr	�	<genexpr>sr���__main__�__mp_main__)�sys�r�dirr�__all__�globals�update�SUBDEBUG�
SUBWARNING�modulesrrrr	�<module>s
�h�$bytecode of module 'multiprocessing'�u��b.���bh)��N}�(hB�b�@sddddgZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZddl
mZm
Z
dd	lmZejZz$ddlZdd
lmZmZmZmZWn$ek
r�ejdkr‚dZYnXdZd
Ze��ZdZdgZeed�r�dZedg7Zejdk�rdZedg7Zefdd�Z dd�Z!dd�Z"dd�Z#dd�Z$Gdd�d�Z%e�rhGdd�de%�Z&Gdd �d e%�Z'Gd!d�de(�Z)dOd"d�Z*ejdk�r�dPd$d�Z+n
dQd%d�Z+Gd&d'�d'e(�Z,d(d)�Z-ejdk�r�Gd*d+�d+e(�Z.d,d-�Z/d.Z0d/Z1d0Z2d1Z3d2d3�Z4d4d5�Z5Gd6d7�d7e(�Z6d8d9�Z7d:d;�Z8Gd<d=�d=e)�Z9d>d?�Z:ejdk�rtd@dA�Z;ej<ej=hZ>dRdBd�Z?n,ddl@Z@ee@dC��r�e@jAZBne@jCZBdSdDd�Z?ejdk�r�dEdF�ZDdGdH�ZEe�Fe'eD�dIdJ�ZGdKdL�ZHe�Fe&eG�ndMdF�ZDdNdH�ZEe�Fe'eD�dS)T�Client�Listener�Pipe�wait�N�)�util)�AuthenticationError�BufferTooShort)�	reduction)�
WAIT_OBJECT_0�WAIT_ABANDONED_0�WAIT_TIMEOUT�INFINITE�win32i g4@�AF_INET�AF_UNIX�AF_PIPEcCst��|S�N��time�	monotonic)�timeout�r�0/usr/lib/python3.8/multiprocessing/connection.py�
_init_timeout;srcCst��|kSrr)�trrr�_check_timeout>srcCsX|dkrdS|dkr&tjdt��d�S|dkrLtjdt��tt�fdd�Std	��d
S)z?
    Return an arbitrary free address for the given family
    r)�	localhostrrz	listener-)�prefix�dirrz\\.\pipe\pyc-%d-%d-�zunrecognized familyN)	�tempfile�mktempr�get_temp_dir�os�getpid�next�
_mmap_counter�
ValueError��familyrrr�arbitrary_addressEs��r+cCsJtjdkr|dkrtd|��tjdkrF|dkrFtt|�sFtd|��dS)zD
    Checks if the family is valid for the current environment.
    rrzFamily %s is not recognized.rN)�sys�platformr(�hasattr�socketr)rrr�_validate_familySs

r0cCsTt|�tkrdSt|�tkr*|�d�r*dSt|�tks@t�|�rDdStd|��dS)z]
    Return the types of the address

    This can be 'AF_INET', 'AF_UNIX', or 'AF_PIPE'
    rz\\rrzaddress type of %r unrecognizedN)�type�tuple�str�
startswithr�is_abstract_socket_namespacer()�addressrrr�address_type_sr7c@s�eZdZdZd+dd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	e
dd��Ze
dd��Ze
dd��Z
dd�Zdd�Zd,dd�Zdd�Zd-dd�Zd.d d!�Zd"d#�Zd/d%d&�Zd'd(�Zd)d*�ZdS)0�_ConnectionBaseNTcCs>|��}|dkrtd��|s(|s(td��||_||_||_dS)Nrzinvalid handlez6at least one of `readable` and `writable` must be True)�	__index__r(�_handle�	_readable�	_writable)�self�handle�readable�writablerrr�__init__us�z_ConnectionBase.__init__cCs|jdk	r|��dSr�r:�_close�r=rrr�__del__�s
z_ConnectionBase.__del__cCs|jdkrtd��dS)Nzhandle is closed)r:�OSErrorrDrrr�
_check_closed�s
z_ConnectionBase._check_closedcCs|jstd��dS)Nzconnection is write-only)r;rFrDrrr�_check_readable�sz_ConnectionBase._check_readablecCs|jstd��dS)Nzconnection is read-only)r<rFrDrrr�_check_writable�sz_ConnectionBase._check_writablecCs"|jrd|_n|��td��dS)NFzbad message length)r<r;�closerFrDrrr�_bad_message_length�sz#_ConnectionBase._bad_message_lengthcCs
|jdkS)z True if the connection is closedN�r:rDrrr�closed�sz_ConnectionBase.closedcCs|jS)z"True if the connection is readable)r;rDrrrr?�sz_ConnectionBase.readablecCs|jS)z"True if the connection is writable)r<rDrrrr@�sz_ConnectionBase.writablecCs|��|jS)z+File descriptor or handle of the connection)rGr:rDrrr�fileno�sz_ConnectionBase.filenocCs$|jdk	r z|��W5d|_XdS)zClose the connectionNrBrDrrrrJ�s
z_ConnectionBase.closercCs�|��|��t|�}|jdkr.tt|��}t|�}|dkrFtd��||krVtd��|dkrh||}n&|dkrztd��n|||kr�td��|�||||��dS)z,Send the bytes data from a bytes-like objectrrzoffset is negativezbuffer length < offsetNzsize is negativezbuffer length < offset + size)rGrI�
memoryview�itemsize�bytes�lenr(�_send_bytes)r=�buf�offset�size�m�nrrr�
send_bytes�s"


z_ConnectionBase.send_bytescCs$|��|��|�t�|��dS)zSend a (picklable) objectN)rGrIrS�_ForkingPickler�dumps�r=�objrrr�send�sz_ConnectionBase.sendcCsJ|��|��|dk	r(|dkr(td��|�|�}|dkrB|��|��S)z7
        Receive bytes data as a bytes object.
        Nrznegative maxlength)rGrHr(�_recv_bytesrK�getvalue)r=�	maxlengthrTrrr�
recv_bytes�s
z_ConnectionBase.recv_bytesc
Cs�|��|��t|���}|j}|t|�}|dkr>td��n||krNtd��|��}|��}|||krvt|�	���|�
d�|�||||||��|W5QR�SQRXdS)zq
        Receive bytes data into a writeable bytes-like object.
        Return the number of bytes read.
        rznegative offsetzoffset too largeN)rGrHrOrPrRr(r_�tellr	r`�seek�readinto)r=rTrUrWrP�bytesize�resultrVrrr�recv_bytes_into�s$



�z_ConnectionBase.recv_bytes_intocCs&|��|��|��}t�|���S)zReceive a (picklable) object)rGrHr_rZ�loads�	getbuffer)r=rTrrr�recv�sz_ConnectionBase.recv�cCs|��|��|�|�S)z/Whether there is any input available to be read)rGrH�_poll�r=rrrr�poll�sz_ConnectionBase.pollcCs|SrrrDrrr�	__enter__sz_ConnectionBase.__enter__cCs|��dSr�rJ�r=�exc_type�	exc_value�exc_tbrrr�__exit__sz_ConnectionBase.__exit__)TT)rN)N)r)rl)�__name__�
__module__�__qualname__r:rArErGrHrIrK�propertyrMr?r@rNrJrYr^rbrhrkrorprvrrrrr8rs.








r8c@sDeZdZdZdZejfdd�Zdd�Zddd	�Z	d
d�Z
dd
�ZdS)�PipeConnectionz�
        Connection class based on a Windows named pipe.
        Overlapped I/O is used, so the handles must have been created
        with FILE_FLAG_OVERLAPPED.
        FcCs||j�dSrrL)r=�_CloseHandlerrrrCszPipeConnection._closec	Cs�tj|j|dd�\}}zHz,|tjkrBt�|jgdt�}|tksBt	�Wn|�
��YnXW5|�d�\}}X|dks|t	�|t|�ks�t	�dS)NT��
overlappedFr)�_winapi�	WriteFiler:�GetOverlappedResult�ERROR_IO_PENDING�WaitForMultipleObjects�eventrr�AssertionError�cancelrR)r=rT�ov�err�nwritten�waitresrrrrSs
�zPipeConnection._send_bytesNc	Cs2|jrd|_t��S|dkr dnt|d�}z�tj|j|dd�\}}dzHz,|tjkrpt�
|jgdt�}|tkspt�Wn|���YnXW5|�d�\}}|dkr�t��}|�|�	��|�WS|tj
kr�|�||��WSXWn:tk
�r$}z|jtjk�rt�n�W5d}~XYnXtd��dS)NF�Tr}rz.shouldn't get here; expected KeyboardInterrupt)�_got_empty_message�io�BytesIO�minr�ReadFiler:r��writerj�ERROR_MORE_DATA�_get_more_datar�r�r�rrr�r�rF�winerror�ERROR_BROKEN_PIPE�EOFError�RuntimeError)	r=�maxsize�bsizer�r��nread�fr��errrr_&s>
�

�
zPipeConnection._recv_bytescCs.|jst�|j�ddkrdStt|g|��S)NrT)r�r�
PeekNamedPiper:�boolrrnrrrrmFs
�zPipeConnection._pollcCs�|��}t��}|�|�t�|j�d}|dks6t�|dk	rVt|�||krV|�	�tj
|j|dd�\}}|�d�\}}|dks�t�||ks�t�|�|���|S)NrrTr})rjr�r�r�rr�r:r�rRrKr�r�)r=r�r�rTr��leftr��rbytesrrrr�Ls
zPipeConnection._get_more_data)N)rwrxry�__doc__r�r�CloseHandlerCrSr_rmr�rrrrr{s
 r{c@s|eZdZdZer,ejfdd�ZejZ	ej
Znej
fdd�ZejZ	ejZe	fdd�Zefdd�Zd	d
�Zddd
�Zdd�ZdS)�
Connectionzo
    Connection class based on an arbitrary file descriptor (Unix only), or
    a socket handle (Windows).
    cCs||j�dSrrL�r=rCrrrrCcszConnection._closecCs||j�dSrrLr�rrrrChscCs8t|�}||j|�}||8}|dkr&q4||d�}qdS�Nr)rRr:)r=rTr��	remainingrXrrr�_sendmszConnection._sendcCsbt��}|j}|}|dkr^|||�}t|�}|dkrJ||krBt�ntd��|�|�||8}q|S)Nrzgot end of file during message)r�r�r:rRr�rFr�)r=rV�readrTr>r��chunkrXrrr�_recvvs


zConnection._recvcCs�t|�}|dkrHt�dd�}t�d|�}|�|�|�|�|�|�n8t�d|�}|dkrr|�|�|�|�n|�||�dS)Ni����!i����!Qi@)rR�struct�packr�)r=rTrX�
pre_header�headerrrrrS�s


zConnection._send_bytesNcCs^|�d�}t�d|���\}|dkr@|�d�}t�d|���\}|dk	rT||krTdS|�|�S)N�r�r��r�)r�r��unpackr`)r=r�rTrVrrrr_�s

zConnection._recv_bytescCst|g|�}t|�Sr)rr�)r=r�rrrrrm�szConnection._poll)N)rwrxryr�r�_multiprocessing�closesocketrCr^�_writerk�_readr$rJr�r�r�r�rSr_rmrrrrr�\s	

r�c@sReZdZdZddd�Zdd�Zdd	�Zed
d��Zedd
��Z	dd�Z
dd�ZdS)rz�
    Returns a listener object.

    This is a wrapper for a bound socket which is 'listening' for
    connections, or for a Windows named pipe.
    NrcCsp|p|rt|�pt}|pt|�}t|�|dkr>t||�|_nt|||�|_|dk	rft|t�sft	d��||_
dS)Nr�authkey should be a byte string)r7�default_familyr+r0�PipeListener�	_listener�SocketListener�
isinstancerQ�	TypeError�_authkey)r=r6r*�backlog�authkeyrrrrA�s�zListener.__init__cCs>|jdkrtd��|j��}|jr:t||j�t||j�|S)zz
        Accept a connection on the bound socket or named pipe of `self`.

        Returns a `Connection` object.
        Nzlistener is closed)r�rF�acceptr��deliver_challenge�answer_challenge)r=�crrrr��s

zListener.acceptcCs |j}|dk	rd|_|��dS)zA
        Close the bound socket or named pipe of `self`.
        N)r�rJ)r=�listenerrrrrJ�szListener.closecCs|jjSr)r��_addressrDrrrr6�szListener.addresscCs|jjSr)r��_last_acceptedrDrrr�
last_accepted�szListener.last_acceptedcCs|SrrrDrrrrp�szListener.__enter__cCs|��dSrrqrrrrrrv�szListener.__exit__)NNrN)rwrxryr�rAr�rJrzr6r�rprvrrrrr�s
	

cCsh|p
t|�}t|�|dkr&t|�}nt|�}|dk	rHt|t�sHtd��|dk	rdt||�t||�|S)z=
    Returns a connection to the address of a `Listener`
    rNr�)	r7r0�
PipeClient�SocketClientr�rQr�r�r�)r6r*r�r�rrrr�s


TcCsj|r>t��\}}|�d�|�d�t|���}t|���}n$t��\}}t|dd�}t|dd�}||fS)�L
        Returns pair of connection objects at either end of a pipe
        TF�r@�r?)r/�
socketpair�setblockingr��detachr$�pipe)�duplex�s1�s2�c1�c2�fd1�fd2rrrrs

c

Cs�td�}|r*tj}tjtjB}tt}}ntj}tj}dt}}t�||tjBtj	Btj
tjBtjBd||tj
tj�}t�||dtjtjtjtj�}t�|tjdd�tj|dd�}|�d�\}	}
|
dks�t�t||d�}t||d�}||fS)	r�rrrNTr}r�r�)r+r�PIPE_ACCESS_DUPLEX�GENERIC_READ�
GENERIC_WRITE�BUFSIZEZPIPE_ACCESS_INBOUND�CreateNamedPipe�FILE_FLAG_OVERLAPPED�FILE_FLAG_FIRST_PIPE_INSTANCE�PIPE_TYPE_MESSAGE�PIPE_READMODE_MESSAGE�	PIPE_WAIT�NMPWAIT_WAIT_FOREVER�NULL�
CreateFile�
OPEN_EXISTING�SetNamedPipeHandleState�ConnectNamedPiper�r�r{)
r�r6�openmode�access�obsize�ibsize�h1�h2r~�_r�r�r�rrrrsV
�
��	��c@s*eZdZdZd
dd�Zdd�Zdd�Zd	S)r�zO
    Representation of a socket which is bound to an address and listening
    rcCs�t�tt|��|_zRtjdkr2|j�tjtjd�|j�d�|j�	|�|j�
|�|j��|_Wn t
k
r�|j���YnX||_d|_|dkr�t�|�s�tj|tj|fdd�|_nd|_dS)N�posixrTrr��args�exitpriority)r/�getattr�_socketr$�name�
setsockopt�
SOL_SOCKET�SO_REUSEADDRr��bind�listen�getsocknamer�rFrJ�_familyr�rr5�Finalize�unlink�_unlink)r=r6r*r�rrrrAGs0

�
�
zSocketListener.__init__cCs&|j��\}|_|�d�t|���S)NT)r�r�r�r�r�r��r=�srrrr�`s
zSocketListener.acceptcCs0z|j��W5|j}|dk	r*d|_|�XdSr)rr�rJ)r=rrrrrJeszSocketListener.closeN)r)rwrxryr�rAr�rJrrrrr�Cs
r�c
CsPt|�}t�tt|���.}|�d�|�|�t|���W5QR�SQRXdS)zO
    Return a connection object connected to the socket given by `address`
    TN)r7r/r�r��connectr�r�)r6r*rrrrr�os


r�c@s8eZdZdZddd�Zd
dd�Zdd	�Zed
d��ZdS)r�z0
        Representation of a named pipe
        NcCsL||_|jdd�g|_d|_t�d|j�tj|tj|j|jfdd�|_	dS)NT)�firstz listener created with address=%rrr�)
r��_new_handle�
_handle_queuer�r�	sub_debugrr��_finalize_pipe_listenerrJ)r=r6r�rrrrA�s
�zPipeListener.__init__Fc
CsHtjtjB}|r|tjO}t�|j|tjtjBtjBtj	t
t
tjtj�Sr)
rr�r�r�r�r�r�r�r�ZPIPE_UNLIMITED_INSTANCESr�r�r�)r=r�flagsrrrr�s

��zPipeListener._new_handlec
Cs�|j�|���|j�d�}ztj|dd�}Wn0tk
r^}z|jtjkrN�W5d}~XYn\Xz<zt�|jgdt
�}Wn |��t�|��YnXW5|�	d�\}}|dks�t
�Xt|�S)NrTr}F)r	�appendr�poprr�rFr��
ERROR_NO_DATAr�r�r�r�rr�r�r{)r=r>r�r�r�r��resrrrr��s(�
zPipeListener.acceptcCs$t�d|�|D]}t�|�qdS)Nz closing listener with address=%r)rr
rr�)�queuer6r>rrrr�sz$PipeListener._finalize_pipe_listener)N)F)	rwrxryr�rArr��staticmethodrrrrrr�s

r�c
Cs�t�}z6t�|d�t�|tjtjBdtjtjtjtj�}Wq�t	k
rz}z |j
tjtjfksht
|�rj�W5d}~XYqXq�q�t�|tjdd�t|�S)zU
        Return a connection object connected to the pipe given by `address`
        ��rN)rrZ
WaitNamedPiper�r�r�r�r�r�rFr��ERROR_SEM_TIMEOUT�ERROR_PIPE_BUSYrr�r�r{)r6r�hr�rrrr��s8
����r��s#CHALLENGE#s	#WELCOME#s	#FAILURE#cCs�ddl}t|t�s$td�t|����t�t�}|�	t
|�|�||d���}|�
d�}||krl|�	t�n|�	t�td��dS)Nr� Authkey must be bytes, not {0!s}�md5�zdigest received was wrong)�hmacr�rQr(�formatr1r$�urandom�MESSAGE_LENGTHrY�	CHALLENGE�new�digestrb�WELCOME�FAILUREr��
connectionr�r�messager!�responserrrr��s
�


r�cCs�ddl}t|t�s$td�t|����|�d�}|dtt��tksNt	d|��|tt�d�}|�
||d���}|�|�|�d�}|t
kr�td��dS)Nrrrzmessage = %rrzdigest sent was rejected)rr�rQr(rr1rbrRrr�r r!rYr"rr$rrrr��s
�
 

r�c@s$eZdZdd�Zdd�Zdd�ZdS)�ConnectionWrappercCs6||_||_||_dD]}t||�}t|||�qdS)N)rNrJrorbrY)�_conn�_dumps�_loadsr��setattr)r=�connr[ri�attrr]rrrrA�s
zConnectionWrapper.__init__cCs|�|�}|j�|�dSr)r*r)rY)r=r]rrrrr^s
zConnectionWrapper.sendcCs|j��}|�|�Sr)r)rbr+rrrrrks
zConnectionWrapper.recvN)rwrxryrAr^rkrrrrr(�sr(cCst�|fdddd��d�S)Nr�utf-8)�	xmlrpclibr[�encode)r]rrr�
_xml_dumpssr2cCst�|�d��\\}}|S)Nr/)r0ri�decode)rr]�methodrrr�
_xml_loadssr5c@seZdZdd�ZdS)�XmlListenercCs"ddlmat�|�}t|tt�Sr�)�
xmlrpc.client�clientr0rr�r(r2r5r\rrrr�s
zXmlListener.acceptN)rwrxryr�rrrrr6sr6cOsddlmatt||�tt�Sr�)r7r8r0r(rr2r5)r��kwdsrrr�	XmlClientsr:cCs�t|�}g}|r�t�|d|�}|tkr*q�n\t|krFtt|�krTnn
|t8}n2t|krptt|�kr~nn
|t8}ntd��|�||�||dd�}d}q|S)NFzShould not get hererr)	�listrr�r
rrRrr�r
)�handlesr�L�readyrrrr�_exhaustive_wait%s 
 
r?c
s^|dkrt}n|dkrd}nt|dd�}t|�}i�g}t��t�}�z@|D�]&}zt|d�}	Wn tk
r�|�|��<YqPXzt	�|	�dd�\}}Wn8tk
r�}zd|j}}|tkrƂW5d}~XYnX|t	jkr�|�|�|�|j<qP|�rjt��dd�d	k�rjz|�d
�\}}Wn*tk
�rP}z
|j}W5d}~XYnX|�sjt
|d��rjd|_��|�d}qPt���|�}W5|D]}|���q�|D]�}z|�d�\}}Wn6tk
�r�}z|j}|tk�r�W5d}~XYnX|t	j
k�r��|j}��|�|dk�r�t
|d��r�d|_�q�X���fdd�|D���fd
d�|D�S)��
        Wait till an object in object_list is ready/readable.

        Returns list of those objects in object_list which are ready/readable.
        Nrrg�?Tr�rN�)�rAFc3s|]}�|VqdSrr)�.0r)�waithandle_to_objrr�	<genexpr>�szwait.<locals>.<genexpr>csg|]}|�kr|�qSrr)rC�o)�
ready_objectsrr�
<listcomp>�s�wait.<locals>.<listcomp>)r�intr;�setr�r�rFr��
_ready_errorsr�ERROR_OPERATION_ABORTEDr��addr.r�r��AttributeErrorr9r�r�r
r,�getwindowsversionr?�keys�update)
�object_listr�ov_list�
ready_handlesr�r�r�r�rFrNr)rGrDrr;sh







�PollSelectorc
Cs�t���}|D]}|�|tj�q|dk	r4t��|}|�|�}|r\dd�|D�W5QR�S|dk	r4|t��}|dkr4|W5QR�Sq4W5QRXdS)r@NcSsg|]\}}|j�qSr)�fileobj)rC�key�eventsrrrrH�srIr)�
_WaitSelector�register�	selectors�
EVENT_READrr�select)rSr�selectorr]�deadliner>rrrr�s
c
CsZ|��}t�|tjtj��6}ddlm}|�|�}t||j	|j
ffW5QR�SQRXdS)Nr)�resource_sharer)rNr/�fromfdr�SOCK_STREAMr ra�	DupSocket�rebuild_connectionr?r@)r-r>rra�dsrrr�reduce_connection�s

rgcCs|��}t|��||�Sr�r�r�)rfr?r@�sockrrrre�srecCsB|jrtjnd|jrtjndB}t�|��|�}t||j|jffSr�)	r?rZFILE_GENERIC_READr@ZFILE_GENERIC_WRITEr
�	DupHandlerN�rebuild_pipe_connection)r-r��dhrrr�reduce_pipe_connection�s
�rmcCs|��}t|||�Sr)r�r{)rlr?r@r>rrrrk�srkcCs t�|���}t||j|jffSr)r
�DupFdrNrer?r@)r-�dfrrrrg�scCs|��}t|||�Srrh)ror?r@�fdrrrre�s)NN)T)T)N)N)I�__all__r�r$r,r/r�rr!�	itertoolsr�r rrr	�contextr
�ForkingPicklerrZrrrr
r�ImportErrorr-r��CONNECTION_TIMEOUT�countr'r��familiesr.rrr+r0r7r8r{r��objectrrrr�r�r�r�rrr"r#r�r�r(r2r5r6r:r?r�ZERROR_NETNAME_DELETEDrLrr\rVrZ�SelectSelectorrgrer[rmrkrrrr�<module>
s�




PT=

,,8	P
�h�/bytecode of module 'multiprocessing.connection'�u��b.��3h)��N}�(hB�2�@s�ddlZddlZddlZddlmZddlmZdZGdd�de�ZGdd	�d	e�Z	Gd
d�de�Z
Gdd
�d
e�ZGdd�de�Z
Gdd�dej�ZGdd�de
�Zejdk�rRGdd�dej�ZGdd�dej�ZGdd�dej�ZGdd�de
�ZGdd�de
�ZGdd �d e
�Ze�e�e�d!�Zejd"k�rDeed#�Zneed$�Zn8Gd%d�dej�ZGd&d�de
�Zd#e�iZeed#�Zd'd(�Ze��Zd)d*�Zd+d,�Zd-d.�ZdS)/�N�)�process)�	reduction�c@seZdZdS)�ProcessErrorN��__name__�
__module__�__qualname__rrr�-/usr/lib/python3.8/multiprocessing/context.pyrsrc@seZdZdS)�BufferTooShortNrrrrrrsrc@seZdZdS)�TimeoutErrorNrrrrrr
sr
c@seZdZdS)�AuthenticationErrorNrrrrrrsrc@sXeZdZeZeZeZeZeej	�Z	eej
�Z
eej�Zdd�Zdd�Z
dCdd�Zdd	�Zd
d�ZdDd
d�ZdEdd�ZdFdd�Zdd�ZdGdd�ZdHdd�ZdIdd�Zdd�ZdJd d!�Zd"d#�Zd$d%�Zdd&�d'd(�Zdd&�d)d*�Zd+d,�Zd-d.�ZdKd/d0�Z d1d2�Z!d3d4�Z"d5d6�Z#dLd7d8�Z$dMd:d;�Z%dNd<d=�Z&e'd>d?��Z(e(j)d@d?��Z(dAdB�Z*dS)O�BaseContextcCs"t��}|dkrtd��n|SdS)z(Returns the number of CPUs in the systemNzcannot determine number of cpus)�os�	cpu_count�NotImplementedError)�self�numrrrr)s
zBaseContext.cpu_countcCs&ddlm}||��d�}|��|S)z�Returns a manager associated with a running server process

        The managers methods such as `Lock()`, `Condition()` and `Queue()`
        can be used to create shared objects.
        r)�SyncManager��ctx)�managersr�get_context�start)rr�mrrr�Manager1szBaseContext.ManagerTcCsddlm}||�S)z1Returns two connection object connected by a piper)�Pipe)�
connectionr)r�duplexrrrrr<szBaseContext.PipecCsddlm}||��d�S)z#Returns a non-recursive lock objectr)�Lockr)�synchronizer r)rr rrrr AszBaseContext.LockcCsddlm}||��d�S)zReturns a recursive lock objectr)�RLockr)r!r"r)rr"rrrr"FszBaseContext.RLockNcCsddlm}|||��d�S)zReturns a condition objectr)�	Conditionr)r!r#r)r�lockr#rrrr#KszBaseContext.ConditionrcCsddlm}|||��d�S)zReturns a semaphore objectr)�	Semaphorer)r!r%r)r�valuer%rrrr%PszBaseContext.SemaphorecCsddlm}|||��d�S)z"Returns a bounded semaphore objectr)�BoundedSemaphorer)r!r'r)rr&r'rrrr'UszBaseContext.BoundedSemaphorecCsddlm}||��d�S)zReturns an event objectr)�Eventr)r!r(r)rr(rrrr(ZszBaseContext.EventcCs ddlm}|||||��d�S)zReturns a barrier objectr)�Barrierr)r!r)r)r�parties�action�timeoutr)rrrr)_szBaseContext.BarrierrcCsddlm}|||��d�S)�Returns a queue objectr)�Queuer)�queuesr.r)r�maxsizer.rrrr.dszBaseContext.QueuecCsddlm}|||��d�S)r-r)�
JoinableQueuer)r/r1r)rr0r1rrrr1iszBaseContext.JoinableQueuecCsddlm}||��d�S)r-r)�SimpleQueuer)r/r2r)rr2rrrr2nszBaseContext.SimpleQueuercCs"ddlm}||||||��d�S)zReturns a process pool objectr)�Pool)�context)�poolr3r)r�	processes�initializer�initargs�maxtasksperchildr3rrrr3ss
�zBaseContext.PoolcGsddlm}||f|��S)zReturns a shared objectr)�RawValue)�sharedctypesr:)r�typecode_or_type�argsr:rrrr:zszBaseContext.RawValuecCsddlm}|||�S)zReturns a shared arrayr)�RawArray)r;r>)rr<�size_or_initializerr>rrrr>szBaseContext.RawArray)r$cGs&ddlm}||f|�||��d��S)z$Returns a synchronized shared objectr)�Value�r$r)r;r@r)rr<r$r=r@rrrr@�s�zBaseContext.ValuecCs ddlm}|||||��d�S)z#Returns a synchronized shared arrayr)�ArrayrA)r;rBr)rr<r?r$rBrrrrB�s�zBaseContext.ArraycCs,tjdkr(ttdd�r(ddlm}|�dS)z�Check whether this is a fake forked process in a frozen executable.
        If so then run code specified by commandline and exit.
        �win32�frozenFr)�freeze_supportN)�sys�platform�getattr�spawnrE)rrErrrrE�szBaseContext.freeze_supportcCsddlm}|�S)zZReturn package logger -- if it does not already exist then
        it is created.
        r)�
get_logger)�utilrJ)rrJrrrrJ�szBaseContext.get_loggercCsddlm}||�S)z8Turn on logging and add a handler which prints to stderrr)�
log_to_stderr)rKrL)r�levelrLrrrrL�szBaseContext.log_to_stderrcCsddlm}dS)zVInstall support for sending connections and sockets
        between processes
        r)rN)�r)rrrrr�allow_connection_pickling�sz%BaseContext.allow_connection_picklingcCsddlm}||�dS)z�Sets the path to a python.exe or pythonw.exe binary used to run
        child processes instead of sys.executable when using the 'spawn'
        start method.  Useful for people embedding Python.
        r)�set_executableN)rIrP)r�
executablerPrrrrP�szBaseContext.set_executablecCsddlm}||�dS)zkSet list of module names to try to load in forkserver process.
        This is really just a hint.
        r)�set_forkserver_preloadN)�
forkserverrR)r�module_namesrRrrrrR�sz"BaseContext.set_forkserver_preloadcCsH|dkr|Szt|}Wn"tk
r:td|�d�YnX|��|S)Nzcannot find context for %r)�_concrete_contexts�KeyError�
ValueError�_check_available)r�methodrrrrr�szBaseContext.get_contextFcCs|jS�N)�_name�r�
allow_nonerrr�get_start_method�szBaseContext.get_start_methodcCstd��dS)Nz+cannot set start method of concrete context)rW�rrY�forcerrr�set_start_method�szBaseContext.set_start_methodcCst��d�S)z_Controls how objects will be reduced to a form that can be
        shared with other processes.r)�globals�get�rrrr�reducer�szBaseContext.reducercCs|t�d<dS)Nr)rb)rrrrrre�scCsdSrZrrdrrrrX�szBaseContext._check_available)T)N)r)r)NN)r)r)NNrN)N)N)F)F)+rr	r
rrr
r�staticmethodr�current_process�parent_process�active_childrenrrrr r"r#r%r'r(r)r.r1r2r3r:r>r@rBrErJrLrOrPrRrr^ra�propertyre�setterrXrrrrrsR









�







rc@seZdZdZedd��ZdS)�ProcessNcCst��j�|�SrZ)�_default_contextrrl�_Popen)�process_objrrrrn�szProcess._Popen�rr	r
�
_start_methodrfrnrrrrrl�srlcsFeZdZeZdd�Zd
�fdd�	Zddd�Zdd	d
�Zdd�Z�Z	S)�DefaultContextcCs||_d|_dSrZ)rm�_actual_context)rr4rrr�__init__�szDefaultContext.__init__Ncs0|dkr |jdkr|j|_|jSt��|�SdSrZ)rsrm�superr)rrY��	__class__rrr�s

zDefaultContext.get_contextFcCs<|jdk	r|std��|dkr,|r,d|_dS|�|�|_dS)Nzcontext has already been set)rs�RuntimeErrorrr_rrrra�szDefaultContext.set_start_methodcCs"|jdkr|rdS|j|_|jjSrZ)rsrmr[r\rrrr^�s

zDefaultContext.get_start_methodcCsBtjdkrdgStjdkr"ddgnddg}tjr:|�d�|SdS)NrCrI�darwin�forkrS)rFrGr�HAVE_SEND_HANDLE�append)r�methodsrrr�get_all_start_methodss

z$DefaultContext.get_all_start_methods)N)F)F)
rr	r
rlrtrrar^r~�
__classcell__rrrvrrr�s

rrrCc@seZdZdZedd��ZdS)�ForkProcessrzcCsddlm}||�S�Nr)�Popen)�
popen_forkr��ror�rrrrnszForkProcess._PopenNrprrrrr�sr�c@seZdZdZedd��ZdS)�SpawnProcessrIcCsddlm}||�Sr�)�popen_spawn_posixr�r�rrrrns�SpawnProcess._PopenNrprrrrr�sr�c@seZdZdZedd��ZdS)�ForkServerProcessrScCsddlm}||�Sr�)�popen_forkserverr�r�rrrrn szForkServerProcess._PopenNrprrrrr�sr�c@seZdZdZeZdS)�ForkContextrzN)rr	r
r[r�rlrrrrr�%sr�c@seZdZdZeZdS��SpawnContextrIN�rr	r
r[r�rlrrrrr�)sr�c@seZdZdZeZdd�ZdS)�ForkServerContextrScCstjstd��dS)Nz%forkserver start method not available)rr{rWrdrrrrX0sz"ForkServerContext._check_availableN)rr	r
r[r�rlrXrrrrr�-sr�)rzrIrSryrIrzc@seZdZdZedd��ZdS)r�rIcCsddlm}||�Sr�)Zpopen_spawn_win32r�r�rrrrnDsr�Nrprrrrr�Bsc@seZdZdZeZdSr�r�rrrrr�IscCst|t_dSrZ)rUrmrs)rYrrr�_force_start_methodVsr�cCsttdd�S)N�spawning_popen)rH�_tlsrrrr�get_spawning_popen_sr�cCs
|t_dSrZ)r�r�)�popenrrr�set_spawning_popenbsr�cCs t�dkrtdt|�j��dS)NzF%s objects should only be shared between processes through inheritance)r�rx�typer)�objrrr�assert_spawninges
��r�) rrF�	threadingrNrr�__all__�	Exceptionrrr
r�objectr�BaseProcessrlrrrGr�r�r�r�r�r�rUrmr��localr�r�r�r�rrrr�<module>sL?,���h�,bytecode of module 'multiprocessing.context'�u��b.��th)��N}�(hB/�@sdddddddddd	d
ddd
ddgZddlZddlZddlZddlZddlmZddlmZmZm	Z	m
Z
ddlmZmZm
Z
ddlmZGdd�dej�ZeZejZe��e�_dd�Zdd�ZGdd�de�ZeZeZd'dd�ZGd d!�d!e�Zd"d�Zd#d$�Z d(d&d�Z!eZ"dS))�Process�current_process�active_children�freeze_support�Lock�RLock�	Semaphore�BoundedSemaphore�	Condition�Event�Barrier�Queue�Manager�Pipe�Pool�
JoinableQueue�N�)r)rrrr)r
r	r)rc@s4eZdZddddifdd�Zdd�Zedd��ZdS)	�DummyProcessN�cCs8tj�||||||�d|_t��|_d|_t�|_	dS)NF)
�	threading�Thread�__init__�_pid�weakref�WeakKeyDictionary�	_children�
_start_calledr�_parent)�self�group�target�name�args�kwargsrr�4/usr/lib/python3.8/multiprocessing/dummy/__init__.pyr$s

zDummyProcess.__init__cCsN|jt�k	r td�|jt����d|_t|jd�r>d|jj|<tj�	|�dS)Nz,Parent is {0!r} but current_process is {1!r}Tr)
rr�RuntimeError�formatr�hasattrrrr�start�rrrr$r(+s��zDummyProcess.startcCs|jr|��sdSdSdS)Nr)r�is_aliver)rrr$�exitcode5szDummyProcess.exitcode)�__name__�
__module__�__qualname__rr(�propertyr+rrrr$r"s
rcCs2t�j}t|�D]}|��s|�|d�qt|�S�N)rr�listr*�pop)�children�prrr$rDs
cCsdSr0rrrrr$rKsc@seZdZdd�Zdd�ZdS)�	NamespacecKs|j�|�dSr0)�__dict__�update)r�kwdsrrr$rSszNamespace.__init__cCsZt|j���}g}|D]$\}}|�d�s|�d||f�q|��d|jjd�|�fS)N�_z%s=%rz%s(%s)z, )	r1r6�items�
startswith�append�sort�	__class__r,�join)rr:�tempr!�valuerrr$�__repr__Us
zNamespace.__repr__N)r,r-r.rrBrrrr$r5Rsr5TcCst�||�Sr0)�array)�typecode�sequence�lockrrr$�ArrayasrGc@s8eZdZd
dd�Zedd��Zejdd��Zdd�Zd	S)�ValueTcCs||_||_dSr0)�	_typecode�_value)rrDrArFrrr$reszValue.__init__cCs|jSr0�rJr)rrr$rAiszValue.valuecCs
||_dSr0rK)rrArrr$rAmscCsdt|�j|j|jfS)Nz<%s(%r, %r)>)�typer,rIrJr)rrr$rBqszValue.__repr__N)T)r,r-r.rr/rA�setterrBrrrr$rHds


rHcCs
tjtSr0)�sys�modulesr,rrrr$r
tscCsdSr0rrrrr$�shutdownwsrPrcCsddlm}||||�S)N�)�
ThreadPool)�poolrR)�	processes�initializer�initargsrRrrr$rzs)T)NNr)#�__all__rrNrrC�
connectionrrrrrr
r	r�queuerrrr�current_threadrrrrr�objectr5�dictr1rGrHr
rPrrrrrr$�<module>sN�


�h�*bytecode of module 'multiprocessing.dummy'�u��b.��4
h)��N}�(hB�	�@sRdddgZddlmZdgZGdd�de�Zdd�Zdd	d�ZGd
d�de�ZdS)
�Client�Listener�Pipe�)�QueueNc@sBeZdZddd�Zdd�Zdd�Zed	d
��Zdd�Zd
d�Z	dS)rN�cCst|�|_dS�N)r�_backlog_queue)�self�address�family�backlog�r
�6/usr/lib/python3.8/multiprocessing/dummy/connection.py�__init__szListener.__init__cCst|j���Sr)�
Connectionr�get�r	r
r
r�acceptszListener.acceptcCs
d|_dSr�rrr
r
r�closeszListener.closecCs|jSrrrr
r
rr
szListener.addresscCs|Srr
rr
r
r�	__enter__!szListener.__enter__cCs|��dSr�r�r	�exc_type�	exc_value�exc_tbr
r
r�__exit__$szListener.__exit__)NNr)
�__name__�
__module__�__qualname__rrr�propertyr
rrr
r
r
rrs

cCs&t�t�}}|�||f�t||�Sr)r�putr)r
�_in�_outr
r
rr(sTcCs"t�t�}}t||�t||�fSr)rr)�duplex�a�br
r
rr.sc@s6eZdZdd�Zd
dd�Zdd�Zdd	�Zd
d�ZdS)rcCs,||_||_|j|_|_|j|_|_dSr)r#r"r!�send�
send_bytesr�recv�
recv_bytes)r	r"r#r
r
rr5szConnection.__init__�c	CsN|j��dkrdS|dkrdS|jj�|jj�|�W5QRX|j��dkS)NrTr+F)r"�qsize�	not_empty�wait)r	�timeoutr
r
r�poll;s
zConnection.pollcCsdSrr
rr
r
rrDszConnection.closecCs|Srr
rr
r
rrGszConnection.__enter__cCs|��dSrrrr
r
rrJszConnection.__exit__N)r+)rrrrr0rrrr
r
r
rr3s

	r)T)	�__all__�queuer�families�objectrrrrr
r
r
r�<module>
s

�h�5bytecode of module 'multiprocessing.dummy.connection'�u��b.��� h)��N}�(hB� �@s�ddlZddlZddlZddlZddlZddlZddlZddlZddlZddl	m
Z
ddl	mZddlm
Z
ddl	mZddl	mZddl	mZd	d
ddgZd
Ze�d�ZGdd�de�Zddd�Zdd�Zdd�Zdd�Ze�ZejZejZejZejZdS)�N�)�
connection)�process)�	reduction)�resource_tracker)�spawn)�util�ensure_running�get_inherited_fds�connect_to_new_process�set_forkserver_preload��qc@sDeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)�
ForkServercCs.d|_d|_d|_d|_t��|_dg|_dS)N�__main__)�_forkserver_address�_forkserver_alive_fd�_forkserver_pid�_inherited_fds�	threading�Lock�_lock�_preload_modules��self�r�0/usr/lib/python3.8/multiprocessing/forkserver.py�__init__"s
zForkServer.__init__c	Cs|j�|��W5QRXdS�N)r�_stop_unlockedrrrr�_stop*szForkServer._stopcCsV|jdkrdSt�|j�d|_t�|jd�d|_t�|j�sLt�|j�d|_dS)Nr)	r�os�closer�waitpidr�is_abstract_socket_namespacer�unlinkrrrrr/s
zForkServer._stop_unlockedcCs&tdd�|jD��std��||_dS)z>Set list of module names to try to load in forkserver process.css|]}t|�tkVqdSr)�type�str)�.0�modrrr�	<genexpr>@sz4ForkServer.set_forkserver_preload.<locals>.<genexpr>z&module_names must be a list of stringsN)�allr�	TypeError)r�
modules_namesrrrr>sz!ForkServer.set_forkserver_preloadcCs|jS)z�Return list of fds inherited from parent process.

        This returns None if the current process was not started by fork
        server.
        )rrrrrr
DszForkServer.get_inherited_fdsc
Cs�|��t|�dtkr td��t�tj���}|�|j�t�	�\}}t�	�\}}|||j
t��g}||7}zNz&t�||�||fWW�4W5QR�St�
|�t�
|��YnXW5t�
|�t�
|�XW5QRXdS)a;Request forkserver to create a child process.

        Returns a pair of fds (status_r, data_w).  The calling process can read
        the child process's pid and (eventually) its returncode from status_r.
        The calling process should write to data_w the pickled preparation and
        process data.
        �ztoo many fdsN)r	�len�MAXFDS_TO_SEND�
ValueError�socket�AF_UNIX�connectrr!�piperr�getfdr"r�sendfds)r�fds�client�parent_r�child_w�child_r�parent_w�allfdsrrrrLs(�


z!ForkServer.connect_to_new_processcs�|j��~t��|jdk	r`t�|jtj�\}}|sBW5QR�dSt�|j�d|_	d|_d|_d}|j
r�ddh�t�d�}�fdd�|�
�D�}ni}t�tj���}t�d�}|�|�t�|�s�t�|d	�|��t��\}}ztzV|��|g}	||��||j
|f;}t��}
|
gt��}|d
|g7}t�|
||	�}Wnt�|��YnXW5t�|�X||_	||_||_W5QRXW5QRXdS)z�Make sure that a fork server is running.

        This can be called from any process.  Note that usually a child
        process will just reuse the forkserver started by its parent, so
        ensure_running() will do nothing.
        NzCfrom multiprocessing.forkserver import main; main(%d, %d, %r, **%r)�	main_path�sys_path�ignorecsi|]\}}|�kr||�qSrr)r(�x�y��desired_keysrr�
<dictcomp>�sz-ForkServer.ensure_running.<locals>.<dictcomp>r3i�z-c)rrr	rr!r#�WNOHANGr"rrrr�get_preparation_data�itemsr2r3r�arbitrary_address�bindrr$�chmod�listenr5�fileno�get_executable�_args_from_interpreter_flags�spawnv_passfds)r�pid�status�cmd�data�listener�address�alive_r�alive_w�fds_to_pass�exe�argsrrDrr	isN





�
zForkServer.ensure_runningN)
�__name__�
__module__�__qualname__rr rrr
rr	rrrrr srcCs�|rdd|kr8|dk	r8dt��_zt�|�W5t��`X|D]&}zt|�Wq<tk
r`Yq<Xq<t��t	�
�\}}t	�|d�t	�|d�dd�}tj
|tjtji}	dd�|	��D�}
t�|�i}tjtj|d	���}t�����}
|��t_|
�|tj�|
�|tj�|
�|tj��z�d
d�|
��D�}|�r"�qB�q"||k�rjt	�|d�d
k�sftd��t�||k�r\t	�|d�zt	�dt	j �\}}Wnt!k
�r�Y�q\YnX|dk�rq\|�"|d�}|dk	�rJt	�#|��r�t	�$|�}n&t	�%|��std�&||���t	�'|�}zt(||�Wnt)k
�r<YnXt	�*|�nt+�,d|��q�||k�r�|�-�d��,}t.�/|t0d�}t1|�t0k�r�t2d�&t1|����|^}}}|�*�t	�3�}|dk�rNd}zpz<|�*�|
�*�||||g}|�5|�6��t7||||
�}Wn.t8k
�r:t9j:t9�;��t9j<�=�YnXW5t	�4|�XnNzt(||�Wnt)k
�rrYnX|||<t	�*|�|D]}t	�*|��q�W5QRXWn4t>k
�r�}z|j?t?j@k�r̂W5d}~XYnX�qW5QRXW5QRXdS)zRun forkserver.rNTFcWsdSrr)�_unusedrrr�sigchld_handler�szmain.<locals>.sigchld_handlercSsi|]\}}|t�||��qSr)�signal)r(�sig�valrrrrF�s�zmain.<locals>.<dictcomp>)rNcSsg|]\}}|j�qSr)�fileobj)r(�key�eventsrrr�
<listcomp>�szmain.<locals>.<listcomp>r�zNot at EOF?i���rzChild {0:n} status is {1:n}z.forkserver: waitpid returned unexpected pid %dzToo many ({0:n}) fds to send)Ar�current_process�_inheritingr�import_main_path�
__import__�ImportErrorr�_close_stdinr!r5�set_blockingrb�SIGCHLD�SIGINT�SIG_IGNrI�
set_wakeup_fdr2r3�	selectors�DefaultSelector�getsockname�_forkserverr�register�
EVENT_READ�select�read�AssertionError�
SystemExitr#rG�ChildProcessError�pop�WIFSIGNALED�WTERMSIG�	WIFEXITED�format�WEXITSTATUS�write_signed�BrokenPipeErrorr"�warnings�warn�acceptr�recvfdsr0r/�RuntimeError�fork�_exit�extend�values�
_serve_one�	Exception�sys�
excepthook�exc_info�stderr�flush�OSError�errno�ECONNABORTED)�listener_fdrX�preloadr?r@�modname�sig_r�sig_wra�handlers�old_handlers�	pid_to_fdrV�selector�rfdsrR�stsr;�
returncode�sr8r<�code�
unused_fds�fd�errr�main�s�

��
�




��
�

��

�
r�c	Csht�d�|��D]\}}t�||�q|D]}t�|�q,|^t_tj_	t_
t�|�}t�
||�}|S)Nrj)rbrurIr!r"ryrr�_resource_tracker�_fdr�dupr�_main)	r<r8r�r�rcrdr��parent_sentinelr�rrrr�1s
�
r�cCsNd}tj}t|�|kr@t�||t|��}|s6td��||7}q
t�|�dS)Nrizunexpected EOFr)�
SIGNED_STRUCT�sizer/r!r}�EOFError�unpack)r�rU�lengthr�rrr�read_signedHs
r�cCs<t�|�}|r8t�||�}|dkr*td��||d�}q
dS)Nrzshould not get here)r��packr!�writer�)r��n�msg�nbytesrrrr�Rs
r�)NN) r�r!rvrbr2�structr�rr��rr�contextrrrr�__all__r0�Structr��objectrr�r�r�r�ryr	r
rrrrrr�<module>s>�


�h�/bytecode of module 'multiprocessing.forkserver'�u��b.��	h)��N}�(hB��@s�ddlZddlmZddlZddlZddlZddlZddlZddlm	Z	m
Z
ddlmZdgZ
ejdkr�ddlZGdd	�d	e�Zn,Gd
d	�d	e�Zdd�Zd
d�Ze	�ee�Gdd�de�ZGdd�de�ZdS)�N)�defaultdict�)�	reduction�assert_spawning)�util�
BufferWrapper�win32c@s0eZdZdZe��Zdd�Zdd�Zdd�Z	dS)	�ArenazL
        A shared memory area backed by anonymous memory (Windows).
        cCsx||_td�D]B}dt��t|j�f}tjd||d�}t��dkrHqZ|�	�qt
d��||_||_|j|jf|_
dS)N�dz	pym-%d-%s�����tagnamerzCannot find name for new mmap)�size�range�os�getpid�next�_rand�mmap�_winapi�GetLastError�close�FileExistsError�name�buffer�_state)�selfr�ir�buf�r�*/usr/lib/python3.8/multiprocessing/heap.py�__init__&s
�Arena.__init__cCst|�|jS�N)rr)rrrr �__getstate__5szArena.__getstate__cCs,|\|_|_|_tjd|j|jd�|_dS)Nrr)rrrrr)r�staterrr �__setstate__9szArena.__setstate__N)
�__name__�
__module__�__qualname__�__doc__�tempfile�_RandomNameSequencerr!r$r&rrrr r	s
r	c@s8eZdZdZejdkrdgZngZd
dd�Zdd�Zd	S)r	zJ
        A shared memory area backed by a temporary file (POSIX).
        �linuxz/dev/shmrcCsx||_||_|dkrbtjdt��|�|�d�\|_}t�|�t�	|tj
|jf�t�|j|�t�|j|j�|_
dS)Nrzpym-%d-)�prefix�dir)r�fdr+�mkstemprr�_choose_dir�unlinkr�Finalizer�	ftruncaterr)rrr0rrrr r!Ms
�
r"cCs6|jD]&}t�|�}|j|j|kr|Sqt��Sr#)�_dir_candidatesr�statvfs�f_bavail�f_frsizer�get_temp_dir)rr�d�strrr r2[s



zArena._choose_dirN)r)	r'r(r)r*�sys�platformr6r!r2rrrr r	Cs

cCs(|jdkrtd��t|jt�|j�ffS)NrzDArena is unpicklable because forking was enabled when it was created)r0�
ValueError�
rebuild_arenarr�DupFd)�arrr �reduce_arenads
rCcCst||���Sr#)r	�detach)r�dupfdrrr r@jsr@c@szeZdZdZdZdZejfdd�Ze	dd��Z
dd�Zd	d
�Zdd�Z
d
d�Zdd�Zdd�Zdd�Zdd�Zdd�ZdS)�Heap�i@cCsXt��|_t��|_||_g|_i|_i|_	i|_
tt�|_
g|_g|_d|_d|_dS�Nr)rr�_lastpid�	threading�Lock�_lock�_size�_lengths�_len_to_seq�_start_to_block�_stop_to_blockr�set�_allocated_blocks�_arenas�_pending_free_blocks�
_n_mallocs�_n_frees)rrrrr r!{s


z
Heap.__init__cCs|d}|||@S)Nrr)�n�	alignment�maskrrr �_roundup�sz
Heap._roundupcCsZ|�t|j|�tj�}|j|jkr0|jd9_t�d|�t|�}|j	�
|�|d|fS)N�z"allocating a new mmap of length %dr)r[�maxrMr�PAGESIZE�_DOUBLE_ARENA_SIZE_UNTILr�infor	rT�append)rr�length�arenarrr �
_new_arena�szHeap._new_arenacCs�|j}||jkrdS|j�|�}|r(t�|j|df=|j||f=|j�|�|j	|}|�|d|f�|s~|j	|=|j
�|�dSrH)r�_DISCARD_FREE_SPACE_LARGER_THANrS�pop�AssertionErrorrPrQrT�removerOrN)rrcrb�blocks�seqrrr �_discard_arena�s

zHeap._discard_arenac	Cs|t�|j|�}|t|j�kr&|�|�S|j|}|j|}|��}|sV|j|=|j|=|\}}}|j||f=|j||f=|Sr#)	�bisect�bisect_leftrN�lenrdrOrfrPrQ)	rrrrbrj�blockrc�start�stoprrr �_malloc�s



zHeap._mallocc	Cs�|\}}}z|j||f}Wntk
r0YnX|�|�\}}z|j||f}Wntk
rfYnX|�|�\}}|||f}||}z|j|�|�Wn.tk
r�|g|j|<t�|j|�YnX||j||f<||j||f<dSr#)	rQ�KeyError�_absorbrPrOrarl�insortrN)	rrorcrprq�
prev_block�_�
next_blockrbrrr �_add_free_block�s(

zHeap._add_free_blockcCs^|\}}}|j||f=|j||f=||}|j|}|�|�|sV|j|=|j�|�||fSr#)rPrQrOrhrN)rrorcrprqrbrjrrr rt�s


zHeap._absorbcCs4|\}}}|j|}|�||f�|s0|�|�dSr#)rSrhrk)rrorcrprqrirrr �_remove_allocated_block�s


zHeap._remove_allocated_blockcCsBz|j��}Wntk
r&Yq>YnX|�|�|�|�qdSr#)rUrf�
IndexErrorryrz�rrorrr �_free_pending_blockss

zHeap._free_pending_blockscCs~t��|jkr$td�t��|j���|j�d�s>|j�|�n<z.|j
d7_
|��|�|�|�
|�W5|j�	�XdS)Nz$My pid ({0:n}) is not last pid {1:n}Fr)rrrIr?�formatrL�acquirerUra�releaserWr}ryrzr|rrr �frees
��
z	Heap.freec
Cs�|dkrtd�|���tj|kr.td�|���t��|jkrD|��|j	��|j
d7_
|��|�t
|d�|j�}|�|�\}}}||}||kr�|�|||f�|j|�||f�|||fW5QR�SQRXdS)Nr�Size {0:n} out of range�Size {0:n} too larger)r?r~r=�maxsize�
OverflowErrorrrrIr!rLrVr}r[r]�
_alignmentrrryrS�add)rrrcrprq�	real_stoprrr �malloc(s 
zHeap.mallocN)r'r(r)r�rer_rr^r!�staticmethodr[rdrkrrryrtrzr}r�r�rrrr rFss

rFc@s"eZdZe�Zdd�Zdd�ZdS)rcCs^|dkrtd�|���tj|kr.td�|���tj�|�}||f|_t	j
|tjj|fd�dS)Nrr�r�)�args)r?r~r=r�r�r�_heapr�rrr4r�)rrrorrr r!Fs

zBufferWrapper.__init__cCs&|j\\}}}}t|j�|||�Sr#)r�
memoryviewr)rrcrprqrrrr �create_memoryviewOszBufferWrapper.create_memoryviewN)r'r(r)rFr�r!r�rrrr rBs	)rl�collectionsrrrr=r+rJ�contextrr�r�__all__r>r�objectr	rCr@�registerrFrrrrr �<module>
s&
$!P�h�)bytecode of module 'multiprocessing.heap'�u��b.����h)��N}�(hB:��@sBdddddgZddlZddlZddlZddlZddlZddlZddlZddlmZddl	m
Z
d	d
lmZd	dl
mZmZmZd	dlmZd	d
lmZd	dlmZd	dlmZzd	dlmZdZWnek
r�dZYnXdd�Ze�eje�dd�dD�Zedek	�r.dd�ZeD]Ze�ee��qGdd�de�Zdifdd�Z dd�Z!Gd d!�d!e"�Z#d"d#�Z$d$d%�Z%Gd&d'�d'e�Z&Gd(d)�d)e�Z'ej(ej)fej*ej+fd*�Z,Gd+d�de�Z-Gd,d-�d-e.�Z/Gd.d�de�Z0d/d0�Z1ifd1d2�Z2dld3d4�Z3Gd5d6�d6e�Z4Gd7d8�d8e�Z5dmd9d:�Z6Gd;d<�d<e0�Z7Gd=d>�d>e0�Z8Gd?d@�d@e8�Z9GdAdB�dBe0�Z:GdCdD�dDe0�Z;GdEdF�dFe0�Z<GdGdH�dHe0�Z=e2dIdJ�Z>GdKdL�dLe>�Z?e2dMdN�Z@dOdPie@_Ae2dQdR�ZBe2dSdT�ZCdUdUdUdPdPdV�eC_AGdWdS�dSeC�ZDGdXd�de-�ZEeE�dYejF�eE�dZejF�eE�d[ejGe:�eE�d\ejHe8�eE�d]ejIe8�eE�d^ejJe8�eE�d_ejKe8�eE�d`ejLe9�eE�daejMe;�eE�dbejNeD�eE�dcee?�eE�ddeOe@�eE�d8e5e=�eE�d:e6eB�eE�d6e4e<�eEjdPe7dde�eEjdUddf�e�r>Gdgdh�dh�ZPGdidj�dje&�ZQGdkd�de-�ZRdS)n�BaseManager�SyncManager�	BaseProxy�Token�SharedMemoryManager�N)�getpid)�
format_exc�)�
connection)�	reduction�get_spawning_popen�ProcessError)�pool)�process)�util)�get_context)�
shared_memoryTFcCstj|j|��ffS�N)�array�typecode�tobytes)�a�r�./usr/lib/python3.8/multiprocessing/managers.py�reduce_array-srcCsg|]}tti|����qSr)�type�getattr��.0�namerrr�
<listcomp>1sr )�items�keys�valuescCstt|�ffSr)�list��objrrr�rebuild_as_list3sr'c@s4eZdZdZdZdd�Zdd�Zdd�Zd	d
�ZdS)rz3
    Type to uniquely identify a shared object
    ��typeid�address�idcCs||||_|_|_dSrr()�selfr)r*r+rrr�__init__BszToken.__init__cCs|j|j|jfSrr(�r,rrr�__getstate__EszToken.__getstate__cCs|\|_|_|_dSrr(�r,�staterrr�__setstate__HszToken.__setstate__cCsd|jj|j|j|jfS)Nz %s(typeid=%r, address=%r, id=%r))�	__class__�__name__r)r*r+r.rrr�__repr__Ks�zToken.__repr__N)	r4�
__module__�__qualname__�__doc__�	__slots__r-r/r2r5rrrrr<srcCs8|�||||f�|��\}}|dkr*|St||��dS)zL
    Send a message to manager using connection `c` and return response
    �#RETURNN)�send�recv�convert_to_error)�cr+�
methodname�args�kwds�kind�resultrrr�dispatchSs
rDcCsd|dkr|S|dkrRt|t�s4td�||t|����|dkrHtd|�St|�Sntd�|��SdS)N�#ERROR)�
#TRACEBACK�#UNSERIALIZABLEz.Result {0!r} (kind '{1}') type is {2}, not strrGzUnserializable message: %s
zUnrecognized message type {!r})�
isinstance�str�	TypeError�formatr�RemoteError�
ValueError)rBrCrrrr=]s
��
r=c@seZdZdd�ZdS)rLcCsdt|jd�dS)NzM
---------------------------------------------------------------------------
rzK---------------------------------------------------------------------------)rIr@r.rrr�__str__mszRemoteError.__str__N)r4r6r7rNrrrrrLlsrLcCs2g}t|�D] }t||�}t|�r|�|�q|S)z4
    Return a list of names of methods of `obj`
    )�dirr�callable�append)r&�tempr�funcrrr�all_methodsts
rTcCsdd�t|�D�S)zP
    Return a list of names of methods of `obj` which do not start with '_'
    cSsg|]}|ddkr|�qS)r�_rrrrrr �sz"public_methods.<locals>.<listcomp>)rTr%rrr�public_methodssrVc	@s�eZdZdZdddddddd	d
g	Zdd�Zd
d�Zdd�Zdd�Zdd�Z	dd�Z
dd�Zdd�Zeee
d�Z
dd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&e_d'd(�Zd)d*�Zd+d,�Zd-d.�Zd/S)0�ServerzM
    Server class which runs in a process controlled by a manager object
    �shutdown�create�accept_connection�get_methods�
debug_info�number_of_objects�dummy�incref�decrefcCsxt|t�std�|t|����||_t�|�|_t	|\}}||dd�|_
|j
j|_ddi|_i|_
i|_t��|_dS)Nz&Authkey {0!r} is type {1!s}, not bytes�)r*�backlog�0�Nr)rH�bytesrJrKr�registryr�AuthenticationString�authkey�listener_client�listenerr*�	id_to_obj�id_to_refcount�id_to_local_proxy_obj�	threading�Lock�mutex)r,rfr*rh�
serializer�Listener�Clientrrrr-�s 
��

zServer.__init__c	Cs�t��|_|t��_zVtj|jd�}d|_|��z|j��sL|j�d�q4Wnttfk
rfYnXW5tjtjkr�t	�
d�tjt_tjt_t�
d�XdS)z(
        Run the server forever
        zresetting stdout, stderrr)�targetTr	N)rn�Event�
stop_eventr�current_process�_manager_server�sys�stdout�
__stdout__r�debug�
__stderr__�stderr�exit�Thread�accepter�daemon�start�is_set�wait�KeyboardInterrupt�
SystemExit)r,r�rrr�
serve_forever�s 




zServer.serve_forevercCsNz|j��}Wntk
r&YqYnXtj|j|fd�}d|_|��qdS)N�rtr@T)rj�accept�OSErrorrnr��handle_requestr�r�)r,r>�trrrr��s
zServer.acceptercCsLd}}}zTt�||j�t�||j�|��}|\}}}}||jksTtd|��t||�}Wntk
r~dt	�f}	Yn>Xz||f|�|�}Wntk
r�dt	�f}	Yn
Xd|f}	z|�
|	�Wnttk
�r>}
zTz|�
dt	�f�Wntk
�rYnXt�d|	�t�d|�t�d|
�W5d}
~
XYnX|�
�dS)z)
        Handle a new connection
        Nz%r unrecognizedrFr:zFailure to send message: %rz ... request was %r� ... exception was %r)r
�deliver_challengerh�answer_challenger<�public�AssertionErrorr�	Exceptionrr;r�info�close)r,r>�funcnamerC�request�ignorer@rArS�msg�errrr��s4zServer.handle_requestc
Cs�t�dt��j�|j}|j}|j}|j�	��s�zBd}}|�}|\}}}	}
z||\}}}Wn^t
k
r�}
z@z|j|\}}}Wn&t
k
r�}z|
�W5d}~XYnXW5d}
~
XYnX||kr�td|t
|�|f��t||�}z||	|
�}Wn,tk
�r"}zd|f}W5d}~XYnPX|�o4|�|d�}|�rj|�|||�\}}t||j|�}d||ff}nd|f}Wn�tk
�r�|dk�r�dt�f}nNz,|j|}|||||f|	�|
�}d|f}Wn tk
�r�dt�f}YnXYnPtk
�rt�dt��j�t�d	�Yn tk
�r<dt�f}YnXzDz||�Wn2tk
�r~}z|d
t�f�W5d}~XYnXWq$tk
�r�}z@t�dt��j�t�d|�t�d
|�|��t�d�W5d}~XYq$Xq$dS)zQ
        Handle requests from the proxies in a particular process/thread
        z$starting server thread to service %rNz+method %r of %r object is not in exposed=%rrE�#PROXYr:rFz$got EOF -- exiting thread serving %rrrGzexception in thread serving %rz ... message was %rr�r	)rr|rn�current_threadrr<r;rkrvr��KeyErrorrm�AttributeErrorrrr��getrYrr*r�fallback_mapping�EOFErrorryrr�r�)r,�connr<r;rkr?r&r��identr@rA�exposed�	gettypeid�ke�	second_ke�function�resr�r�r)�rident�rexposed�token�
fallback_funcrCrrr�serve_client�s���(��


����$�zServer.serve_clientcCs|Srr�r,r�r�r&rrr�fallback_getvalue5szServer.fallback_getvaluecCst|�Sr�rIr�rrr�fallback_str8szServer.fallback_strcCst|�Sr)�reprr�rrr�
fallback_repr;szServer.fallback_repr)rNr5�	#GETVALUEcCsdSrr�r,r>rrrr^DszServer.dummyc
Cs�|j�tg}t|j���}|��|D]<}|dkr&|�d||j|t|j|d�dd�f�q&d�|�W5QR�SQRXdS)zO
        Return some info --- useful to spot problems with refcounting
        rcz  %s:       refcount=%s
    %srN�K�
)	rpr$rlr"�sortrQrIrk�join)r,r>rCr"r�rrrr\Gs
��zServer.debug_infocCs
t|j�S)z*
        Number of shared objects
        )�lenrlr�rrrr]WszServer.number_of_objectscCsLz:zt�d�|�d�Wnddl}|��YnXW5|j��XdS)z'
        Shutdown this process
        z!manager received shutdown message�r:NrN)rv�setrr|r;�	traceback�	print_exc)r,r>r�rrrrX^s
zServer.shutdownc	Os�t|�dkr|^}}}}n�|s(td��n�d|krDtdt|�d��|�d�}t|�dkr~|^}}}ddl}|jd	tdd
�nFd|kr�tdt|�d��|�d�}|^}}ddl}|jdtdd
�t|�}|j��|j|\}}}}	|dk�r|�st|�dk�rt	d
��|d}
n
|||�}
|dk�r2t
|
�}|dk	�rlt|t��s\td�
|t|����t|�t|�}dt|
�}t�d||�|
t|�|f|j|<||jk�r�d|j|<W5QRX|�||�|t|�fS)z>
        Create a new shared object and return its id
        �z8descriptor 'create' of 'Server' object needs an argumentr)�7create expected at least 2 positional arguments, got %dr	�rNz2Passing 'typeid' as keyword argument is deprecated)�
stacklevelr>z-Passing 'c' as keyword argument is deprecatedz4Without callable, must have one non-keyword argumentz,Method_to_typeid {0!r}: type {1!s}, not dictz%xz&%r callable returned object with id %r)r�rJ�pop�warnings�warn�DeprecationWarning�tuplerprfrMrVrH�dictrKrr$r+rr|r�rkrlr_)r@rAr,r>r)r�rPr��method_to_typeid�	proxytyper&r�rrrrYksp

�

�
�
��

�



��z
Server.createz$($self, c, typeid, /, *args, **kwds)cCst|j|jd�S)zL
        Return the methods of the shared object indicated by token
        r	)r�rkr+)r,r>r�rrrr[�szServer.get_methodscCs"|t��_|�d�|�|�dS)z=
        Spawn a new thread to serve this connection
        r�N)rnr�rr;r�)r,r>rrrrrZ�s

zServer.accept_connectioncCs�|j��z|j|d7<Wnhtk
r�}zJ||jkrrd|j|<|j||j|<|j|\}}}t�d|�n|�W5d}~XYnXW5QRXdS)Nr	z&Server re-enabled tracking & INCREF %r)rprlr�rmrkrr|)r,r>r�r�r&r�r�rrrr_�s

�z
Server.increfc	Cs�||jkr$||jkr$t�d|�dS|j�Z|j|dkrXtd�||j||j|���|j|d8<|j|dkr�|j|=W5QRX||jkr�d|j|<t�d|�|j�|j|=W5QRXdS)NzServer DECREF skipping %rrz+Id {0!s} ({1!r}) has refcount {2:n}, not 1+r	)NrNzdisposing of obj with id %r)rlrmrr|rpr�rKrk)r,r>r�rrrr`�s,
���

z
Server.decrefN)r4r6r7r8r�r-r�r�r�r�r�r�r�r�r^r\r]rXrY�__text_signature__r[rZr_r`rrrrrW�s<�
"Q�
=rWc@seZdZdgZdZdZdZdS)�State�valuerr	r�N)r4r6r7r9�INITIAL�STARTED�SHUTDOWNrrrrr��sr�)�pickle�	xmlrpclibc@s�eZdZdZiZeZd"dd�Zdd�Zdd	�Z	d#dd�Z
ed$d
d��Zdd�Z
d%dd�Zdd�Zdd�Zdd�Zdd�Zedd��Zedd��Zed&d d!��ZdS)'rz!
    Base class for managers
    Nr�cCs\|dkrt��j}||_t�|�|_t�|_tj|j_	||_
t|\|_|_
|pTt�|_dSr)rrwrh�_addressrg�_authkeyr��_stater�r��_serializerri�	_Listener�_Clientr�_ctx)r,r*rhrq�ctxrrrr-s

zBaseManager.__init__cCsf|jjtjkrP|jjtjkr&td��n*|jjtjkr>td��ntd�|jj���t|j	|j
|j|j�S)zX
        Return server object with serve_forever() method and address attribute
        �Already started server�Manager has shut down�Unknown state {!r})
r�r�r�r�r�r
r�rKrW�	_registryr�r�r�r.rrr�
get_servers

�
�zBaseManager.get_servercCs8t|j\}}||j|jd�}t|dd�tj|j_dS)z>
        Connect manager object to the server process
        �rhNr^)	rir�r�r�rDr�r�r�r�)r,rrrsr�rrr�connectszBaseManager.connectrc	Cs4|jjtjkrP|jjtjkr&td��n*|jjtjkr>td��ntd�|jj���|dk	rht|�sht	d��t
jdd�\}}|jj
t|�j|j|j|j|j|||fd�|_d	�d
d�|jjD��}t|�jd||j_|j��|��|��|_|��tj|j_tj|t|�j|j|j|j|j|jfd
d�|_ dS)z@
        Spawn a server process for this manager object
        r�r�r�Nzinitializer must be a callableF)�duplexr��:css|]}t|�VqdSrr�)r�irrr�	<genexpr>Asz$BaseManager.start.<locals>.<genexpr>�-r�r@�exitpriority)!r�r�r�r�r�r
r�rKrPrJr
�Piper��Processr�_run_serverr�r�r�r��_processr��	_identityr4rr�r�r<r�Finalize�_finalize_managerr�rX)r,�initializer�initargs�reader�writerr�rrrr�(sH

���


��zBaseManager.startc	Cs^t�tjtj�|dk	r ||�|�||||�}|�|j�|��t�d|j�|�	�dS)z@
        Create a server, report its address and run it
        Nzmanager serving at %r)
�signal�SIGINT�SIG_IGN�_Serverr;r*r�rr�r�)	�clsrfr*rhrqr�r�r��serverrrrr�SszBaseManager._run_servercOsd|jjtjkstd��|j|j|jd�}zt	|dd|f||�\}}W5|��Xt
||j|�|fS)zP
        Create a new shared object; return the token and exposed tuple
        zserver not yet startedr�NrY)r�r�r�r�r�r�r�r�r�rDr)r,r)r@rAr�r+r�rrr�_createjs
zBaseManager._createcCs*|jdk	r&|j�|�|j��s&d|_dS)zC
        Join the manager process (if it has been spawned)
        N)r�r��is_alive�r,�timeoutrrrr�vs

zBaseManager.joincCs2|j|j|jd�}zt|dd�W�S|��XdS)zS
        Return some info about the servers shared objects and connections
        r�Nr\�r�r�r�r�rD�r,r�rrr�_debug_infoszBaseManager._debug_infocCs2|j|j|jd�}zt|dd�W�S|��XdS)z5
        Return the number of shared objects
        r�Nr]r�rrrr�_number_of_objects�szBaseManager._number_of_objectscCsj|jjtjkr|��|jjtjkrf|jjtjkr<td��n*|jjtjkrTtd��ntd�|jj���|S)NzUnable to start serverr�r�)	r�r�r�r�r�r�r
r�rKr.rrr�	__enter__�s

�zBaseManager.__enter__cCs|��dSr)rX�r,�exc_type�exc_val�exc_tbrrr�__exit__�szBaseManager.__exit__cCs�|��r�t�d�z,|||d�}zt|dd�W5|��XWntk
rRYnX|jdd�|��r�t�d�t|d�r�t�d	�|��|jd
d�|��r�t�d�t	j
|_ztj
|=Wntk
r�YnXdS)zQ
        Shutdown the manager process; will be registered as a finalizer
        z#sending shutdown message to managerr�NrXg�?)r�zmanager still alive�	terminatez'trying to `terminate()` manager processg�������?z#manager still alive after terminate)r�rr�r�rDr�r��hasattrr	r�r�r�r�_address_to_localr�)rr*rhr1r�r�rrrr��s.




zBaseManager._finalize_managercCs|jSr)r�r.rrrr*�szBaseManager.addressTc
s�d|jkr|j��|_�dkr"t�|p0t�dd�}|p@t�dd�}|r�t|���D]8\}}t|�tksrt	d|��t|�tksRt	d|��qR|||�f|j�<|r‡�fdd�}	�|	_
t|�|	�dS)z9
        Register a typeid with the manager type
        r�N�	_exposed_�_method_to_typeid_z%r is not a stringcs`t�d��|j�f|�|�\}}�||j||j|d�}|j|j|jd�}t|dd|jf�|S)Nz)requesting creation of a shared %r object��managerrhr�r�r`)	rr|r�r�r�r�r*rDr+)r,r@rAr��exp�proxyr��r�r)rrrR�s�z"BaseManager.register.<locals>.temp)�__dict__r��copy�	AutoProxyrr$r!rrIr�r4�setattr)
r�r)rPr�r�r��
create_method�keyr�rRrrr�register�s*

��

zBaseManager.register)NNr�N)Nr)Nr)N)NNNNT)r4r6r7r8r�rWr�r-r�r�r��classmethodr�r�r�rrrr�staticmethodr��propertyr*rrrrrr�s8�
	
+�
	




�c@seZdZdd�Zdd�ZdS)�ProcessLocalSetcCst�|dd��dS)NcSs|��Sr)�clearr%rrr�<lambda>��z*ProcessLocalSet.__init__.<locals>.<lambda>)r�register_after_forkr.rrrr-�szProcessLocalSet.__init__cCst|�dfSrd)rr.rrr�
__reduce__�szProcessLocalSet.__reduce__N)r4r6r7r-r"rrrrr�src@s�eZdZdZiZe��Zddd�Zdd�Z	d	ifd
d�Z
dd
�Zdd�Ze
dd��Zdd�Zdd�Zdd�Zdd�Zdd�ZdS)rz.
    A base for proxies of shared objects
    NTFc		Cs�tj�8tj�|jd�}|dkr:t��t�f}|tj|j<W5QRX|d|_|d|_	||_
|j
j|_||_
||_t|d|_||_|dk	r�t�|�|_n"|j
dk	r�|j
j|_nt��j|_|r�|��t�|tj�dS)Nrr	)r�_mutexrr�r*r�ForkAwareLocalr�_tls�_idset�_tokenr+�_id�_managerr�rir��_owned_by_managerrrgr�rwrh�_increfr!�_after_fork)	r,r�rqrrhr�r_�
manager_owned�	tls_idsetrrrr-s*



zBaseProxy.__init__cCsdt�d�t��j}t��jdkr4|dt��j7}|j|jj	|j
d�}t|dd|f�||j_
dS)Nzmaking connection to manager�
MainThread�|r�rZ)rr|rrwrrnr�r�r'r*r�rDr%r
)r,rr�rrr�_connect-s

zBaseProxy._connectrcCs�z|jj}Wn6tk
rBt�dt��j�|��|jj}YnX|�	|j
|||f�|��\}}|dkrp|S|dkr�|\}}|jj
|jd}	|jj|_|	||j|j|j|d�}
|j|j|jd�}t|dd|jf�|
St||��dS)	zV
        Try to call a method of the referent and return a copy of the result
        z#thread %r does not own a connectionr:r����rr�Nr`)r%r
r�rr|rnr�rr1r;r(r<r)r�r)r'r*r�r�r�rDr+r=)r,r?r@rAr�rBrCr�r�r�rrrr�_callmethod6s6�
�zBaseProxy._callmethodcCs
|�d�S)z9
        Get a copy of the value of the referent
        r��r3r.rrr�	_getvalueTszBaseProxy._getvaluec	Cs�|jrt�d|jj�dS|j|jj|jd�}t|dd|j	f�t�d|jj�|j
�|j	�|joj|jj
}tj|tj|j|j||j|j
|jfdd�|_dS)Nz%owned_by_manager skipped INCREF of %rr�r_z	INCREF %r�
r�)r*rr|r'r+r�r*r�rDr(r&�addr)r�r�r�_decrefr%�_close)r,r�r1rrrr+Zs$
��zBaseProxy._increfc
Cs�|�|j�|dks |jtjkr�z2t�d|j�||j|d�}t|dd|jf�Wq�t	k
r�}zt�d|�W5d}~XYq�Xnt�d|j�|s�t
|d�r�t�dt��j
�|j��|`dS)Nz	DECREF %rr�r`z... decref failed %sz%DECREF %r -- manager already shutdownr
z-thread %r has no more proxies so closing conn)�discardr+r�r�r�rr|r*rDr�r
rnr�rr
r�)r�rhr1�tls�idsetr�r�r�rrrr8ns �
zBaseProxy._decrefc
CsHd|_z|��Wn0tk
rB}zt�d|�W5d}~XYnXdS)Nzincref failed: %s)r)r+r�rr�)r,r�rrrr,�s
zBaseProxy._after_forkcCs^i}t�dk	r|j|d<t|dd�rB|j|d<tt|j|j|ffStt|�|j|j|ffSdS)Nrh�_isautoFr�)	rr�rr�RebuildProxyrr'r�r�r,rArrrr"�s


��zBaseProxy.__reduce__cCs|��Sr)r5)r,�memorrr�__deepcopy__�szBaseProxy.__deepcopy__cCsdt|�j|jjt|�fS)Nz<%s object, typeid %r at %#x>)rr4r'r)r+r.rrrr5�s�zBaseProxy.__repr__cCs:z|�d�WStk
r4t|�dd�dYSXdS)zV
        Return representation of the referent (or a fall-back if that fails)
        r5Nr2z; '__str__()' failed>)r3r�r�r.rrrrN�szBaseProxy.__str__)NNNTF)r4r6r7r8rr�ForkAwareThreadLockr#r-r1r3r5r+rr8r,r"rAr5rNrrrrr�s(�
)	

cCs�tt��dd�}|rT|j|jkrTt�d|�d|d<|j|jkrT|j|j|j|j<|�	dd�optt��dd�}|||fd|i|��S)	z5
    Function used for unpickling proxy objects.
    rxNz*Rebuild a proxy owned by manager, token=%rTr-r_�_inheritingF)
rrrwr*rr|r+rmrkr�)rSr�rqrAr�r_rrrr>�s
�
�r>cCspt|�}z|||fWStk
r*YnXi}|D]}td||f|�q4t|tf|�}||_||||f<|S)zB
    Return a proxy type whose methods are given by `exposed`
    zOdef %s(self, /, *args, **kwds):
        return self._callmethod(%r, args, kwds))r�r��execrrr)rr��_cache�dic�meth�	ProxyTyperrr�
MakeProxyType�s ��rIc
Cs�t|d}|dkrB||j|d�}zt|dd|f�}W5|��X|dkrX|dk	rX|j}|dkrjt��j}td|j	|�}||||||d�}	d|	_
|	S)z*
    Return an auto-proxy for `token`
    r	Nr�r[z
AutoProxy[%s])rrhr_T)rir*r�rDr�rrwrhrIr)r=)
r�rqrrhr�r_r�r�rHrrrrr�s 


�rc@seZdZdd�Zdd�ZdS)�	NamespacecKs|j�|�dSr)r�updater?rrrr-�szNamespace.__init__cCsZt|j���}g}|D]$\}}|�d�s|�d||f�q|��d|jjd�|�fS)NrUz%s=%rz%s(%s)z, )	r$rr!�
startswithrQr�r3r4r�)r,r!rRrr�rrrr5�s
zNamespace.__repr__N)r4r6r7r-r5rrrrrJ�srJc@s8eZdZddd�Zdd�Zdd�Zdd	�Zeee�Zd
S)�ValueTcCs||_||_dSr)�	_typecode�_value)r,rr��lockrrrr-szValue.__init__cCs|jSr�rOr.rrrr�sz	Value.getcCs
||_dSrrQ�r,r�rrrr�
sz	Value.setcCsdt|�j|j|jfS)Nz
%s(%r, %r))rr4rNrOr.rrrr5szValue.__repr__N)T)	r4r6r7r-r�r�r5rr�rrrrrMs

rMcCst�||�Sr)r)r�sequencerPrrr�ArraysrTc@s8eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�ZdS)
�
IteratorProxy)�__next__r;�throwr�cCs|Srrr.rrr�__iter__szIteratorProxy.__iter__cGs|�d|�S)NrVr4�r,r@rrrrVszIteratorProxy.__next__cGs|�d|�S)Nr;r4rYrrrr;szIteratorProxy.sendcGs|�d|�S)NrWr4rYrrrrWszIteratorProxy.throwcGs|�d|�S)Nr�r4rYrrrr�!szIteratorProxy.closeN)	r4r6r7rrXrVr;rWr�rrrrrUsrUc@s2eZdZdZddd�Zdd�Zdd	�Zd
d�ZdS)
�
AcquirerProxy)�acquire�releaseTNcCs"|dkr|fn||f}|�d|�S�Nr[r4)r,�blockingr�r@rrrr['szAcquirerProxy.acquirecCs
|�d�S�Nr\r4r.rrrr\*szAcquirerProxy.releasecCs
|�d�Sr]r4r.rrrr,szAcquirerProxy.__enter__cCs
|�d�Sr_r4rrrrr.szAcquirerProxy.__exit__)TN)r4r6r7rr[r\rrrrrrrZ%s

rZc@s6eZdZdZddd�Zd
dd�Zdd	�Zdd
d�ZdS)�ConditionProxy)r[r\r��notify�
notify_allNcCs|�d|f�S�Nr�r4r�rrrr�4szConditionProxy.waitr	cCs|�d|f�S)Nrar4)r,�nrrrra6szConditionProxy.notifycCs
|�d�S)Nrbr4r.rrrrb8szConditionProxy.notify_allcCsd|�}|r|S|dk	r$t��|}nd}d}|s`|dk	rN|t��}|dkrNq`|�|�|�}q,|S)Nr)�time�	monotonicr�)r,�	predicater�rC�endtime�waittimerrr�wait_for:s
zConditionProxy.wait_for)N)r	)N)r4r6r7rr�rarbrjrrrrr`2s


r`c@s2eZdZdZdd�Zdd�Zdd�Zdd	d
�ZdS)�
EventProxy)r�r�rr�cCs
|�d�S)Nr�r4r.rrrr�OszEventProxy.is_setcCs
|�d�S�Nr�r4r.rrrr�QszEventProxy.setcCs
|�d�S)Nrr4r.rrrrSszEventProxy.clearNcCs|�d|f�Srcr4r�rrrr�UszEventProxy.wait)N)r4r6r7rr�r�rr�rrrrrkMs
rkc@sNeZdZdZddd�Zdd�Zdd�Zed	d
��Zedd��Z	ed
d��Z
dS)�BarrierProxy)�__getattribute__r��abort�resetNcCs|�d|f�Srcr4r�rrrr�[szBarrierProxy.waitcCs
|�d�S)Nror4r.rrrro]szBarrierProxy.abortcCs
|�d�S)Nrpr4r.rrrrp_szBarrierProxy.resetcCs|�dd�S)Nrn)�partiesr4r.rrrrqaszBarrierProxy.partiescCs|�dd�S)Nrn)�	n_waitingr4r.rrrrrdszBarrierProxy.n_waitingcCs|�dd�S)Nrn)�brokenr4r.rrrrsgszBarrierProxy.broken)N)r4r6r7rr�rorprrqrrrsrrrrrmYs


rmc@s(eZdZdZdd�Zdd�Zdd�ZdS)	�NamespaceProxy)rn�__setattr__�__delattr__cCs0|ddkrt�||�St�|d�}|d|f�S)NrrUr3rn)�objectrn�r,r�
callmethodrrr�__getattr__nszNamespaceProxy.__getattr__cCs4|ddkrt�|||�St�|d�}|d||f�S)NrrUr3ru)rwrurn)r,rr�ryrrrrusszNamespaceProxy.__setattr__cCs0|ddkrt�||�St�|d�}|d|f�S)NrrUr3rv)rwrvrnrxrrrrvxszNamespaceProxy.__delattr__N)r4r6r7rrzrurvrrrrrtlsrtc@s*eZdZdZdd�Zdd�Zeee�ZdS)�
ValueProxy)r�r�cCs
|�d�S)Nr�r4r.rrrr��szValueProxy.getcCs|�d|f�Srlr4rRrrrr��szValueProxy.setN)r4r6r7rr�r�rr�rrrrr{sr{�
BaseListProxy)�__add__�__contains__�__delitem__�__getitem__�__len__�__mul__�__reversed__�__rmul__�__setitem__rQ�count�extend�index�insertr��remove�reverser��__imul__c@seZdZdd�Zdd�ZdS)�	ListProxycCs|�d|f�|S)Nr�r4rRrrr�__iadd__�szListProxy.__iadd__cCs|�d|f�|S)Nr�r4rRrrrr��szListProxy.__imul__N)r4r6r7r�r�rrrrr��sr��	DictProxy)r~rr�rXr�r�rrr�r!r"r��popitem�
setdefaultrKr#rX�Iterator�
ArrayProxy)r�r�r��	PoolProxy)�apply�apply_asyncr��imap�imap_unorderedr��map�	map_async�starmap�
starmap_asyncr	�AsyncResult)r�r�r�r�r�c@seZdZdd�Zdd�ZdS)r�cCs|Srrr.rrrr�szPoolProxy.__enter__cCs|��dSr)r	rrrrr�szPoolProxy.__exit__N)r4r6r7rrrrrrr��sc@seZdZdZdS)ra(
    Subclass of `BaseManager` which supports a number of shared object types.

    The types registered are those intended for the synchronization
    of threads, plus `dict`, `list` and `Namespace`.

    The `multiprocessing.Manager()` function creates started instances of
    this class.
    N)r4r6r7r8rrrrr�s�Queue�
JoinableQueueruro�RLock�	Semaphore�BoundedSemaphore�	Condition�Barrier�Poolr$r�)r�r)rc@sLeZdZdZgfdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dS)�_SharedMemoryTrackerz+Manages one or more shared memory segments.cCs||_||_dSr��shared_memory_context_name�
segment_names)r,rr�rrrr-�sz_SharedMemoryTracker.__init__cCs(t�d|�dt����|j�|�dS)z6Adds the supplied shared memory block name to tracker.zRegister segment � in pid N)rr|rr�rQ�r,�segment_namerrr�register_segment�sz%_SharedMemoryTracker.register_segmentcCsBt�d|�dt����|j�|�t�|�}|��|��dS)z�Calls unlink() on the shared memory block with the supplied name
            and removes it from the list of blocks being tracked.zDestroy segment r�N)	rr|rr�r�r�SharedMemoryr��unlink)r,r��segmentrrr�destroy_segment�s

z$_SharedMemoryTracker.destroy_segmentcCs"|jdd�D]}|�|�qdS)z<Calls destroy_segment() on all tracked shared memory blocks.N)r�r�r�rrrr��sz_SharedMemoryTracker.unlinkcCs(t�d|jj�dt����|��dS)NzCall z.__del__ in )rr|r3r4rr�r.rrr�__del__�sz_SharedMemoryTracker.__del__cCs|j|jfSrr�r.rrrr/�sz!_SharedMemoryTracker.__getstate__cCs|j|�dSr)r-r0rrrr2sz!_SharedMemoryTracker.__setstate__N)r4r6r7r8r-r�r�r�r�r/r2rrrrr��s	r�c@sReZdZejdddgZdd�Zdd�Zde_d	d
�Zdd�Z	d
d�Z
dd�ZdS)�SharedMemoryServer�
track_segment�release_segment�
list_segmentscOsZtj|f|�|�|j}t|t�r,t�|�}td|�dt����|_	t
�dt����dS)NZshm_rUz"SharedMemoryServer started by pid )rWr-r*rHre�os�fsdecoder�r�shared_memory_contextrr|)r,r@�kwargsr*rrrr-
s

�zSharedMemoryServer.__init__cOstt|�dkr|d}n4d|kr(|d}n"|s6td��ntdt|�d��ttj|dd�rhtj|d	<tj||�S)
z�Create a new distributed-shared object (not backed by a shared
            memory block) and return its id to be used in a Proxy Object.r�r�r)zDdescriptor 'create' of 'SharedMemoryServer' object needs an argumentr�r	r2Z_shared_memory_proxyr�)r�rJr
r,rfr�rWrY)r@r��typeodr)rrrrYs



�
zSharedMemoryServer.createz&($self, c, typeid, /, *args, **kwargs)cCs|j��t�||�S)zACall unlink() on all tracked shared memory, terminate the Server.)r�r�rWrXr�rrrrX)s
zSharedMemoryServer.shutdowncCs|j�|�dS)z?Adds the supplied shared memory block name to Server's tracker.N)r�r��r,r>r�rrrr�.sz SharedMemoryServer.track_segmentcCs|j�|�dS)z�Calls unlink() on the shared memory block with the supplied name
            and removes it from the tracker instance inside the Server.N)r�r�r�rrrr�2sz"SharedMemoryServer.release_segmentcCs|jjS)zbReturns a list of names of shared memory blocks that the Server
            is currently tracking.)r�r�r�rrrr�7sz SharedMemoryServer.list_segmentsN)r4r6r7rWr�r-rYr�rXr�r�r�rrrrr�s�
r�c@s<eZdZdZeZdd�Zdd�Zdd�Zdd	�Z	d
d�Z
dS)
ra�Like SyncManager but uses SharedMemoryServer instead of Server.

        It provides methods for creating and returning SharedMemory instances
        and for creating a list-like object (ShareableList) backed by shared
        memory.  It also provides methods that create and return Proxy Objects
        that support synchronization across processes (i.e. multi-process-safe
        locks and semaphores).
        cOsNtjdkrddlm}|��tj|f|�|�t�|j	j
�dt����dS)N�posixr	)�resource_trackerz created by pid )r�r�r��ensure_runningrr-rr|r3r4r)r,r@r�r�rrrr-Is

zSharedMemoryManager.__init__cCst�|jj�dt����dS)Nz.__del__ by pid )rr|r3r4rr.rrrr�UszSharedMemoryManager.__del__cCsh|jjtjkrP|jjtjkr&td��n*|jjtjkr>td��ntd�|jj���|�|j	|j
|j|j�S)z@Better than monkeypatching for now; merge into Server ultimatelyz"Already started SharedMemoryServerz!SharedMemoryManager has shut downr�)
r�r�r�r�r�r
r�rKr�r�r�r�r�r.rrrr�Ys

��zSharedMemoryManager.get_servercCsx|j|j|jd��\}tjdd|d�}zt|dd|jf�Wn.tk
rh}z|��|�W5d}~XYnXW5QRX|S)zoReturns a new SharedMemory instance with the specified size in
            bytes, to be tracked by the manager.r�NT)rY�sizer�)	r�r�r�rr�rDr�
BaseExceptionr�)r,r�r��smsr�rrrr�fs z SharedMemoryManager.SharedMemorycCsv|j|j|jd��Z}t�|�}zt|dd|jjf�Wn0tk
rf}z|j�	�|�W5d}~XYnXW5QRX|S)z�Returns a new ShareableList instance populated with the values
            from the input sequence, to be tracked by the manager.r�Nr�)
r�r�r�r�
ShareableListrD�shmrr�r�)r,rSr��slr�rrrr�rs

 z!SharedMemoryManager.ShareableListN)r4r6r7r8r�r�r-r�r�r�r�rrrrr=s	
)NNNT)T)S�__all__ryrnr�r�queuerer�rr�rr�r
�contextrrr
rrrrr�	HAS_SHMEM�ImportErrorrr�
view_typesr$r'�	view_typerwrrDr=r�rLrTrVrWr�rrrs�XmlListener�	XmlClientrirr�rrr>rIrrJrMrTrUrZr`rkrmrtr{r|r�r�r
r��
BasePoolProxyr�rr�ruror�r�r�r�r�r�r�r�r�rrrrr�<module>s��


c

�	w
4�


	
	
�

�

�%8�h�-bytecode of module 'multiprocessing.managers'�u��b.���ah)��N}�(hB�a�@sdddgZddlZddlZddlZddlZddlZddlZddlZddlZddlm	Z	ddl
mZddl
mZm
Z
ddlmZd	Zd
ZdZdZe��Zd
d�Zdd�ZGdd�de�ZGdd�d�Zdd�ZGdd�de�Zd+dd�Zdd�ZGdd �d e�Z Gd!d�de!�Z"Gd"d#�d#e!�Z#e#Z$Gd$d%�d%e#�Z%Gd&d'�d'e!�Z&Gd(d)�d)e&�Z'Gd*d�de"�Z(dS),�Pool�
ThreadPool�N)�Empty�)�util)�get_context�TimeoutError)�wait�INIT�RUN�CLOSE�	TERMINATEcCstt|��S�N)�list�map��args�r�*/usr/lib/python3.8/multiprocessing/pool.py�mapstar/srcCstt�|d|d��S)Nrr)r�	itertools�starmaprrrr�starmapstar2src@seZdZdd�Zdd�ZdS)�RemoteTracebackcCs
||_dSr��tb)�selfrrrr�__init__:szRemoteTraceback.__init__cCs|jSrr�rrrr�__str__<szRemoteTraceback.__str__N)�__name__�
__module__�__qualname__rrrrrrr9src@seZdZdd�Zdd�ZdS)�ExceptionWithTracebackcCs0t�t|�||�}d�|�}||_d||_dS)N�z

"""
%s""")�	traceback�format_exception�type�join�excr)rr)rrrrr@s
zExceptionWithTraceback.__init__cCst|j|jffSr)�rebuild_excr)rrrrr�
__reduce__Esz!ExceptionWithTraceback.__reduce__N)r r!r"rr+rrrrr#?sr#cCst|�|_|Sr)r�	__cause__)r)rrrrr*Hs
r*cs0eZdZdZ�fdd�Zdd�Zdd�Z�ZS)�MaybeEncodingErrorzVWraps possible unpickleable errors, so they can be
    safely sent through the socket.cs.t|�|_t|�|_tt|��|j|j�dSr)�reprr)�value�superr-r)rr)r/��	__class__rrrTs

zMaybeEncodingError.__init__cCsd|j|jfS)Nz(Error sending result: '%s'. Reason: '%s')r/r)rrrrrYs�zMaybeEncodingError.__str__cCsd|jj|fS)Nz<%s: %s>)r2r rrrr�__repr__]szMaybeEncodingError.__repr__)r r!r"�__doc__rrr3�
__classcell__rrr1rr-Psr-rFc
Cs�|dk	r(t|t�r|dks(td�|���|j}|j}t|d�rR|j��|j	��|dk	rb||�d}|dks~|�r�||k�r�z
|�}	Wn(t
tfk
r�t�
d�Y�q�YnX|	dkr�t�
d��q�|	\}
}}}
}zd||
|�f}WnHtk
�r0}z(|�r|tk	�rt||j�}d|f}W5d}~XYnXz||
||f�WnRtk
�r�}z2t||d�}t�
d	|�||
|d|ff�W5d}~XYnXd}	}
}}}
}|d7}qft�
d
|�dS)NrzMaxtasks {!r} is not valid�_writerrz)worker got EOFError or OSError -- exitingzworker got sentinel -- exitingTFz0Possible encoding error while sending result: %szworker exiting after %d tasks)�
isinstance�int�AssertionError�format�put�get�hasattrr6�close�_reader�EOFError�OSErrorr�debug�	Exception�_helper_reraises_exceptionr#�
__traceback__r-)�inqueue�outqueue�initializer�initargs�maxtasks�wrap_exceptionr;r<�	completed�task�job�i�funcr�kwds�result�e�wrappedrrr�workerasN�





�$
rUcCs|�dS)z@Pickle-able helper function for use by _guarded_task_generation.Nr)�exrrrrD�srDcs2eZdZdZdd��fdd�
Z�fdd�Z�ZS)�
_PoolCachez�
    Class that implements a cache for the Pool class that will notify
    the pool management threads every time the cache is emptied. The
    notification is done by the use of a queue that is provided when
    instantiating the cache.
    N��notifiercs||_t�j||�dSr)rYr0r)rrYrrQr1rrr�sz_PoolCache.__init__cs t��|�|s|j�d�dSr)r0�__delitem__rYr;)r�itemr1rrrZ�sz_PoolCache.__delitem__)r r!r"r4rrZr5rrr1rrW�srWc@s�eZdZdZdZedd��ZdLdd�Zej	e
fd	d
�Zdd�Zd
d�Z
edd��Zedd��Zdd�Zedd��Zedd��Zdd�Zdd�Zdifdd�ZdMdd �ZdNd!d"�ZdOd#d$�Zd%d&�ZdPd(d)�ZdQd*d+�Zdiddfd,d-�ZdRd.d/�ZdSd0d1�ZedTd2d3��Ze d4d5��Z!ed6d7��Z"ed8d9��Z#ed:d;��Z$d<d=�Z%d>d?�Z&d@dA�Z'dBdC�Z(edDdE��Z)e dFdG��Z*dHdI�Z+dJdK�Z,dS)UrzS
    Class which supports an async version of applying functions to arguments.
    TcOs|j||�Sr��Process)�ctxrrQrrrr]�szPool.ProcessNrcCsg|_t|_|pt�|_|��t��|_|j��|_	t
|j	d�|_||_||_
||_|dkrjt��phd}|dkrztd��|dk	r�t|�s�td��||_z|��WnHtk
r�|jD]}|jdkr�|��q�|jD]}|��q؂YnX|��}tjtj|j|j|j|j|j|j|j |j!|j
|j|j|j"||j	fd�|_#d|j#_$t%|j#_|j#�&�tjtj'|j|j(|j!|j|jfd�|_)d|j)_$t%|j)_|j)�&�tjtj*|j!|j+|jfd�|_,d|j,_$t%|j,_|j,�&�t-j.||j/|j|j |j!|j|j	|j#|j)|j,|jf	dd�|_0t%|_dS)	NrXrz&Number of processes must be at least 1zinitializer must be a callable��targetrT�)r�exitpriority)1�_poolr
�_stater�_ctx�
_setup_queues�queue�SimpleQueue�
_taskqueue�_change_notifierrW�_cache�_maxtasksperchild�_initializer�	_initargs�os�	cpu_count�
ValueError�callable�	TypeError�
_processes�_repopulate_poolrC�exitcode�	terminater(�_get_sentinels�	threading�Threadr�_handle_workersr]�_inqueue�	_outqueue�_wrap_exception�_worker_handler�daemonr�start�
_handle_tasks�
_quick_put�
_task_handler�_handle_results�
_quick_get�_result_handlerr�Finalize�_terminate_pool�
_terminate)r�	processesrHrI�maxtasksperchild�context�p�	sentinelsrrrr�s�





��
��
�
��z
Pool.__init__cCs>|j|kr:|d|��t|d�t|dd�dk	r:|j�d�dS)Nz&unclosed running multiprocessing pool )�sourcerj)rd�ResourceWarning�getattrrjr;)r�_warnrrrr�__del__s

�zPool.__del__c	Cs0|j}d|j�d|j�d|j�dt|j��d�	S)N�<�.z state=z pool_size=�>)r2r!r"rd�lenrc)r�clsrrrr3sz
Pool.__repr__cCs|jjg}|jjg}||�Sr)r}r?rj)r�task_queue_sentinels�self_notifier_sentinelsrrrrxs

zPool._get_sentinelscCsdd�|D�S)NcSsg|]}t|d�r|j�qS)�sentinel)r=r�)�.0rUrrr�
<listcomp>s
�z.Pool._get_worker_sentinels.<locals>.<listcomp>r��workersrrr�_get_worker_sentinelss�zPool._get_worker_sentinelscCsPd}ttt|���D]6}||}|jdk	rt�d|�|��d}||=q|S)z�Cleanup after any worker processes which have exited due to reaching
        their specified lifetime.  Returns True if any workers were cleaned up.
        FN�cleaning up worker %dT)�reversed�ranger�rvrrBr()�pool�cleanedrOrUrrr�_join_exited_workerss
zPool._join_exited_workerscCs0|�|j|j|j|j|j|j|j|j|j	|j
�
Sr)�_repopulate_pool_staticrer]rtrcr|r}rmrnrlr~rrrrru.s�zPool._repopulate_poolc

Csft|t|��D]P}
||t||||||	fd�}|j�dd�|_d|_|��|�|�t�	d�qdS)z�Bring the number of pool processes up to the specified number,
        for use after reaping workers which have exited.
        r_r]Z
PoolWorkerTzadded workerN)
r�r�rU�name�replacer�r��appendrrB)r^r]r�r�rFrGrHrIr�rKrO�wrrrr�7s��
zPool._repopulate_pool_staticc

Cs*t�|�r&t�||||||||||	�
dS)zEClean up any exited workers and start replacements for them.
        N)rr�r�)
r^r]r�r�rFrGrHrIr�rKrrr�_maintain_poolJs
�zPool._maintain_poolcCs4|j��|_|j��|_|jjj|_|jjj|_	dSr)
rerhr|r}r6�sendr�r?�recvr�rrrrrfVszPool._setup_queuescCs|jtkrtd��dS)NzPool not running)rdrrqrrrr�_check_running\s
zPool._check_runningcCs|�|||���S)zT
        Equivalent of `func(*args, **kwds)`.
        Pool must be running.
        )�apply_asyncr<)rrPrrQrrr�apply`sz
Pool.applycCs|�||t|���S)zx
        Apply `func` to each element in `iterable`, collecting the results
        in a list that is returned.
        )�
_map_asyncrr<�rrP�iterable�	chunksizerrrrgszPool.mapcCs|�||t|���S)z�
        Like `map()` method but the elements of the `iterable` are expected to
        be iterables as well and will be unpacked as arguments. Hence
        `func` and (a, b) becomes func(a, b).
        )r�rr<r�rrrrnszPool.starmapcCs|�||t|||�S)z=
        Asynchronous version of `starmap()` method.
        )r�r�rrPr�r��callback�error_callbackrrr�
starmap_asyncvs�zPool.starmap_asyncc
csjz,d}t|�D]\}}||||fifVqWn8tk
rd}z||dt|fifVW5d}~XYnXdS)z�Provides a generator of tasks for imap and imap_unordered with
        appropriate handling for iterables which throw exceptions during
        iteration.���rN)�	enumeraterCrD)r�
result_jobrPr�rO�xrSrrr�_guarded_task_generation~szPool._guarded_task_generationrcCs�|��|dkr:t|�}|j�|�|j||�|jf�|S|dkrPtd�|���t	�
|||�}t|�}|j�|�|jt|�|jf�dd�|D�SdS)zP
        Equivalent of `map()` -- can be MUCH slower than `Pool.map()`.
        rzChunksize must be 1+, not {0:n}css|]}|D]
}|Vq
qdSrr�r��chunkr[rrr�	<genexpr>�szPool.imap.<locals>.<genexpr>N)r��IMapIteratorrir;r��_job�_set_lengthrqr:r�
_get_tasksr�rrPr�r�rR�task_batchesrrr�imap�s4�������z	Pool.imapcCs�|��|dkr:t|�}|j�|�|j||�|jf�|S|dkrPtd�|���t	�
|||�}t|�}|j�|�|jt|�|jf�dd�|D�SdS)zL
        Like `imap()` method but ordering of results is arbitrary.
        rzChunksize must be 1+, not {0!r}css|]}|D]
}|Vq
qdSrrr�rrrr��sz&Pool.imap_unordered.<locals>.<genexpr>N)r��IMapUnorderedIteratorrir;r�r�r�rqr:rr�rr�rrr�imap_unordered�s0������zPool.imap_unorderedcCs6|��t|||�}|j�|jd|||fgdf�|S)z;
        Asynchronous version of `apply()` method.
        rN)r��ApplyResultrir;r�)rrPrrQr�r�rRrrrr��szPool.apply_asynccCs|�||t|||�S)z9
        Asynchronous version of `map()` method.
        )r�rr�rrr�	map_async�s�zPool.map_asyncc
Cs�|��t|d�st|�}|dkrJtt|�t|j�d�\}}|rJ|d7}t|�dkrZd}t�|||�}t||t|�||d�}	|j	�
|�|	j||�df�|	S)zY
        Helper function to implement map, starmap and their async counterparts.
        �__len__N�rr�r�)
r�r=r�divmodr�rcrr��	MapResultrir;r�r�)
rrPr��mapperr�r�r��extrar�rRrrrr��s,
����zPool._map_asynccCs"t||d�|��s|��qdS)N)�timeout)r	�emptyr<)r��change_notifierr�rrr�_wait_for_updates�szPool._wait_for_updatescCspt��}|jtks |rX|jtkrX|�|||||||	|
||�
|�|�|
�}|�||�q|�d�t	�
d�dS)Nzworker handler exiting)ry�current_threadrdrr
r�r�r�r;rrB)r��cache�	taskqueuer^r]r�r�rFrGrHrIr�rKr�r��thread�current_sentinelsrrrr{�s�
zPool._handle_workersc

Cspt��}t|jd�D]�\}}d}z�|D]�}|jtkrBt�d�q�z||�Wq&tk
r�}
zB|dd�\}	}z||	�	|d|
f�Wnt
k
r�YnXW5d}
~
XYq&Xq&|r�t�d�|r�|dnd}||d�W�qW�
�q
W5d}}}	Xqt�d�z6t�d�|�d�t�d	�|D]}|d��q.Wn tk
�r`t�d
�YnXt�d�dS)Nz'task handler found thread._state != RUN�Fzdoing set_length()rr�ztask handler got sentinelz/task handler sending sentinel to result handlerz(task handler sending sentinel to workersz/task handler got OSError when sending sentinelsztask handler exiting)
ryr��iterr<rdrrrBrC�_set�KeyErrorr;rA)
r�r;rGr�r�r��taskseq�
set_lengthrMrNrS�idxr�rrrr�sB






zPool._handle_tasksc	Cs�t��}z
|�}Wn$ttfk
r6t�d�YdSX|jtkr`|jtksTt	d��t�d�q�|dkrtt�d�q�|\}}}z||�
||�Wntk
r�YnXd}}}q|�rR|jtk�rRz
|�}Wn$ttfk
r�t�d�YdSX|dk�rt�d�q�|\}}}z||�
||�Wntk
�rBYnXd}}}q�t|d��r�t�d�z,t
d�D]}|j���s��q�|��qrWnttfk
�r�YnXt�d	t|�|j�dS)
Nz.result handler got EOFError/OSError -- exitingzThread not in TERMINATEz,result handler found thread._state=TERMINATEzresult handler got sentinelz&result handler ignoring extra sentinelr?z"ensuring that outqueue is not full�
z7result handler exiting: len(cache)=%s, thread._state=%s)ryr�rAr@rrBrdrr
r9r�r�r=r�r?�pollr�)rGr<r�r�rMrNrO�objrrrr�:s^











�zPool._handle_resultsccs0t|�}tt�||��}|s dS||fVqdSr)r��tupler�islice)rP�it�sizer�rrrr�vs
zPool._get_taskscCstd��dS)Nz:pool objects cannot be passed between processes or pickled)�NotImplementedErrorrrrrr+s�zPool.__reduce__cCs2t�d�|jtkr.t|_t|j_|j�d�dS)Nzclosing pool)rrBrdrrrrjr;rrrrr>�s


z
Pool.closecCst�d�t|_|��dS)Nzterminating pool)rrBr
rdr�rrrrrw�s
zPool.terminatecCsjt�d�|jtkrtd��n|jttfkr4td��|j��|j	��|j
��|jD]}|��qXdS)Nzjoining poolzPool is still runningzIn unknown state)rrBrdrrqrr
rr(r�r�rc)rr�rrrr(�s






z	Pool.joincCs@t�d�|j��|��r<|j��r<|j��t�	d�qdS)Nz7removing tasks from inqueue until task handler finishedr)
rrB�_rlock�acquire�is_aliver?r�r��time�sleep)rF�task_handlerr�rrr�_help_stuff_finish�s



zPool._help_stuff_finishc
CsXt�d�t|_|�d�t|_t�d�|�||t|��|��sXt|	�dkrXtd��t|_|�d�|�d�t�d�t	�
�|k	r�|��|r�t|dd�r�t�d�|D]}
|
j
dkr�|
��q�t�d�t	�
�|k	r�|��t�d	�t	�
�|k	�r|��|�rTt|dd��rTt�d
�|D](}
|
���r*t�d|
j�|
���q*dS)Nzfinalizing poolz&helping task handler/workers to finishrz.Cannot have cache with result_hander not alivezjoining worker handlerrwzterminating workerszjoining task handlerzjoining result handlerzjoining pool workersr�)rrBr
rdr;r�r�r�r9ryr�r(r=rvrw�pid)r�r�rFrGr�r��worker_handlerr��result_handlerr�r�rrrr��sB


�









zPool._terminate_poolcCs|��|Sr)r�rrrr�	__enter__�szPool.__enter__cCs|��dSr)rw)r�exc_type�exc_val�exc_tbrrr�__exit__�sz
Pool.__exit__)NNrNN)N)N)NNN)r)r)NNN)NNN)N)-r r!r"r4r~�staticmethodr]r�warnings�warnrr�r3rxr�r�rur�r�rfr�r�rrr�r�r�r�r�r�r�r��classmethodr{r�r�r�r+r>rwr(r�r�r�r�rrrrr�sx
�
P

	



�


�

�
�


-
;


5c@s@eZdZdd�Zdd�Zdd�Zddd	�Zdd
d�Zdd
�ZdS)r�cCs>||_t��|_tt�|_|j|_||_||_	||j|j<dSr)
rcry�Event�_event�next�job_counterr�rk�	_callback�_error_callback)rr�r�r�rrrr�s

zApplyResult.__init__cCs
|j��Sr)r�is_setrrrr�ready�szApplyResult.readycCs|��std�|���|jS)Nz{0!r} not ready)rrqr:�_successrrrr�
successful�szApplyResult.successfulNcCs|j�|�dSr)rr	�rr�rrrr	�szApplyResult.waitcCs,|�|�|��st�|jr"|jS|j�dSr)r	rrr�_valuer
rrrr<�s
zApplyResult.getcCsZ|\|_|_|jr$|jr$|�|j�|jr<|js<|�|j�|j��|j|j=d|_dSr)	rrrrr�setrkr�rc�rrOr�rrrr�s

zApplyResult._set)N)N)	r r!r"rrr	r	r<r�rrrrr��s	

	r�c@seZdZdd�Zdd�ZdS)r�cCshtj||||d�d|_dg||_||_|dkrNd|_|j��|j|j	=n||t
||�|_dS)Nr�Tr)r�rrr�
_chunksize�_number_leftrrrkr��bool)rr�r��lengthr�r�rrrrs
�
zMapResult.__init__cCs�|jd8_|\}}|rv|jrv||j||j|d|j�<|jdkr�|jrZ|�|j�|j|j=|j��d|_	nL|s�|jr�d|_||_|jdkr�|j
r�|�
|j�|j|j=|j��d|_	dS)NrrF)rrrrrrkr�rrrcr)rrO�success_result�successrRrrrr�$s&







zMapResult._setN)r r!r"rr�rrrrr�s
r�c@s:eZdZdd�Zdd�Zddd�ZeZdd	�Zd
d�ZdS)
r�cCsT||_t�t���|_tt�|_|j|_t	�
�|_d|_d|_
i|_||j|j<dS)Nr)rcry�	Condition�Lock�_condrrr�rk�collections�deque�_items�_index�_length�	_unsorted)rr�rrrrBs

zIMapIterator.__init__cCs|Srrrrrr�__iter__MszIMapIterator.__iter__NcCs�|j��z|j��}Wnztk
r�|j|jkr>d|_td�|j�|�z|j��}Wn2tk
r�|j|jkr�d|_td�t	d�YnXYnXW5QRX|\}}|r�|S|�dSr)
rr�popleft�
IndexErrorrrrc�
StopIterationr	r)rr�r[rr/rrrrPs&zIMapIterator.nextc	Cs�|j��|j|krn|j�|�|jd7_|j|jkrb|j�|j�}|j�|�|jd7_q,|j��n
||j|<|j|jkr�|j|j	=d|_
W5QRXdS�Nr)rrrr�r�pop�notifyrrkr�rcr
rrrr�hs


zIMapIterator._setc	CsB|j�2||_|j|jkr4|j��|j|j=d|_W5QRXdSr)rrrr#rkr�rc)rrrrrr�ys

zIMapIterator._set_length)N)	r r!r"rrr�__next__r�r�rrrrr�@s
r�c@seZdZdd�ZdS)r�c	CsV|j�F|j�|�|jd7_|j��|j|jkrH|j|j=d|_W5QRXdSr!)	rrr�rr#rrkr�rcr
rrrr��s

zIMapUnorderedIterator._setN)r r!r"r�rrrrr��sr�c@sVeZdZdZedd��Zddd�Zdd	�Zd
d�Zedd
��Z	edd��Z
dd�ZdS)rFcOsddlm}|||�S)Nrr\)�dummyr])r^rrQr]rrrr]�szThreadPool.ProcessNrcCst�||||�dSr)rr)rr�rHrIrrrr�szThreadPool.__init__cCs,t��|_t��|_|jj|_|jj|_dSr)rgrhr|r}r;r�r<r�rrrrrf�s


zThreadPool._setup_queuescCs
|jjgSr)rjr?rrrrrx�szThreadPool._get_sentinelscCsgSrrr�rrrr��sz ThreadPool._get_worker_sentinelscCsFz|jdd�qWntjk
r(YnXt|�D]}|�d�q2dS)NF)�block)r<rgrr�r;)rFr�r�rOrrrr��szThreadPool._help_stuff_finishcCst�|�dSr)r�r�)rr�r�r�rrrr��szThreadPool._wait_for_updates)NNr)r r!r"r~r�r]rrfrxr�r�r�rrrrr�s




)NrNF))�__all__rrrorgryr�r%r�rr$rrr�
connectionr	r
rrr
�countrrrrCrr#r*r-rUrD�dictrW�objectrr��AsyncResultr�r�r�rrrrr�<module>
sN	�
-=)+E�h�)bytecode of module 'multiprocessing.pool'�u��b.���
h)��N}�(hBD
�@s6ddlZddlZddlmZdgZGdd�de�ZdS)�N�)�util�Popenc@s`eZdZdZdd�Zdd�Zejfdd�Zdd	d
�Z	dd�Z
d
d�Zdd�Zdd�Z
dd�ZdS)r�forkcCs"t��d|_d|_|�|�dS�N)r�_flush_std_streams�
returncode�	finalizer�_launch)�self�process_obj�r
�0/usr/lib/python3.8/multiprocessing/popen_fork.py�__init__szPopen.__init__cCs|Srr
)r�fdr
r
r�duplicate_for_childszPopen.duplicate_for_childc
Cs�|jdkr�zt�|j|�\}}Wn(tk
rH}z
WY�dSd}~XYnX||jkr�t�|�rnt�|�|_n$t�|�s�td�	|���t�
|�|_|jS)NzStatus is {:n})r�os�waitpid�pid�OSError�WIFSIGNALED�WTERMSIG�	WIFEXITED�AssertionError�format�WEXITSTATUS)r�flagr�sts�er
r
r�polls


z
Popen.pollNcCsN|jdkrH|dk	r0ddlm}||jg|�s0dS|�|dkrBtjnd�S|jS)Nr)�waitg)r�multiprocessing.connectionr �sentinelrr�WNOHANG)r�timeoutr r
r
rr (s
z
Popen.waitcCsZ|jdkrVzt�|j|�Wn8tk
r0Yn&tk
rT|jdd�dkrP�YnXdS)Ng�������?)r$)rr�killr�ProcessLookupErrorrr )r�sigr
r
r�_send_signal2s
zPopen._send_signalcCs|�tj�dSr)r(�signal�SIGTERM�rr
r
r�	terminate<szPopen.terminatecCs|�tj�dSr)r(r)�SIGKILLr+r
r
rr%?sz
Popen.killc	Cs�d}t��\}}t��\}}t��|_|jdkrdz$t�|�t�|�|j|d�}W5t�|�Xn0t�|�t�|�t�|tj	||f�|_
||_dS)Nrr)�parent_sentinel)r�piperr�_exit�close�
_bootstrapr�Finalize�	close_fdsr	r")rr�code�parent_r�child_w�child_r�parent_wr
r
rr
Bs 






�z
Popen._launchcCs|jdk	r|��dSr)r	r+r
r
rr1Us
zPopen.close)N)�__name__�
__module__�__qualname__�methodrrrr#rr r(r,r%r
r1r
r
r
rrs


)rr)�r�__all__�objectrr
r
r
r�<module>s�h�/bytecode of module 'multiprocessing.popen_fork'�u��b.���	h)��N}�(hBa	�@s�ddlZddlZddlmZmZejs.ed��ddlmZddlm	Z	ddlm
Z
ddlmZd	gZGd
d�de
�ZGdd	�d	e	j�ZdS)
�N�)�	reduction�set_spawning_popenz,No support for sending fds between processes)�
forkserver)�
popen_fork)�spawn)�util�Popenc@seZdZdd�Zdd�ZdS)�_DupFdcCs
||_dS�N)�ind)�selfr�r�6/usr/lib/python3.8/multiprocessing/popen_forkserver.py�__init__sz_DupFd.__init__cCst��|jSr)r�get_inherited_fdsr)r
rrr�detachsz
_DupFd.detachN)�__name__�
__module__�__qualname__rrrrrrr
sr
csBeZdZdZeZ�fdd�Zdd�Zdd�Ze	j
fdd	�Z�ZS)
r	rcsg|_t��|�dSr)�_fds�superr)r
�process_obj��	__class__rrr!szPopen.__init__cCs|j�|�t|j�dS)Nr)r�append�len)r
�fdrrr�duplicate_for_child%szPopen.duplicate_for_childc	Cs�t�|j�}t��}t|�zt�||�t�||�W5td�Xt�	|j
�\|_}t�
|�}t�|tj||jf�|_t|ddd��}|�|���W5QRXt�|j�|_dS)N�wbT)�closefd)r�get_preparation_data�_name�io�BytesIOrr�dumpr�connect_to_new_processr�sentinel�os�dupr�Finalize�	close_fds�	finalizer�open�write�	getbuffer�read_signed�pid)r
r�	prep_data�buf�w�	_parent_w�frrr�_launch)s


�z
Popen._launchc	Csr|jdkrlddlm}|tjkr$dnd}||jg|�s:dSzt�|j�|_Wntt	fk
rjd|_YnX|jS)Nr)�wait�)
�
returncode�multiprocessing.connectionr8r(�WNOHANGr'rr0�OSError�EOFError)r
�flagr8�timeoutrrr�poll=s
z
Popen.poll)
rrr�methodr
�DupFdrrr7r(r<rA�
__classcell__rrrrr	s)r#r(�contextrr�HAVE_SEND_HANDLE�ImportError�rrrr�__all__�objectr
r	rrrr�<module>s
�h�5bytecode of module 'multiprocessing.popen_forkserver'�u��b.���h)��N}�(hB��@spddlZddlZddlmZmZddlmZddlmZddlmZdgZ	Gdd	�d	e
�ZGd
d�dej�ZdS)�N�)�	reduction�set_spawning_popen)�
popen_fork)�spawn)�util�Popenc@seZdZdd�Zdd�ZdS)�_DupFdcCs
||_dS�N��fd��selfr�r�7/usr/lib/python3.8/multiprocessing/popen_spawn_posix.py�__init__sz_DupFd.__init__cCs|jSr
r)rrrr�detachsz
_DupFd.detachN)�__name__�
__module__�__qualname__rrrrrrr	sr	cs4eZdZdZeZ�fdd�Zdd�Zdd�Z�Z	S)rrcsg|_t��|�dSr
)�_fds�superr)r�process_obj��	__class__rrrszPopen.__init__cCs|j�|�|Sr
)r�appendr
rrr�duplicate_for_child"szPopen.duplicate_for_childcCsXddlm}|��}|j�|�t�|j�}t�	�}t
|�zt�||�t�||�W5t
d�Xd}}}}	z~t��\}}t��\}}	tj||d�}|j�||g�t
�t��||j�|_||_t|	ddd��}
|
�|���W5QRXW5g}
||	fD]}|dk	�r|
�|��qt
�|t
j|
�|_||fD]}|dk	�r6t�|��q6XdS)Nr)�resource_tracker)�
tracker_fd�pipe_handle�wbF)�closefd)�r�getfdrrr�get_preparation_data�_name�io�BytesIOrr�dumpr�Finalize�	close_fds�	finalizer�os�close�pipe�get_command_line�extend�spawnv_passfds�get_executable�pid�sentinel�open�write�	getbuffer)rrrr�	prep_data�fp�parent_r�child_w�child_r�parent_w�fds_to_closer�cmd�frrr�_launch&sB
�
�

z
Popen._launch)
rrr�methodr	�DupFdrrrA�
__classcell__rrrrrs
)
r&r,�contextrrr"rrr�__all__�objectr	rrrrr�<module>s
�h�6bytecode of module 'multiprocessing.popen_spawn_posix'�u��b.��0+h)��N}�(hB�*�@s8ddddgZddlZddlZddlZddlZddlZddlmZzej�	e�
��ZWnek
rldZYnXdd�Z
dd�Zd	d�Zd
d�ZGdd�de�ZGd
d�de�ZGdd�de�ZGdd�de�Zdae�ae�d�ae�a[iZeej� ��D]0\Z!Z"e!dd�dkr�de!kr�de!��ee"<q�e�Z#dS)�BaseProcess�current_process�active_children�parent_process�N)�WeakSetcCstS)z@
    Return process object representing the current process
    )�_current_process�rr�-/usr/lib/python3.8/multiprocessing/process.pyr%scCst�tt�S)zN
    Return list of process objects corresponding to live child processes
    )�_cleanup�list�	_childrenrrrr	r+scCstS)z?
    Return process object representing the parent process
    )�_parent_processrrrr	r3scCs*tt�D]}|j��dk	rt�|�qdS�N)rr�_popen�poll�discard)�prrr	r
=sr
c@s�eZdZdZdd�Zddddifdd�dd�Zd	d
�Zdd�Zd
d�Zdd�Z	dd�Z
d,dd�Zdd�Zdd�Z
edd��Zejdd��Zedd��Zejdd��Zedd ��Zejd!d ��Zed"d#��Zed$d%��ZeZed&d'��Zd(d)�Zd-d*d+�ZdS).rz�
    Process objects represent activity that is run in a separate process

    The class is analogous to `threading.Thread`
    cCst�dSr)�NotImplementedError��selfrrr	�_PopenMszBaseProcess._PopenNr)�daemoncCs�|dkstd��tt�}tj|f|_tj��|_t��|_	tj
|_d|_d|_
||_t|�|_t|�|_|p�t|�jdd�dd�|jD��|_|dk	r�||_t�|�dS)Nz#group argument must be None for nowF�-�:css|]}t|�VqdSr)�str)�.0�irrr	�	<genexpr>^sz'BaseProcess.__init__.<locals>.<genexpr>)�AssertionError�next�_process_counterr�	_identity�_config�copy�os�getpid�_parent_pid�name�_parent_namer�_closed�_target�tuple�_args�dict�_kwargs�type�__name__�join�_namer�	_dangling�add)r�group�targetr'�args�kwargsr�countrrr	�__init__Ps"


�zBaseProcess.__init__cCs|jrtd��dS)Nzprocess object is closed)r)�
ValueErrorrrrr	�
_check_closedcszBaseProcess._check_closedcCs|jr|j|j|j�dS)zQ
        Method to be run in sub-process; can be overridden in sub-class
        N)r*r,r.rrrr	�rungszBaseProcess.runcCsz|��|jdkstd��|jt��ks0td��tj�d�rDtd��t	�|�
|�|_|jj|_|`
|`|`t�|�dS)z%
        Start child process
        Nzcannot start a process twicez:can only start a process object created by current processrz3daemonic processes are not allowed to have children)r<rrr&r$r%rr"�getr
r�sentinel�	_sentinelr*r,r.rr4rrrr	�startns��
zBaseProcess.startcCs|��|j��dS)zT
        Terminate process; sends SIGTERM signal or uses TerminateProcess()
        N)r<r�	terminaterrrr	rB�szBaseProcess.terminatecCs|��|j��dS)zT
        Terminate process; sends SIGKILL signal or uses TerminateProcess()
        N)r<r�killrrrr	rC�szBaseProcess.killcCsR|��|jt��kstd��|jdk	s0td��|j�|�}|dk	rNt�|�dS)z5
        Wait until child process terminates
        zcan only join a child processNzcan only join a started process)	r<r&r$r%rr�waitrr)r�timeout�resrrr	r1�szBaseProcess.joincCs`|��|tkrdS|jt��ks*td��|jdkr8dS|j��}|dkrNdSt�	|�dSdS)z1
        Return whether process is alive
        Tzcan only test a child processNF)
r<rr&r$r%rrrrr)r�
returncoderrr	�is_alive�s


zBaseProcess.is_alivecCsH|jdk	r>|j��dkr td��|j��d|_|`t�|�d|_dS)z�
        Close the Process object.

        This method releases resources held by the Process object.  It is
        an error to call this method if the child process is still running.
        Nz^Cannot close a process while it is still running. You should first call join() or terminate().T)rrr;�closer@rrr)rrrr	rI�s


zBaseProcess.closecCs|jSr)r2rrrr	r'�szBaseProcess.namecCst|t�std��||_dS)Nzname must be a string)�
isinstancerrr2)rr'rrr	r'�scCs|j�dd�S)z4
        Return whether process is a daemon
        rF)r"r>rrrr	r�szBaseProcess.daemoncCs |jdkstd��||jd<dS)z1
        Set whether process is a daemon
        Nzprocess has already startedr)rrr")r�daemonicrrr	r�scCs
|jdS)N�authkey)r"rrrr	rL�szBaseProcess.authkeycCst|�|jd<dS)z2
        Set authorization key of process
        rLN)�AuthenticationStringr")rrLrrr	rL�scCs"|��|jdkr|jS|j��S)zM
        Return exit code of process or `None` if it has yet to stop
        N)r<rrrrrr	�exitcode�s
zBaseProcess.exitcodecCs*|��|tkrt��S|jo$|jjSdS)zU
        Return identifier (PID) of process or `None` if it has yet to start
        N)r<rr$r%r�pidrrrr	�ident�szBaseProcess.identcCs4|��z|jWStk
r.td�d�YnXdS)z{
        Return a file descriptor (Unix) or handle (Windows) suitable for
        waiting for process termination.
        zprocess not startedN)r<r@�AttributeErrorr;rrrr	r?�s
zBaseProcess.sentinelcCs�d}|tkrd}nL|jrd}n@|jt��kr2d}n,|jdkrBd}n|j��}|dk	rZd}nd}t|�jd|j	g}|jdk	r�|�
d|jj�|�
d|j�|�
|�|dk	r�t�
||�}|�
d	|�|jr�|�
d
�dd�|�S)
N�started�closed�unknown�initial�stoppedzname=%rzpid=%sz	parent=%szexitcode=%srz<%s>� )rr)r&r$r%rrr/r0r2�appendrO�_exitcode_to_namer>rr1)rrN�status�inforrr	�__repr__s0




zBaseProcess.__repr__c
Csvddlm}m}�z>z�|jdk	r,|�|j�t	�
d�at�a
|��t}|at|j|j|�atjrnt����z|j��|��W5~X|�d�z|��d}W5|��XWn�tk
�r}zJ|js�d}n:t|jdt�r�|jd}nt j!�"t#|jd�d�d}W5d}~XYn2d}ddl$}t j!�"d|j%�|�&�YnXW5t��|�d|�|��X|S)N�)�util�contextz process exiting with exitcode %dz child process calling self.run()r�
zProcess %s:
)'�r^r_�	threading�	_shutdownr[�_flush_std_streams�
_start_method�_force_start_method�	itertoolsr9r �setr�_close_stdinr�_ParentProcessr(r&r
�_HAVE_THREAD_NATIVE_ID�main_thread�_set_native_id�_finalizer_registry�clear�_run_after_forkers�_exit_functionr=�
SystemExitr7rJ�int�sys�stderr�writer�	tracebackr'�	print_exc)r�parent_sentinelr^r_rN�old_process�erwrrr	�
_bootstrap"sR

�


zBaseProcess._bootstrap)N)N)r0�
__module__�__qualname__�__doc__rr:r<r=rArBrCr1rHrI�propertyr'�setterrrLrNrPrOr?r\r|rrrr	rGsD�







	


c@seZdZdd�ZdS)rMcCs,ddlm}|�dkrtd��tt|�ffS)Nr])�get_spawning_popenzJPickling an AuthenticationString object is disallowed for security reasons)r_r��	TypeErrorrM�bytes)rr�rrr	�
__reduce__Xs
�zAuthenticationString.__reduce__N)r0r}r~r�rrrr	rMWsrMc@s6eZdZdd�Zdd�Zedd��Zd
dd	�ZeZdS)rjcCs4d|_||_||_d|_d|_d|_||_i|_dS)NrF)r!r2�_pidr&rr)r@r")rr'rOr?rrr	r:hsz_ParentProcess.__init__cCsddlm}||jgdd�S)Nr�rD�rE��multiprocessing.connectionrDr@)rrDrrr	rHrsz_ParentProcess.is_alivecCs|jSr)r�rrrr	rPvsz_ParentProcess.identNcCs ddlm}||jg|d�dS)z6
        Wait until parent process terminates
        rr�r�Nr�)rrErDrrr	r1zsz_ParentProcess.join)N)	r0r}r~r:rHr�rPr1rOrrrr	rjfs


rjc@seZdZdd�Zdd�ZdS)�_MainProcesscCs8d|_d|_d|_d|_d|_tt�d��dd�|_dS)NrZMainProcessF� z/mp)rLZ	semprefix)	r!r2r&rr)rMr$�urandomr"rrrr	r:�s�z_MainProcess.__init__cCsdSrrrrrr	rI�sz_MainProcess.closeN)r0r}r~r:rIrrrr	r��sr�r]�ZSIG�_r)$�__all__r$rt�signalrgrb�_weakrefsetr�path�abspath�getcwd�ORIGINAL_DIR�OSErrorrrrr
�objectrr�rMrjr�r
rr9r rhrrYr�__dict__�itemsr'�signumr3rrrr	�<module>
s@�


!
�h�,bytecode of module 'multiprocessing.process'�u��b.���%h)��N}�(hBB%�@s�dddgZddlZddlZddlZddlZddlZddlZddlZddlm	Z	m
Z
ddlZddlm
Z
ddlmZejjZdd	lmZmZmZmZmZGd
d�de�Ze�ZGdd�de�ZGdd�de�ZdS)
�Queue�SimpleQueue�
JoinableQueue�N)�Empty�Full�)�
connection)�context)�debug�info�Finalize�register_after_fork�
is_exitingc@s�eZdZd*dd�Zdd�Zdd�Zdd	�Zd+dd
�Zd,dd�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zd d!�Zed"d#��Zed$d%��Zed&d'��Zed(d)��ZdS)-rrcCs�|dkrddlm}||_tjdd�\|_|_|��|_t	�
�|_tj
dkrTd|_n
|��|_|�|�|_d|_|��tj
dkr�t|tj�dS)Nrr)�
SEM_VALUE_MAXF��duplex�win32)�synchronizer�_maxsizer�Pipe�_reader�_writer�Lock�_rlock�os�getpid�_opid�sys�platform�_wlock�BoundedSemaphore�_sem�
_ignore_epipe�_after_forkr
r��self�maxsize�ctx�r(�,/usr/lib/python3.8/multiprocessing/queues.py�__init__$s




zQueue.__init__cCs.t�|�|j|j|j|j|j|j|j|j	fS�N)
r	�assert_spawningr"rrrrrr!r�r%r(r(r)�__getstate__9s
�zQueue.__getstate__c	Cs0|\|_|_|_|_|_|_|_|_|��dSr+)	r"rrrrrr!rr#�r%�stater(r(r)�__setstate__>s�zQueue.__setstate__cCsbtd�t�t���|_t��|_d|_d|_	d|_
d|_d|_|j
j|_|jj|_|jj|_dS)NzQueue._after_fork()F)r
�	threading�	Conditionr�	_notempty�collections�deque�_buffer�_thread�_jointhread�_joincancelled�_closed�_closer�
send_bytes�_send_bytesr�
recv_bytes�_recv_bytes�poll�_pollr-r(r(r)r#Cs


zQueue._after_forkTNc	Csf|jrtd|�d���|j�||�s(t�|j�.|jdkrB|��|j�	|�|j�
�W5QRXdS�NzQueue z
 is closed)r;�
ValueErrorr!�acquirerr4r8�
_start_threadr7�append�notify�r%�obj�block�timeoutr(r(r)�putPs
z	Queue.putc	Cs�|jrtd|�d���|rH|dkrH|j�|��}W5QRX|j��nr|rXt��|}|j�||�sjt	�zB|r�|t��}|�
|�s�t	�n|�
�s�t	�|��}|j��W5|j��Xt�|�SrC)
r;rDrr@r!�release�time�	monotonicrErrB�_ForkingPickler�loads)r%rKrL�res�deadliner(r(r)�get\s*
z	Queue.getcCs|j|jj��Sr+)rr!�_semlock�
_get_valuer-r(r(r)�qsizevszQueue.qsizecCs
|��Sr+�rBr-r(r(r)�emptyzszQueue.emptycCs|jj��Sr+)r!rV�_is_zeror-r(r(r)�full}sz
Queue.fullcCs
|�d�S�NF)rUr-r(r(r)�
get_nowait�szQueue.get_nowaitcCs|�|d�Sr])rM�r%rJr(r(r)�
put_nowait�szQueue.put_nowaitcCs2d|_z|j��W5|j}|r,d|_|�XdS)NT)r;r<r�close)r%rar(r(r)ra�szQueue.closecCs.td�|jstd�|���|jr*|��dS)NzQueue.join_thread()zQueue {0!r} not closed)r
r;�AssertionError�formatr9r-r(r(r)�join_thread�szQueue.join_threadcCs6td�d|_z|j��Wntk
r0YnXdS)NzQueue.cancel_join_thread()T)r
r:r9�cancel�AttributeErrorr-r(r(r)�cancel_join_thread�szQueue.cancel_join_threadc
Cs�td�|j��tjtj|j|j|j|j	|j
j|j|j
|jfdd�|_d|j_td�|j��td�|js�t|jtjt�|j�gdd�|_t|tj|j|jgd	d�|_dS)
NzQueue._start_thread()ZQueueFeederThread)�target�args�nameTzdoing self._thread.start()z... done self._thread.start()���)�exitpriority�
)r
r7�clearr2�Threadr�_feedr4r>rrrar"�_on_queue_feeder_errorr!r8�daemon�startr:r�_finalize_join�weakref�refr9�_finalize_closer<r-r(r(r)rF�s<
��
�
�zQueue._start_threadcCs4td�|�}|dk	r(|��td�ntd�dS)Nzjoining queue threadz... queue thread joinedz... queue thread already dead)r
�join)�twr�threadr(r(r)rt�s
zQueue._finalize_joinc	Cs.td�|�|�t�|��W5QRXdS)Nztelling queue thread to quit)r
rG�	_sentinelrH)�buffer�notemptyr(r(r)rw�s
zQueue._finalize_closec
CsXtd�|j}|j}	|j}
|j}t}tjdkr<|j}
|j}nd}
z�|�z|sT|
�W5|	�Xzb|�}||kr�td�|�WWdSt�	|�}|
dkr�||�qb|
�z||�W5|�XqbWnt
k
r�YnXWq@tk
�rP}zV|�rt|dd�t
jk�rWY�6dSt��r.td|�WY�dS|��|||�W5d}~XYq@Xq@dS)Nz$starting thread to feed data to piperz%feeder thread got sentinel -- exiting�errnorzerror in queue thread: %s)r
rErN�wait�popleftr{rrrQ�dumps�
IndexError�	Exception�getattrr~�EPIPErr)r|r}r=�	writelockra�ignore_epipe�onerror�	queue_sem�nacquire�nrelease�nwait�bpopleft�sentinel�wacquire�wreleaserJ�er(r(r)rp�sN







zQueue._feedcCsddl}|��dS)z�
        Private API hook called when feeding data in the background thread
        raises an exception.  For overriding by concurrent.futures.
        rN)�	traceback�	print_exc)r�rJr�r(r(r)rq
szQueue._on_queue_feeder_error)r)TN)TN)�__name__�
__module__�__qualname__r*r.r1r#rMrUrXrZr\r^r`rardrgrF�staticmethodrtrwrprqr(r(r(r)r"s.



 
	

=c@s@eZdZddd�Zdd�Zdd�Zdd
d�Zdd
�Zdd�Zd	S)rrcCs*tj|||d�|�d�|_|��|_dS)N)r'r)rr*�	Semaphore�_unfinished_tasksr3�_condr$r(r(r)r*#szJoinableQueue.__init__cCst�|�|j|jfSr+)rr.r�r�r-r(r(r)r.(szJoinableQueue.__getstate__cCs,t�||dd��|dd�\|_|_dS)N���)rr1r�r�r/r(r(r)r1+szJoinableQueue.__setstate__TNc
Cs�|jrtd|�d���|j�||�s(t�|j�J|j�8|jdkrJ|��|j	�
|�|j��|j�
�W5QRXW5QRXdSrC)r;rDr!rErr4r�r8rFr7rGr�rNrHrIr(r(r)rM/s

zJoinableQueue.putc	Cs@|j�0|j�d�std��|jj��r2|j��W5QRXdS)NFz!task_done() called too many times)r�r�rErDrVr[�
notify_allr-r(r(r)�	task_done<s
zJoinableQueue.task_donec	Cs,|j�|jj��s|j��W5QRXdSr+)r�r�rVr[rr-r(r(r)rxCszJoinableQueue.join)r)TN)	r�r�r�r*r.r1rMr�rxr(r(r(r)r!s


c@s<eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
S)rcCsHtjdd�\|_|_|��|_|jj|_tj	dkr:d|_
n
|��|_
dS)NFrr)rrrrrrrArBrrr)r%r'r(r(r)r*Ns


zSimpleQueue.__init__cCs
|��Sr+rYr-r(r(r)rZWszSimpleQueue.emptycCst�|�|j|j|j|jfSr+)r	r,rrrrr-r(r(r)r.Zs
zSimpleQueue.__getstate__cCs"|\|_|_|_|_|jj|_dSr+)rrrrrArBr/r(r(r)r1^szSimpleQueue.__setstate__c	Cs&|j�|j��}W5QRXt�|�Sr+)rrr?rQrR)r%rSr(r(r)rUbszSimpleQueue.getc	CsDt�|�}|jdkr"|j�|�n|j�|j�|�W5QRXdSr+)rQr�rrr=r_r(r(r)rMhs


zSimpleQueue.putN)	r�r�r�r*rZr.r1rUrMr(r(r(r)rLs	)�__all__rrr2r5rOrur~�queuerr�_multiprocessing�rr	�	reduction�ForkingPicklerrQ�utilr
rrr
r�objectrr{rrr(r(r(r)�<module>
s$
v
+�h�+bytecode of module 'multiprocessing.queues'�u��b.��D h)��N}�(hB��@sddlmZddlZddlZddlZddlZddlZddlZddlZddl	m
Z
ddddd	gZejd
kp�e
ed�o�e
ed�o�e
ejd
�ZGdd�dej�ZejZd6dd	�Zejd
k�redddg7ZddlZd7dd�dd�Zdd�Zdd�Zdd�ZGdd�de�ZnHedddg7ZddlZejdkZdd�Zdd�Zd d�Zd!d�Zd"d�Zd#d$�ZGd%d&�d&�Z ee!e �j"�e�d'd(�Z#ee!e$j%�e#�ee!e&j'�e#�d)d*�Z(d+d,�Z)eej*e(�ejd
k�r�d-d.�Z+d/d0�Z,eeje+�nd1d.�Z+d2d0�Z,eeje+�Gd3d4�d4ed5�Z-dS)8�)�ABCMetaN�)�context�send_handle�recv_handle�ForkingPickler�register�dump�win32�CMSG_LEN�
SCM_RIGHTS�sendmsgcsJeZdZdZiZejZ�fdd�Ze	dd��Z
e	d	dd��Zej
Z
�ZS)
rz)Pickler subclass used by multiprocessing.cs*t�j|�|j��|_|j�|j�dS�N)�super�__init__�_copyreg_dispatch_table�copy�dispatch_table�update�_extra_reducers��self�args��	__class__��//usr/lib/python3.8/multiprocessing/reduction.pyr&szForkingPickler.__init__cCs||j|<dS)z&Register a reduce function for a type.N)r)�cls�type�reducerrrr+szForkingPickler.registerNcCs t��}|||��|�|��Sr)�io�BytesIOr	�	getbuffer)r�obj�protocol�bufrrr�dumps0szForkingPickler.dumps)N)�__name__�
__module__�__qualname__�__doc__r�copyregrrr�classmethodrr&�pickle�loads�
__classcell__rrrrr!s
cCst||��|�dS)z3Replacement for pickle.dump() using ForkingPickler.N)rr	)r#�filer$rrrr	:s�	DupHandle�	duplicate�steal_handleF)�source_processcCs6t��}|dkr|}|dkr |}t�|||d|tj�S)z<Duplicate a handle.  (target_process is a handle not a pid!)Nr)�_winapi�GetCurrentProcess�DuplicateHandle�DUPLICATE_SAME_ACCESS)�handle�target_process�inheritabler4�current_processrrrr2Gs�c	CsFt�tjd|�}z$t�||t��ddtjtjB�W�St�|�XdS)z5Steal a handle from process identified by source_pid.FrN)r5�OpenProcess�PROCESS_DUP_HANDLE�CloseHandler7r6r8�DUPLICATE_CLOSE_SOURCE)�
source_pidr9�source_process_handlerrrr3Ss�
�cCst|tj|�}|�|�dS�z&Send a handle over a local connection.N)r1r5r8�send)�connr9�destination_pid�dhrrrr_scCs|����S)�)Receive a handle over a local connection.)�recv�detach)rErrrrdsc@s"eZdZdZddd�Zdd�ZdS)r1zPicklable wrapper for a handle.Nc	Cs\|dkrt��}t�tjd|�}zt�t��|||dd�|_W5t�|�X||_	||_
dS)NFr)�os�getpidr5r=r>r?r7r6�_handle�_access�_pid)rr9�access�pid�procrrrrjs�
zDupHandle.__init__c	CsZ|jt��kr|jSt�tjd|j�}z"t�||jt�	�|j
dtj�W�St�|�XdS)z1Get the handle.  This should only be called once.FN)rOrKrLrMr5r=r>r?r7r6rNr@)rrRrrrrJys
��zDupHandle.detach)N)r'r(r)r*rrJrrrrr1hs
�DupFd�sendfds�recvfds�darwincCsVt�d|�}tt|�dg�}|�|gtjtj|fg�trR|�d�dkrRt	d��dS)z,Send an array of fds over an AF_UNIX socket.�i�r�Az%did not receive acknowledgement of fdN)
�array�bytes�lenr
�socket�
SOL_SOCKETr�ACKNOWLEDGErI�RuntimeError)�sock�fds�msgrrrrT�s
c	Cst�d�}|j|}|�dt�|��\}}}}|s:|s:t�z�trJ|�d�t|�dkrft	dt|���|d\}}	}
|tj
kr�|	tjkr�t|
�|jdkr�t�|�
|
�t|�d|dkr�td�t|�|d���t|�WSWnttfk
r�YnXt	d��d	S)
z/Receive an array of fds over an AF_UNIX socket.rWrrYzreceived %d items of ancdatarrXz Len is {0:n} but msg[0] is {1!r}zInvalid data receivedN)rZ�itemsize�recvmsgr]�
CMSG_SPACE�EOFErrorr_rDr\r`r^r�
ValueError�	frombytes�AssertionError�format�list�
IndexError)ra�size�a�
bytes_sizerc�ancdata�flags�addr�
cmsg_level�	cmsg_type�	cmsg_datarrrrU�s<


�
�
��c	Cs2t�|��tjtj��}t||g�W5QRXdSrC)r]�fromfd�fileno�AF_UNIX�SOCK_STREAMrT)rEr9rF�srrrr�sc
Cs<t�|��tjtj��}t|d�dW5QR�SQRXdS)rHrrN)r]rwrxryrzrU)rEr{rrrr�scCsFt��}|dk	r |�|�|��Str:ddlm}|�|�Std��dS)zReturn a wrapper for an fd.Nr)�resource_sharerz&SCM_RIGHTS appears not to be available)r�get_spawning_popenrS�duplicate_for_child�HAVE_SEND_HANDLE�r|rh)�fd�	popen_objr|rrrrS�s
cCs2|jdkrt|j|jjffSt|j|jjffSdSr)�__self__�getattrr�__func__r'��mrrr�_reduce_method�s
r�c@seZdZdd�ZdS)�_CcCsdSrr)rrrr�f�sz_C.fN)r'r(r)r�rrrrr��sr�cCst|j|jffSr)r��__objclass__r'r�rrr�_reduce_method_descriptor�sr�cCst|j|j|jpiffSr)�_rebuild_partial�funcr�keywords)�prrr�_reduce_partial�sr�cCstj|f|�|�Sr)�	functools�partial)r�rr�rrrr��sr�cCsddlm}t||�ffS)Nr)�	DupSocket)r|r��_rebuild_socket)r{r�rrr�_reduce_socket�sr�cCs|��Sr)rJ)�dsrrrr��sr�cCs"t|���}t||j|j|jffSr)rSrxr��familyr�proto)r{�dfrrrr��scCs|��}tj||||d�S)N)rx)rJr])r�r�rr�r�rrrr��sc@sdeZdZdZeZeZeZeZeZe	j
dkr8eZeZe
Z
neZeZeZeZeZeZeZeZdd�ZdS)�AbstractReducerz�Abstract base class for use in implementing a Reduction class
    suitable for use in replacing the standard reduction mechanism
    used in multiprocessing.r
cGsNttt�j�t�tttj�t�tttj	�t�tt
jt�tt
j
t�dSr)rrr�r�r�rl�appendr��int�__add__r�r�r�r]r�rrrrrs
zAbstractReducer.__init__N)r'r(r)r*rrr	rr�sys�platformr3r2r1rTrUrSr�r�r�r�r�rrrrrr��s&
r�)�	metaclass)N)NF).�abcrr+r�r rKr-r]r�r�r�__all__r��hasattrr�Picklerrrr	r5r2r3rr�objectr1rZr_rTrUrSr�r�rr�r�rlr�r�r�r�r�r�r�r�r�rrrr�<module>
sj

�
�	
�#
�h�.bytecode of module 'multiprocessing.reduction'�u��b.���h)��N}�(hBx�@s�ddlZddlZddlZddlZddlZddlmZddlmZddlm	Z	dgZ
ejdkrxe
dg7Z
Gd	d�de�Z
ne
d
g7Z
Gdd
�d
e�ZGdd
�d
e�Ze�ZejZdS)�N�)�process)�	reduction)�util�stop�win32�	DupSocketc@s eZdZdZdd�Zdd�ZdS)rzPicklable wrapper for a socket.cs(|����fdd�}t�|�j�|_dS)Ncs��|�}|�|�dS�N)�share�
send_bytes)�conn�pidr
��new_sock��5/usr/lib/python3.8/multiprocessing/resource_sharer.py�sends
z DupSocket.__init__.<locals>.send)�dup�_resource_sharer�register�close�_id)�self�sockrrrr�__init__szDupSocket.__init__c
Cs6t�|j�� }|��}t�|�W5QR�SQRXdS)z1Get the socket.  This should only be called once.N)r�get_connectionr�
recv_bytes�socketZ	fromshare)rrr
rrr�detach$szDupSocket.detachN��__name__�
__module__�__qualname__�__doc__rrrrrrrs�DupFdc@s eZdZdZdd�Zdd�ZdS)r$z-Wrapper for fd which can be used at any time.cs4t�|���fdd�}�fdd�}t�||�|_dS)Ncst�|�|�dSr	)r�send_handle)rr
��new_fdrrr1szDupFd.__init__.<locals>.sendcst���dSr	)�osrrr&rrr3szDupFd.__init__.<locals>.close)r(rrrr)r�fdrrrr&rr/s
zDupFd.__init__c
Cs.t�|j��}t�|�W5QR�SQRXdS)z-Get the fd.  This should only be called once.N)rrrr�recv_handle)rrrrrr7szDupFd.detachNrrrrrr$-sc@sNeZdZdZdd�Zdd�Zedd��Zdd	d
�Zdd�Z	d
d�Z
dd�ZdS)�_ResourceSharerz.Manager for resources using background thread.cCs@d|_i|_g|_t��|_d|_d|_d|_t	�
|tj�dS)Nr)
�_key�_cache�
_old_locks�	threading�Lock�_lock�	_listener�_address�_threadr�register_after_forkr+�
_afterfork)rrrrr?s
z_ResourceSharer.__init__c
CsZ|j�J|jdkr|��|jd7_||f|j|j<|j|jfW5QR�SQRXdS)z+Register resource, returning an identifier.Nr)r1r3�_startr,r-)rrrrrrrIs
z_ResourceSharer.registercCs<ddlm}|\}}||t��jd�}|�|t��f�|S)z<Return connection from which to receive identified resource.r��Client��authkey)�
connectionr9r�current_processr;rr(�getpid)�identr9�address�key�crrrrRs
z_ResourceSharer.get_connectionNc	Cs�ddlm}|j��|jdk	r�||jt��jd�}|�d�|��|j	�
|�|j	��rdt�
d�|j��d|_	d|_d|_|j��D]\}\}}|�q�|j��W5QRXdS)z:Stop the background thread and clear registered resources.rr8Nr:z._ResourceSharer thread did not stop when asked)r<r9r1r3rr=r;rrr4�join�is_aliver�sub_warningr2r-�items�clear)r�timeoutr9rBrArrrrrr[s$
�



z_ResourceSharer.stopcCsj|j��D]\}\}}|�q
|j��|j�|j�t��|_|jdk	rT|j�	�d|_d|_
d|_dSr	)r-rFrGr.�appendr1r/r0r2rr3r4)rrArrrrrr6ps



z_ResourceSharer._afterforkcCsjddlm}|jdkstd��t�d�|t��jd�|_|jj	|_
tj|j
d�}d|_|��||_dS)Nr)�ListenerzAlready have Listenerz0starting listener and thread for sending handlesr:)�targetT)r<rJr2�AssertionErrorr�debugrr=r;r@r3r/�Thread�_serve�daemon�startr4)rrJ�trrrr7~s

z_ResourceSharer._startc	Cs�ttd�rt�tjt���zh|j���T}|��}|dkrHW5QR�Wq�|\}}|j�	|�\}}z|||�W5|�XW5QRXWqt
��s�tj
t���YqXqdS)N�pthread_sigmask)�hasattr�signalrS�	SIG_BLOCK�
valid_signalsr2�accept�recvr-�popr�
is_exiting�sys�
excepthook�exc_info)rr�msgrA�destination_pidrrrrrrO�s
z_ResourceSharer._serve)N)r r!r"r#rr�staticmethodrrr6r7rOrrrrr+=s
	

r+)r(rUrr\r/�r�contextrr�__all__�platform�objectrr$r+rrrrrr�<module>s 


`�h�4bytecode of module 'multiprocessing.resource_sharer'�u��b.���h)��N}�(hBV�@s�ddlZddlZddlZddlZddlZddlmZddlmZdddgZe	ed�Z
ejejfZ
d	d
d�iZejdkr�ddlZddlZe�ejejd
��Gdd�de�Ze�ZejZejZejZejZdd�ZdS)�N�)�spawn)�util�ensure_running�register�
unregister�pthread_sigmaskZnoopcCsdS�N�r
r
r
�6/usr/lib/python3.8/multiprocessing/resource_tracker.py�<lambda>!�r�posix)Z	semaphore�
shared_memoryc@sLeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dS)�ResourceTrackercCst��|_d|_d|_dSr	)�	threading�Lock�_lock�_fd�_pid��selfr
r
r�__init__0s
zResourceTracker.__init__c	CsT|j�D|jdkr W5QR�dSt�|j�d|_t�|jd�d|_W5QRXdS)Nr)rr�os�close�waitpidrrr
r
r�_stop5s
zResourceTracker._stopcCs|��|jSr	)rrrr
r
r�getfdBszResourceTracker.getfdcCst|j��b|jdk	r~|��r*W5QR�dSt�|j�z|jdk	rPt�|jd�Wntk
rfYnXd|_d|_t�	d�g}z|�
tj�
��Wntk
r�YnXd}t��\}}z�zr|�
|�t��}|gt��}|dt|�g7}z&t�rt�tjt�t�|||�}W5t�r,t�tjt�XWnt�|��YnX||_||_W5t�|�XW5QRXdS)z�Make sure that resource tracker process is running.

        This can be run from any process.  Usually a child process will use
        the resource created by its parent.NrzUresource_tracker: process died unexpectedly, relaunching.  Some resources might leak.z:from multiprocessing.resource_tracker import main;main(%d)z"--multiprocessing-resource-tracker)rr�_check_aliverrrr�ChildProcessError�warnings�warn�append�sys�stderr�fileno�	Exception�piper�get_executabler�_args_from_interpreter_flags�str�
_HAVE_SIGMASK�signalr�SIG_UNBLOCK�_IGNORED_SIGNALS�	SIG_BLOCK�spawnv_passfds)r�fds_to_pass�cmd�r�w�exe�args�pidr
r
rrFsJ






zResourceTracker.ensure_runningcCs2zt�|jd�Wntk
r(YdSXdSdS)z;Check that the pipe has not been closed by sending a probe.s
PROBE:0:noop
FTN)r�writer�OSErrorrr
r
rr�s
zResourceTracker._check_alivecCs|�d||�dS)z0Register name of resource with resource tracker.�REGISTERN��_send�r�name�rtyper
r
rr�szResourceTracker.registercCs|�d||�dS)z2Unregister name of resource with resource tracker.�
UNREGISTERNr;r=r
r
rr�szResourceTracker.unregistercCsb|��d�|||��d�}t|�dkr0td��t�|j|�}|t|�ks^td�|t|����dS)Nz{0}:{1}:{2}
�asciiiz
name too longznbytes {0:n} but len(msg) {1:n})	r�format�encode�len�
ValueErrorrr8r�AssertionError)rr2r>r?�msg�nbytesr
r
rr<�s�zResourceTracker._sendN)�__name__�
__module__�__qualname__rrrrrrrr<r
r
r
rr.s
@rc
Cst�tjtj�t�tjtj�tr2t�tjt�tj	tj
fD]&}z|��Wq>tk
rbYq>Xq>dd�t
��D�}z�t|d���}|D]�}z�|���d��d�\}}}t
�|d�}	|	dkr�td	|�d
|����|dkr�||�|�n2|dk�r||�|�n|d
k�rntd|��Wq�tk
�rTztjt���WnYnXYq�Xq�W5QRXW5|��D]�\}}|�r�zt�dt|�|f�Wntk
�r�YnX|D]V}zLzt
||�Wn6tk
�r�}zt�d||f�W5d}~XYnXW5X�q��qnXdS)zRun resource tracker.cSsi|]}|t��qSr
)�set)�.0r?r
r
r�
<dictcomp>�szmain.<locals>.<dictcomp>zQresource_tracker: There appear to be %d leaked %s objects to clean up at shutdownzresource_tracker: %r: %sN�rbrA�:zCannot register z. for automatic cleanup: unknown resource type r:r@ZPROBEzunrecognized command %r)r,�SIGINT�SIG_IGN�SIGTERMr+rr-r.r#�stdin�stdoutrr&�_CLEANUP_FUNCS�keys�itemsr r!rD�open�strip�decode�split�getrE�add�remove�RuntimeError�
excepthook�exc_info)
�fd�f�cacher?�rtype_cacher>�e�liner2�cleanup_funcr
r
r�main�s^�


�
(rj)rr,r#rr �rr�__all__�hasattrr+rQrSr.rVr>�_multiprocessing�_posixshmem�update�
sem_unlink�
shm_unlink�objectr�_resource_trackerrrrrrjr
r
r
r�<module>s4

�
�w�h�5bytecode of module 'multiprocessing.resource_tracker'�u��b.��s8h)��N}�(hB&8�@s�dZddgZddlmZddlZddlZddlZddlZddlZej	dkrXddl
Z
dZnddlZdZej
ejBZd	Zer~d
ZndZdd
�ZGdd�d�ZdZGdd�d�ZdS)z�Provides shared memory for direct access across processes.

The API of this package is currently provisional. Refer to the
documentation for details.
�SharedMemory�
ShareableList�)�partialN�ntFT�z/psm_Zwnsm_cCsBttt�d}|dks td��tt�|�}t|�tks>t�|S)z6Create a random filename for the shared memory object.�z_SHM_NAME_PREFIX too long)�_SHM_SAFE_NAME_LENGTH�len�_SHM_NAME_PREFIX�AssertionError�secrets�	token_hex)�nbytes�name�r�3/usr/lib/python3.8/multiprocessing/shared_memory.py�_make_filename&s
rc@s�eZdZdZdZdZdZdZej	Z
dZer.dndZ
ddd	�Zd
d�Zdd
�Zdd�Zedd��Zedd��Zedd��Zdd�Zdd�ZdS)ra�Creates a new shared memory block or attaches to an existing
    shared memory block.

    Every shared memory block is assigned a unique name.  This enables
    one process to create a shared memory block with a particular name
    so that a different process can attach to that same shared memory
    block using that same name.

    As a resource for sharing data across processes, shared memory blocks
    may outlive the original process that created them.  When one process
    no longer needs access to a shared memory block that might still be
    needed by other processes, the close() method should be called.
    When a shared memory block is no longer needed by any process, the
    unlink() method should be called to ensure proper cleanup.N���i�TFrc
	Csl|dkstd��|r0ttjB|_|dkr0td��|dkrL|jtj@sLtd��t�rH|dkr�t�}ztj	||j|j
d�|_Wntk
r�YqZYnX||_
q�qZn.|jr�d|n|}tj	||j|j
d�|_||_
z<|r�|r�t�|j|�t�|j�}|j}t�|j|�|_Wn tk
�r*|���YnXddlm}||j
d	��n|�r�|dk�r^t�n|}t�tjtjtj|d
?d@|d@|�}zXt��}|tjk�r�|dk	�r�tt j!t�"t j!�|tj��nW��qNtjd||d
�|_W5t�|�X||_
�qV�qNnX||_
t�#tj$d|�}zt�%|tj$ddd�}	W5t�|�Xt�&|	�}tjd||d
�|_||_'t(|j�|_)dS)Nrz!'size' must be a positive integerz4'size' must be a positive number different from zeroz&'name' can only be None if create=True)�mode�/�)�register�
shared_memory� l��r)�tagnameF)*�
ValueError�_O_CREX�os�O_RDWR�_flags�O_EXCL�
_USE_POSIXr�_posixshmem�shm_open�_mode�_fd�FileExistsError�_name�_prepend_leading_slash�	ftruncate�fstat�st_size�mmap�_mmap�OSError�unlink�resource_trackerr�_winapi�CreateFileMapping�INVALID_HANDLE_VALUE�NULL�PAGE_READWRITE�CloseHandle�GetLastError�ERROR_ALREADY_EXISTS�errno�EEXIST�strerror�OpenFileMapping�
FILE_MAP_READ�
MapViewOfFile�VirtualQuerySize�_size�
memoryview�_buf)
�selfr�create�size�statsr�	temp_name�h_map�last_error_code�p_bufrrr�__init__Is��
�
�

�
��
zSharedMemory.__init__cCs&z|��Wntk
r YnXdS�N)�closer.�rCrrr�__del__�szSharedMemory.__del__cCs|j|jd|jffS)NF)�	__class__rrErNrrr�
__reduce__�s��zSharedMemory.__reduce__cCs|jj�d|j�d|j�d�S)N�(z, size=�))rP�__name__rrErNrrr�__repr__�szSharedMemory.__repr__cCs|jS)z4A memoryview of contents of the shared memory block.)rBrNrrr�buf�szSharedMemory.bufcCs.|j}tr*|jr*|j�d�r*|jdd�}|S)z4Unique name that identifies the shared memory block.rrN)r'r!r(�
startswith)rC�
reported_namerrrr�s

zSharedMemory.namecCs|jS)zSize in bytes.)r@rNrrrrE�szSharedMemory.sizecCsX|jdk	r|j��d|_|jdk	r4|j��d|_trT|jdkrTt�|j�d|_dS)zkCloses access to the shared memory from this instance but does
        not destroy the shared memory block.Nrr)rB�releaser-rMr!r%rrNrrrrM�s



zSharedMemory.closecCs2tr.|jr.ddlm}t�|j�||jd�dS)z�Requests that the underlying shared memory block be destroyed.

        In order to ensure proper cleanup of resources, unlink should be
        called once (and only once) across all processes which have access
        to the shared memory block.r)�
unregisterrN)r!r'r0rZr"�
shm_unlink)rCrZrrrr/�s
zSharedMemory.unlink)NFr)rT�
__module__�__qualname__�__doc__r'r%r-rBrrrr$r!r(rKrOrQrU�propertyrVrrErMr/rrrrr0s(
l




�utf8c@seZdZdZedededededdj	diZ
dZd	d
�dd
�dd
�d
d
�d�Ze
dd��Zd6dd�dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zed$d%��Zed&d'��Zed(d)��Zed*d+��Zed,d-��Zed.d/��Zed0d1��Zd2d3�Z d4d5�Z!dS)7ra�Pattern for a mutable list-like object shareable via a shared
    memory block.  It differs from the built-in list type in that these
    lists can not change their overall length (i.e. no append, insert,
    etc.)

    Because values are packed into a memoryview as bytes, the struct
    packing format for any storable value must require no more than 8
    characters to describe its format.�q�dzxxxxxxx?z%dsNzxxxxxx?x�cCs|SrLr��valuerrr�<lambda>
�zShareableList.<lambda>cCs|�d��t�S�N�)�rstrip�decode�	_encodingrdrrrrfrgcCs
|�d�Srh)rjrdrrrrfrgcCsdSrLr)�_valuerrrrf
rg)rrr�cCs:t|ttdjf�sdSt|t�r$dSt|t�r2dSdSdS)z�Used in concert with _back_transforms_mapping to convert values
        into the appropriate Python objects when retrieving them from
        the list as well as when storing them.Nrrrrn)�
isinstance�str�bytesrPrdrrr�_extract_recreation_codes

z&ShareableList._extract_recreation_code�rcs�|dk	r��fdd�|D�}t|��_tdd�|D���jks@t�t�fdd�|D���_�fdd�|D�}t�d�jd�	|��j
�j�}nd	}|dk	r�|dkr�t|��_
nt|d
|d��_
|dk	�rjt�tjd�j�j
jd�jf�j��tjd�	|��j
j�jf�fd
d�|D���tj�j
�j
j�jf�fdd�|D���tj�j�j
j�jf|��n t���_t��j�j
jd	��_dS)NcsPg|]H}t|ttf�s$�jt|�n&�jt|��jt|��jdf�qS)r)rorprq�_types_mapping�type�
_alignmentr	��.0�itemrNrr�
<listcomp> s���z*ShareableList.__init__.<locals>.<listcomp>css|]}t|�dkVqdS)rcN)r	�rx�fmtrrr�	<genexpr>)sz)ShareableList.__init__.<locals>.<genexpr>c3s0|](}|ddkr�jnt|dd��VqdS)r�sN)rv�intr{rNrrr}*s�csg|]}��|��qSr)rrrwrNrrrz.sra�rcT)rDrErc3s&|]}t|t�r|���n|VqdSrL)rorp�encode�rx�v��_encrrr}Msc3s|]}|���VqdSrL)r�r�r�rrr}Ss)r	�	_list_len�sumr�tuple�_allocated_bytes�struct�calcsize�_format_size_metainfo�join�_format_packing_metainfo�_format_back_transform_codesr�shmrl�	pack_intorV�_offset_data_start�_offset_packing_formats�_offset_back_transform_codes�unpack_from)rC�sequencer�_formats�_recreation_codes�requested_sizer)r�rCrrKs|
�
�

�����
��������
�zShareableList.__init__cCsj|dkr|n||j}||jks*|jdkr2td��t�d|jj|j|d�d}|�d�}|�t	�}|S)z>Gets the packing format for a single value stored in the list.r� Requested position out of range.�8srcri)
r��
IndexErrorr�r�r�rVr�rjrkrl)rC�positionr�r|�
fmt_as_strrrr�_get_packing_formatds��

z!ShareableList._get_packing_formatcCs\|dkr|n||j}||jks*|jdkr2td��t�d|jj|j|�d}|j|}|S)z9Gets the back transformation function for a single value.rr��b)r�r�r�r�r�rVr��_back_transforms_mapping)rCr��transform_code�transform_functionrrr�_get_back_transformts��
z!ShareableList._get_back_transformcCs~|dkr|n||j}||jks*|jdkr2td��t�d|jj|j|d|�t��|�	|�}t�d|jj|j
||�dS)zvSets the packing format and back transformation code for a
        single value in the list at the specified position.rr�r�rcr�N)r�r�r�r�r�rVr�r�rlrrr�)rCr�r�rer�rrr�!_set_packing_format_and_transform�s �
�z/ShareableList._set_packing_format_and_transformcCsjz6|jt|jd|��}t�|�|�|jj|�\}Wntk
rRtd��YnX|�	|�}||�}|S)Nzindex out of range)
r�r�r�r�r�r�r�rVr�r�)rCr��offsetr��back_transformrrr�__getitem__�s��

zShareableList.__getitem__cCs�z&|jt|jd|��}|�|�}Wntk
rBtd��YnXt|ttf�sf|jt	|�}|}nZt|t�rz|�
t�n|}t|�|j|kr�t
d��|ddkr�|}n|jt|j|f}|�|||�t�||jj||�dS)Nzassignment index out of rangez(bytes/str item exceeds available storagerr~)r�r�r�r�r�rorprqrtrur�rlr	rr�r�r�r�rV)rCr�rer��current_format�
new_format�
encoded_valuerrr�__setitem__�s6�����zShareableList.__setitem__cCst|j|jjd�dfS)Nrsr)rrPr�rrNrrrrQ�szShareableList.__reduce__cCst�d|jjd�dS)Nrar)r�r�r�rVrNrrr�__len__�szShareableList.__len__cCs"|jj�dt|��d|jj�d�S)NrRz, name=rS)rPrT�listr�rrNrrrrU�szShareableList.__repr__csd��fdd�t�j�D��S)z>The struct packing format used by all currently stored values.r�c3s|]}��|�VqdSrL)r�)rx�irNrrr}�sz'ShareableList.format.<locals>.<genexpr>)r��ranger�rNrrNr�format�s�zShareableList.formatcCs|j�d�S)z=The struct packing format used for metainfo on storage sizes.ra�r�rNrrrr��sz#ShareableList._format_size_metainfocCs
d|jS)z?The struct packing format used for the values' packing formats.r�r�rNrrrr��sz&ShareableList._format_packing_metainfocCs
d|jS)z?The struct packing format used for the values' back transforms.r�r�rNrrrr��sz*ShareableList._format_back_transform_codescCs|jddS)Nrrcr�rNrrrr��sz ShareableList._offset_data_startcCs|jt|j�SrL)r�r�r�rNrrrr��sz%ShareableList._offset_packing_formatscCs|j|jdS)Nrc)r�r�rNrrrr��sz*ShareableList._offset_back_transform_codescst�fdd�|D��S)zCL.count(value) -> integer -- return number of occurrences of value.c3s|]}�|kVqdSrLr)rx�entryrdrrr}�sz&ShareableList.count.<locals>.<genexpr>)r�)rCrerrdr�count�szShareableList.countcCs4t|�D]\}}||kr|Sqt|�d���dS)zpL.index(value) -> integer -- return first index of value.
        Raises ValueError if the value is not present.z not in this containerN)�	enumerater)rCrer�r�rrr�index�s
zShareableList.index)N)"rTr\r]r^r�float�boolrprqrPrtrvr��staticmethodrrrKr�r�r�r�r�rQr�rUr_r�r�r�r�r�r�r�r�r�rrrrr�s^
��

F






)r^�__all__�	functoolsrr,rr9r�rrr1r!r"�O_CREATr rrr
rrrlrrrrr�<module>s,

E�h�2bytecode of module 'multiprocessing.shared_memory'�u��b.���h)��N}�(hBy�@sBddlZddlZddlmZddlmZddlmZmZejZ	dddd	d
dgZ
ejejej
ejejejejejejejejejejejd�Zd
d�Zdd�Zdd�Zddd�dd�Zddd�dd	�Zdd
�Zd&dd�Z dd�Z!dd�Z"dd�Z#dZ$iZ%e�&�Z'Gdd�de(�Z)Gd d!�d!e)�Z*Gd"d#�d#e)�Z+Gd$d%�d%e+�Z,dS)'�N�)�heap)�get_context)�	reduction�assert_spawning�RawValue�RawArray�Value�Array�copy�synchronized)�c�u�b�B�h�H�i�I�l�L�q�Q�f�dcCs t�|�}t�|�}t||d�S�N)�ctypes�sizeofr�
BufferWrapper�
rebuild_ctype)�type_�size�wrapper�r#�2/usr/lib/python3.8/multiprocessing/sharedctypes.py�
_new_value's

r%cGs<t�||�}t|�}t�t�|�dt�|��|j|�|S)z>
    Returns a ctypes object allocated from shared memory
    r)�typecode_to_type�getr%r�memset�	addressofr�__init__)�typecode_or_type�argsr �objr#r#r$r,s

cCsjt�||�}t|t�rD||}t|�}t�t�|�dt�|��|S|t	|�}t|�}|j
|�|SdS)z=
    Returns a ctypes array allocated from shared memory
    rN)r&r'�
isinstance�intr%rr(r)r�lenr*)r+�size_or_initializerr r-�resultr#r#r$r6s

T)�lock�ctxcGsXt|f|��}|dkr|S|dkr4|p*t�}|��}t|d�sJtd|��t|||d�S)z6
    Return a synchronization wrapper for a Value
    F�TN�acquire�%r has no method 'acquire'�r4)rr�RLock�hasattr�AttributeErrorr)r+r3r4r,r-r#r#r$r	Fs

cCsTt||�}|dkr|S|dkr0|p&t�}|��}t|d�sFtd|��t|||d�S)z9
    Return a synchronization wrapper for a RawArray
    Fr5r6r7r8)rrr9r:r;r)r+r1r3r4r-r#r#r$r
Ts


cCstt|��}|t�|�d<|S)Nr)r%�typer�pointer)r-�new_objr#r#r$rbscCs�t|t�rtd��|pt�}t|tj�r4t|||�St|tj�rd|jtj	krXt
|||�St|||�St|�}zt
|}WnRtk
r�dd�|jD�}dd�|D�}d|j}t|tf|�}t
|<YnX||||�SdS)Nzobject already synchronizedcSsg|]}|d�qS)rr#)�.0�fieldr#r#r$�
<listcomp>vsz synchronized.<locals>.<listcomp>cSsi|]}|t|��qSr#)�
make_property)r?�namer#r#r$�
<dictcomp>wsz synchronized.<locals>.<dictcomp>�Synchronized)r.�SynchronizedBase�AssertionErrorrr�_SimpleCDatarEr
�_type_�c_char�SynchronizedString�SynchronizedArrayr<�class_cache�KeyError�_fields_�__name__)r-r3r4�cls�scls�namesr�	classnamer#r#r$rgs"

cCs@t|�t|tj�r(t|j|j|jffStt|�|jdffSdSr)	rr.rr
rrI�_wrapper�_length_r<)r-r#r#r$�reduce_ctype�srWcCs8|dk	r||}t�|t�|��}|�|�}||_|Sr)�_ForkingPickler�registerrW�create_memoryview�from_bufferrU)r r"�length�bufr-r#r#r$r�s
rcCsPz
t|WStk
rJi}tt|fd|�||t|<||YSXdS)N�)�
prop_cacherN�exec�template)rCrr#r#r$rB�s
rBz�
def get%s(self):
    self.acquire()
    try:
        return self._obj.%s
    finally:
        self.release()
def set%s(self, value):
    self.acquire()
    try:
        self._obj.%s = value
    finally:
        self.release()
%s = property(get%s, set%s)
c@sFeZdZddd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dS)rFNcCsB||_|r||_n|ptdd�}|��|_|jj|_|jj|_dS)NT)�force)�_obj�_lockrr9r6�release)�selfr-r3r4r#r#r$r*�s

zSynchronizedBase.__init__cCs
|j��Sr)rd�	__enter__�rfr#r#r$rg�szSynchronizedBase.__enter__cGs|jj|�Sr)rd�__exit__)rfr,r#r#r$ri�szSynchronizedBase.__exit__cCst|�t|j|jffSr)rrrcrdrhr#r#r$�
__reduce__�szSynchronizedBase.__reduce__cCs|jSr�rcrhr#r#r$�get_obj�szSynchronizedBase.get_objcCs|jSr)rdrhr#r#r$�get_lock�szSynchronizedBase.get_lockcCsdt|�j|jfS)Nz<%s wrapper for %s>)r<rPrcrhr#r#r$�__repr__�szSynchronizedBase.__repr__)NN)
rP�
__module__�__qualname__r*rgrirjrlrmrnr#r#r#r$rF�s

rFc@seZdZed�ZdS)rE�valueN)rProrprBrqr#r#r#r$rE�srEc@s4eZdZdd�Zdd�Zdd�Zdd�Zd	d
�ZdS)rLcCs
t|j�Sr)r0rcrhr#r#r$�__len__�szSynchronizedArray.__len__c
Cs&|�|j|W5QR�SQRXdSrrk)rfrr#r#r$�__getitem__�szSynchronizedArray.__getitem__c	Cs|�||j|<W5QRXdSrrk)rfrrqr#r#r$�__setitem__�szSynchronizedArray.__setitem__c
Cs*|�|j||�W5QR�SQRXdSrrk)rf�start�stopr#r#r$�__getslice__�szSynchronizedArray.__getslice__c	Cs"|�||j||�<W5QRXdSrrk)rfrurv�valuesr#r#r$�__setslice__�szSynchronizedArray.__setslice__N)rProrprrrsrtrwryr#r#r#r$rL�s
rLc@seZdZed�Zed�ZdS)rKrq�rawN)rProrprBrqrzr#r#r#r$rK�srK)NN)-r�weakref�rr�contextrr�ForkingPicklerrX�__all__rJ�c_wchar�c_byte�c_ubyte�c_short�c_ushort�c_int�c_uint�c_long�c_ulong�
c_longlong�c_ulonglong�c_float�c_doubler&r%rrr	r
rrrWrrBrar_�WeakKeyDictionaryrM�objectrFrErLrKr#r#r#r$�<module>
sL�


	 �h�1bytecode of module 'multiprocessing.sharedctypes'�u��b.��]h)��N}�(hB�@s$ddlZddlZddlZddlZddlmZmZddlmZddlm	Z	ddlm
Z
ddd	d
ddd
gZejdkrzdZ
dZneedd�Z
ej���d�Zer�ej�ejd�anejadd	�Zdd
�Zdd�Zdd�Zdd�Zd&dd�Zdd�Zdd�Zdd�ZgZ dd �Z!d!d"�Z"d#d$�Z#d%d
�Z$dS)'�N�)�get_start_method�set_start_method)�process)�	reduction)�util�_main�freeze_support�set_executable�get_executable�get_preparation_data�get_command_line�import_main_path�win32F�frozenzpythonservice.exez
python.execCs|adS�N��_python_exe)�exe�r�+/usr/lib/python3.8/multiprocessing/spawn.pyr
)scCstSrrrrrrr-scCs$t|�dkr|ddkrdSdSdS)z=
    Return whether commandline indicates we are forking
    �r�--multiprocessing-forkTFN)�len)�argvrrr�
is_forking4srcCsdttj�r`i}tjdd�D]0}|�d�\}}|dkr@d||<qt|�||<qtf|�t��dS)zE
    Run code for process object if this in not the main process
    rN�=�None)r�sysr�split�int�
spawn_main�exit)�kwds�arg�name�valuerrrr	>s


cKshttdd�r(tjdgdd�|��D�Sd}|d�dd	�|��D��;}t��}tg|d
|dgSdS)zJ
    Returns prefix of command line used for spawning a child process
    rFrcSsg|]}d|�qS)�%s=%rr��.0�itemrrr�
<listcomp>Tsz$get_command_line.<locals>.<listcomp>z<from multiprocessing.spawn import spawn_main; spawn_main(%s)z, css|]}d|VqdS)r'Nrr(rrr�	<genexpr>Wsz#get_command_line.<locals>.<genexpr>z-cN)�getattrr�
executable�items�joinr�_args_from_interpreter_flagsr)r#�prog�optsrrrr
Ns�cCs�ttj�std��tjdkrrddl}ddl}|dk	rL|�|j|j	Bd|�}nd}t
j||d�}|�|t
j�}|}n"ddlm}	||	j_|}t
�|�}t||�}
t�|
�dS)	z7
    Run code specified by data received over pipe
    zNot forkingrrNF)�source_processr)�resource_tracker)rrr�AssertionError�platform�msvcrt�_winapiZOpenProcessZSYNCHRONIZEZPROCESS_DUP_HANDLEr�	duplicate�open_osfhandle�os�O_RDONLY�r5�_resource_tracker�_fd�duprr")�pipe_handle�
parent_pid�
tracker_fdr8r9r4�
new_handle�fd�parent_sentinelr5�exitcoderrrr!\s,

��

r!c	Cs`tj|ddd��@}dt��_z$tj�|�}t|�tj�|�}W5t��`XW5QRX|�	|�S)N�rbT)�closefd)
r<�fdopenr�current_process�_inheritingr�pickle�load�prepare�
_bootstrap)rFrG�from_parent�preparation_data�selfrrrrxs
cCstt��dd�rtd��dS)NrMFa
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.)r-rrL�RuntimeErrorrrrr�_check_not_importing_main�srVcCst�ttjt��jd�}tjdk	r2tj��|d<t	j
��}z|�d�}Wnt
k
r^YnXtj||<|j||t	jtjt��t�d�t	jd}t|jdd�}|dk	r�||d<nft	jd	ks�t�st�st|d
d�}|dk	�rtj
�|��s
tjdk	�r
tj
�tj|�}tj
�|�|d<|S)zM
    Return info about parent needed by child to unpickle process object
    )�
log_to_stderr�authkeyN�	log_levelr>)r%�sys_path�sys_argv�orig_dir�dir�start_method�__main__r%�init_main_from_namer�__file__�init_main_from_path)rV�dictr�_log_to_stderrrrLrX�_logger�getEffectiveLevelr�path�copy�index�
ValueError�ORIGINAL_DIR�updaterr<�getcwdr�modulesr-�__spec__r7�WINEXE�
WINSERVICE�isabsr0�normpath)r%�drZ�i�main_module�
main_mod_name�	main_pathrrrr�sD�


�


�cCs�d|kr|dt��_d|kr,|dt��_d|krD|drDt��d|kr^t���|d�d|krp|dt_	d|kr�|dt_
d|kr�t�|d�d|kr�|dt_
d	|kr�t|d	d
d�d|kr�t|d�nd
|kr�t|d
�dS)zE
    Try to get current process ready to unpickle process object
    r%rXrWrYrZr[r]r\r^T)�forcer`rbN)rrLr%rXrrW�
get_logger�setLevelrrgrr<�chdirrkr�_fixup_main_from_name�_fixup_main_from_path)�datarrrrP�s,


rPcCs~tjd}|dks|�d�r dSt|jdd�|kr6dSt�|�t�d�}t	j
|ddd�}|j�|�|tjd<tjd<dS)Nr_z	.__main__r%�__mp_main__T)�run_name�	alter_sys)
rrn�endswithr-ro�old_main_modules�append�types�
ModuleType�runpy�
run_module�__dict__rl)�mod_name�current_mainrv�main_contentrrrr}�s


�r}cCs�tjd}tj�tj�|��d}|dkr.dSt|dd�|krBdSt�|�t	�
d�}tj|dd�}|j
�|�|tjd<tjd<dS)Nr_rZipythonrar�)r�)rrnr<rg�splitext�basenamer-r�r�r�r�r��run_pathr�rl)rxr��	main_namervr�rrrr~	s


�r~cCst|�dS)z<
    Set sys.modules['__main__'] to module at main_path
    N)r~)rxrrrr%s)NN)%r<rr�r�r>rrr�contextrr�__all__r7rprqr-r.�lowerr�rgr0�exec_prefixrr
rrr	r
r!rrVrr�rPr}r~rrrrr�<module>sD�


2&�h�*bytecode of module 'multiprocessing.spawn'�u��b.��V,h)��N}�(hB,�@s,ddddddgZddlZddlZddlZddlZddlZdd	lmZdd
lmZddlm	Z	zddlm
Z
mZWnek
r�ed
��YnXe
ed��\ZZej
jZGdd�de�Z
Gdd�de
�ZGdd�de�ZGdd�de
�ZGdd�de
�ZGdd�de�ZGdd�de�ZGdd�dej�ZdS)�Lock�RLock�	Semaphore�BoundedSemaphore�	Condition�Event�N�)�context)�process)�util)�SemLock�
sem_unlinkz�This platform lacks a functioning sem_open implementation, therefore, the required synchronization primitives needed will not function, see issue 3770.�c@s\eZdZe��Zdd�Zedd��Zdd�Z	dd�Z
d	d
�Zdd�Zd
d�Z
edd��ZdS)rc	Cs�|dkrtj��}|��}tjdkp*|dk}td�D]>}z t�||||�	�|�}|_
Wntk
rlYq4Xq|q4td��t�
d|j�|��tjdkr�dd�}	t�||	�|j
jdk	r�dd	lm}
|
|j
jd
�tj|tj|j
jfdd�dS)
N�win32�fork�dzcannot find name for semaphorezcreated semlock with handle %scSs|j��dS�N)�_semlock�_after_fork)�obj�r�1/usr/lib/python3.8/multiprocessing/synchronize.pyrGsz%SemLock.__init__.<locals>._after_forkr)�register�	semaphorer)�exitpriority)r	�_default_context�get_context�get_start_method�sys�platform�range�_multiprocessingr�
_make_namer�FileExistsErrorr�debug�handle�
_make_methods�register_after_fork�name�resource_trackerr�Finalize�_cleanup)�self�kind�value�maxvalue�ctxr(�
unlink_now�i�slrrrrr�__init__2s8
�
�zSemLock.__init__cCs"ddlm}t|�||d�dS)Nr)�
unregisterr)r)r5r
)r(r5rrrr+TszSemLock._cleanupcCs|jj|_|jj|_dSr)r�acquire�release�r,rrrr&Zs
zSemLock._make_methodscCs
|j��Sr)r�	__enter__r8rrrr9^szSemLock.__enter__cGs|jj|�Sr)r�__exit__�r,�argsrrrr:aszSemLock.__exit__cCsDt�|�|j}tjdkr,t���|j�}n|j}||j|j	|j
fS)Nr)r	�assert_spawningrrr�get_spawning_popen�duplicate_for_childr%r-r/r()r,r3�hrrr�__getstate__ds

zSemLock.__getstate__cCs,tjj|�|_t�d|d�|��dS)Nz recreated blocker with handle %rr)r!r�_rebuildrrr$r&�r,�staterrr�__setstate__mszSemLock.__setstate__cCsdt��jdttj�fS)Nz%s-%sZ	semprefix)r
�current_process�_config�nextr�_randrrrrr"rs�zSemLock._make_nameN)�__name__�
__module__�__qualname__�tempfile�_RandomNameSequencerIr4�staticmethodr+r&r9r:rArEr"rrrrr.s"
	rc@s&eZdZd	dd�Zdd�Zdd�ZdS)
rrcCstj|t|t|d�dS�N�r0)rr4�	SEMAPHORE�
SEM_VALUE_MAX�r,r.r0rrrr4}szSemaphore.__init__cCs
|j��Sr)r�
_get_valuer8rrr�	get_value�szSemaphore.get_valuecCs8z|j��}Wntk
r&d}YnXd|jj|fS)N�unknownz<%s(value=%s)>)rrU�	Exception�	__class__rJ�r,r.rrr�__repr__�s

zSemaphore.__repr__N)r)rJrKrLr4rVr[rrrrr{s
c@seZdZddd�Zdd�ZdS)rrcCstj|t|||d�dSrP�rr4rRrTrrrr4�szBoundedSemaphore.__init__cCs>z|j��}Wntk
r&d}YnXd|jj||jjfS)NrWz<%s(value=%s, maxvalue=%s)>)rrUrXrYrJr/rZrrrr[�s
�zBoundedSemaphore.__repr__N)r�rJrKrLr4r[rrrrr�s
c@seZdZdd�Zdd�ZdS)rcCstj|tdd|d�dS�NrrQr\�r,r0rrrr4�sz
Lock.__init__cCs�zf|j��r8t��j}t��jdkrd|dt��j7}n,|j��dkrLd}n|j��dkr`d}nd}Wnt	k
r~d}YnXd	|j
j|fS)
N�
MainThread�|r�Noner�SomeOtherThread�SomeOtherProcessrWz<%s(owner=%s)>)r�_is_miner
rFr(�	threading�current_threadrU�_countrXrYrJ)r,r(rrrr[�s


z
Lock.__repr__Nr]rrrrr�sc@seZdZdd�Zdd�ZdS)rcCstj|tdd|d�dSr^)rr4�RECURSIVE_MUTEXr_rrrr4�szRLock.__init__cCs�z||j��rBt��j}t��jdkr6|dt��j7}|j��}n8|j��dkrZd\}}n |j��dkrrd\}}nd\}}Wnt	k
r�d\}}YnXd	|j
j||fS)
Nr`rar)rbrr)rc�nonzero)rdrj)rWrW�<%s(%s, %s)>)rrer
rFr(rfrgrhrUrXrYrJ)r,r(�countrrrr[�s



zRLock.__repr__Nr]rrrrr�sc@sleZdZddd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	ddd�Z
ddd�Zdd�Zddd�Z
dS)rNcCs>|p
|��|_|�d�|_|�d�|_|�d�|_|��dS�Nr)r�_lockr�_sleeping_count�_woken_count�_wait_semaphorer&)r,�lockr0rrrr4�s
zCondition.__init__cCst�|�|j|j|j|jfSr)r	r=rnrorprqr8rrrrA�s

�zCondition.__getstate__cCs |\|_|_|_|_|��dSr)rnrorprqr&rCrrrrE�s
�
zCondition.__setstate__cCs
|j��Sr)rnr9r8rrrr9�szCondition.__enter__cGs|jj|�Sr)rnr:r;rrrr:�szCondition.__exit__cCs|jj|_|jj|_dSr)rnr6r7r8rrrr&�s
zCondition._make_methodscCsJz|jj��|jj��}Wntk
r4d}YnXd|jj|j|fS)NrWrk)rorrUrprXrYrJrn)r,�num_waitersrrrr[�s

�
zCondition.__repr__c	Cs~|jj��std��|j��|jj��}t|�D]}|j��q2z|j
�	d|�W�S|j��t|�D]}|j�	�qhXdS)Nz,must acquire() condition before using wait()T)rnrre�AssertionErrorror7rhr rpr6rq)r,�timeoutrlr2rrr�wait�s�

zCondition.waitrcCs�|jj��std��|j�d�r(td��|j�d�rN|j�d�}|s(td��q(d}||krz|j�d�rz|j��|d7}qR|r�t	|�D]}|j��q�|j�d�r�q�dS)Nzlock is not ownedFz<notify: Should not have been able to acquire _wait_semaphorez>notify: Bug in sleeping_count.acquire- res should not be Falserr)
rnrrertrqr6rpror7r )r,�n�res�sleepersr2rrr�notifys$��

zCondition.notifycCs|jtjd�dS)N)rw)rzr�maxsizer8rrr�
notify_all(szCondition.notify_allcCsd|�}|r|S|dk	r$t��|}nd}d}|s`|dk	rN|t��}|dkrNq`|�|�|�}q,|Srm)�time�	monotonicrv)r,�	predicateru�result�endtime�waittimerrr�wait_for+s
zCondition.wait_for)N)N)r)N)rJrKrLr4rArEr9r:r&r[rvrzr|r�rrrrr�s


c@s6eZdZdd�Zdd�Zdd�Zdd�Zdd
d�Zd	S)
rcCs |�|���|_|�d�|_dSrm)rr�_condr�_flagr_rrrr4CszEvent.__init__c	CsD|j�4|j�d�r,|j��W5QR�dSW5QR�dSQRXdS�NFT)r�r�r6r7r8rrr�is_setGs

zEvent.is_setc	Cs6|j�&|j�d�|j��|j��W5QRXdS�NF)r�r�r6r7r|r8rrr�setNs
z	Event.setc	Cs"|j�|j�d�W5QRXdSr�)r�r�r6r8rrr�clearTszEvent.clearNc	Csh|j�X|j�d�r |j��n|j�|�|j�d�rP|j��W5QR�dSW5QR�dSQRXdSr�)r�r�r6r7rv)r,rurrrrvXs
z
Event.wait)N)rJrKrLr4r�r�r�rvrrrrrAs
c@sZeZdZddd�Zdd�Zdd�Zedd	��Zejd
d	��Zedd��Z	e	jd
d��Z	dS)�BarrierNc	CsRddl}ddlm}||�d�d�}|��}|�|||||f�d|_d|_dS)Nrr)�
BufferWrapperr2r)�struct�heapr��calcsizerrE�_staterh)	r,�parties�actionrur0r�r��wrapper�condrrrr4jszBarrier.__init__cCs.|\|_|_|_|_|_|j���d�|_dS)Nr2)�_parties�_action�_timeoutr��_wrapper�create_memoryview�cast�_arrayrCrrrrEss
�zBarrier.__setstate__cCs|j|j|j|j|jfSr)r�r�r�r�r�r8rrrrAxs�zBarrier.__getstate__cCs
|jdSrm�r�r8rrrr�|szBarrier._statecCs||jd<dSrmr�rZrrrr��scCs
|jdS�Nrr�r8rrrrh�szBarrier._countcCs||jd<dSr�r�rZrrrrh�s)NN)
rJrKrLr4rErA�propertyr��setterrhrrrrr�hs
	


r�)�__all__rfrrMr!r}�r	r
rrr
�ImportError�listr rirRrS�objectrrrrrrr�rrrr�<module>s8�	Mo'�h�0bytecode of module 'multiprocessing.synchronize'�u��b.��-h)��N}�(hB�,�@s�ddlZddlZddlZddlZddlZddlZddlmZddlm	Z	ddddd	d
ddd
ddddddgZ
dZdZdZ
dZdZdZdZdadadd�Zdd�Zdd�Zdd�Zdd	�Zd@d d
�Zd!d"�Zd#d$�Ze�Zd%d&�Zd'd�Ze��Z e�!�Z"d(d)�Z#d*d�Z$iZ%e�!�Z&Gd+d�de'�Z(dAd,d-�Z)d.d
�Z*da+eee)e	j,e	j-fd/d0�Z.e�/e.�Gd1d�de'�Z0Gd2d�dej1�Z2ze�3d3�Z4Wne5k
�r�d4Z4YnXd5d�Z6d6d7�Z7d8d9�Z8d:d;�Z9d<d=�Z:d>d?�Z;dS)B�N)�_args_from_interpreter_flags�)�process�	sub_debug�debug�info�sub_warning�
get_logger�
log_to_stderr�get_temp_dir�register_after_fork�
is_exiting�Finalize�ForkAwareThreadLock�ForkAwareLocal�close_all_fds_except�SUBDEBUG�
SUBWARNING��
���multiprocessingz+[%(levelname)s/%(processName)s] %(message)sFcGstrtjt|f|��dS�N)�_logger�logr��msg�args�r�*/usr/lib/python3.8/multiprocessing/util.pyr,scGstrtjt|f|��dSr)rr�DEBUGrrrr r0scGstrtjt|f|��dSr)rr�INFOrrrr r4scGstrtjt|f|��dSr)rrrrrrr r8scCs|ddl}|��z\tsj|�t�adt_ttd�rFt�	t
�t�t
�n$tj�
t
dif�tj�t
dif�W5|��XtS)z0
    Returns logger used by multiprocessing
    rN�
unregisterr)�logging�_acquireLock�_releaseLockr�	getLogger�LOGGER_NAME�	propagate�hasattr�atexitr#�_exit_function�register�
_exithandlers�remove�append)r$rrr r	<s



cCsJddl}t�}|�t�}|��}|�|�|�|�|rB|�|�dat	S)zB
    Turn on logging and add a handler which prints to stderr
    rNT)
r$r	�	Formatter�DEFAULT_LOGGING_FORMAT�
StreamHandler�setFormatter�
addHandler�setLevel�_log_to_stderrr)�levelr$�logger�	formatter�handlerrrr r
Ws



cCs tjdkrdSttd�rdSdS)N�linuxT�getandroidapilevelF)�sys�platformr*rrrr �#_platform_supports_abstract_socketsls


r@cCs@|sdSt|t�r|ddkSt|t�r4|ddkStd��dS)NFr�z(address type of {address!r} unrecognized)�
isinstance�bytes�str�	TypeError)�addressrrr �is_abstract_socket_namespacets

rGcCs&||�t��}|dk	r"d|jd<dS)N�tempdir)r�current_process�_config)�rmtreerHrIrrr �_remove_temp_dir�srLcCsft��j�d�}|dkrbddl}ddl}|jdd�}td|�tdt	|j
|fdd�|t��jd<|S)NrHrzpymp-)�prefixzcreated temp directory %si����)r�exitpriority)rrIrJ�get�shutil�tempfile�mkdtemprrrLrK)rHrPrQrrr r�s
�cCsftt���}|��|D]H\\}}}}z||�Wqtk
r^}ztd|�W5d}~XYqXqdS)Nz after forker raised exception %s)�list�_afterfork_registry�items�sort�	Exceptionr)rU�index�ident�func�obj�errr �_run_after_forkers�sr]cCs|ttt�t|�|f<dSr)rT�next�_afterfork_counter�id)r[rZrrr r�sc@sFeZdZdZddd�Zdeeejfdd�Z	dd	�Z
d
d�Zdd
�ZdS)rzA
    Class which supports object finalization using weakrefs
    rNcCs�|dk	r&t|t�s&td�|t|����|dk	r>t�||�|_n|dkrNtd��||_	||_
|p`i|_|tt
�f|_t��|_|t|j<dS)Nz3Exitpriority ({0!r}) must be None or int, not {1!s}z+Without object, exitpriority cannot be None)rB�intrE�format�type�weakref�ref�_weakref�
ValueError�	_callback�_args�_kwargsr^�_finalizer_counter�_key�os�getpid�_pid�_finalizer_registry)�selfr[�callbackr�kwargsrNrrr �__init__�s"��

zFinalize.__init__cCs�z||j=Wntk
r(|d�YnbX|j|�krD|d�d}n$|d|j|j|j�|j|j|j�}d|_|_|_|_|_|SdS)zQ
        Run the callback unless it has already been called or cancelled
        zfinalizer no longer registeredz+finalizer ignored because different processNz/finalizer calling %s with args %s and kwargs %s)rl�KeyErrorrorhrirjrf)rq�wrrprrn�resrrr �__call__�s$��zFinalize.__call__cCsDzt|j=Wntk
r Yn Xd|_|_|_|_|_dS)z3
        Cancel finalization of the object
        N)rprlrurfrhrirj�rqrrr �cancel�s��zFinalize.cancelcCs
|jtkS)zS
        Return whether this finalizer is still waiting to invoke callback
        )rlrpryrrr �still_active�szFinalize.still_activec	Cs�z|��}Wnttfk
r(d}YnX|dkr>d|jjSd|jjt|jd|j�f}|jrr|dt|j�7}|j	r�|dt|j	�7}|j
ddk	r�|dt|j
d�7}|dS)	Nz<%s object, dead>z<%s object, callback=%s�__name__z, args=z	, kwargs=rz, exitpriority=�>)rf�AttributeErrorrE�	__class__r|�getattrrhrirDrjrl)rqr[�xrrr �__repr__�s"
�zFinalize.__repr__)rNN)
r|�
__module__�__qualname__�__doc__rtrprrmrnrxrzr{r�rrrr r�s
�
c	s�tdkrdS�dkrdd��n�fdd���fdd�tt�D�}|jdd�|D]P}t�|�}|dk	rPtd	|�z
|�WqPtk
r�d
dl}|��YqPXqP�dkr�t��dS)z�
    Run all finalizers whose exit priority is not None and at least minpriority

    Finalizers with highest priority are called first; finalizers with
    the same priority will be called in reverse order of creation.
    NcSs|ddk	S�Nrr��prrr �<lambda>�z!_run_finalizers.<locals>.<lambda>cs|ddk	o|d�kSr�rr�)�minpriorityrr r�r�csg|]}�|�r|�qSrr)�.0�key)�frr �
<listcomp>#sz#_run_finalizers.<locals>.<listcomp>T)�reversez
calling %sr)	rprSrVrOrrW�	traceback�	print_exc�clear)r��keysr��	finalizerr�r)r�r�r �_run_finalizerss$



r�cCstp
tdkS)z6
    Returns true if the process is shutting down
    N)�_exitingrrrr r
8scCs�ts�da|d�|d�|d�|�dk	rr|�D] }|jr0|d|j�|j��q0|�D]}|d|j�|��qX|d�|�dS)NTzprocess shutting downz2running all "atexit" finalizers with priority >= 0rz!calling terminate() for daemon %szcalling join() for process %sz)running the remaining "atexit" finalizers)r��daemon�name�_popen�	terminate�join)rrr��active_childrenrIr�rrr r,@s	



r,c@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
rcCs|��t|tj�dSr)�_resetrrryrrr rtqszForkAwareThreadLock.__init__cCs"t��|_|jj|_|jj|_dSr)�	threading�Lock�_lock�acquire�releaseryrrr r�us

zForkAwareThreadLock._resetcCs
|j��Sr)r��	__enter__ryrrr r�zszForkAwareThreadLock.__enter__cGs|jj|�Sr)r��__exit__)rqrrrr r�}szForkAwareThreadLock.__exit__N)r|r�r�rtr�r�r�rrrr rpsc@seZdZdd�Zdd�ZdS)rcCst|dd��dS)NcSs
|j��Sr)�__dict__r�)r[rrr r��r�z)ForkAwareLocal.__init__.<locals>.<lambda>)rryrrr rt�szForkAwareLocal.__init__cCst|�dfS)Nr)rcryrrr �
__reduce__�szForkAwareLocal.__reduce__N)r|r�r�rtr�rrrr r�s�SC_OPEN_MAX�cCsbt|�dtg}|��|dtks,td��tt|�d�D] }t�||d||d�q<dS)N���zfd too larger)rS�MAXFDrV�AssertionError�range�lenrm�
closerange)�fds�irrr r�s
c	Cs�tjdkrdSztj��Wnttfk
r4YnXz@t�tjtj�}zt|dd�t_Wnt�|��YnXWnttfk
r�YnXdS)NF)�closefd)	r>�stdin�close�OSErrorrgrm�open�devnull�O_RDONLY)�fdrrr �_close_stdin�s

r�c	CsTztj��Wnttfk
r&YnXztj��Wnttfk
rNYnXdSr)r>�stdout�flushr~rg�stderrrrrr �_flush_std_streams�sr�cCsxddl}tttt|���}t��\}}z6|�|t�	|�gd|dddddddd||ddd�W�St�|�t�|�XdS)NrTr�F)
�_posixsubprocess�tuple�sorted�maprarm�piper��	fork_exec�fsencode)�pathr�passfdsr��errpipe_read�
errpipe_writerrr �spawnv_passfds�s2
�
r�cGs|D]}t�|�qdS)z/Close each file descriptor given as an argumentN)rmr�)r�r�rrr �	close_fds�sr�cCsZddlm}t��ddlm}|j��ddlm}|j	��t
�|��|��dS)zKCleanup multiprocessing resources when multiprocessing tests
    completed.r)�support)�
forkserver)�resource_trackerN)
�testr�r�_cleanuprr��_forkserver�_stopr��_resource_trackerr��
gc_collect�
reap_children)r�r�r�rrr �_cleanup_tests�s

r�)N)N)<rm�	itertoolsr>rdr+r��
subprocessr�r�__all__�NOTSETrr!r"rr(r2rr7rrrrr	r
r@rG�abstract_sockets_supportedrLr�WeakValueDictionaryrT�countr_r]rrprk�objectrr�r
r�r�rIr,r-r�localr�sysconfr�rWrr�r�r�r�r�rrrr �<module>
s��

		V
,�
*



�h�)bytecode of module 'multiprocessing.util'�u��b.��g9h)��N}�(hB19�&@s(dZdZdZdZdZdZdZdZdZdd	l	Z	dd	l
Z
dd	lZdd	lZdd
lTddd
ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0g&Z
d1d2�Zd3d�Zd4d�Zd5d
�Zd6d�Zd7d�Zd8d�Zejje_d9d�Zd:d�Zd;d�Zd<d�Zzdd=lmZWnek
�r(d	ZYnXd>d�Zd?d�Zd@d�ZdAd �Z dBdC�Z!zddDlm"Z"Wnek
�r|e!Z#Yn
XdEd!�Z#zddFlm$Z$m%Z&Wnek
�r�e#Z'YnXdGdH�Z(dIdJ�Z)dKd*�Z'e*e
dL��o�e
�+�dMdNkZ,dRdOd,�Z-dPd0�Z.zddQlm/Z0Wnek
�r"YnXd	S)Sz�Common pathname manipulations, WindowsNT/95 version.

Instead of importing this module directly, import os and refer to this
module as os.path.
�.�..�\�;�/z.;C:\bin�nul�N)�*�normcase�isabs�join�
splitdrive�split�splitext�basename�dirname�commonprefix�getsize�getmtime�getatime�getctime�islink�exists�lexists�isdir�isfile�ismount�
expanduser�
expandvars�normpath�abspath�curdir�pardir�sep�pathsep�defpath�altsep�extsep�devnull�realpath�supports_unicode_filenames�relpath�samefile�sameopenfile�samestat�
commonpathcCst|t�rdSdSdS)N�\/�\/)�
isinstance�bytes��path�r5�/usr/lib/python3.8/ntpath.py�
_get_bothseps"s
r7cCs8t�|�}t|t�r$|�dd���S|�dd���SdS)zaNormalize case of pathname.

    Makes all characters lowercase and all slashes into backslashes.�/�\rrN)�os�fspathr1r2�replace�lower��sr5r5r6r	,s

cCsjt�|�}t|t�r,|�dd��d�rBdSn|�dd��d�rBdSt|�d}t|�d	koh|d	t|�kS)
zTest whether a path is absoluter8r9�\\?\Trr�\\?\�r)	r:r;r1r2r<�
startswithr�lenr7r>r5r5r6r
=s

c

GsTt�|�}t|t�r"d}d}d}nd}d}d}z�|sD|dd�|t|�\}}ttj|�D]~}t|�\}}	|	r�|	d|kr�|s�|s�|}|	}q\n*|r�||kr�|��|��kr�|}|	}q\|}|r�|d|kr�||}||	}q\|�r|d|k�r|�r|dd�|k�r|||WS||WSttt	fk
�rNt
jd	|f|���YnXdS)
Nr9r/�:rr0�:r���r)r:r;r1r2r�mapr=�	TypeError�AttributeError�BytesWarning�genericpath�_check_arg_types)
r4�pathsr"�seps�colon�result_drive�result_path�p�p_drive�p_pathr5r5r6rMsL


��
cCst�|�}t|�dk�rt|t�r0d}d}d}nd}d}d}|�||�}|dd�|dkr�|dd	�|kr�|�|d�}|d
kr�|dd�|fS|�||d�}||dkr�|dd�|fS|d
kr�t|�}|d|�||d�fS|dd�|k�r|dd�|dd�fS|dd�|fS)
a�Split a pathname into drive/UNC sharepoint and relative path specifiers.
    Returns a 2-tuple (drive_or_unc, path); either part may be empty.

    If you assign
        result = splitdrive(p)
    It is always true that:
        result[0] + result[1] == p

    If the path contained a drive letter, drive_or_unc will contain everything
    up to and including the colon.  e.g. splitdrive("c:/dir") returns ("c:", "/dir")

    If the path contained a UNC path, the drive_or_unc will contain the host name
    and share up to but not including the fourth directory separator character.
    e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir")

    Paths cannot contain both a drive letter and a UNC path.

    �r9r8rErrrFr�rGNrB)r:r;rDr1r2r<�find)rSr"r%rP�normp�index�index2r5r5r6r|s.

$cCsxt�|�}t|�}t|�\}}t|�}|rD||d|krD|d8}q&|d|�||d�}}|�|�pj|}|||fS)z~Split a pathname.

    Return tuple (head, tail) where tail is everything after the final slash.
    Either part may be empty.rBN)r:r;r7rrD�rstrip)rSrO�d�i�head�tailr5r5r6r
�s

cCs8t�|�}t|t�r$t�|ddd�St�|ddd�SdS)Nr9r8�.rrr)r:r;r1r2rL�	_splitext�rSr5r5r6r�s

cCst|�dS)z)Returns the final component of a pathnamerB�r
rcr5r5r6r�scCst|�dS)z-Returns the directory component of a pathnamerrdrcr5r5r6r�sc
Cs8zt�|�}Wntttfk
r*YdSXt�|j�S)zhTest whether a path is a symbolic link.
    This will always return false for Windows prior to 6.0.
    F)r:�lstat�OSError�
ValueErrorrJ�stat�S_ISLNK�st_mode�r4�str5r5r6r�s
c	Cs.zt�|�}Wnttfk
r(YdSXdS)zCTest whether a path exists.  Returns True for broken symbolic linksFT)r:rerfrgrkr5r5r6r�s
)�_getvolumepathnamecCstt�|�}t|�}t|�}t|�\}}|rD|d|krD|pB||kS||krPdStrl|�|�t|��|�kSdSdS)zaTest whether a path is a mount point (a drive root, the root of a
    share, or a mounted volume)rTFN)r:r;r7rrrmr\)r4rO�root�restr5r5r6rs
cCs�t�|�}t|t�rd}nd}|�|�s,|Sdt|�}}||kr\||t|�kr\|d7}q:dtjkrrtjd}nFdtjkr�|Sztjd}Wntk
r�d}YnXt	|tjd�}t|t�r�t�
|�}|dkr�t	t|�|d|��}|||d�S)	zLExpand ~ and ~user constructs.

    If user or $HOME is unknown, do nothing.�~�~rB�USERPROFILE�HOMEPATH�	HOMEDRIVE�N)r:r;r1r2rCrDr7�environ�KeyErrorr�fsencoder)r4�tilder^�n�userhome�driver5r5r6r!s.








cCs2t�|�}t|t�rhd|kr(d|kr(|Sddl}t|j|jdd�}d}d}d}d	}d}ttd
d�}nFd|kr|d|kr||Sddl}|j|jd}d
}d}d}d}d}tj}|dd�}	d}
t	|�}|
|k�r.||
|
d�}||k�rX||
dd�}t	|�}z&|�
|�}
|	||d|
d�7}	Wn*tk
�rR|	||7}	|d}
YnX�n�||k�rJ||
d|
d�|k�r�|	|7}	|
d7}
n�||
dd�}t	|�}z|�
|�}
Wn*tk
�r�|	||7}	|d}
YnhX|d|
�}
z.|dk�rt�tjt�
|
��}n||
}Wn"tk
�r<||
|}YnX|	|7}	�n�||k�r||
d|
d�|k�r�|	|7}	|
d7}
�q$||
d|
d�|k�r^||
dd�}t	|�}z|�
|�}
Wn.tk
�r�|	|||7}	|d}
YnlX|d|
�}
z.|dk�r"t�tjt�
|
��}n||
}Wn&tk
�rR|||
|}YnX|	|7}	n�|dd�}
|
d7}
||
|
d�}|�r�||k�r�|
|7}
|
d7}
||
|
d�}�q�z.|dk�r�t�tjt�
|
��}n||
}Wntk
�r||
}YnX|	|7}	|�r$|
d8}
n|	|7}	|
d7}
q�|	S)zfExpand shell variables of the forms $var, ${var} and %var%.

    Unknown variables are left unchanged.�$�%rNz_-�ascii�'�{�}�environb�$�%�'�{�}rBrV)r:r;r1r2�string�
ascii_letters�digits�getattrrvrDrZrgrx�fsdecoderw)r4r��varchars�quote�percent�brace�rbrace�dollarrv�resrZ�pathlen�c�var�valuer5r5r6rQs�













c	CsPt�|�}t|t�r*d}d}d}d}d}nd}d}d}d	}d
}|�|�rL|S|�||�}t|�\}}|�|�r�||7}|�|�}|�|�}d}|t	|�k�r,||r�|||kr�||=q�|||k�r"|dkr�||d|kr�||d|d�=|d8}n&|dk�r|�
|��r||=n|d7}q�|d7}q�|�sB|�sB|�|�||�|�S)
z0Normalize path, eliminating double slashes, etc.r9r8ra�..)s\\.\r@rrrr)z\\.\rArrB)
r:r;r1r2rCr<r�lstripr
rD�endswith�appendr)	r4r"r%r r!�special_prefixes�prefix�compsr^r5r5r6r�sF









cCs@t�|�}t|�s8t|t�r&t��}nt��}t||�}t|�S)z�Return the absolute version of a path as a fallback function in case
    `nt._getfullpathname` is not available or raises OSError. See bpo-31047 for
    more.

    )	r:r;r
r1r2�getcwdb�getcwdrr)r4�cwdr5r5r6�_abspath_fallback�s



r�)�_getfullpathnamec	Cs4ztt|��WSttfk
r.t|�YSXdS)z&Return the absolute version of a path.N)rr�rfrgr�r3r5r5r6rs)�_getfinalpathname�readlinkc
Cs�d}t�}t|�|kr�|�t|��z:|}t|�}t|�s\t|�sJ|}Wq�ttt|�|��}Wq
t	k
r�}z|j
|kr�WY�q��W5d}~XYq
tk
r�Yq�Yq
Xq
|S)N)rBrVrW��� �2�C�Wi&i(i))�setr	�add�_nt_readlinkr
rrrrrf�winerrorrg)r4�allowed_winerror�seen�old_path�exr5r5r6�_readlink_deeps&
r�cCs�d}d}|r�zt|�}|r$t||�n|WStk
r�}z�|j|krF�z0t|�}||krt|rft||�n|WWY�TSWntk
r�YnXt|�\}}|r�|s�||WY�S|r�t||�n|}W5d}~XYqXq|S)N)rBrVrWr�r�r�r�r�r��{i�i�ru)r�rrfr�r�r
)r4r�r`r��new_path�namer5r5r6�_getfinalpathname_nonstrictCs(
 &r�c	
Cs^t|�}t|t�rBd}d}d}t��}t|�tt�t��krjdSn(d}d}d}t��}t|�tt�krjdS|�	|�}|s�t
|�s�t||�}zt|�}d	}Wn0t
k
r�}z|j}t|�}W5d}~XYnX|�sZ|�	|��rZ|�	|�r�||t|�d�}n|t|�d�}zt|�|k�r"|}Wn4t
k
�rX}z|j|k�rH|}W5d}~XYnX|S)
Nr@s\\?\UNC\s\\s\\.\NULrAz\\?\UNC\z\\z\\.\NULr)rr1r2r:r�r	rxr'r�rCr
rr�rfr�r�rD)	r4r��
unc_prefix�new_unc_prefixr��
had_prefix�initial_winerrorr��spathr5r5r6r(qsD



�getwindowsversionrWrVcCsft�|�}t|t�r"d}d}d}nd}d}d}|dkr:|}|sFtd��t�|�}z�tt|��}tt|��}t|�\}}t|�\}	}
t|�t|	�kr�td	|	|f��d
d�|�	|�D�}dd�|
�	|�D�}d
}
t
||�D]$\}}t|�t|�kr�q�|
d7}
q�|gt|�|
||
d�}|�s(|WSt|�WSt
ttttfk
�r`t�d||��YnXdS)z#Return a relative version of a pathr9rar�rrrNzno path specifiedz&path is on mount %r, start on mount %rcSsg|]}|r|�qSr5r5��.0�xr5r5r6�
<listcomp>�szrelpath.<locals>.<listcomp>cSsg|]}|r|�qSr5r5r�r5r5r6r��srrBr*)r:r;r1r2rgrrrr	r
�ziprDrrIrJrK�DeprecationWarningrLrM)r4�startr"r r!�	start_abs�path_abs�start_drive�
start_rest�
path_drive�	path_rest�
start_list�	path_listr^�e1�e2�rel_listr5r5r6r*�sJ


�

c	s�|std��tttj|��}t|dt�r8d�d�d�nd�d�d��z@��fd	d
�|D�}�fdd
�|D�}zt�fdd
�|D��\}Wntk
r�td�d�YnXttdd
�|D���dkr�td��t	|d�
����\}}|���}�fdd
�|D�}�fdd
�|D�}t|�}t
|�}t|�D]*\}	}
|
||	k�r*|d|	�}�qf�q*|dt|��}|�rt|�n|}|��|�WSttfk
�r�tjd|���YnXdS)zDGiven a sequence of path names, returns the longest common sub-path.z%commonpath() arg is an empty sequencerr9r8rarrrcs g|]}t|��������qSr5)rr<r=)r�rS)r%r"r5r6r��szcommonpath.<locals>.<listcomp>csg|]\}}|����qSr5rd�r�r]rS�r"r5r6r��sc3s"|]\}}|dd��kVqdS)NrBr5r�r�r5r6�	<genexpr>�szcommonpath.<locals>.<genexpr>z%Can't mix absolute and relative pathsNcss|]\}}|VqdS)Nr5r�r5r5r6r��srBzPaths don't have the same drivecsg|]}|r|�kr|�qSr5r5�r�r��r r5r6r��scsg|]}�fdd�|D��qS)csg|]}|r|�kr|�qSr5r5r�r�r5r6r�sz)commonpath.<locals>.<listcomp>.<listcomp>r5)r�r?r�r5r6r�sr.)r.)rg�tuplerHr:r;r1r2r�rDrr<r
�min�max�	enumeraterrIrJrLrM)rN�drivesplits�split_pathsr
r|r4�common�s1�s2r^r�r�r5)r%r r"r6r.�sF

)�_isdir)N)1�__doc__r r!r&r"r#r%r$r'r:�sysrhrL�__all__r7r	r
rrr
rrbrrrr�ntrm�ImportErrorrrrrr�r�rr�r�r�r(r�r��hasattrr�r)r*r.r�rr5r5r5r6�<module>s�	�
/8

0q2

*.2�
84�h�bytecode of module 'ntpath'�u��b.��h)��N}�(hB���G@s�dZddlmZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlmZzddlZWnek
r�ddlZYnXzeWne k
�r e!ZYnXddl"m#Z#ddl$m%Z%m&Z&m'Z'ddlm(Z(zddlm)Z)m*Z*m+Z+d	Z,Wnek
�r�d
Z,YnXddlm-Z.ddl/m0Z0m1Z1zddl2m3Z4e4j5Wnek
�r�dZ4YnXd
dl6m7Z7ddl"m8Z8ddl"m9Z9e:d�e:d�e:d�e:d�e:d�e;Z<dej=k�r>dk�rJnne>d��e#j?�rZdZ@dZAdZBdZCdZDdZEdZFdZGdZHdZIdZJdZKdZLdZMdZNdZOdZPdZQdZRGdd�deS�ZTdd�ZUiZVdd�ZWdd �ZXd!d"�ZYd#d$�ZZd%d&�Z[d'd(�Z\d)d*�Z]d+d,�Z^Z_d-d.�Z`d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNddOddPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsgGZaGdtdJ�dJeb�ZcGdudK�dKec�ZdGdvdw�dwed�ZeGdxdL�dLec�ZfGdydM�dMec�ZgiZhdzjiej=�Zjd{Zkd|Zld
ZmdZnd}Zod~dn�Zpdd1�Zqgfd�d��Zrd�d��Zsd�d��Zte�ud��Zve�ud��ZwetZxd�dS�Zyd�d0�ZzezZ{d�d2�Z|d�d3�Z}�dd�d4�Z~d�d5�ZGd�da�da�Z�Gd�db�dbe��Z�Gd�dE�dE�Z�Gd�d��d�e��Z�Gd�dD�dD�Z�e�Z�Gd�dN�dNe>�Z�Gd�dF�dF�Z�d�dC�Z�d�dP�Z�d�dQ�Z�d�dV�Z�d�dW�Z�d�dX�Z��dd�dY�Z�Gd�dh�dh�Z�epe�e��Gd�di�die��Z�Gd�dj�dje��Z�e����Gd�df�dfe��Z�e��Z�Gd�d��d�e��Z�Gd�d��d�e��Z�Gd�dk�dke��Z�epe
j�e��Gd�dc�dce��Z�Gd�dd�dde��Z�Gd�de�dee��Z�eWd�id��d�dl�Z��dd�d@�Z��dd�d��Z�e�e
j�e���dd�d��Z�e�e�e��d�d��Z��dd�d��Z�d�d��Z�Gd�d��d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�e�ej�e��e�e4d���r�e�e4j�e��eWd�ideWd�idÍd�dm�Z�d�dƄZ�d�dȄZ�d�d=�Z��dd�do�Z�d�d̄Z�e�ej�e��e�e
j�e��e�e4d���r*e�e4j�e��d�d΄Z�e�e�e��d�d[�Z�d�dфZ�ifd�dӄZ�d�dՄZ�d�dׄZ�d�dلZ�d�dT�Z�e�udۡj�Z�e�ud�ej�ej�B�j�Z�Gd�dI�dI�Z�d�d߄Z�d�d�Z�Gd�dG�dG�Z�Gd�d�d�eÃZ�Gd�d�d�eÃZ�e�e�e�d�Z�d�d�Z�Gd�d�d�eȃZ�d�dO�Z�Gd�dH�dHe9j�j̃Z�d�d�Z�d�d�Z�d�dZ�Z�d�d�Z�d�dU�Z�d�d��Z�ej�d�eTd	d��d�d��Z�e�eՃfd�d���Z�e�d�d���Z�G�ddq�dqe؃Z�dS(aZ
Package resource API
--------------------

A resource is a logical file contained within a package, or a logical
subdirectory thereof.  The package resource API expects resource names
to have their path parts separated with ``/``, *not* whatever the local
path separator is.  Do not use os.path operations to manipulate resource
names being passed into the API.

The package resource API is designed to work with normal filesystem packages,
.egg files, and unpacked .egg files.  It can also work in a limited way with
.zip files and with custom PEP 302 loaders that support the ``get_data()``
method.
�)�absolute_importN)�get_importer)�six)�urllib�map�filter)�utime)�mkdir�rename�unlinkTF)�open)�isdir�split�)�
py31compat)�appdirs)�	packagingz&pkg_resources.extern.packaging.versionz)pkg_resources.extern.packaging.specifiersz+pkg_resources.extern.packaging.requirementsz&pkg_resources.extern.packaging.markerszpkg_resources.py2_warn)�r)r�zPython 3.5 or later is requiredc@seZdZdZdS)�
PEP440Warningza
    Used when there is an issue with a version or specifier not complying with
    PEP 440.
    N��__name__�
__module__�__qualname__�__doc__�rr�8/usr/lib/python3/dist-packages/pkg_resources/__init__.pyrysrcCs8ztj�|�WStjjk
r2tj�|�YSXdS�N)r�version�Version�InvalidVersion�
LegacyVersion)�vrrr�
parse_version�sr#cKs"t��|�t�t�||��dSr)�globals�update�_state_vars�dict�fromkeys)�vartype�kwrrr�_declare_state�sr+cCs8i}t�}t��D] \}}|d|||�||<q|S)N�_sget_)r$r&�items��state�g�kr"rrr�__getstate__�s
r2cCs8t�}|��D]$\}}|dt|||||�q|S)N�_sset_)r$r-r&r.rrr�__setstate__�sr4cCs|��Sr)�copy��valrrr�
_sget_dict�sr8cCs|��|�|�dSr)�clearr%��key�obr/rrr�
_sset_dict�sr=cCs|��Sr)r2r6rrr�_sget_object�sr>cCs|�|�dSr)r4r:rrr�_sset_object�sr?cGsdSrr��argsrrr�<lambda>��rBcCsbt�}t�|�}|dk	r^tjdkr^z&dd�t�dd��|�d�f}Wntk
r\YnX|S)aZReturn this platform's maximum compatible version.

    distutils.util.get_platform() normally reports the minimum version
    of Mac OS X that would be required to *use* extensions produced by
    distutils.  But what we want when checking compatibility is to know the
    version of Mac OS X that we are *running*.  To allow usage of packages that
    explicitly require a newer version of Mac OS X, we must also know the
    current version of the OS.

    If this condition occurs for any other platform with a version in its
    platform strings, this function should be extended accordingly.
    N�darwinzmacosx-%s-%s�.�r)	�get_build_platform�macosVersionString�match�sys�platform�join�_macosx_vers�group�
ValueError)�plat�mrrr�get_supported_platform�s

&rR�require�
run_script�get_provider�get_distribution�load_entry_point�
get_entry_map�get_entry_info�iter_entry_points�resource_string�resource_stream�resource_filename�resource_listdir�resource_exists�resource_isdir�declare_namespace�working_set�add_activation_listener�find_distributions�set_extraction_path�cleanup_resources�get_default_cache�Environment�
WorkingSet�ResourceManager�Distribution�Requirement�
EntryPoint�ResolutionError�VersionConflict�DistributionNotFound�UnknownExtra�ExtractionError�parse_requirements�	safe_name�safe_version�get_platform�compatible_platforms�yield_lines�split_sections�
safe_extra�to_filename�invalid_marker�evaluate_marker�ensure_directory�normalize_path�EGG_DIST�BINARY_DIST�SOURCE_DIST�
CHECKOUT_DIST�DEVELOP_DIST�IMetadataProvider�IResourceProvider�FileMetadata�PathMetadata�EggMetadata�
EmptyProvider�empty_provider�NullProvider�EggProvider�DefaultProvider�ZipProvider�register_finder�register_namespace_handler�register_loader_type�fixup_namespace_packagesr�PkgResourcesDeprecationWarning�run_main�AvailableDistributionsc@seZdZdZdd�ZdS)rnz.Abstract base for dependency resolution errorscCs|jjt|j�Sr)�	__class__r�reprrA��selfrrr�__repr__�szResolutionError.__repr__N)rrrrr�rrrrrn�sc@s<eZdZdZdZedd��Zedd��Zdd�Zd	d
�Z	dS)roz�
    An already-installed version conflicts with the requested version.

    Should be initialized with the installed Distribution and the requested
    Requirement.
    z3{self.dist} is installed but {self.req} is requiredcCs
|jdS�Nrr@r�rrr�dist
szVersionConflict.distcCs
|jdS�Nrr@r�rrr�reqszVersionConflict.reqcCs|jjft��Sr��	_template�format�localsr�rrr�reportszVersionConflict.reportcCs|s|S|j|f}t|�S)zt
        If required_by is non-empty, return a version of self that is a
        ContextualVersionConflict.
        )rA�ContextualVersionConflict)r��required_byrArrr�with_contextszVersionConflict.with_contextN)
rrrrr��propertyr�r�r�r�rrrrros

c@s&eZdZdZejdZedd��ZdS)r�z�
    A VersionConflict that accepts a third parameter, the set of the
    requirements that required the installed Distribution.
    z by {self.required_by}cCs
|jdS)NrFr@r�rrrr�+sz%ContextualVersionConflict.required_byN)rrrrror�r�r�rrrrr�#s
r�c@sHeZdZdZdZedd��Zedd��Zedd��Zd	d
�Z	dd�Z
d
S)rpz&A requested distribution was not foundzSThe '{self.req}' distribution was not found and is required by {self.requirers_str}cCs
|jdSr�r@r�rrrr�6szDistributionNotFound.reqcCs
|jdSr�r@r�rrr�	requirers:szDistributionNotFound.requirerscCs|js
dSd�|j�S)Nzthe applicationz, )r�rLr�rrr�
requirers_str>sz"DistributionNotFound.requirers_strcCs|jjft��Srr�r�rrrr�DszDistributionNotFound.reportcCs|��Sr)r�r�rrr�__str__GszDistributionNotFound.__str__N)rrrrr�r�r�r�r�r�r�rrrrrp0s


c@seZdZdZdS)rqz>Distribution doesn't have an "extra feature" of the given nameNrrrrrrqKsz{}.{}rrF���cCs|t|<dS)aRegister `provider_factory` to make providers for `loader_type`

    `loader_type` is the type or class of a PEP 302 ``module.__loader__``,
    and `provider_factory` is a function that, passed a *module* object,
    returns an ``IResourceProvider`` for that module.
    N)�_provider_factories)�loader_type�provider_factoryrrrr�YscCstt|t�r$t�|�p"tt|��dSztj|}Wn&tk
rXt	|�tj|}YnXt
|dd�}tt|�|�S)z?Return an IResourceProvider for the named module or requirementr�
__loader__N)
�
isinstancerlrb�findrS�strrJ�modules�KeyError�
__import__�getattr�
_find_adapterr�)�moduleOrReq�module�loaderrrrrUcs
cCsd|s\t��d}|dkrLd}tj�|�rLttd�rLt�|�}d|krL|d}|�|�	d��|dS)Nr�z0/System/Library/CoreServices/SystemVersion.plist�	readPlist�ProductVersionrE)
rK�mac_ver�os�path�exists�hasattr�plistlibr��appendr)�_cacher�plist�
plist_contentrrrrMps

rMcCsddd��||�S)N�ppc)�PowerPC�Power_Macintosh)�get)�machinerrr�_macosx_arch�sr�cCs~ddlm}|�}tjdkrz|�d�szz>t�}t��d�dd�}dt	|d�t	|d	�t
|�fWStk
rxYnX|S)
z�Return this platform's string for platform-specific distributions

    XXX Currently this is the same as ``distutils.util.get_platform()``, but it
    needs some hacks for Linux and Mac OS X.
    r)rvrDzmacosx-�� �_zmacosx-%d.%d-%sr)�	sysconfigrvrJrK�
startswithrMr��uname�replace�intr�rO)rvrPrr�rrrrG�s

�rGzmacosx-(\d+)\.(\d+)-(.*)zdarwin-(\d+)\.(\d+)\.(\d+)-(.*)cCs�|dks|dks||krdSt�|�}|r�t�|�}|s�t�|�}|r�t|�d��}d|�d�|�d�f}|dkr||dks�|dkr�|d	kr�dSd
S|�d�|�d�ks�|�d�|�d�kr�d
St|�d��t|�d��kr�d
SdSd
S)z�Can code for the `provided` platform run on the `required` platform?

    Returns true if either platform is ``None``, or the platforms are equal.

    XXX Needs compatibility checks for Linux and other unixy OSes.
    NTrz%s.%srF�z10.3�z10.4Fr)rHrI�darwinVersionStringr�rN)�provided�required�reqMac�provMac�
provDarwin�dversion�macosversionrrrrw�s2


���cCs<t�d�j}|d}|��||d<t|�d�||�dS)z@Locate distribution `dist_spec` and run its `script_name` scriptrrrN�rJ�	_getframe�	f_globalsr9rSrT)�	dist_spec�script_name�ns�namerrrrT�s
cCs@t|tj�rt�|�}t|t�r(t|�}t|t�s<td|��|S)z@Return a current distribution object for a Requirement or stringz-Expected string, Requirement, or Distribution)r�r�string_typesrl�parserUrk�	TypeError�r�rrrrV�s



cCst|��||�S)zDReturn `name` entry point of `group` for `dist` or raise ImportError)rVrW�r�rNr�rrrrW�scCst|��|�S)�=Return the entry point map for `group`, or the full entry map)rVrX)r�rNrrrrX�scCst|��||�S�z<Return the EntryPoint object for `group`+`name`, or ``None``)rVrYr�rrrrY�sc@s<eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
S)r�cCsdS)z;Does the package's distribution contain the named metadata?Nr�r�rrr�has_metadata�szIMetadataProvider.has_metadatacCsdS)z'The named metadata resource as a stringNrr�rrr�get_metadata�szIMetadataProvider.get_metadatacCsdS)z�Yield named metadata resource as list of non-blank non-comment lines

       Leading and trailing whitespace is stripped from each line, and lines
       with ``#`` as the first non-blank character are omitted.Nrr�rrr�get_metadata_lines�sz$IMetadataProvider.get_metadata_linescCsdS)z>Is the named metadata a directory?  (like ``os.path.isdir()``)Nrr�rrr�metadata_isdirsz IMetadataProvider.metadata_isdircCsdS)z?List of metadata names in the directory (like ``os.listdir()``)Nrr�rrr�metadata_listdirsz"IMetadataProvider.metadata_listdircCsdS)z=Execute the named script in the supplied namespace dictionaryNr)r��	namespacerrrrT
szIMetadataProvider.run_scriptN)	rrrr�r�r�r�r�rTrrrrr��sc@s@eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dS)r�z3An object that provides access to package resourcescCsdS)zdReturn a true filesystem path for `resource_name`

        `manager` must be an ``IResourceManager``Nr��manager�
resource_namerrr�get_resource_filenamesz'IResourceProvider.get_resource_filenamecCsdS)ziReturn a readable file-like object for `resource_name`

        `manager` must be an ``IResourceManager``Nrr�rrr�get_resource_streamsz%IResourceProvider.get_resource_streamcCsdS)zmReturn a string containing the contents of `resource_name`

        `manager` must be an ``IResourceManager``Nrr�rrr�get_resource_stringsz%IResourceProvider.get_resource_stringcCsdS)z,Does the package contain the named resource?Nr�r�rrr�has_resource szIResourceProvider.has_resourcecCsdS)z>Is the named resource a directory?  (like ``os.path.isdir()``)Nrr�rrrr`#sz IResourceProvider.resource_isdircCsdS)z?List of resource names in the directory (like ``os.listdir()``)Nrr�rrrr^&sz"IResourceProvider.resource_listdirN)
rrrrr�r�r�r�r`r^rrrrr�sc@s�eZdZdZd'dd�Zedd��Zedd��Zd	d
�Zdd�Z	d
d�Z
d(dd�Zdd�Zdd�Z
d)dd�Zd*dd�Zd+dd�Zdd�Zd,dd �Zd!d"�Zd#d$�Zd%d&�ZdS)-rizDA collection of active distributions on sys.path (or a similar list)NcCs>g|_i|_i|_g|_|dkr&tj}|D]}|�|�q*dS)z?Create working set from list of path entries (default=sys.path)N)�entries�
entry_keys�by_key�	callbacksrJr��	add_entry)r�r��entryrrr�__init__-szWorkingSet.__init__cCsb|�}zddlm}Wntk
r.|YSXz|�|�Wntk
r\|�|�YSX|S)z1
        Prepare the master working set.
        r)�__requires__)�__main__r�ImportErrorrSro�_build_from_requirements)�cls�wsrrrr�
_build_master:s
zWorkingSet._build_mastercCsf|g�}t|�}|�|t��}|D]}|�|�q"tjD]}||jkr8|�|�q8|jtjdd�<|S)zQ
        Build a working set from a requirement spec. Rewrites sys.path.
        N)rs�resolverh�addrJr�r�r)r	�req_specr
�reqs�distsr�rrrrrNs

z#WorkingSet._build_from_requirementscCs<|j�|g�|j�|�t|d�D]}|�||d�q$dS)a�Add a path item to ``.entries``, finding any distributions on it

        ``find_distributions(entry, True)`` is used to find distributions
        corresponding to the path entry, and they are added.  `entry` is
        always appended to ``.entries``, even if it is already present.
        (This is because ``sys.path`` can contain the same value more than
        once, and the ``.entries`` of the ``sys.path`` WorkingSet should always
        equal ``sys.path``.)
        TFN)r��
setdefaultr�r�rdr
)r�rr�rrrrds
zWorkingSet.add_entrycCs|j�|j�|kS)z9True if `dist` is the active distribution for its project)rr�r;�r�r�rrr�__contains__sszWorkingSet.__contains__cCs,|j�|j�}|dk	r(||kr(t||��|S)a�Find a distribution matching requirement `req`

        If there is an active distribution for the requested project, this
        returns it as long as it meets the version requirement specified by
        `req`.  But, if there is an active distribution for the project and it
        does *not* meet the `req` requirement, ``VersionConflict`` is raised.
        If there is no active distribution for the requested project, ``None``
        is returned.
        N)rr�r;ro)r�r�r�rrrr�ws

zWorkingSet.findcs��fdd�|D�S)aYield entry point objects from `group` matching `name`

        If `name` is None, yields all entry points in `group` from all
        distributions in the working set, otherwise only ones matching
        both `group` and `name` are yielded (in distribution order).
        c3s8|]0}|�����D]}�dks*�|jkr|VqqdSr)rX�valuesr�)�.0r�r�rNr�rr�	<genexpr>�s
�z/WorkingSet.iter_entry_points.<locals>.<genexpr>r�r�rNr�rrrrZ�s�zWorkingSet.iter_entry_pointscCs>t�d�j}|d}|��||d<|�|�d�||�dS)z?Locate distribution for `requires` and run `script_name` scriptrrrNr�)r��requiresr�r�r�rrrrT�s
zWorkingSet.run_scriptccsLi}|jD]<}||jkrq
|j|D] }||kr$d||<|j|Vq$q
dS)z�Yield distributions for non-duplicate projects in the working set

        The yield order is the order in which the items' path entries were
        added to the working set.
        rN)r�r�r)r��seen�itemr;rrr�__iter__�s

zWorkingSet.__iter__TFcCs�|r|j|j||d�|dkr$|j}|j�|g�}|j�|jg�}|sV|j|jkrVdS||j|j<|j|krx|�|j�|j|kr�|�|j�|�|�dS)aAdd `dist` to working set, associated with `entry`

        If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
        On exit from this routine, `entry` is added to the end of the working
        set's ``.entries`` (if it wasn't already present).

        `dist` is only added to the working set if it's for a project that
        doesn't already have a distribution in the set, unless `replace=True`.
        If it's added, any callbacks registered with the ``subscribe()`` method
        will be called.
        �r�N)	�	insert_onr��locationr�rr;rr��
_added_new)r�r�r�insertr��keys�keys2rrrr
�s

zWorkingSet.addcCsxt|�ddd�}i}i}g}t�}	t�t�}
|�rt|�d�}||krHq.|	�||�sVq.|�|j�}|dk�r|j	�|j�}|dks�||kr�|r�|}
|dkr�|dkr�t
|j�}nt
g�}tg�}
|j
||
||d�}||j<|dkr�|
�|d�}t||��|�|�||k�r$|
|}t||��|��|�|j�ddd�}|�|�|D] }|
|�|j�|j|	|<�qHd||<q.|S)a�List all distributions needed to (recursively) meet `requirements`

        `requirements` must be a sequence of ``Requirement`` objects.  `env`,
        if supplied, should be an ``Environment`` instance.  If
        not supplied, it defaults to all distributions available within any
        entry or distribution in the working set.  `installer`, if supplied,
        will be invoked with each requirement that cannot be met by an
        already-installed distribution; it should return a ``Distribution`` or
        ``None``.

        Unless `replace_conflicting=True`, raises a VersionConflict exception
        if
        any requirements are found on the path that have the correct name but
        the wrong version.  Otherwise, if an `installer` is supplied it will be
        invoked to obtain the correct version of the requirement and activate
        it.

        `extras` is a list of the extras to be used with these requirements.
        This is important because extra requirements may look like `my_req;
        extra = "my_extra"`, which would otherwise be interpreted as a purely
        optional requirement.  Instead, we want to be able to assert that these
        requirements are truly required.
        Nr�r)�replace_conflictingT)�list�
_ReqExtras�collections�defaultdict�set�pop�markers_passr�r;rrhr�ri�
best_matchrpr�ror�r�extras�extendr
�project_name)r��requirements�env�	installerr$r-�	processed�best�to_activate�
req_extrasr�r�r�r
r��
dependent_req�new_requirements�new_requirementrrrr�sT


�




zWorkingSet.resolvecCs
t|�}|��i}i}|dkr4t|j�}||7}n||}|�g�}	tt|	j|��|D]�}
||
D]�}|��g}z|	�|||�}
WnBt	k
r�}z$|||<|r�WY�qfn
WY�qZW5d}~XYqfXtt|	j|
��|�
t�|
��qZqfqZt|�}|��||fS)asFind all activatable distributions in `plugin_env`

        Example usage::

            distributions, errors = working_set.find_plugins(
                Environment(plugin_dirlist)
            )
            # add plugins+libs to sys.path
            map(working_set.add, distributions)
            # display errors
            print('Could not load', errors)

        The `plugin_env` should be an ``Environment`` instance that contains
        only distributions that are in the project's "plugin directory" or
        directories. The `full_env`, if supplied, should be an ``Environment``
        contains all currently-available distributions.  If `full_env` is not
        supplied, one is created automatically from the ``WorkingSet`` this
        method is called on, which will typically mean that every directory on
        ``sys.path`` will be scanned for distributions.

        `installer` is a standard installer callback as used by the
        ``resolve()`` method. The `fallback` flag indicates whether we should
        attempt to resolve older versions of a plugin if the newest version
        cannot be resolved.

        This method returns a 2-tuple: (`distributions`, `error_info`), where
        `distributions` is a list of the distributions found in `plugin_env`
        that were loadable, along with any other distributions that are needed
        to resolve their dependencies.  `error_info` is a dictionary mapping
        unloadable plugin distributions to an exception instance describing the
        error that occurred. Usually this will be a ``DistributionNotFound`` or
        ``VersionConflict`` instance.
        N)
r%�sortrhr�r�rr
�as_requirementrrnr%r'r()r��
plugin_env�full_envr2�fallback�plugin_projects�
error_info�
distributionsr1�
shadow_setr/r�r��	resolveesr"rrr�find_plugins(s4$




zWorkingSet.find_pluginscGs&|�t|��}|D]}|�|�q|S)a�Ensure that distributions matching `requirements` are activated

        `requirements` must be a string or a (possibly-nested) sequence
        thereof, specifying the distributions and versions required.  The
        return value is a sequence of the distributions that needed to be
        activated to fulfill the requirements; all relevant distributions are
        included, even if they were already activated in this working set.
        )rrsr
)r�r0�neededr�rrrrS|s	zWorkingSet.requirecCs8||jkrdS|j�|�|s"dS|D]}||�q&dS)z�Invoke `callback` for all distributions

        If `existing=True` (default),
        call on all existing ones, as well.
        N)rr�)r��callback�existingr�rrr�	subscribe�s
zWorkingSet.subscribecCs|jD]}||�qdSr)r)r�r�rFrrrr �s
zWorkingSet._added_newcCs,|jdd�|j��|j��|jdd�fSr)r�r�r5rrr�rrrr2�s
�zWorkingSet.__getstate__cCs@|\}}}}|dd�|_|��|_|��|_|dd�|_dSr)r�r5r�rr)r��e_k_b_cr�r"rrrrrr4�s


zWorkingSet.__setstate__)N)N)NTF)NNFN)NNT)T)rrrrr�classmethodrrrrr�rZrTrr
rrDrSrHr r2r4rrrrri*s4





�
]�
T
c@seZdZdZddd�ZdS)r&z>
    Map each requirement to the extras that demanded it.
    Ncs2�fdd�|��d�|pdD�}�jp0t|�S)z�
        Evaluate markers for req against each extra that
        demanded it.

        Return False if the req has a marker and fails
        evaluation. Otherwise, return True.
        c3s|]}�j�d|i�VqdS)�extraN��marker�evaluate)rrK�r�rrr�s�z*_ReqExtras.markers_pass.<locals>.<genexpr>rr)r�rM�any)r�r�r-�extra_evalsrrOrr+�s
�z_ReqExtras.markers_pass)N)rrrrr+rrrrr&�sr&c@sxeZdZdZde�efdd�Zdd�Zdd�Zdd	d
�Z	dd�Z
d
d�Zddd�Zddd�Z
dd�Zdd�Zdd�ZdS)rhz5Searchable snapshot of distributions on a search pathNcCs i|_||_||_|�|�dS)a!Snapshot distributions available on a search path

        Any distributions found on `search_path` are added to the environment.
        `search_path` should be a sequence of ``sys.path`` items.  If not
        supplied, ``sys.path`` is used.

        `platform` is an optional string specifying the name of the platform
        that platform-specific distributions must be compatible with.  If
        unspecified, it defaults to the current platform.  `python` is an
        optional string naming the desired version of Python (e.g. ``'3.6'``);
        it defaults to the current version.

        You may explicitly set `platform` (and/or `python`) to ``None`` if you
        wish to map *all* distributions, not just those compatible with the
        running platform or Python version.
        N)�_distmaprK�python�scan)r��search_pathrKrSrrrr�szEnvironment.__init__cCs2|jdkp|jdkp|j|jk}|o0t|j|j�S)z�Is distribution `dist` acceptable for this environment?

        The distribution must match the platform and python version
        requirements specified when this environment was created, or False
        is returned.
        N)rS�
py_versionrwrK)r�r��	py_compatrrr�can_add�s
�
�zEnvironment.can_addcCs|j|j�|�dS)z"Remove `dist` from the environmentN)rRr;�removerrrrrY�szEnvironment.removecCs4|dkrtj}|D]}t|�D]}|�|�qqdS)adScan `search_path` for distributions usable in this environment

        Any distributions found are added to the environment.
        `search_path` should be a sequence of ``sys.path`` items.  If not
        supplied, ``sys.path`` is used.  Only distributions conforming to
        the platform/python version defined at initialization are added.
        N)rJr�rdr
)r�rUrr�rrrrT�s
zEnvironment.scancCs|��}|j�|g�S)aReturn a newest-to-oldest list of distributions for `project_name`

        Uses case-insensitive `project_name` comparison, assuming all the
        project's distributions use their project's name converted to all
        lowercase as their key.

        )�lowerrRr�)r�r/�distribution_keyrrr�__getitem__�szEnvironment.__getitem__cCsL|�|�rH|��rH|j�|jg�}||krH|�|�|jt�d�dd�dS)zLAdd `dist` if we ``can_add()`` it and it has not already been added
        �hashcmpT�r;�reverseN)	rX�has_versionrRrr;r�r:�operator�
attrgetter)r�r�rrrrr
s

zEnvironment.addFcCsfz|�|�}Wntk
r,|s$�d}YnX|dk	r:|S||jD]}||krD|SqD|�||�S)a�Find distribution best matching `req` and usable on `working_set`

        This calls the ``find(req)`` method of the `working_set` to see if a
        suitable distribution is already active.  (This may raise
        ``VersionConflict`` if an unsuitable version of the project is already
        active in the specified `working_set`.)  If a suitable distribution
        isn't active, this method returns the newest distribution in the
        environment that meets the ``Requirement`` in `req`.  If no suitable
        distribution is found, and `installer` is supplied, then the result of
        calling the environment's ``obtain(req, installer)`` method will be
        returned.
        N)r�ror;�obtain)r�r�rbr2r$r�rrrr,s

zEnvironment.best_matchcCs|dk	r||�SdS)a�Obtain a distribution matching `requirement` (e.g. via download)

        Obtain a distro that matches requirement (e.g. via download).  In the
        base ``Environment`` class, this routine just returns
        ``installer(requirement)``, unless `installer` is None, in which case
        None is returned instead.  This method is a hook that allows subclasses
        to attempt other ways of obtaining a distribution before falling back
        to the `installer` argument.Nr)r��requirementr2rrrrc,s	zEnvironment.obtainccs"|j��D]}||r
|Vq
dS)z=Yield the unique project names of the available distributionsN)rRr"�r�r;rrrr8szEnvironment.__iter__cCsVt|t�r|�|�n<t|t�rD|D]}||D]}|�|�q0q$ntd|f��|S)z2In-place addition of a distribution or environmentzCan't add %r to environment)r�rkr
rhr�)r��other�projectr�rrr�__iadd__>s

zEnvironment.__iadd__cCs*|jgddd�}||fD]}||7}q|S)z4Add an environment or distribution to an environmentN)rKrS�r�)r�rf�newr1rrr�__add__Js
zEnvironment.__add__)N)NF)N)rrrrrR�PY_MAJORrrXrYrTr\r
r,rcrrhrkrrrrrh�s"�


�

c@seZdZdZdS)rraTAn error occurred extracting a resource

    The following attributes are available from instances of this exception:

    manager
        The resource manager that raised this exception

    cache_path
        The base directory for resource extraction

    original_error
        The exception instance that caused extraction to fail
    NrrrrrrrVsc@s�eZdZdZdZdd�Zdd�Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Zddd�Z
edd��Zdd�Zdd�Zd dd�ZdS)!rjz'Manage resource extraction and packagesNcCs
i|_dSr)�cached_filesr�rrrrjszResourceManager.__init__cCst|��|�S)zDoes the named resource exist?)rUr��r��package_or_requirementr�rrrr_mszResourceManager.resource_existscCst|��|�S)z,Is the named resource an existing directory?)rUr`rnrrrr`qs�zResourceManager.resource_isdircCst|��||�S)z4Return a true filesystem path for specified resource)rUr�rnrrrr]ws�z!ResourceManager.resource_filenamecCst|��||�S)z9Return a readable file-like object for specified resource)rUr�rnrrrr\}s�zResourceManager.resource_streamcCst|��||�S)z%Return specified resource as a string)rUr�rnrrrr[�s�zResourceManager.resource_stringcCst|��|�S)z1List the contents of the named resource directory)rUr^rnrrrr^�s�z ResourceManager.resource_listdircCsRt��d}|jpt�}t�d���}t|jft	���}||_
||_||_|�dS)z5Give an error message for problems extracting file(s)ra
            Can't extract file(s) to egg cache

            The following error occurred while trying to extract file(s)
            to the Python egg cache:

              {old_exc}

            The Python egg cache directory is currently set to:

              {cache_path}

            Perhaps your account does not have write access to this directory?
            You can change the cache directory by setting the PYTHON_EGG_CACHE
            environment variable to point to an accessible directory.
            N)
rJ�exc_info�extraction_pathrg�textwrap�dedent�lstriprrr�r�r��
cache_path�original_error)r��old_excru�tmpl�errrrr�extraction_error�sz ResourceManager.extraction_errorrcCsf|jp
t�}tjj||df|��}zt|�Wntk
rL|��YnX|�|�d|j	|<|S)a�Return absolute location in cache for `archive_name` and `names`

        The parent directory of the resulting path will be created if it does
        not already exist.  `archive_name` should be the base filename of the
        enclosing egg (which may not be the name of the enclosing zipfile!),
        including its ".egg" extension.  `names`, if provided, should be a
        sequence of path name parts "under" the egg's extraction location.

        This method should only be called by resource providers that need to
        obtain an extraction location, and only for names they intend to
        extract, as it tracks the generated names for possible cleanup later.
        z-tmpr)
rqrgr�r�rL�_bypass_ensure_directory�	Exceptionrz�_warn_unsafe_extraction_pathrm)r��archive_name�names�extract_path�target_pathrrr�get_cache_path�s


zResourceManager.get_cache_pathcCsVtjdkr|�tjd�sdSt�|�j}|tj@s>|tj@rRd|}t�	|t
�dS)aN
        If the default extraction path is overridden and set to an insecure
        location, such as /tmp, it opens up an opportunity for an attacker to
        replace an extracted file with an unauthorized payload. Warn the user
        if a known insecure location is used.

        See Distribute #375 for more details.
        �nt�windirNz�%s is writable by group/others and vulnerable to attack when used with get_resource_filename. Consider a more secure location (set with .set_extraction_path or the PYTHON_EGG_CACHE environment variable).)r�r�r��environ�stat�st_mode�S_IWOTH�S_IWGRP�warnings�warn�UserWarning)r��mode�msgrrrr}�s
��z,ResourceManager._warn_unsafe_extraction_pathcCs.tjdkr*t�|�jdBd@}t�||�dS)a4Perform any platform-specific postprocessing of `tempname`

        This is where Mac header rewrites should be done; other platforms don't
        have anything special they should do.

        Resource providers should call this method ONLY after successfully
        extracting a compressed resource.  They must NOT call it on resources
        that are already in the filesystem.

        `tempname` is the current (temporary) name of the file, and `filename`
        is the name it will be renamed to by the caller after this routine
        returns.
        �posiximi�N)r�r�r�r��chmod)r��tempname�filenamer�rrr�postprocess�s
zResourceManager.postprocesscCs|jrtd��||_dS)a�Set the base path where resources will be extracted to, if needed.

        If you do not call this routine before any extractions take place, the
        path defaults to the return value of ``get_default_cache()``.  (Which
        is based on the ``PYTHON_EGG_CACHE`` environment variable, with various
        platform-specific fallbacks.  See that routine's documentation for more
        details.)

        Resources are extracted to subdirectories of this path based upon
        information given by the ``IResourceProvider``.  You may set this to a
        temporary directory, but then you must call ``cleanup_resources()`` to
        delete the extracted files when done.  There is no guarantee that
        ``cleanup_resources()`` will be able to remove all extracted files.

        (Note: you may not change the extraction path for a given resource
        manager once resources have been extracted, unless you first call
        ``cleanup_resources()``.)
        z5Can't change extraction path, files already extractedN)rmrOrq�r�r�rrrre�s
�z#ResourceManager.set_extraction_pathFcCsdS)aB
        Delete all extracted resource files and directories, returning a list
        of the file and directory names that could not be successfully removed.
        This function does not have any concurrency protection, so it should
        generally only be called when the extraction path is a temporary
        directory exclusive to a single process.  This method is not
        automatically called; you must call it explicitly or register it as an
        ``atexit`` function if you wish to ensure cleanup of a temporary
        directory used for extractions.
        Nr)r��forcerrrrfsz!ResourceManager.cleanup_resources)r)F)rrrrrqrr_r`r]r\r[r^rzr��staticmethodr}r�rerfrrrrrjfs 

cCstj�d�ptjdd�S)z�
    Return the ``PYTHON_EGG_CACHE`` environment variable
    or a platform-relevant user cache dir for an app
    named "Python-Eggs".
    �PYTHON_EGG_CACHEzPython-Eggs)�appname)r�r�r�r�user_cache_dirrrrrrgs
�cCst�dd|�S)z�Convert an arbitrary string to a standard distribution name

    Any runs of non-alphanumeric/. characters are replaced with a single '-'.
    �[^A-Za-z0-9.]+�-)�re�subr�rrrrt&scCsJzttj�|��WStjjk
rD|�dd�}t�dd|�YSXdS)zB
    Convert an arbitrary string to a standard version string
    r�rEr�r�N)r�rrrr r�r�r�)rrrrru.s
cCst�dd|���S)z�Convert an arbitrary string to a standard 'extra' name

    Any runs of non-alphanumeric characters are replaced with a single '_',
    and the result is always lowercased.
    z[^A-Za-z0-9.-]+r�)r�r�rZ)rKrrrrz:scCs|�dd�S)z|Convert a project or version name to its filename-escaped form

    Any '-' characters are currently replaced with '_'.
    r�r�rr�rrrr{Csc
CsHzt|�Wn6tk
rB}zd|_d|_|WY�Sd}~XYnXdS)zo
    Validate text as a PEP 508 environment marker; return an exception
    if invalid or False otherwise.
    NF)r}�SyntaxErrorr��lineno)�text�errrr|Ksc
CsJztj�|�}|��WStjjk
rD}zt|��W5d}~XYnXdS)z�
    Evaluate a PEP 508 environment marker.
    Return a boolean indicating the marker result in this environment.
    Raise SyntaxError if marker is invalid.

    This implementation uses the 'pyparsing' module.
    N)r�markers�MarkerrN�
InvalidMarkerr�)r�rKrMr�rrrr}Ys

c@s�eZdZdZdZdZdZdd�Zdd�Zdd�Z	d	d
�Z
dd�Zd
d�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zed'd(��Zd)d*�ZdS)+r�zETry to implement resources and metadata for arbitrary PEP 302 loadersNcCs(t|dd�|_tj�t|dd��|_dS)Nr��__file__r�)r�r�r�r��dirname�module_path�r�r�rrrroszNullProvider.__init__cCs|�|j|�Sr)�_fnr��r�r�r�rrrr�ssz"NullProvider.get_resource_filenamecCst�|�||��Sr)�io�BytesIOr�r�rrrr�vsz NullProvider.get_resource_streamcCs|�|�|j|��Sr)�_getr�r�r�rrrr�ysz NullProvider.get_resource_stringcCs|�|�|j|��Sr)�_hasr�r��r�r�rrrr�|szNullProvider.has_resourcecCs|�|j|�Sr)r��egg_info�r�r�rrr�_get_metadata_pathszNullProvider._get_metadata_pathcCs |js|jS|�|�}|�|�Sr)r�r�r��r�r�r�rrrr��s
zNullProvider.has_metadatac
Cst|js
dS|�|�}|�|�}tjr(|Sz|�d�WStk
rn}z|jd�||�7_�W5d}~XYnXdS)Nr��utf-8z in {} file at path: {})	r�r�r�r�PY2�decode�UnicodeDecodeError�reasonr�)r�r�r��value�excrrrr��s

zNullProvider.get_metadatacCst|�|��Sr�rxr�r�rrrr��szNullProvider.get_metadata_linescCs|�|�|j|��Sr)�_isdirr�r�r�rrrr`�szNullProvider.resource_isdircCs|jo|�|�|j|��Sr)r�r�r�r�rrrr��szNullProvider.metadata_isdircCs|�|�|j|��Sr)�_listdirr�r�r�rrrr^�szNullProvider.resource_listdircCs|jr|�|�|j|��SgSr)r�r�r�r�rrrr��szNullProvider.metadata_listdirc
Cs�d|}|�|�s$tdjft����|�|��dd�}|�dd�}|�|j|�}||d<tj	�
|�r�t|���}t
||d�}t|||�n>dd	lm}t|�d|�d�|f||<t
||d�}	t|	||�dS)
Nzscripts/z<Script {script!r} not found in metadata at {self.egg_info!r}z
�
�
r��execr)�cache)r�rnr�r�r�r�r�r�r�r�r�r�read�compiler��	linecacher��lenr)
r�r�r��script�script_text�script_filename�source�coder��script_coderrrrT�s.
���zNullProvider.run_scriptcCstd��dS�Nz9Can't perform this operation for unregistered loader type��NotImplementedErrorr�rrrr��s�zNullProvider._hascCstd��dSr�r�r�rrrr��s�zNullProvider._isdircCstd��dSr�r�r�rrrr��s�zNullProvider._listdircCs*|�|�|r&tjj|f|�d���S|S)N�/)�_validate_resource_pathr�r�rLr)r��baser�rrrr��s
zNullProvider._fncCsptjj|�tj�kp&t�|�p&t�|�}|s0dSd}t�|�rPt�|�sPt|��t	j
|dd�dtdd�dS)aO
        Validate the resource paths according to the docs.
        https://setuptools.readthedocs.io/en/latest/pkg_resources.html#basic-resource-access

        >>> warned = getfixture('recwarn')
        >>> warnings.simplefilter('always')
        >>> vrp = NullProvider._validate_resource_path
        >>> vrp('foo/bar.txt')
        >>> bool(warned)
        False
        >>> vrp('../foo/bar.txt')
        >>> bool(warned)
        True
        >>> warned.clear()
        >>> vrp('/foo/bar.txt')
        >>> bool(warned)
        True
        >>> vrp('foo/../../bar.txt')
        >>> bool(warned)
        True
        >>> warned.clear()
        >>> vrp('foo/f../bar.txt')
        >>> bool(warned)
        False

        Windows path separators are straight-up disallowed.
        >>> vrp(r'\foo/bar.txt')
        Traceback (most recent call last):
        ...
        ValueError: Use of .. or absolute path in a resource path is not allowed.

        >>> vrp(r'C:\foo/bar.txt')
        Traceback (most recent call last):
        ...
        ValueError: Use of .. or absolute path in a resource path is not allowed.

        Blank values are allowed

        >>> vrp('')
        >>> bool(warned)
        False

        Non-string values are not.

        >>> vrp(None)
        Traceback (most recent call last):
        ...
        AttributeError: ...
        Nz=Use of .. or absolute path in a resource path is not allowed.r�z/ and will raise exceptions in a future release.r�)�
stacklevel)r�r��pardirr�	posixpath�sep�isabs�ntpathrOr�r��DeprecationWarning)r��invalidr�rrrr��s6���z$NullProvider._validate_resource_pathcCs$t|jd�r|j�|�Std��dS)N�get_dataz=Can't perform this operation for loaders without 'get_data()')r�r�r�r�r�rrrr� s
�zNullProvider._get)rrrr�egg_namer�r�rr�r�r�r�r�r�r�r�r`r�r^r�rTr�r�r�r�r�r�r�rrrrr�hs2
Jc@s eZdZdZdd�Zdd�ZdS)r�z&Provider based on a virtual filesystemcCst�||�|��dSr)r�r�
_setup_prefixr�rrrr.szEggProvider.__init__cCsZ|j}d}||krVt|�r@tj�|�|_tj�|d�|_||_qV|}tj�	|�\}}q
dS)N�EGG-INFO)
r��_is_egg_pathr�r��basenamer�rLr��egg_rootr)r�r��oldr�rrrr�2szEggProvider._setup_prefixN)rrrrrr�rrrrr�+sc@sDeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Ze	dd
��Z
dS)r�z6Provides access to package resources in the filesystemcCstj�|�Sr)r�r�r�r�rrrr�DszDefaultProvider._hascCstj�|�Sr)r�r�r
r�rrrr�GszDefaultProvider._isdircCs
t�|�Sr)r��listdirr�rrrr�JszDefaultProvider._listdircCst|�|j|�d�S�N�rb)rr�r�r�rrrr�Msz#DefaultProvider.get_resource_streamc
Cs*t|d��}|��W5QR�SQRXdSr�)rr�)r�r��streamrrrr�PszDefaultProvider._getcCs,d}|D]}tt|td��}t||�qdS)N)�SourceFileLoader�SourcelessFileLoader)r��importlib_machinery�typer�)r	�loader_namesr��
loader_clsrrr�	_registerTszDefaultProvider._registerN)rrrrr�r�r�r�r�rJr�rrrrr�Asc@s8eZdZdZdZdd�ZZdd�Zdd�Zd	d
�Z	dS)r�z.Provider that returns nothing for all requestsNcCsdS�NFrr�rrrrBdrCzEmptyProvider.<lambda>cCsdS�Nr�rr�rrrr�fszEmptyProvider._getcCsgSrrr�rrrr�iszEmptyProvider._listdircCsdSrrr�rrrrlszEmptyProvider.__init__)
rrrrr�r�r�r�r�rrrrrr�_sc@s eZdZdZedd��ZeZdS)�ZipManifestsz
    zip manifest builder
    c
s@t�|��,��fdd����D�}t|�W5QR�SQRXdS)a
        Build a dictionary similar to the zipimport directory
        caches, except instead of tuples, store ZipInfo objects.

        Use a platform-specific path separator (os.sep) for the path keys
        for compatibility with pypy on Windows.
        c3s&|]}|�dtj���|�fVqdS)r�N)r�r�r��getinfo�rr���zfilerrr�s��z%ZipManifests.build.<locals>.<genexpr>N)�zipfile�ZipFile�namelistr')r	r�r-rr�r�buildxs
	
�zZipManifests.buildN)rrrrrJr��loadrrrrr�ss
r�c@s$eZdZdZe�dd�Zdd�ZdS)�MemoizedZipManifestsz%
    Memoized zipfile manifests.
    �manifest_modzmanifest mtimecCsRtj�|�}t�|�j}||ks.||j|krH|�|�}|�||�||<||jS)zW
        Load a manifest at path or return a suitable manifest already loaded.
        )	r�r��normpathr��st_mtime�mtimer�r��manifest)r�r�r�r�rrrr��s
zMemoizedZipManifests.loadN)rrrrr'�
namedtupler�r�rrrrr��sr�c@s�eZdZdZdZe�Zdd�Zdd�Zdd�Z	e
d	d
��Zdd�Ze
d
d��Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd �ZdS)!r�z"Resource support for zips and eggsNcCs t�||�|jjtj|_dSr)r�rr��archiver�r��zip_prer�rrrr�szZipProvider.__init__cCsP|�tj�}||jjkrdS|�|j�r:|t|j�d�Std||jf��dS)Nr��%s is not a subpath of %s)	�rstripr�r�r�rr�rr��AssertionError�r��fspathrrr�
_zipinfo_name�s�zZipProvider._zipinfo_namecCsP|j|}|�|jtj�r:|t|j�dd��tj�Std||jf��dS)Nrr)rr�r�r�r�r�rr)r��zip_pathrrrr�_parts�s
�zZipProvider._partscCs|j�|jj�Sr)�_zip_manifestsr�r�rr�rrr�zipinfo�szZipProvider.zipinfocCs\|jstd��|�|�}|��}d�|�|��|krP|D]}|�||�|��q8|�||�S)Nz5resource_filename() only supported for .egg, not .zipr�)r�r��_resource_to_zip�_get_eager_resourcesrLr	�_extract_resource�
_eager_to_zip)r�r�r�r�eagersr�rrrr��s�
z!ZipProvider.get_resource_filenamecCs"|j}|jd}t�|�}||fS)N)rrr�)�	file_size�	date_time�time�mktime)�zip_stat�sizer�	timestamprrr�_get_date_and_size�s

zZipProvider._get_date_and_sizec
Csx||��kr@|��|D]}|�|tj�||��}qtj�|�S|�|j|�\}}ts`t	d��z�|�
|j|�|��}|�
||�r�|WStdtj�|�d�\}}	t�||j�|��t�|�t|	||f�|�|	|�zt|	|�Wnhtjk
�rNtj�|��rH|�
||��r |YWStjdk�rHt|�t|	|�|YWS�YnXWn tjk
�rr|��YnX|S)Nz>"os.rename" and "os.unlink" are not supported on this platformz	.$extract)�dirr�)�_indexrr�r�rLr�rr�
WRITE_SUPPORT�IOErrorr�r�r	�_is_current�_mkstemp�writer�r��closerr�r
�error�isfiler�rrz)
r�r�rr��lastrr�	real_path�outf�tmpnamrrrr�sN��
�




zZipProvider._extract_resourcec		Csx|�|j|�\}}tj�|�s$dSt�|�}|j|ksB|j|krFdS|j�	|�}t
|d��}|��}W5QRX||kS)zK
        Return True if the file_path is current for this zip_path
        Fr�)rrr�r�r"r��st_sizer�r�r�rr�)	r��	file_pathrrrr��zip_contents�f�
file_contentsrrrrs
zZipProvider._is_currentcCs>|jdkr8g}dD]}|�|�r|�|�|��q||_|jS)N)znative_libs.txtzeager_resources.txt)rr�r.r�)r�rr�rrrr
#s

z ZipProvider._get_eager_resourcesc	Cs�z|jWStk
r�i}|jD]V}|�tj�}|r"tj�|dd��}||krh||�|d�q"q2|��g||<q2q"||_|YSXdS)Nr�)	�	_dirindex�AttributeErrorrrr�r�rLr�r*)r��indr��parts�parentrrrr,s
zZipProvider._indexcCs |�|�}||jkp||��kSr)rrr)r�rrrrrr�=s
zZipProvider._hascCs|�|�|��kSr)rrrrrrr�AszZipProvider._isdircCst|���|�|�d��S�Nr)r%rr�rrrrrr�DszZipProvider._listdircCs|�|�|j|��Sr)rr�r�r�rrrrGszZipProvider._eager_to_zipcCs|�|�|j|��Sr)rr�r�r�rrrrJszZipProvider._resource_to_zip)rrrrrr�r
rrr	r�rr�r�rrrr
rr�r�r�rrrrrrr��s(



7	c@s@eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dS)r�a*Metadata handler for standalone PKG-INFO files

    Usage::

        metadata = FileMetadata("/path/to/PKG-INFO")

    This provider rejects all data and metadata requests except for PKG-INFO,
    which is treated as existing, and will be the contents of the file at
    the provided location.
    cCs
||_dSr�r�r�rrrr]szFileMetadata.__init__cCs|jSrr2r�rrrr�`szFileMetadata._get_metadata_pathcCs|dkotj�|j�S)N�PKG-INFO)r�r�r"r�rrrr�cszFileMetadata.has_metadatac	CsD|dkrtd��tj|jddd��}|��}W5QRX|�|�|S)Nr3z(No metadata except PKG-INFO is availabler�r�)�encoding�errors)r�r�rr�r��_warn_on_replacement)r�r�r*�metadatarrrr�fs
zFileMetadata.get_metadatacCs2d�d�}||kr.d}|jft��}t�|�dS)Ns�r�z2{self.path} could not be properly decoded in UTF-8)r�r�r�r�r�)r�r7�replacement_charrxr�rrrr6os

z!FileMetadata._warn_on_replacementcCst|�|��Srr�r�rrrr�wszFileMetadata.get_metadata_linesN)
rrrrrr�r�r�r6r�rrrrr�Qs	c@seZdZdZdd�ZdS)r�asMetadata provider for egg directories

    Usage::

        # Development eggs:

        egg_info = "/path/to/PackageName.egg-info"
        base_dir = os.path.dirname(egg_info)
        metadata = PathMetadata(base_dir, egg_info)
        dist_name = os.path.splitext(os.path.basename(egg_info))[0]
        dist = Distribution(basedir, project_name=dist_name, metadata=metadata)

        # Unpacked egg directories:

        egg_path = "/path/to/PackageName-ver-pyver-etc.egg"
        metadata = PathMetadata(egg_path, os.path.join(egg_path,'EGG-INFO'))
        dist = Distribution.from_filename(egg_path, metadata=metadata)
    cCs||_||_dSr)r�r�)r�r�r�rrrr�szPathMetadata.__init__N�rrrrrrrrrr�{sc@seZdZdZdd�ZdS)r�z Metadata provider for .egg filescCsD|jtj|_||_|jr0tj�|j|j�|_n|j|_|�	�dS)z-Create a metadata provider from a zipimporterN)
rr�r�rr��prefixr�rLr�r�)r��importerrrrr�szEggMetadata.__init__Nr9rrrrr��sr'��_distribution_finderscCs|t|<dS)axRegister `distribution_finder` to find distributions in sys.path items

    `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
    handler), and `distribution_finder` is a callable that, passed a path
    item and the importer instance, yields ``Distribution`` instances found on
    that path item.  See ``pkg_resources.find_on_path`` for an example.Nr<)�
importer_type�distribution_finderrrrr��scCst|�}tt|�}||||�S)z.Yield distributions accessible via `path_item`)rr�r=)�	path_item�onlyr;�finderrrrrd�s
c	cs�|j�d�rdSt|�}|�d�r2tj||d�V|r:dS|�d�D]|}t|�r�tj	�
||�}tt�
|�|�}|D]
}|VqrqD|���d�rDtj	�
||�}tt�
|��}||_t�|||�VqDdS)z@
    Find eggs in zip files; possibly multiple nested eggs.
    z.whlNr3�r7r��
.dist-info)r�endswithr�r�rk�
from_filenamer^r�r�r�rL�find_eggs_in_zip�	zipimport�zipimporterrZr��
from_location)	r;r@rAr7�subitem�subpathrr��submetarrrrG�s$

rGcCsdSr1r)r;r@rArrr�find_nothing�srNcCsdd�}t||dd�S)aL
    Given a list of filenames, return them in descending order
    by version number.

    >>> names = 'bar', 'foo', 'Python-2.7.10.egg', 'Python-2.7.2.egg'
    >>> _by_version_descending(names)
    ['Python-2.7.10.egg', 'Python-2.7.2.egg', 'foo', 'bar']
    >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.egg'
    >>> _by_version_descending(names)
    ['Setuptools-1.2.3.egg', 'Setuptools-1.2.3b1.egg']
    >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.post1.egg'
    >>> _by_version_descending(names)
    ['Setuptools-1.2.3.post1.egg', 'Setuptools-1.2.3b1.egg']
    cSs2tj�|�\}}t�|�d�|g�}dd�|D�S)z6
        Parse each component of the filename
        r�cSsg|]}tj�|��qSr)rrr�)r�partrrr�
<listcomp>�sz?_by_version_descending.<locals>._by_version.<locals>.<listcomp>)r�r��splitext�	itertools�chainr)r��extr/rrr�_by_version�sz+_by_version_descending.<locals>._by_versionTr^)�sorted)rrUrrr�_by_version_descending�srWc
#s�t���t��r4tj�t�tj��d��d�VdSt��}��fdd�|D�}t	|�}|D]2}tj��|�}t
�|��}||�D]
}	|	Vq�q\dS)z6Yield distributions accessible on a sys.path directoryr�rCNc3s|]}t�|��r|VqdSr)�dist_factory)rr�rAr@rrrs�zfind_on_path.<locals>.<genexpr>)�_normalize_cached�_is_unpacked_eggrkrFr�r�r�rL�safe_listdirrWrX)
r;r@rAr��filtered�path_item_entriesr�fullpath�factoryr�rrYr�find_on_path�s(���racCsH|��}tt|jd��}|r tS|s0t|�r0tS|sB|�d�rBtSt�S)z9
    Return a dist_factory for a path_item and entry
    )�	.egg-inforDz	.egg-link)	rZrPrrE�distributions_from_metadatar�rd�resolve_egg_link�NoDists)r@rrArZ�is_metarrrrXs������rXc@s*eZdZdZdd�ZejreZdd�ZdS)rezS
    >>> bool(NoDists())
    False

    >>> list(NoDists()('anything'))
    []
    cCsdSr�rr�rrr�__bool__/szNoDists.__bool__cCstd�Sr1)�iter)r�r_rrr�__call__4szNoDists.__call__N)	rrrrrgrr��__nonzero__rirrrrre's
rec
Csvzt�|�WSttfk
r$YnNtk
rp}z0|jtjtjtjfkpXt	|dd�dk}|s`�W5d}~XYnXdS)zI
    Attempt to list contents of path, but suppress some exceptions.
    �winerrorNir)
r�r��PermissionError�NotADirectoryError�OSError�errno�ENOTDIR�EACCES�ENOENTr�)r�r��	ignorablerrrr\8s�r\ccsftj�|�}tj�|�r:tt�|��dkr.dSt||�}nt|�}tj�|�}t	j
|||td�VdS)Nr)�
precedence)r�r�r�r
r�r�r�r�r�rkrJr�)r��rootr7rrrrrcMs�rcc	cs4t|��"}|D]}|��}|r|VqW5QRXdS)z1
    Yield non-empty lines from file at path
    N)r�strip)r�r*�linerrr�non_empty_lines\s

rxcs.t��}�fdd�|D�}tt|�}t|d�S)za
    Given a path to an .egg-link, resolve distributions
    present in the referenced path.
    c3s$|]}tj�tj���|�VqdSr)r�r�rLr�)r�refr2rrrms�z#resolve_egg_link.<locals>.<genexpr>r)rxrrd�next)r��referenced_paths�resolved_paths�dist_groupsrr2rrdgs
�
rd�
FileFinder��_namespace_handlers)�_namespace_packagescCs|t|<dS)a�Register `namespace_handler` to declare namespace packages

    `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
    handler), and `namespace_handler` is a callable like this::

        def namespace_handler(importer, path_entry, moduleName, module):
            # return a path_entry to use for child packages

    Namespace handlers are only called if the importer object has already
    agreed that it can handle the relevant path item, and they should only
    return a subpath if the module __path__ does not already contain an
    equivalent subpath.  For an example namespace handler, see
    ``pkg_resources.file_ns_handler``.
    Nr)r>�namespace_handlerrrrr�~sc	Cs�t|�}|dkrdSt���t�d�|�|�}W5QRX|dkrHdStj�|�}|dkr�t�	|�}tj|<g|_
t|�nt|d�s�t
d|��tt|�}|||||�}|dk	r�|j
}|�|�|�|�t|||�|S)zEEnsure that named package includes a subpath of path_item (if needed)N�ignore�__path__�Not a package:)rr��catch_warnings�simplefilter�find_modulerJr�r��types�
ModuleTyper��_set_parent_nsr�r�r�r�r��load_module�_rebuild_mod_path)�packageNamer@r;r�r��handlerrLr�rrr�
_handle_ns�s.







r�csjdd�tjD���fdd����fdd�}t||d�}dd�|D�}t|jt�r`||jd	d	�<n||_d	S)
zq
    Rebuild module.__path__ ensuring that all entries are ordered
    corresponding to their sys.path order
    cSsg|]}t|��qSr�rZ�r�prrrrP�sz%_rebuild_mod_path.<locals>.<listcomp>cs.z��|�WStk
r(td�YSXdS)z/
        Workaround for #520 and #513.
        �infN)�indexrO�float)r)�sys_pathrr�safe_sys_path_index�sz._rebuild_mod_path.<locals>.safe_sys_path_indexcs<|�tj�}��d�d}|d|�}�ttj�|���S)zR
        Return the ordinal of the path based on its position in sys.path
        rErN)rr�r��countrZrL)r��
path_parts�module_partsr/)�package_namer�rr�position_in_sys_path�sz/_rebuild_mod_path.<locals>.position_in_sys_path)r;cSsg|]}t|��qSrr�r�rrrrP�sN)rJr�rVr�r�r%)�	orig_pathr�r�r��new_pathr)r�r�r�rr��s		r�cCs�t��z�|tkrW��dStj}|�d�\}}}|r|t|�|tkrLt|�ztj	|j
}Wntk
rztd|��YnXt�
|p�dg��|�t�
|g�|D]}t||�q�W5t��XdS)z9Declare that package 'packageName' is a namespace packageNrEr�)�_imp�acquire_lock�release_lockr�rJr��
rpartitionrar�r�r�r-r�rr�r�)r�r�r0r�r@rrrra�s&cCsFt��z.t�|d�D]}t||�}|rt||�qW5t��XdS)zDEnsure that previously-declared namespace packages include path_itemrN)r�r�r�r�r�r�r�)r@r0�packagerLrrrr��s
cCsDtj�||�d�d�}t|�}|jD]}t|�|kr&q@q&|SdS)zBCompute an ns-package subpath for a filesystem or zipfile importerrEr�N)r�r�rLrrZr�)r;r@r�r�rL�
normalizedrrrr�file_ns_handler�s
r�cCsdSrr)r;r@r�r�rrr�null_ns_handler	sr�cCs tj�tj�tj�t|����S)z1Normalize a file/dir name for comparison purposes)r�r��normcase�realpathr��
_cygwin_patch�r�rrrr	s�cCstjdkrtj�|�S|S)a
    Contrary to POSIX 2008, on Cygwin, getcwd (3) contains
    symlink components. Using
    os.path.abspath() works around this limitation. A fix in os.getcwd()
    would probably better, in Cygwin even more so, except
    that this seems to be by design...
    �cygwin)rJrKr�r��abspathr�rrrr� 	sr�cCs8z
||WStk
r2t|�||<}|YSXdSr)r�r)r�r��resultrrrrZ+	s

rZcCs|���d�S)z7
    Determine if given path appears to be an egg.
    �.egg)rZrEr2rrrr�3	sr�cCs t|�otj�tj�|dd��S)z@
    Determine if given path appears to be an unpacked egg.
    r�r3)r�r�r�r"rLr2rrrr[:	s�r[cCs<|�d�}|��}|r8d�|�}ttj||tj|�dS)NrE)rr*rL�setattrrJr�)r�r/r�r0rrrr�D	s


r�ccsZt|tj�r8|��D] }|��}|r|�d�s|Vqn|D]}t|�D]
}|VqHq<dS)z9Yield non-empty/non-comment lines of a string or sequence�#N)r�rr��
splitlinesrvr�rx)�strs�s�ssrrrrxL	s
z\w+(\.\w+)*$z�
    (?P<name>[^-]+) (
        -(?P<ver>[^-]+) (
            -py(?P<pyver>[^-]+) (
                -(?P<plat>.+)
            )?
        )?
    )?
    c@s�eZdZdZddd�Zdd�Zdd	�Zddd�Zd
d�Zddd�Z	e
�d�Ze
ddd��Ze
dd��Ze
ddd��Ze
ddd��ZdS) rmz3Object representing an advertised importable objectrNcCs<t|�std|��||_||_t|�|_t|�|_||_dS)NzInvalid module name)�MODULErOr��module_name�tuple�attrsr-r�)r�r�r�r�r-r�rrrrl	s


zEntryPoint.__init__cCsHd|j|jf}|jr*|dd�|j�7}|jrD|dd�|j�7}|S)Nz%s = %s�:rEz [%s]�,)r�r�r�rLr-)r�r�rrrr�u	szEntryPoint.__str__cCsdt|�S)NzEntryPoint.parse(%r)�r�r�rrrr�}	szEntryPoint.__repr__FcOs|r|j||�|��S)zH
        Require packages for this EntryPoint, then resolve it.
        )r�r�rSr)r�rSrA�kwargsrrrr��	szEntryPoint.loadc
CsXt|jdgdd�}zt�t|j|�WStk
rR}ztt|���W5d}~XYnXdS)zD
        Resolve the entry point from its module and attrs.
        rr)�fromlist�levelN)	r�r��	functools�reducer�r�r-rr�)r�r�r�rrrr�	s
zEntryPoint.resolvecCsL|jr|jstd|��|j�|j�}tj||||jd�}tttj|��dS)Nz&Can't require() without a distribution)r-)	r-r�rqrrbrr%rr
)r�r1r2rr-rrrrS�	s

zEntryPoint.requirez]\s*(?P<name>.+?)\s*=\s*(?P<module>[\w.]+)\s*(:\s*(?P<attr>[\w.]+))?\s*(?P<extras>\[.*\])?\s*$cCsf|j�|�}|sd}t||��|��}|�|d�}|drJ|d�d�nd}||d|d|||�S)aParse a single entry point from string `src`

        Entry point syntax follows the form::

            name = some.module:some.attr [extra1, extra2]

        The entry name and module name are required, but the ``:attrs`` and
        ``[extras]`` parts are optional
        z9EntryPoint must be in 'name=module:attrs [extras]' formatr-�attrrErr�r�)�patternrIrO�	groupdict�
_parse_extrasr)r	�srcr�rQr��resr-r�rrrr��	s
zEntryPoint.parsecCs(|sdSt�d|�}|jr"t��|jS)Nr�x)rlr��specsrOr-)r	�extras_specr�rrrr��	szEntryPoint._parse_extrascCsVt|�std|��i}t|�D]2}|�||�}|j|krFtd||j��|||j<q|S)zParse an entry point groupzInvalid group namezDuplicate entry point)r�rOrxr�r�)r	rN�linesr��thisrw�eprrr�parse_group�	s

zEntryPoint.parse_groupcCstt|t�r|��}nt|�}i}|D]J\}}|dkrB|s:q$td��|��}||kr\td|��|�|||�||<q$|S)z!Parse a map of entry point groupsNz%Entry points must be listed in groupszDuplicate group name)r�r'r-ryrOrvr�)r	�datar��mapsrNr�rrr�	parse_map�	s


zEntryPoint.parse_map)rrN)F)NN)N)N)N)rrrrrr�r�r�rrSr�r�r�rJr�r�r�r�rrrrrmi	s$
	



�	
cCs>|sdStj�|�}|d�d�r:tj�|dd�d�S|S)Nr�r�zmd5=)r�)rr��urlparser��
urlunparse)r�parsedrrr�_remove_md5_fragment�	sr�cCs@dd�}t||�}tt|�d�}|�d�\}}}t|���p>dS)z�
    Given an iterable of lines from a Metadata file, return
    the value of the Version field, if present, or None otherwise.
    cSs|���d�S)Nzversion:)rZr�)rwrrr�is_version_line�	sz+_version_from_file.<locals>.is_version_liner�r�N)rrzrh�	partitionrurv)r�r��
version_linesrwr�r�rrr�_version_from_file�	s

r�cs�eZdZdZdZddddedefdd�ZedSdd��Z	dd	�Z
ed
d��Zdd
�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zedd��Zedd��Zdd�Zed d!��Zed"d#��Zed$d%��Zd&d'�ZdTd)d*�Zd+d,�Zd-d.�Zd/d0�ZdUd2d3�Z d4d5�Z!d6d7�Z"d8d9�Z#d:d;�Z$�fd<d=�Z%e&e'd>��s4[%edVd?d@��Z(dAdB�Z)dCdD�Z*dWdEdF�Z+dGdH�Z,dXdIdJ�Z-dKdL�Z.dMdN�Z/dOdP�Z0edQdR��Z1�Z2S)Yrkz5Wrap an actual or potential sys.path entry w/metadatar3NcCsFt|pd�|_|dk	r t|�|_||_||_||_||_|p>t|_	dS)N�Unknown)
rtr/ru�_versionrVrKrrtr��	_provider)r�rr7r/rrVrKrtrrrr
s
zDistribution.__init__cKs~dgd\}}}}tj�|�\}}	|	��tkr^t|	��}t|�}
|
r^|
�dddd�\}}}}|||f||||d�|����S)Nr�r��ver�pyverrP)r/rrVrK)r�r�rQrZ�_distributionImpl�EGG_NAMErN�_reload_version)r	rr�r7r*r/rrVrKrTrIrrrrJ
s.����zDistribution.from_locationcCs|Srrr�rrrr�%
szDistribution._reload_versioncCs(|j|j|jt|j�|jpd|jp$dfSr�)�parsed_versionrtr;r�rrVrKr�rrrr](
s�zDistribution.hashcmpcCs
t|j�Sr)�hashr]r�rrr�__hash__3
szDistribution.__hash__cCs|j|jkSr�r]�r�rfrrr�__lt__6
szDistribution.__lt__cCs|j|jkSrr�r�rrr�__le__9
szDistribution.__le__cCs|j|jkSrr�r�rrr�__gt__<
szDistribution.__gt__cCs|j|jkSrr�r�rrr�__ge__?
szDistribution.__ge__cCst||j�sdS|j|jkSr�)r�r�r]r�rrr�__eq__B
szDistribution.__eq__cCs
||kSrrr�rrr�__ne__H
szDistribution.__ne__cCs6z|jWStk
r0|j��|_}|YSXdSr)�_keyr-r/rZrerrrr;O
s
zDistribution.keycCst|d�st|j�|_|jS)N�_parsed_version)r�r#rr�r�rrrr�W
s
zDistribution.parsed_versioncCsXtjj}t|j|�}|sdS|js&dSt�d����dd�}t	�
|jft|��t
�dS)Na>
            '{project_name} ({version})' is being parsed as a legacy,
            non PEP 440,
            version. You may find odd behavior and sort order.
            In particular it will be sorted as less than 0.0. It
            is recommended to migrate to PEP 440 compatible
            versions.
            r�r�)rrr!r�r�rrrsrvr�r�r�r��varsr)r��LV�	is_legacyrxrrr�_warn_legacy_version^
s�	z!Distribution._warn_legacy_versioncCsZz|jWStk
rT|��}|dkrL|�|j�}d�|j|�}t||��|YSXdS)Nz4Missing 'Version:' header and/or {} file at path: {})r�r-�_get_version�_get_metadata_path_for_display�PKG_INFOr�rO)r�rr�r�rrrrx
s��
zDistribution.versioncCs4z|jWStk
r,|�|���|_YnX|jS)z~
        A map of extra to its list of (direct) requirements
        for this distribution, including the null extra.
        )�_Distribution__dep_mapr-�_filter_extras�_build_dep_mapr�rrr�_dep_map�
s
zDistribution._dep_mapcCsrttd|��D]^}|}|�|�}|�d�\}}}|oDt|�pDt|�}|rNg}t|�pXd}|�|g��|�q|S)z�
        Given a mapping of extras to dependencies, strip off
        environment markers and filter out any dependencies
        not matching the markers.
        Nr�)	r%rr*r�r|r}rzrr.)�dmrK�	new_extrarr�rM�fails_markerrrrr��
s
�zDistribution._filter_extrascCs@i}dD]2}t|�|��D]\}}|�|g��t|��qq|S)N)zrequires.txtzdepends.txt)ry�
_get_metadatarr.rs)r�r�r�rKrrrrr��
s
zDistribution._build_dep_maprc	Csf|j}g}|�|�dd��|D]@}z|�|t|��Wq tk
r^td||f��Yq Xq |S)z@List of Requirements needed for this distro if `extras` are usedNrz%s has no such extra feature %r)r�r.r�rzr�rq)r�r-r��depsrTrrrr�
s
�zDistribution.requirescCs,z|j�|�}Wntk
r&YdSX|S)zK
        Return the path to the given metadata file, if available.
        z[could not detect])r�r�r|r�rrrr��
s
z+Distribution._get_metadata_path_for_displayccs$|�|�r |�|�D]
}|VqdSr)r�r�)r�r�rwrrrr��
s
zDistribution._get_metadatacCs|�|j�}t|�}|Sr)r�r�r�)r�r�rrrrr��
szDistribution._get_versionFcCsV|dkrtj}|j||d�|tjkrRt|j�|�d�D]}|tjkr:t|�q:dS)z>Ensure distribution is importable on `path` (default=sys.path)Nr�namespace_packages.txt)rJr�rr�rr�r�ra)r�r�r��pkgrrr�activate�
s


zDistribution.activatecCs8dt|j�t|j�|jptf}|jr4|d|j7}|S)z@Return what this distribution's standard .egg filename should bez
%s-%s-py%sr�)r{r/rrVrlrK)r�r�rrrr��
s�zDistribution.egg_namecCs |jrd||jfSt|�SdS)Nz%s (%s))rr�r�rrrr��
szDistribution.__repr__cCs@zt|dd�}Wntk
r(d}YnX|p0d}d|j|fS)Nrz[unknown version]z%s %s)r�rOr/)r�rrrrr��
s
zDistribution.__str__cCs|�d�rt|��t|j|�S)zADelegate all unrecognized public attributes to .metadata providerr�)r�r-r�r�)r�r�rrr�__getattr__�
s
zDistribution.__getattr__cs.tttt|����tdd�|j��D��B�S)Ncss|]}|�d�s|VqdS�r�N)r�)rr�rrrrs
�z'Distribution.__dir__.<locals>.<genexpr>)r%r)�superrk�__dir__r�r�rirrrs���zDistribution.__dir__rcKs|jt|�tj�|�|f|�Sr)rJrZr�r�r�)r	r�r7r*rrrrFs
��zDistribution.from_filenamecCs<t|jtjj�r"d|j|jf}nd|j|jf}t�|�S)z?Return a ``Requirement`` that matches this distribution exactlyz%s==%sz%s===%s)r�r�rrrr/rlr�)r��specrrrr;szDistribution.as_requirementcCs.|�||�}|dkr&td||ff��|��S)z=Return the `name` entry point of `group` or raise ImportErrorNzEntry point %r not found)rYrr�)r�rNr�r�rrrrW!szDistribution.load_entry_pointcCsPz
|j}Wn,tk
r6t�|�d�|�}|_YnX|dk	rL|�|i�S|S)r�zentry_points.txtN)�_ep_mapr-rmr�r�r�)r�rN�ep_maprrrrX(s
�zDistribution.get_entry_mapcCs|�|��|�Sr�)rXr�rrrrrY4szDistribution.get_entry_infoc
Cs4|p|j}|sdSt|�}tj�|�}dd�|D�}t|�D]|\}}||kr^|rVq�q�dSq<||kr<|jtkr<|s�|||d�kr�dS|tjkr�|�	�|�
||�|�
||�q�q<|tjkr�|�	�|r�|�
d|�n
|�|�dSz|�||d�}	Wnt
k
�rY�q0Yq�X||	=||	=|	}q�dS)a�Ensure self.location is on path

        If replace=False (default):
            - If location is already in path anywhere, do nothing.
            - Else:
              - If it's an egg and its parent directory is on path,
                insert just ahead of the parent.
              - Else: add to the end of path.
        If replace=True:
            - If location is already on path anywhere (not eggs)
              or higher priority than its parent (eggs)
              do nothing.
            - Else:
              - If it's an egg and its parent directory is on path,
                insert just ahead of the parent,
                removing any lower-priority entries.
              - Else: add it to the front of path.
        NcSsg|]}|rt|�p|�qSrr�r�rrrrPRsz*Distribution.insert_on.<locals>.<listcomp>rr)rrZr�r�r��	enumeratertr�rJ�check_version_conflictr!r�r�rO)
r�r��locr��nloc�bdir�npathr�r�nprrrr8s@



zDistribution.insert_oncCs�|jdkrdSt�|�d��}t|j�}|�d�D]p}|tjks2||ks2|tkrRq2|dkr\q2t	tj|dd�}|r�t|��
|�s2|�
|j�r�q2td|||jf�q2dS)N�
setuptoolsr�z
top_level.txt)�
pkg_resourcesr�siter�zIModule %s was already imported from %s, but %s is being added to sys.path)r;r'r(r�rrrJr�r�r�r��
issue_warning)r��nspr�modname�fnrrrr
|s*

�
�
��z#Distribution.check_version_conflictcCs6z
|jWn&tk
r0tdt|��YdSXdS)NzUnbuilt egg for FT)rrOrr�r�rrrr`�s
zDistribution.has_versioncKs@d}|��D]}|�|t||d��q|�d|j�|jf|�S)z@Copy this distribution, substituting in any changed keyword argsz<project_name version py_version platform location precedenceNr7)rrr�r�r�)r�r*rr�rrr�clone�s
zDistribution.clonecCsdd�|jD�S)NcSsg|]}|r|�qSrr)r�deprrrrP�sz'Distribution.extras.<locals>.<listcomp>)r�r�rrrr-�szDistribution.extras)N)r)NF)N)N)NF)3rrrrr�rlr�rrJrJr�r�r]r�r�r�r�r�r�r�r;r�r�rr�r�r�r�rr�r�r�rr�r�r�rrr��objectrFr;rWrXrYrr
r`rr-�
__classcell__rrrirrk
st�










		

Dc@seZdZdd�ZdS)�EggInfoDistributioncCs|��}|r||_|S)a�
        Packages installed by distutils (e.g. numpy or scipy),
        which uses an old safe_version, and so
        their version numbers can get mangled when
        converted to filenames (e.g., 1.11.0.dev0+2329eae to
        1.11.0.dev0_2329eae). These distributions will not be
        parsed properly
        downstream by Distribution and safe_version, so
        take an extra step and try to get the version number from
        the metadata file itself instead of the filename.
        )r�r�)r��
md_versionrrrr��sz#EggInfoDistribution._reload_versionN)rrrr�rrrrr�src@s>eZdZdZdZe�d�Zedd��Z	edd��Z
dd	�Zd
S)�DistInfoDistributionzV
    Wrap an actual or potential sys.path entry
    w/metadata, .dist-info style.
    �METADATAz([\(,])\s*(\d.*?)\s*([,\)])cCsFz|jWStk
r@|�|j�}tj���|�|_|jYSXdS)zParse and cache metadataN)�	_pkg_infor-r�r��email�parser�Parser�parsestr)r�r7rrr�_parsed_pkg_info�sz%DistInfoDistribution._parsed_pkg_infocCs2z|jWStk
r,|��|_|jYSXdSr)�_DistInfoDistribution__dep_mapr-�_compute_dependenciesr�rrrr��s

zDistInfoDistribution._dep_mapcs�dgi}|_g�|j�d�p gD]}��t|��q"�fdd�}t|d��}|d�|�|j�d�pjgD](}t|���}tt||��|�||<ql|S)z+Recompute this distribution's dependencies.Nz
Requires-Distc3s*�D] }|jr|j�d|i�r|VqdS)NrKrL)rKr��rrr�reqs_for_extra�szBDistInfoDistribution._compute_dependencies.<locals>.reqs_for_extrazProvides-Extra)	r%r$�get_allr.rs�	frozensetrzrvr%)r�r�r�r(�commonrK�s_extrarr'rr&�sz*DistInfoDistribution._compute_dependenciesN)rrrrr�r�r��EQEQr�r$r�r&rrrrr�s

	
r)r�rbrDcOsZd}t�}zt�|�j|kr&|d7}qWntk
r<YnXtj|d|di|��dS)Nrr�)r$rJr�r�rOr�r�)rAr*r�r0rrrr�src@seZdZdd�ZdS)�RequirementParseErrorcCsd�|j�S)Nr�)rLrAr�rrrr�szRequirementParseError.__str__N)rrrr�rrrrr.sr.c	cs�tt|��}|D]l}d|kr.|d|�d��}|�d�rr|dd���}z|t|�7}Wntk
rpYdSXt|�VqdS)z�Yield ``Requirement`` objects for each specification in `strs`

    `strs` must be a string, or a (possibly-nested) iterable thereof.
    z #N�\���)rhrxr�rErvrz�
StopIterationrl)r�r�rwrrrrss

csPeZdZ�fdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Ze	d
d��Z
�ZS)rlc
s�ztt|��|�Wn2tjjk
rF}ztt|���W5d}~XYnX|j|_	t
|j�}||��|_|_
dd�|jD�|_ttt|j��|_|j
|j|jt|j�|jr�t|j�ndf|_t|j�|_dS)z>DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!NcSsg|]}|j|jf�qSr)rar)rrrrrrP%sz(Requirement.__init__.<locals>.<listcomp>)rrlrrr0�InvalidRequirementr.r�r��unsafe_namertrZr/r;�	specifierr�r�rrzr-�urlr*rM�hashCmpr��_Requirement__hash)r��requirement_stringr�r/rirrrs$
��zRequirement.__init__cCst|t�o|j|jkSr)r�rlr6r�rrrr�1s

�zRequirement.__eq__cCs
||kSrrr�rrrr�7szRequirement.__ne__cCs0t|t�r |j|jkrdS|j}|jj|dd�S)NFT)�prereleases)r�rkr;rr4�contains)r�rrrrr:s

zRequirement.__contains__cCs|jSr)r7r�rrrr�FszRequirement.__hash__cCsdt|�S)NzRequirement.parse(%r)r�r�rrrr�IszRequirement.__repr__cCst|�\}|Sr)rs)r�r�rrrr�Ls
zRequirement.parse)rrrrr�r�rr�r�r�r�rrrrirrlscCst|kr|tfS|S)zJ
    Ensure object appears in the mro even
    for old-style classes.
    )r)�classesrrr�_always_objectRs
r<cCs<tt�t|dt|����}|D]}||kr||SqdS)z2Return an adapter factory for `ob` from `registry`r�N)r<�inspect�getmror�r�)�registryr<r��trrrr�\sr�cCstj�|�}tj|dd�dS)z1Ensure that the parent directory of `path` existsT)�exist_okN)r�r�r�r�makedirs)r�r�rrrr~dscCsXtstd��t|�\}}|rT|rTt|�sTt|�zt|d�Wntk
rRYnXdS)z/Sandbox-bypassing version of ensure_directory()z*"os.mkdir" not supported on this platform.i�N)rrrr
r{r	�FileExistsError)r�r�r�rrrr{jsr{ccsvd}g}t|�D]V}|�d�r\|�d�rP|s0|r:||fV|dd���}g}qftd|��q|�|�q||fVdS)asSplit a string or iterable thereof into (section, content) pairs

    Each ``section`` is a stripped version of the section header ("[section]")
    and each ``content`` is a list of stripped lines excluding blank lines and
    comment-only lines.  If there are any such lines before the first section
    header, they're returned in a first ``section`` of ``None``.
    N�[�]rr�zInvalid section heading)rxr�rErvrOr�)r��section�contentrwrrrryws


cOs*tj}ztt_tj||�W�S|t_XdSr)r�r�os_open�tempfile�mkstemp)rAr*�old_openrrrr�s
rr�)�categoryr�cOs|||�|Srr)r*rAr�rrr�_call_aside�s
rMcs.t���|d<|��fdd�t��D��dS)z=Set up global resource manager (deliberately not state-saved)�_managerc3s&|]}|�d�s|t�|�fVqdSr)r�r�r��r�rrr�s
�z_initialize.<locals>.<genexpr>N)rjr%r)r0rrOr�_initialize�s
�rPcCs|t��}td|d�|j}|j}|j}|j}|}tdd�|D��|dd�dd�g|_t	t
|jtj
��t��t��d	S)
aE
    Prepare the master working set and make the ``require()``
    API available.

    This function has explicit effects on the global state
    of pkg_resources. It is intended to be invoked once at
    the initialization of this module.

    Invocation by other packages is unsupported and done
    at their own risk.
    r)rbcss|]}|jdd�VqdS)FrN�r)rr�rrrr�s�z1_initialize_master_working_set.<locals>.<genexpr>cSs|jdd�S)NTrrQr�rrrrB�rCz0_initialize_master_working_set.<locals>.<lambda>F)rGN)rirr+rSrZrHrTr�r�r%rrrJr�r$r%r�)rbrSrZrcrTr�rrr�_initialize_master_working_set�s"
��rRc@seZdZdZdS)r�z�
    Base class for warning about deprecations in ``pkg_resources``

    This class is not derived from ``DeprecationWarning``, and as such is
    visible by default.
    Nrrrrrr��s)N)N)F)F)F)F)N)�r�
__future__rrJr�r�rr�r�r�rHr�r�r��pkgutilrarKr'�email.parserr rorIrrrRr=r�r�rr�r�imprC�	NameErrorrn�pkg_resources.externr�pkg_resources.extern.six.movesrrrrr	r
rrrrH�os.pathr
r�importlib.machinery�	machineryr�rr�rrrr�r��
__metaclass__�version_info�RuntimeErrorr�rlrmrSrbrc�resources_streamrf�resource_dirr\rer`r[rZr^r]r_r=r�r��RuntimeWarningrr#r&r+r2r4r8r=r>r?�
_sget_none�
_sset_nonerR�__all__r|rnror�rprqr�r�rlr�r�r�r�r�r�rUrMr�rGr�rHr�rvrwrTr�rVrWrXrYr�r�rir'r&rhr�rrrjrgrtrurzr{r|r}r�rr�r�r�r�r�r�r�r�rIr�r�r�r�rdrGrNrWrarXrer\rcrxrd�ImpImporterr�r~r�r�r�rar�r�r�rr�rZr�r[r�rxrIr��VERBOSE�
IGNORECASEr�rmr�r�rkrrr�rrOr.rsr0rlr<r�r~r{ryr�filterwarningsrMr$rPrR�Warningr�rrrr�<module>sZ



�2 




.
5	A
-*

 ""


	
�	
'3�
7


'�-�h�"bytecode of module 'pkg_resources'�u��b.���h)��N}�(hC��@sdS)N�rrr�@/usr/lib/python3/dist-packages/pkg_resources/_vendor/__init__.py�<module>��h�*bytecode of module 'pkg_resources._vendor'�u��b.��FPh)��N}�(hB�O�@s�dZdZd�eee��ZddlZddlZejddkZ	e	r>eZ
ej�d�r�ddlZe�
�ddZe�d�rrdZq�e�d	�r�d
Zq�dZnejZd4d
d�Zd5dd�Zd6dd�Zd7dd�Zd8dd�Zd9dd�Zd:dd�ZGdd�de�Zdd�Zd d!�Zd"d#�Zd$d%�Zedk�r�ze�eZWnnek
�r�zdd&lm Z eZWnBek
�r�zddl!Z"eZWnek
�r|eZYnXYnXYnXe#d'k�r�d(Z$d)Z%d*Z&e'd+e�e'd,�ee$e%d-d.�Z(e&D]Z)e'd/e)e*e(e)�f��q�e'd0�ee$e%�Z(e&D]Z)e'd/e)e*e(e)�f��q�e'd1�ee$�Z(e&D]Z)e'd/e)e*e(e)�f��q,e'd2�ee$dd3�Z(e&D]Z)e'd/e)e*e(e)�f��qbdS);zyUtilities for determining application-specific dirs.

See <http://github.com/ActiveState/appdirs> for details and usage.
)����.�Nr�java�Windows�win32ZMac�darwinZlinux2FcCs�tdkr^|dkr|}|rdpd}tj�t|��}|r�|dk	rNtj�|||�}q�tj�||�}nNtdkr�tj�d�}|r�tj�||�}n&t�dtj�d	��}|r�tj�||�}|r�|r�tj�||�}|S)
aJReturn full path to the user-specific data dir for this application.

        "appname" is the name of application.
            If None, just the system directory is returned.
        "appauthor" (only used on Windows) is the name of the
            appauthor or distributing body for this application. Typically
            it is the owning company name. This falls back to appname. You may
            pass False to disable it.
        "version" is an optional version path element to append to the
            path. You might want to use this if you want multiple versions
            of your app to be able to run independently. If used, this
            would typically be "<major>.<minor>".
            Only applied when appname is present.
        "roaming" (boolean, default False) can be set True to use the Windows
            roaming appdata directory. That means that for users on a Windows
            network setup for roaming profiles, this user data will be
            sync'd on login. See
            <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
            for a discussion of issues.

    Typical user data directories are:
        Mac OS X:               ~/Library/Application Support/<AppName>
        Unix:                   ~/.local/share/<AppName>    # or in $XDG_DATA_HOME, if defined
        Win XP (not roaming):   C:\Documents and Settings\<username>\Application Data\<AppAuthor>\<AppName>
        Win XP (roaming):       C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>
        Win 7  (not roaming):   C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>
        Win 7  (roaming):       C:\Users\<username>\AppData\Roaming\<AppAuthor>\<AppName>

    For Unix, we follow the XDG spec and support $XDG_DATA_HOME.
    That means, by default "~/.local/share/<AppName>".
    rN�
CSIDL_APPDATA�CSIDL_LOCAL_APPDATAFr	z~/Library/Application Support/�
XDG_DATA_HOMEz~/.local/share��system�os�path�normpath�_get_win_folder�join�
expanduser�getenv)�appname�	appauthor�version�roaming�constr�r�?/usr/lib/python3/dist-packages/pkg_resources/_vendor/appdirs.py�
user_data_dir-s& rcstdkrR|dkr�}tj�td��}�r�|dk	rBtj�||��}q�tj�|��}n�tdkrztj�d�}�r�tj�|��}ntt�dtj�dd	g��}d
d�|�	tj�D�}�r�|r�tj��|���fdd�|D�}|r�tj�|�}n|d
}|S��r|�rtj�||�}|S)aiReturn full path to the user-shared data dir for this application.

        "appname" is the name of application.
            If None, just the system directory is returned.
        "appauthor" (only used on Windows) is the name of the
            appauthor or distributing body for this application. Typically
            it is the owning company name. This falls back to appname. You may
            pass False to disable it.
        "version" is an optional version path element to append to the
            path. You might want to use this if you want multiple versions
            of your app to be able to run independently. If used, this
            would typically be "<major>.<minor>".
            Only applied when appname is present.
        "multipath" is an optional parameter only applicable to *nix
            which indicates that the entire list of data dirs should be
            returned. By default, the first item from XDG_DATA_DIRS is
            returned, or '/usr/local/share/<AppName>',
            if XDG_DATA_DIRS is not set

    Typical site data directories are:
        Mac OS X:   /Library/Application Support/<AppName>
        Unix:       /usr/local/share/<AppName> or /usr/share/<AppName>
        Win XP:     C:\Documents and Settings\All Users\Application Data\<AppAuthor>\<AppName>
        Vista:      (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.)
        Win 7:      C:\ProgramData\<AppAuthor>\<AppName>   # Hidden, but writeable on Win 7.

    For Unix, this is using the $XDG_DATA_DIRS[0] default.

    WARNING: Do not use this on Windows. See the Vista-Fail note above for why.
    rN�CSIDL_COMMON_APPDATAFr	z/Library/Application Support�
XDG_DATA_DIRSz/usr/local/sharez
/usr/sharecSs g|]}tj�|�tj���qSr�rrr�rstrip�sep��.0�xrrr�
<listcomp>�sz!site_data_dir.<locals>.<listcomp>csg|]}tj�|�g��qSr�rr"rr#�rrrr&�sr)
rrrrrrrr�pathsep�split�rrr�	multipathr�pathlistrr(r�
site_data_dirds6�r.cCsXtdkrt||d|�}n&t�dtj�d��}|r>tj�||�}|rT|rTtj�||�}|S)a�Return full path to the user-specific config dir for this application.

        "appname" is the name of application.
            If None, just the system directory is returned.
        "appauthor" (only used on Windows) is the name of the
            appauthor or distributing body for this application. Typically
            it is the owning company name. This falls back to appname. You may
            pass False to disable it.
        "version" is an optional version path element to append to the
            path. You might want to use this if you want multiple versions
            of your app to be able to run independently. If used, this
            would typically be "<major>.<minor>".
            Only applied when appname is present.
        "roaming" (boolean, default False) can be set True to use the Windows
            roaming appdata directory. That means that for users on a Windows
            network setup for roaming profiles, this user data will be
            sync'd on login. See
            <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
            for a discussion of issues.

    Typical user config directories are:
        Mac OS X:               same as user_data_dir
        Unix:                   ~/.config/<AppName>     # or in $XDG_CONFIG_HOME, if defined
        Win *:                  same as user_data_dir

    For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME.
    That means, by default "~/.config/<AppName>".
    �rr	N�XDG_CONFIG_HOMEz	~/.config�rrrrrrr�rrrrrrrr�user_config_dir�sr3cs�tdkr*t�|�}�r�|r�tj�||�}ndt�dd�}dd�|�tj�D�}�rt|rbtj��|���fdd�|D�}|r�tj�|�}n|d}|S)aReturn full path to the user-shared data dir for this application.

        "appname" is the name of application.
            If None, just the system directory is returned.
        "appauthor" (only used on Windows) is the name of the
            appauthor or distributing body for this application. Typically
            it is the owning company name. This falls back to appname. You may
            pass False to disable it.
        "version" is an optional version path element to append to the
            path. You might want to use this if you want multiple versions
            of your app to be able to run independently. If used, this
            would typically be "<major>.<minor>".
            Only applied when appname is present.
        "multipath" is an optional parameter only applicable to *nix
            which indicates that the entire list of config dirs should be
            returned. By default, the first item from XDG_CONFIG_DIRS is
            returned, or '/etc/xdg/<AppName>', if XDG_CONFIG_DIRS is not set

    Typical site config directories are:
        Mac OS X:   same as site_data_dir
        Unix:       /etc/xdg/<AppName> or $XDG_CONFIG_DIRS[i]/<AppName> for each value in
                    $XDG_CONFIG_DIRS
        Win *:      same as site_data_dir
        Vista:      (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.)

    For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if multipath=False

    WARNING: Do not use this on Windows. See the Vista-Fail note above for why.
    r/�XDG_CONFIG_DIRSz/etc/xdgcSs g|]}tj�|�tj���qSrr r#rrrr&�sz#site_config_dir.<locals>.<listcomp>csg|]}tj�|�g��qSrr'r#r(rrr&�sr)rr.rrrrr*r)r+rr(r�site_config_dir�s
r5TcCs�tdkrd|dkr|}tj�td��}|r�|dk	rBtj�|||�}ntj�||�}|r�tj�|d�}nNtdkr�tj�d�}|r�tj�||�}n&t�dtj�d	��}|r�tj�||�}|r�|r�tj�||�}|S)
aReturn full path to the user-specific cache dir for this application.

        "appname" is the name of application.
            If None, just the system directory is returned.
        "appauthor" (only used on Windows) is the name of the
            appauthor or distributing body for this application. Typically
            it is the owning company name. This falls back to appname. You may
            pass False to disable it.
        "version" is an optional version path element to append to the
            path. You might want to use this if you want multiple versions
            of your app to be able to run independently. If used, this
            would typically be "<major>.<minor>".
            Only applied when appname is present.
        "opinion" (boolean) can be False to disable the appending of
            "Cache" to the base app data dir for Windows. See
            discussion below.

    Typical user cache directories are:
        Mac OS X:   ~/Library/Caches/<AppName>
        Unix:       ~/.cache/<AppName> (XDG default)
        Win XP:     C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Cache
        Vista:      C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Cache

    On Windows the only suggestion in the MSDN docs is that local settings go in
    the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming
    app data dir (the default returned by `user_data_dir` above). Apps typically
    put cache data somewhere *under* the given dir here. Some examples:
        ...\Mozilla\Firefox\Profiles\<ProfileName>\Cache
        ...\Acme\SuperApp\Cache\1.0
    OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value.
    This can be disabled with the `opinion=False` option.
    rNrF�Cacher	z~/Library/Caches�XDG_CACHE_HOMEz~/.cacher
�rrr�opinionrrrr�user_cache_dirs(!r:cCsXtdkrt||d|�}n&t�dtj�d��}|r>tj�||�}|rT|rTtj�||�}|S)aReturn full path to the user-specific state dir for this application.

        "appname" is the name of application.
            If None, just the system directory is returned.
        "appauthor" (only used on Windows) is the name of the
            appauthor or distributing body for this application. Typically
            it is the owning company name. This falls back to appname. You may
            pass False to disable it.
        "version" is an optional version path element to append to the
            path. You might want to use this if you want multiple versions
            of your app to be able to run independently. If used, this
            would typically be "<major>.<minor>".
            Only applied when appname is present.
        "roaming" (boolean, default False) can be set True to use the Windows
            roaming appdata directory. That means that for users on a Windows
            network setup for roaming profiles, this user data will be
            sync'd on login. See
            <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
            for a discussion of issues.

    Typical user state directories are:
        Mac OS X:  same as user_data_dir
        Unix:      ~/.local/state/<AppName>   # or in $XDG_STATE_HOME, if defined
        Win *:     same as user_data_dir

    For Unix, we follow this Debian proposal <https://wiki.debian.org/XDGBaseDirectorySpecification#state>
    to extend the XDG spec and support $XDG_STATE_HOME.

    That means, by default "~/.local/state/<AppName>".
    r/N�XDG_STATE_HOMEz~/.local/stater1r2rrr�user_state_dir:sr<cCs�tdkr tj�tj�d�|�}nNtdkrLt|||�}d}|rntj�|d�}n"t|||�}d}|rntj�|d�}|r�|r�tj�||�}|S)a�Return full path to the user-specific log dir for this application.

        "appname" is the name of application.
            If None, just the system directory is returned.
        "appauthor" (only used on Windows) is the name of the
            appauthor or distributing body for this application. Typically
            it is the owning company name. This falls back to appname. You may
            pass False to disable it.
        "version" is an optional version path element to append to the
            path. You might want to use this if you want multiple versions
            of your app to be able to run independently. If used, this
            would typically be "<major>.<minor>".
            Only applied when appname is present.
        "opinion" (boolean) can be False to disable the appending of
            "Logs" to the base app data dir for Windows, and "log" to the
            base cache dir for Unix. See discussion below.

    Typical user log directories are:
        Mac OS X:   ~/Library/Logs/<AppName>
        Unix:       ~/.cache/<AppName>/log  # or under $XDG_CACHE_HOME if defined
        Win XP:     C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Logs
        Vista:      C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Logs

    On Windows the only suggestion in the MSDN docs is that local settings
    go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in
    examples of what some windows apps use for a logs dir.)

    OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA`
    value for Windows and appends "log" to the user cache dir for Unix.
    This can be disabled with the `opinion=False` option.
    r	z~/Library/LogsrF�Logs�log)rrrrrrr:r8rrr�user_log_dirds" 
�r?c@sneZdZdZddd�Zedd��Zedd	��Zed
d��Zedd
��Z	edd��Z
edd��Zedd��ZdS)�AppDirsz1Convenience wrapper for getting application dirs.NFcCs"||_||_||_||_||_dS)N)rrrrr,)�selfrrrrr,rrr�__init__�s
zAppDirs.__init__cCst|j|j|j|jd�S�N)rr)rrrrr�rArrrr�s
�zAppDirs.user_data_dircCst|j|j|j|jd�S�N)rr,)r.rrrr,rDrrrr.�s
�zAppDirs.site_data_dircCst|j|j|j|jd�SrC)r3rrrrrDrrrr3�s
�zAppDirs.user_config_dircCst|j|j|j|jd�SrE)r5rrrr,rDrrrr5�s
�zAppDirs.site_config_dircCst|j|j|jd�S�N�r)r:rrrrDrrrr:�s
�zAppDirs.user_cache_dircCst|j|j|jd�SrF)r<rrrrDrrrr<�s
�zAppDirs.user_state_dircCst|j|j|jd�SrF)r?rrrrDrrrr?�s
�zAppDirs.user_log_dir)NNNFF)
�__name__�
__module__�__qualname__�__doc__rB�propertyrr.r3r5r:r<r?rrrrr@�s&�






r@cCsHtrddl}nddl}dddd�|}|�|jd�}|�||�\}}|S)z�This is a fallback technique at best. I'm not sure if using the
    registry for this guarantees us the correct answer for all CSIDL_*
    names.
    rN�AppDatazCommon AppDataz
Local AppData�r
rrz@Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders)�PY3�winreg�_winreg�OpenKey�HKEY_CURRENT_USER�QueryValueEx)�
csidl_namerQ�shell_folder_name�key�dir�typerrr�_get_win_folder_from_registry�s
���rZcCs�ddlm}m}|�dt||�dd�}z^t|�}d}|D]}t|�dkr8d}qRq8|r�zddl}|�|�}Wnt	k
r�YnXWnt
k
r�YnX|S)Nr)�shellcon�shellF�T)�win32com.shellr[r\�SHGetFolderPath�getattr�unicode�ord�win32api�GetShortPathName�ImportError�UnicodeError)rUr[r\rX�
has_high_char�crcrrr�_get_win_folder_with_pywin32�s$
ricCs�ddl}dddd�|}|�d�}|jj�d|dd|�d}|D]}t|�dkr@d	}qZq@|r�|�d�}|jj�|j|d�r�|}|jS)
Nr��#�rNiFr]T)	�ctypes�create_unicode_buffer�windll�shell32�SHGetFolderPathWrb�kernel32�GetShortPathNameW�value)rUrm�csidl_const�bufrgrh�buf2rrr�_get_win_folder_with_ctypes�s&��

rxcCs�ddl}ddlm}ddlm}|jjd}|�d|�}|jj	}|�
dt|j|�d|jj
|�|j�|����d�}d}|D]}	t|	�dkr|d	}q�q||r�|�d|�}|jj	}
|
�|||�r�|j�|����d�}|S)
Nr)�jna)r�rh�Fr]T)�array�com.sunry�com.sun.jna.platformr�WinDef�MAX_PATH�zeros�Shell32�INSTANCEr_r`�ShlObj�SHGFP_TYPE_CURRENT�Native�toString�tostringr!rb�Kernel32rd)rUr|ryr�buf_sizervr\rXrgrh�kernelrrr�_get_win_folder_with_jnas&r�)ro�__main__ZMyAppZ	MyCompany)rr3r:r<r?r.r5z-- app dirs %s --z%-- app dirs (with optional 'version')z1.0rGz%s: %sz)
-- app dirs (without optional 'version')z+
-- app dirs (without optional 'appauthor')z(
-- app dirs (with disabled 'appauthor'))r)NNNF)NNNF)NNNF)NNNF)NNNT)NNNF)NNNT)+rK�__version_info__r�map�str�__version__�sysr�version_inforOra�platform�
startswith�java_ver�os_namerrr.r3r5r:r<r?�objectr@rZrirxr�rerrmro�com.sun.jna�comrHrr�props�print�dirs�propr`rrrr�<module>s~



7
B
(
3
9
*
30


�h�2bytecode of module 'pkg_resources._vendor.appdirs'�u��b.��^h)��N}�(hB�@sTddlmZmZmZddlmZmZmZmZm	Z	m
Z
mZmZdddddd	d
dgZ
dS)
�)�absolute_import�division�print_function�)�
__author__�
__copyright__�	__email__�__license__�__summary__�	__title__�__uri__�__version__rr
rr
rrr	rN)�
__future__rrr�	__about__rrrr	r
rrr
�__all__�rr�J/usr/lib/python3/dist-packages/pkg_resources/_vendor/packaging/__init__.py�<module>s(��h�4bytecode of module 'pkg_resources._vendor.packaging'�u��b.��
h)��N}�(hB��@sPddlmZmZmZdddddddd	gZd
ZdZdZd
ZdZ	dZ
dZde	ZdS)�)�absolute_import�division�print_function�	__title__�__summary__�__uri__�__version__�
__author__�	__email__�__license__�
__copyright__�	packagingz"Core utilities for Python packagesz!https://github.com/pypa/packagingz16.8z)Donald Stufft and individual contributorszdonald@stufft.ioz"BSD or Apache License, Version 2.0zCopyright 2014-2016 %sN)
�
__future__rrr�__all__rrrrr	r
rr�rr�K/usr/lib/python3/dist-packages/pkg_resources/_vendor/packaging/__about__.py�<module>s"��h�>bytecode of module 'pkg_resources._vendor.packaging.__about__'�u��b.��h)��N}�(hB��@sVddlmZmZmZddlZejddkZejddkZerDefZ	ne
fZ	dd�ZdS)�)�absolute_import�division�print_functionN��cs&G��fdd�d��}t�|ddi�S)z/
    Create a base class with a metaclass.
    cseZdZ��fdd�ZdS)z!with_metaclass.<locals>.metaclasscs�|�|�S)N�)�cls�name�
this_bases�d��bases�metar�I/usr/lib/python3/dist-packages/pkg_resources/_vendor/packaging/_compat.py�__new__sz)with_metaclass.<locals>.metaclass.__new__N)�__name__�
__module__�__qualname__rrrrr�	metaclasssr�temporary_classr)�typer)rr
rrrr�with_metaclasssr)�
__future__rrr�sys�version_info�PY2�PY3�str�string_types�
basestringrrrrr�<module>s�h�<bytecode of module 'pkg_resources._vendor.packaging._compat'�u��b.��h)��N}�(hB�
�@sDddlmZmZmZGdd�de�Ze�ZGdd�de�Ze�ZdS)�)�absolute_import�division�print_functionc@sTeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�ZdS)�InfinitycCsdS)Nr���selfrr�M/usr/lib/python3/dist-packages/pkg_resources/_vendor/packaging/_structures.py�__repr__	szInfinity.__repr__cCstt|��S�N��hash�reprrrrr	�__hash__szInfinity.__hash__cCsdS�NFr�r�otherrrr	�__lt__szInfinity.__lt__cCsdSrrrrrr	�__le__szInfinity.__le__cCst||j�Sr��
isinstance�	__class__rrrr	�__eq__szInfinity.__eq__cCst||j�Srrrrrr	�__ne__szInfinity.__ne__cCsdS�NTrrrrr	�__gt__szInfinity.__gt__cCsdSrrrrrr	�__ge__szInfinity.__ge__cCstSr)�NegativeInfinityrrrr	�__neg__!szInfinity.__neg__N��__name__�
__module__�__qualname__r
rrrrrrrrrrrr	rsrc@sTeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�ZdS)rcCsdS)Nz	-Infinityrrrrr	r
)szNegativeInfinity.__repr__cCstt|��Srrrrrr	r,szNegativeInfinity.__hash__cCsdSrrrrrr	r/szNegativeInfinity.__lt__cCsdSrrrrrr	r2szNegativeInfinity.__le__cCst||j�Srrrrrr	r5szNegativeInfinity.__eq__cCst||j�Srrrrrr	r8szNegativeInfinity.__ne__cCsdSrrrrrr	r;szNegativeInfinity.__gt__cCsdSrrrrrr	r>szNegativeInfinity.__ge__cCstSr)rrrrr	rAszNegativeInfinity.__neg__Nrrrrr	r'srN)�
__future__rrr�objectrrrrrr	�<module>s�h�@bytecode of module 'pkg_resources._vendor.packaging._structures'�u��b.��#h)��N}�(hB�"�	@s@ddlmZmZmZddlZddlZddlZddlZddlm	Z	m
Z
mZmZddlm
Z
mZmZmZddlmZddlmZddlmZmZd	d
ddd
gZGdd	�d	e�ZGdd
�d
e�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�Z Gdd�de�Z!ed�ed�Bed�Bed�Bed�Bed�Bed�Bed �Bed!�Bed"�Bed#�Bed$�Bed%�Bed&�Bed'�Bed(�Bed)�Bed*�BZ"d#d"ddddd+�Z#e"�$d,d-��ed.�ed/�Bed0�Bed1�Bed2�Bed3�Bed4�Bed5�BZ%e%ed6�Bed7�BZ&e&�$d8d-��ed9�ed:�BZ'e'�$d;d-��ed<�ed=�BZ(e"e'BZ)ee)e&e)�Z*e*�$d>d-��ed?��+�Z,ed@��+�Z-e�Z.e*ee,e.e-�BZ/e.e/e
e(e.�>ee.eZ0dAdB�Z1dSdDdE�Z2dFd-�dGd-�ej3ej4ej5ej6ej7ej8dH�Z9dIdJ�Z:e�Z;dKdL�Z<dMdN�Z=dOdP�Z>dQd
�Z?GdRd�de�Z@dS)T�)�absolute_import�division�print_functionN)�ParseException�ParseResults�stringStart�	stringEnd)�
ZeroOrMore�Group�Forward�QuotedString)�Literal�)�string_types)�	Specifier�InvalidSpecifier�
InvalidMarker�UndefinedComparison�UndefinedEnvironmentName�Marker�default_environmentc@seZdZdZdS)rzE
    An invalid marker was found, users should refer to PEP 508.
    N��__name__�
__module__�__qualname__�__doc__�rr�I/usr/lib/python3/dist-packages/pkg_resources/_vendor/packaging/markers.pyrsc@seZdZdZdS)rzP
    An invalid operation was attempted on a value that doesn't support it.
    Nrrrrrrsc@seZdZdZdS)rz\
    A name was attempted to be used that does not exist inside of the
    environment.
    Nrrrrrr%sc@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
�NodecCs
||_dS�N)�value)�selfr rrr�__init__.sz
Node.__init__cCs
t|j�Sr)�strr �r!rrr�__str__1szNode.__str__cCsd�|jjt|��S)Nz<{0}({1!r})>)�format�	__class__rr#r$rrr�__repr__4sz
Node.__repr__cCst�dSr)�NotImplementedErrorr$rrr�	serialize7szNode.serializeN)rrrr"r%r(r*rrrrr,src@seZdZdd�ZdS)�VariablecCst|�Sr�r#r$rrrr*=szVariable.serializeN�rrrr*rrrrr+;sr+c@seZdZdd�ZdS)�ValuecCs
d�|�S)Nz"{0}")r&r$rrrr*CszValue.serializeNr-rrrrr.Asr.c@seZdZdd�ZdS)�OpcCst|�Srr,r$rrrr*IszOp.serializeNr-rrrrr/Gsr/�implementation_version�platform_python_implementation�implementation_name�python_full_version�platform_release�platform_version�platform_machine�platform_system�python_version�sys_platform�os_name�os.name�sys.platform�platform.version�platform.machine�platform.python_implementation�python_implementation�extra)r;r<r=r>r?r@cCstt�|d|d��S�Nr)r+�ALIASES�get��s�l�trrr�<lambda>i�rIz===�==�>=�<=�!=z~=�>�<�not in�incCst|d�SrB)r/rErrrrIwrJ�'�"cCst|d�SrB)r.rErrrrIzrJ�and�orcCst|d�SrB)�tuplerErrrrI�rJ�(�)cCs t|t�rdd�|D�S|SdS)NcSsg|]}t|��qSr)�_coerce_parse_result)�.0�irrr�
<listcomp>�sz(_coerce_parse_result.<locals>.<listcomp>)�
isinstancer)�resultsrrrrZ�s
rZTcCs�t|tttf�st�t|t�rHt|�dkrHt|dttf�rHt|d�St|t�r�dd�|D�}|rnd�|�Sdd�|�dSn"t|t�r�d�dd	�|D��S|SdS)
Nrrcss|]}t|dd�VqdS)F)�firstN)�_format_marker�r[�mrrr�	<genexpr>�sz!_format_marker.<locals>.<genexpr>� rXrYcSsg|]}|���qSr)r*rbrrrr]�sz"_format_marker.<locals>.<listcomp>)r^�listrWr�AssertionError�lenra�join)�markerr`�innerrrrra�s�


racCs||kSrr��lhs�rhsrrrrI�rJcCs||kSrrrlrrrrI�rJ)rRrQrPrMrKrNrLrOcCslztd�|��|g��}Wntk
r.YnX|�|�St�|���}|dkrbtd�|||���|||�S)N�z#Undefined {0!r} on {1!r} and {2!r}.)	rrir*r�contains�
_operatorsrDrr&)rm�oprn�spec�operrrr�_eval_op�s
�rucCs&|�|t�}|tkr"td�|���|S)Nz/{0!r} does not exist in evaluation environment.)rD�
_undefinedrr&)�environment�namer rrr�_get_env�s�ryc	Cs�gg}|D]�}t|tttf�s"t�t|t�rB|d�t||��q
t|t�r�|\}}}t|t�rtt||j	�}|j	}n|j	}t||j	�}|d�t
|||��q
|dks�t�|dkr
|�g�q
tdd�|D��S)N���)rUrVrVcss|]}t|�VqdSr)�all)r[�itemrrrrd�sz$_evaluate_markers.<locals>.<genexpr>)r^rfrWrrg�append�_evaluate_markersr+ryr ru�any)	�markersrw�groupsrjrmrrrn�	lhs_value�	rhs_valuerrrr~�s"



r~cCs2d�|�}|j}|dkr.||dt|j�7}|S)Nz{0.major}.{0.minor}.{0.micro}�finalr)r&�releaselevelr#�serial)�info�version�kindrrr�format_full_version�s

r�cCslttd�r ttjj�}tjj}nd}d}||tjt��t�	�t�
�t��t��t��t��dd�tjd�S)N�implementation�0ro�)r2r0r:r6r4r7r5r3r1r8r9)
�hasattr�sysr�r�r�rx�os�platform�machine�release�systemr8r@)�iverr2rrrr�s"

�c@s.eZdZdd�Zdd�Zdd�Zd
dd	�ZdS)rc
Cs`ztt�|��|_WnFtk
rZ}z(d�|||j|jd��}t|��W5d}~XYnXdS)Nz+Invalid marker: {0!r}, parse error at {1!r}�)rZ�MARKER�parseString�_markersrr&�locr)r!rj�e�err_strrrrr"s�zMarker.__init__cCs
t|j�Sr)rar�r$rrrr%szMarker.__str__cCsd�t|��S)Nz<Marker({0!r})>)r&r#r$rrrr(szMarker.__repr__NcCs$t�}|dk	r|�|�t|j|�S)a$Evaluate a marker.

        Return the boolean from evaluating the given marker against the
        environment. environment is an optional argument to override all or
        part of the determined environment.

        The environment is determined from the current Python process.
        N)r�updater~r�)r!rw�current_environmentrrr�evaluate s	
zMarker.evaluate)N)rrrr"r%r(r�rrrrrs)T)A�
__future__rrr�operatorr�r�r��pkg_resources.extern.pyparsingrrrrr	r
rrr
�L�_compatr�
specifiersrr�__all__�
ValueErrorrrr�objectrr+r.r/�VARIABLErC�setParseAction�VERSION_CMP�	MARKER_OP�MARKER_VALUE�BOOLOP�
MARKER_VAR�MARKER_ITEM�suppress�LPAREN�RPAREN�MARKER_EXPR�MARKER_ATOMr�rZra�lt�le�eq�ne�ge�gtrqrurvryr~r�rrrrrr�<module>s����������	�
���
���������������
��h�<bytecode of module 'pkg_resources._vendor.packaging.markers'�u��b.��ph)��N}�(hB�@srddlmZmZmZddlZddlZddlmZmZm	Z	m
Z
ddlmZmZm
Z
mZmZddlmZddlmZddlmZmZdd	lmZmZmZGd
d�de�Zeejej�Z ed��!�Z"ed
��!�Z#ed��!�Z$ed��!�Z%ed��!�Z&ed��!�Z'ed��!�Z(ed�Z)e ee)�e BZ*ee ee*��Z+e+d�Z,e+Z-ed�d�Z.e(e.Z/e-ee&e-�Z0e"e
e0�e#d�Z1eej2ej3ej4B�Z5eej2ej3ej4B�Z6e5e6AZ7ee7ee&e7�ddd�d�Z8e
e$e8e%e8B�Z9e9�:dd��e	e9�d�Z;e;�:dd��e	e��d�Ze�:d d��e'Z<e<eZ=e;e
e=�Z>e/e
e=�Z?e,e
e1�e?e>BZ@ee@eZAGd!d"�d"eB�ZCdS)#�)�absolute_import�division�print_functionN)�stringStart�	stringEnd�originalTextFor�ParseException)�
ZeroOrMore�Word�Optional�Regex�Combine)�Literal)�parse�)�MARKER_EXPR�Marker)�LegacySpecifier�	Specifier�SpecifierSetc@seZdZdZdS)�InvalidRequirementzJ
    An invalid requirement was found, users should refer to PEP 508.
    N)�__name__�
__module__�__qualname__�__doc__�rr�N/usr/lib/python3/dist-packages/pkg_resources/_vendor/packaging/requirements.pyrsr�[�]�(�)�,�;�@z-_.�namez[^ ]+�url�extrasF)�
joinString�adjacent�	_raw_speccCs
|jpdS)N�)r)��s�l�trrr�<lambda>6�r/�	specifiercCs|dS)Nrrr+rrrr/9r0�markercCst||j|j��S)N)r�_original_start�
_original_endr+rrrr/=r0c@s(eZdZdZdd�Zdd�Zdd�ZdS)	�Requirementz�Parse a requirement.

    Parse a given requirement string into its parts, such as name, specifier,
    URL, and extras. Raises InvalidRequirement on a badly-formed requirement
    string.
    c
Cs�zt�|�}Wn@tk
rN}z"td�||j|jd����W5d}~XYnX|j|_|jr�t�|j�}|j	r�|j
r�|j	s�|j
s�td��|j|_nd|_t|jr�|j�
�ng�|_t|j�|_|jr�|jnd|_dS)Nz+Invalid requirement, parse error at "{0!r}"�zInvalid URL given)�REQUIREMENT�parseStringrr�format�locr$r%�urlparse�scheme�netloc�setr&�asListrr1r2)�self�requirement_string�req�e�
parsed_urlrrr�__init__Xs,����
zRequirement.__init__cCsz|jg}|jr*|�d�d�t|j����|jr@|�t|j��|jrX|�d�|j��|j	rp|�d�|j	��d�|�S)Nz[{0}]r!z@ {0}z; {0}r*)
r$r&�appendr9�join�sortedr1�strr%r2)r@�partsrrr�__str__mszRequirement.__str__cCsd�t|��S)Nz<Requirement({0!r})>)r9rI)r@rrr�__repr__~szRequirement.__repr__N)rrrrrErKrLrrrrr5Ksr5)D�
__future__rrr�string�re�pkg_resources.extern.pyparsingrrrrr	r
rrr
r�L�%pkg_resources.extern.six.moves.urllibrr;�markersrr�
specifiersrrr�
ValueErrorr�
ascii_letters�digits�ALPHANUM�suppress�LBRACKET�RBRACKET�LPAREN�RPAREN�COMMA�	SEMICOLON�AT�PUNCTUATION�IDENTIFIER_END�
IDENTIFIER�NAME�EXTRA�URI�URL�EXTRAS_LIST�EXTRAS�
_regex_str�VERBOSE�
IGNORECASE�VERSION_PEP440�VERSION_LEGACY�VERSION_ONE�VERSION_MANY�
_VERSION_SPEC�setParseAction�VERSION_SPEC�MARKER_SEPERATOR�MARKER�VERSION_AND_MARKER�URL_AND_MARKER�NAMED_REQUIREMENTr7�objectr5rrrr�<module>sf�����h�Abytecode of module 'pkg_resources._vendor.packaging.requirements'�u��b.���Mh)��N}�(hB9M�@s�ddlmZmZmZddlZddlZddlZddlZddlm	Z	m
Z
ddlmZm
Z
mZGdd�de�ZGdd	�d	e
eje��ZGd
d�de�ZGdd
�d
e�Zdd�ZGdd�de�Ze�d�Zdd�Zdd�ZGdd�de�ZdS)�)�absolute_import�division�print_functionN�)�string_types�with_metaclass)�Version�
LegacyVersion�parsec@seZdZdZdS)�InvalidSpecifierzH
    An invalid specifier was found, users should refer to PEP 440.
    N)�__name__�
__module__�__qualname__�__doc__�rr�L/usr/lib/python3/dist-packages/pkg_resources/_vendor/packaging/specifiers.pyrsrc@s�eZdZejdd��Zejdd��Zejdd��Zejdd��Zej	d	d
��Z
e
jdd
��Z
ejdd
d��Zejddd��Z
dS)�
BaseSpecifiercCsdS)z�
        Returns the str representation of this Specifier like object. This
        should be representative of the Specifier itself.
        Nr��selfrrr�__str__szBaseSpecifier.__str__cCsdS)zF
        Returns a hash value for this Specifier like object.
        Nrrrrr�__hash__szBaseSpecifier.__hash__cCsdS)zq
        Returns a boolean representing whether or not the two Specifier like
        objects are equal.
        Nr�r�otherrrr�__eq__$szBaseSpecifier.__eq__cCsdS)zu
        Returns a boolean representing whether or not the two Specifier like
        objects are not equal.
        Nrrrrr�__ne__+szBaseSpecifier.__ne__cCsdS)zg
        Returns whether or not pre-releases as a whole are allowed by this
        specifier.
        Nrrrrr�prereleases2szBaseSpecifier.prereleasescCsdS)zd
        Sets whether or not pre-releases as a whole are allowed by this
        specifier.
        Nr�r�valuerrrr9sNcCsdS)zR
        Determines if the given item is contained within this specifier.
        Nr�r�itemrrrr�contains@szBaseSpecifier.containscCsdS)z�
        Takes an iterable of items and filters them so that only items which
        are contained within this specifier are allowed in it.
        Nr)r�iterablerrrr�filterFszBaseSpecifier.filter)N)N)rr
r�abc�abstractmethodrrrr�abstractpropertyr�setterr r"rrrrrs 





rc@s�eZdZiZd dd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zedd��Z
edd��Zedd��Zejdd��Zdd�Zd!dd�Zd"dd�ZdS)#�_IndividualSpecifier�NcCsF|j�|�}|std�|���|�d���|�d���f|_||_dS)NzInvalid specifier: '{0}'�operator�version)�_regex�searchr�format�group�strip�_spec�_prereleases)r�specr�matchrrr�__init__Rs�z_IndividualSpecifier.__init__cCs0|jdk	rd�|j�nd}d�|jjt|�|�S)N�, prereleases={0!r}r(z<{0}({1!r}{2})>)r1r-r�	__class__r�str�r�prerrr�__repr___s���z_IndividualSpecifier.__repr__cCsdj|j�S)Nz{0}{1})r-r0rrrrrlsz_IndividualSpecifier.__str__cCs
t|j�S�N)�hashr0rrrrrosz_IndividualSpecifier.__hash__cCsPt|t�r4z|�|�}WqDtk
r0tYSXnt||j�sDtS|j|jkSr;��
isinstancerr6r�NotImplementedr0rrrrrrs
z_IndividualSpecifier.__eq__cCsPt|t�r4z|�|�}WqDtk
r0tYSXnt||j�sDtS|j|jkSr;r=rrrrr}s
z_IndividualSpecifier.__ne__cCst|d�|j|��S)Nz_compare_{0})�getattrr-�
_operators)r�oprrr�
_get_operator�sz"_IndividualSpecifier._get_operatorcCst|ttf�st|�}|Sr;)r>r	rr
�rr*rrr�_coerce_version�sz$_IndividualSpecifier._coerce_versioncCs
|jdS)Nr�r0rrrrr)�sz_IndividualSpecifier.operatorcCs
|jdS)NrrFrrrrr*�sz_IndividualSpecifier.versioncCs|jSr;�r1rrrrr�sz _IndividualSpecifier.prereleasescCs
||_dSr;rGrrrrr�scCs
|�|�Sr;�r �rrrrr�__contains__�sz!_IndividualSpecifier.__contains__cCs:|dkr|j}|�|�}|jr&|s&dS|�|j�||j�S�NF)rrE�
is_prereleaserCr)r*rrrrr �s

z_IndividualSpecifier.containsccs�d}g}d|dk	r|ndi}|D]B}|�|�}|j|f|�r |jrX|sX|jsX|�|�q d}|Vq |s||r||D]
}|VqpdS)NFrT)rEr rLr�append)rr!r�yielded�found_prereleases�kwr*�parsed_versionrrrr"�s"
��z_IndividualSpecifier.filter)r(N)N)N)rr
rrAr4r:rrrrrCrE�propertyr)r*rr&rJr r"rrrrr'Ns(







r'c@sveZdZdZe�dedejejB�Zdddddd	d
�Z	dd�Z
d
d�Zdd�Zdd�Z
dd�Zdd�Zdd�ZdS)�LegacySpecifiera�
        (?P<operator>(==|!=|<=|>=|<|>))
        \s*
        (?P<version>
            [^,;\s)]* # Since this is a "legacy" specifier, and the version
                      # string can be just about anything, we match everything
                      # except for whitespace, a semi-colon for marker support,
                      # a closing paren since versions can be enclosed in
                      # them, and a comma since it's a version separator.
        )
        �^\s*�\s*$�equal�	not_equal�less_than_equal�greater_than_equal�	less_than�greater_than)�==�!=�<=�>=�<�>cCst|t�stt|��}|Sr;)r>r	r7rDrrrrE�s
zLegacySpecifier._coerce_versioncCs||�|�kSr;�rE�r�prospectiver2rrr�_compare_equal�szLegacySpecifier._compare_equalcCs||�|�kSr;rbrcrrr�_compare_not_equal�sz"LegacySpecifier._compare_not_equalcCs||�|�kSr;rbrcrrr�_compare_less_than_equal�sz(LegacySpecifier._compare_less_than_equalcCs||�|�kSr;rbrcrrr�_compare_greater_than_equalsz+LegacySpecifier._compare_greater_than_equalcCs||�|�kSr;rbrcrrr�_compare_less_thansz"LegacySpecifier._compare_less_thancCs||�|�kSr;rbrcrrr�_compare_greater_thansz%LegacySpecifier._compare_greater_thanN)rr
r�
_regex_str�re�compile�VERBOSE�
IGNORECASEr+rArErerfrgrhrirjrrrrrS�s(�

��	rScst����fdd��}|S)Ncst|t�sdS�|||�SrK)r>rrc��fnrr�wrappeds
z)_require_version_compare.<locals>.wrapped)�	functools�wraps)rqrrrrpr�_require_version_compare
sruc	@s�eZdZdZe�dedejejB�Zdddddd	d
dd�Z	e
d
d��Ze
dd��Ze
dd��Z
e
dd��Ze
dd��Ze
dd��Ze
dd��Zdd�Zedd��Zejdd��Zd S)!�	Specifiera
        (?P<operator>(~=|==|!=|<=|>=|<|>|===))
        (?P<version>
            (?:
                # The identity operators allow for an escape hatch that will
                # do an exact string match of the version you wish to install.
                # This will not be parsed by PEP 440 and we cannot determine
                # any semantic meaning from it. This operator is discouraged
                # but included entirely as an escape hatch.
                (?<====)  # Only match for the identity operator
                \s*
                [^\s]*    # We just match everything, except for whitespace
                          # since we are only testing for strict identity.
            )
            |
            (?:
                # The (non)equality operators allow for wild card and local
                # versions to be specified so we have to define these two
                # operators separately to enable that.
                (?<===|!=)            # Only match for equals and not equals

                \s*
                v?
                (?:[0-9]+!)?          # epoch
                [0-9]+(?:\.[0-9]+)*   # release
                (?:                   # pre release
                    [-_\.]?
                    (a|b|c|rc|alpha|beta|pre|preview)
                    [-_\.]?
                    [0-9]*
                )?
                (?:                   # post release
                    (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
                )?

                # You cannot use a wild card and a dev or local version
                # together so group them with a | and make them optional.
                (?:
                    (?:[-_\.]?dev[-_\.]?[0-9]*)?         # dev release
                    (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local
                    |
                    \.\*  # Wild card syntax of .*
                )?
            )
            |
            (?:
                # The compatible operator requires at least two digits in the
                # release segment.
                (?<=~=)               # Only match for the compatible operator

                \s*
                v?
                (?:[0-9]+!)?          # epoch
                [0-9]+(?:\.[0-9]+)+   # release  (We have a + instead of a *)
                (?:                   # pre release
                    [-_\.]?
                    (a|b|c|rc|alpha|beta|pre|preview)
                    [-_\.]?
                    [0-9]*
                )?
                (?:                                   # post release
                    (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
                )?
                (?:[-_\.]?dev[-_\.]?[0-9]*)?          # dev release
            )
            |
            (?:
                # All other operators only allow a sub set of what the
                # (non)equality operators do. Specifically they do not allow
                # local versions to be specified nor do they allow the prefix
                # matching wild cards.
                (?<!==|!=|~=)         # We have special cases for these
                                      # operators so we want to make sure they
                                      # don't match here.

                \s*
                v?
                (?:[0-9]+!)?          # epoch
                [0-9]+(?:\.[0-9]+)*   # release
                (?:                   # pre release
                    [-_\.]?
                    (a|b|c|rc|alpha|beta|pre|preview)
                    [-_\.]?
                    [0-9]*
                )?
                (?:                                   # post release
                    (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
                )?
                (?:[-_\.]?dev[-_\.]?[0-9]*)?          # dev release
            )
        )
        rTrU�
compatiblerVrWrXrYrZr[�	arbitrary)�~=r\r]r^r_r`ra�===cCsNd�tt�dd�t|���dd��}|d7}|�d�||�oL|�d�||�S)N�.cSs|�d�o|�d�S)N�post�dev)�
startswith��xrrr�<lambda>�s�z/Specifier._compare_compatible.<locals>.<lambda>����.*r_r\)�join�list�	itertools�	takewhile�_version_splitrC)rrdr2�prefixrrr�_compare_compatible�s�����zSpecifier._compare_compatiblecCsp|�d�rPt|j�}t|dd��}tt|��}|dt|��}t||�\}}nt|�}|jsht|j�}||kS)Nr����)�endswithr�publicr�r7�len�_pad_version�localrcrrrre�s


zSpecifier._compare_equalcCs|�||�Sr;)rercrrrrf�szSpecifier._compare_not_equalcCs|t|�kSr;�rrcrrrrg�sz"Specifier._compare_less_than_equalcCs|t|�kSr;r�rcrrrrh�sz%Specifier._compare_greater_than_equalcCs<t|�}||ksdS|js8|jr8t|j�t|j�kr8dSdS�NFT)rrL�base_versionrcrrrri�szSpecifier._compare_less_thancCs^t|�}||ksdS|js8|jr8t|j�t|j�kr8dS|jdk	rZt|j�t|j�krZdSdSr�)r�is_postreleaser�r�rcrrrrj�s
zSpecifier._compare_greater_thancCst|���t|���kSr;)r7�lowerrcrrr�_compare_arbitraryszSpecifier._compare_arbitrarycCsR|jdk	r|jS|j\}}|dkrN|dkr@|�d�r@|dd�}t|�jrNdSdS)N)r\r_r^ryrzr\r�r�TF)r1r0r�r
rL)rr)r*rrrrs


zSpecifier.prereleasescCs
||_dSr;rGrrrrrsN)rr
rrkrlrmrnror+rArur�rerfrgrhrirjr�rRrr&rrrrrvsD�_

��

"





rvz^([0-9]+)((?:a|b|c|rc)[0-9]+)$cCs@g}|�d�D],}t�|�}|r0|�|���q|�|�q|S)Nr{)�split�
_prefix_regexr,�extend�groupsrM)r*�resultrr3rrrr�'s
r�c
Cs�gg}}|�tt�dd�|���|�tt�dd�|���|�|t|d�d��|�|t|d�d��|�ddgtdt|d�t|d���|�ddgtdt|d�t|d���ttj|��ttj|��fS)NcSs|��Sr;��isdigitrrrrr�6�z_pad_version.<locals>.<lambda>cSs|��Sr;r�rrrrr�7r�rr�0)rMr�r�r�r��insert�max�chain)�left�right�
left_split�right_splitrrrr�2s 
"�"��r�c@s�eZdZddd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Zdd�Z	dd�Z
dd�Zedd��Z
e
jdd��Z
dd�Zddd�Zd dd�ZdS)!�SpecifierSetr(Nc	Csndd�|�d�D�}t�}|D]:}z|�t|��Wqtk
rV|�t|��YqXqt|�|_||_dS)NcSsg|]}|��r|���qSr)r/��.0�srrr�
<listcomp>Rsz)SpecifierSet.__init__.<locals>.<listcomp>�,)	r��set�addrvrrS�	frozenset�_specsr1)r�
specifiersr�parsed�	specifierrrrr4Os
zSpecifierSet.__init__cCs*|jdk	rd�|j�nd}d�t|�|�S)Nr5r(z<SpecifierSet({0!r}{1})>)r1r-rr7r8rrrr:ds
��zSpecifierSet.__repr__cCsd�tdd�|jD���S)Nr�css|]}t|�VqdSr;)r7r�rrr�	<genexpr>nsz'SpecifierSet.__str__.<locals>.<genexpr>)r��sortedr�rrrrrmszSpecifierSet.__str__cCs
t|j�Sr;)r<r�rrrrrpszSpecifierSet.__hash__cCs�t|t�rt|�}nt|t�s"tSt�}t|j|jB�|_|jdkrX|jdk	rX|j|_n<|jdk	rv|jdkrv|j|_n|j|jkr�|j|_ntd��|S)NzFCannot combine SpecifierSets with True and False prerelease overrides.)r>rr�r?r�r�r1�
ValueError)rrr�rrr�__and__ss 





�zSpecifierSet.__and__cCsFt|t�rt|�}n&t|t�r,tt|��}nt|t�s:tS|j|jkSr;�r>rr�r'r7r?r�rrrrr�s



zSpecifierSet.__eq__cCsFt|t�rt|�}n&t|t�r,tt|��}nt|t�s:tS|j|jkSr;r�rrrrr�s



zSpecifierSet.__ne__cCs
t|j�Sr;)r�r�rrrr�__len__�szSpecifierSet.__len__cCs
t|j�Sr;)�iterr�rrrr�__iter__�szSpecifierSet.__iter__cCs.|jdk	r|jS|jsdStdd�|jD��S)Ncss|]}|jVqdSr;�rr�rrrr��sz+SpecifierSet.prereleases.<locals>.<genexpr>)r1r��anyrrrrr�s

zSpecifierSet.prereleasescCs
||_dSr;rGrrrrr�scCs
|�|�Sr;rHrIrrrrJ�szSpecifierSet.__contains__csLt�ttf�st����dkr$|j��s2�jr2dSt��fdd�|jD��S)NFc3s|]}|j��d�VqdS)r�NrHr��rrrrr��s�z(SpecifierSet.contains.<locals>.<genexpr>)r>r	rr
rrL�allr�rrr�rr �s
�zSpecifierSet.containscCs�|dkr|j}|jr6|jD]}|j|t|�d�}q|Sg}g}|D]P}t|ttf�s^t|�}n|}t|t�rnqB|jr�|s�|s�|�	|�qB|�	|�qB|s�|r�|dkr�|S|SdS)Nr�)
rr�r"�boolr>r	rr
rLrM)rr!rr2�filteredrOrrQrrrr"�s*



zSpecifierSet.filter)r(N)N)N)rr
rr4r:rrr�rrr�r�rRrr&rJr r"rrrrr�Ms 
	




r�)�
__future__rrrr#rsr�rl�_compatrrr*rr	r
r�r�ABCMeta�objectrr'rSrurvrmr�r�r�r�rrrr�<module>s&9	4	
�h�?bytecode of module 'pkg_resources._vendor.packaging.specifiers'�u��b.���)h)��N}�(hBx)�	@s�ddlmZmZmZddlZddlZddlZddlmZddddd	gZ	e�
d
ddd
dddg�Zdd�ZGdd�de
�ZGdd�de�ZGdd�de�Ze�dej�Zdddddd�Zdd�Zdd�ZdZGd d�de�Zd!d"�Ze�d#�Zd$d%�Zd&d'�ZdS)(�)�absolute_import�division�print_functionN�)�Infinity�parse�Version�
LegacyVersion�InvalidVersion�VERSION_PATTERN�_Version�epoch�release�dev�pre�post�localcCs,z
t|�WStk
r&t|�YSXdS)z�
    Parse the given version string and return either a :class:`Version` object
    or a :class:`LegacyVersion` object depending on if the given version is
    a valid PEP 440 version or a legacy version.
    N)rr
r	)�version�r�I/usr/lib/python3/dist-packages/pkg_resources/_vendor/packaging/version.pyrs
c@seZdZdZdS)r
zF
    An invalid version was found, users should refer to PEP 440.
    N)�__name__�
__module__�__qualname__�__doc__rrrrr
$sc@sLeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dS)�_BaseVersioncCs
t|j�S�N)�hash�_key��selfrrr�__hash__,sz_BaseVersion.__hash__cCs|�|dd��S)NcSs||kSrr��s�orrr�<lambda>0�z%_BaseVersion.__lt__.<locals>.<lambda>��_compare�r�otherrrr�__lt__/sz_BaseVersion.__lt__cCs|�|dd��S)NcSs||kSrrr!rrrr$3r%z%_BaseVersion.__le__.<locals>.<lambda>r&r(rrr�__le__2sz_BaseVersion.__le__cCs|�|dd��S)NcSs||kSrrr!rrrr$6r%z%_BaseVersion.__eq__.<locals>.<lambda>r&r(rrr�__eq__5sz_BaseVersion.__eq__cCs|�|dd��S)NcSs||kSrrr!rrrr$9r%z%_BaseVersion.__ge__.<locals>.<lambda>r&r(rrr�__ge__8sz_BaseVersion.__ge__cCs|�|dd��S)NcSs||kSrrr!rrrr$<r%z%_BaseVersion.__gt__.<locals>.<lambda>r&r(rrr�__gt__;sz_BaseVersion.__gt__cCs|�|dd��S)NcSs||kSrrr!rrrr$?r%z%_BaseVersion.__ne__.<locals>.<lambda>r&r(rrr�__ne__>sz_BaseVersion.__ne__cCst|t�stS||j|j�Sr)�
isinstancer�NotImplementedr)rr)�methodrrrr'As
z_BaseVersion._compareN)rrrr r*r+r,r-r.r/r'rrrrr*src@s`eZdZdd�Zdd�Zdd�Zedd��Zed	d
��Zedd��Z	ed
d��Z
edd��ZdS)r	cCst|�|_t|j�|_dSr)�str�_version�_legacy_cmpkeyr)rrrrr�__init__Js
zLegacyVersion.__init__cCs|jSr�r4rrrr�__str__NszLegacyVersion.__str__cCsd�tt|���S)Nz<LegacyVersion({0})>��format�reprr3rrrr�__repr__QszLegacyVersion.__repr__cCs|jSrr7rrrr�publicTszLegacyVersion.publiccCs|jSrr7rrrr�base_versionXszLegacyVersion.base_versioncCsdSrrrrrrr\szLegacyVersion.localcCsdS�NFrrrrr�
is_prerelease`szLegacyVersion.is_prereleasecCsdSr?rrrrr�is_postreleasedszLegacyVersion.is_postreleaseN)rrrr6r8r<�propertyr=r>rr@rArrrrr	Hs



z(\d+ | [a-z]+ | \.| -)�czfinal-�@)r�preview�-�rcrccs\t�|�D]F}t�||�}|r
|dkr(q
|dd�dkrF|�d�Vq
d|Vq
dVdS)N�.r�
0123456789��*�*final)�_legacy_version_component_re�split�_legacy_version_replacement_map�get�zfill)r"�partrrr�_parse_version_partsrsrScCszd}g}t|���D]T}|�d�r^|dkrD|rD|ddkrD|��q*|r^|ddkr^|��qD|�|�qt|�}||fS)N���rKrLz*final-�00000000)rS�lower�
startswith�pop�append�tuple)rr
�partsrRrrrr5�s


r5a�
    v?
    (?:
        (?:(?P<epoch>[0-9]+)!)?                           # epoch
        (?P<release>[0-9]+(?:\.[0-9]+)*)                  # release segment
        (?P<pre>                                          # pre-release
            [-_\.]?
            (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
            [-_\.]?
            (?P<pre_n>[0-9]+)?
        )?
        (?P<post>                                         # post release
            (?:-(?P<post_n1>[0-9]+))
            |
            (?:
                [-_\.]?
                (?P<post_l>post|rev|r)
                [-_\.]?
                (?P<post_n2>[0-9]+)?
            )
        )?
        (?P<dev>                                          # dev release
            [-_\.]?
            (?P<dev_l>dev)
            [-_\.]?
            (?P<dev_n>[0-9]+)?
        )?
    )
    (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
c@s|eZdZe�dedejejB�Zdd�Z	dd�Z
dd�Zed	d
��Z
edd��Zed
d��Zedd��Zedd��ZdS)rz^\s*z\s*$c
Cs�|j�|�}|std�|���t|�d�r8t|�d��ndtdd�|�d��d�D��t	|�d�|�d	��t	|�d
�|�d�p�|�d��t	|�d
�|�d��t
|�d��d�|_t|jj
|jj|jj|jj|jj|jj�|_dS)NzInvalid version: '{0}'r
rcss|]}t|�VqdSr)�int��.0�irrr�	<genexpr>�sz#Version.__init__.<locals>.<genexpr>rrH�pre_l�pre_n�post_l�post_n1�post_n2�dev_l�dev_nr�r
rrrrr)�_regex�searchr
r:r�groupr\rZrN�_parse_letter_version�_parse_local_versionr4�_cmpkeyr
rrrrrr)rr�matchrrrr6�s8�����zVersion.__init__cCsd�tt|���S)Nz<Version({0})>r9rrrrr<�szVersion.__repr__cCs�g}|jjdkr$|�d�|jj��|�d�dd�|jjD���|jjdk	rl|�d�dd�|jjD���|jjdk	r�|�d�|jjd	��|jjdk	r�|�d
�|jjd	��|jj	dk	r�|�d�d�dd�|jj	D����d�|�S)
Nr�{0}!rHcss|]}t|�VqdSr�r3�r^�xrrrr`�sz"Version.__str__.<locals>.<genexpr>�css|]}t|�VqdSrrqrrrrrr`�sz.post{0}rz.dev{0}z+{0}css|]}t|�VqdSrrqrrrrrr`s)
r4r
rYr:�joinrrrrr�rr[rrrr8�s�zVersion.__str__cCst|��dd�dS)N�+rr�r3rNrrrrr=
szVersion.publiccCsLg}|jjdkr$|�d�|jj��|�d�dd�|jjD���d�|�S)NrrprHcss|]}t|�VqdSrrqrrrrrr`sz'Version.base_version.<locals>.<genexpr>rt)r4r
rYr:rurrvrrrr>s
zVersion.base_versioncCs$t|�}d|kr |�dd�dSdS)Nrwrrx)r�version_stringrrrrsz
Version.localcCst|jjp|jj�Sr)�boolr4rrrrrrr@!szVersion.is_prereleasecCst|jj�Sr)rzr4rrrrrrA%szVersion.is_postreleaseN)rrr�re�compiler�VERBOSE�
IGNORECASErir6r<r8rBr=r>rr@rArrrrr�s"

�#



cCsv|rZ|dkrd}|��}|dkr&d}n(|dkr4d}n|dkrBd}n|dkrNd	}|t|�fS|sr|rrd	}|t|�fSdS)
Nr�alpha�a�beta�b)rCrrErG)�rev�rr)rVr\)�letter�numberrrrrl*s rlz[\._-]cCs$|dk	r tdd�t�|�D��SdS)zR
    Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
    Ncss&|]}|��s|��nt|�VqdSr)�isdigitrVr\)r^rRrrrr`Qs�z'_parse_local_version.<locals>.<genexpr>)rZ�_local_version_seperatorsrN)rrrrrmLs�rmcCs�tttt�dd�t|�����}|dkr@|dkr@|dk	r@t}n|dkrLt}|dkrZt}|dkrft}|dkrvt}ntdd�|D��}||||||fS)NcSs|dkS)Nrr)rsrrrr$`r%z_cmpkey.<locals>.<lambda>css*|]"}t|t�r|dfnt|fVqdS)rtN)r0r\rr]rrrr`�s�z_cmpkey.<locals>.<genexpr>)rZ�reversed�list�	itertools�	dropwhilerrhrrrrnWs,���
	�rn)�
__future__rrr�collectionsr�r{�_structuresr�__all__�
namedtuplerr�
ValueErrorr
�objectrr	r|r}rMrOrSr5rrrlr�rmrnrrrr�<module>sH��!�� k
�h�<bytecode of module 'pkg_resources._vendor.packaging.version'�u��b.��h)��N}�(hB��i@s�dZdZdZdZddlZddlmZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlZddlmZzddlmZWn ek
r�ddlmZYnXzdd	lmZdd
lmZWn,ek
r�dd	l
mZdd
l
mZYnXzddl
mZWnBek
�rFzddlmZWnek
�r@dZYnXYnXdd
ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtgiZee	j�ddu�ZeddukZ e �rpe	j!Z"e#Z$e%Z&e#Z'e(e)e*e+e,ee-e.e/e0e1gZ2n`e	j3Z"e4Z5dvdw�Z'gZ2ddl6Z6dx�7�D]8Z8ze2�9e:e6e8��Wne;k
�r�Y�q�YnX�q�e<dydz�e5d{�D��Z=d|d}�Z>Gd~d�de?�Z@ejAejBZCd�ZDeDd�ZEeCeDZFe%d��ZGd��Hd�dz�ejID��ZJGd�d#�d#eK�ZLGd�d%�d%eL�ZMGd�d'�d'eL�ZNGd�d)�d)eN�ZOGd�d,�d,eK�ZPGd�d��d�e?�ZQGd�d(�d(e?�ZRe�SeR�d�d?�ZTd�dP�ZUd�dM�ZVd�d��ZWd�d��ZXd�d��ZYd�dW�ZZ�d/d�d��Z[Gd�d*�d*e?�Z\Gd�d2�d2e\�Z]Gd�d�de]�Z^Gd�d�de]�Z_Gd�d�de]�Z`e`Zae`e\_bGd�d�de]�ZcGd�d�de`�ZdGd�d
�d
ec�ZeGd�dr�dre]�ZfGd�d5�d5e]�ZgGd�d-�d-e]�ZhGd�d+�d+e]�ZiGd�d�de]�ZjGd�d4�d4e]�ZkGd�d��d�e]�ZlGd�d�del�ZmGd�d�del�ZnGd�d�del�ZoGd�d0�d0el�ZpGd�d/�d/el�ZqGd�d7�d7el�ZrGd�d6�d6el�ZsGd�d&�d&e\�ZtGd�d�det�ZuGd�d"�d"et�ZvGd�d�det�ZwGd�d�det�ZxGd�d$�d$e\�ZyGd�d�dey�ZzGd�d�dey�Z{Gd�d��d�ey�Z|Gd�d�de|�Z}Gd�d8�d8e|�Z~Gd�d��d�e?�Ze�Z�Gd�d!�d!ey�Z�Gd�d.�d.ey�Z�Gd�d�dey�Z�Gd�dÄd�e��Z�Gd�d3�d3ey�Z�Gd�d�de��Z�Gd�d�de��Z�Gd�d�de��Z�Gd�d1�d1e��Z�Gd�d �d e?�Z�d�dh�Z��d0d�dF�Z��d1d�dB�Z�d�dЄZ�d�dU�Z�d�dT�Z�d�dԄZ��d2d�dY�Z�d�dG�Z��d3d�dm�Z�d�dn�Z�d�dp�Z�e^���dI�Z�en���dO�Z�eo���dN�Z�ep���dg�Z�eq���df�Z�egeGd�d�d܍��d�dބ�Z�ehd߃��d�dބ�Z�ehd���d�dބ�Z�e�e�Be�Bejd�d{d܍BZ�e�e�e�d�e��Z�e`d�e�d���d�e�e}e�e�B����d�d�Z�d�de�Z�d�dS�Z�d�db�Z�d�d`�Z�d�ds�Z�e�d�dބ�Z�e�d�dބ�Z�d�d�Z�d�dQ�Z�d�dR�Z�d�dk�Z�e?�e�_��d4d�dq�Z�e@�Z�e?�e�_�e?�e�_�e�d��e�d��fd�do�Z�e�Z�e�ehd��d����d��Z�e�ehd��d����d��Z�e�ehd��d�ehd��d�B����d�Z�e�ea�d�e�������d�Z�d�d�de���f�ddV�Z��d5�ddl�Z�e��d�Z�e��d�Z�e�egeCeF�d����d��\Z�Z�e�ed	�7��d
��Z�eh�d�d�Heàġ��d
����d�ZŐdda�Z�e�eh�d��d����d�Z�eh�d����d�Z�eh�d��ɡ���d�Z�eh�d����d�Z�e�eh�d��de�B����d�Z�e�Z�eh�d����d�Z�e�e}egeJdːd�e�eg�d�e`d˃eo�����ϡ���d�Z�e�e�e���e�Bd��d����d@�Z�G�d dt�dt�Z�eӐd!k�r�ed�d"�Z�ed�d#�Z�egeCeF�d$�Z�e�e֐d%dՐd&���e��Z�e�e�e׃����d'�Zؐd(e�BZ�e�e֐d%dՐd&���e��Z�e�e�eڃ����d)�Z�eԐd*�eِd'�e�eېd)�Z�eܠݐd+�e�jޠݐd,�e�jߠݐd,�e�j�ݐd-�ddl�Z�e�j᠝e�e�j��e�j�ݐd.�dS(6a�	
pyparsing module - Classes and methods to define and execute parsing grammars
=============================================================================

The pyparsing module is an alternative approach to creating and executing simple grammars,
vs. the traditional lex/yacc approach, or the use of regular expressions.  With pyparsing, you
don't need to learn a new syntax for defining grammars or matching expressions - the parsing module
provides a library of classes that you use to construct the grammar directly in Python.

Here is a program to parse "Hello, World!" (or any greeting of the form 
C{"<salutation>, <addressee>!"}), built up using L{Word}, L{Literal}, and L{And} elements 
(L{'+'<ParserElement.__add__>} operator gives L{And} expressions, strings are auto-converted to
L{Literal} expressions)::

    from pyparsing import Word, alphas

    # define grammar of a greeting
    greet = Word(alphas) + "," + Word(alphas) + "!"

    hello = "Hello, World!"
    print (hello, "->", greet.parseString(hello))

The program outputs the following::

    Hello, World! -> ['Hello', ',', 'World', '!']

The Python representation of the grammar is quite readable, owing to the self-explanatory
class names, and the use of '+', '|' and '^' operators.

The L{ParseResults} object returned from L{ParserElement.parseString<ParserElement.parseString>} can be accessed as a nested list, a dictionary, or an
object with named attributes.

The pyparsing module handles some of the problems that are typically vexing when writing text parsers:
 - extra or missing whitespace (the above program will also handle "Hello,World!", "Hello  ,  World  !", etc.)
 - quoted strings
 - embedded comments


Getting Started -
-----------------
Visit the classes L{ParserElement} and L{ParseResults} to see the base classes that most other pyparsing
classes inherit from. Use the docstrings for examples of how to:
 - construct literal match expressions from L{Literal} and L{CaselessLiteral} classes
 - construct character word-group expressions using the L{Word} class
 - see how to create repetitive expressions using L{ZeroOrMore} and L{OneOrMore} classes
 - use L{'+'<And>}, L{'|'<MatchFirst>}, L{'^'<Or>}, and L{'&'<Each>} operators to combine simple expressions into more complex ones
 - associate names with your parsed results using L{ParserElement.setResultsName}
 - find some helpful expression short-cuts like L{delimitedList} and L{oneOf}
 - find more useful common expressions in the L{pyparsing_common} namespace class
z2.2.1z18 Sep 2018 00:49 UTCz*Paul McGuire <ptmcg@users.sourceforge.net>�N)�ref)�datetime)�RLock)�Iterable)�MutableMapping)�OrderedDict�And�CaselessKeyword�CaselessLiteral�
CharsNotIn�Combine�Dict�Each�Empty�
FollowedBy�Forward�
GoToColumn�Group�Keyword�LineEnd�	LineStart�Literal�
MatchFirst�NoMatch�NotAny�	OneOrMore�OnlyOnce�Optional�Or�ParseBaseException�ParseElementEnhance�ParseException�ParseExpression�ParseFatalException�ParseResults�ParseSyntaxException�
ParserElement�QuotedString�RecursiveGrammarException�Regex�SkipTo�	StringEnd�StringStart�Suppress�Token�TokenConverter�White�Word�WordEnd�	WordStart�
ZeroOrMore�	alphanums�alphas�
alphas8bit�anyCloseTag�
anyOpenTag�
cStyleComment�col�commaSeparatedList�commonHTMLEntity�countedArray�cppStyleComment�dblQuotedString�dblSlashComment�
delimitedList�dictOf�downcaseTokens�empty�hexnums�htmlComment�javaStyleComment�line�lineEnd�	lineStart�lineno�makeHTMLTags�makeXMLTags�matchOnlyAtCol�matchPreviousExpr�matchPreviousLiteral�
nestedExpr�nullDebugAction�nums�oneOf�opAssoc�operatorPrecedence�
printables�punc8bit�pythonStyleComment�quotedString�removeQuotes�replaceHTMLEntity�replaceWith�
restOfLine�sglQuotedString�srange�	stringEnd�stringStart�traceParseAction�
unicodeString�upcaseTokens�
withAttribute�
indentedBlock�originalTextFor�ungroup�
infixNotation�locatedExpr�	withClass�
CloseMatch�tokenMap�pyparsing_common�cCsft|t�r|Sz
t|�WStk
r`t|��t��d�}td�}|�dd��|�	|�YSXdS)aDrop-in replacement for str(obj) that tries to be Unicode friendly. It first tries
           str(obj). If that fails with a UnicodeEncodeError, then it tries unicode(obj). It
           then < returns the unicode object | encodes it with the default encoding | ... >.
        �xmlcharrefreplacez&#\d+;cSs$dtt|ddd���dd�S)Nz\ur����)�hex�int��t�ry�A/usr/lib/python3/dist-packages/pkg_resources/_vendor/pyparsing.py�<lambda>��z_ustr.<locals>.<lambda>N)
�
isinstance�unicode�str�UnicodeEncodeError�encode�sys�getdefaultencodingr)�setParseAction�transformString)�obj�ret�
xmlcharrefryryrz�_ustr�s

r�z6sum len sorted reversed list tuple set any all min maxccs|]
}|VqdS�Nry)�.0�yryryrz�	<genexpr>�sr��cCs:d}dd�d��D�}t||�D]\}}|�||�}q |S)z/Escape &, <, >, ", ', etc. in a string of data.z&><"'css|]}d|dVqdS)�&�;Nry)r��sryryrzr��sz_xml_escape.<locals>.<genexpr>zamp gt lt quot apos)�split�zip�replace)�data�from_symbols�
to_symbols�from_�to_ryryrz�_xml_escape�s
r�c@seZdZdS)�
_ConstantsN)�__name__�
__module__�__qualname__ryryryrzr��sr��
0123456789ZABCDEFabcdef�\�ccs|]}|tjkr|VqdSr�)�string�
whitespace�r��cryryrzr��s
c@sPeZdZdZddd�Zedd��Zdd	�Zd
d�Zdd
�Z	ddd�Z
dd�ZdS)rz7base exception class for all parsing runtime exceptionsrNcCs>||_|dkr||_d|_n||_||_||_|||f|_dS�Nr�)�loc�msg�pstr�
parserElement�args)�selfr�r�r��elemryryrz�__init__�szParseBaseException.__init__cCs||j|j|j|j�S)z�
        internal factory method to simplify creating one type of ParseException 
        from another - avoids having __init__ signature conflicts among subclasses
        )r�r�r�r�)�cls�peryryrz�_from_exception�sz"ParseBaseException._from_exceptioncCsN|dkrt|j|j�S|dkr,t|j|j�S|dkrBt|j|j�St|��dS)z�supported attributes by name are:
            - lineno - returns the line number of the exception text
            - col - returns the column number of the exception text
            - line - returns the line containing the exception text
        rL)r;�columnrIN)rLr�r�r;rI�AttributeError)r��anameryryrz�__getattr__�szParseBaseException.__getattr__cCsd|j|j|j|jfS)Nz"%s (at char %d), (line:%d, col:%d))r�r�rLr��r�ryryrz�__str__�s�zParseBaseException.__str__cCst|�Sr��r�r�ryryrz�__repr__�szParseBaseException.__repr__�>!<cCs<|j}|jd}|r4d�|d|�|||d�f�}|��S)z�Extracts the exception line from the input string, and marks
           the location of the exception with a special symbol.
        r�r�N)rIr��join�strip)r��markerString�line_str�line_columnryryrz�
markInputline�s

�z ParseBaseException.markInputlinecCsd��tt|��S)Nzlineno col line)r��dir�typer�ryryrz�__dir__szParseBaseException.__dir__)rNN)r�)r�r�r��__doc__r��classmethodr�r�r�r�r�r�ryryryrzr�s



c@seZdZdZdS)r!aN
    Exception thrown when parse expressions don't match class;
    supported attributes by name are:
     - lineno - returns the line number of the exception text
     - col - returns the column number of the exception text
     - line - returns the line containing the exception text
        
    Example::
        try:
            Word(nums).setName("integer").parseString("ABC")
        except ParseException as pe:
            print(pe)
            print("column: {}".format(pe.col))
            
    prints::
       Expected integer (at char 0), (line:1, col:1)
        column: 1
    N�r�r�r�r�ryryryrzr!sc@seZdZdZdS)r#znuser-throwable exception thrown when inconsistent parse content
       is found; stops all parsing immediatelyNr�ryryryrzr#sc@seZdZdZdS)r%z�just like L{ParseFatalException}, but thrown internally when an
       L{ErrorStop<And._ErrorStop>} ('-' operator) indicates that parsing is to stop 
       immediately because an unbacktrackable syntax error has been foundNr�ryryryrzr%sc@s eZdZdZdd�Zdd�ZdS)r(zZexception thrown by L{ParserElement.validate} if the grammar could be improperly recursivecCs
||_dSr���parseElementTrace�r��parseElementListryryrzr�4sz"RecursiveGrammarException.__init__cCs
d|jS)NzRecursiveGrammarException: %sr�r�ryryrzr�7sz!RecursiveGrammarException.__str__N)r�r�r�r�r�r�ryryryrzr(2sc@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
�_ParseResultsWithOffsetcCs||f|_dSr���tup)r��p1�p2ryryrzr�;sz _ParseResultsWithOffset.__init__cCs
|j|Sr�r��r��iryryrz�__getitem__=sz#_ParseResultsWithOffset.__getitem__cCst|jd�S�Nr)�reprr�r�ryryrzr�?sz _ParseResultsWithOffset.__repr__cCs|jd|f|_dSr�r�r�ryryrz�	setOffsetAsz!_ParseResultsWithOffset.setOffsetN)r�r�r�r�r�r�r�ryryryrzr�:sr�c@s�eZdZdZd[dd�Zddddefdd�Zdd	�Zefd
d�Zdd
�Z	dd�Z
dd�Zdd�ZeZ
dd�Zdd�Zdd�Zdd�Zdd�Zer�eZeZeZn$eZeZeZdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd\d(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Z d2d3�Z!d4d5�Z"d6d7�Z#d8d9�Z$d:d;�Z%d<d=�Z&d]d?d@�Z'dAdB�Z(dCdD�Z)dEdF�Z*d^dHdI�Z+dJdK�Z,dLdM�Z-d_dOdP�Z.dQdR�Z/dSdT�Z0dUdV�Z1dWdX�Z2dYdZ�Z3dS)`r$aI
    Structured parse results, to provide multiple means of access to the parsed data:
       - as a list (C{len(results)})
       - by list index (C{results[0], results[1]}, etc.)
       - by attribute (C{results.<resultsName>} - see L{ParserElement.setResultsName})

    Example::
        integer = Word(nums)
        date_str = (integer.setResultsName("year") + '/' 
                        + integer.setResultsName("month") + '/' 
                        + integer.setResultsName("day"))
        # equivalent form:
        # date_str = integer("year") + '/' + integer("month") + '/' + integer("day")

        # parseString returns a ParseResults object
        result = date_str.parseString("1999/12/31")

        def test(s, fn=repr):
            print("%s -> %s" % (s, fn(eval(s))))
        test("list(result)")
        test("result[0]")
        test("result['month']")
        test("result.day")
        test("'month' in result")
        test("'minutes' in result")
        test("result.dump()", str)
    prints::
        list(result) -> ['1999', '/', '12', '/', '31']
        result[0] -> '1999'
        result['month'] -> '12'
        result.day -> '31'
        'month' in result -> True
        'minutes' in result -> False
        result.dump() -> ['1999', '/', '12', '/', '31']
        - day: 31
        - month: 12
        - year: 1999
    NTcCs"t||�r|St�|�}d|_|S�NT)r}�object�__new__�_ParseResults__doinit)r��toklist�name�asList�modal�retobjryryrzr�ks


zParseResults.__new__c
Csb|jrvd|_d|_d|_i|_||_||_|dkr6g}||t�rP|dd�|_n||t�rft|�|_n|g|_t	�|_
|dk	�r^|�r^|s�d|j|<||t�r�t|�}||_||t
d�ttf�r�|ddgfk�s^||t�r�|g}|�r(||t��rt|��d�||<ntt|d�d�||<|||_n6z|d||<Wn$tttfk
�r\|||<YnXdS)NFrr�)r��_ParseResults__name�_ParseResults__parent�_ParseResults__accumNames�_ParseResults__asList�_ParseResults__modal�list�_ParseResults__toklist�_generatorType�dict�_ParseResults__tokdictrvr�r��
basestringr$r��copy�KeyError�	TypeError�
IndexError)r�r�r�r�r�r}ryryrzr�tsB



$
zParseResults.__init__cCsPt|ttf�r|j|S||jkr4|j|ddStdd�|j|D��SdS)NrtrcSsg|]}|d�qS�rry�r��vryryrz�
<listcomp>�sz,ParseResults.__getitem__.<locals>.<listcomp>)r}rv�slicer�r�r�r$r�ryryrzr��s


zParseResults.__getitem__cCs�||t�r0|j�|t��|g|j|<|d}nD||ttf�rN||j|<|}n&|j�|t��t|d�g|j|<|}||t�r�t|�|_	dSr�)
r�r��getr�rvr�r�r$�wkrefr�)r��kr�r}�subryryrz�__setitem__�s


"
zParseResults.__setitem__c
Cs�t|ttf�r�t|j�}|j|=t|t�rH|dkr:||7}t||d�}tt|�|���}|��|j	�
�D]>\}}|D]0}t|�D]"\}\}}	t||	|	|k�||<q�qxqln|j	|=dS�Nrr�)
r}rvr��lenr�r��range�indices�reverser��items�	enumerater�)
r�r��mylen�removedr��occurrences�jr��value�positionryryrz�__delitem__�s

zParseResults.__delitem__cCs
||jkSr�)r�)r�r�ryryrz�__contains__�szParseResults.__contains__cCs
t|j�Sr�)r�r�r�ryryrz�__len__�r|zParseResults.__len__cCs
|jSr��r�r�ryryrz�__bool__�r|zParseResults.__bool__cCs
t|j�Sr���iterr�r�ryryrz�__iter__�r|zParseResults.__iter__cCst|jddd��S�Nrtr
r�ryryrz�__reversed__�r|zParseResults.__reversed__cCs$t|jd�r|j��St|j�SdS)N�iterkeys)�hasattrr�rrr�ryryrz�	_iterkeys�s
zParseResults._iterkeyscs�fdd����D�S)Nc3s|]}�|VqdSr�ry�r�r�r�ryrzr��sz+ParseResults._itervalues.<locals>.<genexpr>�rr�ryr�rz�_itervalues�szParseResults._itervaluescs�fdd����D�S)Nc3s|]}|�|fVqdSr�ryrr�ryrzr��sz*ParseResults._iteritems.<locals>.<genexpr>rr�ryr�rz�
_iteritems�szParseResults._iteritemscCst|���S)zVReturns all named result keys (as a list in Python 2.x, as an iterator in Python 3.x).)r�rr�ryryrz�keys�szParseResults.keyscCst|���S)zXReturns all named result values (as a list in Python 2.x, as an iterator in Python 3.x).)r��
itervaluesr�ryryrz�values�szParseResults.valuescCst|���S)zfReturns all named result key-values (as a list of tuples in Python 2.x, as an iterator in Python 3.x).)r��	iteritemsr�ryryrzr��szParseResults.itemscCs
t|j�S)z�Since keys() returns an iterator, this method is helpful in bypassing
           code that looks for the existence of any defined results names.)�boolr�r�ryryrz�haskeys�szParseResults.haskeyscOs�|s
dg}|��D]*\}}|dkr0|d|f}qtd|��qt|dt�sdt|�dksd|d|kr~|d}||}||=|S|d}|SdS)a�
        Removes and returns item at specified index (default=C{last}).
        Supports both C{list} and C{dict} semantics for C{pop()}. If passed no
        argument or an integer argument, it will use C{list} semantics
        and pop tokens from the list of parsed tokens. If passed a 
        non-integer argument (most likely a string), it will use C{dict}
        semantics and pop the corresponding value from any defined 
        results names. A second default return value argument is 
        supported, just as in C{dict.pop()}.

        Example::
            def remove_first(tokens):
                tokens.pop(0)
            print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
            print(OneOrMore(Word(nums)).addParseAction(remove_first).parseString("0 123 321")) # -> ['123', '321']

            label = Word(alphas)
            patt = label("LABEL") + OneOrMore(Word(nums))
            print(patt.parseString("AAB 123 321").dump())

            # Use pop() in a parse action to remove named result (note that corresponding value is not
            # removed from list form of results)
            def remove_LABEL(tokens):
                tokens.pop("LABEL")
                return tokens
            patt.addParseAction(remove_LABEL)
            print(patt.parseString("AAB 123 321").dump())
        prints::
            ['AAB', '123', '321']
            - LABEL: AAB

            ['AAB', '123', '321']
        rt�defaultrz-pop() got an unexpected keyword argument '%s'r�N)r�r�r}rvr�)r�r��kwargsr�r��indexr��defaultvalueryryrz�pop�s""
�
�zParseResults.popcCs||kr||S|SdS)ai
        Returns named result matching the given key, or if there is no
        such name, then returns the given C{defaultValue} or C{None} if no
        C{defaultValue} is specified.

        Similar to C{dict.get()}.
        
        Example::
            integer = Word(nums)
            date_str = integer("year") + '/' + integer("month") + '/' + integer("day")           

            result = date_str.parseString("1999/12/31")
            print(result.get("year")) # -> '1999'
            print(result.get("hour", "not specified")) # -> 'not specified'
            print(result.get("hour")) # -> None
        Nry)r��key�defaultValueryryrzr�3szParseResults.getcCsR|j�||�|j��D]4\}}t|�D]"\}\}}t||||k�||<q(qdS)a
        Inserts new element at location index in the list of parsed tokens.
        
        Similar to C{list.insert()}.

        Example::
            print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']

            # use a parse action to insert the parse location in the front of the parsed results
            def insert_locn(locn, tokens):
                tokens.insert(0, locn)
            print(OneOrMore(Word(nums)).addParseAction(insert_locn).parseString("0 123 321")) # -> [0, '0', '123', '321']
        N)r��insertr�r�r�r�)r�r�insStrr�rr�rrryryrzr#IszParseResults.insertcCs|j�|�dS)a�
        Add single element to end of ParseResults list of elements.

        Example::
            print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
            
            # use a parse action to compute the sum of the parsed integers, and add it to the end
            def append_sum(tokens):
                tokens.append(sum(map(int, tokens)))
            print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444]
        N)r��append)r��itemryryrzr%]szParseResults.appendcCs$t|t�r||7}n|j�|�dS)a
        Add sequence of elements to end of ParseResults list of elements.

        Example::
            patt = OneOrMore(Word(alphas))
            
            # use a parse action to append the reverse of the matched strings, to make a palindrome
            def make_palindrome(tokens):
                tokens.extend(reversed([t[::-1] for t in tokens]))
                return ''.join(tokens)
            print(patt.addParseAction(make_palindrome).parseString("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl'
        N)r}r$r��extend)r��itemseqryryrzr'ks

zParseResults.extendcCs|jdd�=|j��dS)z7
        Clear all elements and results names.
        N)r�r��clearr�ryryrzr)}szParseResults.clearcCsjz
||WStk
r YdSX||jkrb||jkrH|j|ddStdd�|j|D��SndSdS)Nr�rtrcSsg|]}|d�qSr�ryr�ryryrzr��sz,ParseResults.__getattr__.<locals>.<listcomp>)r�r�r�r$�r�r�ryryrzr��s


zParseResults.__getattr__cCs|��}||7}|Sr��r�)r��otherr�ryryrz�__add__�szParseResults.__add__cs�|jrjt|j���fdd��|j��}�fdd�|D�}|D],\}}|||<t|dt�r<t|�|d_q<|j|j7_|j�	|j�|S)Ncs|dkr�S|�Sr�ry)�a)�offsetryrzr{�r|z'ParseResults.__iadd__.<locals>.<lambda>c	s4g|],\}}|D]}|t|d�|d��f�qqS�rr�)r��r�r��vlistr�)�	addoffsetryrzr��s�z)ParseResults.__iadd__.<locals>.<listcomp>r)
r�r�r�r�r}r$r�r�r��update)r�r,�
otheritems�otherdictitemsr�r�ry)r3r/rz�__iadd__�s


�zParseResults.__iadd__cCs&t|t�r|dkr|��S||SdSr�)r}rvr��r�r,ryryrz�__radd__�szParseResults.__radd__cCsdt|j�t|j�fS)Nz(%s, %s))r�r�r�r�ryryrzr��szParseResults.__repr__cCsdd�dd�|jD��dS)N�[�, css(|] }t|t�rt|�nt|�VqdSr�)r}r$r�r��r�r�ryryrzr��sz'ParseResults.__str__.<locals>.<genexpr>�])r�r�r�ryryrzr��szParseResults.__str__r�cCsLg}|jD]<}|r |r |�|�t|t�r8||��7}q
|�t|��q
|Sr�)r�r%r}r$�
_asStringListr�)r��sep�outr&ryryrzr>�s


zParseResults._asStringListcCsdd�|jD�S)a�
        Returns the parse results as a nested list of matching tokens, all converted to strings.

        Example::
            patt = OneOrMore(Word(alphas))
            result = patt.parseString("sldkj lsdkj sldkj")
            # even though the result prints in string-like form, it is actually a pyparsing ParseResults
            print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj']
            
            # Use asList() to create an actual list
            result_list = result.asList()
            print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj']
        cSs"g|]}t|t�r|��n|�qSry)r}r$r�)r��resryryrzr��sz'ParseResults.asList.<locals>.<listcomp>rr�ryryrzr��szParseResults.asListcs6tr|j}n|j}�fdd��t�fdd�|�D��S)a�
        Returns the named parse results as a nested dictionary.

        Example::
            integer = Word(nums)
            date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
            
            result = date_str.parseString('12/31/1999')
            print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]})
            
            result_dict = result.asDict()
            print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'}

            # even though a ParseResults supports dict-like access, sometime you just need to have a dict
            import json
            print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable
            print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"}
        cs6t|t�r.|��r|��S�fdd�|D�Sn|SdS)Ncsg|]}�|��qSryryr���toItemryrzr��sz7ParseResults.asDict.<locals>.toItem.<locals>.<listcomp>)r}r$r�asDict)r�rBryrzrC�s

z#ParseResults.asDict.<locals>.toItemc3s|]\}}|�|�fVqdSr�ry�r�r�r�rBryrzr��sz&ParseResults.asDict.<locals>.<genexpr>)�PY_3r�rr�)r��item_fnryrBrzrD�s
	zParseResults.asDictcCs8t|j�}|j��|_|j|_|j�|j�|j|_|S)zA
        Returns a new copy of a C{ParseResults} object.
        )r$r�r�r�r�r�r4r��r�r�ryryrzr��s
zParseResults.copyFcCsLd}g}tdd�|j��D��}|d}|s8d}d}d}d}	|dk	rJ|}	n|jrV|j}	|	sf|rbdSd}	|||d|	d	g7}t|j�D]�\}
}t|t�r�|
|kr�||�||
|o�|dk||�g7}n||�d|o�|dk||�g7}q�d}|
|kr�||
}|�s|�rq�nd}t	t
|��}
|||d|d	|
d
|d	g	7}q�|||d
|	d	g7}d�|�S)z�
        (Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.
        �
css(|] \}}|D]}|d|fVqqdS�r�Nryr1ryryrzr�s�z%ParseResults.asXML.<locals>.<genexpr>�  r�N�ITEM�<�>�</)r�r�r�r�r�r�r}r$�asXMLr�r�r�)r��doctag�namedItemsOnly�indent�	formatted�nlr@�
namedItems�nextLevelIndent�selfTagr�rA�resTag�xmlBodyTextryryrzrP�s^

�

�
�zParseResults.asXMLcCs:|j��D]*\}}|D]\}}||kr|Sqq
dSr�)r�r�)r�r�r�r2r�r�ryryrz�__lookup;s
zParseResults.__lookupcCs�|jr|jS|jr.|��}|r(|�|�SdSnNt|�dkrxt|j�dkrxtt|j����dddkrxtt|j����SdSdS)a(
        Returns the results name for this token expression. Useful when several 
        different expressions might match at a particular location.

        Example::
            integer = Word(nums)
            ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d")
            house_number_expr = Suppress('#') + Word(nums, alphanums)
            user_data = (Group(house_number_expr)("house_number") 
                        | Group(ssn_expr)("ssn")
                        | Group(integer)("age"))
            user_info = OneOrMore(user_data)
            
            result = user_info.parseString("22 111-22-3333 #221B")
            for item in result:
                print(item.getName(), ':', item[0])
        prints::
            age : 22
            ssn : 111-22-3333
            house_number : 221B
        Nr�r)rrt)	r�r��_ParseResults__lookupr�r��nextrrr)r��parryryrz�getNameBs
��zParseResults.getNamercCsZg}d}|�|t|����|�rP|��r�tdd�|��D��}|D]r\}}|r\|�|�|�d|d||f�t|t�r�|r�|�|�||d��q�|�t|��qF|�t	|��qFn�t
dd�|D���rP|}t|�D]r\}	}
t|
t��r$|�d|d||	|d|d|
�||d�f�q�|�d|d||	|d|dt|
�f�q�d	�|�S)
aH
        Diagnostic method for listing out the contents of a C{ParseResults}.
        Accepts an optional C{indent} argument so that this string can be embedded
        in a nested display of other data.

        Example::
            integer = Word(nums)
            date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
            
            result = date_str.parseString('12/31/1999')
            print(result.dump())
        prints::
            ['12', '/', '31', '/', '1999']
            - day: 1999
            - month: 31
            - year: 12
        rIcss|]\}}t|�|fVqdSr�)rrEryryrzr�~sz$ParseResults.dump.<locals>.<genexpr>z
%s%s- %s: rKr�css|]}t|t�VqdSr�)r}r$)r��vvryryrzr��sz
%s%s[%d]:
%s%s%sr�)
r%r�r�r�sortedr�r}r$�dumpr��anyr�r�)r�rS�depth�fullr@�NLr�r�r�r�r`ryryrzrbgs,

4,zParseResults.dumpcOstj|��f|�|�dS)a�
        Pretty-printer for parsed results as a list, using the C{pprint} module.
        Accepts additional positional or keyword args as defined for the 
        C{pprint.pprint} method. (U{http://docs.python.org/3/library/pprint.html#pprint.pprint})

        Example::
            ident = Word(alphas, alphanums)
            num = Word(nums)
            func = Forward()
            term = ident | num | Group('(' + func + ')')
            func <<= ident + Group(Optional(delimitedList(term)))
            result = func.parseString("fna a,b,(fnb c,d,200),100")
            result.pprint(width=40)
        prints::
            ['fna',
             ['a',
              'b',
              ['(', 'fnb', ['c', 'd', '200'], ')'],
              '100']]
        N)�pprintr��r�r�rryryrzrg�szParseResults.pprintcCs.|j|j��|jdk	r|��p d|j|jffSr�)r�r�r�r�r�r�r�ryryrz�__getstate__�s��zParseResults.__getstate__cCsN|d|_|d\|_}}|_i|_|j�|�|dk	rDt|�|_nd|_dSr�)r�r�r�r�r4r�r�)r��stater^�inAccumNamesryryrz�__setstate__�s
�zParseResults.__setstate__cCs|j|j|j|jfSr�)r�r�r�r�r�ryryrz�__getnewargs__�szParseResults.__getnewargs__cCstt|��t|���Sr�)r�r�r�rr�ryryrzr��szParseResults.__dir__)NNTT)N)r�)NFr�T)r�rT)4r�r�r�r�r�r}r�r�r�rrrr	�__nonzero__rrrrrrFrrr�rrrrr r�r#r%r'r)r�r-r7r9r�r�r>r�rDr�rPr\r_rbrgrirlrmr�ryryryrzr$Dsh&
	'	
4

#
=%
-
cCsF|}d|krt|�kr4nn||ddkr4dS||�dd|�S)aReturns current column within a string, counting newlines as line separators.
   The first column is number 1.

   Note: the default parsing behavior is to expand tabs in the input string
   before starting the parsing process.  See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
   on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
   consistent view of the parsed string, the parse location, and line and column
   positions within the parsed string.
   rr�rI)r��rfind)r��strgr�ryryrzr;�s
cCs|�dd|�dS)aReturns current line number within a string, counting newlines as line separators.
   The first line is number 1.

   Note: the default parsing behavior is to expand tabs in the input string
   before starting the parsing process.  See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
   on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
   consistent view of the parsed string, the parse location, and line and column
   positions within the parsed string.
   rIrr�)�count)r�rpryryrzrL�s
cCsF|�dd|�}|�d|�}|dkr2||d|�S||dd�SdS)zfReturns the line of text containing loc within a string, counting newlines as line separators.
       rIrr�N)ro�find)r�rp�lastCR�nextCRryryrzrI�s
cCs8tdt|�dt|�dt||�t||�f�dS)NzMatch z at loc z(%d,%d))�printr�rLr;)�instringr��exprryryrz�_defaultStartDebugAction�srxcCs$tdt|�dt|����dS)NzMatched z -> )rur�rr�)rv�startloc�endlocrw�toksryryrz�_defaultSuccessDebugAction�sr|cCstdt|��dS)NzException raised:)rur�)rvr�rw�excryryrz�_defaultExceptionDebugAction�sr~cGsdS)zG'Do-nothing' debug action, to suppress debugging output during parsing.Nry)r�ryryrzrS�srscs��tkr�fdd�Sdg�dg�tdd�dkrFddd�}dd	d
��ntj}tj�d}|dd�d
}|d|d|f�������fdd�}d}zt�dt�d�j�}Wntk
r�t��}YnX||_|S)Ncs�|�Sr�ry�r��lrx)�funcryrzr{r|z_trim_arity.<locals>.<lambda>rFrs)rq�cSs8tdkrdnd}tj||dd�|}|dd�gS)N)rqr�r������r���limitrs)�system_version�	traceback�
extract_stack)r�r/�
frame_summaryryryrzr�sz"_trim_arity.<locals>.extract_stackcSs$tj||d�}|d}|dd�gS)Nr�rtrs)r��
extract_tb)�tbr��framesr�ryryrzr�sz_trim_arity.<locals>.extract_tb�r�rtr�c	s�z"�|�dd��}d�d<|WStk
r��dr>�n4z.t��d}�|dd�ddd��ksj�W5~X�d�kr��dd7<Yq�YqXqdS)NrTrtrsr�r�)r�r��exc_info)r�r�r��r��
foundArityr�r��maxargs�pa_call_line_synthryrz�wrapper-s z_trim_arity.<locals>.wrapperz<parse action>r��	__class__)r)r)	�singleArgBuiltinsr�r�r�r��getattrr��	Exceptionr)r�r�r��	LINE_DIFF�	this_liner��	func_nameryr�rz�_trim_aritys,

�r�cs�eZdZdZdZdZedd��Zedd��Zd�dd	�Z	d
d�Z
dd
�Zd�dd�Zd�dd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd�dd �Zd!d"�Zd�d#d$�Zd%d&�Zd'd(�ZGd)d*�d*e�Zed+k	r�Gd,d-�d-e�ZnGd.d-�d-e�ZiZe�Zd/d/gZ d�d0d1�Z!eZ"ed2d3��Z#dZ$ed�d5d6��Z%d�d7d8�Z&e'dfd9d:�Z(d;d<�Z)e'fd=d>�Z*e'dfd?d@�Z+dAdB�Z,dCdD�Z-dEdF�Z.dGdH�Z/dIdJ�Z0dKdL�Z1dMdN�Z2dOdP�Z3dQdR�Z4dSdT�Z5dUdV�Z6dWdX�Z7dYdZ�Z8d�d[d\�Z9d]d^�Z:d_d`�Z;dadb�Z<dcdd�Z=dedf�Z>dgdh�Z?d�didj�Z@dkdl�ZAdmdn�ZBdodp�ZCdqdr�ZDgfdsdt�ZEd�dudv�ZF�fdwdx�ZGdydz�ZHd{d|�ZId}d~�ZJdd��ZKd�d�d��ZLd�d�d��ZM�ZNS)�r&z)Abstract base level parser element class.z 
	
FcCs
|t_dS)a�
        Overrides the default whitespace chars

        Example::
            # default whitespace chars are space, <TAB> and newline
            OneOrMore(Word(alphas)).parseString("abc def\nghi jkl")  # -> ['abc', 'def', 'ghi', 'jkl']
            
            # change to just treat newline as significant
            ParserElement.setDefaultWhitespaceChars(" \t")
            OneOrMore(Word(alphas)).parseString("abc def\nghi jkl")  # -> ['abc', 'def']
        N)r&�DEFAULT_WHITE_CHARS��charsryryrz�setDefaultWhitespaceCharsTs
z'ParserElement.setDefaultWhitespaceCharscCs
|t_dS)a�
        Set class to be used for inclusion of string literals into a parser.
        
        Example::
            # default literal class used is Literal
            integer = Word(nums)
            date_str = integer("year") + '/' + integer("month") + '/' + integer("day")           

            date_str.parseString("1999/12/31")  # -> ['1999', '/', '12', '/', '31']


            # change to Suppress
            ParserElement.inlineLiteralsUsing(Suppress)
            date_str = integer("year") + '/' + integer("month") + '/' + integer("day")           

            date_str.parseString("1999/12/31")  # -> ['1999', '12', '31']
        N)r&�_literalStringClass)r�ryryrz�inlineLiteralsUsingcsz!ParserElement.inlineLiteralsUsingcCs�t�|_d|_d|_d|_||_d|_tj|_	d|_
d|_d|_t�|_
d|_d|_d|_d|_d|_d|_d|_d|_d|_dS)NTFr�)NNN)r��parseAction�
failAction�strRepr�resultsName�
saveAsList�skipWhitespacer&r��
whiteChars�copyDefaultWhiteChars�mayReturnEmpty�keepTabs�ignoreExprs�debug�streamlined�
mayIndexError�errmsg�modalResults�debugActions�re�callPreparse�
callDuringTry)r��savelistryryrzr�xs(zParserElement.__init__cCs<t�|�}|jdd�|_|jdd�|_|jr8tj|_|S)a$
        Make a copy of this C{ParserElement}.  Useful for defining different parse actions
        for the same parsing pattern, using copies of the original parse element.
        
        Example::
            integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
            integerK = integer.copy().addParseAction(lambda toks: toks[0]*1024) + Suppress("K")
            integerM = integer.copy().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M")
            
            print(OneOrMore(integerK | integerM | integer).parseString("5K 100 640K 256M"))
        prints::
            [5120, 100, 655360, 268435456]
        Equivalent form of C{expr.copy()} is just C{expr()}::
            integerM = integer().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M")
        N)r�r�r�r�r&r�r�)r��cpyryryrzr��s
zParserElement.copycCs*||_d|j|_t|d�r&|j|j_|S)af
        Define name for this expression, makes debugging and exception messages clearer.
        
        Example::
            Word(nums).parseString("ABC")  # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1)
            Word(nums).setName("integer").parseString("ABC")  # -> Exception: Expected integer (at char 0), (line:1, col:1)
        �	Expected �	exception)r�r�rr�r�r*ryryrz�setName�s


zParserElement.setNamecCs4|��}|�d�r"|dd�}d}||_||_|S)aP
        Define name for referencing matching tokens as a nested attribute
        of the returned parse results.
        NOTE: this returns a *copy* of the original C{ParserElement} object;
        this is so that the client can define a basic element, such as an
        integer, and reference it in multiple places with different names.

        You can also set results names using the abbreviated syntax,
        C{expr("name")} in place of C{expr.setResultsName("name")} - 
        see L{I{__call__}<__call__>}.

        Example::
            date_str = (integer.setResultsName("year") + '/' 
                        + integer.setResultsName("month") + '/' 
                        + integer.setResultsName("day"))

            # equivalent form:
            date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
        �*NrtT)r��endswithr�r�)r�r��listAllMatches�newselfryryrz�setResultsName�s
zParserElement.setResultsNameTcs@|r&|j�d�fdd�	}�|_||_nt|jd�r<|jj|_|S)z�Method to invoke the Python pdb debugger when this element is
           about to be parsed. Set C{breakFlag} to True to enable, False to
           disable.
        Tcsddl}|���||||�Sr�)�pdb�	set_trace)rvr��	doActions�callPreParser���_parseMethodryrz�breaker�sz'ParserElement.setBreak.<locals>.breaker�_originalParseMethod)TT)�_parser�r)r��	breakFlagr�ryr�rz�setBreak�s
zParserElement.setBreakcOs&tttt|���|_|�dd�|_|S)a
        Define one or more actions to perform when successfully matching parse element definition.
        Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)},
        C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where:
         - s   = the original string being parsed (see note below)
         - loc = the location of the matching substring
         - toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object
        If the functions in fns modify the tokens, they can return them as the return
        value from fn, and the modified list of tokens will replace the original.
        Otherwise, fn does not need to return any value.

        Optional keyword arguments:
         - callDuringTry = (default=C{False}) indicate if parse action should be run during lookaheads and alternate testing

        Note: the default parsing behavior is to expand tabs in the input string
        before starting the parsing process.  See L{I{parseString}<parseString>} for more information
        on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
        consistent view of the parsed string, the parse location, and line and column
        positions within the parsed string.
        
        Example::
            integer = Word(nums)
            date_str = integer + '/' + integer + '/' + integer

            date_str.parseString("1999/12/31")  # -> ['1999', '/', '12', '/', '31']

            # use parse action to convert to ints at parse time
            integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
            date_str = integer + '/' + integer + '/' + integer

            # note that integer fields are now ints, not strings
            date_str.parseString("1999/12/31")  # -> [1999, '/', 12, '/', 31]
        r�F)r��mapr�r�r�r��r��fnsrryryrzr��s"zParserElement.setParseActioncOs4|jtttt|���7_|jp,|�dd�|_|S)z�
        Add one or more parse actions to expression's list of parse actions. See L{I{setParseAction}<setParseAction>}.
        
        See examples in L{I{copy}<copy>}.
        r�F)r�r�r�r�r�r�r�ryryrz�addParseActionszParserElement.addParseActioncs^|�dd��|�dd�rtnt�|D] ����fdd�}|j�|�q$|jpV|�dd�|_|S)a�Add a boolean predicate function to expression's list of parse actions. See 
        L{I{setParseAction}<setParseAction>} for function call signatures. Unlike C{setParseAction}, 
        functions passed to C{addCondition} need to return boolean success/fail of the condition.

        Optional keyword arguments:
         - message = define a custom message to be used in the raised exception
         - fatal   = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException
         
        Example::
            integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
            year_int = integer.copy()
            year_int.addCondition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later")
            date_str = year_int + '/' + integer + '/' + integer

            result = date_str.parseString("1999/12/31")  # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1)
        �messagezfailed user-defined condition�fatalFcs$tt��|||��s �||���dSr�)rr�r��exc_type�fnr�ryrz�pa&sz&ParserElement.addCondition.<locals>.par�)r�r#r!r�r%r�)r�r�rr�ryr�rz�addConditionszParserElement.addConditioncCs
||_|S)aDefine action to perform if parsing fails at this expression.
           Fail acton fn is a callable function that takes the arguments
           C{fn(s,loc,expr,err)} where:
            - s = string being parsed
            - loc = location where expression match was attempted and failed
            - expr = the parse expression that failed
            - err = the exception thrown
           The function returns no value.  It may throw C{L{ParseFatalException}}
           if it is desired to stop parsing immediately.)r�)r�r�ryryrz�
setFailAction-s
zParserElement.setFailActionc	CsNd}|rJd}|jD]4}z|�||�\}}d}qWqtk
rDYqXqq|S�NTF)r�r�r!)r�rvr��
exprsFound�e�dummyryryrz�_skipIgnorables:s


zParserElement._skipIgnorablescCsH|jr|�||�}|jrD|j}t|�}||krD|||krD|d7}q&|S�Nr�)r�r�r�r�r�)r�rvr��wt�instrlenryryrz�preParseGs
zParserElement.preParsecCs|gfSr�ry�r�rvr�r�ryryrz�	parseImplSszParserElement.parseImplcCs|Sr�ry�r�rvr��	tokenlistryryrz�	postParseVszParserElement.postParsec
Cs�|j}|s|jr�|jdr,|jd|||�|rD|jrD|�||�}n|}|}zDz|�|||�\}}Wn(tk
r�t|t|�|j	|��YnXWnXt
k
r�}	z:|jdr�|jd||||	�|jr�|�||||	��W5d}	~	XYnXn�|�r|j�r|�||�}n|}|}|j�s&|t|�k�rjz|�|||�\}}Wn*tk
�rft|t|�|j	|��YnXn|�|||�\}}|�|||�}t
||j|j|jd�}
|j�r�|�s�|j�r�|�rTzN|jD]B}||||
�}|dk	�r�t
||j|j�o�t|t
tf�|jd�}
�q�WnFt
k
�rP}	z&|jd�r>|jd||||	��W5d}	~	XYnXnJ|jD]B}||||
�}|dk	�rZt
||j|j�o�t|t
tf�|jd�}
�qZ|�r�|jd�r�|jd|||||
�||
fS)Nrrs)r�r�r�)r�r�r�r�r�r�r�r!r�r�rr�r�r$r�r�r�r�r�r}r�)r�rvr�r�r��	debugging�preloc�tokensStart�tokens�err�	retTokensr�ryryrz�
_parseNoCacheZst





�

�
zParserElement._parseNoCachecCs@z|j||dd�dWStk
r:t|||j|��YnXdS)NF)r�r)r�r#r!r��r�rvr�ryryrz�tryParse�szParserElement.tryParsec	Cs4z|�||�Wnttfk
r*YdSXdSdS)NFT)r�r!r�r�ryryrz�canParseNext�s
zParserElement.canParseNextc@seZdZdd�ZdS)zParserElement._UnboundedCachecs~i�t�|_���fdd�}�fdd�}�fdd�}�fdd�}t�||�|_t�||�|_t�||�|_t�||�|_dS)	Ncs��|��Sr��r��r�r!��cache�not_in_cacheryrzr��sz3ParserElement._UnboundedCache.__init__.<locals>.getcs|�|<dSr�ry�r�r!r�r�ryrz�set�sz3ParserElement._UnboundedCache.__init__.<locals>.setcs���dSr��r)r�r�ryrzr)�sz5ParserElement._UnboundedCache.__init__.<locals>.clearcst��Sr��r�r�r�ryrz�	cache_len�sz9ParserElement._UnboundedCache.__init__.<locals>.cache_len)r�r��types�
MethodTyper�r�r)r)r�r�r�r)r�ryr�rzr��sz&ParserElement._UnboundedCache.__init__N�r�r�r�r�ryryryrz�_UnboundedCache�sr�Nc@seZdZdd�ZdS)�ParserElement._FifoCachecs�t�|_�t����fdd�}��fdd�}�fdd�}�fdd�}t�||�|_t�||�|_t�||�|_t�||�|_dS)	Ncs��|��Sr�r�r�r�ryrzr��s�.ParserElement._FifoCache.__init__.<locals>.getcs>|�|<t���kr:z��d�Wqtk
r6YqXqdS�NF)r��popitemr�r�)r��sizeryrzr��s�.ParserElement._FifoCache.__init__.<locals>.setcs���dSr�r�r�r�ryrzr)�s�0ParserElement._FifoCache.__init__.<locals>.clearcst��Sr�r�r�r�ryrzr��s�4ParserElement._FifoCache.__init__.<locals>.cache_len)	r�r��_OrderedDictr�r�r�r�r)r�r�rr�r�r)r�ry)r�r�rrzr��s�!ParserElement._FifoCache.__init__Nr�ryryryrz�
_FifoCache�sr
c@seZdZdd�ZdS)r�cs�t�|_�i�t�g�����fdd�}���fdd�}��fdd�}�fdd�}t�||�|_t�||�|_t�||�|_t�||�|_	dS)	Ncs��|��Sr�r�r�r�ryrzr��srcs4|�|<t���kr&�����d�q��|�dSr�)r�r �popleftr%r�)r��key_fiforryrzr��srcs������dSr�r�r�)r�rryrzr)�srcst��Sr�r�r�r�ryrzr��sr)
r�r��collections�dequer�r�r�r�r)rrry)r�rr�rrzr��sr	Nr�ryryryrzr
�srcCsd\}}|||||f}tj��tj}|�|�}	|	|jkr�tj|d7<z|�||||�}	Wn8tk
r�}
z|�||
j	|
j
���W5d}
~
XYn.X|�||	d|	d��f�|	W5QR�Sn@tj|d7<t|	t
�r�|	�|	d|	d��fW5QR�SW5QRXdS)Nr0r�r)r&�packrat_cache_lock�
packrat_cacher�r��packrat_cache_statsr�rr�r�r�r�r}r�)r�rvr�r�r��HIT�MISS�lookupr�rr�ryryrz�_parseCaches$


zParserElement._parseCachecCs(tj��dgttj�tjdd�<dSr�)r&rr)r�rryryryrz�
resetCaches
zParserElement.resetCache�cCs8tjs4dt_|dkr t��t_nt�|�t_tjt_dS)a�Enables "packrat" parsing, which adds memoizing to the parsing logic.
           Repeated parse attempts at the same string location (which happens
           often in many complex grammars) can immediately return a cached value,
           instead of re-executing parsing/validating code.  Memoizing is done of
           both valid results and parsing exceptions.
           
           Parameters:
            - cache_size_limit - (default=C{128}) - if an integer value is provided
              will limit the size of the packrat cache; if None is passed, then
              the cache size will be unbounded; if 0 is passed, the cache will
              be effectively disabled.
            
           This speedup may break existing programs that use parse actions that
           have side-effects.  For this reason, packrat parsing is disabled when
           you first import pyparsing.  To activate the packrat feature, your
           program must call the class method C{ParserElement.enablePackrat()}.  If
           your program uses C{psyco} to "compile as you go", you must call
           C{enablePackrat} before calling C{psyco.full()}.  If you do not do this,
           Python will crash.  For best results, call C{enablePackrat()} immediately
           after importing pyparsing.
           
           Example::
               import pyparsing
               pyparsing.ParserElement.enablePackrat()
        TN)r&�_packratEnabledr�rr
rr�)�cache_size_limitryryrz�
enablePackrat%szParserElement.enablePackratc
Cs�t��|js|��|jD]}|��q|js8|��}z<|�|d�\}}|rr|�||�}t	�t
�}|�||�Wn0tk
r�}ztjr��n|�W5d}~XYnX|SdS)aB
        Execute the parse expression with the given string.
        This is the main interface to the client code, once the complete
        expression has been built.

        If you want the grammar to require that the entire input string be
        successfully parsed, then set C{parseAll} to True (equivalent to ending
        the grammar with C{L{StringEnd()}}).

        Note: C{parseString} implicitly calls C{expandtabs()} on the input string,
        in order to report proper column numbers in parse actions.
        If the input string contains tabs and
        the grammar uses parse actions that use the C{loc} argument to index into the
        string being parsed, you can ensure you have a consistent view of the input
        string by:
         - calling C{parseWithTabs} on your grammar before calling C{parseString}
           (see L{I{parseWithTabs}<parseWithTabs>})
         - define your parse action using the full C{(s,loc,toks)} signature, and
           reference the input string using the parse action's C{s} argument
         - explictly expand the tabs in your input string before calling
           C{parseString}
        
        Example::
            Word('a').parseString('aaaaabaaa')  # -> ['aaaaa']
            Word('a').parseString('aaaaabaaa', parseAll=True)  # -> Exception: Expected end of text
        rN)
r&rr��
streamliner�r��
expandtabsr�r�rr+r�verbose_stacktrace)r�rv�parseAllr�r�r��ser}ryryrz�parseStringHs$

zParserElement.parseStringc
cs6|js|��|jD]}|��q|js4t|���}t|�}d}|j}|j}t	�
�d}	z�||kr�|	|kr�z |||�}
|||
dd�\}}Wntk
r�|
d}YqZX||kr�|	d7}	||
|fV|r�|||�}
|
|kr�|}q�|d7}q�|}qZ|
d}qZWn4tk
�r0}zt	j
�r�n|�W5d}~XYnXdS)a�
        Scan the input string for expression matches.  Each match will return the
        matching tokens, start location, and end location.  May be called with optional
        C{maxMatches} argument, to clip scanning after 'n' matches are found.  If
        C{overlap} is specified, then overlapping matches will be reported.

        Note that the start and end locations are reported relative to the string
        being parsed.  See L{I{parseString}<parseString>} for more information on parsing
        strings with embedded tabs.

        Example::
            source = "sldjf123lsdjjkf345sldkjf879lkjsfd987"
            print(source)
            for tokens,start,end in Word(alphas).scanString(source):
                print(' '*start + '^'*(end-start))
                print(' '*start + tokens[0])
        
        prints::
        
            sldjf123lsdjjkf345sldkjf879lkjsfd987
            ^^^^^
            sldjf
                    ^^^^^^^
                    lsdjjkf
                              ^^^^^^
                              sldkjf
                                       ^^^^^^
                                       lkjsfd
        rF�r�r�N)r�rr�r�r�rr�r�r�r&rr!rr)r�rv�
maxMatches�overlapr�r�r��
preparseFn�parseFn�matchesr��nextLocr��nextlocr}ryryrz�
scanStringzsB




zParserElement.scanStringc
Cs�g}d}d|_z�|�|�D]Z\}}}|�|||��|rpt|t�rR||��7}nt|t�rf||7}n
|�|�|}q|�||d��dd�|D�}d�tt	t
|���WStk
r�}ztj
rƂn|�W5d}~XYnXdS)af
        Extension to C{L{scanString}}, to modify matching text with modified tokens that may
        be returned from a parse action.  To use C{transformString}, define a grammar and
        attach a parse action to it that modifies the returned token list.
        Invoking C{transformString()} on a target string will then scan for matches,
        and replace the matched text patterns according to the logic in the parse
        action.  C{transformString()} returns the resulting transformed string.
        
        Example::
            wd = Word(alphas)
            wd.setParseAction(lambda toks: toks[0].title())
            
            print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york."))
        Prints::
            Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.
        rTNcSsg|]}|r|�qSryry)r��oryryrzr��sz1ParserElement.transformString.<locals>.<listcomp>r�)r�r)r%r}r$r�r�r�r�r��_flattenrr&r)r�rvr@�lastErxr�r�r}ryryrzr��s(



zParserElement.transformStringc
CsRztdd�|�||�D��WStk
rL}ztjr8�n|�W5d}~XYnXdS)a�
        Another extension to C{L{scanString}}, simplifying the access to the tokens found
        to match the given parse expression.  May be called with optional
        C{maxMatches} argument, to clip searching after 'n' matches are found.
        
        Example::
            # a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters
            cap_word = Word(alphas.upper(), alphas.lower())
            
            print(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity"))

            # the sum() builtin can be used to merge results into a single ParseResults object
            print(sum(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity")))
        prints::
            [['More'], ['Iron'], ['Lead'], ['Gold'], ['I'], ['Electricity']]
            ['More', 'Iron', 'Lead', 'Gold', 'I', 'Electricity']
        cSsg|]\}}}|�qSryry)r�rxr�r�ryryrzr��sz.ParserElement.searchString.<locals>.<listcomp>N)r$r)rr&r)r�rvr"r}ryryrz�searchString�szParserElement.searchStringc	csTd}d}|j||d�D]*\}}}|||�V|r<|dV|}q||d�VdS)a[
        Generator method to split a string using the given expression as a separator.
        May be called with optional C{maxsplit} argument, to limit the number of splits;
        and the optional C{includeSeparators} argument (default=C{False}), if the separating
        matching text should be included in the split results.
        
        Example::        
            punc = oneOf(list(".,;:/-!?"))
            print(list(punc.split("This, this?, this sentence, is badly punctuated!")))
        prints::
            ['This', ' this', '', ' this sentence', ' is badly punctuated', '']
        r)r"N)r))	r�rv�maxsplit�includeSeparators�splits�lastrxr�r�ryryrzr�s

zParserElement.splitcCsFt|t�rt�|�}t|t�s:tjdt|�tdd�dSt||g�S)a�
        Implementation of + operator - returns C{L{And}}. Adding strings to a ParserElement
        converts them to L{Literal}s by default.
        
        Example::
            greet = Word(alphas) + "," + Word(alphas) + "!"
            hello = "Hello, World!"
            print (hello, "->", greet.parseString(hello))
        Prints::
            Hello, World! -> ['Hello', ',', 'World', '!']
        �4Cannot combine element of type %s with ParserElementrs��
stacklevelN)	r}r�r&r��warnings�warnr��
SyntaxWarningrr8ryryrzr-s


�zParserElement.__add__cCsBt|t�rt�|�}t|t�s:tjdt|�tdd�dS||S)z]
        Implementation of + operator when left operand is not a C{L{ParserElement}}
        r2rsr3N�r}r�r&r�r5r6r�r7r8ryryrzr91s


�zParserElement.__radd__cCsJt|t�rt�|�}t|t�s:tjdt|�tdd�dS|t�	�|S)zQ
        Implementation of - operator, returns C{L{And}} with error stop
        r2rsr3N)
r}r�r&r�r5r6r�r7r�
_ErrorStopr8ryryrz�__sub__=s


�zParserElement.__sub__cCsBt|t�rt�|�}t|t�s:tjdt|�tdd�dS||S)z]
        Implementation of - operator when left operand is not a C{L{ParserElement}}
        r2rsr3Nr8r8ryryrz�__rsub__Is


�zParserElement.__rsub__cs�t|t�r|d}}n�t|t�r�|ddd�}|ddkrHd|df}t|dt�r�|ddkr�|ddkrvt��S|ddkr�t��S�|dt��Sq�t|dt�r�t|dt�r�|\}}||8}q�tdt|d�t|d���ntdt|���|dk�rtd��|dk�rtd	��||k�r6dk�rBnntd
��|�r���fdd��|�r�|dk�rt��|�}nt�g|��|�}n�|�}n|dk�r��}nt�g|�}|S)
a�
        Implementation of * operator, allows use of C{expr * 3} in place of
        C{expr + expr + expr}.  Expressions may also me multiplied by a 2-integer
        tuple, similar to C{{min,max}} multipliers in regular expressions.  Tuples
        may also include C{None} as in:
         - C{expr*(n,None)} or C{expr*(n,)} is equivalent
              to C{expr*n + L{ZeroOrMore}(expr)}
              (read as "at least n instances of C{expr}")
         - C{expr*(None,n)} is equivalent to C{expr*(0,n)}
              (read as "0 to n instances of C{expr}")
         - C{expr*(None,None)} is equivalent to C{L{ZeroOrMore}(expr)}
         - C{expr*(1,None)} is equivalent to C{L{OneOrMore}(expr)}

        Note that C{expr*(None,n)} does not raise an exception if
        more than n exprs exist in the input stream; that is,
        C{expr*(None,n)} does not enforce a maximum number of expr
        occurrences.  If this behavior is desired, then write
        C{expr*(None,n) + ~expr}
        r)NNNrsr�z7cannot multiply 'ParserElement' and ('%s','%s') objectsz0cannot multiply 'ParserElement' and '%s' objectsz/cannot multiply ParserElement by negative valuez@second tuple value must be greater or equal to first tuple valuez+cannot multiply ParserElement by 0 or (0,0)cs(|dkrt��|d��St��SdSr�)r��n��makeOptionalListr�ryrzr?�sz/ParserElement.__mul__.<locals>.makeOptionalList)	r}rv�tupler4rr�r��
ValueErrorr)r�r,�minElements�optElementsr�ryr>rz�__mul__UsD







zParserElement.__mul__cCs
|�|�Sr�)rDr8ryryrz�__rmul__�szParserElement.__rmul__cCsFt|t�rt�|�}t|t�s:tjdt|�tdd�dSt||g�S)zI
        Implementation of | operator - returns C{L{MatchFirst}}
        r2rsr3N)	r}r�r&r�r5r6r�r7rr8ryryrz�__or__�s


�zParserElement.__or__cCsBt|t�rt�|�}t|t�s:tjdt|�tdd�dS||BS)z]
        Implementation of | operator when left operand is not a C{L{ParserElement}}
        r2rsr3Nr8r8ryryrz�__ror__�s


�zParserElement.__ror__cCsFt|t�rt�|�}t|t�s:tjdt|�tdd�dSt||g�S)zA
        Implementation of ^ operator - returns C{L{Or}}
        r2rsr3N)	r}r�r&r�r5r6r�r7rr8ryryrz�__xor__�s


�zParserElement.__xor__cCsBt|t�rt�|�}t|t�s:tjdt|�tdd�dS||AS)z]
        Implementation of ^ operator when left operand is not a C{L{ParserElement}}
        r2rsr3Nr8r8ryryrz�__rxor__�s


�zParserElement.__rxor__cCsFt|t�rt�|�}t|t�s:tjdt|�tdd�dSt||g�S)zC
        Implementation of & operator - returns C{L{Each}}
        r2rsr3N)	r}r�r&r�r5r6r�r7rr8ryryrz�__and__�s


�zParserElement.__and__cCsBt|t�rt�|�}t|t�s:tjdt|�tdd�dS||@S)z]
        Implementation of & operator when left operand is not a C{L{ParserElement}}
        r2rsr3Nr8r8ryryrz�__rand__�s


�zParserElement.__rand__cCst|�S)zE
        Implementation of ~ operator - returns C{L{NotAny}}
        )rr�ryryrz�
__invert__�szParserElement.__invert__cCs|dk	r|�|�S|��SdS)a

        Shortcut for C{L{setResultsName}}, with C{listAllMatches=False}.
        
        If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be
        passed as C{True}.
           
        If C{name} is omitted, same as calling C{L{copy}}.

        Example::
            # these are equivalent
            userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno")
            userdata = Word(alphas)("name") + Word(nums+"-")("socsecno")             
        N)r�r�r*ryryrz�__call__�s
zParserElement.__call__cCst|�S)z�
        Suppresses the output of this C{ParserElement}; useful to keep punctuation from
        cluttering up returned output.
        )r-r�ryryrz�suppress�szParserElement.suppresscCs
d|_|S)a
        Disables the skipping of whitespace before matching the characters in the
        C{ParserElement}'s defined pattern.  This is normally only used internally by
        the pyparsing module, but may be needed in some whitespace-sensitive grammars.
        F�r�r�ryryrz�leaveWhitespaceszParserElement.leaveWhitespacecCsd|_||_d|_|S)z8
        Overrides the default whitespace chars
        TF)r�r�r�)r�r�ryryrz�setWhitespaceChars
sz ParserElement.setWhitespaceCharscCs
d|_|S)z�
        Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string.
        Must be called before C{parseString} when the input grammar contains elements that
        match C{<TAB>} characters.
        T)r�r�ryryrz�
parseWithTabsszParserElement.parseWithTabscCsLt|t�rt|�}t|t�r4||jkrH|j�|�n|j�t|����|S)a�
        Define expression to be ignored (e.g., comments) while doing pattern
        matching; may be called repeatedly, to define multiple comment or other
        ignorable patterns.
        
        Example::
            patt = OneOrMore(Word(alphas))
            patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj']
            
            patt.ignore(cStyleComment)
            patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd']
        )r}r�r-r�r%r�r8ryryrz�ignores


zParserElement.ignorecCs"|pt|pt|ptf|_d|_|S)zT
        Enable display of debugging messages while doing pattern matching.
        T)rxr|r~r�r�)r��startAction�
successAction�exceptionActionryryrz�setDebugActions6s�zParserElement.setDebugActionscCs|r|�ttt�nd|_|S)a�
        Enable display of debugging messages while doing pattern matching.
        Set C{flag} to True to enable, False to disable.

        Example::
            wd = Word(alphas).setName("alphaword")
            integer = Word(nums).setName("numword")
            term = wd | integer
            
            # turn on debugging for wd
            wd.setDebug()

            OneOrMore(term).parseString("abc 123 xyz 890")
        
        prints::
            Match alphaword at loc 0(1,1)
            Matched alphaword -> ['abc']
            Match alphaword at loc 3(1,4)
            Exception raised:Expected alphaword (at char 4), (line:1, col:5)
            Match alphaword at loc 7(1,8)
            Matched alphaword -> ['xyz']
            Match alphaword at loc 11(1,12)
            Exception raised:Expected alphaword (at char 12), (line:1, col:13)
            Match alphaword at loc 15(1,16)
            Exception raised:Expected alphaword (at char 15), (line:1, col:16)

        The output shown is that produced by the default debug actions - custom debug actions can be
        specified using L{setDebugActions}. Prior to attempting
        to match the C{wd} expression, the debugging message C{"Match <exprname> at loc <n>(<line>,<col>)"}
        is shown. Then if the parse succeeds, a C{"Matched"} message is shown, or an C{"Exception raised"}
        message is shown. Also note the use of L{setName} to assign a human-readable name to the expression,
        which makes debugging and exception messages easier to understand - for instance, the default
        name created for the C{Word} expression without calling C{setName} is C{"W:(ABCD...)"}.
        F)rWrxr|r~r�)r��flagryryrz�setDebug@s#zParserElement.setDebugcCs|jSr�)r�r�ryryrzr�iszParserElement.__str__cCst|�Sr�r�r�ryryrzr�lszParserElement.__repr__cCsd|_d|_|Sr�)r�r�r�ryryrzroszParserElement.streamlinecCsdSr�ryr�ryryrz�checkRecursiontszParserElement.checkRecursioncCs|�g�dS)zj
        Check defined expressions for valid structure, check for infinite recursive definitions.
        N)rZ)r��
validateTraceryryrz�validatewszParserElement.validatecCs�z|��}Wn2tk
r>t|d��}|��}W5QRXYnXz|�||�WStk
r~}ztjrj�n|�W5d}~XYnXdS)z�
        Execute the parse expression on the given file or filename.
        If a filename is specified (instead of a file object),
        the entire file is opened, read, and closed before parsing.
        �rN)�readr��openr rr&r)r��file_or_filenamer�
file_contents�fr}ryryrz�	parseFile}szParserElement.parseFilecsHt|t�r"||kp t|�t|�kSt|t�r6|�|�Stt|�|kSdSr�)r}r&�varsr�r&�superr8�r�ryrz�__eq__�s



zParserElement.__eq__cCs
||kSr�ryr8ryryrz�__ne__�szParserElement.__ne__cCstt|��Sr�)�hash�idr�ryryrz�__hash__�szParserElement.__hash__cCs||kSr�ryr8ryryrz�__req__�szParserElement.__req__cCs
||kSr�ryr8ryryrz�__rne__�szParserElement.__rne__cCs4z|jt|�|d�WdStk
r.YdSXdS)a�
        Method for quick testing of a parser against a test string. Good for simple 
        inline microtests of sub expressions while building up larger parser.
           
        Parameters:
         - testString - to test against this expression for a match
         - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests
            
        Example::
            expr = Word(nums)
            assert expr.matches("100")
        �rTFN)r r�r)r��
testStringrryryrzr&�s

zParserElement.matches�#cCs�t|t�r"tttj|������}t|t�r4t|�}g}g}d}	|D�]�}
|dk	r^|�	|
d�sf|rr|
sr|�
|
�qD|
sxqDd�|�|
g}g}z:|
�dd�}
|j
|
|d�}|�
|j|d��|	o�|}	Wn�tk
�rr}
z�t|
t�r�dnd	}d|
k�r*|�
t|
j|
��|�
d
t|
j|
�dd|�n|�
d
|
jd|�|�
d
t|
��|	�o\|}	|
}W5d}
~
XYnDtk
�r�}z$|�
dt|��|	�o�|}	|}W5d}~XYnX|�r�|�r�|�
d	�td�|��|�
|
|f�qD|	|fS)a3
        Execute the parse expression on a series of test strings, showing each
        test, the parsed results or where the parse failed. Quick and easy way to
        run a parse expression against a list of sample strings.
           
        Parameters:
         - tests - a list of separate test strings, or a multiline string of test strings
         - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests           
         - comment - (default=C{'#'}) - expression for indicating embedded comments in the test 
              string; pass None to disable comment filtering
         - fullDump - (default=C{True}) - dump results as list followed by results names in nested outline;
              if False, only dump nested list
         - printResults - (default=C{True}) prints test output to stdout
         - failureTests - (default=C{False}) indicates if these tests are expected to fail parsing

        Returns: a (success, results) tuple, where success indicates that all tests succeeded
        (or failed if C{failureTests} is True), and the results contain a list of lines of each 
        test's output
        
        Example::
            number_expr = pyparsing_common.number.copy()

            result = number_expr.runTests('''
                # unsigned integer
                100
                # negative integer
                -100
                # float with scientific notation
                6.02e23
                # integer with scientific notation
                1e-12
                ''')
            print("Success" if result[0] else "Failed!")

            result = number_expr.runTests('''
                # stray character
                100Z
                # missing leading digit before '.'
                -.100
                # too many '.'
                3.14.159
                ''', failureTests=True)
            print("Success" if result[0] else "Failed!")
        prints::
            # unsigned integer
            100
            [100]

            # negative integer
            -100
            [-100]

            # float with scientific notation
            6.02e23
            [6.02e+23]

            # integer with scientific notation
            1e-12
            [1e-12]

            Success
            
            # stray character
            100Z
               ^
            FAIL: Expected end of text (at char 3), (line:1, col:4)

            # missing leading digit before '.'
            -.100
            ^
            FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1)

            # too many '.'
            3.14.159
                ^
            FAIL: Expected end of text (at char 4), (line:1, col:5)

            Success

        Each test string must be on a single line. If you want to test a string that spans multiple
        lines, create a test like this::

            expr.runTest(r"this is a test\n of strings that spans \n 3 lines")
        
        (Note that this is a raw string literal, you must include the leading 'r'.)
        TNFrI�\nrn)rez(FATAL)r�� r��^zFAIL: zFAIL-EXCEPTION: )r}r�r�r�rr��rstrip�
splitlinesrr&r%r�r�r rbrr#rIr�r;r�ru)r��testsr�comment�fullDump�printResults�failureTests�
allResults�comments�successrxr@�resultr�r�r}ryryrz�runTests�sNW




$


zParserElement.runTests)F)F)T)T)TT)TT)r)F)N)T)F)T)TrpTTF)Or�r�r�r�r�r�staticmethodr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rr
rrrrrr�rrrr �_MAX_INTr)r�r-r�r-r9r:r;rDrErFrGrHrIrJrKrLrMrNrPrQrRrSrWrYr�r�rrZr\rcrgrhrkrlrmr&r�
__classcell__ryryrfrzr&Os�




&




G

"
2G+D
			

)

cs eZdZdZ�fdd�Z�ZS)r.zT
    Abstract C{ParserElement} subclass, for defining atomic matching patterns.
    cstt|�jdd�dS�NF�r�)rer.r�r�rfryrzr�@	szToken.__init__�r�r�r�r�r�r�ryryrfrzr.<	scs eZdZdZ�fdd�Z�ZS)rz,
    An empty token, will always match.
    cs$tt|���d|_d|_d|_dS)NrTF)rerr�r�r�r�r�rfryrzr�H	szEmpty.__init__r�ryryrfrzrD	scs*eZdZdZ�fdd�Zddd�Z�ZS)rz(
    A token that will never match.
    cs*tt|���d|_d|_d|_d|_dS)NrTFzUnmatchable token)rerr�r�r�r�r�r�rfryrzr�S	s
zNoMatch.__init__TcCst|||j|��dSr�)r!r�r�ryryrzr�Z	szNoMatch.parseImpl)T�r�r�r�r�r�r�r�ryryrfrzrO	scs*eZdZdZ�fdd�Zddd�Z�ZS)ra�
    Token to exactly match a specified string.
    
    Example::
        Literal('blah').parseString('blah')  # -> ['blah']
        Literal('blah').parseString('blahfooblah')  # -> ['blah']
        Literal('blah').parseString('bla')  # -> Exception: Expected "blah"
    
    For case-insensitive matching, use L{CaselessLiteral}.
    
    For keyword matching (force word break before and after the matched string),
    use L{Keyword} or L{CaselessKeyword}.
    cs�tt|���||_t|�|_z|d|_Wn*tk
rVtj	dt
dd�t|_YnXdt
|j�|_d|j|_d|_d|_dS)Nrz2null string passed to Literal; use Empty() insteadrsr3�"%s"r�F)rerr��matchr��matchLen�firstMatchCharr�r5r6r7rr�r�r�r�r�r��r��matchStringrfryrzr�l	s
�zLiteral.__init__TcCsJ|||jkr6|jdks&|�|j|�r6||j|jfSt|||j|��dSr�)r�r��
startswithr�r!r�r�ryryrzr�	s��zLiteral.parseImpl)Tr�ryryrfrzr^	s
csLeZdZdZedZd�fdd�	Zddd	�Z�fd
d�Ze	dd
��Z
�ZS)ra\
    Token to exactly match a specified string as a keyword, that is, it must be
    immediately followed by a non-keyword character.  Compare with C{L{Literal}}:
     - C{Literal("if")} will match the leading C{'if'} in C{'ifAndOnlyIf'}.
     - C{Keyword("if")} will not; it will only match the leading C{'if'} in C{'if x=1'}, or C{'if(y==2)'}
    Accepts two optional constructor arguments in addition to the keyword string:
     - C{identChars} is a string of characters that would be valid identifier characters,
          defaulting to all alphanumerics + "_" and "$"
     - C{caseless} allows case-insensitive matching, default is C{False}.
       
    Example::
        Keyword("start").parseString("start")  # -> ['start']
        Keyword("start").parseString("starting")  # -> Exception

    For case-insensitive matching, use L{CaselessKeyword}.
    �_$NFcs�tt|���|dkrtj}||_t|�|_z|d|_Wn$tk
r^t	j
dtdd�YnXd|j|_d|j|_
d|_d|_||_|r�|��|_|��}t|�|_dS)Nrz2null string passed to Keyword; use Empty() insteadrsr3r�r�F)rerr��DEFAULT_KEYWORD_CHARSr�r�r�r�r�r5r6r7r�r�r�r��caseless�upper�
caselessmatchr��
identChars)r�r�r�r�rfryrzr��	s*
�
zKeyword.__init__TcCs|jr|||||j���|jkr�|t|�|jksL|||j��|jkr�|dksj||d��|jkr�||j|jfSnv|||jkr�|jdks�|�|j|�r�|t|�|jks�|||j|jkr�|dks�||d|jkr�||j|jfSt	|||j
|��dSr�)r�r�r�r�r�r�r�r�r�r!r�r�ryryrzr��	s4����������zKeyword.parseImplcstt|���}tj|_|Sr�)rerr�r�r�)r�r�rfryrzr��	szKeyword.copycCs
|t_dS)z,Overrides the default Keyword chars
        N)rr�r�ryryrz�setDefaultKeywordChars�	szKeyword.setDefaultKeywordChars)NF)T)r�r�r�r�r5r�r�r�r�r�r�r�ryryrfrzr�	s
cs*eZdZdZ�fdd�Zddd�Z�ZS)r
al
    Token to match a specified string, ignoring case of letters.
    Note: the matched results will always be in the case of the given
    match string, NOT the case of the input text.

    Example::
        OneOrMore(CaselessLiteral("CMD")).parseString("cmd CMD Cmd10") # -> ['CMD', 'CMD', 'CMD']
        
    (Contrast with example for L{CaselessKeyword}.)
    cs6tt|��|���||_d|j|_d|j|_dS)Nz'%s'r�)rer
r�r��returnStringr�r�r�rfryrzr��	szCaselessLiteral.__init__TcCs@||||j���|jkr,||j|jfSt|||j|��dSr�)r�r�r�r�r!r�r�ryryrzr��	szCaselessLiteral.parseImpl)Tr�ryryrfrzr
�	s
cs,eZdZdZd�fdd�	Zd	dd�Z�ZS)
r	z�
    Caseless version of L{Keyword}.

    Example::
        OneOrMore(CaselessKeyword("CMD")).parseString("cmd CMD Cmd10") # -> ['CMD', 'CMD']
        
    (Contrast with example for L{CaselessLiteral}.)
    Ncstt|�j||dd�dS)NT�r�)rer	r�)r�r�r�rfryrzr��	szCaselessKeyword.__init__TcCsj||||j���|jkrV|t|�|jksF|||j��|jkrV||j|jfSt|||j|��dSr�)r�r�r�r�r�r�r!r�r�ryryrzr��	s��zCaselessKeyword.parseImpl)N)Tr�ryryrfrzr	�	scs,eZdZdZd�fdd�	Zd	dd�Z�ZS)
rnax
    A variation on L{Literal} which matches "close" matches, that is, 
    strings with at most 'n' mismatching characters. C{CloseMatch} takes parameters:
     - C{match_string} - string to be matched
     - C{maxMismatches} - (C{default=1}) maximum number of mismatches allowed to count as a match
    
    The results from a successful parse will contain the matched text from the input string and the following named results:
     - C{mismatches} - a list of the positions within the match_string where mismatches were found
     - C{original} - the original match_string used to compare against the input string
    
    If C{mismatches} is an empty list, then the match was an exact match.
    
    Example::
        patt = CloseMatch("ATCATCGAATGGA")
        patt.parseString("ATCATCGAAXGGA") # -> (['ATCATCGAAXGGA'], {'mismatches': [[9]], 'original': ['ATCATCGAATGGA']})
        patt.parseString("ATCAXCGAAXGGA") # -> Exception: Expected 'ATCATCGAATGGA' (with up to 1 mismatches) (at char 0), (line:1, col:1)

        # exact match
        patt.parseString("ATCATCGAATGGA") # -> (['ATCATCGAATGGA'], {'mismatches': [[]], 'original': ['ATCATCGAATGGA']})

        # close match allowing up to 2 mismatches
        patt = CloseMatch("ATCATCGAATGGA", maxMismatches=2)
        patt.parseString("ATCAXCGAAXGGA") # -> (['ATCAXCGAAXGGA'], {'mismatches': [[4, 9]], 'original': ['ATCATCGAATGGA']})
    r�csBtt|���||_||_||_d|j|jf|_d|_d|_dS)Nz&Expected %r (with up to %d mismatches)F)	rernr�r��match_string�
maxMismatchesr�r�r�)r�r�r�rfryrzr�

szCloseMatch.__init__TcCs�|}t|�}|t|j�}||kr�|j}d}g}	|j}
tt|||�|j��D]2\}}|\}}
||
krN|	�|�t|	�|
krNq�qN|d}t|||�g�}|j|d<|	|d<||fSt|||j|��dS)Nrr��original�
mismatches)	r�r�r�r�r�r%r$r!r�)r�rvr�r��startr��maxlocr��match_stringlocr�r��s_m�src�mat�resultsryryrzr�
s( 

zCloseMatch.parseImpl)r�)Tr�ryryrfrzrn�	s	cs8eZdZdZd
�fdd�	Zdd	d
�Z�fdd�Z�ZS)r1a	
    Token for matching words composed of allowed character sets.
    Defined with string containing all allowed initial characters,
    an optional string containing allowed body characters (if omitted,
    defaults to the initial character set), and an optional minimum,
    maximum, and/or exact length.  The default value for C{min} is 1 (a
    minimum value < 1 is not valid); the default values for C{max} and C{exact}
    are 0, meaning no maximum or exact length restriction. An optional
    C{excludeChars} parameter can list characters that might be found in 
    the input C{bodyChars} string; useful to define a word of all printables
    except for one or two characters, for instance.
    
    L{srange} is useful for defining custom character set strings for defining 
    C{Word} expressions, using range notation from regular expression character sets.
    
    A common mistake is to use C{Word} to match a specific literal string, as in 
    C{Word("Address")}. Remember that C{Word} uses the string argument to define
    I{sets} of matchable characters. This expression would match "Add", "AAA",
    "dAred", or any other word made up of the characters 'A', 'd', 'r', 'e', and 's'.
    To match an exact literal string, use L{Literal} or L{Keyword}.

    pyparsing includes helper strings for building Words:
     - L{alphas}
     - L{nums}
     - L{alphanums}
     - L{hexnums}
     - L{alphas8bit} (alphabetic characters in ASCII range 128-255 - accented, tilded, umlauted, etc.)
     - L{punc8bit} (non-alphabetic characters in ASCII range 128-255 - currency, symbols, superscripts, diacriticals, etc.)
     - L{printables} (any non-whitespace character)

    Example::
        # a word composed of digits
        integer = Word(nums) # equivalent to Word("0123456789") or Word(srange("0-9"))
        
        # a word with a leading capital, and zero or more lowercase
        capital_word = Word(alphas.upper(), alphas.lower())

        # hostnames are alphanumeric, with leading alpha, and '-'
        hostname = Word(alphas, alphanums+'-')
        
        # roman numeral (not a strict parser, accepts invalid mix of characters)
        roman = Word("IVXLCDM")
        
        # any string of non-whitespace characters, except for ','
        csv_value = Word(printables, excludeChars=",")
    Nr�rFcs�tt|����rFd��fdd�|D��}|rFd��fdd�|D��}||_t|�|_|rl||_t|�|_n||_t|�|_|dk|_	|dkr�t
d��||_|dkr�||_nt
|_|dkr�||_||_t|�|_d|j|_d	|_||_d
|j|jk�r�|dk�r�|dk�r�|dk�r�|j|jk�r8dt|j�|_nHt|j�dk�rfdt�|j�t|j�f|_nd
t|j�t|j�f|_|j�r�d|jd|_zt�|j�|_Wntk
�r�d|_YnXdS)Nr�c3s|]}|�kr|VqdSr�ryr���excludeCharsryrzr�`
sz Word.__init__.<locals>.<genexpr>c3s|]}|�kr|VqdSr�ryr�r�ryrzr�b
srr�zZcannot specify a minimum length < 1; use Optional(Word()) if zero-length word is permittedr�Frrz[%s]+z%s[%s]*z	[%s][%s]*z\b)rer1r�r��
initCharsOrigr��	initChars�
bodyCharsOrig�	bodyChars�maxSpecifiedrA�minLen�maxLenr�r�r�r�r��	asKeyword�_escapeRegexRangeChars�reStringr�r��escape�compiler�)r�r�r��min�max�exactr�r�rfr�rzr�]
s\



0
����z
Word.__init__Tc
Cs>|jr<|j�||�}|s(t|||j|��|��}||��fS|||jkrZt|||j|��|}|d7}t|�}|j}||j	}t
||�}||kr�|||kr�|d7}q�d}	|||jkr�d}	|jr�||kr�|||kr�d}	|j
�r|dkr�||d|k�s||k�r|||k�rd}	|	�r.t|||j|��||||�fS)Nr�FTr)r�r�r!r��end�groupr�r�r�r�r�r�r�r�)
r�rvr�r�r~r�r��	bodycharsr��throwExceptionryryrzr��
s6


2zWord.parseImplcsvztt|���WStk
r$YnX|jdkrpdd�}|j|jkr`d||j�||j�f|_nd||j�|_|jS)NcSs$t|�dkr|dd�dS|SdS)N��...r��r�ryryrz�
charsAsStr�
sz Word.__str__.<locals>.charsAsStrz	W:(%s,%s)zW:(%s))rer1r�r�r�r�r�)r�r�rfryrzr��
s
zWord.__str__)Nr�rrFN)T�r�r�r�r�r�r�r�r�ryryrfrzr1.
s.6
#csFeZdZdZee�d��Zd�fdd�	Zddd�Z	�fd	d
�Z
�ZS)
r)a�
    Token for matching strings that match a given regular expression.
    Defined with string specifying the regular expression in a form recognized by the inbuilt Python re module.
    If the given regex contains named groups (defined using C{(?P<name>...)}), these will be preserved as 
    named parse results.

    Example::
        realnum = Regex(r"[+-]?\d+\.\d*")
        date = Regex(r'(?P<year>\d{4})-(?P<month>\d\d?)-(?P<day>\d\d?)')
        # ref: http://stackoverflow.com/questions/267399/how-do-you-match-only-valid-roman-numerals-with-a-regular-expression
        roman = Regex(r"M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})")
    z[A-Z]rcs�tt|���t|t�r�|s,tjdtdd�||_||_	zt
�|j|j	�|_
|j|_Wq�t
jk
r�tjd|tdd��Yq�Xn2t|tj�r�||_
t|�|_|_||_	ntd��t|�|_d|j|_d|_d|_d	S)
z�The parameters C{pattern} and C{flags} are passed to the C{re.compile()} function as-is. See the Python C{re} module for an explanation of the acceptable patterns and flags.z0null string passed to Regex; use Empty() insteadrsr3�$invalid pattern (%s) passed to RegexzCRegex may only be constructed with a string or a compiled RE objectr�FTN)rer)r�r}r�r5r6r7�pattern�flagsr�r�r��
sre_constants�error�compiledREtyperrAr�r�r�r�r�)r�r�r�rfryrzr��
s:
�
�
�
zRegex.__init__TcCs`|j�||�}|s"t|||j|��|��}|��}t|���}|rX|D]}||||<qF||fSr�)r�r�r!r�r��	groupdictr$r�)r�rvr�r�r~�dr�r�ryryrzr��
szRegex.parseImplcsFztt|���WStk
r$YnX|jdkr@dt|j�|_|jS)NzRe:(%s))rer)r�r�r�r�r�r�rfryrzr�
s
z
Regex.__str__)r)T)r�r�r�r�r�r�r�r�r�r�r�r�ryryrfrzr)�
s
"

cs8eZdZdZd�fdd�	Zddd�Z�fd	d
�Z�ZS)
r'a�
    Token for matching strings that are delimited by quoting characters.
    
    Defined with the following parameters:
        - quoteChar - string of one or more characters defining the quote delimiting string
        - escChar - character to escape quotes, typically backslash (default=C{None})
        - escQuote - special quote sequence to escape an embedded quote string (such as SQL's "" to escape an embedded ") (default=C{None})
        - multiline - boolean indicating whether quotes can span multiple lines (default=C{False})
        - unquoteResults - boolean indicating whether the matched text should be unquoted (default=C{True})
        - endQuoteChar - string of one or more characters defining the end of the quote delimited string (default=C{None} => same as quoteChar)
        - convertWhitespaceEscapes - convert escaped whitespace (C{'\t'}, C{'\n'}, etc.) to actual whitespace (default=C{True})

    Example::
        qs = QuotedString('"')
        print(qs.searchString('lsjdf "This is the quote" sldjf'))
        complex_qs = QuotedString('{{', endQuoteChar='}}')
        print(complex_qs.searchString('lsjdf {{This is the "quote"}} sldjf'))
        sql_qs = QuotedString('"', escQuote='""')
        print(sql_qs.searchString('lsjdf "This is the quote with ""embedded"" quotes" sldjf'))
    prints::
        [['This is the quote']]
        [['This is the "quote"']]
        [['This is the quote with "embedded" quotes']]
    NFTc
sNtt����|��}|s0tjdtdd�t��|dkr>|}n"|��}|s`tjdtdd�t��|�_t	|��_
|d�_|�_t	|��_
|�_|�_|�_|�_|r�tjtjB�_dt��j�t�jd�|dk	r�t|�p�df�_n<d�_dt��j�t�jd�|dk	�rt|��pdf�_t	�j�d	k�rp�jd
d��fdd
�tt	�j�d	dd�D��d7_|�r��jdt�|�7_|�r��jdt�|�7_t��j�d�_�jdt��j�7_zt��j�j��_�j�_Wn0tjk
�r&tjd�jtdd��YnXt ���_!d�j!�_"d�_#d�_$dS)Nz$quoteChar cannot be the empty stringrsr3z'endQuoteChar cannot be the empty stringrz%s(?:[^%s%s]r�z%s(?:[^%s\n\r%s]r�z|(?:z)|(?:c3s4|],}dt��jd|��t�j|�fVqdS)z%s[^%s]N)r�r��endQuoteCharr�r<r�ryrzr�Xs��z(QuotedString.__init__.<locals>.<genexpr>rt�)z|(?:%s)z|(?:%s.)z(.)z)*%sr�r�FT)%rer'r�r�r5r6r7�SyntaxError�	quoteCharr��quoteCharLen�firstQuoteCharr��endQuoteCharLen�escChar�escQuote�unquoteResults�convertWhitespaceEscapesr��	MULTILINE�DOTALLr�r�r�r�r�r��escCharReplacePatternr�r�r�r�r�r�r�r�r�)r�r�r�r��	multiliner�r�r�rfr�rzr�/s|



��
������
zQuotedString.__init__c	Cs�|||jkr|j�||�pd}|s4t|||j|��|��}|��}|jr�||j|j	�}t
|t�r�d|kr�|jr�ddddd�}|�
�D]\}}|�||�}q�|jr�t�|jd|�}|jr�|�|j|j�}||fS)N�\�	rI��
)�\trqz\fz\rz\g<1>)r�r�r�r!r�r�r�r�r�r�r}r�r�r�r�r�r�r�r�r�)	r�rvr�r�r~r��ws_map�wslit�wscharryryrzr�ps* 
�zQuotedString.parseImplcsHztt|���WStk
r$YnX|jdkrBd|j|jf|_|jS)Nz.quoted string, starting with %s ending with %s)rer'r�r�r�r�r�r�rfryrzr��s
zQuotedString.__str__)NNFTNT)Tr�ryryrfrzr'sA
#cs8eZdZdZd�fdd�	Zddd�Z�fd	d
�Z�ZS)
ra�
    Token for matching words composed of characters I{not} in a given set (will
    include whitespace in matched characters if not listed in the provided exclusion set - see example).
    Defined with string containing all disallowed characters, and an optional
    minimum, maximum, and/or exact length.  The default value for C{min} is 1 (a
    minimum value < 1 is not valid); the default values for C{max} and C{exact}
    are 0, meaning no maximum or exact length restriction.

    Example::
        # define a comma-separated-value as anything that is not a ','
        csv_value = CharsNotIn(',')
        print(delimitedList(csv_value).parseString("dkls,lsdkjf,s12 34,@!#,213"))
    prints::
        ['dkls', 'lsdkjf', 's12 34', '@!#', '213']
    r�rcs�tt|���d|_||_|dkr*td��||_|dkr@||_nt|_|dkrZ||_||_t	|�|_
d|j
|_|jdk|_d|_
dS)NFr�zfcannot specify a minimum length < 1; use Optional(CharsNotIn()) if zero-length char group is permittedrr�)rerr�r��notCharsrAr�r�r�r�r�r�r�r�)r�r�r�r�r�rfryrzr��s 
zCharsNotIn.__init__TcCs�|||jkrt|||j|��|}|d7}|j}t||jt|��}||krb|||krb|d7}qD|||jkr�t|||j|��||||�fSr�)r�r!r�r�r�r�r�)r�rvr�r�r��notchars�maxlenryryrzr��s
�
zCharsNotIn.parseImplcsfztt|���WStk
r$YnX|jdkr`t|j�dkrTd|jdd�|_nd|j|_|jS)Nr�z
!W:(%s...)z!W:(%s))rerr�r�r�r�r�r�rfryrzr��s
zCharsNotIn.__str__)r�rr)Tr�ryryrfrzr�s
cs<eZdZdZdddddd�Zd�fdd�	Zddd�Z�ZS)r0a�
    Special matching class for matching whitespace.  Normally, whitespace is ignored
    by pyparsing grammars.  This class is included when some whitespace structures
    are significant.  Define with a string containing the whitespace characters to be
    matched; default is C{" \t\r\n"}.  Also takes optional C{min}, C{max}, and C{exact} arguments,
    as defined for the C{L{Word}} class.
    z<SPC>z<TAB>z<LF>z<CR>z<FF>)rrr�rIr�r�� 	
r�rcs�tt����|�_��d��fdd��jD���d�dd��jD���_d�_d�j�_	|�_
|dkrt|�_nt�_|dkr�|�_|�_
dS)Nr�c3s|]}|�jkr|VqdSr�)�
matchWhiter�r�ryrzr��s
z!White.__init__.<locals>.<genexpr>css|]}tj|VqdSr�)r0�	whiteStrsr�ryryrzr��sTr�r)
rer0r�r�rQr�r�r�r�r�r�r�r�)r��wsr�r�r�rfr�rzr��s zWhite.__init__TcCs�|||jkrt|||j|��|}|d7}||j}t|t|��}||krb|||jkrb|d7}qB|||jkr�t|||j|��||||�fSr�)r�r!r�r�r�r�r�)r�rvr�r�r�r�ryryrzr�	s

zWhite.parseImpl)r�r�rr)T)r�r�r�r�r�r�r�r�ryryrfrzr0�s�cseZdZ�fdd�Z�ZS)�_PositionTokencs(tt|���|jj|_d|_d|_dSr�)rer�r�r�r�r�r�r�r�rfryrzr�s
z_PositionToken.__init__�r�r�r�r�r�ryryrfrzr�sr�cs2eZdZdZ�fdd�Zdd�Zd	dd�Z�ZS)
rzb
    Token to advance to a specific column of input text; useful for tabular report scraping.
    cstt|���||_dSr�)rerr�r;)r��colnorfryrzr�$szGoToColumn.__init__cCs\t||�|jkrXt|�}|jr*|�||�}||krX||��rXt||�|jkrX|d7}q*|Sr�)r;r�r�r��isspace)r�rvr�r�ryryrzr�(s$
zGoToColumn.preParseTcCsDt||�}||jkr"t||d|��||j|}|||�}||fS)NzText not in expected column�r;r!)r�rvr�r��thiscol�newlocr�ryryrzr�1s

zGoToColumn.parseImpl)T)r�r�r�r�r�r�r�r�ryryrfrzr s	cs*eZdZdZ�fdd�Zddd�Z�ZS)ra�
    Matches if current position is at the beginning of a line within the parse string
    
    Example::
    
        test = '''        AAA this line
        AAA and this line
          AAA but not this one
        B AAA and definitely not this one
        '''

        for t in (LineStart() + 'AAA' + restOfLine).searchString(test):
            print(t)
    
    Prints::
        ['AAA', ' this line']
        ['AAA', ' and this line']    

    cstt|���d|_dS)NzExpected start of line)rerr�r�r�rfryrzr�OszLineStart.__init__TcCs*t||�dkr|gfSt|||j|��dSr�)r;r!r�r�ryryrzr�SszLineStart.parseImpl)Tr�ryryrfrzr:scs*eZdZdZ�fdd�Zddd�Z�ZS)rzU
    Matches if current position is at the end of a line within the parse string
    cs,tt|���|�tj�dd��d|_dS)NrIr�zExpected end of line)rerr�rQr&r�r�r�r�rfryrzr�\szLineEnd.__init__TcCsb|t|�kr6||dkr$|ddfSt|||j|��n(|t|�krN|dgfSt|||j|��dS)NrIr��r�r!r�r�ryryrzr�aszLineEnd.parseImpl)Tr�ryryrfrzrXscs*eZdZdZ�fdd�Zddd�Z�ZS)r,zM
    Matches if current position is at the beginning of the parse string
    cstt|���d|_dS)NzExpected start of text)rer,r�r�r�rfryrzr�pszStringStart.__init__TcCs0|dkr(||�|d�kr(t|||j|��|gfSr�)r�r!r�r�ryryrzr�tszStringStart.parseImpl)Tr�ryryrfrzr,lscs*eZdZdZ�fdd�Zddd�Z�ZS)r+zG
    Matches if current position is at the end of the parse string
    cstt|���d|_dS)NzExpected end of text)rer+r�r�r�rfryrzr�szStringEnd.__init__TcCs^|t|�krt|||j|��n<|t|�kr6|dgfS|t|�krJ|gfSt|||j|��dSr�r�r�ryryrzr��szStringEnd.parseImpl)Tr�ryryrfrzr+{scs.eZdZdZef�fdd�	Zddd�Z�ZS)r3ap
    Matches if the current position is at the beginning of a Word, and
    is not preceded by any character in a given set of C{wordChars}
    (default=C{printables}). To emulate the C{} behavior of regular expressions,
    use C{WordStart(alphanums)}. C{WordStart} will also match at the beginning of
    the string being parsed, or at the beginning of a line.
    cs"tt|���t|�|_d|_dS)NzNot at the start of a word)rer3r�r��	wordCharsr��r�r�rfryrzr��s
zWordStart.__init__TcCs@|dkr8||d|jks(|||jkr8t|||j|��|gfSr�)r�r!r�r�ryryrzr��s�zWordStart.parseImpl)T�r�r�r�r�rXr�r�r�ryryrfrzr3�scs.eZdZdZef�fdd�	Zddd�Z�ZS)r2aZ
    Matches if the current position is at the end of a Word, and
    is not followed by any character in a given set of C{wordChars}
    (default=C{printables}). To emulate the C{} behavior of regular expressions,
    use C{WordEnd(alphanums)}. C{WordEnd} will also match at the end of
    the string being parsed, or at the end of a line.
    cs(tt|���t|�|_d|_d|_dS)NFzNot at the end of a word)rer2r�r�r�r�r�r�rfryrzr��s
zWordEnd.__init__TcCsPt|�}|dkrH||krH|||jks8||d|jkrHt|||j|��|gfSr�)r�r�r!r�)r�rvr�r�r�ryryrzr��s�zWordEnd.parseImpl)Tr�ryryrfrzr2�scs�eZdZdZd�fdd�	Zdd�Zdd�Zd	d
�Z�fdd�Z�fd
d�Z	�fdd�Z
d�fdd�	Zgfdd�Z�fdd�Z
�ZS)r"z^
    Abstract subclass of ParserElement, for combining and post-processing parsed tokens.
    Fcs�tt|��|�t|t�r"t|�}t|t�r<t�|�g|_	nht|t
�rxt|�}tdd�|D��rlttj|�}t|�|_	n,zt|�|_	Wnt
k
r�|g|_	YnXd|_dS)Ncss|]}t|t�VqdSr�)r}r�)r�rwryryrzr��sz+ParseExpression.__init__.<locals>.<genexpr>F)rer"r�r}r�r�r�r&r��exprsr�allr�r�r��r�r�r�rfryrzr��s


zParseExpression.__init__cCs
|j|Sr�)r�r�ryryrzr��szParseExpression.__getitem__cCs|j�|�d|_|Sr�)r�r%r�r8ryryrzr%�szParseExpression.appendcCs0d|_dd�|jD�|_|jD]}|��q|S)z~Extends C{leaveWhitespace} defined in base class, and also invokes C{leaveWhitespace} on
           all contained expressions.FcSsg|]}|���qSryr+�r�r�ryryrzr��sz3ParseExpression.leaveWhitespace.<locals>.<listcomp>)r�r�rP)r�r�ryryrzrP�s


zParseExpression.leaveWhitespacecsrt|t�rB||jkrntt|��|�|jD]}|�|jd�q*n,tt|��|�|jD]}|�|jd�qX|Sr
)r}r-r�rer"rSr�)r�r,r�rfryrzrS�s



zParseExpression.ignorecsNztt|���WStk
r$YnX|jdkrHd|jjt|j�f|_|jS�Nz%s:(%s))	rer"r�r�r�r�r�r�r�r�rfryrzr��s
zParseExpression.__str__cs*tt|���|jD]}|��qt|j�dk�r|jd}t||j�r�|js�|jdkr�|j	s�|jdd�|jdg|_d|_
|j|jO_|j|jO_|jd}t||j��r|j�s|jdk�r|j	�s|jdd�|jdd�|_d|_
|j|jO_|j|jO_dt
|�|_|S)Nrsrr�rtr�)rer"rr�r�r}r�r�r�r�r�r�r�r�r�)r�r�r,rfryrzr�s<


���
���zParseExpression.streamlinecstt|��||�}|Sr�)rer"r�)r�r�r�r�rfryrzr�
szParseExpression.setResultsNamecCs6|dd�|g}|jD]}|�|�q|�g�dSr�)r�r\rZ)r�r[�tmpr�ryryrzr\
s
zParseExpression.validatecs$tt|���}dd�|jD�|_|S)NcSsg|]}|���qSryr+r�ryryrzr�%
sz(ParseExpression.copy.<locals>.<listcomp>)rer"r�r�rHrfryrzr�#
szParseExpression.copy)F)F)r�r�r�r�r�r�r%rPrSr�rr�r\r�r�ryryrfrzr"�s	
"csTeZdZdZGdd�de�Zd�fdd�	Zddd�Zd	d
�Zdd�Z	d
d�Z
�ZS)ra

    Requires all given C{ParseExpression}s to be found in the given order.
    Expressions may be separated by whitespace.
    May be constructed using the C{'+'} operator.
    May also be constructed using the C{'-'} operator, which will suppress backtracking.

    Example::
        integer = Word(nums)
        name_expr = OneOrMore(Word(alphas))

        expr = And([integer("id"),name_expr("name"),integer("age")])
        # more easily written as:
        expr = integer("id") + name_expr("name") + integer("age")
    cseZdZ�fdd�Z�ZS)zAnd._ErrorStopcs&ttj|�j||�d|_|��dS)N�-)rerr9r�r�rPrhrfryrzr�9
szAnd._ErrorStop.__init__r�ryryrfrzr98
sr9TcsRtt|��||�tdd�|jD��|_|�|jdj�|jdj|_d|_	dS)Ncss|]}|jVqdSr��r�r�ryryrzr�@
szAnd.__init__.<locals>.<genexpr>rT)
rerr�r�r�r�rQr�r�r�r�rfryrzr�>
s
zAnd.__init__c	Cs�|jdj|||dd�\}}d}|jdd�D]�}t|tj�rDd}q.|r�z|�|||�\}}Wq�tk
rt�Yq�tk
r�}zd|_t�|��W5d}~XYq�t	k
r�t|t
|�|j|��Yq�Xn|�|||�\}}|s�|��r.||7}q.||fS)NrFr!r�T)
r�r�r}rr9r%r�
__traceback__r�r�r�r�r)	r�rvr�r��
resultlist�	errorStopr��
exprtokensr�ryryrzr�E
s(
z
And.parseImplcCst|t�rt�|�}|�|�Sr��r}r�r&r�r%r8ryryrzr7^
s

zAnd.__iadd__cCs6|dd�|g}|jD]}|�|�|jsq2qdSr�)r�rZr��r�r��subRecCheckListr�ryryrzrZc
s


zAnd.checkRecursioncCs@t|d�r|jS|jdkr:dd�dd�|jD��d|_|jS)Nr��{rrcss|]}t|�VqdSr�r�r�ryryrzr�o
szAnd.__str__.<locals>.<genexpr>�}�rr�r�r�r�r�ryryrzr�j
s


 zAnd.__str__)T)T)r�r�r�r�rr9r�r�r7rZr�r�ryryrfrzr(
s
csDeZdZdZd�fdd�	Zddd�Zdd	�Zd
d�Zdd
�Z�Z	S)ra�
    Requires that at least one C{ParseExpression} is found.
    If two expressions match, the expression that matches the longest string will be used.
    May be constructed using the C{'^'} operator.

    Example::
        # construct Or using '^' operator
        
        number = Word(nums) ^ Combine(Word(nums) + '.' + Word(nums))
        print(number.searchString("123 3.1416 789"))
    prints::
        [['123'], ['3.1416'], ['789']]
    Fcs:tt|��||�|jr0tdd�|jD��|_nd|_dS)Ncss|]}|jVqdSr�r�r�ryryrzr��
szOr.__init__.<locals>.<genexpr>T)rerr�r�rcr�r�rfryrzr��
szOr.__init__TcCsRd}d}g}|jD]�}z|�||�}Wnvtk
rb}	zd|	_|	j|krR|	}|	j}W5d}	~	XYqtk
r�t|�|kr�t|t|�|j|�}t|�}YqX|�||f�q|�r(|j	dd�d�|D]^\}
}z|�
|||�WStk
�r$}	z d|	_|	j|k�r|	}|	j}W5d}	~	XYq�Xq�|dk	�r@|j|_|�nt||d|��dS)NrtcSs
|dSr�ry)�xryryrzr{�
r|zOr.parseImpl.<locals>.<lambda>)r!� no defined alternatives to match)r�r�r!r�r�r�r�r�r%�sortr�r�)r�rvr�r��	maxExcLoc�maxExceptionr&r��loc2r��_ryryrzr��
s<


zOr.parseImplcCst|t�rt�|�}|�|�Sr�r�r8ryryrz�__ixor__�
s

zOr.__ixor__cCs@t|d�r|jS|jdkr:dd�dd�|jD��d|_|jS)Nr�r�z ^ css|]}t|�VqdSr�r�r�ryryrzr��
szOr.__str__.<locals>.<genexpr>r�r�r�ryryrzr��
s


 z
Or.__str__cCs,|dd�|g}|jD]}|�|�qdSr��r�rZr�ryryrzrZ�
s
zOr.checkRecursion)F)T)
r�r�r�r�r�r�rr�rZr�ryryrfrzrt
s

&	csDeZdZdZd�fdd�	Zddd�Zdd	�Zd
d�Zdd
�Z�Z	S)ra�
    Requires that at least one C{ParseExpression} is found.
    If two expressions match, the first one listed is the one that will match.
    May be constructed using the C{'|'} operator.

    Example::
        # construct MatchFirst using '|' operator
        
        # watch the order of expressions to match
        number = Word(nums) | Combine(Word(nums) + '.' + Word(nums))
        print(number.searchString("123 3.1416 789")) #  Fail! -> [['123'], ['3'], ['1416'], ['789']]

        # put more selective expression first
        number = Combine(Word(nums) + '.' + Word(nums)) | Word(nums)
        print(number.searchString("123 3.1416 789")) #  Better -> [['123'], ['3.1416'], ['789']]
    Fcs:tt|��||�|jr0tdd�|jD��|_nd|_dS)Ncss|]}|jVqdSr�r�r�ryryrzr��
sz&MatchFirst.__init__.<locals>.<genexpr>T)rerr�r�rcr�r�rfryrzr��
szMatchFirst.__init__Tc	Cs�d}d}|jD]�}z|�|||�}|WStk
r`}z|j|krP|}|j}W5d}~XYqtk
r�t|�|kr�t|t|�|j|�}t|�}YqXq|dk	r�|j|_|�nt||d|��dS)Nrtr)r�r�r!r�r�r�r�r�)	r�rvr�r�rrr�r�r�ryryrzr��
s$


zMatchFirst.parseImplcCst|t�rt�|�}|�|�Sr�r�r8ryryrz�__ior__�
s

zMatchFirst.__ior__cCs@t|d�r|jS|jdkr:dd�dd�|jD��d|_|jS)Nr�r�� | css|]}t|�VqdSr�r�r�ryryrzr��
sz%MatchFirst.__str__.<locals>.<genexpr>r�r�r�ryryrzr��
s


 zMatchFirst.__str__cCs,|dd�|g}|jD]}|�|�qdSr�rr�ryryrzrZs
zMatchFirst.checkRecursion)F)T)
r�r�r�r�r�r�rr�rZr�ryryrfrzr�
s
	cs<eZdZdZd�fdd�	Zddd�Zdd�Zd	d
�Z�ZS)
ram
    Requires all given C{ParseExpression}s to be found, but in any order.
    Expressions may be separated by whitespace.
    May be constructed using the C{'&'} operator.

    Example::
        color = oneOf("RED ORANGE YELLOW GREEN BLUE PURPLE BLACK WHITE BROWN")
        shape_type = oneOf("SQUARE CIRCLE TRIANGLE STAR HEXAGON OCTAGON")
        integer = Word(nums)
        shape_attr = "shape:" + shape_type("shape")
        posn_attr = "posn:" + Group(integer("x") + ',' + integer("y"))("posn")
        color_attr = "color:" + color("color")
        size_attr = "size:" + integer("size")

        # use Each (using operator '&') to accept attributes in any order 
        # (shape and posn are required, color and size are optional)
        shape_spec = shape_attr & posn_attr & Optional(color_attr) & Optional(size_attr)

        shape_spec.runTests('''
            shape: SQUARE color: BLACK posn: 100, 120
            shape: CIRCLE size: 50 color: BLUE posn: 50,80
            color:GREEN size:20 shape:TRIANGLE posn:20,40
            '''
            )
    prints::
        shape: SQUARE color: BLACK posn: 100, 120
        ['shape:', 'SQUARE', 'color:', 'BLACK', 'posn:', ['100', ',', '120']]
        - color: BLACK
        - posn: ['100', ',', '120']
          - x: 100
          - y: 120
        - shape: SQUARE


        shape: CIRCLE size: 50 color: BLUE posn: 50,80
        ['shape:', 'CIRCLE', 'size:', '50', 'color:', 'BLUE', 'posn:', ['50', ',', '80']]
        - color: BLUE
        - posn: ['50', ',', '80']
          - x: 50
          - y: 80
        - shape: CIRCLE
        - size: 50


        color: GREEN size: 20 shape: TRIANGLE posn: 20,40
        ['color:', 'GREEN', 'size:', '20', 'shape:', 'TRIANGLE', 'posn:', ['20', ',', '40']]
        - color: GREEN
        - posn: ['20', ',', '40']
          - x: 20
          - y: 40
        - shape: TRIANGLE
        - size: 20
    Tcs8tt|��||�tdd�|jD��|_d|_d|_dS)Ncss|]}|jVqdSr�r�r�ryryrzr�?sz Each.__init__.<locals>.<genexpr>T)rerr�r�r�r�r��initExprGroupsr�rfryrzr�=sz
Each.__init__c	s�|jr�tdd�|jD��|_dd�|jD�}dd�|jD�}|||_dd�|jD�|_dd�|jD�|_dd�|jD�|_|j|j7_d	|_|}|jdd�}|jdd��g}d
}	|	�rj|�|j|j}
g}|
D]v}z|�||�}Wn t	k
�r|�
|�Yq�X|�
|j�t|�|��||k�r@|�
|�q�|�kr܈�
|�q�t|�t|
�kr�d	}	q�|�r�d�dd�|D��}
t	||d
|
��|�fdd�|jD�7}g}|D]"}|�|||�\}}|�
|��q�t|tg��}||fS)Ncss&|]}t|t�rt|j�|fVqdSr�)r}rrjrwr�ryryrzr�Es
z!Each.parseImpl.<locals>.<genexpr>cSsg|]}t|t�r|j�qSry�r}rrwr�ryryrzr�Fs
z"Each.parseImpl.<locals>.<listcomp>cSs g|]}|jrt|t�s|�qSry)r�r}rr�ryryrzr�Gs
cSsg|]}t|t�r|j�qSry)r}r4rwr�ryryrzr�Is
cSsg|]}t|t�r|j�qSry)r}rrwr�ryryrzr�Js
cSs g|]}t|tttf�s|�qSry)r}rr4rr�ryryrzr�KsFTr;css|]}t|�VqdSr�r�r�ryryrzr�fsz*Missing one or more required elements (%s)cs$g|]}t|t�r|j�kr|�qSryrr���tmpOptryrzr�js

)r
r�r��opt1map�	optionals�multioptionals�
multirequired�requiredr�r!r%r�rj�remover�r�r��sumr$)r�rvr�r��opt1�opt2�tmpLoc�tmpReqd�
matchOrder�keepMatching�tmpExprs�failedr��missingr�r��finalResultsryrrzr�CsP

zEach.parseImplcCs@t|d�r|jS|jdkr:dd�dd�|jD��d|_|jS)Nr�r�z & css|]}t|�VqdSr�r�r�ryryrzr�yszEach.__str__.<locals>.<genexpr>r�r�r�ryryrzr�ts


 zEach.__str__cCs,|dd�|g}|jD]}|�|�qdSr�rr�ryryrzrZ}s
zEach.checkRecursion)T)T)	r�r�r�r�r�r�r�rZr�ryryrfrzrs
5
1	csleZdZdZd�fdd�	Zddd�Zdd	�Z�fd
d�Z�fdd
�Zdd�Z	gfdd�Z
�fdd�Z�ZS)r za
    Abstract subclass of C{ParserElement}, for combining and post-processing parsed tokens.
    Fcs�tt|��|�t|t�r@ttjt�r2t�|�}nt�t	|��}||_
d|_|dk	r�|j|_|j
|_
|�|j�|j|_|j|_|j|_|j�|j�dSr�)rer r�r}r��
issubclassr&r�r.rrwr�r�r�rQr�r�r�r�r�r'�r�rwr�rfryrzr��s
zParseElementEnhance.__init__TcCs2|jdk	r|jj|||dd�Std||j|��dS)NFr!r�)rwr�r!r�r�ryryrzr��s
zParseElementEnhance.parseImplcCs*d|_|j��|_|jdk	r&|j��|Sr)r�rwr�rPr�ryryrzrP�s


z#ParseElementEnhance.leaveWhitespacecsrt|t�rB||jkrntt|��|�|jdk	rn|j�|jd�n,tt|��|�|jdk	rn|j�|jd�|Sr
)r}r-r�rer rSrwr8rfryrzrS�s



zParseElementEnhance.ignorecs&tt|���|jdk	r"|j��|Sr�)rer rrwr�rfryrzr�s

zParseElementEnhance.streamlinecCsB||krt||g��|dd�|g}|jdk	r>|j�|�dSr�)r(rwrZ)r�r�r�ryryrzrZ�s

z"ParseElementEnhance.checkRecursioncCs6|dd�|g}|jdk	r(|j�|�|�g�dSr��rwr\rZ�r�r[r�ryryrzr\�s
zParseElementEnhance.validatecsXztt|���WStk
r$YnX|jdkrR|jdk	rRd|jjt|j�f|_|jSr�)	rer r�r�r�rwr�r�r�r�rfryrzr��szParseElementEnhance.__str__)F)T)
r�r�r�r�r�r�rPrSrrZr\r�r�ryryrfrzr �s
cs*eZdZdZ�fdd�Zddd�Z�ZS)ra�
    Lookahead matching of the given parse expression.  C{FollowedBy}
    does I{not} advance the parsing position within the input string, it only
    verifies that the specified parse expression matches at the current
    position.  C{FollowedBy} always returns a null token list.

    Example::
        # use FollowedBy to match a label only if it is followed by a ':'
        data_word = Word(alphas)
        label = data_word + FollowedBy(':')
        attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
        
        OneOrMore(attr_expr).parseString("shape: SQUARE color: BLACK posn: upper left").pprint()
    prints::
        [['shape', 'SQUARE'], ['color', 'BLACK'], ['posn', 'upper left']]
    cstt|��|�d|_dSr�)rerr�r��r�rwrfryrzr��szFollowedBy.__init__TcCs|j�||�|gfSr�)rwr�r�ryryrzr��szFollowedBy.parseImpl)Tr�ryryrfrzr�scs2eZdZdZ�fdd�Zd	dd�Zdd�Z�ZS)
ra�
    Lookahead to disallow matching with the given parse expression.  C{NotAny}
    does I{not} advance the parsing position within the input string, it only
    verifies that the specified parse expression does I{not} match at the current
    position.  Also, C{NotAny} does I{not} skip over leading whitespace. C{NotAny}
    always returns a null token list.  May be constructed using the '~' operator.

    Example::
        
    cs0tt|��|�d|_d|_dt|j�|_dS)NFTzFound unwanted token, )rerr�r�r�r�rwr�r#rfryrzr��szNotAny.__init__TcCs&|j�||�rt|||j|��|gfSr�)rwr�r!r�r�ryryrzr��szNotAny.parseImplcCs4t|d�r|jS|jdkr.dt|j�d|_|jS)Nr�z~{r��rr�r�r�rwr�ryryrzr�s


zNotAny.__str__)Tr�ryryrfrzr�s

cs(eZdZd�fdd�	Zddd�Z�ZS)	�_MultipleMatchNcsFtt|��|�d|_|}t|t�r.t�|�}|dk	r<|nd|_dSr�)	rer%r�r�r}r�r&r��	not_ender)r�rw�stopOn�enderrfryrzr�s

z_MultipleMatch.__init__Tc	Cs�|jj}|j}|jdk	}|r$|jj}|r2|||�||||dd�\}}zV|j}	|r`|||�|	rp|||�}
n|}
|||
|�\}}|s�|��rR||7}qRWnttfk
r�YnX||fS�NFr!)	rwr�r�r&r�r�rr!r�)r�rvr�r��self_expr_parse�self_skip_ignorables�check_ender�
try_not_enderr��hasIgnoreExprsr��	tmptokensryryrzr�s*



z_MultipleMatch.parseImpl)N)T)r�r�r�r�r�r�ryryrfrzr%
sr%c@seZdZdZdd�ZdS)ra�
    Repetition of one or more of the given expression.
    
    Parameters:
     - expr - expression that must match one or more times
     - stopOn - (default=C{None}) - expression for a terminating sentinel
          (only required if the sentinel would ordinarily match the repetition 
          expression)          

    Example::
        data_word = Word(alphas)
        label = data_word + FollowedBy(':')
        attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).setParseAction(' '.join))

        text = "shape: SQUARE posn: upper left color: BLACK"
        OneOrMore(attr_expr).parseString(text).pprint()  # Fail! read 'color' as data instead of next label -> [['shape', 'SQUARE color']]

        # use stopOn attribute for OneOrMore to avoid reading label string as part of the data
        attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
        OneOrMore(attr_expr).parseString(text).pprint() # Better -> [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']]
        
        # could also be written as
        (attr_expr * (1,)).parseString(text).pprint()
    cCs4t|d�r|jS|jdkr.dt|j�d|_|jS)Nr�r�z}...r$r�ryryrzr�Js


zOneOrMore.__str__N)r�r�r�r�r�ryryryrzr0scs8eZdZdZd
�fdd�	Zd�fdd�	Zdd	�Z�ZS)r4aw
    Optional repetition of zero or more of the given expression.
    
    Parameters:
     - expr - expression that must match zero or more times
     - stopOn - (default=C{None}) - expression for a terminating sentinel
          (only required if the sentinel would ordinarily match the repetition 
          expression)          

    Example: similar to L{OneOrMore}
    Ncstt|�j||d�d|_dS)N)r'T)rer4r�r�)r�rwr'rfryrzr�_szZeroOrMore.__init__Tc	s<ztt|��|||�WSttfk
r6|gfYSXdSr�)rer4r�r!r�r�rfryrzr�cszZeroOrMore.parseImplcCs4t|d�r|jS|jdkr.dt|j�d|_|jS)Nr�r:�]...r$r�ryryrzr�is


zZeroOrMore.__str__)N)Tr�ryryrfrzr4Ssc@s eZdZdd�ZeZdd�ZdS)�
_NullTokencCsdSrryr�ryryrzr	ssz_NullToken.__bool__cCsdSr�ryr�ryryrzr�vsz_NullToken.__str__N)r�r�r�r	rnr�ryryryrzr1rsr1cs6eZdZdZef�fdd�	Zd	dd�Zdd�Z�ZS)
raa
    Optional matching of the given expression.

    Parameters:
     - expr - expression that must match zero or more times
     - default (optional) - value to be returned if the optional expression is not found.

    Example::
        # US postal code can be a 5-digit zip, plus optional 4-digit qualifier
        zip = Combine(Word(nums, exact=5) + Optional('-' + Word(nums, exact=4)))
        zip.runTests('''
            # traditional ZIP code
            12345
            
            # ZIP+4 form
            12101-0001
            
            # invalid ZIP
            98765-
            ''')
    prints::
        # traditional ZIP code
        12345
        ['12345']

        # ZIP+4 form
        12101-0001
        ['12101-0001']

        # invalid ZIP
        98765-
             ^
        FAIL: Expected end of text (at char 5), (line:1, col:6)
    cs.tt|�j|dd�|jj|_||_d|_dS)NFr�T)rerr�rwr�r"r�)r�rwrrfryrzr��s
zOptional.__init__Tc	Cszz|jj|||dd�\}}WnTttfk
rp|jtk	rh|jjr^t|jg�}|j||jj<ql|jg}ng}YnX||fSr))rwr�r!r�r"�_optionalNotMatchedr�r$)r�rvr�r�r�ryryrzr��s


zOptional.parseImplcCs4t|d�r|jS|jdkr.dt|j�d|_|jS)Nr�r:r=r$r�ryryrzr��s


zOptional.__str__)T)	r�r�r�r�r2r�r�r�r�ryryrfrzrzs"
cs,eZdZdZd	�fdd�	Zd
dd�Z�ZS)r*a�	
    Token for skipping over all undefined text until the matched expression is found.

    Parameters:
     - expr - target expression marking the end of the data to be skipped
     - include - (default=C{False}) if True, the target expression is also parsed 
          (the skipped text and target expression are returned as a 2-element list).
     - ignore - (default=C{None}) used to define grammars (typically quoted strings and 
          comments) that might contain false matches to the target expression
     - failOn - (default=C{None}) define expressions that are not allowed to be 
          included in the skipped test; if found before the target expression is found, 
          the SkipTo is not a match

    Example::
        report = '''
            Outstanding Issues Report - 1 Jan 2000

               # | Severity | Description                               |  Days Open
            -----+----------+-------------------------------------------+-----------
             101 | Critical | Intermittent system crash                 |          6
              94 | Cosmetic | Spelling error on Login ('log|n')         |         14
              79 | Minor    | System slow when running too many reports |         47
            '''
        integer = Word(nums)
        SEP = Suppress('|')
        # use SkipTo to simply match everything up until the next SEP
        # - ignore quoted strings, so that a '|' character inside a quoted string does not match
        # - parse action will call token.strip() for each matched token, i.e., the description body
        string_data = SkipTo(SEP, ignore=quotedString)
        string_data.setParseAction(tokenMap(str.strip))
        ticket_expr = (integer("issue_num") + SEP 
                      + string_data("sev") + SEP 
                      + string_data("desc") + SEP 
                      + integer("days_open"))
        
        for tkt in ticket_expr.searchString(report):
            print tkt.dump()
    prints::
        ['101', 'Critical', 'Intermittent system crash', '6']
        - days_open: 6
        - desc: Intermittent system crash
        - issue_num: 101
        - sev: Critical
        ['94', 'Cosmetic', "Spelling error on Login ('log|n')", '14']
        - days_open: 14
        - desc: Spelling error on Login ('log|n')
        - issue_num: 94
        - sev: Cosmetic
        ['79', 'Minor', 'System slow when running too many reports', '47']
        - days_open: 47
        - desc: System slow when running too many reports
        - issue_num: 79
        - sev: Minor
    FNcs`tt|��|�||_d|_d|_||_d|_t|t	�rFt
�|�|_n||_dt
|j�|_dS)NTFzNo match found for )rer*r��
ignoreExprr�r��includeMatchr�r}r�r&r��failOnr�rwr�)r�r,�includerSr5rfryrzr��s
zSkipTo.__init__Tc	Cs&|}t|�}|j}|jj}|jdk	r,|jjnd}|jdk	rB|jjnd}	|}
|
|kr�|dk	rf|||
�rfq�|	dk	r�z|	||
�}
Wqntk
r�Yq�YqnXqnz|||
ddd�Wq�tt	fk
r�|
d7}
YqJXq�qJt|||j
|��|
}|||�}t|�}|j�r||||dd�\}}
||
7}||fS)NF)r�r�r�r!)
r�rwr�r5r�r3r�rr!r�r�r$r4)r�rvr�r�ryr�rw�
expr_parse�self_failOn_canParseNext�self_ignoreExpr_tryParse�tmploc�skiptext�
skipresultr�ryryrzr��s:
zSkipTo.parseImpl)FNN)Tr�ryryrfrzr*�s6
csbeZdZdZd�fdd�	Zdd�Zdd�Zd	d
�Zdd�Zgfd
d�Z	dd�Z
�fdd�Z�ZS)raK
    Forward declaration of an expression to be defined later -
    used for recursive grammars, such as algebraic infix notation.
    When the expression is known, it is assigned to the C{Forward} variable using the '<<' operator.

    Note: take care when assigning to C{Forward} not to overlook precedence of operators.
    Specifically, '|' has a lower precedence than '<<', so that::
        fwdExpr << a | b | c
    will actually be evaluated as::
        (fwdExpr << a) | b | c
    thereby leaving b and c out as parseable alternatives.  It is recommended that you
    explicitly group the values inserted into the C{Forward}::
        fwdExpr << (a | b | c)
    Converting to use the '<<=' operator instead will avoid this problem.

    See L{ParseResults.pprint} for an example of a recursive parser created using
    C{Forward}.
    Ncstt|�j|dd�dSr�)rerr�r8rfryrzr�@szForward.__init__cCsjt|t�rt�|�}||_d|_|jj|_|jj|_|�|jj	�|jj
|_
|jj|_|j�
|jj�|Sr�)r}r�r&r�rwr�r�r�rQr�r�r�r�r'r8ryryrz�
__lshift__Cs





zForward.__lshift__cCs||>Sr�ryr8ryryrz�__ilshift__PszForward.__ilshift__cCs
d|_|SrrOr�ryryrzrPSszForward.leaveWhitespacecCs$|js d|_|jdk	r |j��|Sr�)r�rwrr�ryryrzrWs


zForward.streamlinecCs>||kr0|dd�|g}|jdk	r0|j�|�|�g�dSr�r!r"ryryrzr\^s

zForward.validatecCsVt|d�r|jS|jjdSz|jdk	r4t|j�}nd}W5|j|_X|jjd|S)Nr�z: ...�Nonez: )rr�r�r��_revertClass�_ForwardNoRecurserwr�)r��	retStringryryrzr�es


zForward.__str__cs.|jdk	rtt|���St�}||K}|SdSr�)rwrerr�rHrfryrzr�vs

zForward.copy)N)
r�r�r�r�r�r=r>rPrr\r�r�r�ryryrfrzr-s
c@seZdZdd�ZdS)rAcCsdS)Nr�ryr�ryryrzr�sz_ForwardNoRecurse.__str__N)r�r�r�r�ryryryrzrA~srAcs"eZdZdZd�fdd�	Z�ZS)r/zQ
    Abstract subclass of C{ParseExpression}, for converting parsed results.
    Fcstt|��|�d|_dSr)rer/r�r�r rfryrzr��szTokenConverter.__init__)Fr�ryryrfrzr/�scs6eZdZdZd
�fdd�	Z�fdd�Zdd	�Z�ZS)ra�
    Converter to concatenate all matching tokens to a single string.
    By default, the matching patterns must also be contiguous in the input string;
    this can be disabled by specifying C{'adjacent=False'} in the constructor.

    Example::
        real = Word(nums) + '.' + Word(nums)
        print(real.parseString('3.1416')) # -> ['3', '.', '1416']
        # will also erroneously match the following
        print(real.parseString('3. 1416')) # -> ['3', '.', '1416']

        real = Combine(Word(nums) + '.' + Word(nums))
        print(real.parseString('3.1416')) # -> ['3.1416']
        # no match when there are internal spaces
        print(real.parseString('3. 1416')) # -> Exception: Expected W:(0123...)
    r�Tcs8tt|��|�|r|��||_d|_||_d|_dSr�)rerr�rP�adjacentr��
joinStringr�)r�rwrDrCrfryrzr��szCombine.__init__cs(|jrt�||�ntt|��|�|Sr�)rCr&rSrerr8rfryrzrS�szCombine.ignorecCsP|��}|dd�=|td�|�|j��g|jd�7}|jrH|��rH|gS|SdS)Nr�)r�)r�r$r�r>rDr�r�r)r�rvr�r��retToksryryrzr��s
"zCombine.postParse)r�T)r�r�r�r�r�rSr�r�ryryrfrzr�s
cs(eZdZdZ�fdd�Zdd�Z�ZS)ra�
    Converter to return the matched tokens as a list - useful for returning tokens of C{L{ZeroOrMore}} and C{L{OneOrMore}} expressions.

    Example::
        ident = Word(alphas)
        num = Word(nums)
        term = ident | num
        func = ident + Optional(delimitedList(term))
        print(func.parseString("fn a,b,100"))  # -> ['fn', 'a', 'b', '100']

        func = ident + Group(Optional(delimitedList(term)))
        print(func.parseString("fn a,b,100"))  # -> ['fn', ['a', 'b', '100']]
    cstt|��|�d|_dSr�)rerr�r�r#rfryrzr��szGroup.__init__cCs|gSr�ryr�ryryrzr��szGroup.postParse�r�r�r�r�r�r�r�ryryrfrzr�s
cs(eZdZdZ�fdd�Zdd�Z�ZS)r
aW
    Converter to return a repetitive expression as a list, but also as a dictionary.
    Each element can also be referenced using the first token in the expression as its key.
    Useful for tabular report scraping when the first column can be used as a item key.

    Example::
        data_word = Word(alphas)
        label = data_word + FollowedBy(':')
        attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).setParseAction(' '.join))

        text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
        attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
        
        # print attributes as plain groups
        print(OneOrMore(attr_expr).parseString(text).dump())
        
        # instead of OneOrMore(expr), parse using Dict(OneOrMore(Group(expr))) - Dict will auto-assign names
        result = Dict(OneOrMore(Group(attr_expr))).parseString(text)
        print(result.dump())
        
        # access named fields as dict entries, or output as dict
        print(result['shape'])        
        print(result.asDict())
    prints::
        ['shape', 'SQUARE', 'posn', 'upper left', 'color', 'light blue', 'texture', 'burlap']

        [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
        - color: light blue
        - posn: upper left
        - shape: SQUARE
        - texture: burlap
        SQUARE
        {'color': 'light blue', 'posn': 'upper left', 'texture': 'burlap', 'shape': 'SQUARE'}
    See more examples at L{ParseResults} of accessing fields by results name.
    cstt|��|�d|_dSr�)rer
r�r�r#rfryrzr��sz
Dict.__init__cCs�t|�D]�\}}t|�dkrq|d}t|t�r@t|d���}t|�dkr\td|�||<qt|�dkr�t|dt�s�t|d|�||<q|��}|d=t|�dks�t|t�r�|�	�r�t||�||<qt|d|�||<q|j
r�|gS|SdS)Nrr�r�rs)r�r�r}rvr�r�r�r$r�rr�)r�rvr�r�r��tok�ikey�	dictvalueryryrzr��s$
zDict.postParserFryryrfrzr
�s#c@s eZdZdZdd�Zdd�ZdS)r-aV
    Converter for ignoring the results of a parsed expression.

    Example::
        source = "a, b, c,d"
        wd = Word(alphas)
        wd_list1 = wd + ZeroOrMore(',' + wd)
        print(wd_list1.parseString(source))

        # often, delimiters that are useful during parsing are just in the
        # way afterward - use Suppress to keep them out of the parsed output
        wd_list2 = wd + ZeroOrMore(Suppress(',') + wd)
        print(wd_list2.parseString(source))
    prints::
        ['a', ',', 'b', ',', 'c', ',', 'd']
        ['a', 'b', 'c', 'd']
    (See also L{delimitedList}.)
    cCsgSr�ryr�ryryrzr�szSuppress.postParsecCs|Sr�ryr�ryryrzrN"szSuppress.suppressN)r�r�r�r�r�rNryryryrzr-sc@s(eZdZdZdd�Zdd�Zdd�ZdS)	rzI
    Wrapper for parse actions, to ensure they are only called once.
    cCst|�|_d|_dSr)r��callable�called)r��
methodCallryryrzr�*s
zOnlyOnce.__init__cCs.|js|�|||�}d|_|St||d��dS)NTr�)rKrJr!)r�r�r�rxr�ryryrzrM-s
zOnlyOnce.__call__cCs
d|_dSr)rKr�ryryrz�reset3szOnlyOnce.resetN)r�r�r�r�r�rMrMryryryrzr&scs:t����fdd�}z�j|_Wntk
r4YnX|S)at
    Decorator for debugging parse actions. 
    
    When the parse action is called, this decorator will print C{">> entering I{method-name}(line:I{current_source_line}, I{parse_location}, I{matched_tokens})".}
    When the parse action completes, the decorator will print C{"<<"} followed by the returned value, or any exception that the parse action raised.

    Example::
        wd = Word(alphas)

        @traceParseAction
        def remove_duplicate_chars(tokens):
            return ''.join(sorted(set(''.join(tokens))))

        wds = OneOrMore(wd).setParseAction(remove_duplicate_chars)
        print(wds.parseString("slkdjs sld sldd sdlf sdljf"))
    prints::
        >>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', 0, (['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {}))
        <<leaving remove_duplicate_chars (ret: 'dfjkls')
        ['dfjkls']
    c
s��j}|dd�\}}}t|�dkr8|djjd|}tj�d|t||�||f�z�|�}Wn8tk
r�}ztj�d||f��W5d}~XYnXtj�d||f�|S)Nr�rqr�.z">>entering %s(line: '%s', %d, %r)
z<<leaving %s (exception: %s)
z<<leaving %s (ret: %r)
)r�r�r�r��stderr�writerIr�)�paArgs�thisFuncr�r�rxr�r}�rbryrz�zLsztraceParseAction.<locals>.z)r�r�r�)rbrTryrSrzrd6s
�,FcCs`t|�dt|�dt|�d}|rBt|t||���|�S|tt|�|��|�SdS)a�
    Helper to define a delimited list of expressions - the delimiter defaults to ','.
    By default, the list elements and delimiters can have intervening whitespace, and
    comments, but this can be overridden by passing C{combine=True} in the constructor.
    If C{combine} is set to C{True}, the matching tokens are returned as a single token
    string, with the delimiters included; otherwise, the matching tokens are returned
    as a list of tokens, with the delimiters suppressed.

    Example::
        delimitedList(Word(alphas)).parseString("aa,bb,cc") # -> ['aa', 'bb', 'cc']
        delimitedList(Word(hexnums), delim=':', combine=True).parseString("AA:BB:CC:DD:EE") # -> ['AA:BB:CC:DD:EE']
    z [rrr0N)r�rr4r�r-)rw�delim�combine�dlNameryryrzrBbs
$csjt����fdd�}|dkr0tt��dd��}n|��}|�d�|j|dd�|��d	t��d
�S)a:
    Helper to define a counted list of expressions.
    This helper defines a pattern of the form::
        integer expr expr expr...
    where the leading integer tells how many expr expressions follow.
    The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed.
    
    If C{intExpr} is specified, it should be a pyparsing expression that produces an integer value.

    Example::
        countedArray(Word(alphas)).parseString('2 ab cd ef')  # -> ['ab', 'cd']

        # in this parser, the leading integer value is given in binary,
        # '10' indicating that 2 values are in the array
        binaryConstant = Word('01').setParseAction(lambda t: int(t[0], 2))
        countedArray(Word(alphas), intExpr=binaryConstant).parseString('10 ab cd ef')  # -> ['ab', 'cd']
    cs.|d}�|r tt�g|��p&tt�>gSr�)rrrE)r�r�rxr=��	arrayExprrwryrz�countFieldParseAction�s"z+countedArray.<locals>.countFieldParseActionNcSst|d�Sr�)rvrwryryrzr{�r|zcountedArray.<locals>.<lambda>�arrayLenT�r�z(len) r�)rr1rTr�r�r�r�r�)rw�intExprr[ryrYrzr>us
cCs6g}|D](}t|t�r&|�t|��q|�|�q|Sr�)r}r�r'r+r%)�Lr�r�ryryrzr+�s
r+cs6t���fdd�}|j|dd���dt|���S)a*
    Helper to define an expression that is indirectly defined from
    the tokens matched in a previous expression, that is, it looks
    for a 'repeat' of a previous expression.  For example::
        first = Word(nums)
        second = matchPreviousLiteral(first)
        matchExpr = first + ":" + second
    will match C{"1:1"}, but not C{"1:2"}.  Because this matches a
    previous literal, will also match the leading C{"1:1"} in C{"1:10"}.
    If this is not desired, use C{matchPreviousExpr}.
    Do I{not} use with packrat parsing enabled.
    csP|rBt|�dkr�|d>qLt|���}�tdd�|D��>n
�t�>dS)Nr�rcss|]}t|�VqdSr�)r�r��ttryryrzr��szDmatchPreviousLiteral.<locals>.copyTokenToRepeater.<locals>.<genexpr>)r�r+r�rr)r�r�rx�tflat��repryrz�copyTokenToRepeater�sz1matchPreviousLiteral.<locals>.copyTokenToRepeaterTr]�(prev) )rr�r�r�)rwreryrcrzrQ�s


csFt��|��}�|K��fdd�}|j|dd���dt|���S)aS
    Helper to define an expression that is indirectly defined from
    the tokens matched in a previous expression, that is, it looks
    for a 'repeat' of a previous expression.  For example::
        first = Word(nums)
        second = matchPreviousExpr(first)
        matchExpr = first + ":" + second
    will match C{"1:1"}, but not C{"1:2"}.  Because this matches by
    expressions, will I{not} match the leading C{"1:1"} in C{"1:10"};
    the expressions are evaluated first, and then compared, so
    C{"1"} is compared with C{"10"}.
    Do I{not} use with packrat parsing enabled.
    cs*t|�����fdd�}�j|dd�dS)Ncs$t|���}|�kr tddd��dS)Nr�r)r+r�r!)r�r�rx�theseTokens��matchTokensryrz�mustMatchTheseTokens�szLmatchPreviousExpr.<locals>.copyTokenToRepeater.<locals>.mustMatchTheseTokensTr])r+r�r�)r�r�rxrjrcrhrzre�sz.matchPreviousExpr.<locals>.copyTokenToRepeaterTr]rf)rr�r�r�r�)rw�e2reryrcrzrP�scCs:dD]}|�|t|�}q|�dd�}|�dd�}t|�S)Nz\^-]rIrqr�r�)r��_bslashr�)r�r�ryryrzr��s
r�Tc
s�|rdd�}dd�}t�ndd�}dd�}t�g}t|t�rF|��}n$t|t�rZt|�}ntjdt	dd�|stt
�Sd	}|t|�d
k�r||}t||d
d��D]R\}}	||	|�r�|||d
=qxq�|||	�r�|||d
=|�
||	�|	}qxq�|d
7}qx|�s�|�r�zlt|�td�|��k�rTtd
d�dd�|D����d�|��WStd�dd�|D����d�|��WSWn&tk
�r�tjdt	dd�YnXt�fdd�|D���d�|��S)a�
    Helper to quickly define a set of alternative Literals, and makes sure to do
    longest-first testing when there is a conflict, regardless of the input order,
    but returns a C{L{MatchFirst}} for best performance.

    Parameters:
     - strs - a string of space-delimited literals, or a collection of string literals
     - caseless - (default=C{False}) - treat all literals as caseless
     - useRegex - (default=C{True}) - as an optimization, will generate a Regex
          object; otherwise, will generate a C{MatchFirst} object (if C{caseless=True}, or
          if creating a C{Regex} raises an exception)

    Example::
        comp_oper = oneOf("< = > <= >= !=")
        var = Word(alphas)
        number = Word(nums)
        term = var | number
        comparison_expr = term + comp_oper + term
        print(comparison_expr.searchString("B = 12  AA=23 B<=AA AA>12"))
    prints::
        [['B', '=', '12'], ['AA', '=', '23'], ['B', '<=', 'AA'], ['AA', '>', '12']]
    cSs|��|��kSr�)r��r.�bryryrzr{�r|zoneOf.<locals>.<lambda>cSs|���|���Sr�)r�r�rmryryrzr{�r|cSs||kSr�ryrmryryrzr{�r|cSs
|�|�Sr�)r�rmryryrzr{�r|z6Invalid argument to oneOf, expected string or iterablersr3rr�Nr�z[%s]css|]}t|�VqdSr�)r��r��symryryrzr�szoneOf.<locals>.<genexpr>r	�|css|]}t�|�VqdSr�)r�r�roryryrzr�sz7Exception creating Regex for oneOf, building MatchFirstc3s|]}�|�VqdSr�ryro��parseElementClassryrzr�$s)r
rr}r�r�rr�r5r6r7rr�r�r#r�r)r�r�r)
�strsr��useRegex�isequal�masks�symbolsr��currr,ryrrrzrU�sT



�


**�cCsttt||���S)a�
    Helper to easily and clearly define a dictionary by specifying the respective patterns
    for the key and value.  Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens
    in the proper order.  The key pattern can include delimiting markers or punctuation,
    as long as they are suppressed, thereby leaving the significant key text.  The value
    pattern can include named results, so that the C{Dict} results can include named token
    fields.

    Example::
        text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
        attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
        print(OneOrMore(attr_expr).parseString(text).dump())
        
        attr_label = label
        attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)

        # similar to Dict, but simpler call format
        result = dictOf(attr_label, attr_value).parseString(text)
        print(result.dump())
        print(result['shape'])
        print(result.shape)  # object attribute access works too
        print(result.asDict())
    prints::
        [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
        - color: light blue
        - posn: upper left
        - shape: SQUARE
        - texture: burlap
        SQUARE
        SQUARE
        {'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'}
    )r
r4r)r!rryryrzrC&s!cCs^t��dd��}|��}d|_|d�||d�}|r@dd�}ndd�}|�|�|j|_|S)	a�
    Helper to return the original, untokenized text for a given expression.  Useful to
    restore the parsed fields of an HTML start tag into the raw tag text itself, or to
    revert separate tokens with intervening whitespace back to the original matching
    input text. By default, returns astring containing the original parsed text.  
       
    If the optional C{asString} argument is passed as C{False}, then the return value is a 
    C{L{ParseResults}} containing any results names that were originally matched, and a 
    single token containing the original matched text from the input string.  So if 
    the expression passed to C{L{originalTextFor}} contains expressions with defined
    results names, you must set C{asString} to C{False} if you want to preserve those
    results name values.

    Example::
        src = "this is test <b> bold <i>text</i> </b> normal text "
        for tag in ("b","i"):
            opener,closer = makeHTMLTags(tag)
            patt = originalTextFor(opener + SkipTo(closer) + closer)
            print(patt.searchString(src)[0])
    prints::
        ['<b> bold <i>text</i> </b>']
        ['<i>text</i>']
    cSs|Sr�ry)r�r�rxryryrzr{ar|z!originalTextFor.<locals>.<lambda>F�_original_start�
_original_endcSs||j|j�Sr�)rzr{rryryrzr{fr|cSs&||�d�|�d��g|dd�<dS)Nrzr{)r rryryrz�extractTexthsz$originalTextFor.<locals>.extractText)rr�r�r�r�)rw�asString�	locMarker�endlocMarker�	matchExprr|ryryrzriIs

cCst|��dd��S)zp
    Helper to undo pyparsing's default grouping of And expressions, even
    if all but one are non-empty.
    cSs|dSr�ryrwryryrzr{sr|zungroup.<locals>.<lambda>)r/r�)rwryryrzrjnscCs4t��dd��}t|d�|d�|����d��S)a�
    Helper to decorate a returned token with its starting and ending locations in the input string.
    This helper adds the following results names:
     - locn_start = location where matched expression begins
     - locn_end = location where matched expression ends
     - value = the actual parsed results

    Be careful if the input text contains C{<TAB>} characters, you may want to call
    C{L{ParserElement.parseWithTabs}}

    Example::
        wd = Word(alphas)
        for match in locatedExpr(wd).searchString("ljsdf123lksdjjf123lkkjj1222"):
            print(match)
    prints::
        [[0, 'ljsdf', 5]]
        [[8, 'lksdjjf', 15]]
        [[18, 'lkkjj', 23]]
    cSs|Sr�ryrryryrzr{�r|zlocatedExpr.<locals>.<lambda>�
locn_startr�locn_end)rr�rr�rP)rw�locatorryryrzrlusz\[]-*.$+^?()~ �r�cCs|ddSr�ryrryryrzr{�r|r{z\\0?[xX][0-9a-fA-F]+cCstt|d�d�d��S)Nrz\0x�)�unichrrv�lstriprryryrzr{�r|z	\\0[0-7]+cCstt|ddd�d��S)Nrr��)r�rvrryryrzr{�r|z\]r�r:rs�negate�bodyr=csFdd��z"d��fdd�t�|�jD��WStk
r@YdSXdS)a�
    Helper to easily define string ranges for use in Word construction.  Borrows
    syntax from regexp '[]' string range definitions::
        srange("[0-9]")   -> "0123456789"
        srange("[a-z]")   -> "abcdefghijklmnopqrstuvwxyz"
        srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_"
    The input string must be enclosed in []'s, and the returned string is the expanded
    character set joined into a single string.
    The values enclosed in the []'s may be:
     - a single character
     - an escaped character with a leading backslash (such as C{\-} or C{\]})
     - an escaped hex character with a leading C{'\x'} (C{\x21}, which is a C{'!'} character) 
         (C{\0x##} is also supported for backwards compatibility) 
     - an escaped octal character with a leading C{'\0'} (C{\041}, which is a C{'!'} character)
     - a range of any of the above, separated by a dash (C{'a-z'}, etc.)
     - any combination of the above (C{'aeiouy'}, C{'a-zA-Z0-9_$'}, etc.)
    cSs<t|t�s|Sd�dd�tt|d�t|d�d�D��S)Nr�css|]}t|�VqdSr�)r�r�ryryrzr��sz+srange.<locals>.<lambda>.<locals>.<genexpr>rr�)r}r$r�r��ord)�pryryrzr{�r|zsrange.<locals>.<lambda>r�c3s|]}�|�VqdSr�ry)r��part��	_expandedryrzr��szsrange.<locals>.<genexpr>N)r��_reBracketExprr r�r�r�ryr�rzra�s
"cs�fdd�}|S)zt
    Helper method for defining parse actions that require matching at a specific
    column in the input text.
    cs"t||��krt||d���dS)Nzmatched token not at column %dr�)rp�locnr{r<ryrz�	verifyCol�sz!matchOnlyAtCol.<locals>.verifyColry)r=r�ryr<rzrO�scs�fdd�S)a�
    Helper method for common parse actions that simply return a literal value.  Especially
    useful when used with C{L{transformString<ParserElement.transformString>}()}.

    Example::
        num = Word(nums).setParseAction(lambda toks: int(toks[0]))
        na = oneOf("N/A NA").setParseAction(replaceWith(math.nan))
        term = na | num
        
        OneOrMore(term).parseString("324 234 N/A 234") # -> [324, 234, nan, 234]
    cs�gSr�ryr��replStrryrzr{�r|zreplaceWith.<locals>.<lambda>ryr�ryr�rzr^�scCs|ddd�S)a
    Helper parse action for removing quotation marks from parsed quoted strings.

    Example::
        # by default, quotation marks are included in parsed results
        quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"]

        # use removeQuotes to strip quotation marks from parsed results
        quotedString.setParseAction(removeQuotes)
        quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"]
    rr�rtryrryryrzr\�scsN��fdd�}zt�dt�d�j�}Wntk
rBt��}YnX||_|S)aG
    Helper to define a parse action by mapping a function to all elements of a ParseResults list.If any additional 
    args are passed, they are forwarded to the given function as additional arguments after
    the token, as in C{hex_integer = Word(hexnums).setParseAction(tokenMap(int, 16))}, which will convert the
    parsed data to an integer using base 16.

    Example (compare the last to example in L{ParserElement.transformString}::
        hex_ints = OneOrMore(Word(hexnums)).setParseAction(tokenMap(int, 16))
        hex_ints.runTests('''
            00 11 22 aa FF 0a 0d 1a
            ''')
        
        upperword = Word(alphas).setParseAction(tokenMap(str.upper))
        OneOrMore(upperword).runTests('''
            my kingdom for a horse
            ''')

        wd = Word(alphas).setParseAction(tokenMap(str.title))
        OneOrMore(wd).setParseAction(' '.join).runTests('''
            now is the winter of our discontent made glorious summer by this sun of york
            ''')
    prints::
        00 11 22 aa FF 0a 0d 1a
        [0, 17, 34, 170, 255, 10, 13, 26]

        my kingdom for a horse
        ['MY', 'KINGDOM', 'FOR', 'A', 'HORSE']

        now is the winter of our discontent made glorious summer by this sun of york
        ['Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York']
    cs��fdd�|D�S)Ncsg|]}�|f����qSryry)r��tokn�r�r�ryrzr��sz(tokenMap.<locals>.pa.<locals>.<listcomp>ryrr�ryrzr��sztokenMap.<locals>.par�r�)r�r�r�r)r�r�r�r�ryr�rzro�s 
�cCst|���Sr��r�r�rwryryrzr{r|cCst|���Sr��r��lowerrwryryrzr{r|c	Cs�t|t�r|}t||d�}n|j}tttd�}|r�t���	t
�}td�|d�tt
t|td�|���tddgd��d	��	d
d��td�}n�d
�dd�tD��}t���	t
�t|�B}td�|d�tt
t|�	t�ttd�|����tddgd��d	��	dd��td�}ttd�|d�}|�dd
�|�dd��������d|�}|�dd
�|�dd��������d|�}||_||_||fS)zRInternal helper to construct opening and closing tag expressions, given a tag namer�z_-:rM�tag�=�/F�rrEcSs|ddkS�Nrr�ryrryryrzr{r|z_makeTags.<locals>.<lambda>rNr�css|]}|dkr|VqdS)rNNryr�ryryrzr�sz_makeTags.<locals>.<genexpr>cSs|ddkSr�ryrryryrzr{r|rOr��:rrz<%s>r�z</%s>)r}r�rr�r1r6r5r@r�r�r\r-r
r4rrr�r�rXr[rDr�_Lr��titler�r�r�)�tagStr�xml�resname�tagAttrName�tagAttrValue�openTag�printablesLessRAbrack�closeTagryryrz�	_makeTagss>
�������..r�cCs
t|d�S)a 
    Helper to construct opening and closing tag expressions for HTML, given a tag name. Matches
    tags in either upper or lower case, attributes with namespaces and with quoted or unquoted values.

    Example::
        text = '<td>More info at the <a href="http://pyparsing.wikispaces.com">pyparsing</a> wiki page</td>'
        # makeHTMLTags returns pyparsing expressions for the opening and closing tags as a 2-tuple
        a,a_end = makeHTMLTags("A")
        link_expr = a + SkipTo(a_end)("link_text") + a_end
        
        for link in link_expr.searchString(text):
            # attributes in the <A> tag (like "href" shown here) are also accessible as named results
            print(link.link_text, '->', link.href)
    prints::
        pyparsing -> http://pyparsing.wikispaces.com
    F�r��r�ryryrzrM(scCs
t|d�S)z�
    Helper to construct opening and closing tag expressions for XML, given a tag name. Matches
    tags only in the given upper/lower case.

    Example: similar to L{makeHTMLTags}
    Tr�r�ryryrzrN;scs8|r|dd��n|���dd��D���fdd�}|S)a<
    Helper to create a validating parse action to be used with start tags created
    with C{L{makeXMLTags}} or C{L{makeHTMLTags}}. Use C{withAttribute} to qualify a starting tag
    with a required attribute value, to avoid false matches on common tags such as
    C{<TD>} or C{<DIV>}.

    Call C{withAttribute} with a series of attribute names and values. Specify the list
    of filter attributes names and values as:
     - keyword arguments, as in C{(align="right")}, or
     - as an explicit dict with C{**} operator, when an attribute name is also a Python
          reserved word, as in C{**{"class":"Customer", "align":"right"}}
     - a list of name-value tuples, as in ( ("ns1:class", "Customer"), ("ns2:align","right") )
    For attribute names with a namespace prefix, you must use the second form.  Attribute
    names are matched insensitive to upper/lower case.
       
    If just testing for C{class} (with or without a namespace), use C{L{withClass}}.

    To verify that the attribute exists, but without specifying a value, pass
    C{withAttribute.ANY_VALUE} as the value.

    Example::
        html = '''
            <div>
            Some text
            <div type="grid">1 4 0 1 0</div>
            <div type="graph">1,3 2,3 1,1</div>
            <div>this has no type</div>
            </div>
                
        '''
        div,div_end = makeHTMLTags("div")

        # only match div tag having a type attribute with value "grid"
        div_grid = div().setParseAction(withAttribute(type="grid"))
        grid_expr = div_grid + SkipTo(div | div_end)("body")
        for grid_header in grid_expr.searchString(html):
            print(grid_header.body)
        
        # construct a match with any div tag having a type attribute, regardless of the value
        div_any_type = div().setParseAction(withAttribute(type=withAttribute.ANY_VALUE))
        div_expr = div_any_type + SkipTo(div | div_end)("body")
        for div_header in div_expr.searchString(html):
            print(div_header.body)
    prints::
        1 4 0 1 0

        1 4 0 1 0
        1,3 2,3 1,1
    NcSsg|]\}}||f�qSryryrEryryrzr�zsz!withAttribute.<locals>.<listcomp>csZ�D]P\}}||kr$t||d|��|tjkr|||krt||d||||f��qdS)Nzno matching attribute z+attribute '%s' has value '%s', must be '%s')r!rg�	ANY_VALUE)r�r�r��attrName�	attrValue��attrsryrzr�{s�zwithAttribute.<locals>.pa)r�)r��attrDictr�ryr�rzrgDs2cCs|rd|nd}tf||i�S)a�
    Simplified version of C{L{withAttribute}} when matching on a div class - made
    difficult because C{class} is a reserved word in Python.

    Example::
        html = '''
            <div>
            Some text
            <div class="grid">1 4 0 1 0</div>
            <div class="graph">1,3 2,3 1,1</div>
            <div>this &lt;div&gt; has no class</div>
            </div>
                
        '''
        div,div_end = makeHTMLTags("div")
        div_grid = div().setParseAction(withClass("grid"))
        
        grid_expr = div_grid + SkipTo(div | div_end)("body")
        for grid_header in grid_expr.searchString(html):
            print(grid_header.body)
        
        div_any_type = div().setParseAction(withClass(withAttribute.ANY_VALUE))
        div_expr = div_any_type + SkipTo(div | div_end)("body")
        for div_header in div_expr.searchString(html):
            print(div_header.body)
    prints::
        1 4 0 1 0

        1 4 0 1 0
        1,3 2,3 1,1
    z%s:class�class)rg)�	classname�	namespace�	classattrryryrzrm�s �(r�cCs�t�}||||B}t|�D�]l\}}|ddd�\}}	}
}|	dkrPd|nd|}|	dkr�|dkstt|�dkr|td��|\}
}t��|�}|
tjk�r^|	d	kr�t||�t|t	|��}n�|	dk�r|dk	r�t|||�t|t	||��}nt||�t|t	|��}nD|	dk�rTt||
|||�t||
|||�}ntd
��n�|
tj
k�rB|	d	k�r�t|t��s�t|�}t|j
|�t||�}n�|	dk�r�|dk	�r�t|||�t|t	||��}nt||�t|t	|��}nD|	dk�r8t||
|||�t||
|||�}ntd
��ntd��|�rvt|ttf��rl|j|�n
|�|�||�|�|BK}|}q||K}|S)aD

    Helper method for constructing grammars of expressions made up of
    operators working in a precedence hierarchy.  Operators may be unary or
    binary, left- or right-associative.  Parse actions can also be attached
    to operator expressions. The generated parser will also recognize the use 
    of parentheses to override operator precedences (see example below).
    
    Note: if you define a deep operator list, you may see performance issues
    when using infixNotation. See L{ParserElement.enablePackrat} for a
    mechanism to potentially improve your parser performance.

    Parameters:
     - baseExpr - expression representing the most basic element for the nested
     - opList - list of tuples, one for each operator precedence level in the
      expression grammar; each tuple is of the form
      (opExpr, numTerms, rightLeftAssoc, parseAction), where:
       - opExpr is the pyparsing expression for the operator;
          may also be a string, which will be converted to a Literal;
          if numTerms is 3, opExpr is a tuple of two expressions, for the
          two operators separating the 3 terms
       - numTerms is the number of terms for this operator (must
          be 1, 2, or 3)
       - rightLeftAssoc is the indicator whether the operator is
          right or left associative, using the pyparsing-defined
          constants C{opAssoc.RIGHT} and C{opAssoc.LEFT}.
       - parseAction is the parse action to be associated with
          expressions matching this operator expression (the
          parse action tuple member may be omitted); if the parse action
          is passed a tuple or list of functions, this is equivalent to
          calling C{setParseAction(*fn)} (L{ParserElement.setParseAction})
     - lpar - expression for matching left-parentheses (default=C{Suppress('(')})
     - rpar - expression for matching right-parentheses (default=C{Suppress(')')})

    Example::
        # simple example of four-function arithmetic with ints and variable names
        integer = pyparsing_common.signed_integer
        varname = pyparsing_common.identifier 
        
        arith_expr = infixNotation(integer | varname,
            [
            ('-', 1, opAssoc.RIGHT),
            (oneOf('* /'), 2, opAssoc.LEFT),
            (oneOf('+ -'), 2, opAssoc.LEFT),
            ])
        
        arith_expr.runTests('''
            5+3*6
            (5+3)*6
            -2--11
            ''', fullDump=False)
    prints::
        5+3*6
        [[5, '+', [3, '*', 6]]]

        (5+3)*6
        [[[5, '+', 3], '*', 6]]

        -2--11
        [[['-', 2], '-', ['-', 11]]]
    r�Nr�rqz%s termz	%s%s termrsz@if numterms=3, opExpr must be a tuple or list of two expressionsr�z6operator must be unary (1), binary (2), or ternary (3)z2operator must indicate right or left associativity)rr�r�rAr�rV�LEFTrrr�RIGHTr}rrwr@r�r�)�baseExpr�opList�lpar�rparr��lastExprr��operDef�opExpr�arity�rightLeftAssocr��termName�opExpr1�opExpr2�thisExprr�ryryrzrk�sZ=
&
�



&
�

z4"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*�"z string enclosed in double quotesz4'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*�'z string enclosed in single quotesz*quotedString using single or double quotes�uzunicode string literalcCs�||krtd��|dk�r*t|t��r"t|t��r"t|�dkr�t|�dkr�|dk	r�tt|t||tjdd����	dd��}n$t
��t||tj��	dd��}nx|dk	r�tt|t|�t|�ttjdd����	dd��}n4ttt|�t|�ttjdd����	d	d��}ntd
��t
�}|dk	�rd|tt|�t||B|B�t|��K}n$|tt|�t||B�t|��K}|�d||f�|S)a~	
    Helper method for defining nested lists enclosed in opening and closing
    delimiters ("(" and ")" are the default).

    Parameters:
     - opener - opening character for a nested list (default=C{"("}); can also be a pyparsing expression
     - closer - closing character for a nested list (default=C{")"}); can also be a pyparsing expression
     - content - expression for items within the nested lists (default=C{None})
     - ignoreExpr - expression for ignoring opening and closing delimiters (default=C{quotedString})

    If an expression is not provided for the content argument, the nested
    expression will capture all whitespace-delimited content between delimiters
    as a list of separate values.

    Use the C{ignoreExpr} argument to define expressions that may contain
    opening or closing characters that should not be treated as opening
    or closing characters for nesting, such as quotedString or a comment
    expression.  Specify multiple expressions using an C{L{Or}} or C{L{MatchFirst}}.
    The default is L{quotedString}, but if no expressions are to be ignored,
    then pass C{None} for this argument.

    Example::
        data_type = oneOf("void int short long char float double")
        decl_data_type = Combine(data_type + Optional(Word('*')))
        ident = Word(alphas+'_', alphanums+'_')
        number = pyparsing_common.number
        arg = Group(decl_data_type + ident)
        LPAR,RPAR = map(Suppress, "()")

        code_body = nestedExpr('{', '}', ignoreExpr=(quotedString | cStyleComment))

        c_function = (decl_data_type("type") 
                      + ident("name")
                      + LPAR + Optional(delimitedList(arg), [])("args") + RPAR 
                      + code_body("body"))
        c_function.ignore(cStyleComment)
        
        source_code = '''
            int is_odd(int x) { 
                return (x%2); 
            }
                
            int dec_to_hex(char hchar) { 
                if (hchar >= '0' && hchar <= '9') { 
                    return (ord(hchar)-ord('0')); 
                } else { 
                    return (10+ord(hchar)-ord('A'));
                } 
            }
        '''
        for func in c_function.searchString(source_code):
            print("%(name)s (%(type)s) args: %(args)s" % func)

    prints::
        is_odd (int) args: [['int', 'x']]
        dec_to_hex (int) args: [['char', 'hchar']]
    z.opening and closing strings cannot be the sameNr�r�cSs|d��Sr��r�rwryryrzr{gr|znestedExpr.<locals>.<lambda>cSs|d��Sr�r�rwryryrzr{jr|cSs|d��Sr�r�rwryryrzr{pr|cSs|d��Sr�r�rwryryrzr{tr|zOopening and closing arguments must be strings if no content expression is givenznested %s%s expression)rAr}r�r�rrrr&r�r�rEr�rrrr-r4r�)�opener�closer�contentr3r�ryryrzrR%sH:
���������
*$cs��fdd�}�fdd�}�fdd�}tt��d����}t�t��|��d�}t��|��d	�}t��|��d
�}	|r�tt|�|t|t|�t|��|	�}
n$tt|�t|t|�t|���}
|�	t
t��|
�d�S)a
	
    Helper method for defining space-delimited indentation blocks, such as
    those used to define block statements in Python source code.

    Parameters:
     - blockStatementExpr - expression defining syntax of statement that
            is repeated within the indented block
     - indentStack - list created by caller to manage indentation stack
            (multiple statementWithIndentedBlock expressions within a single grammar
            should share a common indentStack)
     - indent - boolean indicating whether block must be indented beyond the
            the current level; set to False for block of left-most statements
            (default=C{True})

    A valid block must contain at least one C{blockStatement}.

    Example::
        data = '''
        def A(z):
          A1
          B = 100
          G = A2
          A2
          A3
        B
        def BB(a,b,c):
          BB1
          def BBA():
            bba1
            bba2
            bba3
        C
        D
        def spam(x,y):
             def eggs(z):
                 pass
        '''


        indentStack = [1]
        stmt = Forward()

        identifier = Word(alphas, alphanums)
        funcDecl = ("def" + identifier + Group( "(" + Optional( delimitedList(identifier) ) + ")" ) + ":")
        func_body = indentedBlock(stmt, indentStack)
        funcDef = Group( funcDecl + func_body )

        rvalue = Forward()
        funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")")
        rvalue << (funcCall | identifier | Word(nums))
        assignment = Group(identifier + "=" + rvalue)
        stmt << ( funcDef | assignment | identifier )

        module_body = OneOrMore(stmt)

        parseTree = module_body.parseString(data)
        parseTree.pprint()
    prints::
        [['def',
          'A',
          ['(', 'z', ')'],
          ':',
          [['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]],
         'B',
         ['def',
          'BB',
          ['(', 'a', 'b', 'c', ')'],
          ':',
          [['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]],
         'C',
         'D',
         ['def',
          'spam',
          ['(', 'x', 'y', ')'],
          ':',
          [[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]] 
    csN|t|�krdSt||�}|�dkrJ|�dkr>t||d��t||d��dS)Nrtzillegal nestingznot a peer entry)r�r;r#r!�r�r�rx�curCol��indentStackryrz�checkPeerIndent�s
z&indentedBlock.<locals>.checkPeerIndentcs2t||�}|�dkr"��|�nt||d��dS)Nrtznot a subentry)r;r%r!r�r�ryrz�checkSubIndent�s
z%indentedBlock.<locals>.checkSubIndentcsN|t|�krdSt||�}�r6|�dkr6|�dksBt||d�����dS)Nrtr�znot an unindent)r�r;r!r r�r�ryrz�
checkUnindent�s
z$indentedBlock.<locals>.checkUnindentz	 �INDENTr��UNINDENTzindented block)rrrQrNrr�r�rrrSrl)�blockStatementExprr�rSr�r�r�rfr��PEER�UNDENT�smExprryr�rzrhs(N����z#[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]z[\0xa1-\0xbf\0xd7\0xf7]z_:zany tagzgt lt amp nbsp quot aposz><& "'z&(?P<entity>rqz);zcommon HTML entitycCst�|j�S)zRHelper parser action to replace common HTML entities with their special characters)�_htmlEntityMapr��entityrwryryrzr]�sz/\*(?:[^*]|\*(?!/))*z*/zC style commentz<!--[\s\S]*?-->zHTML commentz.*zrest of linez//(?:\\\n|[^\n])*z
// commentzC++ style commentz#.*zPython style commentr�� 	�	commaItemr�c@s�eZdZdZee�Zee�Ze	e
��d��e�Z
e	e��d��eed��Zed��d��e�Ze��e�de��e��d�Ze�d	d
��eeeed���e�B�d�Ze�e�ed
��d��e�Zed��d��e�ZeeBeB��Zed��d��e�Ze	eded��d�Zed��d�Z ed��d�Z!e!de!d�d�Z"ee!de!d�dee!de!d��d�Z#e#�$dd
��d e �d!�Z%e&e"e%Be#B�d"���d"�Z'ed#��d$�Z(e)d=d&d'��Z*e)d>d)d*��Z+ed+��d,�Z,ed-��d.�Z-ed/��d0�Z.e/��e0��BZ1e)d1d2��Z2e&e3e4d3�e5�e	e6d3d4�ee7d5�������d6�Z8e9ee:�;�e8Bd7d8���d9�Z<e)ed:d
���Z=e)ed;d
���Z>d<S)?rpa�

    Here are some common low-level expressions that may be useful in jump-starting parser development:
     - numeric forms (L{integers<integer>}, L{reals<real>}, L{scientific notation<sci_real>})
     - common L{programming identifiers<identifier>}
     - network addresses (L{MAC<mac_address>}, L{IPv4<ipv4_address>}, L{IPv6<ipv6_address>})
     - ISO8601 L{dates<iso8601_date>} and L{datetime<iso8601_datetime>}
     - L{UUID<uuid>}
     - L{comma-separated list<comma_separated_list>}
    Parse actions:
     - C{L{convertToInteger}}
     - C{L{convertToFloat}}
     - C{L{convertToDate}}
     - C{L{convertToDatetime}}
     - C{L{stripHTMLTags}}
     - C{L{upcaseTokens}}
     - C{L{downcaseTokens}}

    Example::
        pyparsing_common.number.runTests('''
            # any int or real number, returned as the appropriate type
            100
            -100
            +100
            3.14159
            6.02e23
            1e-12
            ''')

        pyparsing_common.fnumber.runTests('''
            # any int or real number, returned as float
            100
            -100
            +100
            3.14159
            6.02e23
            1e-12
            ''')

        pyparsing_common.hex_integer.runTests('''
            # hex numbers
            100
            FF
            ''')

        pyparsing_common.fraction.runTests('''
            # fractions
            1/2
            -3/4
            ''')

        pyparsing_common.mixed_integer.runTests('''
            # mixed fractions
            1
            1/2
            -3/4
            1-3/4
            ''')

        import uuid
        pyparsing_common.uuid.setParseAction(tokenMap(uuid.UUID))
        pyparsing_common.uuid.runTests('''
            # uuid
            12345678-1234-5678-1234-567812345678
            ''')
    prints::
        # any int or real number, returned as the appropriate type
        100
        [100]

        -100
        [-100]

        +100
        [100]

        3.14159
        [3.14159]

        6.02e23
        [6.02e+23]

        1e-12
        [1e-12]

        # any int or real number, returned as float
        100
        [100.0]

        -100
        [-100.0]

        +100
        [100.0]

        3.14159
        [3.14159]

        6.02e23
        [6.02e+23]

        1e-12
        [1e-12]

        # hex numbers
        100
        [256]

        FF
        [255]

        # fractions
        1/2
        [0.5]

        -3/4
        [-0.75]

        # mixed fractions
        1
        [1]

        1/2
        [0.5]

        -3/4
        [-0.75]

        1-3/4
        [1.75]

        # uuid
        12345678-1234-5678-1234-567812345678
        [UUID('12345678-1234-5678-1234-567812345678')]
    �integerzhex integerr�z[+-]?\d+zsigned integerr��fractioncCs|d|dS)Nrrtryrwryryrzr{�r|zpyparsing_common.<lambda>r�z"fraction or mixed integer-fractionz
[+-]?\d+\.\d*zreal numberz+[+-]?\d+([eE][+-]?\d+|\.\d*([eE][+-]?\d+)?)z$real number with scientific notationz[+-]?\d+\.?\d*([eE][+-]?\d+)?�fnumberr�
identifierzK(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})){3}zIPv4 addressz[0-9a-fA-F]{1,4}�hex_integerr��zfull IPv6 address)rr�z::zshort IPv6 addresscCstdd�|D��dkS)Ncss|]}tj�|�rdVqdSrJ)rp�
_ipv6_partr&r`ryryrzr��sz,pyparsing_common.<lambda>.<locals>.<genexpr>r�)rrwryryrzr{�r|z::ffff:zmixed IPv6 addresszIPv6 addressz:[0-9a-fA-F]{2}([:.-])[0-9a-fA-F]{2}(?:\1[0-9a-fA-F]{2}){4}zMAC address�%Y-%m-%dcs�fdd�}|S)a�
        Helper to create a parse action for converting parsed date string to Python datetime.date

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})

        Example::
            date_expr = pyparsing_common.iso8601_date.copy()
            date_expr.setParseAction(pyparsing_common.convertToDate())
            print(date_expr.parseString("1999-12-31"))
        prints::
            [datetime.date(1999, 12, 31)]
        c
sNzt�|d����WStk
rH}zt||t|���W5d}~XYnXdSr�)r�strptime�daterAr!r�r�r�rx�ve��fmtryrz�cvt_fn�sz.pyparsing_common.convertToDate.<locals>.cvt_fnry�r�r�ryr�rz�
convertToDate�szpyparsing_common.convertToDate�%Y-%m-%dT%H:%M:%S.%fcs�fdd�}|S)a
        Helper to create a parse action for converting parsed datetime string to Python datetime.datetime

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%dT%H:%M:%S.%f"})

        Example::
            dt_expr = pyparsing_common.iso8601_datetime.copy()
            dt_expr.setParseAction(pyparsing_common.convertToDatetime())
            print(dt_expr.parseString("1999-12-31T23:59:59.999"))
        prints::
            [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)]
        c
sJzt�|d��WStk
rD}zt||t|���W5d}~XYnXdSr�)rr�rAr!rr�r�ryrzr��sz2pyparsing_common.convertToDatetime.<locals>.cvt_fnryr�ryr�rz�convertToDatetime�sz"pyparsing_common.convertToDatetimez7(?P<year>\d{4})(?:-(?P<month>\d\d)(?:-(?P<day>\d\d))?)?zISO8601 datez�(?P<year>\d{4})-(?P<month>\d\d)-(?P<day>\d\d)[T ](?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d(\.\d*)?)?)?(?P<tz>Z|[+-]\d\d:?\d\d)?zISO8601 datetimez2[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}�UUIDcCstj�|d�S)a
        Parse action to remove HTML tags from web page HTML source

        Example::
            # strip HTML links from normal text 
            text = '<td>More info at the <a href="http://pyparsing.wikispaces.com">pyparsing</a> wiki page</td>'
            td,td_end = makeHTMLTags("TD")
            table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)("body") + td_end
            
            print(table_text.parseString(text).body) # -> 'More info at the pyparsing wiki page'
        r)rp�_html_stripperr�)r�r�r�ryryrz�
stripHTMLTagss
zpyparsing_common.stripHTMLTagsrUr�r�r�r�r�zcomma separated listcCst|���Sr�r�rwryryrzr{"r|cCst|���Sr�r�rwryryrzr{%r|N)r�)r�)?r�r�r�r�rorv�convertToInteger�float�convertToFloatr1rTr�r�r�rFr�r)�signed_integerr�r�rrN�
mixed_integerr�real�sci_realr�numberr�r6r5r��ipv4_addressr��_full_ipv6_address�_short_ipv6_addressr��_mixed_ipv6_addressr�ipv6_address�mac_addressr�r�r��iso8601_date�iso8601_datetime�uuidr9r8r�r�rrrrXr0�
_commasepitemrBr[r��comma_separated_listrfrDryryryrzrpsV""
2
 
���__main__�select�fromr�rN)rW�columnsr�Ztables�commandaK
        # '*' as column list and dotted table name
        select * from SYS.XYZZY

        # caseless match on "SELECT", and casts back to "select"
        SELECT * from XYZZY, ABC

        # list of column names, and mixed case SELECT keyword
        Select AA,BB,CC from Sys.dual

        # multiple tables
        Select A, B, C from Sys.dual, Table2

        # invalid SELECT keyword - should fail
        Xelect A, B, C from Sys.dual

        # incomplete command - should fail
        Select

        # invalid column name - should fail
        Select ^^^ frox Sys.dual

        z]
        100
        -100
        +100
        3.14159
        6.02e23
        1e-12
        z 
        100
        FF
        z6
        12345678-1234-5678-1234-567812345678
        )rs)rUF)N)FT)T)r�)T)�r��__version__�__versionTime__�
__author__r��weakrefrr�r�r�r5r�r�r
rgr�r�r�_threadr�ImportError�	threading�collections.abcrrrr�ordereddict�__all__r@�version_infor�rF�maxsizer�rr��chrr�r�rr�ra�reversedr�r�rcr�r�r�r��maxint�xranger��__builtin__r��fnamer%r�r�r�r�r�r�r��ascii_uppercase�ascii_lowercaser6rTrFr5rlr��	printablerXr�rr!r#r%r(r�r$�registerr;rLrIrxr|r~rSr�r&r.rrrr�r�rr
r	rnr1r)r'rr0r�rrrr,r+r3r2r"rrrrr rrr%rr4r1r2rr*rrAr/rrr
r-rrdrBr>r+rQrPr�rUrCrirjrlr�rErKrJrcrbr��_escapedPunc�_escapedHexChar�_escapedOctChar�_singleChar�
_charRanger�r�rarOr^r\rorfrDr�rMrNrgr�rmrVr�r�rkrWr@r`r[rerRrhr7rYr9r8r�r�r�rr=r]r:rGrPr_rAr?rHrZrrr<rpr��selectToken�	fromToken�ident�
columnName�columnNameList�
columnSpec�	tableName�
tableNameList�	simpleSQLrr�r�r�rr�ryryryrz�<module>s��4�
8



@v&A= I
G3pLOD|M &#@sQ,A,	I#%0
,	?#p
��Zr

 (
 
���� 


"
	�?�h�4bytecode of module 'pkg_resources._vendor.pyparsing'�u��b.���_h)��N}�(hB\_�A@sRdZddlmZddlZddlZddlZddlZddlZdZdZ	ej
ddkZej
ddkZej
dd�dkZ
er�efZefZefZeZeZejZn~efZeefZeejfZeZeZej�d	�r�ed
�ZnHGdd�de�Z ze!e ��Wne"k
�red
�ZYn
Xed
�Z[ dd�Z#dd�Z$Gdd�de�Z%Gdd�de%�Z&Gdd�dej'�Z(Gdd�de%�Z)Gdd�de�Z*e*e+�Z,Gdd�de(�Z-e)dddd �e)d!d"d#d$d!�e)d%d"d"d&d%�e)d'd(d#d)d'�e)d*d(d+�e)d,d"d#d-d,�e)d.d/d/d0d.�e)d1d/d/d.d1�e)d2d(d#d3d2�e)d4d(e
�rd5nd6d7�e)d8d(d9�e)d:d;d<d=�e)d d d�e)d>d>d?�e)d@d@d?�e)dAdAd?�e)d3d(d#d3d2�e)dBd"d#dCdB�e)dDd"d"dEdD�e&d#d(�e&dFdG�e&dHdI�e&dJdKdL�e&dMdNdM�e&dOdPdQ�e&dRdSdT�e&dUdVdW�e&dXdYdZ�e&d[d\d]�e&d^d_d`�e&dadbdc�e&dddedf�e&dgdhdi�e&djdjdk�e&dldldk�e&dmdmdk�e&dndndo�e&dpdq�e&drds�e&dtdu�e&dvdwdv�e&dxdy�e&dzd{d|�e&d}d~d�e&d�d�d��e&d�d�d��e&d�d�d��e&d�d�d��e&d�d�d��e&d�d�d��e&d�d�d��e&d�d�d��e&d�d�d�e&d�d�d��e&d�d�d��e&d�d�d��e&d�e+d�d��e&d�e+d�d��e&d�e+d�e+d��e&d�d�d��e&d�d�d��e&d�d�d��g>Z.ejd�k�rRe.e&d�d��g7Z.e.D]2Z/e0e-e/j1e/�e2e/e&��rVe,�3e/d�e/j1��qV[/e.e-_.e-e+d��Z4e,�3e4d��Gd�d��d�e(�Z5e)d�d�d��e)d�d�d��e)d�d�d��e)d�d�d��e)d�d�d��e)d�d�d��e)d�d�d��e)d�d�d��e)d�d�d��e)d�d�d��e)d=d�d��e)d�d�d��e)d�d�d��e)d�d�d��e)d�d�d��e)d�d�d��e)d�d�d��e)d�d�d��e)d�d�d��e)d�d�d��e)d�d�d��e)d�d�d��e)d�d�d��gZ6e6D]Z/e0e5e/j1e/��q�[/e6e5_.e,�3e5e+d��d�dҡGd�dԄd�e(�Z7e)d�d�d��e)d�d�d��e)d�d�d��gZ8e8D]Z/e0e7e/j1e/��q[/e8e7_.e,�3e7e+d��d�dۡGd�d݄d�e(�Z9e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃e)d�d�d߃g!Z:e:D]Z/e0e9e/j1e/��q�[/e:e9_.e,�3e9e+�d��d�d�G�d�d��de(�Z;e)�dd��d�e)�dd��d�e)�dd��d�e)�d	d��d�gZ<e<D]Z/e0e;e/j1e/��q8[/e<e;_.e,�3e;e+�d
��d�d�G�d
�d��de(�Z=e)�dd�d��gZ>e>D]Z/e0e=e/j1e/��q�[/e>e=_.e,�3e=e+�d��d�d�G�d�d��dej'�Z?e,�3e?e+d���d��d�d�Z@�d�d�ZAe�	rH�dZB�dZC�dZD�dZE�dZF�dZGn$�d ZB�d!ZC�d"ZD�d#ZE�d$ZF�d%ZGzeHZIWn"eJk
�	r��d&�d'�ZIYnXeIZHzeKZKWn"eJk
�	r��d(�d)�ZKYnXe�	r�d*�d+�ZLejMZN�d,�d-�ZOeZPn>�d.�d+�ZL�d/�d0�ZN�d1�d-�ZOG�d2�d3��d3e�ZPeKZKe#eL�d4�e�QeB�ZRe�QeC�ZSe�QeD�ZTe�QeE�ZUe�QeF�ZVe�QeG�ZWe�
rԐd5�d6�ZX�d7�d8�ZY�d9�d:�ZZ�d;�d<�Z[e�\�d=�Z]e�\�d>�Z^e�\�d?�Z_nT�d@�d6�ZX�dA�d8�ZY�dB�d:�ZZ�dC�d<�Z[e�\�dD�Z]e�\�dE�Z^e�\�dF�Z_e#eX�dG�e#eY�dH�e#eZ�dI�e#e[�dJ�e�r�dK�dL�Z`�dM�dN�ZaebZcddldZded�e�dO�jfZg[de�hd�ZiejjZkelZmddlnZnenjoZoenjpZp�dPZqej
�dQ�dQk�r�dRZr�dSZsn�dTZr�dUZsnj�dV�dL�Z`�dW�dN�ZaecZcebZg�dX�dY�Zi�dZ�d[�Zke�tejuev�ZmddloZoeojoZoZp�d\Zq�dRZr�dSZse#e`�d]�e#ea�d^��d_�dP�Zw�d`�dT�Zx�da�dU�Zye�r�eze4j{�db�Z|�d|�dc�dd�Z}n�d}�de�df�Z|e|�dg�ej
dd��dhk�r�e|�di�n.ej
dd��dhk�
re|�dj�n�dk�dl�Z~eze4j{�dmd�Zedk�
rL�dn�do�Zej
dd��dpk�
rreZ��dq�do�Ze#e}�dr�ej
dd�dk�
r�ej�ej�f�ds�dt�Z�nej�Z��du�dv�Z��dw�dx�Z��dy�dz�Z�gZ�e+Z�e�����d{�dk	�
r�ge�_�ej��rBe�ej��D]4\Z�Z�ee��j+dk�re�j1e+k�rej�e�=�q>�q[�[�ej���e,�dS(~z6Utilities for writing code that runs on Python 2 and 3�)�absolute_importNz'Benjamin Peterson <benjamin@python.org>z1.10.0��)r��javai���c@seZdZdd�ZdS)�XcCsdS)Nl���selfrr�;/usr/lib/python3/dist-packages/pkg_resources/_vendor/six.py�__len__>sz	X.__len__N)�__name__�
__module__�__qualname__rrrrrr<srl����cCs
||_dS)z Add documentation to a function.N)�__doc__)�func�docrrr�_add_docKsrcCst|�tj|S)z7Import module, returning the module after the last dot.)�
__import__�sys�modules��namerrr�_import_modulePsrc@seZdZdd�Zdd�ZdS)�
_LazyDescrcCs
||_dS�Nr�r
rrrr�__init__Xsz_LazyDescr.__init__cCsB|��}t||j|�zt|j|j�Wntk
r<YnX|Sr)�_resolve�setattrr�delattr�	__class__�AttributeError)r
�obj�tp�resultrrr�__get__[sz_LazyDescr.__get__N)r
rrrr&rrrrrVsrcs.eZdZd�fdd�	Zdd�Zdd�Z�ZS)	�MovedModuleNcs2tt|��|�tr(|dkr |}||_n||_dSr)�superr'r�PY3�mod)r
r�old�new�r!rrriszMovedModule.__init__cCs
t|j�Sr)rr*r	rrrrrszMovedModule._resolvecCs"|��}t||�}t|||�|Sr)r�getattrr)r
�attr�_module�valuerrr�__getattr__us
zMovedModule.__getattr__)N)r
rrrrr2�
__classcell__rrr-rr'gs	r'cs(eZdZ�fdd�Zdd�ZgZ�ZS)�_LazyModulecstt|��|�|jj|_dSr)r(r4rr!rrr-rrr~sz_LazyModule.__init__cCs ddg}|dd�|jD�7}|S)Nrr
cSsg|]
}|j�qSrr)�.0r/rrr�
<listcomp>�sz'_LazyModule.__dir__.<locals>.<listcomp>)�_moved_attributes)r
�attrsrrr�__dir__�sz_LazyModule.__dir__)r
rrrr9r7r3rrr-rr4|sr4cs&eZdZd�fdd�	Zdd�Z�ZS)�MovedAttributeNcsdtt|��|�trH|dkr |}||_|dkr@|dkr<|}n|}||_n||_|dkrZ|}||_dSr)r(r:rr)r*r/)r
r�old_mod�new_mod�old_attr�new_attrr-rrr�szMovedAttribute.__init__cCst|j�}t||j�Sr)rr*r.r/)r
�modulerrrr�s
zMovedAttribute._resolve)NN)r
rrrrr3rrr-rr:�sr:c@sVeZdZdZdd�Zdd�Zdd�Zdd	d
�Zdd�Zd
d�Z	dd�Z
dd�ZeZdS)�_SixMetaPathImporterz�
    A meta path importer to import six.moves and its submodules.

    This class implements a PEP302 finder and loader. It should be compatible
    with Python 2.5 and all existing versions of Python3
    cCs||_i|_dSr)r�
known_modules)r
�six_module_namerrrr�sz_SixMetaPathImporter.__init__cGs"|D]}||j|jd|<qdS�N�.�rAr)r
r*�	fullnames�fullnamerrr�_add_module�sz _SixMetaPathImporter._add_modulecCs|j|jd|SrCrE�r
rGrrr�_get_module�sz _SixMetaPathImporter._get_moduleNcCs||jkr|SdSr)rA)r
rG�pathrrr�find_module�s
z _SixMetaPathImporter.find_modulecCs2z|j|WStk
r,td|��YnXdS)Nz!This loader does not know module )rA�KeyError�ImportErrorrIrrr�__get_module�sz!_SixMetaPathImporter.__get_modulecCsTztj|WStk
r YnX|�|�}t|t�r@|��}n||_|tj|<|Sr)rrrM� _SixMetaPathImporter__get_module�
isinstancer'r�
__loader__)r
rGr*rrr�load_module�s



z _SixMetaPathImporter.load_modulecCst|�|�d�S)z�
        Return true, if the named module is a package.

        We need this method to get correct spec objects with
        Python 3.4 (see PEP451)
        �__path__)�hasattrrPrIrrr�
is_package�sz_SixMetaPathImporter.is_packagecCs|�|�dS)z;Return None

        Required, if is_package is implementedN)rPrIrrr�get_code�s
z_SixMetaPathImporter.get_code)N)
r
rrrrrHrJrLrPrSrVrW�
get_sourcerrrrr@�s
	r@c@seZdZdZgZdS)�_MovedItemszLazy loading of moved objectsN)r
rrrrTrrrrrY�srY�	cStringIO�io�StringIO�filter�	itertools�builtins�ifilter�filterfalse�ifilterfalse�input�__builtin__�	raw_input�internr�map�imap�getcwd�osZgetcwdu�getcwdb�range�xrange�
reload_module�	importlib�imp�reload�reduce�	functools�shlex_quoteZpipes�shlex�quote�UserDict�collections�UserList�
UserString�zip�izip�zip_longest�izip_longest�configparser�ConfigParser�copyreg�copy_reg�dbm_gnu�gdbmzdbm.gnu�
_dummy_thread�dummy_thread�http_cookiejar�	cookielibzhttp.cookiejar�http_cookies�Cookiezhttp.cookies�
html_entities�htmlentitydefsz
html.entities�html_parser�
HTMLParserzhtml.parser�http_client�httplibzhttp.client�email_mime_multipartzemail.MIMEMultipartzemail.mime.multipart�email_mime_nonmultipartzemail.MIMENonMultipartzemail.mime.nonmultipart�email_mime_textzemail.MIMETextzemail.mime.text�email_mime_basezemail.MIMEBasezemail.mime.base�BaseHTTPServerzhttp.server�
CGIHTTPServer�SimpleHTTPServer�cPickle�pickle�queue�Queue�reprlib�repr�socketserver�SocketServer�_thread�thread�tkinter�Tkinter�tkinter_dialog�Dialogztkinter.dialog�tkinter_filedialog�
FileDialogztkinter.filedialog�tkinter_scrolledtext�ScrolledTextztkinter.scrolledtext�tkinter_simpledialog�SimpleDialogztkinter.simpledialog�tkinter_tix�Tixztkinter.tix�tkinter_ttk�ttkztkinter.ttk�tkinter_constants�Tkconstantsztkinter.constants�tkinter_dnd�Tkdndztkinter.dnd�tkinter_colorchooser�tkColorChooserztkinter.colorchooser�tkinter_commondialog�tkCommonDialogztkinter.commondialog�tkinter_tkfiledialog�tkFileDialog�tkinter_font�tkFontztkinter.font�tkinter_messagebox�tkMessageBoxztkinter.messagebox�tkinter_tksimpledialog�tkSimpleDialog�urllib_parsez.moves.urllib_parsezurllib.parse�urllib_errorz.moves.urllib_errorzurllib.error�urllibz
.moves.urllib�urllib_robotparser�robotparserzurllib.robotparser�
xmlrpc_client�	xmlrpclibz
xmlrpc.client�
xmlrpc_server�SimpleXMLRPCServerz
xmlrpc.server�win32�winreg�_winregzmoves.z.moves�movesc@seZdZdZdS)�Module_six_moves_urllib_parsez7Lazy loading of moved objects in six.moves.urllib_parseN�r
rrrrrrrr�@sr��ParseResult�urlparse�SplitResult�parse_qs�	parse_qsl�	urldefrag�urljoin�urlsplit�
urlunparse�
urlunsplit�
quote_plus�unquote�unquote_plus�	urlencode�
splitquery�splittag�	splituser�
uses_fragment�uses_netloc�uses_params�
uses_query�
uses_relative�moves.urllib_parsezmoves.urllib.parsec@seZdZdZdS)�Module_six_moves_urllib_errorz7Lazy loading of moved objects in six.moves.urllib_errorNr�rrrrr�hsr��URLError�urllib2�	HTTPError�ContentTooShortErrorz.moves.urllib.error�moves.urllib_errorzmoves.urllib.errorc@seZdZdZdS)�Module_six_moves_urllib_requestz9Lazy loading of moved objects in six.moves.urllib_requestNr�rrrrr�|sr��urlopenzurllib.request�install_opener�build_opener�pathname2url�url2pathname�
getproxies�Request�OpenerDirector�HTTPDefaultErrorHandler�HTTPRedirectHandler�HTTPCookieProcessor�ProxyHandler�BaseHandler�HTTPPasswordMgr�HTTPPasswordMgrWithDefaultRealm�AbstractBasicAuthHandler�HTTPBasicAuthHandler�ProxyBasicAuthHandler�AbstractDigestAuthHandler�HTTPDigestAuthHandler�ProxyDigestAuthHandler�HTTPHandler�HTTPSHandler�FileHandler�
FTPHandler�CacheFTPHandler�UnknownHandler�HTTPErrorProcessor�urlretrieve�
urlcleanup�	URLopener�FancyURLopener�proxy_bypassz.moves.urllib.request�moves.urllib_requestzmoves.urllib.requestc@seZdZdZdS)� Module_six_moves_urllib_responsez:Lazy loading of moved objects in six.moves.urllib_responseNr�rrrrr�sr�addbasezurllib.response�addclosehook�addinfo�
addinfourlz.moves.urllib.response�moves.urllib_responsezmoves.urllib.responsec@seZdZdZdS)�#Module_six_moves_urllib_robotparserz=Lazy loading of moved objects in six.moves.urllib_robotparserNr�rrrrr�sr�RobotFileParserz.moves.urllib.robotparser�moves.urllib_robotparserzmoves.urllib.robotparserc@sNeZdZdZgZe�d�Ze�d�Ze�d�Z	e�d�Z
e�d�Zdd�Zd	S)
�Module_six_moves_urllibzICreate a six.moves.urllib namespace that resembles the Python 3 namespacer�r�rrrcCsdddddgS)N�parse�error�request�responser�rr	rrrr9�szModule_six_moves_urllib.__dir__N)
r
rrrrT�	_importerrJrrrrr�r9rrrrr�s




rzmoves.urllibcCstt|j|�dS)zAdd an item to six.moves.N)rrYr)�moverrr�add_move�srcCsXztt|�WnDtk
rRztj|=Wn"tk
rLtd|f��YnXYnXdS)zRemove item from six.moves.zno such move, %rN)r rYr"r��__dict__rMrrrr�remove_move�sr!�__func__�__self__�__closure__�__code__�__defaults__�__globals__�im_func�im_self�func_closure�	func_code�
func_defaults�func_globalscCs|��Sr)�next)�itrrr�advance_iteratorsr0cCstdd�t|�jD��S)Ncss|]}d|jkVqdS)�__call__N)r )r5�klassrrr�	<genexpr>szcallable.<locals>.<genexpr>)�any�type�__mro__)r#rrr�callablesr7cCs|Srr��unboundrrr�get_unbound_functionsr:cCs|Srr�r�clsrrr�create_unbound_methodsr=cCs|jSr)r(r8rrrr:"scCst�|||j�Sr)�types�
MethodTyper!)rr#rrr�create_bound_method%sr@cCst�|d|�Sr)r>r?r;rrrr=(sc@seZdZdd�ZdS)�IteratorcCst|��|�Sr)r5�__next__r	rrrr.-sz
Iterator.nextN)r
rrr.rrrrrA+srAz3Get the function out of a possibly unbound functioncKst|jf|��Sr)�iter�keys��d�kwrrr�iterkeys>srHcKst|jf|��Sr)rC�valuesrErrr�
itervaluesAsrJcKst|jf|��Sr)rC�itemsrErrr�	iteritemsDsrLcKst|jf|��Sr)rC�listsrErrr�	iterlistsGsrNrDrIrKcKs|jf|�Sr)rHrErrrrHPscKs|jf|�Sr)rJrErrrrJSscKs|jf|�Sr)rLrErrrrLVscKs|jf|�Sr)rNrErrrrNYs�viewkeys�
viewvalues�	viewitemsz1Return an iterator over the keys of a dictionary.z3Return an iterator over the values of a dictionary.z?Return an iterator over the (key, value) pairs of a dictionary.zBReturn an iterator over the (key, [values]) pairs of a dictionary.cCs
|�d�S)Nzlatin-1)�encode��srrr�bksrUcCs|SrrrSrrr�unsrVz>B�assertCountEqual�ZassertRaisesRegexpZassertRegexpMatches�assertRaisesRegex�assertRegexcCs|SrrrSrrrrU�scCst|�dd�d�S)Nz\\z\\\\Zunicode_escape)�unicode�replacerSrrrrV�scCst|d�S)Nr��ord)�bsrrr�byte2int�sr`cCst||�Srr])�buf�irrr�
indexbytes�srcZassertItemsEqualzByte literalzText literalcOst|t�||�Sr)r.�_assertCountEqual�r
�args�kwargsrrrrW�scOst|t�||�Sr)r.�_assertRaisesRegexrerrrrY�scOst|t�||�Sr)r.�_assertRegexrerrrrZ�s�execcCs*|dkr|�}|j|k	r"|�|��|�dSr)�
__traceback__�with_traceback)r$r1�tbrrr�reraise�s


rncCsB|dkr*t�d�}|j}|dkr&|j}~n|dkr6|}td�dS)zExecute code in a namespace.NrXzexec _code_ in _globs_, _locs_)r�	_getframe�	f_globals�f_localsrj)�_code_�_globs_�_locs_�framerrr�exec_�s
rvz9def reraise(tp, value, tb=None):
    raise tp, value, tb
)rrzrdef raise_from(value, from_value):
    if from_value is None:
        raise value
    raise value from from_value
zCdef raise_from(value, from_value):
    raise value from from_value
cCs|�dSrr)r1�
from_valuerrr�
raise_from�srx�printc
s.|�dtj���dkrdS�fdd�}d}|�dd�}|dk	r`t|t�rNd}nt|t�s`td��|�d	d�}|dk	r�t|t�r�d}nt|t�s�td
��|r�td��|s�|D]}t|t�r�d}q�q�|r�td�}td
�}nd}d
}|dkr�|}|dkr�|}t|�D] \}	}|	�r||�||��q||�dS)z4The new-style print function for Python 2.4 and 2.5.�fileNcsdt|t�st|�}t�t�rVt|t�rV�jdk	rVt�dd�}|dkrHd}|��j|�}��|�dS)N�errors�strict)	rQ�
basestring�strrzr[�encodingr.rR�write)�datar{��fprrr��s

��zprint_.<locals>.writeF�sepTzsep must be None or a string�endzend must be None or a stringz$invalid keyword arguments to print()�
� )�popr�stdoutrQr[r~�	TypeError�	enumerate)
rfrgr��want_unicoder�r��arg�newline�spacerbrr�r�print_�sL





r�)rrcOs<|�dtj�}|�dd�}t||�|r8|dk	r8|��dS)Nrz�flushF)�getrr�r��_printr�)rfrgr�r�rrrr�s

zReraise an exception.cs���fdd�}|S)Ncst�����|�}�|_|Sr)rs�wraps�__wrapped__)�f��assigned�updated�wrappedrr�wrapperszwraps.<locals>.wrapperr)r�r�r�r�rr�rr�sr�cs&G��fdd�d��}t�|ddi�S)z%Create a base class with a metaclass.cseZdZ��fdd�ZdS)z!with_metaclass.<locals>.metaclasscs�|�|�Srr)r<r�
this_basesrF��bases�metarr�__new__'sz)with_metaclass.<locals>.metaclass.__new__N)r
rrr�rr�rr�	metaclass%sr��temporary_classr)r5r�)r�r�r�rr�r�with_metaclass sr�cs�fdd�}|S)z6Class decorator for creating a class with a metaclass.csh|j��}|�d�}|dk	r@t|t�r,|g}|D]}|�|�q0|�dd�|�dd��|j|j|�S)N�	__slots__r �__weakref__)r �copyr�rQr~r�r
�	__bases__)r<�	orig_vars�slots�	slots_var�r�rrr�.s


zadd_metaclass.<locals>.wrapperr)r�r�rr�r�
add_metaclass,sr�cCs2tr.d|jkrtd|j��|j|_dd�|_|S)a
    A decorator that defines __unicode__ and __str__ methods under Python 2.
    Under Python 3 it does nothing.

    To support Python 2 and 3 with a single code base, define a __str__ method
    returning text and apply this decorator to the class.
    �__str__zY@python_2_unicode_compatible cannot be applied to %s because it doesn't define __str__().cSs|���d�S)Nzutf-8)�__unicode__rRr	rrr�<lambda>J�z-python_2_unicode_compatible.<locals>.<lambda>)�PY2r �
ValueErrorr
r�r�)r2rrr�python_2_unicode_compatible<s
�
r��__spec__)N)NN)�r�
__future__rrsr^�operatorrr>�
__author__�__version__�version_infor�r)�PY34r~�string_types�int�
integer_typesr5�class_types�	text_type�bytes�binary_type�maxsize�MAXSIZEr}�long�	ClassTyper[�platform�
startswith�objectr�len�
OverflowErrorrrrr'�
ModuleTyper4r:r@r
rrYr7r/rrrQrHr�r��_urllib_parse_moved_attributesr��_urllib_error_moved_attributesr�� _urllib_request_moved_attributesr�!_urllib_response_moved_attributesr�$_urllib_robotparser_moved_attributesrrr!�
_meth_func�
_meth_self�
_func_closure�
_func_code�_func_defaults�
_func_globalsr.r0�	NameErrorr7r:r?r@r=rA�
attrgetter�get_method_function�get_method_self�get_function_closure�get_function_code�get_function_defaults�get_function_globalsrHrJrLrN�methodcallerrOrPrQrUrV�chr�unichr�struct�Struct�pack�int2byte�
itemgetterr`�getitemrcrC�	iterbytesr[r\�BytesIOrdrhri�partialrhr^rWrYrZr.r_rvrnrxr�r��WRAPPER_ASSIGNMENTS�WRAPPER_UPDATESr�r�r�r�rT�__package__�globalsr�r��submodule_search_locations�	meta_pathr�rb�importer�appendrrrr�<module>s�

>





























��


�


�D�






















��


��
































�#�����
��





��



5��
�h�.bytecode of module 'pkg_resources._vendor.six'�u��b.���	h)��N}�(hBT	�@s,ddlZGdd�d�ZdZeee���dS)�Nc@s@eZdZdZddd�Zedd��Zddd	�Zd
d�Zdd
�Z	dS)�VendorImporterz�
    A PEP 302 meta path importer for finding optionally-vendored
    or otherwise naturally-installed packages from root_name.
    �NcCs&||_t|�|_|p|�dd�|_dS)N�extern�_vendor)�	root_name�set�vendored_names�replace�
vendor_pkg)�selfrrr
rr�?/usr/lib/python3/dist-packages/pkg_resources/extern/__init__.py�__init__
s
zVendorImporter.__init__ccs|jdVdVdS)zL
        Search first the vendor package then as a natural package.
        �.�N)r
�rrrr�search_pathszVendorImporter.search_pathcCs8|�|jd�\}}}|rdStt|j|j��s4dS|S)z�
        Return self when fullname starts with root_name and the
        target module is one vendored through this importer.
        rN)�	partitionr�any�map�
startswithr)r�fullname�path�root�base�targetrrr�find_moduleszVendorImporter.find_modulec	Cs�|�|jd�\}}}|jD]^}zD||}t|�tj|}|tj|<|r\tjdkr\tj|=|WStk
rxYqXqtdjft	����dS)zK
        Iterate over the search path to locate and load fullname.
        r)�rz�The '{target}' package is required; normally this is bundled with this package so if you get this warning, consult the packager of your distribution.N)
rrr�
__import__�sys�modules�version_info�ImportError�format�locals)rrrrr�prefix�extant�modrrr�load_module#s"



��zVendorImporter.load_modulecCs|tjkrtj�|�dS)zR
        Install this importer into sys.meta_path if not already present.
        N)r�	meta_path�appendrrrr�install@s
zVendorImporter.install)rN)N)
�__name__�
__module__�__qualname__�__doc__r
�propertyrrr'r*rrrrrs


r)�	packaging�	pyparsing�six�appdirs)rr�namesr+r*rrrr�<module>sD�h�)bytecode of module 'pkg_resources.extern'�u��b.���h)��N}�(hB��@sJddlZddlZddlZe�d�ZdZejdkoDe�eded�dS)�Na
    You are running Setuptools on Python 2, which is no longer
    supported and
    >>> SETUPTOOLS WILL STOP WORKING <<<
    in a subsequent release (no sooner than 2020-04-20).
    Please ensure you are installing
    Setuptools using pip 9.x or later or pin to `setuptools<45`
    in your environment.
    If you have done those things and are still encountering
    this message, please comment in
    https://github.com/pypa/setuptools/issues/1458
    about the steps that led to this unsupported combination.
    z)Setuptools will stop working on Python 2
)�z<************************************************************)�sys�warnings�textwrap�dedent�msg�pre�version_info�warn�rr�8/usr/lib/python3/dist-packages/pkg_resources/py2_warn.py�<module>s

�h�+bytecode of module 'pkg_resources.py2_warn'�u��b.���h)��N}�(hBF�@s`ddlZddlZddlZddlmZd	dd�ZejpLdejkoHdknZerVenej	Z	dS)
�N�)�sixFc
CsHzt�|�Wn4tk
rB}z|r0|jtjkr2�W5d}~XYnXdS)N)�os�makedirs�OSError�errno�EEXIST)�path�exist_ok�exc�r�:/usr/lib/python3/dist-packages/pkg_resources/py31compat.py�_makedirs_31s
r)��)rrr)F)
rr�sys�externrr�PY2�version_info�needs_makedirsrrrrr
�<module>s
��h�-bytecode of module 'pkg_resources.py31compat'�u��b.�� h)��N}�(hB��@sdZddlZddlZddlZddlZddlZddlZddlm	Z	m
Z
ddgZGdd�de�Z
Gdd	�d	e�Zd d
d�Zd!dd
�Zefdd�ZGdd�de�Zd"dd�Zd#dd�Zefdd�Zdd�Zd$dd�Zedk�reej�dk�r�edejd�nejd=eejd�dS)%aZrunpy.py - locating and running Python code using the module namespace

Provides support for locating and running Python scripts using the Python
module namespace instead of the native filesystem.

This allows Python code to play nicely with non-filesystem based PEP 302
importers when locating support scripts as well as when importing modules.
�N)�	read_code�get_importer�
run_module�run_pathc@s(eZdZdZdd�Zdd�Zdd�ZdS)	�_TempModulezCTemporarily replace a module in sys.modules with an empty namespacecCs||_t�|�|_g|_dS�N)�mod_name�types�
ModuleType�module�
_saved_module��selfr�r�/usr/lib/python3.8/runpy.py�__init__sz_TempModule.__init__cCsB|j}z|j�tj|�Wntk
r0YnX|jtj|<|Sr)rr�append�sys�modules�KeyErrorrr
rrr�	__enter__ sz_TempModule.__enter__cGs.|jr|jdtj|j<n
tj|j=g|_dS�Nr)rrrr�r�argsrrr�__exit__)s
z_TempModule.__exit__N)�__name__�
__module__�__qualname__�__doc__rrrrrrrrs	rc@s$eZdZdd�Zdd�Zdd�ZdS)�_ModifiedArgv0cCs||_t�|_|_dSr)�value�object�_saved_value�	_sentinel)rr rrrr1sz_ModifiedArgv0.__init__cCs0|j|jk	rtd��tjd|_|jtjd<dS)NzAlready preserving saved valuer)r"r#�RuntimeErrorr�argvr )rrrrr5sz_ModifiedArgv0.__enter__cGs|j|_|jtjd<dSr)r#r r"rr%rrrrr;sz_ModifiedArgv0.__exit__N)rrrrrrrrrrr0src
	Csn|dk	r|�|�|dkr(d}|}d}	n |j}|j}|j}	|dkrH|j}|j|||	d|||d�t||�|S)z)Helper to run code in nominated namespaceN)r�__file__�
__cached__r�
__loader__�__package__�__spec__)�update�loader�origin�cached�parent�exec)
�code�run_globals�init_globalsr�mod_spec�pkg_name�script_namer,�fnamer.rrr�	_run_code@s*
�
r8c	
Cs^|dkr|n|j}t|��6}t|��"|jj}t|||||||�W5QRXW5QRX|��S)z5Helper to run code in new namespace with sys modifiedN)r-rrr�__dict__r8�copy)	r1r3rr4r5r6r7�temp_module�mod_globalsrrr�_run_module_codeZs�r=c
Cs2|�d�r|d��|�d�\}}}|r�zt|�WnHtk
rz}z*|jdksh|j|krj|�|jd�sj�W5d}~XYnXtj�|�}|dk	r�t|d�s�ddl	m
}dj||d�}|t|��zt
j�|�}WnJttttfk
�r}	z"d}||�|t|	�j|	��|	�W5d}	~	XYnX|dk�r2|d	|��|jdk	�r�|d
k�sT|�d��r\|d��z|d}
t|
|�WS|k
�r�}z"|tjk�r��|d
||f��W5d}~XYnX|j}|dk�r�|d|��z|�|�}Wn2tk
�r}z|t|��|�W5d}~XYnX|dk�r(|d|��|||fS)N�.z#Relative module names not supported�__path__r)�warnz�{mod_name!r} found in sys.modules after import of package {pkg_name!r}, but prior to execution of {mod_name!r}; this may result in unpredictable behaviour)rr5z:Error while finding module specification for {!r} ({}: {})zNo module named %s�__main__z	.__main__z%Cannot use package as __main__ modulez3%s; %r is a package and cannot be directly executedz0%r is a namespace package and cannot be executedzNo code object available for %s)�
startswith�
rpartition�
__import__�ImportError�namerr�get�hasattr�warningsr@�format�RuntimeWarning�	importlib�util�	find_spec�AttributeError�	TypeError�
ValueError�typer�submodule_search_locations�endswith�_get_module_detailsr,�get_code)
r�errorr5�_�e�existingr@�msg�spec�ex�
pkg_main_namer,r1rrrrUhsd
��,
�
� 
rUc@seZdZdZdS)�_ErrorzBError that _run_module_as_main() should report without a tracebackN)rrrrrrrrr_�sr_Tc
Cs�z0|s|dkr t|t�\}}}ntt�\}}}Wn:tk
rj}zdtj|f}t�|�W5d}~XYnXtjdj}|r�|jtj	d<t
||dd|�S)a�Runs the designated module in the __main__ namespace

       Note that the executed module will have full access to the
       __main__ namespace. If this is not desirable, the run_module()
       function should be used to run the module code in a fresh namespace.

       At the very least, these variables in __main__ will be overwritten:
           __name__
           __file__
           __cached__
           __loader__
           __package__
    rAz%s: %sNr)rUr_�_get_main_module_detailsr�
executable�exitrr9r-r%r8)r�
alter_argvr4r1�excr[�main_globalsrrr�_run_module_as_main�s�rfFcCs@t|�\}}}|dkr|}|r,t||||�St|i|||�SdS)znExecute a module's code without importing it

       Returns the resulting top level namespace dictionary
    N)rUr=r8)rr3�run_name�	alter_sysr4r1rrrr�sc
Cs�d}tj|}tj|=z\zt|�WW�NStk
rn}z*|t|�kr\|d|tjdf�|��W5d}~XYnXW5|tj|<XdS)NrAzcan't find %r module in %rr)rrrUrE�str�path)rW�	main_name�
saved_mainrdrrrr`�s
��r`c	Csftj�t�|��}t�|��}t|�}W5QRX|dkr^t�|��}t|��|d�}W5QRX||fS)Nr0)	�osrj�abspath�fsdecode�io�	open_coder�compile�read)rgr7�decoded_path�fr1rrr�_get_code_from_file�srvcCs$|dkrd}|�d�d}t|�}d}t|�jdkrFt|�jdkrFd}t|td��sX|rxt||�\}}t|||||d	�Stj	�
d|�znt
�\}}	}t|��P}
t|��<|
jj}t|||||	|���W5QR�W5QR�W�SQRXW5QRXW5ztj	�|�Wntk
�rYnXXdS)
a_Execute code located at the specified filesystem location

       Returns the resulting top level namespace dictionary

       The file path may refer directly to a Python script (i.e.
       one that could be directly executed with execfile) or else
       it may refer to a zipfile or directory containing a top
       level __main__.py script.
    Nz
<run_path>r>rF�imp�NullImporterT)r5r6)rCrrRrr�
isinstancervr=rrj�insert�removerQr`rrrr9r8r:)�	path_namer3rgr5�importer�is_NullImporterr1r7rr4r;r<rrrr�s<
�
��8rA�z!No module specified for execution)�file)NNNNN)NNNNN)T)NNF)NN)rr�importlib.machineryrL�importlib.utilrpr	rm�pkgutilrr�__all__r!rrr8r=rErU�	Exceptionr_rfrr`rvrr�lenr%�print�stderrrrrr�<module>sN��
�
:
�

1
�h�bytecode of module 'runpy'�u��b.��4Ch)��N}�(hBC�@s&dZddlZddlZddlZddlZddlZejejgada	da
dadd�Zdd�Z
dd�Zd	d
�Zdd�Zd2d
d�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd3dd�Zd4dd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Z d-d.�Z!ej"j#�s
e!�d/d0�Z$e%d1k�r"e$�dS)5a�Append module search paths for third-party packages to sys.path.

****************************************************************
* This module is automatically imported during initialization. *
****************************************************************

This will append site-specific paths to the module search path.  On
Unix (including Mac OSX), it starts with sys.prefix and
sys.exec_prefix (if different) and appends
lib/python3/dist-packages.
On other platforms (such as Windows), it tries each of the
prefixes directly, as well as with lib/site-packages appended.  The
resulting directories, if they exist, are appended to sys.path, and
also inspected for path configuration files.

For Debian and derivatives, this sys.path is augmented with directories
for packages distributed within the distribution. Local addons go
into /usr/local/lib/python<version>/dist-packages, Debian addons
install into /usr/lib/python3/dist-packages.
/usr/lib/python<version>/site-packages is not used.

If a file named "pyvenv.cfg" exists one directory above sys.executable,
sys.prefix and sys.exec_prefix are set to that directory and
it is also checked for site-packages (sys.base_prefix and
sys.base_exec_prefix will always be the "real" prefixes of the Python
installation). If "pyvenv.cfg" (a bootstrap configuration file) contains
the key "include-system-site-packages" set to anything other than "false"
(case-insensitive), the system-level prefixes will still also be
searched for site-packages; otherwise they won't.

All of the resulting site-specific directories, if they exist, are
appended to sys.path, and also inspected for path configuration
files.

A path configuration file is a file whose name has the form
<package>.pth; its contents are additional directories (one per line)
to be added to sys.path.  Non-existing directories (or
non-directories) are never added to sys.path; no directory is added to
sys.path more than once.  Blank lines and lines beginning with
'#' are skipped. Lines starting with 'import' are executed.

For example, suppose sys.prefix and sys.exec_prefix are set to
/usr/local and there is a directory /usr/local/lib/python2.5/site-packages
with three subdirectories, foo, bar and spam, and two path
configuration files, foo.pth and bar.pth.  Assume foo.pth contains the
following:

  # foo package configuration
  foo
  bar
  bletch

and bar.pth contains:

  # bar package configuration
  bar

Then the following directories are added to sys.path, in this order:

  /usr/local/lib/python2.5/site-packages/bar
  /usr/local/lib/python2.5/site-packages/foo

Note that bletch is omitted because it doesn't exist; bar precedes foo
because bar.pth comes alphabetically before foo.pth; and spam is
omitted because it is not mentioned in either path configuration file.

The readline module is also automatically configured to enable
completion for systems that support it.  This can be overridden in
sitecustomize, usercustomize or PYTHONSTARTUP.  Starting Python in
isolated mode (-I) disables automatic readline configuration.

After these operations, an attempt is made to import a module
named sitecustomize, which can perform arbitrary additional
site-specific customizations.  If this import fails with an
ImportError exception, it is silently ignored.
�NcGsBtjj|�}ztj�|�}Wntk
r0YnX|tj�|�fS�N)�os�path�join�abspath�OSError�normcase)�paths�dir�r�/usr/lib/python3.8/site.py�makepathasr
cCs�ttj���D]~}tt|dd�dd�dkr,qztj�|j�|_Wnt	t
tfk
rZYnXztj�|j�|_Wqt	t
tfk
r�YqXqdS)zESet all module __file__ and __cached__ attributes to an absolute path�
__loader__N�
__module__)�_frozen_importlib�_frozen_importlib_external)
�set�sys�modules�values�getattrrrr�__file__�AttributeErrorr�	TypeError�
__cached__)�mrrr�	abs_pathsjs�rcCsPg}t�}tjD],}t|�\}}||kr|�|�|�|�q|tjdd�<|S)zK Remove duplicate entries from sys.path along with making them
    absoluteN)rrrr
�append�add)�L�known_pathsr
�dircaserrr�removeduppathszs

r"c	CsVt�}tjD]D}z&tj�|�r4t|�\}}|�|�Wqtk
rNYqYqXq|S)zEReturn a set containing all existing file system items from sys.path.)rrrr�existsr
rr)�d�item�_�itemcaserrr�_init_pathinfo�s
r(cCsr|dkrt�}d}nd}tj�||�}zt�t�|��}Wntk
rPYdSX|��t|�D]�\}}|�	d�rvqbzZ|�	d�r�t
|�Wqb|��}t||�\}}	|	|kr�tj�
|�r�tj�|�|�|	�Wqbtk
�rVtd�|d|�tjd�d	dl}
|
jt���D](}|��D]}td
|tjd��q�qtdtjd�Y�qZYqbXqbW5QRX|�rnd}|S)z�Process a .pth file within the site-packages directory:
       For each line in the file, either combine it with sitedir to a path
       and add that to known_paths, or execute it if it starts with 'import '.
    NTF�#)zimport zimport	z"Error processing line {:d} of {}:
�)�filerz  z
Remainder of file ignored)r(rrr�io�
TextIOWrapper�	open_coder�	enumerate�
startswith�exec�rstripr
r#rrr�	Exception�print�format�stderr�	traceback�format_exception�exc_info�
splitlines)�sitedir�namer �reset�fullname�f�n�liner
r!r7�recordrrr�
addpackage�sF

�rCcCs�|dkrt�}d}nd}t|�\}}||krBtj�|�|�|�zt�|�}Wntk
rfYdSXdd�|D�}t	|�D]}t
|||�q~|r�d}|S)zTAdd 'sitedir' argument to sys.path if missing and handle .pth files in
    'sitedir'NTFcSsg|]}|�d�r|�qS)z.pth)�endswith)�.0r<rrr�
<listcomp>�s
zaddsitedir.<locals>.<listcomp>)r(r
rrrrr�listdirr�sortedrC)r;r r=�sitedircase�namesr<rrr�
addsitedir�s$
rKcCs`tjjrdSttd�r4ttd�r4t��t��kr4dSttd�r\ttd�r\t��t��kr\dSdS)a,Check if user site directory is safe for inclusion

    The function tests for the command line flag (including environment var),
    process uid/gid equal to effective uid/gid.

    None: Disabled for security reasons
    False: Disabled by user (command line option)
    True: Safe and enabled
    F�getuid�geteuidN�getgid�getegidT)	r�flags�no_user_site�hasattrrrMrLrOrNrrrr�check_enableusersite�s
rScCsztj�dd�}|r|Sdd�}tjdkrBtj�d�p6d}||d�Stjdkrptjrp|dd	tjd
tjdd��S|dd�S)
N�PYTHONUSERBASEcWstj�tjj|��Sr)rr�
expanduserr)�argsrrr�joinusersz_getuserbase.<locals>.joinuser�nt�APPDATA�~�Python�darwin�Libraryz%d.%d�z.local)r�environ�getr<r�platform�
_framework�version_info)�env_baserW�baserrr�_getuserbase�s


�rfcCsdtj}tjdkr,|�d|d�|d�d�StjdkrFtjrF|�d�S|�d|d�d	|d�d
�S)NrXz\Pythonrr*z\site-packagesr\z/lib/python/site-packagesz/lib/python�.z/site-packages)rrcrr<rarb)�userbase�versionrrr�	_get_paths

rjcCstdkrt�atS)z�Returns the `user base` directory path.

    The `user base` directory can be used to store data. If the global
    variable ``USER_BASE`` is not initialized yet, this function will also set
    it.
    N)�	USER_BASErfrrrr�getuserbasesrlcCst�}tdkrt|�atS)z�Returns the user-specific site-packages directory path.

    If the global variable ``USER_SITE`` is not initialized yet, this
    function will also set it.
    N)rl�	USER_SITErj)rhrrr�getusersitepackages)srncCs$t�}tr tj�|�r t||�|S)z�Add a per user site-package to sys.path

    Each user has its own python directory with site-packages in the
    home directory.
    )rn�ENABLE_USER_SITErr�isdirrK)r �	user_siterrr�addusersitepackages7s
rrcCsg}t�}|dkrt}|D]�}|r||kr,q|�|�tjdkr�dtjksVtjtjkr||�	tj
�|ddtjdd�d��|�	tj
�|ddtjdd�d	��|�	tj
�|dd
d	��|�	tj
�|ddtjdd�d	��q|�	|�|�	tj
�|dd��q|S)aReturns a list containing all global site-packages directories.

    For each directory present in ``prefixes`` (or the global ``PREFIXES``),
    this function will find its `site-packages` subdirectory depending on the
    system environment, and will return a list of full paths.
    N�/ZVIRTUAL_ENV�lib�python�z
site-packagesz	local/libz
dist-packages�python3)
r�PREFIXESrr�sepr_r�base_prefix�prefixrrrri)�prefixes�sitepackages�seenr{rrr�getsitepackagesEs:

����
rcCs(t|�D]}tj�|�rt||�q|S)zAdd site-packages to sys.path)rrrrprK)r r|r;rrr�addsitepackagesksr�cCs4tjdkrd}nd}t�d|�t_t�d|�t_dS)z�Define new builtins 'quit' and 'exit'.

    These are objects which make the interpreter exit when called.
    The repr of each object contains a hint at how it works.

    �\zCtrl-Z plus ReturnzCtrl-D (i.e. EOF)�quit�exitN)rry�
_sitebuiltins�Quitter�builtinsr�r�)�eofrrr�setquitss

r�cCs�t�dtj�t_tjdd�dkr2t�dd�t_nt�dd�t_gg}}ttd�r�tj	�
tj�}|�d	d
g�|�tj	�
|tj�|tjg�t�dd||�t_dS)
z)Set 'copyright' and 'credits' in builtins�	copyrightN��java�creditsz?Jython is maintained by the Jython developers (www.jython.org).z�    Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
    for supporting Python development.  See www.python.org for more information.rzLICENSE.txtZLICENSE�licensez'See https://www.python.org/psf/license/)r��_Printerrr�r�rar�rRrr�dirnamer�extendr�pardir�curdirr�)�files�dirs�hererrr�setcopyright�s$�

�r�cCst��t_dSr)r��_Helperr��helprrrr�	sethelper�sr�cCsdd�}|t_dS)ajEnable default readline configuration on interactive prompts, by
    registering a sys.__interactivehook__.

    If the readline module can be imported, the hook will set the Tab key
    as completion key and register ~/.python_history as history file.
    This can be overridden in the sitecustomize or usercustomize module,
    or in a PYTHONSTARTUP file.
    cs�ddl}zddl�ddl}Wntk
r2YdSXt�dd�}|dk	r\d|kr\��d�n
��d�z���Wntk
r�YnX���dkr�t	j
�t	j
�d�d��z��
��Wntk
r�YnX��fd	d
�}|�|�dS)Nr�__doc__�Zlibeditzbind ^I rl_completez
tab: completerZz.python_historycs(z����Wntk
r"YnXdSr)�write_history_filerr��history�readlinerr�
write_history�szCenablerlcompleter.<locals>.register_readline.<locals>.write_history)�atexitr��rlcompleter�ImportErrorr�parse_and_bind�read_init_filer�get_current_history_lengthrrrrU�read_history_file�register)r�r��readline_docr�rr�r�register_readline�s0
�z,enablerlcompleter.<locals>.register_readlineN)r�__interactivehook__)r�rrr�enablerlcompleter�s	0r�c	CsHtj}tjdkr*d|kr*tjd}t_ntj}tj�tj�|��\}}tj�	|�}dt_
d}dd�tj�||�tj�||�fD�}|�rD|d}d}	t|dd	��\}
|
D]P}d
|kr�|�
d
�\}}}
|����}|
��}
|dkr�|
��}	q�|dkr�|
t_
q�W5QRX|t_t_t|tjg�|	dk�r8t�dtj�ntjgad
a|S)Nr\Z__PYVENV_LAUNCHER__z
pyvenv.cfgcSsg|]}tj�|�r|�qSr)rr�isfile)rE�conffilerrrrF�s�zvenv.<locals>.<listcomp>r�truezutf-8)�encoding�=zinclude-system-site-packages�homeF)rr_rra�_base_executable�
executabler�splitrr��_homer�open�	partition�strip�lowerr{�exec_prefixr�rx�insertro)r �envr��exe_dirr&�site_prefix�
conf_basename�candidate_confs�virtual_conf�system_siter?rA�key�valuerrr�venv�sB��

r�c
Cs�zBzddl}Wn0tk
r>}z|jdkr,n�W5d}~XYnXWnRtk
r�}z4tjjrltjt���ntj	�
d|jj|f�W5d}~XYnXdS)z,Run custom site specific code, if available.rN�
sitecustomizez@Error in sitecustomize; set PYTHONVERBOSE for traceback:
%s: %s
)
r�r�r<r3rrP�verbose�
excepthookr9r6�write�	__class__�__name__)r��exc�errrrr�execsitecustomize
s

��r�c
Cs�zBzddl}Wn0tk
r>}z|jdkr,n�W5d}~XYnXWnRtk
r�}z4tjjrltjt���ntj	�
d|jj|f�W5d}~XYnXdS)z,Run custom user specific code, if available.rN�
usercustomizez@Error in usercustomize; set PYTHONVERBOSE for traceback:
%s: %s
)
r�r�r<r3rrPr�r�r9r6r�r�r�)r�r�r�rrr�execusercustomize!s

��r�cCs~tjdd�}t�}|tjkr$t�t|�}tdkr:t�at|�}t|�}t	�t
�t�tjj
sjt�t�trzt�dS)z�Add standard site-specific directories to the module search path.

    This function is called automatically when this module is imported,
    unless the python interpreter was started with the -S flag.
    N)rrr"rr�rorSrrr�r�r�r�rP�isolatedr�r�r�)�	orig_pathr rrr�main5s"
r�cCs\d}tjdd�}|s�t�}t�}td�tjD]}td|f�q0td�td|tj�|�rbdndf�td	|tj�|�r�dndf�td
t�t�	d�g}d|kr�|�
t�d
|kr�|�
t�|�r(ttj
�|��tr�t�	d�n6tdk�rt�	d�n tdk�rt�	d�n
t�	d�n0ddl}t|�|tjdtj
f��t�	d�dS)Na�    %s [--user-base] [--user-site]

    Without arguments print some useful information
    With arguments print the value of USER_BASE and/or USER_SITE separated
    by '%s'.

    Exit codes with --user-base or --user-site:
      0 - user site directory is enabled
      1 - user site directory is disabled by user
      2 - uses site directory is disabled by super user
          or for security reasons
     >2 - unknown error
    r*zsys.path = [z    %r,�]zUSER_BASE: %r (%s)r#z
doesn't existzUSER_SITE: %r (%s)zENABLE_USER_SITE: %rrz--user-basez--user-siteFr^rv�
)r�argvrlrnr4rrrpror�rrkrm�pathsepr�textwrap�dedent)r�rV�	user_baserqr
�bufferr�rrr�_scriptWsD
��




r��__main__)N)N)N)&r�rrr�r�r,r{r�rxrormrkr
rr"r(rCrKrSrfrjrlrnrrrr�r�r�r�r�r�r�r�r�rP�no_siter�r�rrrr�<module>sHM	
*
 

&
;4
3
�h�bytecode of module 'site'�u��b.��h)��N}�(hC��@s.zddlZWnek
r Yn
Xe��dS)�N)�apport_python_hook�ImportError�install�rr�#/usr/lib/python3.8/sitecustomize.py�<module>s�h�"bytecode of module 'sitecustomize'�u��b.

Youez - 2016 - github.com/yon3zu
LinuXploit