
    Viw              
          S r SSKrSSKrSSKrSSKJr   SSKJr   SSK
Jr  \" SS	9r\" S
S	9r \  \" S5      u  rrrrSr " S S\5      r " S S\5      r " S S\5      rS\\ " \!\\ \"" S5      /5      4S jr#\#r$ " S S\	5      r% " S S\	5      r&S!S jr'S!S jr( " S S\	5      r) " S S\	5      r* " S S \	5      r+g! \ a     " S S\	5      r Nf = f! \ a    \	" 5       r\	" 5       r Nf = f! \ a    \r\\\\\44u  rrrr Nf = f)"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                   $    \ rS rSrSrS rS rSrg)r   L   z/Dummy reentrant lock for builds without threadsc                     g N selfs    e/home/james-whalen/.local/share/pipx/venvs/semgrep/lib/python3.13/site-packages/boltons/cacheutils.py	__enter__RLock.__enter__N           c                     g r   r	   )r   exctypeexcinstexctbs       r   __exit__RLock.__exit__Q   r   r   r	   N)__name__
__module____qualname____firstlineno____doc__r   r   __static_attributes__r	   r   r   r   r   L   s    9		r   r   )make_sentinel_MISSING)var_name_KWARG_MARK      c                      ^  \ rS rSrSr\SS4S jrS rS rS r	S r
S	 rS
 rS rU 4S jrS rSS jrU 4S jr\4U 4S jjrU 4S jrU 4S jrS rSS jrS rU 4S jrS rU 4S jrSrU =r$ )LRIg   a  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                     US::  a  [        SU-  5      eS=U l        =U l        U l        Xl        [        5       U l        U R                  5         Ub  [        U5      (       d  [        SU-  5      eX0l
        U(       a  U R                  U5        g g )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+   valuesr0   s       r   __init__LRI.__init__}   s    q=<xGHHBCCC4+? W
x'8'8 13:; < <KK r   c                 B    / nX[         [         /US S & 0 U l        Xl        g r   )r   _link_lookup_anchor)r   anchors     r   r-   LRI._init_ll   s&    Xx8q	 r   c                 x    [        S5        U R                  5        H  u  p[        X5        M     [        S5        g )Nz***)print_get_flattened_ll)r   keyvals      r   	_print_llLRI._print_ll   s/    e002JS#O 3er   c                     / nU R                   n UR                  U[           U[           45        U[           nX R                   L a   U$ M=  r   )r7   appendKEYVALUENEXT)r   flattened_listlinks      r   r<   LRI._get_flattened_ll   sO    ||!!49d5k":;:D||# r   c                     U R                   U   nU[           U[           [        '   U[           U[           [        '   U R                  nU[           nU=U[        '   U[        '   XB[        '   X2[        '   U$ r   )r6   rE   PREVr7   )r   r=   newestr8   second_newests        r   !_get_link_and_move_to_front_of_ll%LRI._get_link_and_move_to_front_of_ll   st     ""3' $D\tT#D\tT t-33dfTl$ttr   c                 v    U R                   nU[           nXCX/nU=U[        '   U[        '   XPR                  U'   g r   )r7   rJ   rE   r6   )r   r=   valuer8   rL   rK   s         r   _set_key_and_add_to_front_of_ll#LRI._set_key_and_add_to_front_of_ll   sA     t4-33dfTl!'#r   c                     U R                   nX[        '   X#[        '   U[           =U l         nU[           n[        =U[        '   U[        '   U R
                  U	 X0R
                  U'   U$ r   )r7   rC   rD   rE   r   r6   )r   r=   rP   	oldanchorr8   evicteds         r   _set_key_and_evict_last_in_ll!LRI._set_key_and_evict_last_in_ll   sh     LL	# % )$/v+&..sfUmg&!*#r   c                     U R                   R                  U5      nU[           U[           [        '   U[           U[           [        '   g r   )r6   poprE   rJ   )r   r=   rG   s      r   _remove_from_llLRI._remove_from_ll   s>       $$S):T
4:T
4r   c                 j  > U R                       U R                  U5      nX#[        '   S S S 5        g ! [         ae    [	        U 5      U R
                  :  a  U R                  X5        O$U R                  X5      n[        [        U ]+  U5        [        [        U ]/  X5         Nwf = f! , (       d  f       g = fr   )r,   rM   rD   KeyErrorlenr+   rQ   rV   superr$   __delitem____setitem__)r   r=   rP   rG   rU   	__class__s        r   ra   LRI.__setitem__   s    ZZ
$==cB $U Z  9t9t}},88D"@@LG#t09c4,S89 Zs,   B$2B$A,B!B$ B!!B$$
B2c                 Z   U R                       U R                  U   nU =R
                  S-  sl        U[           sS S S 5        $ ! [         aJ    U =R                  S-  sl        U R                  (       d  e U R	                  U5      =o0U'   Us sS S S 5        $ f = f! , (       d  f       g = fN   )r,   r6   r]   r)   r0   r(   rD   r   r=   rG   rets       r   __getitem__LRI.__getitem__   s    ZZ((- NNaN; Z  1$||"&,,s"333i
 Z Zs.   BABABBBB
B*c                 Z     X   $ ! [          a    U =R                  S-  sl        Us $ f = fre   )r]   r*   r   r=   defaults      r   getLRI.get   s4    	9 	  A% N	s    !**c                    > U R                      [        [        U ]  U5        U R	                  U5        S S S 5        g ! , (       d  f       g = fr   )r,   r_   r$   r`   rZ   )r   r=   rb   s     r   r`   LRI.__delitem__  s1    ZZ#t(-  % ZZs	   %<
A
c                    > U R                       [        [        U ]  U5      nU R	                  U5        UsS S S 5        $ ! [
         a    U[        L a  e Un N#f = f! , (       d  f       g = fr   )r,   r_   r$   rY   rZ   r]   r   )r   r=   rm   rh   rb   s       r   rY   LRI.pop  sc    ZZ*C*3/ $$S) Z  h& Zs+   A?AAAAA
A)c                    > U R                      [        [        U ]  5       nU R	                  US   5        UsS S S 5        $ ! , (       d  f       g = fNr   )r,   r_   r$   popitemrZ   )r   itemrb   s     r   rv   LRI.popitem  s8    ZZd+-D  a) ZZs   (A  
Ac                    > U R                      [        [        U ]  5         U R	                  5         S S S 5        g ! , (       d  f       g = fr   )r,   r_   r$   clearr-   )r   rb   s    r   rz   	LRI.clear  s*    ZZ#t"$MMO ZZs	   #:
Ac                 6    U R                  U R                  U S9$ )N)r+   r2   )rb   r+   r
   s    r   copyLRI.copy$  s    ~~t}}T~BBr   c                     U R                       X   sS S S 5        $ ! [         a'    U =R                  S-  sl        X U'   Us sS S S 5        $ f = f! , (       d  f       g = fre   )r,   r]   r*   rl   s      r   
setdefaultLRI.setdefault'  sW    ZZy Z  $$)$#S	 Z Zs&   A%AAAA
Ac                 P   U R                      XL a
   S S S 5        g U R                  n[        [        USS 5      5      (       a#  UR	                  5        H  nU" XAU   5        M     OU H  u  pEU" XE5        M     U H  nU" XBU   5        M      S S S 5        g ! , (       d  f       g = f)Nkeys)r,   ra   r.   getattrr   )r   EFsetitemkvs         r   r1   
LRI.update0  s    ZZy Z &&G64011AAt$ " DAAM Q4   ZZs   BA2B
B%c                   > U R                      XL a
   S S S 5        g[        U5      [        U 5      :w  a
   S S S 5        g[        U[        5      (       d  X:H  sS S S 5        $ [        [        U ]  U5      sS S S 5        $ ! , (       d  f       g = f)NTF)r,   r^   
isinstancer$   r_   __eq__)r   otherrb   s     r   r   
LRI.__eq__@  sk    ZZ} Z 5zSY&	 Z
 eS))} Z d*51 ZZs   A=A=A=!A==
Bc                     X:X  + $ r   r	   )r   r   s     r   __ne__
LRI.__ne__J  s    ""r   c                    > U R                   R                  n[        [        U ]  5       nU< SU R
                  < SU R                  < SU< S3$ )Nz
(max_size=z
, on_miss=z	, values=))rb   r   r_   r$   __repr__r+   r0   )r   cnval_maprb   s      r   r   LRI.__repr__M  s<    ^^$$T+-t}}dllG= 	>r   )r7   r6   r,   r(   r+   r)   r0   r*   r   )r   r   r   r   r   DEFAULT_MAX_SIZEr3   r-   r?   r<   rM   rQ   rV   rZ   ra   ri   rn   r`   r   rY   rv   rz   r}   r   r1   r   r   r   r   __classcell__)rb   s   @r   r$   r$   g   s    * !1 4$($&$&
  ( 
C 2#> >r   r$   c                       \ rS rSrSrS rSrg)LRUiT  a  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                 ^   U R                       U R                  U5      nU =R
                  S-  sl        U[           sS S S 5        $ ! [         aJ    U =R                  S-  sl        U R                  (       d  e U R	                  U5      =o0U'   Us sS S S 5        $ f = f! , (       d  f       g = fre   )r,   rM   r]   r)   r0   r(   rD   rg   s       r   ri   LRU.__getitem__v  s    ZZ==cB NNaN; Z  1$||"&,,s"333i
 Z Zs.   BABABBBB
B,r	   N)r   r   r   r   r   ri   r   r	   r   r   r   r   T  s     Br   r   c                   .    \ rS rSrSrSrS rS rS rSr	g)	
_HashedKeyi  zgThe _HashedKey guarantees that hash() will be called no more than once
per cached function invocation.

hash_valuec                 >    XS S & [        [        U5      5      U l        g r   )hashtupler   r   r=   s     r   r3   _HashedKey.__init__  s    QuSz*r   c                     U R                   $ r   r   r
   s    r   __hash___HashedKey.__hash__  s    r   c                 d    U R                   R                  < S[        R                  U 5      < S3$ )N(r   )rb   r   listr   r
   s    r   r   _HashedKey.__repr__  s     >>22DMM$4GHHr   r   N)
r   r   r   r   r   	__slots__r3   r   r   r   r	   r   r   r   r     s     I+Ir   r   Fc           	         [        U 5      nU(       a;  [        UR                  5       5      nUR                  U5        UR	                  U5        U(       ab  UR	                  U  Vs/ s H  n[        U5      PM     sn5        U(       a/  UR	                  W VVs/ s H  u  p[        U5      PM     snn5        O&[        U5      S:X  a  [        US   5      U;   a  US   $ [        U5      $ s  snf s  snnf )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
rf   r   )r   sorteditemsrB   extendtyper^   r   )	argskwargstyped
kwarg_mark	fasttypesr=   sorted_itemsr   r   s	            r   make_cache_keyr     s    . t*Cflln-

:

< 

T*TDGT*+JJL9LDAQL9:	SQ4A<941vc? +9s   $C(C-
c                   .    \ rS rSrSrSS jrS rS rSrg)	CachedFunctioni  zqThis type is used by :func:`cached`, below. Instances of this
class are used to wrap functions in caching logic.
Nc                 "  ^ Xl         [        T5      (       a  TU l        OP[        [        TSS 5      5      (       a  [        [        TSS 5      5      (       d  [	        ST-  5      eU4S jnX`l        X0l        X@l        U=(       d    [        U l        g )Nri   ra   zYexpected cache to be a dict-like object, or callable returning a dict-like object, not %rc                     > T $ r   r	   )caches   r   
_get_cache+CachedFunction.__init__.<locals>._get_cache      r   )	funcr.   	get_cacher   r/   scopedr   r   key_funcr   r   r   r   r   r=   r   s     `    r   r3   CachedFunction.__init__  s{    	E??"DN75->??wumTBCC P#$ % %'N
-~r   c                     U R                  5       nU R                  XU R                  S9n X4   nU$ ! [         a    U R                  " U0 UD6=oSU'    U$ f = f)Nr   )r   r   r   r]   r   )r   r   r   r   r=   rh   s         r   __call__CachedFunction.__call__  sg     mmD

m;	:*C 
  	:#yy$9&99C*
	:s   2  AAc                     U R                   R                  nU R                  (       d  U R                  (       d0  U< SU R                  < SU R                  < SU R                  < S3$ U< SU R                  < S3$ )Nz(func=z	, scoped=z, typed=r   )rb   r   r   r   r   r   r   s     r   r   CachedFunction.__repr__  sM    ^^$$::T[[499dkk4::? @ "DII..r   )r   r   r   r   r   TFN)	r   r   r   r   r   r3   r   r   r   r	   r   r   r   r     s    ."/r   r   c                   8    \ rS rSrSrS	S jrS
S jrS rS rSr	g)CachedMethodi  zpSimilar to :class:`CachedFunction`, this type is used by
:func:`cachedmethod` to wrap methods in caching logic.
Nc                   ^ Xl         [        USS5      U l        [        T[        5      (       a  [        T5      U l        Oh[        T5      (       a  TU l        OP[        [        TSS 5      5      (       a  [        [        TSS 5      5      (       d  [        ST-  5      eU4S jnX`l        X0l	        X@l
        U=(       d    [        U l        S U l        g )N__isabstractmethod__Fri   ra   zjexpected cache to be an attribute name, dict-like object, or callable returning a dict-like object, not %rc                    > T$ r   r	   )objr   s    r   r   )CachedMethod.__init__.<locals>._get_cache  r   r   )r   r   r   r   
basestringr   r   r.   r/   r   r   r   r   bound_tor   s     `    r   r3   CachedMethod.__init__  s    	$+D2H%$P!eZ(('.DNe__"DN75->??wumTBCC :<AB C C'N
-~r   c                     Uc  U $ U R                   nU" U R                  U R                  U R                  U R                  U R
                  S9nXl        U$ )N)r   r   r=   )rb   r   r   r   r   r   r   )r   r   objtypeclsrh   s        r   __get__CachedMethod.__get__   sH    ;Knn$))T^^4::$--9
r   c                    U R                   c  US   OU R                   nU R                  U5      nU R                  (       a  U R                   U R                  4U-   OUnU R	                  XRU R
                  S9n XF   nU$ ! [         a7    U R                   b  U R                   4U-   nU R                  " U0 UD6=otU'    U$ f = f)Nr   r   )r   r   r   r   r   r   r]   )r   r   r   r   r   key_argsr=   rh   s           r   r   CachedMethod.__call__	  s    .d1gDMMs#8<DMM499-4mmHDJJm?	:*C
 
	  	:}}('$.#yy$9&99C*
		:s   9A? ?=C ?C c                     U R                   R                  nXR                  U R                  U R                  4nU R
                  b  X R
                  4-  nSU-  $ SU-  $ )Nz+<%s func=%r scoped=%r typed=%r bound_to=%r>z %s(func=%r, scoped=%r, typed=%r))rb   r   r   r   r   r   )r   r   r   s      r   r   CachedMethod.__repr__  sX    ^^$$IIt{{DJJ7==$]]$$DADHI2T9:r   )r   r   r   r   r   r   r   r   r   )
r   r   r   r   r   r3   r   r   r   r   r	   r   r   r   r     s    *;r   r   c                     ^ ^^^ U UUU4S jnU$ )a  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                    > [        U TTTTS9$ N)r   r   r=   )r   r   r   r=   r   r   s    r   cached_func_decorator%cached.<locals>.cached_func_decorator@  s    dE&3OOr   r	   )r   r   r   r=   r   s   ```` r   cachedr     s    BP P  r   c                     ^ ^^^ U UUU4S jnU$ )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                    > [        U TTTTS9$ r   )r   r   s    r   cached_method_decorator-cachedmethod.<locals>.cached_method_decoratorj  s    D%eMMr   r	   )r   r   r   r=   r   s   ```` r   cachedmethodr   E  s    JN N""r   c                   .    \ rS rSrSrS rSS jrS rSrg)	cachedpropertyio  a  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                 V    [        US5      U l        [        USS5      U l        Xl        g )Nr   r   F)r   r   r   r   )r   r   s     r   r3   cachedproperty.__init__y  s'    tY/$+D2H%$P!	r   Nc                 v    Uc  U $ U R                  U5      =o1R                  U R                   R                  '   U$ r   )r   __dict__r   )r   r   r   rP   s       r   r   cachedproperty.__get__~  s4    ;K3799S>ATYY//0r   c                 X    U R                   R                  nSU< SU R                  < S3$ )N<z func=>)rb   r   r   r   s     r   r   cachedproperty.__repr__  s     ^^$$!#TYY//r   )r   r   r   r   )	r   r   r   r   r   r3   r   r   r   r	   r   r   r   r   o  s    
0r   r   c                       \ rS rSrSrSS jr\S 5       rS rS r	SS jr
S	 rS
 rS rS rS rS rS rS rS rS rS rS rSS jrS rSrg)ThresholdCounteri  a$  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.

c                     SUs=:  a  S:  d  O  [        SU-  5      eSU l        0 U l        Xl        [	        SU-  5      U l        SU l        g )Nr   rf   z+expected threshold between 0 and 1, not: %r)r'   total
_count_map
_thresholdint_thresh_count_cur_bucket)r   	thresholds     r   r3   ThresholdCounter.__init__  sU    9 q J() * * 
# Y/r   c                     U R                   $ r   )r  r
   s    r   r  ThresholdCounter.threshold  s    r   c           	         U =R                   S-  sl          U R                  U   S==   S-  ss'   U R                   U R                  -  S:X  an  [        U R                  R                  5        VVs/ s H#  u  p#[        U5      U R                  :  d  M   X#4PM%     snn5      U l        U =R                  S-  sl        g! [         a!    SU R                  S-
  /U R                  U'    Nf = fs  snnf )zIncrement the count of *key* by 1, automatically adding it if it
does not exist.

Cache compaction is triggered every *1/threshold* additions.
rf   r   N)r   r  r]   r  r  dictr   sum)r   r=   r   r   s       r   addThresholdCounter.add  s     	

a
	=OOC #q(# ::***a/"t7L7L7N $B7Ntq'*1v0@0@'@ %+QF7N $B CDO!  	=$%t'7'7!';#<DOOC 	=$Bs   B= 0C+
C+
=(C('C(c                     [         R                  " [         R                  U R                  5       5      n[         R                  R                  U5      $ )zyReturn 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   elementsThresholdCounter.elements  s8     %%i&6&68HI	,,Y77r   Nc                 x    US::  a  / $ [        U R                  5       S SS9nUb  U[        U5      :  a  U$ USU $ )zUGet the top *n* keys and counts as tuples. If *n* is omitted,
returns all the pairs.
r   c                     U S   $ re   r	   )xs    r   <lambda>.ThresholdCounter.most_common.<locals>.<lambda>  s    QqTr   T)r=   reverseN)r   r  r^   )r   nrh   s      r   most_commonThresholdCounter.most_common  sD     6IT^^%>4H9SXJ2Awr   c                 ~    [        U R                  R                  5        VVs/ s H  u  pUPM	     snn5      $ s  snnf )zHGet the sum of counts for keys exceeding the configured data
threshold.
)r  r  r2   )r   count_s      r   get_common_count!ThresholdCounter.get_common_count  s2     $//*@*@*BC*BheE*BCDDCs   9
c                 <    U R                   U R                  5       -
  $ )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_count#ThresholdCounter.get_uncommon_count  s    
 zzD11333r   c                 N    [        U R                  5       5      U R                  -  $ )a  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_commonality ThresholdCounter.get_commonality  s!     T**,-

::r   c                 &    U R                   U   S   $ ru   r  r   s     r   ri   ThresholdCounter.__getitem__  s    s#A&&r   c                 ,    [        U R                  5      $ r   )r^   r  r
   s    r   __len__ThresholdCounter.__len__  s    4??##r   c                     XR                   ;   $ r   r/  r   s     r   __contains__ThresholdCounter.__contains__  s    oo%%r   c                 ,    [        U R                  5      $ r   )iterr  r
   s    r   iterkeysThresholdCounter.iterkeys  s    DOO$$r   c                 4    [        U R                  5       5      $ r   )r   r9  r
   s    r   r   ThresholdCounter.keys  s    DMMO$$r   c              #   H   #    U R                   nU H  nX   S   v   M     g 7fru   r/  r   	count_mapr   s      r   
itervaluesThresholdCounter.itervalues  s$     OO	A,q/! s    "c                 4    [        U R                  5       5      $ r   )r   r@  r
   s    r   r2   ThresholdCounter.values  s    DOO%&&r   c              #   L   #    U R                   nU H  nX!U   S   4v   M     g 7fru   r/  r>  s      r   r  ThresholdCounter.iteritems  s)     OO	Al1o&& s   "$c                 4    [        U R                  5       5      $ r   )r   r  r
   s    r   r   ThresholdCounter.items  s    DNN$%%r   c                 0     X   $ ! [          a    Us $ f = f)z%Get count for *key*, defaulting to 0.)r]   rl   s      r   rn   ThresholdCounter.get  s#    	9 	N	s    c                     Ubr  [        [        USS5      5      (       a=  UR                  5        H(  u  p4[        U5       H  nU R	                  U5        M     M*     OU H  nU R	                  U5        M     U(       a  U R                  U5        gg)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.   r   r  xranger  r1   )r   iterabler   r=   r#  is         r   r1   ThresholdCounter.update%  sw     +t<=="*"4"4"6JC#E] + #7 $CHHSM $KK r   )r  r  r  r  r   )gMbP?r   )r   )r   r   r   r   r   r3   propertyr  r  r  r   r%  r(  r,  ri   r2  r5  r9  r   r@  r2   r  r   rn   r1   r   r	   r   r   r   r     sw    )V	  $8	E4;'$&%%"
''
& r   r   c                   H    \ rS rSrSrS rS rS rS rS r	S r
S	 rS
 rSrg)MinIDMapi8  z
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                 T    [         R                  " 5       U l        0 U l        / U l        g r   )weakrefWeakKeyDictionarymappingref_mapfreer
   s    r   r3   MinIDMap.__init__B  s     002	r   c                 V    U R                   U   S   $ ! [         a     Of = fU R                  (       a!  [        R                  " U R                  5      nO[        U R                   5      n[        R                  " XR                  5      nX#4U R                   U'   X R                  U'   U$ ru   )
rU  r]   rW  heapqheappopr^   rS  ref_cleanrV  )r   anxtr\  s       r   rn   MinIDMap.getG  s    	<<?1%% 		 99--		*Cdll#Ckk![[)*QS
s    
!!c                     U R                   U   u  p#U R                   U	 U R                  U	 [        R                  " U R                  U5        g r   )rU  rV  rZ  heappushrW  )r   r^  freedr\  s       r   dropMinIDMap.dropV  s:    \\!_
LLOLLtyy%(r   c                     [        U R                  U   5        [        R                  " U R                  U R                  U   5        U R                  U	 g r   )r;   rV  rZ  rb  rW  )r   r\  s     r   r]  MinIDMap._clean\  s:    dll3 tyy$,,s"34LLr   c                     XR                   ;   $ r   rU  )r   r^  s     r   r5  MinIDMap.__contains__a  s    LL  r   c                 ,    [        U R                  5      $ r   r8  rU  r
   s    r   __iter__MinIDMap.__iter__d  s    DLL!!r   c                 6    U R                   R                  5       $ r   )rU  r2  r
   s    r   r2  MinIDMap.__len__g  s    ||##%%r   c                 T   ^  [        U 4S j[        T R                  5       5       5      $ )Nc              3   J   >#    U  H  oTR                   U   S    4v   M     g7f)r   Nri  ).0r   r   s     r   	<genexpr>%MinIDMap.iteritems.<locals>.<genexpr>k  s#     H5GQ*+5Gs    #rl  r
   s   `r   r  MinIDMap.iteritemsj  s    HT$,,5GHHHr   )rW  rU  rV  N)r   r   r   r   r   r3   rn   rd  r]  r5  rm  r2  r  r   r	   r   r   rQ  rQ  8  s0    
)
!"&Ir   rQ  r   ),r   rZ  rS  r  operatorr   	threadingr   	Exceptionobjectboltons.typeutilsr   r   r    ImportErrorrK  	NameErrorrangestrbytesunicoder   rJ   rE   rC   rD   r   r  r$   r   r   r   	frozensetr  r   r   _make_cache_keyr   r   r   r   r   r   rQ  r	   r   r   <module>r     sr  BF    	/j1H7K
F
 q dC j>$ j>Z.# .hI I" (-)&S)T$Z'HI"J !#/V #/L5;6 5;p#!L'#T0V 04l v l ^3Iv 3I[     xH(K  FF&)5%#u&E#GS%Fs3   B> C C/ >CCC,+C,/DD