Your IP : 216.73.216.86


Current Path : /home/emeraadmin/public_html/4d695/
Upload File :
Current File : /home/emeraadmin/public_html/4d695/concurrent.zip

PKw}�\�)d�~~)__pycache__/__init__.cpython-36.opt-1.pycnu�[���3


 \&�@sdS)N�rrr�+/usr/lib64/python3.6/concurrent/__init__.py�<module>sPKw}�\�)d�~~)__pycache__/__init__.cpython-36.opt-2.pycnu�[���3


 \&�@sdS)N�rrr�+/usr/lib64/python3.6/concurrent/__init__.py�<module>sPKw}�\�)d�~~#__pycache__/__init__.cpython-36.pycnu�[���3


 \&�@sdS)N�rrr�+/usr/lib64/python3.6/concurrent/__init__.py�<module>sPKw}�\�ߊނ�1futures/__pycache__/__init__.cpython-36.opt-1.pycnu�[���3


 \ �@sPdZdZddlmZmZmZmZmZmZm	Z	m
Z
mZddlm
Z
ddlmZdS)z?Execute computations asynchronously using threads or processes.z"Brian Quinlan (brian@sweetapp.com)�)	�FIRST_COMPLETED�FIRST_EXCEPTION�
ALL_COMPLETED�CancelledError�TimeoutError�Future�Executor�wait�as_completed)�ProcessPoolExecutor)�ThreadPoolExecutorN)�__doc__�
__author__Zconcurrent.futures._baserrrrrrrr	r
Zconcurrent.futures.processrZconcurrent.futures.threadr�rr�3/usr/lib64/python3.6/concurrent/futures/__init__.py�<module>s,	PKw}�\�K`�221futures/__pycache__/__init__.cpython-36.opt-2.pycnu�[���3


 \ �@sLdZddlmZmZmZmZmZmZmZm	Z	m
Z
ddlmZddl
mZdS)z"Brian Quinlan (brian@sweetapp.com)�)	�FIRST_COMPLETED�FIRST_EXCEPTION�
ALL_COMPLETED�CancelledError�TimeoutError�Future�Executor�wait�as_completed)�ProcessPoolExecutor)�ThreadPoolExecutorN)�
__author__Zconcurrent.futures._baserrrrrrrr	r
Zconcurrent.futures.processrZconcurrent.futures.threadr�rr�3/usr/lib64/python3.6/concurrent/futures/__init__.py�<module>s,	PKw}�\�ߊނ�+futures/__pycache__/__init__.cpython-36.pycnu�[���3


 \ �@sPdZdZddlmZmZmZmZmZmZm	Z	m
Z
mZddlm
Z
ddlmZdS)z?Execute computations asynchronously using threads or processes.z"Brian Quinlan (brian@sweetapp.com)�)	�FIRST_COMPLETED�FIRST_EXCEPTION�
ALL_COMPLETED�CancelledError�TimeoutError�Future�Executor�wait�as_completed)�ProcessPoolExecutor)�ThreadPoolExecutorN)�__doc__�
__author__Zconcurrent.futures._baserrrrrrrr	r
Zconcurrent.futures.processrZconcurrent.futures.threadr�rr�3/usr/lib64/python3.6/concurrent/futures/__init__.py�<module>s,	PKw}�\GꂚP�P.futures/__pycache__/_base.cpython-36.opt-1.pycnu�[���3


 \�R�
@sPdZddlZddlZddlZddlZdZdZdZdZdZ	dZ
d	Zd
ZdZ
e	e
eee
gZe	de
d
edede
diZejd�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd �d e�Zd!d"�Zd#d$�Zd/d%d&�Zejd'd(�Z defd)d*�Z!Gd+d,�d,e�Z"Gd-d.�d.e�Z#dS)0z"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�0/usr/lib64/python3.6/concurrent/futures/_base.pyr,src@seZdZdZdS)�CancelledErrorzThe Future was cancelled.N)rrrrrrrrr0src@seZdZdZdS)�TimeoutErrorz*The operation exceeded the given deadline.N)rrrrrrrrr4src@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)�_Waiterz;Provides the event that wait() and as_completed() block on.cCstj�|_g|_dS)N)�	threadingZEvent�event�finished_futures)�selfrrr�__init__:s
z_Waiter.__init__cCs|jj|�dS)N)r�append)r�futurerrr�
add_result>sz_Waiter.add_resultcCs|jj|�dS)N)rr)rrrrr�
add_exceptionAsz_Waiter.add_exceptioncCs|jj|�dS)N)rr)rrrrr�
add_cancelledDsz_Waiter.add_cancelledN)rrrrrr r!r"rrrrr8s
rcsDeZdZdZ�fdd�Z�fdd�Z�fdd�Z�fdd	�Z�ZS)
�_AsCompletedWaiterzUsed by as_completed().cstt|�j�tj�|_dS)N)�superr#rr�Lock�lock)r)�	__class__rrrJsz_AsCompletedWaiter.__init__c
s0|j� tt|�j|�|jj�WdQRXdS)N)r&r$r#r r�set)rr)r'rrr Nsz_AsCompletedWaiter.add_resultc
s0|j� tt|�j|�|jj�WdQRXdS)N)r&r$r#r!rr()rr)r'rrr!Ssz _AsCompletedWaiter.add_exceptionc
s0|j� tt|�j|�|jj�WdQRXdS)N)r&r$r#r"rr()rr)r'rrr"Xsz _AsCompletedWaiter.add_cancelled)	rrrrrr r!r"�
__classcell__rr)r'rr#Gs
r#cs8eZdZdZ�fdd�Z�fdd�Z�fdd�Z�ZS)�_FirstCompletedWaiterz*Used by wait(return_when=FIRST_COMPLETED).cst�j|�|jj�dS)N)r$r rr()rr)r'rrr `sz _FirstCompletedWaiter.add_resultcst�j|�|jj�dS)N)r$r!rr()rr)r'rrr!dsz#_FirstCompletedWaiter.add_exceptioncst�j|�|jj�dS)N)r$r"rr()rr)r'rrr"hsz#_FirstCompletedWaiter.add_cancelled)rrrrr r!r"r)rr)r'rr*]sr*csLeZdZdZ�fdd�Zdd�Z�fdd�Z�fdd	�Z�fd
d�Z�Z	S)�_AllCompletedWaiterz<Used by wait(return_when=FIRST_EXCEPTION and ALL_COMPLETED).cs$||_||_tj�|_t�j�dS)N)�num_pending_calls�stop_on_exceptionrr%r&r$r)rr,r-)r'rrros
z_AllCompletedWaiter.__init__c
Cs4|j�$|jd8_|js&|jj�WdQRXdS)N�)r&r,rr()rrrr�_decrement_pending_callsusz,_AllCompletedWaiter._decrement_pending_callscst�j|�|j�dS)N)r$r r/)rr)r'rrr {sz_AllCompletedWaiter.add_resultcs*t�j|�|jr|jj�n|j�dS)N)r$r!r-rr(r/)rr)r'rrr!sz!_AllCompletedWaiter.add_exceptioncst�j|�|j�dS)N)r$r"r/)rr)r'rrr"�sz!_AllCompletedWaiter.add_cancelled)
rrrrrr/r r!r"r)rr)r'rr+lsr+c@s(eZdZdZdd�Zdd�Zdd�ZdS)	�_AcquireFutureszDA context manager that does an ordered acquire of Future conditions.cCst|td�|_dS)N)�key)�sorted�id�futures)rr4rrrr�sz_AcquireFutures.__init__cCsx|jD]}|jj�qWdS)N)r4�
_condition�acquire)rrrrr�	__enter__�sz_AcquireFutures.__enter__cGsx|jD]}|jj�qWdS)N)r4r5�release)r�argsrrrr�__exit__�sz_AcquireFutures.__exit__N)rrrrrr7r:rrrrr0�sr0cCs�|tkrt�}nZ|tkr t�}nJtdd�|D��}|tkrHt|dd�}n"|tkr^t|dd�}ntd|��x|D]}|j	j
|�qpW|S)Ncss|]}|jttgkVqdS)N)�_stater	r
)�.0�frrr�	<genexpr>�sz._create_and_install_waiters.<locals>.<genexpr>T)r-FzInvalid return condition: %r)rr#rr*�sumrr+r�
ValueError�_waitersr)�fs�return_when�waiterZ
pending_countr=rrr�_create_and_install_waiters�s
rEc	csXxR|rR|d}x|D]}|j|�qW|j�|jj|�WdQRX~|j�VqWdS)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.
    r.N���)�remover5rA�pop)rBrD�ref_collectr=Zfutures_setrrr�_yield_finished_futures�s
rJc	csJ|dk	r|tj�}t|�}t|�}t|��*tdd�|D��}||}t|t�}WdQRXt|�}z�t|||fd�EdHx�|�r|dkr�d}n(|tj�}|dkr�t	dt|�|f��|j
j|�|j�|j
}g|_
|j
j�WdQRX|j�t||||fd�EdHq~WWdx,|D]$}|j�|jj|�WdQRX�qWXdS)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 |]}|jttgkr|VqdS)N)r;r	r
)r<r=rrrr>�szas_completed.<locals>.<genexpr>)rIrz%d (of %d) futures unfinished)�time�	monotonicr(�lenr0rEr�listrJrr�waitr&r�clear�reverser5rArG)	rB�timeout�end_timeZ
total_futuresrrrDZwait_timeoutr=rrr�as_completed�s@

rT�DoneAndNotDoneFuturesz
done not_donecCs�t|���tdd�|D��}t|�|}|tkr>|r>t||�S|tkrf|rftdd�|D��rft||�St|�t|�kr�t||�St||�}WdQRX|jj	|�x*|D]"}|j
�|jj|�WdQRXq�W|j
|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 |]}|jttgkr|VqdS)N)r;r	r
)r<r=rrrr>szwait.<locals>.<genexpr>css(|] }|j�r|j�dk	r|VqdS)N)r
�	exception)r<r=rrrr>$sN)r0r(rrUr�anyrMrErrOr5rArG�updater)rBrRrC�doneZnot_donerDr=rrrrOs"




rOc@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,tj�|_t|_d|_d|_g|_g|_dS)z8Initializes the future. Should not be called by clients.N)	rZ	Conditionr5rr;�_result�
_exceptionrA�_done_callbacks)rrrrr8s
zFuture.__init__cCsBx<|jD]2}y||�Wqtk
r8tjd|�YqXqWdS)Nz!exception calling callback for %r)r]�	Exception�LOGGERrV)r�callbackrrr�_invoke_callbacksAs
zFuture._invoke_callbackscCs�|j�v|jtkr`|jr<d|jjt|�t|j|jjjfSd|jjt|�t|j|jjjfSd|jjt|�t|jfSQRXdS)Nz<%s at %#x state=%s raised %s>z <%s at %#x state=%s returned %s>z<%s at %#x state=%s>)	r5r;r
r\r'rr3�_STATE_TO_DESCRIPTION_MAPr[)rrrr�__repr__Hs"
zFuture.__repr__c
CsR|j�:|jttgkrdS|jttgkr,dSt|_|jj�WdQRX|j�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.
        FTN)r5r;rr
rr	�
notify_allra)rrrr�cancel\sz
Future.cancelc
Cs |j�|jttgkSQRXdS)z(Return True if the future was cancelled.N)r5r;rr	)rrrrr
oszFuture.cancelledc	Cs|j�|jtkSQRXdS)z1Return True if the future is currently executing.N)r5r;r)rrrrrtszFuture.runningcCs"|j�|jtttgkSQRXdS)z>Return True of the future was cancelled or finished executing.N)r5r;rr	r
)rrrrrYyszFuture.donecCs|jr|j�n|jSdS)N)r\r[)rrrrZ__get_result~szFuture.__get_resultcCs>|j�&|jtttgkr(|jj|�dSWdQRX||�dS)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.
        N)r5r;rr	r
r]r)r�fnrrr�add_done_callback�s
zFuture.add_done_callbackNc
Csx|j�h|jttgkrt��n|jtkr0|j�S|jj|�|jttgkrRt��n|jtkrd|j�St��WdQRXdS)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)	r5r;rr	rr
�_Future__get_resultrOr)rrRrrr�result�s

z
Future.resultc
Cst|j�d|jttgkrt��n|jtkr.|jS|jj|�|jttgkrPt��n|jtkr`|jSt��WdQRXdS)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)	r5r;rr	rr
r\rOr)rrRrrrrV�s

zFuture.exceptioncCst|j�d|jtkr6t|_x|jD]}|j|�q WdS|jtkrJt|_dStj	dt
|�|j�td��WdQRXdS)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)r5r;rr	rAr"rrr_Zcriticalr3�RuntimeError)rrDrrr�set_running_or_notify_cancel�s

z#Future.set_running_or_notify_cancelc
CsN|j�6||_t|_x|jD]}|j|�qW|jj�WdQRX|j�dS)z�Sets the return value of work associated with the future.

        Should only be used by Executor implementations and unit tests.
        N)r5r[r
r;rAr rdra)rrirDrrr�
set_result�szFuture.set_resultc
CsN|j�6||_t|_x|jD]}|j|�qW|jj�WdQRX|j�dS)z�Sets the result of the future as being the given exception.

        Should only be used by Executor implementations and unit tests.
        N)r5r\r
r;rAr!rdra)rrVrDrrr�
set_exceptionszFuture.set_exception)N)N)rrrrrrarcrer
rrYrhrgrirVrkrlrmrrrrrZ5s	

"(
rZc@sBeZdZdZdd�Zddd�dd�Zdd
d�Zdd
�Zdd�ZdS)�ExecutorzCThis is an abstract base class for concrete asynchronous executors.cOs
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.
        N)�NotImplementedError)rrfr9�kwargsrrr�submits	zExecutor.submitNr.)rR�	chunksizecsB�dk	r�tj����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)rq)r<r9)rfrrr�
<listcomp>?sz Executor.map.<locals>.<listcomp>c3sdzF�j�x8�rB�dkr(�j�j�Vq�j�j�tj��VqWWdx�D]}|j�qNWXdS)N)rQrHrirKrLre)r)rSrBrRrr�result_iteratorCs 
z%Executor.map.<locals>.result_iterator)rKrL�zip)rrfrRrr�	iterablesrtr)rSrfrBrrRr�map&s

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)rrOrrr�shutdownRszExecutor.shutdowncCs|S)Nr)rrrrr7_szExecutor.__enter__cCs|jdd�dS)NT)rOF)rx)r�exc_typeZexc_valZexc_tbrrrr:bszExecutor.__exit__)T)	rrrrrqrwrxr7r:rrrrrns,

rn)N)$�
__author__�collectionsZloggingrrKrrrrrrrr	r
Z_FUTURE_STATESrbZ	getLoggerr_r^rrr�objectrr#r*r+r0rErJrT�
namedtuplerUrOrZrnrrrr�<module>sR

>1dPKw}�\�I}��2�2.futures/__pycache__/_base.cpython-36.opt-2.pycnu�[���3


 \�R�
@sPdZddlZddlZddlZddlZdZdZdZdZdZ	dZ
d	Zd
ZdZ
e	e
eee
gZe	de
d
edede
diZejd�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd �d e�Zd!d"�Zd#d$�Zd/d%d&�Zejd'd(�Z defd)d*�Z!Gd+d,�d,e�Z"Gd-d.�d.e�Z#dS)0z"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@seZdZdS)�ErrorN)�__name__�
__module__�__qualname__�rr�0/usr/lib64/python3.6/concurrent/futures/_base.pyr,src@seZdZdS)�CancelledErrorN)rrrrrrrr0src@seZdZdS)�TimeoutErrorN)rrrrrrrr4src@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
�_WaitercCstj�|_g|_dS)N)�	threadingZEvent�event�finished_futures)�selfrrr�__init__:s
z_Waiter.__init__cCs|jj|�dS)N)r�append)r�futurerrr�
add_result>sz_Waiter.add_resultcCs|jj|�dS)N)rr)rrrrr�
add_exceptionAsz_Waiter.add_exceptioncCs|jj|�dS)N)rr)rrrrr�
add_cancelledDsz_Waiter.add_cancelledN)rrrrrr r!rrrrr8srcs@eZdZ�fdd�Z�fdd�Z�fdd�Z�fdd�Z�ZS)	�_AsCompletedWaitercstt|�j�tj�|_dS)N)�superr"rr�Lock�lock)r)�	__class__rrrJsz_AsCompletedWaiter.__init__c
s0|j� tt|�j|�|jj�WdQRXdS)N)r%r#r"rr�set)rr)r&rrrNsz_AsCompletedWaiter.add_resultc
s0|j� tt|�j|�|jj�WdQRXdS)N)r%r#r"r rr')rr)r&rrr Ssz _AsCompletedWaiter.add_exceptionc
s0|j� tt|�j|�|jj�WdQRXdS)N)r%r#r"r!rr')rr)r&rrr!Xsz _AsCompletedWaiter.add_cancelled)rrrrrr r!�
__classcell__rr)r&rr"Gsr"cs4eZdZ�fdd�Z�fdd�Z�fdd�Z�ZS)�_FirstCompletedWaitercst�j|�|jj�dS)N)r#rrr')rr)r&rrr`sz _FirstCompletedWaiter.add_resultcst�j|�|jj�dS)N)r#r rr')rr)r&rrr dsz#_FirstCompletedWaiter.add_exceptioncst�j|�|jj�dS)N)r#r!rr')rr)r&rrr!hsz#_FirstCompletedWaiter.add_cancelled)rrrrr r!r(rr)r&rr)]sr)csHeZdZ�fdd�Zdd�Z�fdd�Z�fdd�Z�fd	d
�Z�ZS)�_AllCompletedWaitercs$||_||_tj�|_t�j�dS)N)�num_pending_calls�stop_on_exceptionrr$r%r#r)rr+r,)r&rrros
z_AllCompletedWaiter.__init__c
Cs4|j�$|jd8_|js&|jj�WdQRXdS)N�)r%r+rr')rrrr�_decrement_pending_callsusz,_AllCompletedWaiter._decrement_pending_callscst�j|�|j�dS)N)r#rr.)rr)r&rrr{sz_AllCompletedWaiter.add_resultcs*t�j|�|jr|jj�n|j�dS)N)r#r r,rr'r.)rr)r&rrr sz!_AllCompletedWaiter.add_exceptioncst�j|�|j�dS)N)r#r!r.)rr)r&rrr!�sz!_AllCompletedWaiter.add_cancelled)	rrrrr.rr r!r(rr)r&rr*ls
r*c@s$eZdZdd�Zdd�Zdd�ZdS)�_AcquireFuturescCst|td�|_dS)N)�key)�sorted�id�futures)rr3rrrr�sz_AcquireFutures.__init__cCsx|jD]}|jj�qWdS)N)r3�
_condition�acquire)rrrrr�	__enter__�sz_AcquireFutures.__enter__cGsx|jD]}|jj�qWdS)N)r3r4�release)r�argsrrrr�__exit__�sz_AcquireFutures.__exit__N)rrrrr6r9rrrrr/�sr/cCs�|tkrt�}nZ|tkr t�}nJtdd�|D��}|tkrHt|dd�}n"|tkr^t|dd�}ntd|��x|D]}|j	j
|�qpW|S)Ncss|]}|jttgkVqdS)N)�_stater	r
)�.0�frrr�	<genexpr>�sz._create_and_install_waiters.<locals>.<genexpr>T)r,FzInvalid return condition: %r)rr"rr)�sumrr*r�
ValueError�_waitersr)�fs�return_when�waiterZ
pending_countr<rrr�_create_and_install_waiters�s
rDc	csXxR|rR|d}x|D]}|j|�qW|j�|jj|�WdQRX~|j�VqWdS)Nr-���)�remover4r@�pop)rArC�ref_collectr<Zfutures_setrrr�_yield_finished_futures�s
rIc	csJ|dk	r|tj�}t|�}t|�}t|��*tdd�|D��}||}t|t�}WdQRXt|�}z�t|||fd�EdHx�|�r|dkr�d}n(|tj�}|dkr�t	dt|�|f��|j
j|�|j�|j
}g|_
|j
j�WdQRX|j�t||||fd�EdHq~WWdx,|D]$}|j�|jj|�WdQRX�qWXdS)Ncss |]}|jttgkr|VqdS)N)r:r	r
)r;r<rrrr=�szas_completed.<locals>.<genexpr>)rHrz%d (of %d) futures unfinished)�time�	monotonicr'�lenr/rDr�listrIrr�waitr%r�clear�reverser4r@rF)	rA�timeout�end_timeZ
total_futuresrrrCZwait_timeoutr<rrr�as_completed�s@

rS�DoneAndNotDoneFuturesz
done not_donecCs�t|���tdd�|D��}t|�|}|tkr>|r>t||�S|tkrf|rftdd�|D��rft||�St|�t|�kr�t||�St||�}WdQRX|jj	|�x*|D]"}|j
�|jj|�WdQRXq�W|j
|j�t|t|�|�S)Ncss |]}|jttgkr|VqdS)N)r:r	r
)r;r<rrrr=szwait.<locals>.<genexpr>css(|] }|j�r|j�dk	r|VqdS)N)r
�	exception)r;r<rrrr=$s)r/r'rrTr�anyrLrDrrNr4r@rF�updater)rArQrB�doneZnot_donerCr<rrrrNs"




rNc@s�eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zddd�Zddd�Z
dd�Zdd�Zdd�ZdS) �FuturecCs,tj�|_t|_d|_d|_g|_g|_dS)N)	rZ	Conditionr4rr:�_result�
_exceptionr@�_done_callbacks)rrrrr8s
zFuture.__init__cCsBx<|jD]2}y||�Wqtk
r8tjd|�YqXqWdS)Nz!exception calling callback for %r)r\�	Exception�LOGGERrU)r�callbackrrr�_invoke_callbacksAs
zFuture._invoke_callbackscCs�|j�v|jtkr`|jr<d|jjt|�t|j|jjjfSd|jjt|�t|j|jjjfSd|jjt|�t|jfSQRXdS)Nz<%s at %#x state=%s raised %s>z <%s at %#x state=%s returned %s>z<%s at %#x state=%s>)	r4r:r
r[r&rr2�_STATE_TO_DESCRIPTION_MAPrZ)rrrr�__repr__Hs"
zFuture.__repr__c
CsR|j�:|jttgkrdS|jttgkr,dSt|_|jj�WdQRX|j�dS)NFT)r4r:rr
rr	�
notify_allr`)rrrr�cancel\sz
Future.cancelc
Cs |j�|jttgkSQRXdS)N)r4r:rr	)rrrrr
oszFuture.cancelledc	Cs|j�|jtkSQRXdS)N)r4r:r)rrrrrtszFuture.runningcCs"|j�|jtttgkSQRXdS)N)r4r:rr	r
)rrrrrXyszFuture.donecCs|jr|j�n|jSdS)N)r[rZ)rrrrZ__get_result~szFuture.__get_resultcCs>|j�&|jtttgkr(|jj|�dSWdQRX||�dS)N)r4r:rr	r
r\r)r�fnrrr�add_done_callback�s
zFuture.add_done_callbackNc
Csx|j�h|jttgkrt��n|jtkr0|j�S|jj|�|jttgkrRt��n|jtkrd|j�St��WdQRXdS)N)	r4r:rr	rr
�_Future__get_resultrNr)rrQrrr�result�s

z
Future.resultc
Cst|j�d|jttgkrt��n|jtkr.|jS|jj|�|jttgkrPt��n|jtkr`|jSt��WdQRXdS)N)	r4r:rr	rr
r[rNr)rrQrrrrU�s

zFuture.exceptioncCst|j�d|jtkr6t|_x|jD]}|j|�q WdS|jtkrJt|_dStj	dt
|�|j�td��WdQRXdS)NFTz!Future %s in unexpected state: %szFuture in unexpected state)r4r:rr	r@r!rrr^Zcriticalr2�RuntimeError)rrCrrr�set_running_or_notify_cancel�s

z#Future.set_running_or_notify_cancelc
CsN|j�6||_t|_x|jD]}|j|�qW|jj�WdQRX|j�dS)N)r4rZr
r:r@rrcr`)rrhrCrrr�
set_result�szFuture.set_resultc
CsN|j�6||_t|_x|jD]}|j|�qW|jj�WdQRX|j�dS)N)r4r[r
r:r@r rcr`)rrUrCrrr�
set_exceptionszFuture.set_exception)N)N)rrrrr`rbrdr
rrXrgrfrhrUrjrkrlrrrrrY5s	

"(
rYc@s>eZdZdd�Zddd�dd�Zdd	d
�Zdd�Zd
d�ZdS)�ExecutorcOs
t��dS)N)�NotImplementedError)rrer8�kwargsrrr�submits	zExecutor.submitNr-)rQ�	chunksizecsB�dk	r�tj����fdd�t|�D�����fdd�}|�S)Ncsg|]}�j�f|���qSr)rp)r;r8)rerrr�
<listcomp>?sz Executor.map.<locals>.<listcomp>c3sdzF�j�x8�rB�dkr(�j�j�Vq�j�j�tj��VqWWdx�D]}|j�qNWXdS)N)rPrGrhrJrKrd)r)rRrArQrr�result_iteratorCs 
z%Executor.map.<locals>.result_iterator)rJrK�zip)rrerQrq�	iterablesrsr)rRrerArrQr�map&s

zExecutor.mapTcCsdS)Nr)rrNrrr�shutdownRszExecutor.shutdowncCs|S)Nr)rrrrr6_szExecutor.__enter__cCs|jdd�dS)NT)rNF)rw)r�exc_typeZexc_valZexc_tbrrrr9bszExecutor.__exit__)T)rrrrprvrwr6r9rrrrrms
,

rm)N)$�
__author__�collectionsZloggingrrJrrrrrrrr	r
Z_FUTURE_STATESraZ	getLoggerr^r]rrr�objectrr"r)r*r/rDrIrS�
namedtuplerTrNrYrmrrrr�<module>sR

>1dPKw}�\GꂚP�P(futures/__pycache__/_base.cpython-36.pycnu�[���3


 \�R�
@sPdZddlZddlZddlZddlZdZdZdZdZdZ	dZ
d	Zd
ZdZ
e	e
eee
gZe	de
d
edede
diZejd�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd �d e�Zd!d"�Zd#d$�Zd/d%d&�Zejd'd(�Z defd)d*�Z!Gd+d,�d,e�Z"Gd-d.�d.e�Z#dS)0z"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�0/usr/lib64/python3.6/concurrent/futures/_base.pyr,src@seZdZdZdS)�CancelledErrorzThe Future was cancelled.N)rrrrrrrrr0src@seZdZdZdS)�TimeoutErrorz*The operation exceeded the given deadline.N)rrrrrrrrr4src@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)�_Waiterz;Provides the event that wait() and as_completed() block on.cCstj�|_g|_dS)N)�	threadingZEvent�event�finished_futures)�selfrrr�__init__:s
z_Waiter.__init__cCs|jj|�dS)N)r�append)r�futurerrr�
add_result>sz_Waiter.add_resultcCs|jj|�dS)N)rr)rrrrr�
add_exceptionAsz_Waiter.add_exceptioncCs|jj|�dS)N)rr)rrrrr�
add_cancelledDsz_Waiter.add_cancelledN)rrrrrr r!r"rrrrr8s
rcsDeZdZdZ�fdd�Z�fdd�Z�fdd�Z�fdd	�Z�ZS)
�_AsCompletedWaiterzUsed by as_completed().cstt|�j�tj�|_dS)N)�superr#rr�Lock�lock)r)�	__class__rrrJsz_AsCompletedWaiter.__init__c
s0|j� tt|�j|�|jj�WdQRXdS)N)r&r$r#r r�set)rr)r'rrr Nsz_AsCompletedWaiter.add_resultc
s0|j� tt|�j|�|jj�WdQRXdS)N)r&r$r#r!rr()rr)r'rrr!Ssz _AsCompletedWaiter.add_exceptionc
s0|j� tt|�j|�|jj�WdQRXdS)N)r&r$r#r"rr()rr)r'rrr"Xsz _AsCompletedWaiter.add_cancelled)	rrrrrr r!r"�
__classcell__rr)r'rr#Gs
r#cs8eZdZdZ�fdd�Z�fdd�Z�fdd�Z�ZS)�_FirstCompletedWaiterz*Used by wait(return_when=FIRST_COMPLETED).cst�j|�|jj�dS)N)r$r rr()rr)r'rrr `sz _FirstCompletedWaiter.add_resultcst�j|�|jj�dS)N)r$r!rr()rr)r'rrr!dsz#_FirstCompletedWaiter.add_exceptioncst�j|�|jj�dS)N)r$r"rr()rr)r'rrr"hsz#_FirstCompletedWaiter.add_cancelled)rrrrr r!r"r)rr)r'rr*]sr*csLeZdZdZ�fdd�Zdd�Z�fdd�Z�fdd	�Z�fd
d�Z�Z	S)�_AllCompletedWaiterz<Used by wait(return_when=FIRST_EXCEPTION and ALL_COMPLETED).cs$||_||_tj�|_t�j�dS)N)�num_pending_calls�stop_on_exceptionrr%r&r$r)rr,r-)r'rrros
z_AllCompletedWaiter.__init__c
Cs4|j�$|jd8_|js&|jj�WdQRXdS)N�)r&r,rr()rrrr�_decrement_pending_callsusz,_AllCompletedWaiter._decrement_pending_callscst�j|�|j�dS)N)r$r r/)rr)r'rrr {sz_AllCompletedWaiter.add_resultcs*t�j|�|jr|jj�n|j�dS)N)r$r!r-rr(r/)rr)r'rrr!sz!_AllCompletedWaiter.add_exceptioncst�j|�|j�dS)N)r$r"r/)rr)r'rrr"�sz!_AllCompletedWaiter.add_cancelled)
rrrrrr/r r!r"r)rr)r'rr+lsr+c@s(eZdZdZdd�Zdd�Zdd�ZdS)	�_AcquireFutureszDA context manager that does an ordered acquire of Future conditions.cCst|td�|_dS)N)�key)�sorted�id�futures)rr4rrrr�sz_AcquireFutures.__init__cCsx|jD]}|jj�qWdS)N)r4�
_condition�acquire)rrrrr�	__enter__�sz_AcquireFutures.__enter__cGsx|jD]}|jj�qWdS)N)r4r5�release)r�argsrrrr�__exit__�sz_AcquireFutures.__exit__N)rrrrrr7r:rrrrr0�sr0cCs�|tkrt�}nZ|tkr t�}nJtdd�|D��}|tkrHt|dd�}n"|tkr^t|dd�}ntd|��x|D]}|j	j
|�qpW|S)Ncss|]}|jttgkVqdS)N)�_stater	r
)�.0�frrr�	<genexpr>�sz._create_and_install_waiters.<locals>.<genexpr>T)r-FzInvalid return condition: %r)rr#rr*�sumrr+r�
ValueError�_waitersr)�fs�return_when�waiterZ
pending_countr=rrr�_create_and_install_waiters�s
rEc	csXxR|rR|d}x|D]}|j|�qW|j�|jj|�WdQRX~|j�VqWdS)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.
    r.N���)�remover5rA�pop)rBrD�ref_collectr=Zfutures_setrrr�_yield_finished_futures�s
rJc	csJ|dk	r|tj�}t|�}t|�}t|��*tdd�|D��}||}t|t�}WdQRXt|�}z�t|||fd�EdHx�|�r|dkr�d}n(|tj�}|dkr�t	dt|�|f��|j
j|�|j�|j
}g|_
|j
j�WdQRX|j�t||||fd�EdHq~WWdx,|D]$}|j�|jj|�WdQRX�qWXdS)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 |]}|jttgkr|VqdS)N)r;r	r
)r<r=rrrr>�szas_completed.<locals>.<genexpr>)rIrz%d (of %d) futures unfinished)�time�	monotonicr(�lenr0rEr�listrJrr�waitr&r�clear�reverser5rArG)	rB�timeout�end_timeZ
total_futuresrrrDZwait_timeoutr=rrr�as_completed�s@

rT�DoneAndNotDoneFuturesz
done not_donecCs�t|���tdd�|D��}t|�|}|tkr>|r>t||�S|tkrf|rftdd�|D��rft||�St|�t|�kr�t||�St||�}WdQRX|jj	|�x*|D]"}|j
�|jj|�WdQRXq�W|j
|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 |]}|jttgkr|VqdS)N)r;r	r
)r<r=rrrr>szwait.<locals>.<genexpr>css(|] }|j�r|j�dk	r|VqdS)N)r
�	exception)r<r=rrrr>$sN)r0r(rrUr�anyrMrErrOr5rArG�updater)rBrRrC�doneZnot_donerDr=rrrrOs"




rOc@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,tj�|_t|_d|_d|_g|_g|_dS)z8Initializes the future. Should not be called by clients.N)	rZ	Conditionr5rr;�_result�
_exceptionrA�_done_callbacks)rrrrr8s
zFuture.__init__cCsBx<|jD]2}y||�Wqtk
r8tjd|�YqXqWdS)Nz!exception calling callback for %r)r]�	Exception�LOGGERrV)r�callbackrrr�_invoke_callbacksAs
zFuture._invoke_callbackscCs�|j�v|jtkr`|jr<d|jjt|�t|j|jjjfSd|jjt|�t|j|jjjfSd|jjt|�t|jfSQRXdS)Nz<%s at %#x state=%s raised %s>z <%s at %#x state=%s returned %s>z<%s at %#x state=%s>)	r5r;r
r\r'rr3�_STATE_TO_DESCRIPTION_MAPr[)rrrr�__repr__Hs"
zFuture.__repr__c
CsR|j�:|jttgkrdS|jttgkr,dSt|_|jj�WdQRX|j�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.
        FTN)r5r;rr
rr	�
notify_allra)rrrr�cancel\sz
Future.cancelc
Cs |j�|jttgkSQRXdS)z(Return True if the future was cancelled.N)r5r;rr	)rrrrr
oszFuture.cancelledc	Cs|j�|jtkSQRXdS)z1Return True if the future is currently executing.N)r5r;r)rrrrrtszFuture.runningcCs"|j�|jtttgkSQRXdS)z>Return True of the future was cancelled or finished executing.N)r5r;rr	r
)rrrrrYyszFuture.donecCs|jr|j�n|jSdS)N)r\r[)rrrrZ__get_result~szFuture.__get_resultcCs>|j�&|jtttgkr(|jj|�dSWdQRX||�dS)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.
        N)r5r;rr	r
r]r)r�fnrrr�add_done_callback�s
zFuture.add_done_callbackNc
Csx|j�h|jttgkrt��n|jtkr0|j�S|jj|�|jttgkrRt��n|jtkrd|j�St��WdQRXdS)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)	r5r;rr	rr
�_Future__get_resultrOr)rrRrrr�result�s

z
Future.resultc
Cst|j�d|jttgkrt��n|jtkr.|jS|jj|�|jttgkrPt��n|jtkr`|jSt��WdQRXdS)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)	r5r;rr	rr
r\rOr)rrRrrrrV�s

zFuture.exceptioncCst|j�d|jtkr6t|_x|jD]}|j|�q WdS|jtkrJt|_dStj	dt
|�|j�td��WdQRXdS)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)r5r;rr	rAr"rrr_Zcriticalr3�RuntimeError)rrDrrr�set_running_or_notify_cancel�s

z#Future.set_running_or_notify_cancelc
CsN|j�6||_t|_x|jD]}|j|�qW|jj�WdQRX|j�dS)z�Sets the return value of work associated with the future.

        Should only be used by Executor implementations and unit tests.
        N)r5r[r
r;rAr rdra)rrirDrrr�
set_result�szFuture.set_resultc
CsN|j�6||_t|_x|jD]}|j|�qW|jj�WdQRX|j�dS)z�Sets the result of the future as being the given exception.

        Should only be used by Executor implementations and unit tests.
        N)r5r\r
r;rAr!rdra)rrVrDrrr�
set_exceptionszFuture.set_exception)N)N)rrrrrrarcrer
rrYrhrgrirVrkrlrmrrrrrZ5s	

"(
rZc@sBeZdZdZdd�Zddd�dd�Zdd
d�Zdd
�Zdd�ZdS)�ExecutorzCThis is an abstract base class for concrete asynchronous executors.cOs
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.
        N)�NotImplementedError)rrfr9�kwargsrrr�submits	zExecutor.submitNr.)rR�	chunksizecsB�dk	r�tj����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)rq)r<r9)rfrrr�
<listcomp>?sz Executor.map.<locals>.<listcomp>c3sdzF�j�x8�rB�dkr(�j�j�Vq�j�j�tj��VqWWdx�D]}|j�qNWXdS)N)rQrHrirKrLre)r)rSrBrRrr�result_iteratorCs 
z%Executor.map.<locals>.result_iterator)rKrL�zip)rrfrRrr�	iterablesrtr)rSrfrBrrRr�map&s

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)rrOrrr�shutdownRszExecutor.shutdowncCs|S)Nr)rrrrr7_szExecutor.__enter__cCs|jdd�dS)NT)rOF)rx)r�exc_typeZexc_valZexc_tbrrrr:bszExecutor.__exit__)T)	rrrrrqrwrxr7r:rrrrrns,

rn)N)$�
__author__�collectionsZloggingrrKrrrrrrrr	r
Z_FUTURE_STATESrbZ	getLoggerr_r^rrr�objectrr#r*r+r0rErJrT�
namedtuplerUrOrZrnrrrr�<module>sR

>1dPKw}�\>۱=�=0futures/__pycache__/process.cpython-36.opt-1.pycnu�[���3


 \P�@sbdZdZddlZddlZddlmZddlZddlmZddlZddlm	Z	ddl
mZddlZddl
Z
ddlmZddlZddlZe
j�Zd	ad
d�ZdZGd
d�de�ZGdd�d�Zdd�ZGdd�de�ZGdd�de�ZGdd�de�Zdd�Zdd�Z dd�Z!dd �Z"d!d"�Z#d	a$da%d#d$�Z&d%d&�Z'Gd'd(�d(e(�Z)Gd)d*�d*ej*�Z+ej,e�dS)+a*	Implements ProcessPoolExecutor.

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

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

+----------+     +----------+       +--------+     +-----------+    +---------+
|          |  => | Work Ids |    => |        |  => | Call Q    | => |         |
|          |     +----------+       |        |     +-----------+    |         |
|          |     | ...      |       |        |     | ...       |    |         |
|          |     | 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)�SimpleQueue)�wait)�partialFcCsJdattj��}x|D]\}}|jd�qWx|D]\}}|j�q2WdS)NT)�	_shutdown�list�_threads_queues�items�put�join)r
�t�q�r�2/usr/lib64/python3.6/concurrent/futures/process.py�_python_exitOsr�c@seZdZdd�Zdd�ZdS)�_RemoteTracebackcCs
||_dS)N)�tb)�selfrrrr�__init__asz_RemoteTraceback.__init__cCs|jS)N)r)rrrr�__str__csz_RemoteTraceback.__str__N)�__name__�
__module__�__qualname__rrrrrrr`src@seZdZdd�Zdd�ZdS)�_ExceptionWithTracebackcCs0tjt|�||�}dj|�}||_d||_dS)N�z

"""
%s""")�	traceback�format_exception�typer�excr)rr rrrrrgs
z _ExceptionWithTraceback.__init__cCst|j|jffS)N)�_rebuild_excr r)rrrr�
__reduce__lsz"_ExceptionWithTraceback.__reduce__N)rrrrr"rrrrrfsrcCst|�|_|S)N)r�	__cause__)r rrrrr!os
r!c@seZdZdd�ZdS)�	_WorkItemcCs||_||_||_||_dS)N)�future�fn�args�kwargs)rr%r&r'r(rrrrtsz_WorkItem.__init__N)rrrrrrrrr$ssr$c@seZdZddd�ZdS)�_ResultItemNcCs||_||_||_dS)N)�work_id�	exception�result)rr*r+r,rrrr{sz_ResultItem.__init__)NN)rrrrrrrrr)zsr)c@seZdZdd�ZdS)�	_CallItemcCs||_||_||_||_dS)N)r*r&r'r()rr*r&r'r(rrrr�sz_CallItem.__init__N)rrrrrrrrr-�sr-cgs0t|�}x"ttj||��}|s"dS|Vq
WdS)z, Iterates over zip()ed iterables in chunks. N)�zip�tuple�	itertools�islice)�	chunksize�	iterables�it�chunkrrr�_get_chunks�sr6cs�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)�.0r')r&rr�
<listcomp>�sz"_process_chunk.<locals>.<listcomp>r)r&r5r)r&r�_process_chunk�s	r9cCs�x�|jdd�}|dkr(|jtj��dSy|j|j|j�}WnBtk
r~}z&t||j	�}|jt
|j|d��WYdd}~XqX|jt
|j|d��qWdS)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 multiprocessing.Queue of _CallItems that will be read and
            evaluated by the worker.
        result_queue: A multiprocessing.Queue of _ResultItems that will written
            to by the worker.
        shutdown: A multiprocessing.Event that will be set as a signal to the
            worker that it should exit when call_queue is empty.
    T)�blockN)r+)r,)�getr�os�getpidr&r'r(�
BaseExceptionr�
__traceback__r)r*)�
call_queue�result_queueZ	call_item�r�er rrr�_process_worker�s
&
rDcCsxxr|j�rdSy|jdd�}Wntjk
r4dSX||}|jj�rh|jt||j|j	|j
�dd�q||=qqWdS)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.
    NF)r:T)Zfullr;�queueZEmptyr%Zset_running_or_notify_cancelrr-r&r'r()�pending_work_itemsZwork_idsr@r*�	work_itemrrr�_add_call_item_to_queue�s 

rHcs�d��fdd�}��fdd�}|j}�xlt||��dd��j�D�}	t|g|	�}
||
krf|j�}nr|���dk	r�d�_d�_d�x&|j�D]\}}
|
jj	t
d	��~
q�W|j�x�j�D]}|j�q�W|�dSt
|t��r�j|�}|j���sR|�dSnJ|dk	�rR|j|jd�}
|
dk	�rR|j�rB|
jj	|j�n|
jj|j�~
|��|��r�y|�sr|�dSWntk
�r�YnXd�q(WdS)
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 multiprocessing.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 multiprocessing.Queue that will be filled with _CallItems
            derived from _WorkItems for processing by the process workers.
        result_queue: A multiprocessing.Queue of _ResultItems generated by the
            process workers.
    Ncstp�dkp�jS)N)r�_shutdown_threadr)�executorrr�
shutting_down�sz/_queue_management_worker.<locals>.shutting_downcsZtdd��j�D��}xtd|�D]}�jd�q"W�j�x�j�D]}|j�qFWdS)Ncss|]}|j�VqdS)N)Zis_alive)r7�prrr�	<genexpr>�szD_queue_management_worker.<locals>.shutdown_worker.<locals>.<genexpr>r)�sum�values�rangeZ
put_nowait�closer)Znb_children_alive�irL)r@�	processesrr�shutdown_worker�sz1_queue_management_worker.<locals>.shutdown_workercSsg|]
}|j�qSr)�sentinel)r7rLrrrr8sz,_queue_management_worker.<locals>.<listcomp>Tz^A process in the process pool was terminated abruptly while the future was running or pending.)Z_readerrHrOrZrecv�_brokenrIr
r%Z
set_exception�BrokenProcessPool�clearZ	terminate�
isinstance�int�poprr*r+Z
set_resultr,r)Zexecutor_referencerSrFZwork_ids_queuer@rArKrT�readerZ	sentinelsZreadyZresult_itemr*rGrLr)r@rJrSr�_queue_management_worker�sb



r]cCshtrtrtt��daytjd�}Wnttfk
r:dSX|dkrHdS|dkrTdSd|att��dS)NT�SC_SEM_NSEMS_MAXr�z@system provides too few semaphores (%d available, 256 necessary)���)�_system_limits_checked�_system_limited�NotImplementedErrorr<�sysconf�AttributeError�
ValueError)Z	nsems_maxrrr�_check_system_limitsQsrgccs.x(|D] }|j�x|r$|j�VqWqWdS)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)�reverser[)�iterable�elementrrr�_chain_from_iterable_of_listshs
rkc@seZdZdZdS)rWzy
    Raised when a process in a ProcessPoolExecutor terminated abruptly
    while a future was in the running state.
    N)rrr�__doc__rrrrrWtsrWcsheZdZddd�Zdd�Zdd�Zdd	�Zejjj	e_	dd
d��fdd
�
Z
ddd�Zejjj	e_	�ZS)�ProcessPoolExecutorNcCs�t�|dkrtj�pd|_n|dkr.td��||_tj|jt�|_d|j_	t
�|_tj�|_
d|_i|_d|_tj�|_d|_d|_i|_dS)a/Initializes 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.
        Nrrz"max_workers must be greater than 0TF)rgr<�	cpu_count�_max_workersrf�multiprocessingZQueue�EXTRA_QUEUED_CALLS�_call_queueZ
_ignore_epiper�
_result_queuerE�	_work_ids�_queue_management_thread�
_processesrI�	threadingZLock�_shutdown_lockrV�_queue_count�_pending_work_items)rZmax_workersrrrr|s$


zProcessPoolExecutor.__init__cCsp|jfdd�}|jdkrl|j�tjttj||�|j|j	|j
|j|jfd�|_d|j_|jj
�|jt|j<dS)NcSs|jd�dS)N)r)�_rrrr�
weakref_cb�szFProcessPoolExecutor._start_queue_management_thread.<locals>.weakref_cb)�targetr'T)rsru�_adjust_process_countrwZThreadr]�weakref�refrvrzrtrrZdaemon�startr	)rr|rrr�_start_queue_management_thread�s


z2ProcessPoolExecutor._start_queue_management_threadcCsJxDtt|j�|j�D].}tjt|j|jfd�}|j	�||j|j
<qWdS)N)r}r')rP�lenrvrorpZProcessrDrrrsr��pid)rr{rLrrrr~�sz)ProcessPoolExecutor._adjust_process_countcOs�|j�t|jrtd��|jr$td��tj�}t||||�}||j|j	<|j
j|j	�|j	d7_	|jjd�|j
�|SQRXdS)NzKA child process terminated abruptly, the process pool is not usable anymorez*cannot schedule new futures after shutdownr)rxrVrWrI�RuntimeErrorrZFuturer$rzryrtrrsr�)rr&r'r(�f�wrrr�submit�szProcessPoolExecutor.submitr)�timeoutr2cs:|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.
        rzchunksize must be >= 1.r2)r�)rf�super�maprr9r6rk)rr&r�r2r3Zresults)�	__class__rrr��szProcessPoolExecutor.mapTc	CsT|j�d|_WdQRX|jr8|jjd�|r8|jj�d|_d|_d|_d|_dS)NT)rxrIrursrrrrrv)rrrrr�shutdown�s
zProcessPoolExecutor.shutdown)N)T)
rrrrr�r~r�r�Executorrlr�r��
__classcell__rr)r�rrm{s
(	
rm)-rl�
__author__�atexitr<Zconcurrent.futuresrrErrprZmultiprocessing.connectionrrwr�	functoolsrr0r�WeakKeyDictionaryr	rrrq�	Exceptionrrr!�objectr$r)r-r6r9rDrHr]rarbrgrkr�rWr�rm�registerrrrr�<module>,sJ
		%s	PKw}�\�����%�%0futures/__pycache__/process.cpython-36.opt-2.pycnu�[���3


 \P�@s^dZddlZddlZddlmZddlZddlmZddlZddlmZddl	m
Z
ddlZddlZddl
mZddlZddlZej�Zdad	d
�ZdZGdd
�d
e�ZGdd�d�Zdd�ZGdd�de�ZGdd�de�ZGdd�de�Zdd�Zdd�Zdd�Z dd�Z!d d!�Z"da#da$d"d#�Z%d$d%�Z&Gd&d'�d'e'�Z(Gd(d)�d)ej)�Z*ej+e�dS)*z"Brian Quinlan (brian@sweetapp.com)�N)�_base)�Full)�SimpleQueue)�wait)�partialFcCsJdattj��}x|D]\}}|jd�qWx|D]\}}|j�q2WdS)NT)�	_shutdown�list�_threads_queues�items�put�join)r
�t�q�r�2/usr/lib64/python3.6/concurrent/futures/process.py�_python_exitOsr�c@seZdZdd�Zdd�ZdS)�_RemoteTracebackcCs
||_dS)N)�tb)�selfrrrr�__init__asz_RemoteTraceback.__init__cCs|jS)N)r)rrrr�__str__csz_RemoteTraceback.__str__N)�__name__�
__module__�__qualname__rrrrrrr`src@seZdZdd�Zdd�ZdS)�_ExceptionWithTracebackcCs0tjt|�||�}dj|�}||_d||_dS)N�z

"""
%s""")�	traceback�format_exception�typer�excr)rr rrrrrgs
z _ExceptionWithTraceback.__init__cCst|j|jffS)N)�_rebuild_excr r)rrrr�
__reduce__lsz"_ExceptionWithTraceback.__reduce__N)rrrrr"rrrrrfsrcCst|�|_|S)N)r�	__cause__)r rrrrr!os
r!c@seZdZdd�ZdS)�	_WorkItemcCs||_||_||_||_dS)N)�future�fn�args�kwargs)rr%r&r'r(rrrrtsz_WorkItem.__init__N)rrrrrrrrr$ssr$c@seZdZddd�ZdS)�_ResultItemNcCs||_||_||_dS)N)�work_id�	exception�result)rr*r+r,rrrr{sz_ResultItem.__init__)NN)rrrrrrrrr)zsr)c@seZdZdd�ZdS)�	_CallItemcCs||_||_||_||_dS)N)r*r&r'r()rr*r&r'r(rrrr�sz_CallItem.__init__N)rrrrrrrrr-�sr-cgs0t|�}x"ttj||��}|s"dS|Vq
WdS)N)�zip�tuple�	itertools�islice)�	chunksize�	iterables�it�chunkrrr�_get_chunks�sr6cs�fdd�|D�S)Ncsg|]}�|��qSrr)�.0r')r&rr�
<listcomp>�sz"_process_chunk.<locals>.<listcomp>r)r&r5r)r&r�_process_chunk�s	r9cCs�x�|jdd�}|dkr(|jtj��dSy|j|j|j�}WnBtk
r~}z&t||j	�}|jt
|j|d��WYdd}~XqX|jt
|j|d��qWdS)NT)�block)r+)r,)�getr�os�getpidr&r'r(�
BaseExceptionr�
__traceback__r)r*)�
call_queue�result_queueZ	call_item�r�er rrr�_process_worker�s
&
rDcCsxxr|j�rdSy|jdd�}Wntjk
r4dSX||}|jj�rh|jt||j|j	|j
�dd�q||=qqWdS)NF)r:T)Zfullr;�queueZEmptyr%Zset_running_or_notify_cancelrr-r&r'r()�pending_work_itemsZwork_idsr@r*�	work_itemrrr�_add_call_item_to_queue�s 

rHcs�d��fdd�}��fdd�}|j}�xlt||��dd��j�D�}	t|g|	�}
||
krf|j�}nr|���dk	r�d�_d�_d�x&|j�D]\}}
|
jj	t
d��~
q�W|j�x�j�D]}|j�q�W|�dSt
|t��r�j|�}|j���sR|�dSnJ|dk	�rR|j|jd�}
|
dk	�rR|j�rB|
jj	|j�n|
jj|j�~
|��|��r�y|�sr|�dSWntk
�r�YnXd�q(WdS)	Ncstp�dkp�jS)N)r�_shutdown_threadr)�executorrr�
shutting_down�sz/_queue_management_worker.<locals>.shutting_downcsZtdd��j�D��}xtd|�D]}�jd�q"W�j�x�j�D]}|j�qFWdS)Ncss|]}|j�VqdS)N)Zis_alive)r7�prrr�	<genexpr>�szD_queue_management_worker.<locals>.shutdown_worker.<locals>.<genexpr>r)�sum�values�rangeZ
put_nowait�closer)Znb_children_alive�irL)r@�	processesrr�shutdown_worker�sz1_queue_management_worker.<locals>.shutdown_workercSsg|]
}|j�qSr)�sentinel)r7rLrrrr8sz,_queue_management_worker.<locals>.<listcomp>Tz^A process in the process pool was terminated abruptly while the future was running or pending.)Z_readerrHrOrZrecv�_brokenrIr
r%Z
set_exception�BrokenProcessPool�clearZ	terminate�
isinstance�int�poprr*r+Z
set_resultr,r)Zexecutor_referencerSrFZwork_ids_queuer@rArKrT�readerZ	sentinelsZreadyZresult_itemr*rGrLr)r@rJrSr�_queue_management_worker�sb



r]cCshtrtrtt��daytjd�}Wnttfk
r:dSX|dkrHdS|dkrTdSd|att��dS)NT�SC_SEM_NSEMS_MAXr�z@system provides too few semaphores (%d available, 256 necessary)���)�_system_limits_checked�_system_limited�NotImplementedErrorr<�sysconf�AttributeError�
ValueError)Z	nsems_maxrrr�_check_system_limitsQsrgccs.x(|D] }|j�x|r$|j�VqWqWdS)N)�reverser[)�iterable�elementrrr�_chain_from_iterable_of_listshs
rkc@seZdZdS)rWN)rrrrrrrrWtsrWcsheZdZddd�Zdd�Zdd�Zdd	�Zejjj	e_	dd
d��fdd
�
Z
ddd�Zejjj	e_	�ZS)�ProcessPoolExecutorNcCs�t�|dkrtj�pd|_n|dkr.td��||_tj|jt�|_d|j_	t
�|_tj�|_
d|_i|_d|_tj�|_d|_d|_i|_dS)Nrrz"max_workers must be greater than 0TF)rgr<�	cpu_count�_max_workersrf�multiprocessingZQueue�EXTRA_QUEUED_CALLS�_call_queueZ
_ignore_epiper�
_result_queuerE�	_work_ids�_queue_management_thread�
_processesrI�	threadingZLock�_shutdown_lockrV�_queue_count�_pending_work_items)rZmax_workersrrrr|s$


zProcessPoolExecutor.__init__cCsp|jfdd�}|jdkrl|j�tjttj||�|j|j	|j
|j|jfd�|_d|j_|jj
�|jt|j<dS)NcSs|jd�dS)N)r)�_rrrr�
weakref_cb�szFProcessPoolExecutor._start_queue_management_thread.<locals>.weakref_cb)�targetr'T)rrrt�_adjust_process_countrvZThreadr]�weakref�refruryrsrqZdaemon�startr	)rr{rrr�_start_queue_management_thread�s


z2ProcessPoolExecutor._start_queue_management_threadcCsJxDtt|j�|j�D].}tjt|j|jfd�}|j	�||j|j
<qWdS)N)r|r')rP�lenrurnroZProcessrDrqrrr��pid)rrzrLrrrr}�sz)ProcessPoolExecutor._adjust_process_countcOs�|j�t|jrtd��|jr$td��tj�}t||||�}||j|j	<|j
j|j	�|j	d7_	|jjd�|j
�|SQRXdS)NzKA child process terminated abruptly, the process pool is not usable anymorez*cannot schedule new futures after shutdownr)rwrVrWrI�RuntimeErrorrZFuturer$ryrxrsrrrr�)rr&r'r(�f�wrrr�submit�szProcessPoolExecutor.submitr)�timeoutr2cs:|dkrtd��t�jtt|�t|d|i�|d�}t|�S)Nrzchunksize must be >= 1.r2)r�)rf�super�maprr9r6rk)rr&r�r2r3Zresults)�	__class__rrr��szProcessPoolExecutor.mapTc	CsT|j�d|_WdQRX|jr8|jjd�|r8|jj�d|_d|_d|_d|_dS)NT)rwrIrtrrrrrqru)rrrrr�shutdown�s
zProcessPoolExecutor.shutdown)N)T)
rrrrr�r}r�r�Executor�__doc__r�r��
__classcell__rr)r�rrl{s
(	
rl),�
__author__�atexitr<Zconcurrent.futuresrrErrorZmultiprocessing.connectionrrvr~�	functoolsrr0r�WeakKeyDictionaryr	rrrp�	Exceptionrrr!�objectr$r)r-r6r9rDrHr]rarbrgrkr�rWr�rl�registerrrrr�<module>.sH
		%s	PKw}�\����=�=*futures/__pycache__/process.cpython-36.pycnu�[���3


 \P�@sbdZdZddlZddlZddlmZddlZddlmZddlZddlm	Z	ddl
mZddlZddl
Z
ddlmZddlZddlZe
j�Zd	ad
d�ZdZGd
d�de�ZGdd�d�Zdd�ZGdd�de�ZGdd�de�ZGdd�de�Zdd�Zdd�Z dd�Z!dd �Z"d!d"�Z#d	a$da%d#d$�Z&d%d&�Z'Gd'd(�d(e(�Z)Gd)d*�d*ej*�Z+ej,e�dS)+a*	Implements ProcessPoolExecutor.

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

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

+----------+     +----------+       +--------+     +-----------+    +---------+
|          |  => | Work Ids |    => |        |  => | Call Q    | => |         |
|          |     +----------+       |        |     +-----------+    |         |
|          |     | ...      |       |        |     | ...       |    |         |
|          |     | 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)�SimpleQueue)�wait)�partialFcCsJdattj��}x|D]\}}|jd�qWx|D]\}}|j�q2WdS)NT)�	_shutdown�list�_threads_queues�items�put�join)r
�t�q�r�2/usr/lib64/python3.6/concurrent/futures/process.py�_python_exitOsr�c@seZdZdd�Zdd�ZdS)�_RemoteTracebackcCs
||_dS)N)�tb)�selfrrrr�__init__asz_RemoteTraceback.__init__cCs|jS)N)r)rrrr�__str__csz_RemoteTraceback.__str__N)�__name__�
__module__�__qualname__rrrrrrr`src@seZdZdd�Zdd�ZdS)�_ExceptionWithTracebackcCs0tjt|�||�}dj|�}||_d||_dS)N�z

"""
%s""")�	traceback�format_exception�typer�excr)rr rrrrrgs
z _ExceptionWithTraceback.__init__cCst|j|jffS)N)�_rebuild_excr r)rrrr�
__reduce__lsz"_ExceptionWithTraceback.__reduce__N)rrrrr"rrrrrfsrcCst|�|_|S)N)r�	__cause__)r rrrrr!os
r!c@seZdZdd�ZdS)�	_WorkItemcCs||_||_||_||_dS)N)�future�fn�args�kwargs)rr%r&r'r(rrrrtsz_WorkItem.__init__N)rrrrrrrrr$ssr$c@seZdZddd�ZdS)�_ResultItemNcCs||_||_||_dS)N)�work_id�	exception�result)rr*r+r,rrrr{sz_ResultItem.__init__)NN)rrrrrrrrr)zsr)c@seZdZdd�ZdS)�	_CallItemcCs||_||_||_||_dS)N)r*r&r'r()rr*r&r'r(rrrr�sz_CallItem.__init__N)rrrrrrrrr-�sr-cgs0t|�}x"ttj||��}|s"dS|Vq
WdS)z, Iterates over zip()ed iterables in chunks. N)�zip�tuple�	itertools�islice)�	chunksize�	iterables�it�chunkrrr�_get_chunks�sr6cs�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)�.0r')r&rr�
<listcomp>�sz"_process_chunk.<locals>.<listcomp>r)r&r5r)r&r�_process_chunk�s	r9cCs�x�|jdd�}|dkr(|jtj��dSy|j|j|j�}WnBtk
r~}z&t||j	�}|jt
|j|d��WYdd}~XqX|jt
|j|d��qWdS)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 multiprocessing.Queue of _CallItems that will be read and
            evaluated by the worker.
        result_queue: A multiprocessing.Queue of _ResultItems that will written
            to by the worker.
        shutdown: A multiprocessing.Event that will be set as a signal to the
            worker that it should exit when call_queue is empty.
    T)�blockN)r+)r,)�getr�os�getpidr&r'r(�
BaseExceptionr�
__traceback__r)r*)�
call_queue�result_queueZ	call_item�r�er rrr�_process_worker�s
&
rDcCsxxr|j�rdSy|jdd�}Wntjk
r4dSX||}|jj�rh|jt||j|j	|j
�dd�q||=qqWdS)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.
    NF)r:T)Zfullr;�queueZEmptyr%Zset_running_or_notify_cancelrr-r&r'r()�pending_work_itemsZwork_idsr@r*�	work_itemrrr�_add_call_item_to_queue�s 

rHcs�d��fdd�}��fdd�}|j}�x~t||��dd��j�D�}	|	sNt�t|g|	�}
||
krn|j�}nr|���dk	r�d�_d�_d�x&|j�D]\}}
|
j	j
td	��~
q�W|j�x�j�D]}|j
�q�W|�dSt|t��r|�s�t��j|�}|j���sd|�dSnJ|dk	�rd|j|jd�}
|
dk	�rd|j�rT|
j	j
|j�n|
j	j|j�~
|��|��r�y|�s�|�dSWntk
�r�YnXd�q(WdS)
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 multiprocessing.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 multiprocessing.Queue that will be filled with _CallItems
            derived from _WorkItems for processing by the process workers.
        result_queue: A multiprocessing.Queue of _ResultItems generated by the
            process workers.
    Ncstp�dkp�jS)N)r�_shutdown_threadr)�executorrr�
shutting_down�sz/_queue_management_worker.<locals>.shutting_downcsZtdd��j�D��}xtd|�D]}�jd�q"W�j�x�j�D]}|j�qFWdS)Ncss|]}|j�VqdS)N)Zis_alive)r7�prrr�	<genexpr>�szD_queue_management_worker.<locals>.shutdown_worker.<locals>.<genexpr>r)�sum�values�rangeZ
put_nowait�closer)Znb_children_alive�irL)r@�	processesrr�shutdown_worker�sz1_queue_management_worker.<locals>.shutdown_workercSsg|]
}|j�qSr)�sentinel)r7rLrrrr8sz,_queue_management_worker.<locals>.<listcomp>Tz^A process in the process pool was terminated abruptly while the future was running or pending.)Z_readerrHrO�AssertionErrorrZrecv�_brokenrIr
r%Z
set_exception�BrokenProcessPool�clearZ	terminate�
isinstance�int�poprr*r+Z
set_resultr,r)Zexecutor_referencerSrFZwork_ids_queuer@rArKrT�readerZ	sentinelsZreadyZresult_itemr*rGrLr)r@rJrSr�_queue_management_worker�sf




r^cCshtrtrtt��daytjd�}Wnttfk
r:dSX|dkrHdS|dkrTdSd|att��dS)NT�SC_SEM_NSEMS_MAXr�z@system provides too few semaphores (%d available, 256 necessary)���)�_system_limits_checked�_system_limited�NotImplementedErrorr<�sysconf�AttributeError�
ValueError)Z	nsems_maxrrr�_check_system_limitsQsrhccs.x(|D] }|j�x|r$|j�VqWqWdS)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)�reverser\)�iterable�elementrrr�_chain_from_iterable_of_listshs
rlc@seZdZdZdS)rXzy
    Raised when a process in a ProcessPoolExecutor terminated abruptly
    while a future was in the running state.
    N)rrr�__doc__rrrrrXtsrXcsheZdZddd�Zdd�Zdd�Zdd	�Zejjj	e_	dd
d��fdd
�
Z
ddd�Zejjj	e_	�ZS)�ProcessPoolExecutorNcCs�t�|dkrtj�pd|_n|dkr.td��||_tj|jt�|_d|j_	t
�|_tj�|_
d|_i|_d|_tj�|_d|_d|_i|_dS)a/Initializes 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.
        Nrrz"max_workers must be greater than 0TF)rhr<�	cpu_count�_max_workersrg�multiprocessingZQueue�EXTRA_QUEUED_CALLS�_call_queueZ
_ignore_epiper�
_result_queuerE�	_work_ids�_queue_management_thread�
_processesrI�	threadingZLock�_shutdown_lockrW�_queue_count�_pending_work_items)rZmax_workersrrrr|s$


zProcessPoolExecutor.__init__cCsp|jfdd�}|jdkrl|j�tjttj||�|j|j	|j
|j|jfd�|_d|j_|jj
�|jt|j<dS)NcSs|jd�dS)N)r)�_rrrr�
weakref_cb�szFProcessPoolExecutor._start_queue_management_thread.<locals>.weakref_cb)�targetr'T)rtrv�_adjust_process_countrxZThreadr^�weakref�refrwr{rursZdaemon�startr	)rr}rrr�_start_queue_management_thread�s


z2ProcessPoolExecutor._start_queue_management_threadcCsJxDtt|j�|j�D].}tjt|j|jfd�}|j	�||j|j
<qWdS)N)r~r')rP�lenrwrprqZProcessrDrsrtr��pid)rr|rLrrrr�sz)ProcessPoolExecutor._adjust_process_countcOs�|j�t|jrtd��|jr$td��tj�}t||||�}||j|j	<|j
j|j	�|j	d7_	|jjd�|j
�|SQRXdS)NzKA child process terminated abruptly, the process pool is not usable anymorez*cannot schedule new futures after shutdownr)ryrWrXrI�RuntimeErrorrZFuturer$r{rzrurrtr�)rr&r'r(�f�wrrr�submit�szProcessPoolExecutor.submitr)�timeoutr2cs:|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.
        rzchunksize must be >= 1.r2)r�)rg�super�maprr9r6rl)rr&r�r2r3Zresults)�	__class__rrr��szProcessPoolExecutor.mapTc	CsT|j�d|_WdQRX|jr8|jjd�|r8|jj�d|_d|_d|_d|_dS)NT)ryrIrvrtrrrsrw)rrrrr�shutdown�s
zProcessPoolExecutor.shutdown)N)T)
rrrrr�rr�r�Executorrmr�r��
__classcell__rr)r�rrn{s
(	
rn)-rm�
__author__�atexitr<Zconcurrent.futuresrrErrqrZmultiprocessing.connectionrrxr��	functoolsrr0r�WeakKeyDictionaryr	rrrr�	Exceptionrrr!�objectr$r)r-r6r9rDrHr^rbrcrhrlr�rXr�rn�registerrrrr�<module>,sJ
		%s	PKw}�\!^rJJ/futures/__pycache__/thread.cpython-36.opt-1.pycnu�[���3


 \��@s�dZdZddlZddlmZddlZddlZddlZddlZddl	Z	ej
�Zdadd�Z
eje
�Gdd	�d	e�Zd
d�ZGdd
�d
ej�ZdS)zImplements ThreadPoolExecutor.z"Brian Quinlan (brian@sweetapp.com)�N)�_baseFcCsJdattj��}x|D]\}}|jd�qWx|D]\}}|j�q2WdS)NT)�	_shutdown�list�_threads_queues�items�put�join)r�t�q�r�1/usr/lib64/python3.6/concurrent/futures/thread.py�_python_exit!sr
c@seZdZdd�Zdd�ZdS)�	_WorkItemcCs||_||_||_||_dS)N)�future�fn�args�kwargs)�selfrrrrrrr�__init__-sz_WorkItem.__init__cCsf|jj�sdSy|j|j|j�}Wn2tk
rT}z|jj|�d}WYdd}~XnX|jj|�dS)N)rZset_running_or_notify_cancelrrr�
BaseExceptionZ
set_exceptionZ
set_result)r�result�excrrr�run3s
z
_WorkItem.runN)�__name__�
__module__�__qualname__rrrrrrr,srcCs|yRxL|jdd�}|dk	r$|j�~q|�}ts<|dks<|jrJ|jd�dS~qWWn$tk
rvtjjddd�YnXdS)NT)�blockzException in worker)�exc_info)�getrrrrrZLOGGERZcritical)Zexecutor_referenceZ
work_queueZ	work_itemZexecutorrrr�_worker@s

rc@sReZdZej�jZddd�Zdd�Ze	j
jje_dd�Zd
d
d�Z
e	j
j
je
_dS)�ThreadPoolExecutorN�cCsf|dkrtj�pdd}|dkr(td��||_tj�|_t�|_d|_	t
j�|_|p^d|j
�|_dS)aInitializes 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.
        N��rz"max_workers must be greater than 0FzThreadPoolExecutor-%d)�os�	cpu_count�
ValueError�_max_workers�queueZQueue�_work_queue�set�_threadsr�	threadingZLock�_shutdown_lock�_counter�_thread_name_prefix)rZmax_workersZthread_name_prefixrrrr[s

zThreadPoolExecutor.__init__cOsN|j�>|jrtd��tj�}t||||�}|jj|�|j�|SQRXdS)Nz*cannot schedule new futures after shutdown)	r-r�RuntimeErrorrZFuturerr)r�_adjust_thread_count)rrrr�f�wrrr�submitrszThreadPoolExecutor.submitcCsz|jfdd�}t|j�}||jkrvd|jp,||f}tj|ttj	||�|jfd�}d|_
|j�|jj|�|jt
|<dS)NcSs|jd�dS)N)r)�_r
rrr�
weakref_cb�sz;ThreadPoolExecutor._adjust_thread_count.<locals>.weakref_cbz%s_%d)�name�targetrT)r)�lenr+r'r/r,ZThreadr�weakref�refZdaemon�start�addr)rr6Znum_threadsZthread_namer	rrrr1s



z'ThreadPoolExecutor._adjust_thread_countTc	CsD|j�d|_|jjd�WdQRX|r@x|jD]}|j�q0WdS)NT)r-rr)rr+r)r�waitr	rrr�shutdown�szThreadPoolExecutor.shutdown)Nr!)T)rrr�	itertools�count�__next__r.rr4r�Executor�__doc__r1r?rrrrr Vs


r )rD�
__author__�atexitZconcurrent.futuresrr@r(r,r:r$�WeakKeyDictionaryrrr
�register�objectrrrCr rrrr�<module>s	
PKw}�\�!/futures/__pycache__/thread.cpython-36.opt-2.pycnu�[���3


 \��@s�dZddlZddlmZddlZddlZddlZddlZddlZej	�Z
dadd�Zej
e�Gdd�de�Zd	d
�ZGdd�dej�ZdS)
z"Brian Quinlan (brian@sweetapp.com)�N)�_baseFcCsJdattj��}x|D]\}}|jd�qWx|D]\}}|j�q2WdS)NT)�	_shutdown�list�_threads_queues�items�put�join)r�t�q�r�1/usr/lib64/python3.6/concurrent/futures/thread.py�_python_exit!sr
c@seZdZdd�Zdd�ZdS)�	_WorkItemcCs||_||_||_||_dS)N)�future�fn�args�kwargs)�selfrrrrrrr�__init__-sz_WorkItem.__init__cCsf|jj�sdSy|j|j|j�}Wn2tk
rT}z|jj|�d}WYdd}~XnX|jj|�dS)N)rZset_running_or_notify_cancelrrr�
BaseExceptionZ
set_exceptionZ
set_result)r�result�excrrr�run3s
z
_WorkItem.runN)�__name__�
__module__�__qualname__rrrrrrr,srcCs|yRxL|jdd�}|dk	r$|j�~q|�}ts<|dks<|jrJ|jd�dS~qWWn$tk
rvtjjddd�YnXdS)NT)�blockzException in worker)�exc_info)�getrrrrrZLOGGERZcritical)Zexecutor_referenceZ
work_queueZ	work_itemZexecutorrrr�_worker@s

rc@sReZdZej�jZddd�Zdd�Ze	j
jje_dd�Zd
d
d�Z
e	j
j
je
_dS)�ThreadPoolExecutorN�cCsf|dkrtj�pdd}|dkr(td��||_tj�|_t�|_d|_	t
j�|_|p^d|j
�|_dS)N��rz"max_workers must be greater than 0FzThreadPoolExecutor-%d)�os�	cpu_count�
ValueError�_max_workers�queueZQueue�_work_queue�set�_threadsr�	threadingZLock�_shutdown_lock�_counter�_thread_name_prefix)rZmax_workersZthread_name_prefixrrrr[s

zThreadPoolExecutor.__init__cOsN|j�>|jrtd��tj�}t||||�}|jj|�|j�|SQRXdS)Nz*cannot schedule new futures after shutdown)	r-r�RuntimeErrorrZFuturerr)r�_adjust_thread_count)rrrr�f�wrrr�submitrszThreadPoolExecutor.submitcCsz|jfdd�}t|j�}||jkrvd|jp,||f}tj|ttj	||�|jfd�}d|_
|j�|jj|�|jt
|<dS)NcSs|jd�dS)N)r)�_r
rrr�
weakref_cb�sz;ThreadPoolExecutor._adjust_thread_count.<locals>.weakref_cbz%s_%d)�name�targetrT)r)�lenr+r'r/r,ZThreadr�weakref�refZdaemon�start�addr)rr6Znum_threadsZthread_namer	rrrr1s



z'ThreadPoolExecutor._adjust_thread_countTc	CsD|j�d|_|jjd�WdQRX|r@x|jD]}|j�q0WdS)NT)r-rr)rr+r)r�waitr	rrr�shutdown�szThreadPoolExecutor.shutdown)Nr!)T)rrr�	itertools�count�__next__r.rr4r�Executor�__doc__r1r?rrrrr Vs


r )�
__author__�atexitZconcurrent.futuresrr@r(r,r:r$�WeakKeyDictionaryrrr
�register�objectrrrCr rrrr�<module>s	
PKw}�\!^rJJ)futures/__pycache__/thread.cpython-36.pycnu�[���3


 \��@s�dZdZddlZddlmZddlZddlZddlZddlZddl	Z	ej
�Zdadd�Z
eje
�Gdd	�d	e�Zd
d�ZGdd
�d
ej�ZdS)zImplements ThreadPoolExecutor.z"Brian Quinlan (brian@sweetapp.com)�N)�_baseFcCsJdattj��}x|D]\}}|jd�qWx|D]\}}|j�q2WdS)NT)�	_shutdown�list�_threads_queues�items�put�join)r�t�q�r�1/usr/lib64/python3.6/concurrent/futures/thread.py�_python_exit!sr
c@seZdZdd�Zdd�ZdS)�	_WorkItemcCs||_||_||_||_dS)N)�future�fn�args�kwargs)�selfrrrrrrr�__init__-sz_WorkItem.__init__cCsf|jj�sdSy|j|j|j�}Wn2tk
rT}z|jj|�d}WYdd}~XnX|jj|�dS)N)rZset_running_or_notify_cancelrrr�
BaseExceptionZ
set_exceptionZ
set_result)r�result�excrrr�run3s
z
_WorkItem.runN)�__name__�
__module__�__qualname__rrrrrrr,srcCs|yRxL|jdd�}|dk	r$|j�~q|�}ts<|dks<|jrJ|jd�dS~qWWn$tk
rvtjjddd�YnXdS)NT)�blockzException in worker)�exc_info)�getrrrrrZLOGGERZcritical)Zexecutor_referenceZ
work_queueZ	work_itemZexecutorrrr�_worker@s

rc@sReZdZej�jZddd�Zdd�Ze	j
jje_dd�Zd
d
d�Z
e	j
j
je
_dS)�ThreadPoolExecutorN�cCsf|dkrtj�pdd}|dkr(td��||_tj�|_t�|_d|_	t
j�|_|p^d|j
�|_dS)aInitializes 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.
        N��rz"max_workers must be greater than 0FzThreadPoolExecutor-%d)�os�	cpu_count�
ValueError�_max_workers�queueZQueue�_work_queue�set�_threadsr�	threadingZLock�_shutdown_lock�_counter�_thread_name_prefix)rZmax_workersZthread_name_prefixrrrr[s

zThreadPoolExecutor.__init__cOsN|j�>|jrtd��tj�}t||||�}|jj|�|j�|SQRXdS)Nz*cannot schedule new futures after shutdown)	r-r�RuntimeErrorrZFuturerr)r�_adjust_thread_count)rrrr�f�wrrr�submitrszThreadPoolExecutor.submitcCsz|jfdd�}t|j�}||jkrvd|jp,||f}tj|ttj	||�|jfd�}d|_
|j�|jj|�|jt
|<dS)NcSs|jd�dS)N)r)�_r
rrr�
weakref_cb�sz;ThreadPoolExecutor._adjust_thread_count.<locals>.weakref_cbz%s_%d)�name�targetrT)r)�lenr+r'r/r,ZThreadr�weakref�refZdaemon�start�addr)rr6Znum_threadsZthread_namer	rrrr1s



z'ThreadPoolExecutor._adjust_thread_countTc	CsD|j�d|_|jjd�WdQRX|r@x|jD]}|j�q0WdS)NT)r-rr)rr+r)r�waitr	rrr�shutdown�szThreadPoolExecutor.shutdown)Nr!)T)rrr�	itertools�count�__next__r.rr4r�Executor�__doc__r1r?rrrrr Vs


r )rD�
__author__�atexitZconcurrent.futuresrr@r(r,r:r$�WeakKeyDictionaryrrr
�register�objectrrrCr rrrr�<module>s	
PKw}�\�G��  futures/__init__.pynu�[���# Copyright 2009 Brian Quinlan. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

"""Execute computations asynchronously using threads or processes."""

__author__ = 'Brian Quinlan (brian@sweetapp.com)'

from concurrent.futures._base import (FIRST_COMPLETED,
                                      FIRST_EXCEPTION,
                                      ALL_COMPLETED,
                                      CancelledError,
                                      TimeoutError,
                                      Future,
                                      Executor,
                                      wait,
                                      as_completed)
from concurrent.futures.process import ProcessPoolExecutor
from concurrent.futures.thread import ThreadPoolExecutor
PKw}�\��l��R�Rfutures/_base.pynu�[���# Copyright 2009 Brian Quinlan. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

__author__ = 'Brian Quinlan (brian@sweetapp.com)'

import collections
import logging
import threading
import time

FIRST_COMPLETED = 'FIRST_COMPLETED'
FIRST_EXCEPTION = 'FIRST_EXCEPTION'
ALL_COMPLETED = 'ALL_COMPLETED'
_AS_COMPLETED = '_AS_COMPLETED'

# Possible future states (for internal use by the futures package).
PENDING = 'PENDING'
RUNNING = 'RUNNING'
# The future was cancelled by the user...
CANCELLED = 'CANCELLED'
# ...and _Waiter.add_cancelled() was called by a worker.
CANCELLED_AND_NOTIFIED = 'CANCELLED_AND_NOTIFIED'
FINISHED = 'FINISHED'

_FUTURE_STATES = [
    PENDING,
    RUNNING,
    CANCELLED,
    CANCELLED_AND_NOTIFIED,
    FINISHED
]

_STATE_TO_DESCRIPTION_MAP = {
    PENDING: "pending",
    RUNNING: "running",
    CANCELLED: "cancelled",
    CANCELLED_AND_NOTIFIED: "cancelled",
    FINISHED: "finished"
}

# Logger for internal use by the futures package.
LOGGER = logging.getLogger("concurrent.futures")

class Error(Exception):
    """Base class for all future-related exceptions."""
    pass

class CancelledError(Error):
    """The Future was cancelled."""
    pass

class TimeoutError(Error):
    """The operation exceeded the given deadline."""
    pass

class _Waiter(object):
    """Provides the event that wait() and as_completed() block on."""
    def __init__(self):
        self.event = threading.Event()
        self.finished_futures = []

    def add_result(self, future):
        self.finished_futures.append(future)

    def add_exception(self, future):
        self.finished_futures.append(future)

    def add_cancelled(self, future):
        self.finished_futures.append(future)

class _AsCompletedWaiter(_Waiter):
    """Used by as_completed()."""

    def __init__(self):
        super(_AsCompletedWaiter, self).__init__()
        self.lock = threading.Lock()

    def add_result(self, future):
        with self.lock:
            super(_AsCompletedWaiter, self).add_result(future)
            self.event.set()

    def add_exception(self, future):
        with self.lock:
            super(_AsCompletedWaiter, self).add_exception(future)
            self.event.set()

    def add_cancelled(self, future):
        with self.lock:
            super(_AsCompletedWaiter, self).add_cancelled(future)
            self.event.set()

class _FirstCompletedWaiter(_Waiter):
    """Used by wait(return_when=FIRST_COMPLETED)."""

    def add_result(self, future):
        super().add_result(future)
        self.event.set()

    def add_exception(self, future):
        super().add_exception(future)
        self.event.set()

    def add_cancelled(self, future):
        super().add_cancelled(future)
        self.event.set()

class _AllCompletedWaiter(_Waiter):
    """Used by wait(return_when=FIRST_EXCEPTION and ALL_COMPLETED)."""

    def __init__(self, num_pending_calls, stop_on_exception):
        self.num_pending_calls = num_pending_calls
        self.stop_on_exception = stop_on_exception
        self.lock = threading.Lock()
        super().__init__()

    def _decrement_pending_calls(self):
        with self.lock:
            self.num_pending_calls -= 1
            if not self.num_pending_calls:
                self.event.set()

    def add_result(self, future):
        super().add_result(future)
        self._decrement_pending_calls()

    def add_exception(self, future):
        super().add_exception(future)
        if self.stop_on_exception:
            self.event.set()
        else:
            self._decrement_pending_calls()

    def add_cancelled(self, future):
        super().add_cancelled(future)
        self._decrement_pending_calls()

class _AcquireFutures(object):
    """A context manager that does an ordered acquire of Future conditions."""

    def __init__(self, futures):
        self.futures = sorted(futures, key=id)

    def __enter__(self):
        for future in self.futures:
            future._condition.acquire()

    def __exit__(self, *args):
        for future in self.futures:
            future._condition.release()

def _create_and_install_waiters(fs, return_when):
    if return_when == _AS_COMPLETED:
        waiter = _AsCompletedWaiter()
    elif return_when == FIRST_COMPLETED:
        waiter = _FirstCompletedWaiter()
    else:
        pending_count = sum(
                f._state not in [CANCELLED_AND_NOTIFIED, FINISHED] for f in fs)

        if return_when == FIRST_EXCEPTION:
            waiter = _AllCompletedWaiter(pending_count, stop_on_exception=True)
        elif return_when == ALL_COMPLETED:
            waiter = _AllCompletedWaiter(pending_count, stop_on_exception=False)
        else:
            raise ValueError("Invalid return condition: %r" % return_when)

    for f in fs:
        f._waiters.append(waiter)

    return waiter


def _yield_finished_futures(fs, waiter, ref_collect):
    """
    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.
    """
    while fs:
        f = fs[-1]
        for futures_set in ref_collect:
            futures_set.remove(f)
        with f._condition:
            f._waiters.remove(waiter)
        del f
        # Careful not to keep a reference to the popped value
        yield fs.pop()


def as_completed(fs, timeout=None):
    """An 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.
    """
    if timeout is not None:
        end_time = timeout + time.monotonic()

    fs = set(fs)
    total_futures = len(fs)
    with _AcquireFutures(fs):
        finished = set(
                f for f in fs
                if f._state in [CANCELLED_AND_NOTIFIED, FINISHED])
        pending = fs - finished
        waiter = _create_and_install_waiters(fs, _AS_COMPLETED)
    finished = list(finished)
    try:
        yield from _yield_finished_futures(finished, waiter,
                                           ref_collect=(fs,))

        while pending:
            if timeout is None:
                wait_timeout = None
            else:
                wait_timeout = end_time - time.monotonic()
                if wait_timeout < 0:
                    raise TimeoutError(
                            '%d (of %d) futures unfinished' % (
                            len(pending), total_futures))

            waiter.event.wait(wait_timeout)

            with waiter.lock:
                finished = waiter.finished_futures
                waiter.finished_futures = []
                waiter.event.clear()

            # reverse to keep finishing order
            finished.reverse()
            yield from _yield_finished_futures(finished, waiter,
                                               ref_collect=(fs, pending))

    finally:
        # Remove waiter from unfinished futures
        for f in fs:
            with f._condition:
                f._waiters.remove(waiter)

DoneAndNotDoneFutures = collections.namedtuple(
        'DoneAndNotDoneFutures', 'done not_done')
def wait(fs, timeout=None, return_when=ALL_COMPLETED):
    """Wait 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.
    """
    with _AcquireFutures(fs):
        done = set(f for f in fs
                   if f._state in [CANCELLED_AND_NOTIFIED, FINISHED])
        not_done = set(fs) - done

        if (return_when == FIRST_COMPLETED) and done:
            return DoneAndNotDoneFutures(done, not_done)
        elif (return_when == FIRST_EXCEPTION) and done:
            if any(f for f in done
                   if not f.cancelled() and f.exception() is not None):
                return DoneAndNotDoneFutures(done, not_done)

        if len(done) == len(fs):
            return DoneAndNotDoneFutures(done, not_done)

        waiter = _create_and_install_waiters(fs, return_when)

    waiter.event.wait(timeout)
    for f in fs:
        with f._condition:
            f._waiters.remove(waiter)

    done.update(waiter.finished_futures)
    return DoneAndNotDoneFutures(done, set(fs) - done)

class Future(object):
    """Represents the result of an asynchronous computation."""

    def __init__(self):
        """Initializes the future. Should not be called by clients."""
        self._condition = threading.Condition()
        self._state = PENDING
        self._result = None
        self._exception = None
        self._waiters = []
        self._done_callbacks = []

    def _invoke_callbacks(self):
        for callback in self._done_callbacks:
            try:
                callback(self)
            except Exception:
                LOGGER.exception('exception calling callback for %r', self)

    def __repr__(self):
        with self._condition:
            if self._state == FINISHED:
                if self._exception:
                    return '<%s at %#x state=%s raised %s>' % (
                        self.__class__.__name__,
                        id(self),
                        _STATE_TO_DESCRIPTION_MAP[self._state],
                        self._exception.__class__.__name__)
                else:
                    return '<%s at %#x state=%s returned %s>' % (
                        self.__class__.__name__,
                        id(self),
                        _STATE_TO_DESCRIPTION_MAP[self._state],
                        self._result.__class__.__name__)
            return '<%s at %#x state=%s>' % (
                    self.__class__.__name__,
                    id(self),
                   _STATE_TO_DESCRIPTION_MAP[self._state])

    def cancel(self):
        """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.
        """
        with self._condition:
            if self._state in [RUNNING, FINISHED]:
                return False

            if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
                return True

            self._state = CANCELLED
            self._condition.notify_all()

        self._invoke_callbacks()
        return True

    def cancelled(self):
        """Return True if the future was cancelled."""
        with self._condition:
            return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]

    def running(self):
        """Return True if the future is currently executing."""
        with self._condition:
            return self._state == RUNNING

    def done(self):
        """Return True of the future was cancelled or finished executing."""
        with self._condition:
            return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]

    def __get_result(self):
        if self._exception:
            raise self._exception
        else:
            return self._result

    def add_done_callback(self, fn):
        """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.
        """
        with self._condition:
            if self._state not in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]:
                self._done_callbacks.append(fn)
                return
        fn(self)

    def result(self, timeout=None):
        """Return 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.
        """
        with self._condition:
            if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
                raise CancelledError()
            elif self._state == FINISHED:
                return self.__get_result()

            self._condition.wait(timeout)

            if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
                raise CancelledError()
            elif self._state == FINISHED:
                return self.__get_result()
            else:
                raise TimeoutError()

    def exception(self, timeout=None):
        """Return 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.
        """

        with self._condition:
            if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
                raise CancelledError()
            elif self._state == FINISHED:
                return self._exception

            self._condition.wait(timeout)

            if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
                raise CancelledError()
            elif self._state == FINISHED:
                return self._exception
            else:
                raise TimeoutError()

    # The following methods should only be used by Executors and in tests.
    def set_running_or_notify_cancel(self):
        """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.
        """
        with self._condition:
            if self._state == CANCELLED:
                self._state = CANCELLED_AND_NOTIFIED
                for waiter in self._waiters:
                    waiter.add_cancelled(self)
                # self._condition.notify_all() is not necessary because
                # self.cancel() triggers a notification.
                return False
            elif self._state == PENDING:
                self._state = RUNNING
                return True
            else:
                LOGGER.critical('Future %s in unexpected state: %s',
                                id(self),
                                self._state)
                raise RuntimeError('Future in unexpected state')

    def set_result(self, result):
        """Sets the return value of work associated with the future.

        Should only be used by Executor implementations and unit tests.
        """
        with self._condition:
            self._result = result
            self._state = FINISHED
            for waiter in self._waiters:
                waiter.add_result(self)
            self._condition.notify_all()
        self._invoke_callbacks()

    def set_exception(self, exception):
        """Sets the result of the future as being the given exception.

        Should only be used by Executor implementations and unit tests.
        """
        with self._condition:
            self._exception = exception
            self._state = FINISHED
            for waiter in self._waiters:
                waiter.add_exception(self)
            self._condition.notify_all()
        self._invoke_callbacks()

class Executor(object):
    """This is an abstract base class for concrete asynchronous executors."""

    def submit(self, fn, *args, **kwargs):
        """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.
        """
        raise NotImplementedError()

    def map(self, fn, *iterables, timeout=None, chunksize=1):
        """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.
        """
        if timeout is not None:
            end_time = timeout + time.monotonic()

        fs = [self.submit(fn, *args) for args in zip(*iterables)]

        # Yield must be hidden in closure so that the futures are submitted
        # before the first iterator value is required.
        def result_iterator():
            try:
                # reverse to keep finishing order
                fs.reverse()
                while fs:
                    # Careful not to keep a reference to the popped future
                    if timeout is None:
                        yield fs.pop().result()
                    else:
                        yield fs.pop().result(end_time - time.monotonic())
            finally:
                for future in fs:
                    future.cancel()
        return result_iterator()

    def shutdown(self, wait=True):
        """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.
        """
        pass

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.shutdown(wait=True)
        return False
PKw}�\�T��PPfutures/process.pynu�[���# Copyright 2009 Brian Quinlan. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

"""Implements ProcessPoolExecutor.

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

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

+----------+     +----------+       +--------+     +-----------+    +---------+
|          |  => | Work Ids |    => |        |  => | Call Q    | => |         |
|          |     +----------+       |        |     +-----------+    |         |
|          |     | ...      |       |        |     | ...       |    |         |
|          |     | 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"
"""

__author__ = 'Brian Quinlan (brian@sweetapp.com)'

import atexit
import os
from concurrent.futures import _base
import queue
from queue import Full
import multiprocessing
from multiprocessing import SimpleQueue
from multiprocessing.connection import wait
import threading
import weakref
from functools import partial
import itertools
import traceback

# Workers are created as daemon threads and processes. This is done to allow the
# interpreter to exit when there are still idle processes in a
# ProcessPoolExecutor's process pool (i.e. shutdown() was not called). However,
# allowing workers to die with the interpreter has two undesirable properties:
#   - The workers would still be running during interpreter shutdown,
#     meaning that they would fail in unpredictable ways.
#   - The workers could be killed while evaluating a work item, which could
#     be bad if the callable being evaluated has external side-effects e.g.
#     writing to a file.
#
# To work around this problem, an exit handler is installed which tells the
# workers to exit when their work queues are empty and then waits until the
# threads/processes finish.

_threads_queues = weakref.WeakKeyDictionary()
_shutdown = False

def _python_exit():
    global _shutdown
    _shutdown = True
    items = list(_threads_queues.items())
    for t, q in items:
        q.put(None)
    for t, q in items:
        t.join()

# Controls how many more calls than processes will be queued in the call queue.
# A smaller number will mean that processes spend more time idle waiting for
# work while a larger number will make Future.cancel() succeed less frequently
# (Futures in the call queue cannot be cancelled).
EXTRA_QUEUED_CALLS = 1

# Hack to embed stringification of remote traceback in local traceback

class _RemoteTraceback(Exception):
    def __init__(self, tb):
        self.tb = tb
    def __str__(self):
        return self.tb

class _ExceptionWithTraceback:
    def __init__(self, exc, tb):
        tb = traceback.format_exception(type(exc), exc, tb)
        tb = ''.join(tb)
        self.exc = exc
        self.tb = '\n"""\n%s"""' % tb
    def __reduce__(self):
        return _rebuild_exc, (self.exc, self.tb)

def _rebuild_exc(exc, tb):
    exc.__cause__ = _RemoteTraceback(tb)
    return exc

class _WorkItem(object):
    def __init__(self, future, fn, args, kwargs):
        self.future = future
        self.fn = fn
        self.args = args
        self.kwargs = kwargs

class _ResultItem(object):
    def __init__(self, work_id, exception=None, result=None):
        self.work_id = work_id
        self.exception = exception
        self.result = result

class _CallItem(object):
    def __init__(self, work_id, fn, args, kwargs):
        self.work_id = work_id
        self.fn = fn
        self.args = args
        self.kwargs = kwargs

def _get_chunks(*iterables, chunksize):
    """ Iterates over zip()ed iterables in chunks. """
    it = zip(*iterables)
    while True:
        chunk = tuple(itertools.islice(it, chunksize))
        if not chunk:
            return
        yield chunk

def _process_chunk(fn, chunk):
    """ 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.

    """
    return [fn(*args) for args in chunk]

def _process_worker(call_queue, result_queue):
    """Evaluates calls from call_queue and places the results in result_queue.

    This worker is run in a separate process.

    Args:
        call_queue: A multiprocessing.Queue of _CallItems that will be read and
            evaluated by the worker.
        result_queue: A multiprocessing.Queue of _ResultItems that will written
            to by the worker.
        shutdown: A multiprocessing.Event that will be set as a signal to the
            worker that it should exit when call_queue is empty.
    """
    while True:
        call_item = call_queue.get(block=True)
        if call_item is None:
            # Wake up queue management thread
            result_queue.put(os.getpid())
            return
        try:
            r = call_item.fn(*call_item.args, **call_item.kwargs)
        except BaseException as e:
            exc = _ExceptionWithTraceback(e, e.__traceback__)
            result_queue.put(_ResultItem(call_item.work_id, exception=exc))
        else:
            result_queue.put(_ResultItem(call_item.work_id,
                                         result=r))

def _add_call_item_to_queue(pending_work_items,
                            work_ids,
                            call_queue):
    """Fills 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.
    """
    while True:
        if call_queue.full():
            return
        try:
            work_id = work_ids.get(block=False)
        except queue.Empty:
            return
        else:
            work_item = pending_work_items[work_id]

            if work_item.future.set_running_or_notify_cancel():
                call_queue.put(_CallItem(work_id,
                                         work_item.fn,
                                         work_item.args,
                                         work_item.kwargs),
                               block=True)
            else:
                del pending_work_items[work_id]
                continue

def _queue_management_worker(executor_reference,
                             processes,
                             pending_work_items,
                             work_ids_queue,
                             call_queue,
                             result_queue):
    """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 multiprocessing.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 multiprocessing.Queue that will be filled with _CallItems
            derived from _WorkItems for processing by the process workers.
        result_queue: A multiprocessing.Queue of _ResultItems generated by the
            process workers.
    """
    executor = None

    def shutting_down():
        return _shutdown or executor is None or executor._shutdown_thread

    def shutdown_worker():
        # This is an upper bound
        nb_children_alive = sum(p.is_alive() for p in processes.values())
        for i in range(0, nb_children_alive):
            call_queue.put_nowait(None)
        # Release the queue's resources as soon as possible.
        call_queue.close()
        # If .join() is not called on the created processes then
        # some multiprocessing.Queue methods may deadlock on Mac OS X.
        for p in processes.values():
            p.join()

    reader = result_queue._reader

    while True:
        _add_call_item_to_queue(pending_work_items,
                                work_ids_queue,
                                call_queue)

        sentinels = [p.sentinel for p in processes.values()]
        assert sentinels
        ready = wait([reader] + sentinels)
        if reader in ready:
            result_item = reader.recv()
        else:
            # Mark the process pool broken so that submits fail right now.
            executor = executor_reference()
            if executor is not None:
                executor._broken = True
                executor._shutdown_thread = True
                executor = None
            # All futures in flight must be marked failed
            for work_id, work_item in pending_work_items.items():
                work_item.future.set_exception(
                    BrokenProcessPool(
                        "A process in the process pool was "
                        "terminated abruptly while the future was "
                        "running or pending."
                    ))
                # Delete references to object. See issue16284
                del work_item
            pending_work_items.clear()
            # Terminate remaining workers forcibly: the queues or their
            # locks may be in a dirty state and block forever.
            for p in processes.values():
                p.terminate()
            shutdown_worker()
            return
        if isinstance(result_item, int):
            # Clean shutdown of a worker using its PID
            # (avoids marking the executor broken)
            assert shutting_down()
            p = processes.pop(result_item)
            p.join()
            if not processes:
                shutdown_worker()
                return
        elif result_item is not None:
            work_item = pending_work_items.pop(result_item.work_id, None)
            # work_item can be None if another process terminated (see above)
            if work_item is not None:
                if result_item.exception:
                    work_item.future.set_exception(result_item.exception)
                else:
                    work_item.future.set_result(result_item.result)
                # Delete references to object. See issue16284
                del work_item
        # Check whether we should start shutting down.
        executor = executor_reference()
        # No more work items can be added if:
        #   - The interpreter is shutting down OR
        #   - The executor that owns this worker has been collected OR
        #   - The executor that owns this worker has been shutdown.
        if shutting_down():
            try:
                # Since no new work items can be added, it is safe to shutdown
                # this thread if there are no pending work items.
                if not pending_work_items:
                    shutdown_worker()
                    return
            except Full:
                # This is not a problem: we will eventually be woken up (in
                # result_queue.get()) and be able to send a sentinel again.
                pass
        executor = None

_system_limits_checked = False
_system_limited = None
def _check_system_limits():
    global _system_limits_checked, _system_limited
    if _system_limits_checked:
        if _system_limited:
            raise NotImplementedError(_system_limited)
    _system_limits_checked = True
    try:
        nsems_max = os.sysconf("SC_SEM_NSEMS_MAX")
    except (AttributeError, ValueError):
        # sysconf not available or setting not available
        return
    if nsems_max == -1:
        # indetermined limit, assume that limit is determined
        # by available memory only
        return
    if nsems_max >= 256:
        # minimum number of semaphores available
        # according to POSIX
        return
    _system_limited = "system provides too few semaphores (%d available, 256 necessary)" % nsems_max
    raise NotImplementedError(_system_limited)


def _chain_from_iterable_of_lists(iterable):
    """
    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.
    """
    for element in iterable:
        element.reverse()
        while element:
            yield element.pop()


class BrokenProcessPool(RuntimeError):
    """
    Raised when a process in a ProcessPoolExecutor terminated abruptly
    while a future was in the running state.
    """


class ProcessPoolExecutor(_base.Executor):
    def __init__(self, max_workers=None):
        """Initializes 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.
        """
        _check_system_limits()

        if max_workers is None:
            self._max_workers = os.cpu_count() or 1
        else:
            if max_workers <= 0:
                raise ValueError("max_workers must be greater than 0")

            self._max_workers = max_workers

        # Make the call queue slightly larger than the number of processes to
        # prevent the worker processes from idling. But don't make it too big
        # because futures in the call queue cannot be cancelled.
        self._call_queue = multiprocessing.Queue(self._max_workers +
                                                 EXTRA_QUEUED_CALLS)
        # Killed worker processes can produce spurious "broken pipe"
        # tracebacks in the queue's own worker thread. But we detect killed
        # processes anyway, so silence the tracebacks.
        self._call_queue._ignore_epipe = True
        self._result_queue = SimpleQueue()
        self._work_ids = queue.Queue()
        self._queue_management_thread = None
        # Map of pids to processes
        self._processes = {}

        # Shutdown is a two-step process.
        self._shutdown_thread = False
        self._shutdown_lock = threading.Lock()
        self._broken = False
        self._queue_count = 0
        self._pending_work_items = {}

    def _start_queue_management_thread(self):
        # When the executor gets lost, the weakref callback will wake up
        # the queue management thread.
        def weakref_cb(_, q=self._result_queue):
            q.put(None)
        if self._queue_management_thread is None:
            # Start the processes so that their sentinels are known.
            self._adjust_process_count()
            self._queue_management_thread = threading.Thread(
                    target=_queue_management_worker,
                    args=(weakref.ref(self, weakref_cb),
                          self._processes,
                          self._pending_work_items,
                          self._work_ids,
                          self._call_queue,
                          self._result_queue))
            self._queue_management_thread.daemon = True
            self._queue_management_thread.start()
            _threads_queues[self._queue_management_thread] = self._result_queue

    def _adjust_process_count(self):
        for _ in range(len(self._processes), self._max_workers):
            p = multiprocessing.Process(
                    target=_process_worker,
                    args=(self._call_queue,
                          self._result_queue))
            p.start()
            self._processes[p.pid] = p

    def submit(self, fn, *args, **kwargs):
        with self._shutdown_lock:
            if self._broken:
                raise BrokenProcessPool('A child process terminated '
                    'abruptly, the process pool is not usable anymore')
            if self._shutdown_thread:
                raise RuntimeError('cannot schedule new futures after shutdown')

            f = _base.Future()
            w = _WorkItem(f, fn, args, kwargs)

            self._pending_work_items[self._queue_count] = w
            self._work_ids.put(self._queue_count)
            self._queue_count += 1
            # Wake up queue management thread
            self._result_queue.put(None)

            self._start_queue_management_thread()
            return f
    submit.__doc__ = _base.Executor.submit.__doc__

    def map(self, fn, *iterables, timeout=None, chunksize=1):
        """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: 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.
        """
        if chunksize < 1:
            raise ValueError("chunksize must be >= 1.")

        results = super().map(partial(_process_chunk, fn),
                              _get_chunks(*iterables, chunksize=chunksize),
                              timeout=timeout)
        return _chain_from_iterable_of_lists(results)

    def shutdown(self, wait=True):
        with self._shutdown_lock:
            self._shutdown_thread = True
        if self._queue_management_thread:
            # Wake up queue management thread
            self._result_queue.put(None)
            if wait:
                self._queue_management_thread.join()
        # To reduce the risk of opening too many files, remove references to
        # objects that use file descriptors.
        self._queue_management_thread = None
        self._call_queue = None
        self._result_queue = None
        self._processes = None
    shutdown.__doc__ = _base.Executor.shutdown.__doc__

atexit.register(_python_exit)
PKw}�\�����futures/thread.pynu�[���# Copyright 2009 Brian Quinlan. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

"""Implements ThreadPoolExecutor."""

__author__ = 'Brian Quinlan (brian@sweetapp.com)'

import atexit
from concurrent.futures import _base
import itertools
import queue
import threading
import weakref
import os

# Workers are created as daemon threads. This is done to allow the interpreter
# to exit when there are still idle threads in a ThreadPoolExecutor's thread
# pool (i.e. shutdown() was not called). However, allowing workers to die with
# the interpreter has two undesirable properties:
#   - The workers would still be running during interpreter shutdown,
#     meaning that they would fail in unpredictable ways.
#   - The workers could be killed while evaluating a work item, which could
#     be bad if the callable being evaluated has external side-effects e.g.
#     writing to a file.
#
# To work around this problem, an exit handler is installed which tells the
# workers to exit when their work queues are empty and then waits until the
# threads finish.

_threads_queues = weakref.WeakKeyDictionary()
_shutdown = False

def _python_exit():
    global _shutdown
    _shutdown = True
    items = list(_threads_queues.items())
    for t, q in items:
        q.put(None)
    for t, q in items:
        t.join()

atexit.register(_python_exit)

class _WorkItem(object):
    def __init__(self, future, fn, args, kwargs):
        self.future = future
        self.fn = fn
        self.args = args
        self.kwargs = kwargs

    def run(self):
        if not self.future.set_running_or_notify_cancel():
            return

        try:
            result = self.fn(*self.args, **self.kwargs)
        except BaseException as exc:
            self.future.set_exception(exc)
            # Break a reference cycle with the exception 'exc'
            self = None
        else:
            self.future.set_result(result)

def _worker(executor_reference, work_queue):
    try:
        while True:
            work_item = work_queue.get(block=True)
            if work_item is not None:
                work_item.run()
                # Delete references to object. See issue16284
                del work_item
                continue
            executor = executor_reference()
            # Exit if:
            #   - The interpreter is shutting down OR
            #   - The executor that owns the worker has been collected OR
            #   - The executor that owns the worker has been shutdown.
            if _shutdown or executor is None or executor._shutdown:
                # Notice other workers
                work_queue.put(None)
                return
            del executor
    except BaseException:
        _base.LOGGER.critical('Exception in worker', exc_info=True)

class ThreadPoolExecutor(_base.Executor):

    # Used to assign unique thread names when thread_name_prefix is not supplied.
    _counter = itertools.count().__next__

    def __init__(self, max_workers=None, thread_name_prefix=''):
        """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.
        """
        if max_workers is None:
            # Use this number because ThreadPoolExecutor is often
            # used to overlap I/O instead of CPU work.
            max_workers = (os.cpu_count() or 1) * 5
        if max_workers <= 0:
            raise ValueError("max_workers must be greater than 0")

        self._max_workers = max_workers
        self._work_queue = queue.Queue()
        self._threads = set()
        self._shutdown = False
        self._shutdown_lock = threading.Lock()
        self._thread_name_prefix = (thread_name_prefix or
                                    ("ThreadPoolExecutor-%d" % self._counter()))

    def submit(self, fn, *args, **kwargs):
        with self._shutdown_lock:
            if self._shutdown:
                raise RuntimeError('cannot schedule new futures after shutdown')

            f = _base.Future()
            w = _WorkItem(f, fn, args, kwargs)

            self._work_queue.put(w)
            self._adjust_thread_count()
            return f
    submit.__doc__ = _base.Executor.submit.__doc__

    def _adjust_thread_count(self):
        # When the executor gets lost, the weakref callback will wake up
        # the worker threads.
        def weakref_cb(_, q=self._work_queue):
            q.put(None)
        # TODO(bquinlan): Should avoid creating new threads if there are more
        # idle threads than items in the work queue.
        num_threads = len(self._threads)
        if num_threads < self._max_workers:
            thread_name = '%s_%d' % (self._thread_name_prefix or self,
                                     num_threads)
            t = threading.Thread(name=thread_name, target=_worker,
                                 args=(weakref.ref(self, weakref_cb),
                                       self._work_queue))
            t.daemon = True
            t.start()
            self._threads.add(t)
            _threads_queues[t] = self._work_queue

    def shutdown(self, wait=True):
        with self._shutdown_lock:
            self._shutdown = True
            self._work_queue.put(None)
        if wait:
            for t in self._threads:
                t.join()
    shutdown.__doc__ = _base.Executor.shutdown.__doc__
PKw}�\���I&&__init__.pynu�[���# This directory is a Python package.
PKw}�\�)d�~~)__pycache__/__init__.cpython-36.opt-1.pycnu�[���PKw}�\�)d�~~)�__pycache__/__init__.cpython-36.opt-2.pycnu�[���PKw}�\�)d�~~#�__pycache__/__init__.cpython-36.pycnu�[���PKw}�\�ߊނ�1futures/__pycache__/__init__.cpython-36.opt-1.pycnu�[���PKw}�\�K`�221bfutures/__pycache__/__init__.cpython-36.opt-2.pycnu�[���PKw}�\�ߊނ�+�futures/__pycache__/__init__.cpython-36.pycnu�[���PKw}�\GꂚP�P.�
futures/__pycache__/_base.cpython-36.opt-1.pycnu�[���PKw}�\�I}��2�2.�[futures/__pycache__/_base.cpython-36.opt-2.pycnu�[���PKw}�\GꂚP�P(Ԏfutures/__pycache__/_base.cpython-36.pycnu�[���PKw}�\>۱=�=0��futures/__pycache__/process.cpython-36.opt-1.pycnu�[���PKw}�\�����%�%0�futures/__pycache__/process.cpython-36.opt-2.pycnu�[���PKw}�\����=�=*�Cfutures/__pycache__/process.cpython-36.pycnu�[���PKw}�\!^rJJ/*�futures/__pycache__/thread.cpython-36.opt-1.pycnu�[���PKw}�\�!/ӑfutures/__pycache__/thread.cpython-36.opt-2.pycnu�[���PKw}�\!^rJJ)E�futures/__pycache__/thread.cpython-36.pycnu�[���PKw}�\�G��  �futures/__init__.pynu�[���PKw}�\��l��R�RK�futures/_base.pynu�[���PKw}�\�T��PP~futures/process.pynu�[���PKw}�\������Vfutures/thread.pynu�[���PKw}�\���I&&�l__init__.pynu�[���PK��l