
    .Phv              
       4   d Z ddlZddlZddlZddlmZ 	 ddlmZ n# e$ r  G d d          ZY nw xY w	 ddl	m
Z
  e
d	
          Z e
d
          Zn# e$ r  e            Z e            ZY nw xY w ed          \  ZZZZdZ G d de          Z G d de          Z G d de          Zde eeee ed          g          fdZeZ G d d          Z  G d d          Z!d#dZ"d#dZ# G d d          Z$ G d d           Z% G d! d"          Z&dS )$a  ``cacheutils`` contains consistent implementations of fundamental
cache types. Currently there are two to choose from:

  * :class:`LRI` - Least-recently inserted
  * :class:`LRU` - Least-recently used

Both caches are :class:`dict` subtypes, designed to be as
interchangeable as possible, to facilitate experimentation. A key
practice with performance enhancement with caching is ensuring that
the caching strategy is working. If the cache is constantly missing,
it is just adding more overhead and code complexity. The standard
statistics are:

  * ``hit_count`` - the number of times the queried key has been in
    the cache
  * ``miss_count`` - the number of times a key has been absent and/or
    fetched by the cache
  * ``soft_miss_count`` - the number of times a key has been absent,
    but a default has been provided by the caller, as with
    :meth:`dict.get` and :meth:`dict.setdefault`. Soft misses are a
    subset of misses, so this number is always less than or equal to
    ``miss_count``.

Additionally, ``cacheutils`` provides :class:`ThresholdCounter`, a
cache-like bounded counter useful for online statistics collection.

Learn more about `caching algorithms on Wikipedia
<https://en.wikipedia.org/wiki/Cache_algorithms#Examples>`_.

    N)
attrgetter)RLockc                       e Zd ZdZd Zd ZdS )r   z/Dummy reentrant lock for builds without threadsc                     d S N selfs    R/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/boltons/cacheutils.py	__enter__zRLock.__enter__L       D    c                     d S r   r   )r
   exctypeexcinstexctbs       r   __exit__zRLock.__exit__O   r   r   N)__name__
__module____qualname____doc__r   r   r   r   r   r   r   J   s8        99	 	 		 	 	 	 	r   r      )make_sentinel_MISSING)var_name_KWARG_MARK      c                        e Zd ZdZeddfdZd Zd Zd Zd Z	d Z
d	 Zd
 Z fdZd ZddZ fdZef fd	Z fdZ fdZd ZddZd Z fdZd Z fdZ xZS )LRIa(  The ``LRI`` implements the basic *Least Recently Inserted* strategy to
    caching. One could also think of this as a ``SizeLimitedDefaultDict``.

    *on_miss* is a callable that accepts the missing key (as opposed
    to :class:`collections.defaultdict`'s "default_factory", which
    accepts no arguments.) Also note that, like the :class:`LRI`,
    the ``LRI`` is instrumented with statistics tracking.

    >>> cap_cache = LRI(max_size=2)
    >>> cap_cache['a'], cap_cache['b'] = 'A', 'B'
    >>> from pprint import pprint as pp
    >>> pp(dict(cap_cache))
    {'a': 'A', 'b': 'B'}
    >>> [cap_cache['b'] for i in range(3)][0]
    'B'
    >>> cap_cache['c'] = 'C'
    >>> print(cap_cache.get('a'))
    None
    >>> cap_cache.hit_count, cap_cache.miss_count, cap_cache.soft_miss_count
    (3, 1, 1)
    Nc                 B   |dk    rt          d|z            dx| _        x| _        | _        || _        t                      | _        |                                  |!t          |          st          d|z            || _
        |r|                     |           d S d S )Nr   zexpected max_size > 0, not %rz3expected on_miss to be a callable (or None), not %r)
ValueError	hit_count
miss_countsoft_miss_countmax_sizer   _lock_init_llcallable	TypeErroron_missupdate)r
   r&   valuesr+   s       r   __init__zLRI.__init__t   s    q==<xGHHHBCCC4+? WW
x'8'8 13:; < < < 	 KK	  	 r   c                 P    g }||t           t           g|d d <   i | _        || _        d S r   )r   _link_lookup_anchor)r
   anchors     r   r(   zLRI._init_ll   s2    VXx8qqq	 r   c                     t          d           |                                 D ]\  }}t          ||           t          d           d S )Nz***)print_get_flattened_ll)r
   keyvals      r   	_print_llzLRI._print_ll   sK    e0022 	 	JS##sOOOOer   c                     g }| j         }	 |                    |t                   |t                   f           |t                   }|| j         u rnE|S r   )r1   appendKEYVALUENEXT)r
   flattened_listlinks      r   r5   zLRI._get_flattened_ll   sZ    |	!!49d5k":;;;:Dt|##		
 r   c                    | j         |         }|t                   |t                   t          <   |t                   |t                   t          <   | j        }|t                   }|x|t          <   |t          <   ||t          <   ||t          <   |S r   )r0   r=   PREVr1   )r
   r6   newestr2   second_newests        r   !_get_link_and_move_to_front_of_llz%LRI._get_link_and_move_to_front_of_ll   ss     "3' $D\tT#D\tT t-33dfTl$ttr   c                 v    | j         }|t                   }||||g}|x|t          <   |t          <   || j        |<   d S r   )r1   rA   r=   r0   )r
   r6   valuer2   rC   rB   s         r   _set_key_and_add_to_front_of_llz#LRI._set_key_and_add_to_front_of_ll   sH     te4-33dfTl!'#r   c                     | j         }||t          <   ||t          <   |t                   x| _         }|t                   }t          x|t          <   |t          <   | j        |= || j        |<   |S r   )r1   r;   r<   r=   r   r0   )r
   r6   rF   	oldanchorr2   evicteds         r   _set_key_and_evict_last_in_llz!LRI._set_key_and_evict_last_in_ll   sf     L		# 	% )$/v+&..sfUmg&!*#r   c                     | j                             |          }|t                   |t                   t          <   |t                   |t                   t          <   d S r   )r0   popr=   rA   )r
   r6   r?   s      r   _remove_from_llzLRI._remove_from_ll   sD      $$S)):T
4:T
4r   c                    | j         5  	 |                     |          }||t          <   nv# t          $ ri t	          |           | j        k     r|                     ||           n7|                     ||          }t                      	                    |           Y nw xY wt                      
                    ||           d d d            n# 1 swxY w Y   d S r   )r'   rD   r<   KeyErrorlenr&   rG   rK   super__delitem____setitem__)r
   r6   rF   r?   rJ   	__class__s        r   rT   zLRI.__setitem__   s    Z 	, 	,	$==cBB $U  1 1 1t99t},,88eDDDD"@@eLLGGG''0001 GGU+++	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	s2   C+CA0BCB%CCCc                 <   | j         5  	 | j        |         }nP# t          $ rC | xj        dz  c_        | j        s |                     |          x}| |<   |cY cd d d            S w xY w| xj        dz  c_        |t                   cd d d            S # 1 swxY w Y   d S Nr   )r'   r0   rP   r$   r+   r#   r<   r
   r6   r?   rets       r   __getitem__zLRI.__getitem__   s   Z 	 	(-   1$| "&,,s"3"33d3i

	 	 	 	 	 	 	 	 NNaNN;	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s1   BB>A%B$A%%BBBc                 X    	 | |         S # t           $ r | xj        dz  c_        |cY S w xY wrW   )rP   r%   r
   r6   defaults      r   getzLRI.get   sI    	9 	 	 	  A%  NNN	s   
 ))c                     | j         5  t                                          |           |                     |           d d d            d S # 1 swxY w Y   d S r   )r'   rR   rS   rN   )r
   r6   rU   s     r   rS   zLRI.__delitem__   s    Z 	& 	&GG$$$  %%%	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	&s   7AAAc                     | j         5  	 t                                          |          }|                     |           n# t          $ r |t
          u r |}Y nw xY w|cd d d            S # 1 swxY w Y   d S r   )r'   rR   rM   rN   rP   r   )r
   r6   r]   rY   rU   s       r   rM   zLRI.pop  s    Z 		 		*ggkk#&& $$S))))    h&& 		 		 		 		 		 		 		 		 		 		 		 		 		 		 		 		 		 		s3   A,!AA,AA,AA,,A03A0c                     | j         5  t                                                      }|                     |d                    |cd d d            S # 1 swxY w Y   d S Nr   )r'   rR   popitemrN   )r
   itemrU   s     r   rc   zLRI.popitem  s    Z 	 	77??$$D  a)))	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   =AAAc                     | j         5  t                                                       |                                  d d d            d S # 1 swxY w Y   d S r   )r'   rR   clearr(   )r
   rU   s    r   rf   z	LRI.clear  s    Z 	 	GGMMOOOMMOOO	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   5AAAc                 :    |                      | j        |           S )N)r&   r-   )rU   r&   r	   s    r   copyzLRI.copy  s    ~~t}T~BBBr   c                     | j         5  	 | |         cd d d            S # t          $ r& | xj        dz  c_        || |<   |cY cd d d            S w xY w# 1 swxY w Y   d S rW   )r'   rP   r%   r\   s      r   
setdefaultzLRI.setdefault  s    Z 	 	Cy	 	 	 	 	 	 	 	    $$)$$#S		 	 	 	 	 	 	 		 	 	 	 	 	 	 	 	 	s+   A!AAAAAAc                 `   | j         5  || u r	 d d d            d S | j        }t          t          |dd                     r*|                                D ]} ||||                    n|D ]\  }} |||           |D ]} ||||                    	 d d d            d S # 1 swxY w Y   d S )Nkeys)r'   rT   r)   getattrrl   )r
   EFsetitemkvs         r   r,   z
LRI.update(  sN   Z 	 	Dyy	 	 	 	 	 	 	 	 &G640011 " % %AGAqt$$$$%  " "DAqGAqMMMM ! !1Q4    	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   B#A;B##B'*B'c                 V   | j         5  | |u r	 d d d            dS t          |          t          |           k    r	 d d d            dS t          |t                    s|| k    cd d d            S t	                                          |          cd d d            S # 1 swxY w Y   d S )NTF)r'   rQ   
isinstancer    rR   __eq__)r
   otherrU   s     r   ru   z
LRI.__eq__8  s?   Z 	) 	)u}}	) 	) 	) 	) 	) 	) 	) 	) 5zzSYY&&		) 	) 	) 	) 	) 	) 	) 	)
 eS)) %}	) 	) 	) 	) 	) 	) 	) 	) 77>>%((	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	)s"   B!B
B1 BB"%B"c                     | |k     S r   r   )r
   rv   s     r   __ne__z
LRI.__ne__B  s    EM""r   c                     | j         j        }t                                                      }|d| j        d| j        d|dS )Nz
(max_size=z
, on_miss=z	, values=))rU   r   rR   __repr__r&   r+   )r
   cnval_maprU   s      r   r{   zLRI.__repr__E  sI    ^$''""$$22t}}}dlllGGG= 	>r   r   )r   r   r   r   DEFAULT_MAX_SIZEr.   r(   r8   r5   rD   rG   rK   rN   rT   rZ   r^   rS   r   rM   rc   rf   rh   rj   r,   ru   rx   r{   __classcell__)rU   s   @r   r    r    ^   s        * !1       4        $( ( (  $& & &         & & & & &
  (              
C C C      ) ) ) ) )# # #> > > > > > > > >r   r    c                       e Zd ZdZd ZdS )LRUa%  The ``LRU`` is :class:`dict` subtype implementation of the
    *Least-Recently Used* caching strategy.

    Args:
        max_size (int): Max number of items to cache. Defaults to ``128``.
        values (iterable): Initial values for the cache. Defaults to ``None``.
        on_miss (callable): a callable which accepts a single argument, the
            key not present in the cache, and returns the value to be cached.

    >>> cap_cache = LRU(max_size=2)
    >>> cap_cache['a'], cap_cache['b'] = 'A', 'B'
    >>> from pprint import pprint as pp
    >>> pp(dict(cap_cache))
    {'a': 'A', 'b': 'B'}
    >>> [cap_cache['b'] for i in range(3)][0]
    'B'
    >>> cap_cache['c'] = 'C'
    >>> print(cap_cache.get('a'))
    None

    This cache is also instrumented with statistics
    collection. ``hit_count``, ``miss_count``, and ``soft_miss_count``
    are all integer members that can be used to introspect the
    performance of the cache. ("Soft" misses are misses that did not
    raise :exc:`KeyError`, e.g., ``LRU.get()`` or ``on_miss`` was used to
    cache a default.

    >>> cap_cache.hit_count, cap_cache.miss_count, cap_cache.soft_miss_count
    (3, 1, 1)

    Other than the size-limiting caching behavior and statistics,
    ``LRU`` acts like its parent class, the built-in Python :class:`dict`.
    c                 L   | j         5  	 |                     |          }nP# t          $ rC | xj        dz  c_        | j        s |                     |          x}| |<   |cY cd d d            S w xY w| xj        dz  c_        |t                   cd d d            S # 1 swxY w Y   d S rW   )r'   rD   rP   r$   r+   r#   r<   rX   s       r   rZ   zLRU.__getitem__n  s"   Z 	 	==cBB   1$| "&,,s"3"33d3i

	 	 	 	 	 	 	 	 NNaNN;	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s1   B B>A-B,A--BB BN)r   r   r   r   rZ   r   r   r   r   r   L  s.           B    r   r   c                   (    e Zd ZdZdZd Zd Zd ZdS )
_HashedKeyzoThe _HashedKey guarantees that hash() will be called no more than once
    per cached function invocation.
    
hash_valuec                 V    || d d <   t          t          |                    | _        d S r   )hashtupler   r
   r6   s     r   r.   z_HashedKey.__init__  s(    QQQuSzz**r   c                     | j         S r   )r   r	   s    r   __hash__z_HashedKey.__hash__  s
    r   c                 V    | j         j         dt                              |            dS )N(rz   )rU   r   listr{   r	   s    r   r{   z_HashedKey.__repr__  s*    .)BBDMM$,?,?BBBBr   N)r   r   r   r   	__slots__r.   r   r{   r   r   r   r   r     sW          I+ + +  C C C C Cr   r   Fc                    t          |           }|rKt          |                                          }|                    |           |                    |           |rA|                    d | D                        |r|                    d |D                        n2t          |          dk    rt          |d                   |v r|d         S t          |          S )a  Make a generic key from a function's positional and keyword
    arguments, suitable for use in caches. Arguments within *args* and
    *kwargs* must be `hashable`_. If *typed* is ``True``, ``3`` and
    ``3.0`` will be treated as separate keys.

    The key is constructed in a way that is flat as possible rather than
    as a nested structure that would take more memory.

    If there is only a single argument and its data type is known to cache
    its hash value, then that argument is returned without a wrapper.  This
    saves space and improves lookup speed.

    >>> tuple(make_cache_key(('a', 'b'), {'c': ('d')}))
    ('a', 'b', _KWARG_MARK, ('c', 'd'))

    .. _hashable: https://docs.python.org/2/glossary.html#term-hashable
    c                 ,    g | ]}t          |          S r   type).0rr   s     r   
<listcomp>z"make_cache_key.<locals>.<listcomp>  s    ***DGG***r   c                 2    g | ]\  }}t          |          S r   r   )r   rq   rr   s      r   r   z"make_cache_key.<locals>.<listcomp>  s"    999DAqQ999r   r   r   )r   sorteditemsr:   extendrQ   r   r   )argskwargstyped
kwarg_mark	fasttypesr6   sorted_itemss          r   make_cache_keyr     s    . t**C !fllnn--

:

<    

**T***+++ 	;JJ99L999:::	SQ4A<<9441vc??r   c                   &    e Zd ZdZddZd Zd ZdS )	CachedFunctionzyThis type is used by :func:`cached`, below. Instances of this
    class are used to wrap functions in caching logic.
    TFNc                 0   || _         t                    r| _        nZt          t          dd                     rt          t          dd                     st	          dz            fd}|| _        || _        || _        |pt          | _        d S )NrZ   rT   zYexpected cache to be a dict-like object, or callable returning a dict-like object, not %rc                       S r   r   )caches   r   
_get_cachez+CachedFunction.__init__.<locals>._get_cache      r   )	funcr)   	get_cacherm   r*   scopedr   r   key_funcr
   r   r   r   r   r6   r   s     `    r   r.   zCachedFunction.__init__  s    	E?? 
	("DNN75->>?? 	(wumTBBCC	( P#$ % % %    'DN
-~r   c                     |                                  }|                     ||| j                  }	 ||         }n"# t          $ r  | j        |i |x}||<   Y nw xY w|S )Nr   )r   r   r   rP   r   )r
   r   r   r   r6   rY   s         r   __call__zCachedFunction.__call__  s}      mmD&
m;;	:*CC 	: 	: 	:(ty$9&999C%***	:
s   < AAc                     | j         j        }| j        s| j        s|d| j        d| j        d| j        dS | d| j        dS )Nz(func=z	, scoped=z, typed=rz   )rU   r   r   r   r   r
   r|   s     r   r{   zCachedFunction.__repr__  sd    ^$: 	@T[ 	@rr4999dkkk4:::? @**DI****r   TFN)r   r   r   r   r.   r   r{   r   r   r   r   r     sP         . . . ."  + + + + +r   r   c                   .    e Zd ZdZd	dZd
dZd Zd ZdS )CachedMethodzxSimilar to :class:`CachedFunction`, this type is used by
    :func:`cachedmethod` to wrap methods in caching logic.
    TFNc                    || _         t          |dd          | _        t          t                    rt                    | _        nqt                    r| _        nZt          t          dd                     rt          t          dd                     st          dz            fd}|| _        || _	        || _
        |pt          | _        d | _        d S )N__isabstractmethod__FrZ   rT   zjexpected cache to be an attribute name, dict-like object, or callable returning a dict-like object, not %rc                     S r   r   )objr   s    r   r   z)CachedMethod.__init__.<locals>._get_cache  r   r   )r   rm   r   rt   strr   r   r)   r*   r   r   r   r   bound_tor   s     `    r   r.   zCachedMethod.__init__  s    	$+D2H%$P$P!eS!! 	('..DNNe__ 
	("DNN75->>?? 	(wumTBBCC	( :<AB C C C    'DN
-~r   c                 |    || S | j         } || j        | j        | j        | j        | j                  }||_        |S )N)r   r   r6   )rU   r   r   r   r   r   r   )r
   r   objtypeclsrY   s        r   __get__zCachedMethod.__get__  sJ    ;Knc$)T^4:$-9 9 9
r   c                 F   | j         |d         n| j         }|                     |          }| j        r| j         | j        f|z   n|}|                     ||| j                  }	 ||         }n4# t          $ r' | j         | j         f|z   } | j        |i |x}||<   Y nw xY w|S )Nr   r   )r   r   r   r   r   r   rP   )r
   r   r   r   r   key_argsr6   rY   s           r   r   zCachedMethod.__call__  s    .d1ggDMs##8<MDM49-44mmHfDJm??	:*CC 	: 	: 	:}('$.(ty$9&999C%***	: 
s   $A- -.BBc                 |    | j         j        }|| j        | j        | j        f}| j        || j        fz  }d|z  S d|z  S )Nz+<%s func=%r scoped=%r typed=%r bound_to=%r>z %s(func=%r, scoped=%r, typed=%r))rU   r   r   r   r   r   )r
   r|   r   s      r   r{   zCachedMethod.__repr__  sM    ^$DIt{DJ7=$T]$$DADHI2T9:r   r   r   )r   r   r   r   r.   r   r   r{   r   r   r   r   r     sd            *     ; ; ; ; ;r   r   Tc                       fd}|S )ad  Cache any function with the cache object of your choosing. Note
    that the function wrapped should take only `hashable`_ arguments.

    Args:
        cache (Mapping): Any :class:`dict`-like object suitable for
            use as a cache. Instances of the :class:`LRU` and
            :class:`LRI` are good choices, but a plain :class:`dict`
            can work in some cases, as well. This argument can also be
            a callable which accepts no arguments and returns a mapping.
        scoped (bool): Whether the function itself is part of the
            cache key.  ``True`` by default, different functions will
            not read one another's cache entries, but can evict one
            another's results. ``False`` can be useful for certain
            shared cache use cases. More advanced behavior can be
            produced through the *key* argument.
        typed (bool): Whether to factor argument types into the cache
            check. Default ``False``, setting to ``True`` causes the
            cache keys for ``3`` and ``3.0`` to be considered unequal.

    >>> my_cache = LRU()
    >>> @cached(my_cache)
    ... def cached_lower(x):
    ...     return x.lower()
    ...
    >>> cached_lower("CaChInG's FuN AgAiN!")
    "caching's fun again!"
    >>> len(my_cache)
    1

    .. _hashable: https://docs.python.org/2/glossary.html#term-hashable

    c                 ,    t          |           S N)r   r   r6   )r   r   r   r6   r   r   s    r   cached_func_decoratorz%cached.<locals>.cached_func_decorator8  s    dE&3OOOOr   r   )r   r   r   r6   r   s   ```` r   cachedr     s=    BP P P P P P P P  r   c                       fd}|S )a  Similar to :func:`cached`, ``cachedmethod`` is used to cache
    methods based on their arguments, using any :class:`dict`-like
    *cache* object.

    Args:
        cache (str/Mapping/callable): Can be the name of an attribute
            on the instance, any Mapping/:class:`dict`-like object, or
            a callable which returns a Mapping.
        scoped (bool): Whether the method itself and the object it is
            bound to are part of the cache keys. ``True`` by default,
            different methods will not read one another's cache
            results. ``False`` can be useful for certain shared cache
            use cases. More advanced behavior can be produced through
            the *key* arguments.
        typed (bool): Whether to factor argument types into the cache
            check. Default ``False``, setting to ``True`` causes the
            cache keys for ``3`` and ``3.0`` to be considered unequal.
        key (callable): A callable with a signature that matches
            :func:`make_cache_key` that returns a tuple of hashable
            values to be used as the key in the cache.

    >>> class Lowerer(object):
    ...     def __init__(self):
    ...         self.cache = LRI()
    ...
    ...     @cachedmethod('cache')
    ...     def lower(self, text):
    ...         return text.lower()
    ...
    >>> lowerer = Lowerer()
    >>> lowerer.lower('WOW WHO COULD GUESS CACHING COULD BE SO NEAT')
    'wow who could guess caching could be so neat'
    >>> len(lowerer.cache)
    1

    c                 ,    t          |           S r   )r   r   s    r   cached_method_decoratorz-cachedmethod.<locals>.cached_method_decoratorb  s    D%eMMMMr   r   )r   r   r   r6   r   s   ```` r   cachedmethodr   =  s=    JN N N N N N N N""r   c                   &    e Zd ZdZd ZddZd ZdS )cachedpropertya  The ``cachedproperty`` is used similar to :class:`property`, except
    that the wrapped method is only called once. This is commonly used
    to implement lazy attributes.

    After the property has been accessed, the value is stored on the
    instance itself, using the same name as the cachedproperty. This
    allows the cache to be cleared with :func:`delattr`, or through
    manipulating the object's ``__dict__``.
    c                 j    t          |d          | _        t          |dd          | _        || _        d S )Nr   r   F)rm   r   r   r   )r
   r   s     r   r.   zcachedproperty.__init__q  s3    tY//$+D2H%$P$P!			r   Nc                 `    || S |                      |          x}|j        | j         j        <   |S r   )r   __dict__r   )r
   r   r   rF   s       r   r   zcachedproperty.__get__v  s1    ;K3799S>>ATY/0r   c                 6    | j         j        }d| d| j         dS )N<z func=>)rU   r   r   r   s     r   r{   zcachedproperty.__repr__|  s'    ^$)2))TY))))r   r   )r   r   r   r   r.   r   r{   r   r   r   r   r   g  sP           
   * * * * *r   r   c                       e Zd ZdZddZed             Zd Zd ZddZ	d	 Z
d
 Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd ZddZd ZdS )ThresholdCountera  A **bounded** dict-like Mapping from keys to counts. The
    ThresholdCounter automatically compacts after every (1 /
    *threshold*) additions, maintaining exact counts for any keys
    whose count represents at least a *threshold* ratio of the total
    data. In other words, if a particular key is not present in the
    ThresholdCounter, its count represents less than *threshold* of
    the total data.

    >>> tc = ThresholdCounter(threshold=0.1)
    >>> tc.add(1)
    >>> tc.items()
    [(1, 1)]
    >>> tc.update([2] * 10)
    >>> tc.get(1)
    0
    >>> tc.add(5)
    >>> 5 in tc
    True
    >>> len(list(tc.elements()))
    11

    As you can see above, the API is kept similar to
    :class:`collections.Counter`. The most notable feature omissions
    being that counted items cannot be set directly, uncounted, or
    removed, as this would disrupt the math.

    Use the ThresholdCounter when you need best-effort long-lived
    counts for dynamically-keyed data. Without a bounded datastructure
    such as this one, the dynamic keys often represent a memory leak
    and can impact application reliability. The ThresholdCounter's
    item replacement strategy is fully deterministic and can be
    thought of as *Amortized Least Relevant*. The absolute upper bound
    of keys it will store is *(2/threshold)*, but realistically
    *(1/threshold)* is expected for uniformly random datastreams, and
    one or two orders of magnitude better for real-world data.

    This algorithm is an implementation of the Lossy Counting
    algorithm described in "Approximate Frequency Counts over Data
    Streams" by Manku & Motwani. Hat tip to Kurt Rose for discovery
    and initial implementation.

    MbP?c                     d|cxk     rdk     sn t          d|z            d| _        i | _        || _        t	          d|z            | _        d| _        d S )Nr   r   z+expected threshold between 0 and 1, not: %r)r"   total
_count_map
_thresholdint_thresh_count_cur_bucket)r
   	thresholds     r   r.   zThresholdCounter.__init__  sw    9    q    J() * * * 
# Y//r   c                     | j         S r   )r   r	   s    r   r   zThresholdCounter.threshold  s
    r   c                 D     xj         dz  c_         	  j        |         dxx         dz  cc<   n$# t          $ r d j        dz
  g j        |<   Y nw xY w j          j        z  dk    r: fd j                                        D              _         xj        dz  c_        dS )zIncrement the count of *key* by 1, automatically adding it if it
        does not exist.

        Cache compaction is triggered every *1/threshold* additions.
        r   r   c                 L    i | ] \  }}t          |          j        k    ||!S r   )sumr   )r   rq   rr   r
   s      r   
<dictcomp>z(ThresholdCounter.add.<locals>.<dictcomp>  s?     B B B1'*1vv0@'@'@  !!'@'@'@r   N)r   r   rP   r   r   r   r   s   ` r   addzThresholdCounter.add  s     	

a

	=OC ###q(#### 	= 	= 	=$%t'7!';#<DOC   	= :**a//B B B B0E0E0G0G B B BDO!s   / AAc                     t          j        t           j        |                                           }t           j                            |          S )zReturn an iterator of all the common elements tracked by the
        counter. Yields each key as many times as it has been seen.
        )	itertoolsstarmaprepeat	iteritemschainfrom_iterable)r
   	repeaterss     r   elementszThresholdCounter.elements  s9     %i&68H8HII	,,Y777r   Nc                     |r|dk    rg S t          |                                 d d          }||t          |          k    r|S |d|         S )zeGet the top *n* keys and counts as tuples. If *n* is omitted,
        returns all the pairs.
        r   c                     | d         S rW   r   )xs    r   <lambda>z.ThresholdCounter.most_common.<locals>.<lambda>  s
    QqT r   T)r6   reverseN)r   r   rQ   )r
   nrY   s      r   most_commonzThresholdCounter.most_common  s^      	AFFIT^^%%>>4HHH9SXXJ2A2wr   c                 b    t          d | j                                        D                       S )zXGet the sum of counts for keys exceeding the configured data
        threshold.
        c                     g | ]\  }}|S r   r   )r   count_s      r   r   z5ThresholdCounter.get_common_count.<locals>.<listcomp>  s    CCCheQECCCr   )r   r   r-   r	   s    r   get_common_countz!ThresholdCounter.get_common_count  s/     CC$/*@*@*B*BCCCDDDr   c                 :    | j         |                                 z
  S )zGet the sum of counts for keys that were culled because the
        associated counts represented less than the configured
        threshold. The long-tail counts.
        )r   r   r	   s    r   get_uncommon_countz#ThresholdCounter.get_uncommon_count  s    
 zD113333r   c                 T    t          |                                           | j        z  S )a6  Get a float representation of the effective count accuracy. The
        higher the number, the less uniform the keys being added, and
        the higher accuracy and efficiency of the ThresholdCounter.

        If a stronger measure of data cardinality is required,
        consider using hyperloglog.
        )floatr   r   r	   s    r   get_commonalityz ThresholdCounter.get_commonality  s%     T**,,--
::r   c                 (    | j         |         d         S rb   r   r   s     r   rZ   zThresholdCounter.__getitem__  s    s#A&&r   c                 *    t          | j                  S r   )rQ   r   r	   s    r   __len__zThresholdCounter.__len__  s    4?###r   c                     || j         v S r   r   r   s     r   __contains__zThresholdCounter.__contains__  s    do%%r   c                 *    t          | j                  S r   )iterr   r	   s    r   iterkeyszThresholdCounter.iterkeys   s    DO$$$r   c                 D    t          |                                           S r   )r   r  r	   s    r   rl   zThresholdCounter.keys  s    DMMOO$$$r   c              #   B   K   | j         }|D ]}||         d         V  d S rb   r   r
   	count_maprq   s      r   
itervalueszThresholdCounter.itervalues  s=      O	 	" 	"AA,q/!!!!	" 	"r   c                 D    t          |                                           S r   )r   r  r	   s    r   r-   zThresholdCounter.values  s    DOO%%&&&r   c              #   F   K   | j         }|D ]}|||         d         fV  d S rb   r   r
  s      r   r   zThresholdCounter.iteritems  sB      O	 	' 	'Ail1o&&&&&	' 	'r   c                 D    t          |                                           S r   )r   r   r	   s    r   r   zThresholdCounter.items  s    DNN$$%%%r   r   c                 8    	 | |         S # t           $ r |cY S w xY w)z%Get count for *key*, defaulting to 0.)rP   r\   s      r   r^   zThresholdCounter.get  s5    	9 	 	 	NNN	s   
 c                 0   |zt          t          |dd                    rB|                                D ],\  }}t          |          D ]}|                     |           -n|D ]}|                     |           |r|                     |           dS dS )zLike dict.update() but add counts instead of replacing them, used
        to add multiple items in one call.

        Source can be an iterable of keys to add, or a mapping of keys
        to integer counts.
        Nr   )r)   rm   r   ranger   r,   )r
   iterabler   r6   r   is         r   r,   zThresholdCounter.update  s     +t<<== ""*"4"4"6"6 & &JC"5\\ & &&& $ " "CHHSMMMM 	 KK	  	 r   )r   r   )r   )r   r   r   r   r.   propertyr   r   r   r   r   r   r   rZ   r  r  r  rl   r  r-   r   r   r^   r,   r   r   r   r   r     sZ       ) )V	 	 	 	   X  $8 8 8	 	 	 	E E E4 4 4; ; ;' ' '$ $ $& & &% % %% % %" " "
' ' '' ' '
& & &            r   r   c                   B    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
S )MinIDMapa  
    Assigns arbitrary weakref-able objects the smallest possible unique
    integer IDs, such that no two objects have the same ID at the same
    time.

    Maps arbitrary hashable objects to IDs.

    Based on https://gist.github.com/kurtbrose/25b48114de216a5e55df
    c                 R    t          j                    | _        i | _        g | _        d S r   )weakrefWeakKeyDictionarymappingref_mapfreer	   s    r   r.   zMinIDMap.__init__:  s$    022			r   c                    	 | j         |         d         S # t          $ r Y nw xY w| j        rt          j        | j                  }nt          | j                   }t          j        || j                  }||f| j         |<   || j	        |<   |S rb   )
r  rP   r  heapqheappoprQ   r  ref_cleanr  )r
   anxtr!  s       r   r^   zMinIDMap.get?  s    	<?1%% 	 	 	D	 9 	$-	**CCdl##Ck!T[))*QS
s    
""c                 z    | j         |         \  }}| j         |= | j        |= t          j        | j        |           d S r   )r  r  r  heappushr  )r
   r#  freedr!  s       r   dropzMinIDMap.dropN  s>    \!_
sLOLty%(((((r   c                     t          | j        |                    t          j        | j        | j        |                    | j        |= d S r   )r4   r  r  r&  r  )r
   r!  s     r   r"  zMinIDMap._cleanT  sB    dl3   ty$,s"3444Lr   c                     || j         v S r   r  )r
   r#  s     r   r  zMinIDMap.__contains__Y  s    DL  r   c                 *    t          | j                  S r   r  r  r	   s    r   __iter__zMinIDMap.__iter__\  s    DL!!!r   c                 4    | j                                         S r   )r  r  r	   s    r   r  zMinIDMap.__len___  s    |##%%%r   c                 ^     t           fdt           j                  D                       S )Nc              3   B   K   | ]}|j         |         d          fV  dS )r   Nr+  )r   rq   r
   s     r   	<genexpr>z%MinIDMap.iteritems.<locals>.<genexpr>c  s3      HHQQ*+HHHHHHr   r-  r	   s   `r   r   zMinIDMap.iteritemsb  s0    HHHHT$,5G5GHHHHHHr   N)r   r   r   r   r.   r^   r(  r"  r  r.  r  r   r   r   r   r  r  0  s           
  ) ) )  
! ! !" " "& & &I I I I Ir   r  r   )'r   r  r  r   operatorr   	threadingr   	Exception	typeutilsr   r   r   ImportErrorobjectr  rA   r=   r;   r<   r~   dictr    r   r   r   	frozensetr   r   r   r   _make_cache_keyr   r   r   r   r   r   r  r   r   r   <module>r<     s  > F            	            ((((((}j111H-777KK   vxxH&((KKK q dC k> k> k> k> k>$ k> k> k>\. . . . .# . . .hC C C C C C C C" (-)&YS)TT$ZZ'HII" " " "J !#+ #+ #+ #+ #+ #+ #+ #+L5; 5; 5; 5; 5; 5; 5; 5;p#! #! #! #!L'# '# '# '#T* * * * * * * *4l  l  l  l  l  l  l  l ^3I 3I 3I 3I 3I 3I 3I 3I 3I 3Is    22A A10A1