o ,]@sdZddlmZddlZddlmZddlmZ m Z ddl Z ddl ZddlmZddlmZmZmZddlmZmZmZmZdd lmZmZm Z m!Z!m"Z"e rWdd l#m$Z$m%Z%ndd l&m$Z$m%Z%d d Zdd lm'Z'e"rzddl(m)Z)Wn'e*yddl+m)Z)Ynwzddl,m)Z)Wne*yddl-m)Z)Ynwd3ddZ.Gddde/Z0Gddde1Z2zddlmZddl m3Z3Wn e*yYnwddZ4Gddde1Z5ddZ6d4dd Z7Gd!d"d"e%Z8dd#lm9Z9e9dfd$d%Z:d&d'Z;e2Ze7Z?eZ@e4ZAe.ZBe8ZCe:ZDe;ZEe jFd(kr=dd)l#m2Z2m5Z5dd*lm7Z7dd+lGm;Z;zdd,lm6Z6Wn e*y6Ynwdd-lm:Z:e jFd.krOddlmZdd/l#m4Z4e jFd0krcdd1lHm.Z.dd2l#m8Z8dSdS)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)xr7/usr/lib/python3/dist-packages/future/backports/misc.pyr#s r)islice) get_ident...csfdd}|S)zGDecorator to make a repr function return fillvalue for a recursive callcsLtfdd}td|_td|_td|_tdi|_|S)Nc sJt|tf}|vr S|z |}W||S|wN)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|std|d}|dd}t|dkrtdt|z|jWntyAt|_t|j|_}||_|_i|_ Ynw|j |i|dS)zInitialize an ordered dictionary. The signature is the same as regular dictionaries, but keyword arguments are not recommended because their insertion order is arbitrary. z?descriptor '__init__' of 'OrderedDict' object needs an argumentrN$expected at most 1 arguments, got %d) TypeErrorlen_OrderedDict__rootAttributeErrorr1_OrderedDict__hardroot_proxyr2r3_OrderedDict__map_OrderedDict__update)argskwdsr!rootrrr__init__ns      zOrderedDict.__init__c CsZ||vr%||j|<}|j}|j}||||_|_|_||_|||_||||dS)z!od.__setitem__(i, y) <==> od[i]=yN)r@r<r2r3r") r!r"value dict_setitemrLinklinkrDlastrrr __setitem__s zOrderedDict.__setitem__cCs2||||j|}|j}|j}||_||_dS)z od.__delitem__(y) <==> del od[y]N)r@popr2r3)r!r" dict_delitemrI link_prev link_nextrrr __delitem__s   zOrderedDict.__delitem__cc4|j}|j}||ur|jV|j}||us dSdS)zod.__iter__() <==> iter(od)N)r<r3r"r!rDcurrrrr__iter__zOrderedDict.__iter__ccrQ)z#od.__reversed__() <==> reversed(od)N)r<r2r"rRrrr __reversed__rUzOrderedDict.__reversed__cCs*|j}||_|_|jt|dS)z.od.clear() -> None. Remove all items from od.N)r<r2r3r@cleardict)r!rDrrrrWs  zOrderedDict.clearTcCsj|std|j}|r|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@rXrL)r!rJrDrIrNrOr"rFrrrpopitems  zOrderedDict.popitemcCsp|j|}|j}|j}||_||_|j}|r'|j}||_||_||_|_dS|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"rJrIrNrOrDfirstrrr 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||jurt||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__markerrY)r!r"defaultr#rrrrLs zOrderedDict.popNcCs||vr||S|||<|S)zDod.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in odrr!r"rfrrr setdefaultszOrderedDict.setdefaultcCs*|s d|jjfSd|jjt|fS)zod.__repr__() <==> repr(od)%s()z%s(%r)) __class__r*listitemsr!rrr__repr__ szOrderedDict.__repr__cCsDt|}ttD]}||dq |jd|pddt|fS)z%Return state information for picklingNr)varscopyr7rLrjiterrl)r! inst_dictkrrr __reduce__s zOrderedDict.__reduce__cC ||S)z!od.copy() -> a shallow copy of odrjrmrrrrp zOrderedDict.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|trt||ottt||St||S)zod.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive. ) isinstancer7rX__eq__allmap_eqr!otherrrrr|(s  zOrderedDict.__eq__)Tr)"r*r(r5r)rErXrKr?r1rPrTrVrWrZr\rdrupdaterAkeysvaluesrl__ne__objectrerLrhr0rnrtrp classmethodrzr|rrrrr7_s6           r7)r)nlargestcCs&|j}|D] }||dd||<qdS)z!Tally elements from the iterable.rr8N)get)mappingry mapping_getelemrrr_count_elements>srcseZdZdZfddZddZd/ddZd d Zed/d d Z fd dZ ddZ ddZ ddZ fddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.ZZS)0CounteraDict 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^|std|d}|dd}t|dkrtdt|tt||j|i|dS)a Create a new, empty Counter object. And if given, count elements from an input iterable. Or, initialize the count from another mapping of elements to their counts. >>> 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!rvrrrEws   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")sortedrl _itemgetter_heapqr)r!rbrrr 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_repeatrlrmrrrelementsszCounter.elementscCtd)Nz@Counter.fromkeys() is undefined. Use Counter(iterable) instead.)NotImplementedError)rxryvrrrrzszCounter.fromkeyscs|std|d}|dd}t|dkrtdt||r$|dnd}|durUt|trP|rG|j}|D] \}}|||d||<q8ntt||nt |||r^||dSdS)aLike dict.update() but add counts instead of replacing them. Source can be an iterable, a dictionary, or another Counter instance. >>> 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;r{rrrlrrrrrBrCr!ryself_getrcountrvrrrs&    zCounter.updatecOs|std|d}|dd}t|dkrtdt||r$|dnd}|durS|j}t|trE|D] \}}||d|||<q6n|D] }||dd||<qG|r\||dSdS)aLike dict.update() but subtracts counts instead of replacing them. Counts can be reduced below zero. Both the inputs and outputs are allowed to contain zero and negative counts. Source can be an iterable, a dictionary, or another Counter instance. >>> 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;rr{rrlsubtractrrrrrs$   zCounter.subtractcCru)zReturn a shallow copy.rvrmrrrrp rwz Counter.copycCs|jt|ffSr)rjrXrmrrrrt szCounter.__reduce__cs ||vrtt||dSdS)zGLike dict.__delitem__() but does not raise KeyError for missing values.N)rrrP)r!rrvrrrPszCounter.__delitem__cCs`|sd|jjSzdtdj|}d|jj|fWSty/d|jjt|YSw)Nri, z%r: %rz%s({%s})z {0}({1!r})) rjr*joinr~__mod__rr:formatrX)r!rlrrrrns  zCounter.__repr__cCspt|tstSt}|D]\}}|||}|dkr |||<q|D]\}}||vr5|dkr5|||<q%|S)zAdd counts from two counters. >>> Counter('abbb') + Counter('bcc') Counter({'b': 4, 'c': 2, 'a': 1}) rr{rNotImplementedrlr!rr#rrnewcountrrr__add__(s  zCounter.__add__cCstt|tstSt}|D]\}}|||}|dkr |||<q|D]\}}||vr7|dkr7d|||<q%|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]\}}||}||kr|n|}|dkr&|||<q|D]\}}||vr;|dkr;|||<q+|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!rr#rr other_countrrrr__or__Ns zCounter.__or__cCsRt|tstSt}|D]\}}||}||kr|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 countsrrmrrr__pos__srwzCounter.__pos__cCs t|S)z{Subtracts from an empty counter. Strips positive and zero counts, and flips the sign on negative counts. rrmrrr__neg__ws zCounter.__neg__cCs&dd|D}|D]}||=q |S)z?Internal method to strip elements with a negative or zero countcSsg|] \}}|dks|qS)rr).0rrrrr sz*Counter._keep_positive..)rl)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}) rlrr!rrrrrr__iadd__ 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__rzCounter.__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!rrrrrrr__ior__  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!rrrrrrr__iand__rzCounter.__iand__r)r*r(r5r)rErrrrrzrrrprtrPrnrrrrrrrrrrr __classcell__rrrvrrDs2 2    )#   rcOshd|vrtdtj|dtji|}|\}}|}|r2|d}|dur,|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) popenargskwargsprocessoutput unused_errretcodecmdrrr check_outputs   rr8ccs |V||7}q)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+. r)startsteprrrrs rc@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|pig|_dS)zInitialize a ChainMap by setting *maps* to the given mappings. If no mappings are provided, a single empty dictionary is used. N)rkmaps)r!rrrrrEszChainMap.__init__cCst|r)rYrrrrrzChainMap.__missing__c Cs6|jD]}z||WStyYqw||Sr)rrYr)r!r"rrrr __getitem__s   zChainMap.__getitem__NcCs||vr||S|Srrrgrrrrsz ChainMap.getcCttj|jSr)r;r,unionrrmrrr__len__zChainMap.__len__cCrr)rqr,rrrmrrrrTrzChainMap.__iter__cstfdd|jDS)Nc3s|]}|vVqdSrr)rmrrr sz(ChainMap.__contains__..anyrrrrr __contains__ szChainMap.__contains__cCs t|jSrrrmrrr__bool__  zChainMap.__bool__cCsd|dtt|jS)Nz{0.__class__.__name__}({1})r)rrr~reprrrmrrrrnszChainMap.__repr__cGs|tj|g|RS)z?Create a ChainMap with a single dict created from the iterable.)rXrz)rxryrBrrrrzszChainMap.fromkeyscCs&|j|jdg|jddRS)zHNew ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]rr8N)rjrrprmrrrrps&z ChainMap.copycCs |duri}|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. Nrjr)r!rrrr new_child#szChainMap.new_childcCs|j|jddS)zNew ChainMap from maps[1:].r8Nrrmrrrparents,szChainMap.parentscCs||jd|<dSNr)r)r!r"rFrrrrK1rzChainMap.__setitem__cCs0z |jd|=WdStytd|w)Nr)Key not found in the first mapping: {0!r})rrYrrrrrrP4s  zChainMap.__delitem__cCs(z|jdWStytdw)zPRemove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.rz#No keys found in the first mapping.)rrZrYrmrrrrZ:s  zChainMap.popitemcGs8z |jdj|g|RWStytd|w)zWRemove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].rr)rrLrYr)r!r"rBrrrrLAs  z ChainMap.popcCs|jddS)z'Clear maps[0], leaving maps[1:] intact.rN)rrWrmrrrrWHszChainMap.clearr)r*r(r5r)rErrrrrTrr __nonzero__r0rnrrzrp__copy__rpropertyrrKrPrZrLrWrrrrrs2       r)_GLOBAL_DEFAULT_TIMEOUTc Cs|\}}d}t||dtD]G}|\}}} } } d} z t||| } |tur(| ||r/| || | | WStyT} z| }| durJ| WYd} ~ q d} ~ ww|dur[|td)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!rrBrrrrErzcmp_to_key..K.__init__cs|j|jdkSrrrmycmprr__lt__rzcmp_to_key..K.__lt__cs|j|jdkSrrrrrr__gt__rzcmp_to_key..K.__gt__cs|j|jdkSrrrrrrr|rzcmp_to_key..K.__eq__cs|j|jdkSrrrrrr__le__rzcmp_to_key..K.__le__cs|j|jdkSrrrrrr__ge__rzcmp_to_key..K.__ge__cs|j|jdkSrrrrrrrrzcmp_to_key..K.__ne__cSr)Nzhash not implemented)r:rmrrr__hash__rzcmp_to_key..K.__hash__N) r*r(r5r6rErrr|rrrrrrrrK}s       r )r)rr rrr cmp_to_key{sr )r])r7r)r)r )r)r)r)r)r r )r0)r)r)rr8)Ir) __future__rrmathrroperatorrrrrr^heapqr_weakrefrr? itertoolsrrrrr rr r r r future.utilsrrrrr collectionsrrcollections.abcr_threadr ImportError _dummy_threadthread dummy_threadr0rr1rXr7rrrrrrrrr  _OrderedDict_Counter _check_output_count_ceil__count_elements_recursive_repr _ChainMap_create_connection _cmp_to_key version_info functoolsreprlibrrrrs       V  |  l )