a 97a@sdZddlmZddlZddlmZddlmZ m Z ddl Z ddl ZddlmZddlmZmZmZddlmZmZmZmZdd lmZmZm Z m!Z!m"Z"e rdd l#m$Z$m%Z%ndd l&m$Z$m%Z%d d Zdd lm'Z'e"r zddl(m)Z)Wn e*yddl+m)Z)Yn0n2zddl,m)Z)Wn e*y<ddl-m)Z)Yn0d3ddZ.Gddde/Z0Gddde1Z2zddlmZddl m3Z3Wne*yYn0ddZ4Gddde1Z5ddZ6d4dd Z7Gd!d"d"e%Z8dd#lm9Z9e9dfd$d%Z:d&d'Z;e2Ze7Z?eZ@e4ZAe.ZBe8ZCe:ZDe;ZEe jFd(krdd)l#m2Z2m5Z5dd*lm7Z7dd+lGm;Z;zdd,lm6Z6Wne*yvYn0dd-lm:Z:e jFd.krddlmZdd/l#m4Z4e jFd0krdd1lHm.Z.dd2l#m8Z8dS)5a Miscellaneous function (re)definitions from the Py3.4+ standard library for Python 2.6/2.7. - math.ceil (for Python 2.7) - collections.OrderedDict (for Python 2.6) - collections.Counter (for Python 2.6) - collections.ChainMap (for all versions prior to Python 3.3) - itertools.count (for Python 2.6, with step parameter) - subprocess.check_output (for Python 2.6) - reprlib.recursive_repr (for Python 2.6+) - functools.cmp_to_key (for Python 2.6) )absolute_importN)ceil) itemgettereq)proxy)repeatchainstarmap) getaddrinfo SOCK_STREAMerrorsocket) iteritems itervaluesPY2PY26PY3)MappingMutableMappingcCs tt|S)zZ Return the ceiling of x as an int. This is the smallest integral value >= x. )intoldceil)xrp/private/var/folders/s6/9n5zrl012gv99k63s4q6ccsd4s6mqz/T/pip-target-f5cq3f2q/lib/python/future/backports/misc.pyr#sr)islice) get_ident...csfdd}|S)zGDecorator to make a repr function return fillvalue for a recursive callcsLtfdd}td|_td|_td|_tdi|_|S)Nc sLt|tf}|vrS|z|}W|n |0|SN)idradddiscard)selfkeyresult) fillvalue repr_running user_functionrrwrapperCs  z.decorating_function..wrapper __module____doc____name____annotations__)setgetattrr(r)r*r+)r&r'r$)r%r&rdecorating_function@s   z+recursive_repr..decorating_functionr)r$r/rr.rrecursive_repr=s r0c@seZdZdZdS)_Link)prevnextr" __weakref__N)r*r( __qualname__ __slots__rrrrr1\sr1c@seZdZdZddZejeefddZej fddZ dd Z d d Z d d Z d$ddZ d%ddZddZejZZejZejZejZejZeZefddZd&ddZeddZddZddZed'd d!Z d"d#Z!dS)( OrderedDictz)Dictionary that remembers insertion ordercOs|s td|d}|dd}t|dkr od[i]=yN)r@r<r2r3r") r!r"valueZ dict_setitemrLinklinkrDlastrrr __setitem__s zOrderedDict.__setitem__cCs2||||j|}|j}|j}||_||_dS)z od.__delitem__(y) <==> del od[y]N)r@popr2r3)r!r"Z dict_delitemrH link_prev link_nextrrr __delitem__s   zOrderedDict.__delitem__ccs(|j}|j}||ur$|jV|j}q dS)zod.__iter__() <==> iter(od)N)r<r3r"r!rDcurrrrr__iter__s zOrderedDict.__iter__ccs(|j}|j}||ur$|jV|j}q dS)z#od.__reversed__() <==> reversed(od)N)r<r2r"rOrrr __reversed__s zOrderedDict.__reversed__cCs*|j}||_|_|jt|dS)z.od.clear() -> None. Remove all items from od.N)r<r2r3r@cleardict)r!rDrrrrSs  zOrderedDict.clearTcCsj|s td|j}|r0|j}|j}||_||_n|j}|j}||_||_|j}|j|=t||}||fS)zod.popitem() -> (k, v), return and remove a (key, value) pair. Pairs are returned in LIFO order if last is true or FIFO order if false. zdictionary is empty)KeyErrorr<r2r3r"r@rTrK)r!rIrDrHrLrMr"rFrrrpopitems  zOrderedDict.popitemcCsn|j|}|j}|j}||_||_|j}|rL|j}||_||_||_|_n|j}||_||_||_|_dS)zMove an existing element to the end (or beginning if last==False). Raises KeyError if the element does not exist. When last=True, acts like a fast version of self[key]=self.pop(key). N)r@r2r3r<)r!r"rIrHrLrMrDfirstrrr move_to_ends zOrderedDict.move_to_endcCsVtj}t|d}||j}|||jd7}|||j|7}|||j|7}|S)Nr8)sys getsizeofr;__dict__r@r>r<)r!sizeofnsizerrr __sizeof__s  zOrderedDict.__sizeof__cCs0||vr||}||=|S||jur,t||S)zod.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised. )_OrderedDict__markerrU)r!r"defaultr#rrrrKs zOrderedDict.popNcCs||vr||S|||<|S)zDod.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in odrr!r"rbrrr setdefaultszOrderedDict.setdefaultcCs*|sd|jjfSd|jjt|fS)zod.__repr__() <==> repr(od)%s()z%s(%r)) __class__r*listitemsr!rrr__repr__ szOrderedDict.__repr__cCsDt|}ttD]}||dq|jd|p4ddt|fS)z%Return state information for picklingNr)varscopyr7rKrfiterrh)r! inst_dictkrrr __reduce__s zOrderedDict.__reduce__cCs ||S)z!od.copy() -> a shallow copy of odrfrirrrrlszOrderedDict.copycCs|}|D] }|||<q |S)zOD.fromkeys(S[, v]) -> New ordered dictionary with keys from S. If not specified, the value defaults to None. r)clsiterablerFr!r"rrrfromkeyss zOrderedDict.fromkeyscCs2t|tr&t||o$ttt||St||S)zod.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive. ) isinstancer7rT__eq__allmap_eqr!otherrrrrv(s zOrderedDict.__eq__)T)T)N)N)"r*r(r5r)rErTrJr?r1rNrQrRrSrVrXr`rupdaterAkeysvaluesrh__ne__objectrarKrdr0rjrprl classmethodrtrvrrrrr7_s4           r7)r)nlargestcCs&|j}|D]}||dd||<q dS)z!Tally elements from the iterable.rr8N)get)mappingrsZ mapping_getelemrrr_count_elements>srcseZdZdZfddZddZd/ddZd d Zed0d d Z fd dZ ddZ ddZ ddZ fddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.ZZS)1CounteraDict subclass for counting hashable items. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values. >>> c = Counter('abcdeabcdabcaba') # count elements from a string >>> c.most_common(3) # three most common elements [('a', 5), ('b', 4), ('c', 3)] >>> sorted(c) # list all unique elements ['a', 'b', 'c', 'd', 'e'] >>> ''.join(sorted(c.elements())) # list elements with repetitions 'aaaaabbbbcccdde' >>> sum(c.values()) # total of all counts 15 >>> c['a'] # count of letter 'a' 5 >>> for elem in 'shazam': # update counts from an iterable ... c[elem] += 1 # by adding 1 to each element's count >>> c['a'] # now there are seven 'a' 7 >>> del c['b'] # remove all 'b' >>> c['b'] # now there are zero 'b' 0 >>> d = Counter('simsalabim') # make another counter >>> c.update(d) # add in the second counter >>> c['a'] # now there are nine 'a' 9 >>> c.clear() # empty the counter >>> c Counter() Note: If a count is set to zero or reduced to zero, it will remain in the counter until the entry is deleted or the counter is cleared: >>> c = Counter('aaabbc') >>> c['b'] -= 2 # reduce the count of 'b' by two >>> c.most_common() # 'b' is still in, but its count is zero [('a', 3), ('c', 1), ('b', 0)] cs^|s td|d}|dd}t|dkr>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping >>> c = Counter(a=4, b=2) # a new counter from keyword args z;descriptor '__init__' of 'Counter' object needs an argumentrr8Nr9)r:r;superrrEr|)rBrCr!rqrrrEws   zCounter.__init__cCsdS)z1The count of elements not in the Counter is zero.rrr!r"rrr __missing__szCounter.__missing__NcCs6|durt|tdddStj||tddS)zList the n most common elements and their counts from the most common to the least. If n is None, then list all element counts. >>> Counter('abcdeabcdabcaba').most_common(3) [('a', 5), ('b', 4), ('c', 3)] Nr8T)r"reverser")sortedrh _itemgetter_heapqr)r!r^rrr most_commons zCounter.most_commoncCsttt|S)aIterator over elements repeating each as many times as its count. >>> c = Counter('ABCABC') >>> sorted(c.elements()) ['A', 'A', 'B', 'B', 'C', 'C'] # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1 >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) >>> product = 1 >>> for factor in prime_factors.elements(): # loop over factors ... product *= factor # and multiply them >>> product 1836 Note, if an element's count has been set to zero or is a negative number, elements() will ignore it. )_chain from_iterable_starmap_repeatrhrirrrelementsszCounter.elementscCs tddS)Nz@Counter.fromkeys() is undefined. Use Counter(iterable) instead.)NotImplementedError)rrrsvrrrrtszCounter.fromkeyscs|s td|d}|dd}t|dkr>> c = Counter('which') >>> c.update('witch') # add elements from another iterable >>> d = Counter('watch') >>> c.update(d) # add elements from another counter >>> c['h'] # four 'h' in which, witch, and watch 4 z9descriptor 'update' of 'Counter' object needs an argumentrr8Nr9) r:r;rurrrhrrr|rrBrCr!rsself_getrcountrqrrr|s"    zCounter.updatecOs|s td|d}|dd}t|dkr>> c = Counter('which') >>> c.subtract('witch') # subtract elements from another iterable >>> c.subtract(Counter('watch')) # subtract elements from another counter >>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch 0 >>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch -1 z;descriptor 'subtract' of 'Counter' object needs an argumentrr8Nr9)r:r;rrurrhsubtractrrrrrs    zCounter.subtractcCs ||S)zReturn a shallow copy.rqrirrrrl sz Counter.copycCs|jt|ffSr)rfrTrirrrrp szCounter.__reduce__cs||vrtt||dS)zGLike dict.__delitem__() but does not raise KeyError for missing values.N)rrrN)r!rrqrrrNszCounter.__delitem__cCsd|sd|jjSz(dtdj|}d|jj|fWSty^d|jjt|YS0dS)Nre, z%r: %rz%s({%s})z {0}({1!r})) rfr*joinrx__mod__rr:formatrT)r!rhrrrrjs  zCounter.__repr__cCspt|tstSt}|D]$\}}|||}|dkr|||<q|D] \}}||vrJ|dkrJ|||<qJ|S)zAdd counts from two counters. >>> Counter('abbb') + Counter('bcc') Counter({'b': 4, 'c': 2, 'a': 1}) rrurNotImplementedrhr!r{r#rrnewcountrrr__add__(s    zCounter.__add__cCstt|tstSt}|D]$\}}|||}|dkr|||<q|D]$\}}||vrJ|dkrJd|||<qJ|S)z Subtract count, but keep only results with positive counts. >>> Counter('abbbc') - Counter('bccd') Counter({'b': 2, 'a': 1}) rrrrrr__sub__;s   zCounter.__sub__cCs|t|tstSt}|D]0\}}||}||kr8|n|}|dkr|||<q|D] \}}||vrV|dkrV|||<qV|S)zUnion is the maximum of value in either of the input counters. >>> Counter('abbb') | Counter('bcc') Counter({'b': 3, 'c': 2, 'a': 1}) rrr!r{r#rr other_countrrrr__or__Ns   zCounter.__or__cCsRt|tstSt}|D]0\}}||}||kr8|n|}|dkr|||<q|S)z Intersection is the minimum of corresponding counts. >>> Counter('abbb') & Counter('bcc') Counter({'b': 1}) rrrrrr__and__bs  zCounter.__and__cCs |tS)zEAdds an empty counter, effectively stripping negative and zero countsrrirrr__pos__sszCounter.__pos__cCs t|S)z{Subtracts from an empty counter. Strips positive and zero counts, and flips the sign on negative counts. rrirrr__neg__wszCounter.__neg__cCs&dd|D}|D] }||=q|S)z?Internal method to strip elements with a negative or zero countcSsg|]\}}|dks|qS)rr).0rrrrr z*Counter._keep_positive..)rh)r! nonpositiverrrr_keep_positive~szCounter._keep_positivecCs*|D]\}}|||7<q|S)zInplace add from another counter, keeping only positive counts. >>> c = Counter('abbb') >>> c += Counter('bcc') >>> c Counter({'b': 4, 'c': 2, 'a': 1}) rhrr!r{rrrrr__iadd__s zCounter.__iadd__cCs*|D]\}}|||8<q|S)zInplace subtract counter, but keep only results with positive counts. >>> c = Counter('abbbc') >>> c -= Counter('bccd') >>> c Counter({'b': 2, 'a': 1}) rrrrr__isub__s zCounter.__isub__cCs2|D] \}}||}||kr|||<q|S)zInplace union is the maximum of value from either counter. >>> c = Counter('abbb') >>> c |= Counter('bcc') >>> c Counter({'b': 3, 'c': 2, 'a': 1}) r)r!r{rrrrrr__ior__s  zCounter.__ior__cCs2|D] \}}||}||kr|||<q|S)zInplace intersection is the minimum of corresponding counts. >>> c = Counter('abbb') >>> c &= Counter('bcc') >>> c Counter({'b': 1}) r)r!r{rrrrrr__iand__s  zCounter.__iand__)N)N)r*r(r5r)rErrrrrtr|rrlrprNrjrrrrrrrrrrr __classcell__rrrqrrDs02    )#   rcOshd|vrtdtj|dtji|}|\}}|}|rd|d}|durX|d}t|||S)z[ For Python 2.6 compatibility: see http://stackoverflow.com/questions/4814970/ stdoutz3stdout argument not allowed, it will be overridden.rBNr) ValueError subprocessPopenPIPE communicatepollrCalledProcessError) popenargskwargsprocessoutputZ unused_errretcodecmdrrr check_outputs   rr8ccs|V||7}qdS)z ``itertools.count`` in Py 2.6 doesn't accept a step parameter. This is an enhanced version of ``itertools.count`` for Py2.6 equivalent to ``itertools.count`` in Python 2.7+. Nr)startsteprrrrsrc@seZdZdZddZddZddZd'd d Zd d Zd dZ ddZ ddZ e Z e ddZeddZddZeZd(ddZeddZddZdd Zd!d"Zd#d$Zd%d&ZdS))ChainMapa A ChainMap groups multiple dicts (or other mappings) together to create a single, updateable view. The underlying mappings are stored in a list. That list is public and can accessed or updated using the *maps* attribute. There is no other state. Lookups search the underlying mappings successively until a key is found. In contrast, writes, updates, and deletions only operate on the first mapping. cGst|p ig|_dS)zInitialize a ChainMap by setting *maps* to the given mappings. If no mappings are provided, a single empty dictionary is used. N)rgmaps)r!rrrrrEszChainMap.__init__cCs t|dSr)rUrrrrrszChainMap.__missing__c Cs8|jD]&}z||WSty*Yq0q||Sr)rrUr)r!r"rrrr __getitem__s   zChainMap.__getitem__NcCs||vr||S|Srrrcrrrrsz ChainMap.getcCsttj|jSr)r;r,unionrrirrr__len__szChainMap.__len__cCsttj|jSr)rmr,rrrirrrrQszChainMap.__iter__cstfdd|jDS)Nc3s|]}|vVqdSrr)rmrrr rz(ChainMap.__contains__..anyrrrrr __contains__ szChainMap.__contains__cCs t|jSrrrirrr__bool__ szChainMap.__bool__cCsd|dtt|jS)Nz{0.__class__.__name__}({1})r)rrrxreprrrirrrrjszChainMap.__repr__cGs|tj|g|RS)z?Create a ChainMap with a single dict created from the iterable.)rTrt)rrrsrBrrrrtszChainMap.fromkeyscCs&|j|jdg|jddRS)zHNew ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]rr8N)rfrrlrirrrrlsz ChainMap.copycCs |dur i}|j|g|jRS)z New ChainMap with a new map followed by all previous maps. If no map is provided, an empty dict is used. Nrfr)r!rrrr new_child#szChainMap.new_childcCs|j|jddS)zNew ChainMap from maps[1:].r8Nrrirrrparents,szChainMap.parentscCs||jd|<dSNr)r)r!r"rFrrrrJ1szChainMap.__setitem__cCs6z|jd|=Wn ty0td|Yn0dS)Nr)Key not found in the first mapping: {0!r})rrUrrrrrrN4s zChainMap.__delitem__cCs0z|jdWSty*tdYn0dS)zPRemove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.rz#No keys found in the first mapping.N)rrVrUrirrrrV:s zChainMap.popitemcGs@z|jdj|g|RWSty:td|Yn0dS)zWRemove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].rrN)rrKrUr)r!r"rBrrrrKAs z ChainMap.popcCs|jddS)z'Clear maps[0], leaving maps[1:] intact.rN)rrSrirrrrSHszChainMap.clear)N)N)r*r(r5r)rErrrrrQrr __nonzero__r0rjrrtrl__copy__rpropertyrrJrNrVrKrSrrrrrs0      r)_GLOBAL_DEFAULT_TIMEOUTc Cs|\}}d}t||dtD]}|\}}} } } d} z@t||| } |turP| ||r^| || | | WSty} z | }| dur| WYd} ~ qd} ~ 00q|dur|ntddS)aBackport of 3-argument create_connection() for Py2.6. Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by :func:`getdefaulttimeout` is used. If *source_address* is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. An host of '' or port 0 tells the OS to use the default. Nrz!getaddrinfo returns an empty list) r r r r settimeoutbindconnectr close)addresstimeoutsource_addresshostporterrresafsocktypeproto canonnamesasock_rrrcreate_connectionRs(      rcsGfdddt}|S)z,Convert a cmp= function into a key= functioncsjeZdZdgZddZfddZfddZfdd Zfd d Zfd d Z fddZ ddZ dS)zcmp_to_key..KobjcWs ||_dSrr)r!rrBrrrrEszcmp_to_key..K.__init__cs|j|jdkSrrrzmycmprr__lt__szcmp_to_key..K.__lt__cs|j|jdkSrrrzrrr__gt__szcmp_to_key..K.__gt__cs|j|jdkSrrrzrrrrvszcmp_to_key..K.__eq__cs|j|jdkSrrrzrrr__le__szcmp_to_key..K.__le__cs|j|jdkSrrrzrrr__ge__szcmp_to_key..K.__ge__cs|j|jdkSrrrzrrrrszcmp_to_key..K.__ne__cSs tddS)Nzhash not implemented)r:rirrr__hash__szcmp_to_key..K.__hash__N) r*r(r5r6rErrrvrrrrrrrrK}s      r)r)rrrrr cmp_to_key{sr)rY)r7r)r)r)r)r)r)r)rr)r0)r)r)rr8)Ir) __future__rrmathrroperatorrrrryrZheapqr_weakrefrr? itertoolsrrrrr rr r r r Z future.utilsrrrrr collectionsrrcollections.abcr_threadr ImportError _dummy_threadthread dummy_threadr0rr1rTr7rrrrrrrrr _OrderedDictZ_CounterZ _check_output_count_ceilZ__count_elements_recursive_repr _ChainMap_create_connectionZ _cmp_to_key version_info functoolsreprlibrrrrs     V | l  )