
    Cd                       U d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlZd dlmZmZmZmZmZ d dlmZmZmZ d dlmZmZ d dlmZ d dlmZ d dlmZ d d	lmZmZ d d
l m!Z! d dl"m#Z# d dl$m%Z%m&Z&m'Z'm(Z(m)Z) d dl*m+Z+ d dl,Z-d dl.Z.d dl.m/Z/ d dl0m1Z1  e(d          Z2 e(d          Z3 e(d          Z4 ej5                    Z6e6dk    rdZ6ddZ7dddde8dddZ9d Z: e9            d              Z;d! Z<d" Z=edd$            Z>edd%            Z?ed#e@d&fd'            ZAed(             ZBedd)            ZC G d* d+          ZDee@d,d-fd.            ZEd/ ZFddd2ZGddd5ZHdd7ZIh eJeKeLeMeNeOePeQeReSeTeUeVeWeXeYeZe[e\e]e^e_e`eaebecedeeefe@egeheiejekelemeneoepeqereseteuevZwexeyeze{e|e}e~eeeehZd8 Zdd9Zdd;Z G d< d=          Zdd?Zd@ ZdA ZdB ZddCZdD Z	 ddEZ	 ddFZddHZdddMZddOZddPZdQ ZdR ZdS ZdT ZdU ZdV Zi ZdWedX<    G dY dZ          Z G d[ d\          Z G d] d^          Z e            Z G d_ d`          ZddaZdIdbddgZdIdbddkZ G dl dm          Zdn ZddoZddpZddqZddrZddsZdduZddwZdxdydzd{d|d}d~ddddddZd e                                D             Ze                    d e                                D                        e                    d e                                D                        ddZddZddZdddddddddZdddddddddZe                    d e                                D                        e                    e           e                    d e                                D                        e)ddd            Ze)	 ddd            ZddZd Zd Zd Z ejx        d          Z ej        d          d             ZdddZd Z G d dej                  Z G d d          Zej        d             ZddZddZddZddZddZd ZdS )    )annotationsN)HashableIterableIteratorMappingSet)contextmanagernullcontextsuppress)datetime	timedelta)ENOENT)	lru_cache)import_module)IntegralNumber)add)Lock)AnyClassVarLiteralTypeVaroverload)WeakValueDictionary)config)get_depsKVTasciizutf-8c                     |r | |i |S  | | S )a  Apply a function given its positional and keyword arguments.

    Equivalent to ``func(*args, **kwargs)``
    Most Dask users will never need to use the ``apply`` function.
    It is typically only used by people who need to inject
    keyword argument values into a low level Dask task graph.

    Parameters
    ----------
    func : callable
        The function you want to apply.
    args : tuple
        A tuple containing all the positional arguments needed for ``func``
        (eg: ``(arg_1, arg_2, arg_3)``)
    kwargs : dict, optional
        A dictionary mapping the keyword arguments
        (eg: ``{"kwarg_1": value, "kwarg_2": value}``

    Examples
    --------
    >>> from dask.utils import apply
    >>> def add(number, second_number=5):
    ...     return number + second_number
    ...
    >>> apply(add, (10,), {"second_number": 2})  # equivalent to add(*args, **kwargs)
    12

    >>> task = apply(add, (10,), {"second_number": 2})
    >>> dsk = {'task-name': task}  # adds the task to a low level Dask task graph
     )funcargskwargss      *lib/python3.11/site-packages/dask/utils.pyapplyr'   )   s-    >  tT$V$$$tT{    )versionafter_versionmessageuse_insteadcategoryr)   
str | Noner*   r+   r,   r-   type[Warning]c                "      fd}|S )a&  Decorator to mark a function as deprecated

    Parameters
    ----------
    version : str, optional
        Version of Dask in which the function was deprecated. If specified, the version
        will be included in the default warning message. This should no longer be used
        after the introduction of automated versioning system.
    after_version : str, optional
        Version of Dask after which the function was deprecated. If specified, the
        version will be included in the default warning message.
    message : str, optional
        Custom warning message to raise.
    use_instead : str, optional
        Name of function to use in place of the deprecated function.
        If specified, this will be included in the default warning
        message.
    category : type[Warning], optional
        Type of warning to raise. Defaults to ``FutureWarning``.

    Examples
    --------

    >>> from dask.utils import _deprecated
    >>> @_deprecated(after_version="X.Y.Z", use_instead="bar")
    ... def foo():
    ...     return "baz"
    c                     8 j          d
d dz  n
d dz  ndz  dz  	d dz  nt          j                    fd            }|S )	N zwas deprecated after version zwas deprecated in version zis deprecated z(and will be removed in a future release.z Please use z	 instead.c                 B    t          j        d            | i |S )N   )r-   
stacklevel)warningswarn)r$   r%   r-   r#   msgs     r&   wrapperz/_deprecated.<locals>.decorator.<locals>.wrapper   s/    M#Q????4((((r(   )__name__	functoolswraps)r#   r9   r8   r*   r-   r+   r,   r)   s   ` @r&   	decoratorz_deprecated.<locals>.decorators   s    ?]%%%C(G}GGGG$>G>>>>''==C&<k<<<<C				) 	) 	) 	) 	) 	) 
		) r(   r"   )r)   r*   r+   r,   r-   r=   s   ````` r&   _deprecatedr>   N   s=    J        . r(   c                |     t          |d         t          t          f          r fdt          | D             S   | S )zApply function inside nested lists

    >>> inc = lambda x: x + 1
    >>> deepmap(inc, [[1, 2], [3, 4]])
    [[2, 3], [4, 5]]

    >>> add = lambda x, y: x + y
    >>> deepmap(add, [[1, 2], [3, 4]], [[10, 20], [30, 40]])
    [[11, 22], [33, 44]]
    r   c                *    g | ]}t          g|R  S r"   )deepmap).0itemsr#   s     r&   
<listcomp>zdeepmap.<locals>.<listcomp>   s)    >>>%%u%%%>>>r(   )
isinstancelistr   zip)r#   seqss   ` r&   rA   rA      sJ     $q'D(+,, >>>>3:>>>>tT{r(   c                    |s|S d}|}t          |t                    r"|dz  }|d         }t          |t                    "t          || |          S Nr      )rE   rF   ndeepmap)r#   seqntmps       r&   homogeneous_deepmaprP      se     
	A
C
S$

 	Q!f S$

  AtS!!!r(   c                      dk    rfd|D             S  dk    r fd|D             S t          |t                    r |d                   S  |          S )zCall a function on every element within a nested container

    >>> def inc(x):
    ...     return x + 1
    >>> L = [[1, 2], [3, 4, 5]]
    >>> ndeepmap(2, inc, L)
    [[2, 3], [4, 5, 6]]
    rK   c                &    g | ]} |          S r"   r"   )rB   itemr#   s     r&   rD   zndeepmap.<locals>.<listcomp>   s!    +++tT

+++r(   c                8    g | ]}t          d z
  |          S )rK   )rL   )rB   rS   r#   rN   s     r&   rD   zndeepmap.<locals>.<listcomp>   s)    <<<Qd++<<<r(   r   )rE   rF   )rN   r#   rM   s   `` r&   rL   rL      s     	Avv++++s++++	
Q<<<<<<<<<	C		 tCF||tCyyr(   c                f    	 t          |           S # t          $ r}t          |          |d}~ww xY w)zrAttempt to import a required dependency.

    Raises a RuntimeError if the requested module is not available.
    N)r   ImportErrorRuntimeError)mod_name	error_msges      r&   import_requiredr[      sD    
-X&&& - - -9%%1,-s    
0+0 c              #  ,  K   |                      d          } | rd| z   } t          j        | |          \  }}t          j        |           t          j        |           	 |V  t          j                            |          rwt          t                    5  t          j        
                    |          rt          j        |           nt          j        |           ddd           dS # 1 swxY w Y   dS dS # t          j                            |          rut          t                    5  t          j        
                    |          rt          j        |           nt          j        |           ddd           w # 1 swxY w Y   w w xY w)a  
    Function to create and return a unique temporary file with the given extension, if provided.

    Parameters
    ----------
    extension : str
        The extension of the temporary file to be created
    dir : str
        If ``dir`` is not None, the file will be created in that directory; otherwise,
        Python's default temporary directory is used.

    Returns
    -------
    out : str
        Path to the temporary file

    See Also
    --------
    NamedTemporaryFile : Built-in alternative for creating temporary files
    tmp_path : pytest fixture for creating a temporary directory unique to the test invocation

    Notes
    -----
    This context manager is particularly useful on Windows for opening temporary files multiple times.
    .dirN)lstriptempfilemkstemposcloseremovepathexistsr   OSErrorisdirshutilrmtree)	extensionr`   handlefilenames       r&   tmpfilerp      s     6   %%I $)O	'	s;;;FHHVIh(7>>(## 	('"" ( (7==** (M(++++Ih'''	( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( (	( 	(27>>(## 	('"" ( (7==** (M(++++Ih'''	( ( ( ( ( ( ( ( ( ( ( ( ( ( ( (	(sD   !C= A	C..C25C2=4F1A	F:FF

FF
Fc              #  P  K   t          j        |           }	 |V  t          j                            |          rt          j                            |          rCt          t                    5  t          j	        |           ddd           dS # 1 swxY w Y   dS t          t                    5  t          j
        |           ddd           dS # 1 swxY w Y   dS dS # t          j                            |          rt          j                            |          rAt          t                    5  t          j	        |           ddd           w # 1 swxY w Y   w t          t                    5  t          j
        |           ddd           w # 1 swxY w Y   w w xY w)a  
    Function to create and return a unique temporary directory.

    Parameters
    ----------
    dir : str
        If ``dir`` is not None, the directory will be created in that directory; otherwise,
        Python's default temporary directory is used.

    Returns
    -------
    out : str
        Path to the temporary directory

    Notes
    -----
    This context manager is particularly useful on Windows for opening temporary directories multiple times.
    r_   N)rb   mkdtemprd   rg   rh   rj   r   ri   rk   rl   rf   r`   dirnames     r&   tmpdirru      s     ( 3'''G	'7>>'"" 	'w}}W%% 'g&& + +M'***+ + + + + + + + + + + + + + + + + + g&& ' 'Ig&&&' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '	' 	'27>>'"" 	'w}}W%% 'g&& + +M'***+ + + + + + + + + + + + + + + + g&& ' 'Ig&&&' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '	'sx   C# /BBB2CCC#AF%6EF%EF%EF%7FF%FF%F F%wc              #  J  K   t          |          5 } |||          }	 |                    |            	 |                                 n:# t          $ r Y n.w xY w# 	 |                                 w # t          $ r Y w w xY wxY w|V  d d d            d S # 1 swxY w Y   d S )N)rm   )mode)rp   writere   AttributeError)textrm   openrx   ro   fs         r&   filetextr~     s     	9	%	%	% 
D%%%	GGDMMM				!   				!    
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
si   BAAB
ABABBA43B4
B	>B B	BBBBc              #     K   t          j                    }t          j        |            	 d V  t          j        |           d S # t          j        |           w xY wN)rd   getcwdchdir)new_cwdold_cwds     r&   changed_cwdr   '  s[      ikkGHW
s   A Ac              #     K   t          |           5 }t          |          5  |V  d d d            n# 1 swxY w Y   d d d            d S # 1 swxY w Y   d S r   )ru   r   rs   s     r&   tmp_cwdr   1  s      	 !! 	 	MMM	 	 	 	 	 	 	 	 	 	 	 	 	 	 	                 s,   A3A7	A7	AAAc                  "    e Zd ZdZdZd Zd ZdS )IndexCallablezProvide getitem syntax for functions

    >>> def inc(x):
    ...     return x + 1

    >>> I = IndexCallable(inc)
    >>> I[3]
    4
    fnc                    || _         d S r   r   )selfr   s     r&   __init__zIndexCallable.__init__E  s    r(   c                ,    |                      |          S r   r   )r   keys     r&   __getitem__zIndexCallable.__getitem__H  s    wws||r(   N)r:   
__module____qualname____doc__	__slots__r   r   r"   r(   r&   r   r   8  sC          I      r(   r   tTc              #    K   |rt                      nt                      5  |                                 D ]\  }}	 t          j        t          j                            |                     n# t          $ r Y nw xY w ||d|z             }	 |                    |           	 |	                                 # t          $ r Y w xY w# 	 |	                                 w # t          $ r Y w w xY wxY wt          |           V  | D ]a}t          j                            |          r@t          t                    5  t          j        |           ddd           n# 1 swxY w Y   b	 ddd           dS # 1 swxY w Y   dS )aS  Dumps a number of textfiles to disk

    Parameters
    ----------
    d : dict
        a mapping from filename to text like {'a.csv': '1,1
2,2'}

    Since this is meant for use in tests, this context manager will
    automatically switch to a temporary current directory, to avoid
    race conditions when running tests in parallel.
    rv   N)r   r
   rC   rd   makedirsrg   rt   ri   ry   re   rz   rF   rh   r   rf   )dr|   rx   
use_tmpdirro   r{   r}   s          r&   	filetextsr   L  s(      !	3kmm ( (ggii 	 	NHdBGOOH556666   XsTz**AGGIIII%   DGGIIII%   D 1gg 	( 	(Hw~~h'' (g&& ( (Ih'''( ( ( ( ( ( ( ( ( ( ( ( ( ( (	(#( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( (s   E61A.-E6.
A;8E6:A;;E6C	$B98E69
CE6CE6	C0C C0 
C-*C0,C--C00AE6;EE6E  E6#E $E66E:=E:c                    t          | t                    rt          |           } t          | t          t          f          r"t          t	          t
          |                     } | S )zMake nested iterators concrete lists

    >>> data = [[1, 2], [3, 4]]
    >>> seq = iter(map(iter, data))
    >>> concrete(seq)
    [[1, 2], [3, 4]]
    )rE   r   rF   tuplemapconcreterM   s    r&   r   r   p  sS     #x   3ii#t}%% '3x%%&&Jr(   rN   intc                   ddl }t          |          }|                    dg|z             }|                    d|d                   sJ t	          |          dk     sJ t          ||j        j                  s|j                            |          }|                    |           }|	                    | d          }t          t          |dd         |dd                             D ]\  }\  }}	||||k    ||	k     z  <   |S )zPseudorandom array of integer indexes

    >>> pseudorandom(5, [0.5, 0.5], random_state=123)
    array([1, 0, 0, 1, 1], dtype=int8)

    >>> pseudorandom(10, [0.5, 0.2, 0.2, 0.1], random_state=5)
    array([0, 2, 0, 3, 0, 1, 2, 1, 0, 0], dtype=int8)
    r   NrK      i1dtype)numpyrF   cumsumallcloselenrE   randomRandomStaterandom_sampleempty	enumeraterG   )
rN   prandom_statenpcpxoutilowhighs
             r&   pseudorandomr     s    QA	A37		B;;q"R&!!!!!q66C<<<<lBI$9:: ;y,,\::""1%%A
((1D(
!
!C#C3B3ABB$8$899 ) );C'(Q#X!d(#$$Jr(   returnrF   c                V   ddl }t          fddD                       s|j                                                          d| z  dz            }t          |                    ||j                                      | df                    }t          |          | k    sJ |S )	a  Return a list of arrays that can initialize
    ``np.random.RandomState``.

    Parameters
    ----------
    n : int
        Number of arrays to return.
    random_state : int or np.random.RandomState, optional
        If an int, is used to seed a new ``RandomState``.
    r   Nc              3  8   K   | ]}t          |          V  d S r   hasattr)rB   attrr   s     r&   	<genexpr>z$random_state_data.<locals>.<genexpr>  s>        (,d##     r(   )normalbetabytesuniformip     r   r   )
r   allr   r   r   rF   
frombufferuint32reshaper   )rN   r   r   random_datals    `   r&   random_state_datar     s         0V     ; y,,\::$$S1Wq[11KR]];bi]88@@!RIIJJAq66Q;;;;Hr(   boolc                ~    t          | t                    p(t          | t                    o|                                 S )zj
    >>> is_integer(6)
    True
    >>> is_integer(42.0)
    True
    >>> is_integer('abc')
    False
    )rE   r   float
is_integer)r   s    r&   r   r     s0     a""Oz!U';';'NOr(   c                   t          | t          j                  rt          | j                  S t          | d|           } t          | t                    rt          j        | j	                  S t          j        |           S )z@Version of inspect.getargspec that works with partial and warps.__wrapped__)
rE   r;   partial
getargspecr#   getattrtypeinspectgetfullargspecr   )r#   s    r&   r   r     sn    $	)** %$)$$$4--D$ ,%dm444%d+++r(   c                r   | t           v rdS | t          v rdS 	 t          |           }n# t          $ r Y dS w xY w	 |j        d         dk    ot          | t                    }n# t          $ r d}Y nw xY w|r	|j        rdS |j        dnt          |j                  }t          |j                  |z
  |z
  dk    S )a  Does this function take multiple arguments?

    >>> def f(x, y): pass
    >>> takes_multiple_arguments(f)
    True

    >>> def f(x): pass
    >>> takes_multiple_arguments(f)
    False

    >>> def f(x, y=None): pass
    >>> takes_multiple_arguments(f)
    False

    >>> def f(*args): pass
    >>> takes_multiple_arguments(f)
    True

    >>> class Thing:
    ...     def __init__(self, a): pass
    >>> takes_multiple_arguments(Thing)
    False

    FTr   r   NrK   )
ONE_ARITY_BUILTINSMULTI_ARITY_BUILTINSr   	Exceptionr$   rE   r   varargsdefaultsr   )r#   r   specis_constructor	ndefaultss        r&   takes_multiple_argumentsr   	  s    2 !!!u	%	%	%t$   uu1/JJtT4J4J     4< t]*DM0B0BIty>>I%6::s   ( 
66&A! !A0/A0	list[str]c                p    t          j        |           }d |j                                        D             S )z7Get all non ``*args/**kwargs`` arguments for a functionc                N    g | ]"\  }}|j         |j        |j        |j        fv  |#S r"   )kindPOSITIONAL_OR_KEYWORDPOSITIONAL_ONLYKEYWORD_ONLY)rB   rN   r   s      r&   rD   z"get_named_args.<locals>.<listcomp>;  sB       Aq6a-q/@!.QQQ 	
QQQr(   )r   	signature
parametersrC   )r#   ss     r&   get_named_argsr   8  sA    $A L&&((   r(   c                  L    e Zd ZdZd	dZd	dZd	dZd Zd Ze	d             ZdS )
DispatchzSimple single dispatch.Nc                8    i | _         i | _        |r	|| _        d S d S r   )_lookup_lazyr:   )r   names     r&   r   zDispatch.__init__E  s-    
 	! DMMM	! 	!r(   c                0      fd}| ||          n|S )z7Register dispatch of `func` on arguments of type `type`c                ~    t          t                    rD ]}                    ||            n
| j        <   | S r   )rE   r   registerr   )r#   r   r   r   s     r&   r9   z"Dispatch.register.<locals>.wrapperN  sS    $&& * + +AMM!T****+ &*T"Kr(   r"   )r   r   r#   r9   s   ``  r&   r   zDispatch.registerK  s;    	 	 	 	 	 	 !% 0wwt}}}g=r(   c                0      fd}| ||          n|S )z
        Register a registration function which will be called if the
        *toplevel* module (e.g. 'pandas') is ever loaded.
        c                    | j         <   | S r   )r   )r#   r   toplevels    r&   r9   z'Dispatch.register_lazy.<locals>.wrapper^  s    #'DJx Kr(   r"   )r   r   r#   r9   s   ``  r&   register_lazyzDispatch.register_lazyX  s;    	 	 	 	 	 	 !% 0wwt}}}g=r(   c                   | j         }|j        D ]}	 ||         }||ur|||<   |c S # t          $ r Y nw xY w|j                            d          \  }}}	 | j        |         } |             | j                            |d           |                     |          c S # t          $ r Y w xY wt          d|           )z8Return the function implementation for the given ``cls``r^   NzNo dispatch for )	r   __mro__KeyErrorr   	partitionr   popdispatch	TypeError)r   clslkcls2implr   _r   s           r&   r  zDispatch.dispatchd  s   \K 	* 	*D$x d??"BsG     "_66s;;NHa*:h/ 



x...}}S)))))     0300111s   '
44B
B,+B,c                ^    |                      t          |                    } ||g|R i |S )zJ
        Call the corresponding method based on type of argument.
        )r  r   )r   argr$   r%   meths        r&   __call__zDispatch.__call__}  s;     }}T#YY''tC)$)))&)))r(   c                z    	 |                      t                    }|j        S # t          $ r d| j        z  cY S w xY w)NzSingle Dispatch for %s)r  objectr   r  r:   )r   r#   s     r&   r   zDispatch.__doc__  sN    	<==((D< 	< 	< 	<+dm;;;;	<s    # ::r   )
r:   r   r   r   r   r   r   r  r  propertyr"   r(   r&   r   r   B  s        !!! ! ! !> > > >
> 
> 
> 
>2 2 22* * * < < X< < <r(   r   Nonec                    	 t          j        |            dS # t          $ r}|j        t          k    r Y d}~dS d}~ww xY w)z,
    Ensure that a file does not exist.
    N)rd   unlinkri   errnor   )ro   rZ   s     r&   ensure_not_existsr    s`    
	(   7f s    
>9>c                    |                                  }|dk    s|                    d          r| S d|v rd|vrd| v r| dz   S | dz   S | S )Nz>>>z>>> #z+SKIPz
# doctest:z, +SKIPz  # doctest: +SKIP)strip
startswith)linestrippeds     r&   _skip_doctestr    sn    zz||H5H//88	(		wh664)##...r(   c                n    | dS d                     d |                     d          D                       S )Nr\   
c                ,    g | ]}t          |          S r"   )r  )rB   r  s     r&   rD   z skip_doctest.<locals>.<listcomp>  s     FFFdmD))FFFr(   )joinsplit)docs    r&   skip_doctestr     s7    
{r99FFciiooFFFGGGr(   c                   |                      d          fdt          t                    dz
            D             }t                      }t	          |                                          D ]\  }}||v rjd|z   }|                             ||          |<   |dz                                dt          |          z  dt          |          z            |dz   <   s|                    |           d                              S )Nr  c                    i | ]n}|d z                                             t          d |d z                                             D                       S||                                          oS )rK   c              3  "   K   | ]
}|d k    V  dS )-Nr"   )rB   cs     r&   r   z*extra_titles.<locals>.<dictcomp>.<genexpr>  s&      'O'OQS'O'O'O'O'O'Or(   )r  r   )rB   r   liness     r&   
<dictcomp>z extra_titles.<locals>.<dictcomp>  s       Q< %('O'O%A,:L:L:N:N'O'O'O$O$O	58>>  r(   rK   zExtra r$  )	r  ranger   setsortedrC   replacer   r  )r  titlesseenr   title	new_titler&  s         @r&   extra_titlesr0    s
   IIdOOE   s5zzA~&&  F 55D6<<>>**  5D== 5(IQx''y99E!H Q<//c%jj0@#IBVWWE!a%LLHHUOOOO99Ur(   c                   ddl } |j        |          r"d                    |j        |j        |          }nd|j         d| d}d}|                     d          }	|	d	k    r| d|	d
z            }
| |	d
z   d         }|dk    r:|                    d          }	|d|	d
z            }
||	d
z   d         }|dz  }|dk    :t          j        d|                              d          }|r||	                    d          dz   g}ng }|d| }|
|||d|dg|z   |gz   }n|
||||dg|z   |gz   }d
                    |          } | S )z4Expand docstring by adding disclaimer and extra textr   Nz*This docstring was copied from {}.{}.{}.

zThis docstring was copied from r^   z.

z5Some inconsistencies with the Dask version may exist.

r   r4   rK   z\s*r  zKnown inconsistencies: 
 r\   )r   isclassformatr   r:   findrematchgrouprstripr  )r  r  r   extra
skipblocksinconsistenciesr   l1l2r   headtailindentmorel3bitss                   r&   ignore_warningrE    s   NNNws J;BBNL
 
 Js|IIdIII	@BABww7QU7|1q577|1nn		&!!A!a%=DA=D!OJ	 1nn &$''--a00 	ELL..78DDD&?o??B&"b&"f=DvMDD&"fb&9D@D6IDggdmmJr(   c                    |                      d          }|D ]?fdt          |          D             }t          |          dk    r|\  \  }}|dz   ||<   @d                    |          S )z,Mark unsupported arguments with a disclaimerr  c                T    g | ]$\  }}t          j        d z   dz   |           ||f%S )z^\s*z ?:)r6  r7  )rB   r   r  r	  s      r&   rD   z)unsupported_arguments.<locals>.<listcomp>  sL     
 
 
4x#-t44
I
 
 
r(   rK   z  (Not supported in Dask))r  r   r   r  )r  r$   r&  subsetr   r  r	  s         @r&   unsupported_argumentsrI    s    IIdOOE : :
 
 
 
$U++
 
 

 v;;! KYa99E!H99Ur(   c                   |pg }t          | |j                  }t          |dd          }t          |t                    r|j        }|st          |dd          }|d}|sH| j        dv r?|                                 D ]*}t          ||j        d          }	|	|	j        r	|	j        } n+|rt          || |j        |||          }n|r||                    d          dz   z  }	 t          |          t          |          }
fd|
D             }n# t          $ r g }Y nw xY wt          |          d	k    r|                    |           t          |          d	k    rt          ||          }t          |          }t          |          }|S )
z0Helper function for derived_from to ease testingr   Nr\   >   Series	DataFrame)r:  r;  r<  r  r2  c                    g | ]}|v|	S r"   r"   )rB   mmethod_argss     r&   rD   z!_derived_from.<locals>.<listcomp>&  s#    JJJqQk5I5I5I5I5Ir(   r   )r   r:   rE   r  fgetmror   rE  r9  r   
ValueErrorr   extendrI  r   r0  )r  methodua_argsr:  r;  r<  original_methodr  obj
obj_methodoriginal_argsnot_supportedrO  s               @r&   _derived_fromr[    s    mG c6?33O
/9d
3
3C/8,, <). 	</9d;;C
{  3<#:::7799 	 	C fot<<J%**<% (  
+O!+
 
 
 
 +u||D!!F**$V,,&77JJJJMJJJ   
7||aW%%%
=A#C77
s

C
s

CJs   $,D D D c                *     pg  fd}|S )a  Decorator to attach original class's docstring to the wrapped method.

    The output structure will be: top line of docstring, disclaimer about this
    being auto-derived, any extra text associated with the method being patched,
    the body of the docstring and finally, the list of keywords that exist in
    the original method but not in the dask version.

    Parameters
    ----------
    original_klass: type
        Original class which the method is derived from
    version : str
        Original package version which supports the wrapped method
    ua_args : list
        List of keywords which Dask doesn't support. Keywords existing in
        original but not in Dask will automatically be added.
    skipblocks : int
        How many text blocks (paragraphs) to skip from the start of the
        docstring. Useful for cases where the target has extra front-matter.
    inconsistencies: list
        List of known inconsistencies with method whose docstrings are being
        copied.
    c                    	 t           dd           pd}t           |           _         S # t          $ rF j                            d          d         t          j                    fd            }|cY S w xY w)Nr   r\   )rU  r:  r;  r<  r^   r   c                 r    dj          d}d}||                              z  }t          |          )NzBase package doesn't support 'z'.z) Use {0} {1} or later to use this method.)r:   r4  NotImplementedError)r$   r%   r8   msg2rT  module_namer)   s       r&   wrappedz.derived_from.<locals>.wrapper.<locals>.wrapped`  sF    JvJJJ&FD4;;{G<<<C)#...r(   )r   r[  r   rz   r   r  r;   r<   )	rT  r:  rb  ra  r<  original_klassr;  rU  r)   s	   `  @r&   r9   zderived_from.<locals>.wrapperP  s    	FIt44:E*% /  FN M 	 	 	(399#>>qAK_V$$/ / / / / / %$/ NNN	s   .4 ABBr"   )rc  r)   rU  r;  r<  r9   s   ````` r&   derived_fromrd  4  sF    4 mG        4 Nr(   strc                D   t          | t          j                  rt          | j                  S t          | t
                    r| j        dd         S t          | dd          pd}t          t          |           dd          pd}d|v rd|k    r| j	        dd         S d|v rd	|k    r| j
        dd         S d
|v r%d|k    rdt          | j                  z   dd         S 	 | j        }|dk    rdS |dd         S # t          $ r t          |           dd         cY S w xY w)zGet the name of a function.N2   r   r\   r:   toolzcurrymultipledispatch
Dispatcherr   	vectorize
vectorize_z<lambda>lambda)rE   r;   r   funcnamer#   methodcallerrT  r   r   	func_namer   pyfuncr:   rz   re  )r#   ra  	type_namer   s       r&   ro  ro  m  s]    $	)** #	"""$%%  {3B3$d339rKT

J55;I +'Y"6"6~crc""[((\Y-F-Fy"~++":":x444crc::}:8CRCy   4yy"~s   "C; 1	C; ;!DDFtypr   shortc                <   t          | t                    st          t          |                     S 	 | j        r| j        dk    r| j        S |r| j                            d          ^}}n| j        }|dz   | j        z   S # t          $ r t          |           cY S w xY w)z
    Return the name of a type

    Examples
    --------
    >>> typename(int)
    'int'

    >>> from dask.core import literal
    >>> typename(literal)
    'dask.core.literal'
    >>> typename(literal, short=True)
    'dask.literal'
    builtinsr^   )rE   r   typenamer   r:   r  rz   re  )rt  ru  moduler  s       r&   rx  rx    s     c4   #S		"""
~ 	/:!=!=< ( ^11#66
C<#,..   3xxs   A? 2A? ?BBr   c                    t          | t                    r| S t          | d          r|                                 S 	 t          |           S # t          $ r}t          d|  d          |d}~ww xY w)a  Attempt to turn `s` into bytes.

    Parameters
    ----------
    s : Any
        The object to be converted. Will correctly handled
        * str
        * bytes
        * objects implementing the buffer protocol (memoryview, ndarray, etc.)

    Returns
    -------
    b : bytes

    Raises
    ------
    TypeError
        When `s` cannot be converted

    Examples
    --------
    >>> ensure_bytes('123')
    b'123'
    >>> ensure_bytes(b'123')
    b'123'
    >>> ensure_bytes(bytearray(b'123'))
    b'123'
    encodeObject z6 is neither a bytes object nor can be encoded to bytesN)rE   r   r   r{  r   r  r   rZ   s     r&   ensure_bytesr~    s    : !U 
	H		 xxzz	88O 	 	 	S!SSS 	s   A 
A/A**A/c                    t          | t                    r| S t          | d          r|                                 S 	 t	          j        |           S # t
          $ r}t          d|  d          |d}~ww xY w)zuTurn string or bytes to string

    >>> ensure_unicode('123')
    '123'
    >>> ensure_unicode(b'123')
    '123'
    decoder|  z2 is neither a str object nor can be decoded to strN)rE   re  r   r  codecsr   r  r}  s     r&   ensure_unicoder    s     !S 
	H		 xxzz	=### 	 	 	O!OOO 	s   A 
A4A//A4c                    | ||z  z  |z  S )z

    >>> digit(1234, 0, 10)
    4
    >>> digit(1234, 1, 10)
    3
    >>> digit(1234, 2, 10)
    2
    >>> digit(1234, 3, 10)
    1
    r"   )rN   kbases      r&   digitr    s     a<$r(   c                H    t          |           }|||<   t          |          S )zB

    >>> insert(('a', 'b', 'c'), 0, 'x')
    ('x', 'b', 'c')
    )rF   r   )tuplocvalLs       r&   insertr    s#     	S		AAcF88Or(   c                    t          |           \  }t          d           fd            t          fd                                D                       S )N)maxsizec                d    |          sdS dt          fd|          D                       z   }|S )NrK   c              3  .   K   | ]} |          V  d S r   r"   rB   dep_keymax_depth_by_depss     r&   r   z>dependency_depth.<locals>.max_depth_by_deps.<locals>.<genexpr>  s/      HH7%%g..HHHHHHr(   )max)r   r   depsr  s     r&   r  z+dependency_depth.<locals>.max_depth_by_deps  sD    Cy 	1HHHHd3iHHHHHHr(   c              3  .   K   | ]} |          V  d S r   r"   r  s     r&   r   z#dependency_depth.<locals>.<genexpr>  s/      EEg  ))EEEEEEr(   )r   r   r  keys)dskr  r  r  s     @@r&   dependency_depthr    st    smmGD!t      EEEEEEEEEEr(   c                :    dD ]}| dk     r
| dd| c S | dz  } d S )N)r   KBMBGBTBg      @z3.1fr2   r"   )numr   s     r&   memory_reprr    sL    .  <<$$$$$$$$v r(   c                   d |D             }t          d | D                       } t          d t          t          | |           D                       }ddt          |           z  z   |z  t          |           z  }dd                    d |D                       z  }d	                    fd
|D                       }d	                    |||||g          S )zFormats an ascii table for given columns and rows.

    Parameters
    ----------
    columns : list
        The column names
    rows : list of tuples
        The rows in the table. Each tuple must be the same length as
        ``columns``.
    c                @    g | ]}t          d  |D                       S )c              3  4   K   | ]}t          |          V  d S r   re  rB   r   s     r&   r   z(asciitable.<locals>.<listcomp>.<genexpr>$  s(      $$Q#a&&$$$$$$r(   )r   )rB   rs     r&   rD   zasciitable.<locals>.<listcomp>$  s/    333E$$!$$$$$333r(   c              3  4   K   | ]}t          |          V  d S r   r  r  s     r&   r   zasciitable.<locals>.<genexpr>%  s(      ,,qCFF,,,,,,r(   c           	   3     K   | ]D\  }}t          t          t          t          |                    t          |                    V  Ed S r   )r  r   r   )rB   r   r%  s      r&   r   zasciitable.<locals>.<genexpr>&  sF      VVTQ3s3sA;;''Q00VVVVVVr(   |z	 %%-%ds |z+%s++c              3  &   K   | ]}d |dz   z  V  dS )r$  r4   Nr"   )rB   rv   s     r&   r   zasciitable.<locals>.<genexpr>)  s*      ::aC1q5M::::::r(   r  c              3  "   K   | ]	}|z  V  
d S r   r"   )rB   r  row_templates     r&   r   zasciitable.<locals>.<genexpr>*  s(      44!\A%444444r(   )r   rG   r   r  )columnsrowswidthsheaderbardatar  s         @r&   
asciitabler    s     43d333D,,G,,,,,GVVSdW=U=UVVVVVF;W56&@LE'NN*F
388::6:::::
:C994444t44444D99c63c2333r(   c                    t          d |D                       rd |D             }|                     d                    |                     d S )Nc              3  B   K   | ]}t          |t                     V  d S r   )rE   re  rB   r   s     r&   r   zput_lines.<locals>.<genexpr>/  s/      
1
1az!S!!!
1
1
1
1
1
1r(   c                ,    g | ]}t          |          S r"   r  r  s     r&   rD   zput_lines.<locals>.<listcomp>0  s    '''AQ'''r(   r  )anyry   r  )bufr&  s     r&   	put_linesr  .  sX    

1
15
1
1
111 ('''''IIdiir(   zdict[str, methodcaller]_method_cachec                  X    e Zd ZU dZdZded<   edd            ZddZd Z	d	 Z
d
 ZeZdS )rp  z
    Return a callable object that calls the given method on its operand.

    Unlike the builtin `operator.methodcaller`, instances of this class are
    cached and arguments are passed at call time instead of build time.
    rT  re  rT  r   c                    | j         S r   r  r   s    r&   r#   zmethodcaller.funcB  s     {r(   c                    	 t           |         S # t          $ r0 t                              |           }||_        |t           |<   |cY S w xY wr   )r  r   r  __new__rT  )r  rT  r   s      r&   r  zmethodcaller.__new__G  sX    	 (( 	 	 	>>#&&D DK$(M&!KKK		s    7A	A	c                8     t          || j                  |i |S r   )r   rT  )r   _methodcaller__objr$   r%   s       r&   r  zmethodcaller.__call__P  s#    *wudk**D;F;;;r(   c                     t           | j        ffS r   )rp  rT  r  s    r&   
__reduce__zmethodcaller.__reduce__S  s    t{n--r(   c                2    d| j         j         d| j         dS N<z: >)	__class__r:   rT  r  s    r&   __str__zmethodcaller.__str__V  s"    <4>*<<dk<<<<r(   Nr   re  )rT  re  )r:   r   r   r   r   __annotations__r  r#   r  r  r  r  __repr__r"   r(   r&   rp  rp  7  s           IKKK   X   < < <. . .= = = HHHr(   rp  c                  .    e Zd ZdZdZd Zd Zd Zd ZdS )
itemgetterz;Variant of operator.itemgetter that supports equality testsindexc                    || _         d S r   r  )r   r  s     r&   r   zitemgetter.__init__a  s    


r(   c                    || j                  S r   r  )r   r   s     r&   r  zitemgetter.__call__d  s    }r(   c                     t           | j        ffS r   )r  r  r  s    r&   r  zitemgetter.__reduce__g  s    TZM**r(   c                ^    t          |           t          |          u o| j        |j        k    S r   )r   r  r   others     r&   __eq__zitemgetter.__eq__j  s'    DzzT%[[(FTZ5;-FFr(   N)	r:   r   r   r   r   r   r  r  r  r"   r(   r&   r  r  \  s`        EEI    + + +G G G G Gr(   r  c                      e Zd ZdZd Zd ZdS )MethodCachezAttribute access on this object returns a methodcaller for that
    attribute.

    Examples
    --------
    >>> a = [1, 3, 3]
    >>> M.count(a, 3) == a.count(3)
    True
    c                     t          |          S r   )rp  )r   rS   s     r&   __getattr__zMethodCache.__getattr__y  s    D!!!r(   c                *    t          t                    S r   )rF   r  r  s    r&   __dir__zMethodCache.__dir__|  s    M"""r(   N)r:   r   r   r   r  r  r"   r(   r&   r  r  n  s<         " " "# # # # #r(   r  c                      e Zd ZU dZ e            Zded<   ded<   ded<   ddd
Zd Zd Z	d Z
d Zd Zd Zd Zd ZeZdS )SerializableLocka  A Serializable per-process Lock

    This wraps a normal ``threading.Lock`` object and satisfies the same
    interface.  However, this lock can also be serialized and sent to different
    processes.  It will not block concurrent operations between processes (for
    this you should look at ``multiprocessing.Lock`` or ``locket.lock_file``
    but will consistently deserialize into the same lock.

    So if we make a lock in one process::

        lock = SerializableLock()

    And then send it over to another process multiple times::

        bytes = pickle.dumps(lock)
        a = pickle.loads(bytes)
        b = pickle.loads(bytes)

    Then the deserialized objects will operate as though they were the same
    lock, and collide as appropriate.

    This is useful for consistently protecting resources on a per-process
    level.

    The creation of locks is itself not threadsafe.
    z-ClassVar[WeakValueDictionary[Hashable, Lock]]_locksr   tokenr   lockNHashable | Nonec                   |pt          t          j                              | _        | j        t          j        v rt          j        | j                 | _        d S t                      | _        | j        t          j        | j        <   d S r   )re  uuiduuid4r  r  r  r  r   r   r  s     r&   r   zSerializableLock.__init__  se    /c$*,,//
:)000(/
;DIIIDI26)#DJ///r(   c                &     | j         j        |i |S r   )r  acquirer   r$   r%   s      r&   r  zSerializableLock.acquire       ty $1&111r(   c                &     | j         j        |i |S r   )r  releaser  s      r&   r  zSerializableLock.release  r  r(   c                8    | j                                          d S r   )r  	__enter__r  s    r&   r  zSerializableLock.__enter__  s    	r(   c                $     | j         j        |  d S r   )r  __exit__)r   r$   s     r&   r  zSerializableLock.__exit__  s    	D!!!!r(   c                4    | j                                         S r   )r  lockedr  s    r&   r  zSerializableLock.locked  s    y!!!r(   c                    | j         S r   )r  r  s    r&   __getstate__zSerializableLock.__getstate__  s
    zr(   c                0    |                      |           d S r   )r   r  s     r&   __setstate__zSerializableLock.__setstate__  s    er(   c                2    d| j         j         d| j         dS r  )r  r:   r  r  s    r&   r  zSerializableLock.__str__  s"    ;4>*;;dj;;;;r(   r   )r  r  )r:   r   r   r   r   r  r  r   r  r  r  r  r  r  r  r  r  r"   r(   r&   r  r    s          6 =P<O<Q<QFQQQQOOOJJJ< < < < <2 2 22 2 2  " " "" " "    < < < HHHr(   r  c                    ddl m} ddlm}  || g|          }||j        k    r8|                                                                                                S t                      S )z\Get an instance of the appropriate lock for a certain situation based on
    scheduler used.r   )multiprocessing)get_scheduler)collections	scheduler)	daskr  	dask.baser  getget_contextManagerr   r  )
collectionr   r  r  
actual_gets        r&   get_scheduler_lockr    s     %$$$$$''''''J<9MMMJ_(((**,,4466;;===r(   )copyr   Mapping[K, V]r	  
dict[K, V]c               @   t          |           t          u r|r|                                 n| S 	 | j        }n# t          $ r t          |           cY S w xY wi }t          j        |                                t                    D ]}|	                    |           |S )a/  Convert a generic Mapping into a dict.
    Optimize use case of :class:`~dask.highlevelgraph.HighLevelGraph`.

    Parameters
    ----------
    d : Mapping
    copy : bool
        If True, guarantee that the return value is always a shallow copy of d;
        otherwise it may be the input itself.
    )r   )
r   dictr	  layersrz   rh  uniquevaluesidupdate)r   r	  r  resultlayers        r&   ensure_dictr    s     Aww$&qvvxxxQ&   Aww Ffmmoo2666  eMs   8 AAr   Set[T]set[T]c               |    t          |           t          u r|r|                                 n| S t          |           S )zConvert a generic Set into a set.

    Parameters
    ----------
    s : Set
    copy : bool
        If True, guarantee that the return value is always a shallow copy of s;
        otherwise it may be the input itself.
    )r   r)  r	  )r   r	  s     r&   
ensure_setr    s5     Aww#~~&qvvxxxQ&q66Mr(   c                  Z    e Zd ZdZdZed             Zed             Zedd            ZdS )	OperatorMethodMixinz.A mixin for dynamically implementing operatorsr"   c                p   |j         }|                    d          r|dd         }n|dk    rd}d| d}|dv r&t          | ||                     |                     dS t          | ||                     |                     |dv rdS d	| d}t          | ||                     |d
                     dS )zbind operator to this classr  Nr   invinvert__)absr  negpos)eqgtgeltlenegetitem__rT)r  )r:   endswithsetattr_get_unary_operator_get_binary_operator)r  opr   r
  rmeths        r&   _bind_operatorz"OperatorMethodMixin._bind_operator   s     {== 	9DDU]]DD}}}222Cs66r::;;;;;Cs77;;<<<FFF"$NNNEC 8 8 8 F FGGGGGr(   c                    t           )z+Must return a method used by unary operatorr_  )r  r/  s     r&   r-  z'OperatorMethodMixin._get_unary_operator  
     "!r(   Fc                    t           )z,Must return a method used by binary operatorr3  )r  r/  r  s      r&   r.  z(OperatorMethodMixin._get_binary_operator  r4  r(   NF)	r:   r   r   r   r   classmethodr1  r-  r.  r"   r(   r&   r  r    sv        88IH H [H. " " [" " " " [" " "r(   r  c                     |                     d          }|                     d          }t          |           }|D ]\  }}|                    ||            ||i |S )zi

    >>> from operator import add
    >>> partial_by_order(5, function=add, other=[(1, 10)])
    15
    functionr  )r   rF   r  )r$   r%   r9  r  args2r   r	  s          r&   partial_by_orderr;  #  sp     zz*%%HJJwEJJE  3Q8U%f%%%r(   c                `   ddl m t          | d          pt          | d          }t          t          | d          ojt	          | j        t                    oPt          | d          o@t          fd| j        D                        o|pdt          t          |                     v           S )	aI  Is this object a numpy array or something similar?

    This function tests specifically for an object that already has
    array attributes (e.g. np.ndarray, dask.array.Array, cupy.ndarray,
    sparse.COO), **NOT** for something that can be coerced into an
    array object (e.g. Python lists and tuples). It is meant for dask
    developers and developers of downstream libraries.

    Note that this function does not correspond with NumPy's
    definition of array_like, which includes any object that can be
    coerced into an array (see definition in the NumPy glossary):
    https://numpy.org/doc/stable/glossary.html

    Examples
    --------
    >>> import numpy as np
    >>> is_arraylike(np.ones(5))
    True
    >>> is_arraylike(np.ones(()))
    True
    >>> is_arraylike(5)
    False
    >>> is_arraylike('cat')
    False
    r   )is_dask_collection__array_function____array_ufunc__shaper   c              3  .   K   | ]} |          V  d S r   r"   )rB   rN   r=  s     r&   r   zis_arraylike.<locals>.<genexpr>T  s/      ;;a&&q));;;;;;r(   zscipy.sparse)
r  r=  r   r   rE   r@  r   r  rx  r   )r   is_duck_arrayr=  s     @r&   is_arraylikerC  2  s    4 -,,,,,A344UCT8U8UM7 	Cqw&&	CAw	C ;;;;17;;;;;;	C Ana0A0AA
 
 
r(   c                      j         j         j         j        fdk    rdS  j         t          fddD                       o6t           fddD                       ot	          fddD                        S )	zLooks like a Pandas DataFrame)zpandas.core.framerL  Tc              3  8   K   | ]}t          |          V  d S r   r   rB   r   rt  s     r&   r   z$is_dataframe_like.<locals>.<genexpr>g  s-      PP4GCPPPPPPr(   )groupbyr?  mergemeanc              3  8   K   | ]}t          |          V  d S r   r   )rB   r   dfs     r&   r   z$is_dataframe_like.<locals>.<genexpr>h  s-      DDdD!!DDDDDDr(   )dtypesr  c              3  8   K   | ]}t          |          V  d S r   r   rF  s     r&   r   z$is_dataframe_like.<locals>.<genexpr>i  s-      EE4GC&&EEEEEEr(   r   r   )r  r   r:   r   r  )rK  rt  s   `@r&   is_dataframe_likerO  ]  s    
!67 <  
 t
,CPPPP+OPPPPP 	FDDDD.CDDDDD	FEEEE3DEEEEEEr(   c                      j         t          fddD                       o5t           fddD                       odj                                        vS )zLooks like a Pandas Seriesc              3  8   K   | ]}t          |          V  d S r   r   rF  s     r&   r   z!is_series_like.<locals>.<genexpr>q  s-      GG4GCGGGGGGr(   )rG  r?  rI  c              3  8   K   | ]}t          |          V  d S r   r   rB   r   r   s     r&   r   z!is_series_like.<locals>.<genexpr>r  s-      ??T4  ??????r(   )r   r   r  r  r   r:   lowerr   rt  s   `@r&   is_series_likerW  m  sr    
+CGGGG+FGGGGG 	0????->?????	03<--///r(   c                ~      j         }t           fddD                       od|j                                        v S )zLooks like a Pandas Indexc              3  8   K   | ]}t          |          V  d S r   r   rS  s     r&   r   z is_index_like.<locals>.<genexpr>{  s-      ;;GAt;;;;;;r(   rN  r  rT  rV  s   ` r&   is_index_likerZ  w  sK    
+C;;;;):;;;;; 	,s|))+++r(   c                >    dt          t          |                     v S )Ncupy)re  r   )r   s    r&   is_cupy_typer]    s    Sa\\!!r(   list[str | int]c                @    d t          j        d|           D             S )a  
    Sorting `key` function for performing a natural sort on a collection of
    strings

    See https://en.wikipedia.org/wiki/Natural_sort_order

    Parameters
    ----------
    s : str
        A string that is an element of the collection being sorted

    Returns
    -------
    tuple[str or int]
        Tuple of the parts of the input string where each part is either a
        string or an integer

    Examples
    --------
    >>> a = ['f0', 'f1', 'f2', 'f8', 'f9', 'f10', 'f11', 'f19', 'f20', 'f21']
    >>> sorted(a)
    ['f0', 'f1', 'f10', 'f11', 'f19', 'f2', 'f20', 'f21', 'f8', 'f9']
    >>> sorted(a, key=natural_sort_key)
    ['f0', 'f1', 'f2', 'f8', 'f9', 'f10', 'f11', 'f19', 'f20', 'f21']
    c                X    g | ]'}|                                 rt          |          n|(S r"   )isdigitr   )rB   parts     r&   rD   z$natural_sort_key.<locals>.<listcomp>  s/    TTTd1CIIITTTTr(   z(\d+))r6  r  r   s    r&   natural_sort_keyrd    s&    4 UTbhxQR>S>STTTTr(   float | strc                   t          | t          t          f          rt          |           S |                     dd          } t	          d | D                       sd| z   } t          t          |           dz
  dd          D ]}| |                                         s n|dz   }| d|         }| |d         }	 t          |          }n%# t          $ r}t          d|z            |d}~ww xY w	 t          |
                                         }n%# t          $ r}t          d	|z            |d}~ww xY w||z  }t          |          S )
a\  Parse byte string to numbers

    >>> from dask.utils import parse_bytes
    >>> parse_bytes('100')
    100
    >>> parse_bytes('100 MB')
    100000000
    >>> parse_bytes('100M')
    100000000
    >>> parse_bytes('5kB')
    5000
    >>> parse_bytes('5.4 kB')
    5400
    >>> parse_bytes('1kiB')
    1024
    >>> parse_bytes('1e6')
    1000000
    >>> parse_bytes('1e6 kB')
    1000000000
    >>> parse_bytes('MB')
    1000000
    >>> parse_bytes(123)
    123
    >>> parse_bytes('5 foos')
    Traceback (most recent call last):
        ...
    ValueError: Could not interpret 'foos' as a byte unit
    r2   r\   c              3  >   K   | ]}|                                 V  d S r   )ra  )rB   chars     r&   r   zparse_bytes.<locals>.<genexpr>  s*      ,,$t||~~,,,,,,r(   1rK   r   Nz$Could not interpret '%s' as a numberz'Could not interpret '%s' as a byte unit)rE   r   r   r+  r  r(  r   isalpharR  
byte_sizesrU  r   )	r   r   r  prefixsuffixrN   rZ   
multiplierr  s	            r&   parse_bytesro    s}   : !c5\"" 1vv			#rA,,!,,,,, !G3q66A:r2&&  t||~~ 	E	EEvvYFuvvYFQ&MM Q Q Q?&HIIqPQT/

 T T TBVKLLRSST ^Fv;;s0   :C
 

C,C''C,0D 
D2D--D2i  i@B i ʚ;l    J)l     I5          @                   rK   )kBr  r  r  PBKiBMiBGiBTiBPiBBr\   c                >    i | ]\  }}|                                 |S r"   )rU  rB   r  vs      r&   r'  r'    s&    :::tq!aggii:::r(   c                2    i | ]\  }}|d |v|d         |S )r   r   r"   r~  s      r&   r'  r'    s,    PPPtq!QP3a<<1Q4<<<r(   c                6    i | ]\  }}|d |v |dd         |S )r   Nr   r"   r~  s      r&   r'  r'    s0    NNNAqNSAXX1SbS61XXXr(   r   c                   | dk    r8t          | dz  dz            }t          | |dz  dz  z
  dz            }| d| dS | dk    r2t          | dz            }t          | |dz  z
  dz            }| d| d	S | d
k    r/t          | dz            }t          | |dz  z
            }| d| dS | dk    rd| z  S | dk    rd| dz  z  S d| dz  z  S )a  format integers as time

    >>> from dask.utils import format_time
    >>> format_time(1)
    '1.00 s'
    >>> format_time(0.001234)
    '1.23 ms'
    >>> format_time(0.00012345)
    '123.45 us'
    >>> format_time(123.456)
    '123.46 s'
    >>> format_time(1234.567)
    '20m 34s'
    >>> format_time(12345.67)
    '3hr 25m'
    >>> format_time(123456.78)
    '34hr 17m'
    >>> format_time(1234567.89)
    '14d 6hr'
    i       zd hri   <   zhr rN  iX  zm r   rK   z%.2f sMbP?z%.2f msg     @@z%.2f usg    .A)r   )rN   r   hrN  r   s        r&   format_timer    s   * 	D2QX]"d*++}}q}}};DMMQX#$$}}}}}7{{BKKAF
OO||q|||Avv!|DyyAG$$C  r(   r   c                    d d d d d d d}t          j                    | z
  }|D ]@}t           ||         |                    }|dk    r|d	k    r
|d
d         }| d| dc S AdS )a  Calculate a '3 hours ago' type string from a Python datetime.

    Examples
    --------
    >>> from datetime import datetime, timedelta

    >>> now = datetime.now()
    >>> format_time_ago(now)
    'Just now'

    >>> past = datetime.now() - timedelta(minutes=1)
    >>> format_time_ago(past)
    '1 minute ago'

    >>> past = datetime.now() - timedelta(minutes=2)
    >>> format_time_ago(past)
    '2 minutes ago'

    >>> past = datetime.now() - timedelta(hours=1)
    >>> format_time_ago(past)
    '1 hour ago'

    >>> past = datetime.now() - timedelta(hours=6)
    >>> format_time_ago(past)
    '6 hours ago'

    >>> past = datetime.now() - timedelta(days=1)
    >>> format_time_ago(past)
    '1 day ago'

    >>> past = datetime.now() - timedelta(days=5)
    >>> format_time_ago(past)
    '5 days ago'

    >>> past = datetime.now() - timedelta(days=8)
    >>> format_time_ago(past)
    '1 week ago'

    >>> past = datetime.now() - timedelta(days=16)
    >>> format_time_ago(past)
    '2 weeks ago'

    >>> past = datetime.now() - timedelta(days=190)
    >>> format_time_ago(past)
    '6 months ago'

    >>> past = datetime.now() - timedelta(days=800)
    >>> format_time_ago(past)
    '2 years ago'

    c                    | j         dz  S )Nim  daysdiffs    r&   <lambda>z!format_time_ago.<locals>.<lambda>K  s    di#o r(   c                    | j         dz  S )Ngp=
o>@r  r  s    r&   r  z!format_time_ago.<locals>.<lambda>L  s    ty94 r(   c                    | j         dz  S )N   r  r  s    r&   r  z!format_time_ago.<locals>.<lambda>M  s    di!m r(   c                    | j         S r   r  r  s    r&   r  z!format_time_ago.<locals>.<lambda>N  s    TY r(   c                    | j         dz  S )Nr  secondsr  s    r&   r  z!format_time_ago.<locals>.<lambda>O  s    dlT1 r(   c                    | j         dz  dz  S )Nr  r  r  r  s    r&   r  z!format_time_ago.<locals>.<lambda>P  s    t 3b 8 r(   )yearsmonthsweeksr  hoursminutesr   rK   Nr   r2   z agozJust now)r   nowr   )rN   unitsr  unitdurs        r&   format_time_agor    s    j .-44++&&1188 E <>>AD ' '+%+d##$$77axxCRCy&&D&&&&&&  :r(   c                J    dD ]\  }}| |dz  k    r| |z  dd| dc S |  dS )a  Format bytes as text

    >>> from dask.utils import format_bytes
    >>> format_bytes(1)
    '1 B'
    >>> format_bytes(1234)
    '1.21 kiB'
    >>> format_bytes(12345678)
    '11.77 MiB'
    >>> format_bytes(1234567890)
    '1.15 GiB'
    >>> format_bytes(1234567890000)
    '1.12 TiB'
    >>> format_bytes(1234567890000000)
    '1.10 PiB'

    For all values < 2**60, the output is always <= 10 characters.
    ))Pirt  )Tirs  )Girr  )Mirq  )kirp  g?z.2fr2   r|  z Br"   )rN   rl  r  s      r&   format_bytesr  \  sZ    & , ,	 C<<!e+++&++++++ 888Or(   r  gư>g&.>r  r  iQ i:	 )r   msusnsrN  r  r   rv   )secondminutehourdayweekmillisecondmicrosecond
nanosecondc                     i | ]\  }}|d z   |S rc  r"   r~  s      r&   r'  r'    s"    111DAqQWa111r(   c                >    i | ]\  }}|                                 |S r"   )upperr~  s      r&   r'  r'    s&    IIIA		1IIIr(   r  defaultstr | Literal[False]c                    d S r   r"   r   r  s     r&   parse_timedeltar    s    Cr(   str | float | timedeltac                    d S r   r"   r  s     r&   r  r    s	     Cr(   c                4   | dS t          | t                    r8|                                 } t          |           | k    rt          |           n| S t          | t                    rt          |           } |                     dd          } | d                                         sd| z   } t          t          |           dz
  dd          D ]}| |         
                                s n|dz   }| d|         }| |d         p|}|du rt          d	|            t          |t
                    st          d
|          t          |          }t          |                                         }||z  }t          |          |k    rt          |          }|S )af  Parse timedelta string to number of seconds

    Parameters
    ----------
    s : str, float, timedelta, or None
    default: str or False, optional
        Unit of measure if s  does not specify one. Defaults to seconds.
        Set to False to require s to explicitly specify its own unit.

    Examples
    --------
    >>> from datetime import timedelta
    >>> from dask.utils import parse_timedelta
    >>> parse_timedelta('3s')
    3
    >>> parse_timedelta('3.5 seconds')
    3.5
    >>> parse_timedelta('300ms')
    0.3
    >>> parse_timedelta(timedelta(seconds=3))  # also supports timedeltas
    3
    Nr2   r\   r   ri  rK   r   FzMissing time unit: z"default must be str or False, got )rE   r   total_secondsr   r   re  r+  ra  r(  r   rj  rR  r  r   timedelta_sizesrU  )	r   r  r   r  rl  rm  rN   rn  r  s	            r&   r  r    s   . 	yt!Y ,OOQ1s1vvv!+!V FF			#rAQ4<<>> !G3q66A:r2&&  t||~~ 	E	EEvvYFuvvY!'F2q22333fc"" JHWHHIIIfA 0J^F
6{{fVMr(   c                \    	 |t          j        |           j        v S # t          $ r Y dS w xY w)NF)r   r   r   r   )r#   keywords     r&   has_keywordr    sB    '+D11<<<   uus    
++c                v    t          | t          t          f          sdS | sdS dt          | d                   z   S rJ   )rE   rF   r   ndimlistr   s    r&   r  r    sA    cD%=)) $q $q8CF####r(   c              #     K   g d}}t          |           }t          |d          }|J||k    sJ ||z   |k    r+|                    |           ||z  }t          |d          }n|sJ |V  g d}}|J|r|V  dS dS )a
  Split sizes into chunks of total max_size each

    Parameters
    ----------
    sizes : iterable of numbers
        The sizes to be chunked
    max_size : number
        Maximum total size per chunk.
        It must be greater or equal than each size in sizes
    r   N)iternextappend)sizesmax_sizechunk	chunk_sum
iter_sizessizes         r&   iter_chunksr    s       19EeJ
D!!D

xtx''LLI
D))DDLLLKKK!19E 
   r(   z[a-f]+i c                D   t          |           t          u r|                                 } t          |           t          u r| d         } 	 |                     d          }|d         d                                         s5|d                             d          d                             d          }n|d         }|dd         D ]L}|                                r6t          |          dk    rt          	                    |          	|d|z   z  }L t          |          dk    rt          j	        d	|          rd
S |d         dk    rF|                    d                                          d                             d          d         }|S # t          $ r Y dS w xY w)aw  
    >>> key_split('x')
    'x'
    >>> key_split('x-1')
    'x'
    >>> key_split('x-1-2-3')
    'x'
    >>> key_split(('x-2', 1))
    'x'
    >>> key_split("('x-2', 1)")
    'x'
    >>> key_split("('x', 1)")
    'x'
    >>> key_split('hello-world-1')
    'hello-world'
    >>> key_split(b'hello-world-1')
    'hello-world'
    >>> key_split('ae05086432ca935f6eba409a8ecd4896')
    'data'
    >>> key_split('<module.submodule.myclass object at 0xdaf372')
    'myclass'
    >>> key_split(None)
    'Other'
    >>> key_split('x-abcdefab')  # ignores hex
    'x'
    >>> key_split('_(x)')  # strips unpleasant characters
    'x'
    r   r$  ,z_'()"rK   N       z[a-f0-9]{32}r  r  z<>r^   r   Other)r   r   r  r   r  rj  r  r   hex_patternr7  r6  r   )r   wordsr  words       r&   	key_splitr    s   < Aww%HHJJAww%aDQx{""$$ 	1X^^C((+11(;;FF1XF!""I 	 	D||~~ D		Q;#4#4T#:#:#F#*$v;;"/6!B!B6ayCd++1133A6<<SAA"EM   wws   
C1F =AF 
FF	exclusiveIterable | Nonec                   t          |           }|t          u s	|t          u r| S t          |           S |t          u r| rddlm} | d         }t          |          |u re|} |t          |j                  |j        t          |j	                  |j
                  ft          fd| dd         D                       z   S t          |          r'|ft          fd| dd         D                       z   S |t          u rfd| D             S |t          u r fd|                                 D             S 	 | v rt          |           S n# t          $ r Y nw xY w|t          u rt          fd	| D                       S | S )
a  Convert an object to a string

    If ``exclusive`` is specified, search through `obj` and convert
    values that are in ``exclusive``.

    Note that when searching through dictionaries, only values are
    converted, not the keys.

    Parameters
    ----------
    obj : Any
        Object (or values within) to convert to string
    exclusive: Iterable, optional
        Set of values to search for when converting values to strings

    Returns
    -------
    result : type(obj)
        Stringified copy of ``obj`` or ``obj`` itself if it is already a
        string or bytes.

    Examples
    --------
    >>> stringify(b'x')
    b'x'
    >>> stringify('x')
    'x'
    >>> stringify({('a',0):('a',0), ('a',1): ('a',1)})
    "{('a', 0): ('a', 0), ('a', 1): ('a', 1)}"
    >>> stringify({('a',0):('a',0), ('a',1): ('a',1)}, exclusive={('a',0)})
    {('a', 0): "('a', 0)", ('a', 1): ('a', 1)}
    Nr   )SubgraphCallablec              3  8   K   | ]}t          |          V  d S r   	stringifyrB   r   r  s     r&   r   zstringify.<locals>.<genexpr>v  s-      ??!i9--??????r(   rK   c              3  8   K   | ]}t          |          V  d S r   r  r  s     r&   r   zstringify.<locals>.<genexpr>x  s-      "L"Lq9Q	#:#:"L"L"L"L"L"Lr(   c                0    g | ]}t          |          S r"   r  rB   r  r  s     r&   rD   zstringify.<locals>.<listcomp>{  s#    555A	!Y''555r(   c                8    i | ]\  }}|t          |          S r"   r  )rB   r  r  r  s      r&   r'  zstringify.<locals>.<dictcomp>}  s)    CCCtq!9Q	**CCCr(   c              3  8   K   | ]}t          |          V  d S r   r  r  s     r&   r   zstringify.<locals>.<genexpr>  s-      ::Yq),,::::::r(   )r   re  r   r   dask.optimizationr  r  r  outkeyinkeysr   callablerF   r  rC   r  )rW  r  rt  r  obj0s    `   r&   r  r  A  s   D s))C
czzSE\\
		3xx
e|||6666661v::)))D  dh	22Kdk955I	  ????s122w?????@ @ d^^ 	M7U"L"L"L"LCG"L"L"LLLLL
d{{55555555
d{{CCCCsyy{{CCCC)S>>!    
e||::::c::::::Js   <E 
EEc                   t          |           }|t          u ry| rw| d         }t          |          t          u st          |          t          u rt	          |           S t          |          r%|ft          d | dd         D                       z   S |t          u rd | D             S |t          u rd |                                 D             S |t          u rt          d | D                       S | S )zConvert all collection keys in ``obj`` to strings.

    This is a specialized version of ``stringify()`` that only converts keys
    of the form: ``("a string", ...)``
    r   c              3  4   K   | ]}t          |          V  d S r   stringify_collection_keysr  s     r&   r   z,stringify_collection_keys.<locals>.<genexpr>  s+      "Q"QA#<Q#?#?"Q"Q"Q"Q"Q"Qr(   rK   Nc                ,    g | ]}t          |          S r"   r  rB   r  s     r&   rD   z-stringify_collection_keys.<locals>.<listcomp>  s!    :::)!,,:::r(   c                4    i | ]\  }}|t          |          S r"   r  r~  s      r&   r'  z-stringify_collection_keys.<locals>.<dictcomp>  s'    HHHDAq,Q//HHHr(   c              3  4   K   | ]}t          |          V  d S r   r  r  s     r&   r   z,stringify_collection_keys.<locals>.<genexpr>  s+      ??a.q11??????r(   )	r   r   re  r   r  r  rF   r  rC   )rW  rt  r  s      r&   r  r    s     s))C
e|||1v::T

e 3 3S>>!D>> 	R7U"Q"QQRR"Q"Q"QQQQQ
d{{::c::::
d{{HHCIIKKHHHH
e||??3??????Jr(   c                      e Zd ZdZd ZdS )cached_propertyz/Read only version of functools.cached_property.c                     t          d          )z8Raise an error when attempting to set a cached property.zCan't set attribute)rz   )r   instancer  s      r&   __set__zcached_property.__set__  s    2333r(   N)r:   r   r   r   r  r"   r(   r&   r  r    s)        994 4 4 4 4r(   r  c                  *    e Zd ZdZd Zd Zd Zd ZdS )_HashIdWrapperz>Hash and compare a wrapped object by identity instead of valuec                    || _         d S r   )rb  )r   rb  s     r&   r   z_HashIdWrapper.__init__  s    r(   c                V    t          |t                    st          S | j        |j        u S r   rE   r  NotImplementedrb  r  s     r&   r  z_HashIdWrapper.__eq__  s)    %00 	"!!|u},,r(   c                V    t          |t                    st          S | j        |j        uS r   r  r  s     r&   __ne__z_HashIdWrapper.__ne__  s)    %00 	"!!|5=00r(   c                *    t          | j                  S r   )r  rb  r  s    r&   __hash__z_HashIdWrapper.__hash__  s    $,r(   N)r:   r   r   r   r   r  r  r  r"   r(   r&   r  r    sV        HH  - - -
1 1 1
         r(   r  c                    t          | t                    r| j        } |r(t          t	          j        t          | d                    S t          t	          j        t          |                     S )Nr   )rE   r  rb  r   rh  
accumulater   )rM   initial_zeros     r&   _cumsumr    s[    #~&& k 1U%c322333U%c3//000r(   c                    t          | t                    rt          t          |           |          }nt          t          |           |          }|S )a  Compute :meth:`toolz.accumulate` with caching.

    Caching is by the identify of `seq` rather than the value. It is thus
    important that `seq` is a tuple of immutable objects, and this function
    is intended for use where `seq` is a value that will persist (generally
    block sizes).

    Parameters
    ----------
    seq : tuple
        Values to cumulatively sum.
    initial_zero : bool, optional
        If true, the return value is prefixed with a zero.

    Returns
    -------
    tuple
    )rE   r   r  r  )rM   r  r  s      r&   cached_cumsumr	    sM    & #u 3 ,,l;; s\22Mr(   c                    ddl m} m} ddlm} ddlm} ddlm}m	} 	 ddl
m} n# t          $ r d}Y nw xY wddlm} g d}d	                    d
 |dd         D                        |            j        ||d}	|D ]!}
	  ||
          |	|
<   # | $ r d|	|
<   Y w xY w|                     ||	d                     dS )z,Provide version information for bug reports.r   )PackageNotFoundErrorr)   )dumps)uname)stdoutversion_info)__version__N)r   pandascloudpicklefsspecbokehfastparquetpyarrowzarrr^   c                ,    g | ]}t          |          S r"   r  r  s     r&   rD   z!show_versions.<locals>.<listcomp>  s    ===qCFF===r(      )PythonPlatformr  distributedr4   )rA  )importlib.metadatar  r)   jsonr  platformr  sysr  r  r  r  rV   r  r  system
writelines)r  r)   r  r  r  r  distributed_versiondask_versionr  r  modnames              r&   show_versionsr&    s    A@@@@@@@((((((((#BBBBBBB # # #"# 100000	 	 	D ((==L!,<===>>EGGN*% %F  # #	#%gg..F7OO# 	# 	# 	#"F7OOO	# eeF1---...
Fs   % 44?B
BBc                4    | dk    r|  d| S |  d|p|dz    S )z4Pluralize a count-noun string pattern when necessaryrK   r2   r   r"   )countnounplural_forms      r&   maybe_pluralizer+    s<    zz  $   55+3555r(   rW  c                    t          | t                    oOt          | d          o?t          | d          o/t          | d          ot          | d          ot          | d          S )zReturns True if obj is an instance of a namedtuple.

    Note: This function checks for the existence of the methods and
    attributes that make up the namedtuple API, so it will return True
    IFF obj's type implements that API.
    _make_asdict_replace_fields_field_defaults)rE   r   r   )rW  s    r&   is_namedtuple_instancer2    sw     	3 	,C!!	,C##	, C$$	, C##		,
 C*++r(   c                    t          j        dd           x} r| S 	 ddlm}  |             t          j                             d          s#	 ddlm}  |             dS # t          $ r Y nw xY wdS # t          t          f$ r Y dS w xY w)	Nzdataframe.shuffle.methodr   )default_clientzoptimization.fuse.active)check_minimal_arrow_versionp2ptasksdisk)
r   r  r  r4  r  distributed.shuffler5  rW   rV   rR  )r   r4  r5  s      r&   get_default_shuffle_algorithmr:  (  s    J14888q ......{9:: 	KKKKKK++---u   w$   vvs/   /A/ A 
A*'A/ )A**A/ /BBc                    t          | d          r| j        } t          t          |                               d          d                   S )N_metar^   r   )r   r<  r   rx  r   )likes    r&   get_meta_libraryr>  =  sB    tW z$11#66q9:::r(   r   )
r)   r.   r*   r.   r+   r.   r,   r.   r-   r/   )r\   N)rN   r   )rN   r   r   rF   )r   r   )T)r   r   )r   r  )r\   r   N)Nr\   r   N)NNr   Nr  r6  )rt  r   ru  r   r   re  )r   r   )NN)r   r
  r	  r   r   r  )r   r  r	  r   r   r  )r   re  r   r^  )r   re  r   r   )rN   r   r   re  )rN   r   r   re  )rN   r   r   re  r  )r   r  r  r  r   r  )r   r  r  r  r   r   )r  r  )rW  r   r   r   )
__future__r   r  r;   r   rd   r6  rk   r   rb   r  r6   collections.abcr   r   r   r   r   
contextlibr	   r
   r   r   r   r  r   r   	importlibr   numbersr   r   operatorr   	threadingr   typingr   r   r   r   r   weakrefr   tlzrh  r  r   	dask.corer   r   r   r   getdefaultencodingsystem_encodingr'   FutureWarningr>   rA   rP   rL   r[   rp   ru   r|   r~   r   r   r   r   r   r   r   r   r   r   r  r    r   	bytearrayr   r  chrr7  complexr  r`   r   evalr   r4  	frozensethashhexr  r   r  r   rF   r  minr  octordr(  reprreversedroundr)  slicer*  staticmethodre  sumr   r   varsrG   
memoryviewr   compiledelattrdivmodfilterr   r   rE   
issubclassr   powr,  r   r   r   r   r   r  r  r   r0  rE  rI  r[  rd  ro  rx  r~  r  r  r  r  r  r  r  r  r  rp  r  r  Mr  r  r  r  r  r;  rC  rO  rW  rZ  r]  rd  ro  rk  rC   r  r  r  r  r  tds2r  r  r  r  r  r  r  r  r  r  r  r	  r&  r+  r2  r:  r>  r"   r(   r&   <module>rg     sN   " " " " " " "       				 				  



    F F F F F F F F F F F F F F < < < < < < < < < < ( ( ( ( ( ( ( (             # # # # # # $ $ $ $ $ $ $ $             < < < < < < < < < < < < < < ' ' ' ' ' '                 GCLLGCLLGCLL )#(**gO" " " "N  $"+< < < < < <~  " 	" 	" 	"  &- - - )( )( )( )(X ' ' ' 'B d                  (   (  (  (  (F      6    0	P 	P 	P 	P/// / 
	/
 	/ / 
/ / / / / 	/ / / 	/  
!/" #/$ %/& 	'/( )/* +/, -/. 	//0 1/2 	3/4 5/6 7/8 	9/: ;/< 	=/> ?/@ 
A/B 	C/D E/F 
G/H I/J 
K/L M/N O/P Q/R S/T 
U/V 	W/X 	Y/Z [/\ ]/ b 

 	, 	, 	,,; ,; ,; ,;^   H< H< H< H< H< H< H< H<V     H H H  (& & & &R    HL9 9 9 9z OS6 6 6 6r   @    <' ' ' 'T   *    F F F  4 4 4*      *, + + + +" " " " " " " "JG G G G G G G G$# # # # # # # #$ KMM@ @ @ @ @ @ @ @F    38      0 +0      %" %" %" %" %" %" %" %"P& & &( ( ( (V          " " " "
U U U U:6 6 6 6t 



	
	 
 ;:z'7'7'9'9:::
 
  PPz'7'7'9'9PPP Q Q Q 
  NN)9)9););NNN O O O%! %! %! %!PC C C CL   @ 



					 	 	 	 11DJJLL111 2 2 2   t      II1F1F1H1HIII J J J 
    
 
@I    
5 5 5 5p  $ $ $  8 bj"" V5 5 5pD D D D DN  .4 4 4 4 4i/ 4 4 4               ( 1 1 1   :* * * *Z6 6 6 6   "   *; ; ; ; ;r(   