Ñò „&Ic@sNdZddkZyddklZWn)ej odefd„ƒYZnXdefd„ƒYZdefd „ƒYZd efd „ƒYZ d efd „ƒYZ defd„ƒYZ d„Z d„Z d„Zd„Zeed„Zd„Zd„Zd„Zdd„Zd„ZedjoddkZeiƒndS(s¿Container objects and list/dict helpers. I would have called this "collections" except that Python 2 can't import a top-level module that's the same name as a module in the current package. iÿÿÿÿN(t defaultdictRcBsYeZdZd d„Zd„Zd„Zd„Zd„Zd„Z d„Z d„Z RS( s¹Backport of Python 2.5's ``defaultdict``. From the Python Cookbook. Written by Jason Kirtland. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/523034 cOsN|dj o!t|dƒ otdƒ‚nti|||Ž||_dS(Nt__call__sfirst argument must be callable(tNonethasattrt TypeErrortdictt__init__tdefault_factory(tselfRtatkw((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyRs  cCs8yti||ƒSWntj o|i|ƒSXdS(N(Rt __getitem__tKeyErrort __missing__(Rtkey((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyR scCs8|idjot|ƒ‚n|iƒ||<}|S(N(RRR (RRtvalue((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyR scCsH|idjo tƒ}n |if}t|ƒ|dd|iƒfS(N(RRttuplettypetitems(Rtargs((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyt __reduce__#s  cCs |iƒS(N(t__copy__(R((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pytcopy)scCst|ƒ|i|ƒS(N(RR(R((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyR+scCs1ddk}t|ƒ|i|i|iƒƒƒS(Niÿÿÿÿ(RRRtdeepcopyR(RtmemoR((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyt __deepcopy__-s cCsd|iti|ƒfS(Nsdefaultdict(%s, %s)(RRt__repr__(R((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyR1s N( t__name__t __module__t__doc__RRR R RRRRR(((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyR s       tNotGivencBseZdZRS(s"A default value for function args. Use this when you need to distinguish between ``None`` and no value. Example:: >>> def foo(arg=NotGiven): ... print arg is NotGiven ... >>> foo() True >>> foo(None) False (RRR(((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyR5st DumbObjectcBseZdZd„ZRS(sA container for arbitrary attributes. Usage:: >>> do = DumbObject(a=1, b=2) >>> do.b 2 Alternatives to this class include ``collections.namedtuple`` in Python 2.6, and ``formencode.declarative.Declarative`` in Ian Bicking's FormEncode package. Both alternatives offer more featues, but ``DumbObject`` shines in its simplicity and lack of dependencies. cKs|ii|ƒdS(N(t__dict__tupdate(RR ((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyRWs(RRRR(((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyRHstCountercBsJeZdZd„Zd„Zdd„Zd„Zd„Ze eƒZRS(sBI count the number of occurrences of each value registered with me. Usage: >>> counter = Counter() >>> counter("foo") >>> counter("bar") >>> counter("foo") >>> sorted(counter.result.items()) [('bar', 1), ('foo', 2)] >> counter.result {'foo': 2, 'bar': 1} To see the most frequently-occurring items in order: >>> counter.get_popular(1) [(2, 'foo')] >>> counter.get_popular() [(2, 'foo'), (1, 'bar')] Or if you prefer the list in item order: >>> counter.get_sorted_items() [('bar', 1), ('foo', 2)] cCsttƒ|_d|_dS(Ni(Rtinttresultttotal(R((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyRvscCs&|i|cd7<|id7_dS(s"Register an item with the counter.iN(R$R%(Rtitem((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyRzscCscg}|iiƒD]}||d|dfq~}|idd„ƒ|o || S|SdS(sÃReturn the results as as a list of (count, item) pairs, with the most frequently occurring items first. If ``max_items`` is provided, return no more than that many items. iiRcSsti|d|dfS(ii(tsystmaxint(tx((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyt…sN(R$t iteritemstsort(Rt max_itemst_[1]R)tdata((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyt get_populars 8 cCs|iiƒ}|iƒ|S(sKReturn the result as a list of (item, count) pairs sorted by item. (R$RR,(RR/((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pytget_sorted_items‹s cCs(|ƒ}x|D]}||ƒqW|S(sBuild a Counter from an iterable in one step. This is the same as adding each item individually. >>> counter = Counter.correlate(["A", "B", "A"]) >>> counter.result["A"] 2 >>> counter.result["B"] 1 ((tclass_titerabletcountertelm((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyt correlate“s N( RRRRRRR0R1R6t classmethod(((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyR"[s    t AccumulatorcBs5eZdZd„Zd„Zd„ZeeƒZRS(s>Accumulate a dict of all values for each key. Usage: >>> bowling_scores = Accumulator() >>> bowling_scores("Fred", 0) >>> bowling_scores("Barney", 10) >>> bowling_scores("Fred", 1) >>> bowling_scores("Barney", 9) >>> sorted(bowling_scores.result.items()) [('Barney', [10, 9]), ('Fred', [0, 1])] >> bowling_scores.result {'Fred': [0, 1], 'Barney': [10, 9]} The values are stored in the order they're registered. Alternatives to this class include ``paste.util. multidict.MultiDict`` in Ian Bicking's Paste package. cCsttƒ|_dS(N(RtlistR$(R((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyRºscCs|i|i|ƒdS(N(R$tappend(RRR((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyR½scCs7|ƒ}x'|D]}||ƒ}|||ƒqW|S(såCorrelate several items into an Accumulator in one step. ``key`` is a function to calculate the key for each item, akin to ``list.sort(key=)``. This is the same as adding each item individually. ((R2R3Rt accumulatortvtk((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyR6Ás   (RRRRRR6R7(((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyR8¥s    tUniqueAccumulatorcBs eZdZd„Zd„ZRS(seAccumulate a dict of unique values for each key. The values are stored in an unordered set. cCsttƒ|_dS(N(RtsetR$(R((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyRÖscCs|i|i|ƒdS(N(R$tadd(RRR((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyRÙs(RRRRR(((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyR>Ðs cCsOtƒ}g}x9|D]1}||jo|i|ƒ|i|ƒqqW|S(sÊReturn a list of unique elements in the iterable, preserving the order. Usage: >>> unique([None, "spam", 2, "spam", "A", "spam", "spam", "eggs", "spam"]) [None, 'spam', 2, 'A', 'eggs'] (R?R:R@(tittseentretR5((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pytuniqueÝs   cCs)h}x|D]}||||> only_some_keys({"A": 1, "B": 2, "C": 3}, ["A", "C"]) >>> sorted(only_some_keys({"A": 1, "B": 2, "C": 3}, ["A", "C"]).items()) [('A', 1), ('C', 3)] ((tdictkeysRCR((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pytonly_some_keysìs cCsB|iƒ}x/|D]'}y ||=Wqtj oqXqW|S(s‚Return a copy of the dict without the specified keys. >>> except_keys({"A": 1, "B": 2, "C": 3}, ["A", "C"]) {'B': 2} (RR (RERFRCR((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyt except_keysús   cCsŠx/|D]'}||jotd|ƒ‚qqWh}h}x?|iƒD]1\}}||jo|||> extract_keys({"From": "F", "To": "T", "Received", R"}, ["To", "From"]) ({"From": "F", "To": "T"}, {"Recived": "R"}) >>> regular, extra = extract_keys({"From": "F", "To": "T", "Received": "R"}, ["To", "From"]) >>> sorted(regular.keys()) ['From', 'To'] >>> sorted(extra.keys()) ['Received'] s!key %r is not in original mapping(R R(RERFR=tr1tr2R<((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyt extract_keyss    ccs•t|ƒ}xO|D]G}||jo||i|ƒfVq|tj o||fVqqW|o,x)|iƒD]\}}||fVqrWndS(sLike dict.iteritems() but with a specified key order. ``dic`` is any mapping. ``key_order`` is a list of keys. Items will be yielded in this order. ``other_keys`` is a boolean. ``default`` is a value returned if the key is not in the dict. This yields the items listed in ``key_order``. If a key does not exist in the dict, yield the default value if specified, otherwise skip the missing key. Afterwards, if ``other_keys`` is true, yield the remaining items in an arbitrary order. Usage: >>> dic = {"To": "you", "From": "me", "Date": "2008/1/4", "Subject": "X"} >>> dic["received"] = "..." >>> order = ["From", "To", "Subject"] >>> list(ordered_items(dic, order, False)) [('From', 'me'), ('To', 'you'), ('Subject', 'X')] N(RtpopRR+(REt key_ordert other_keystdefaulttdRR((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyt ordered_items s    cCs6x/|D]'}y ||=Wqtj oqXqWdS(sÍDelete several keys from a dict, ignoring those that don't exist. This modifies the dict in place. >>> d ={"A": 1, "B": 2, "C": 3} >>> del_quiet(d, ["A", "C"]) >>> d {'B': 2} N(R (RERFR((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyt del_quiet>s  cCs{h}d}xh|D]`}y||}Wn5tj o)d}||f}t||ƒ‚nX|||<|d7}qW|S(sFCorrelate several dicts under one superdict. E.g., If you have several dicts each with a 'name' key, this can put them in a container dict keyed by name. >>> d1 = {"name": "Fred", "age": 41} >>> d2 = {"name": "Barney", "age": 31} >>> flintstones = correlate_dicts([d1, d2], "name") >>> sorted(flintstones.keys()) ['Barney', 'Fred'] >>> flintstones["Fred"]["age"] 41 If you're having trouble spelling this method correctly, remember: "relate" has one 'l'. The 'r' is doubled because it occurs after a prefix. Thus "correlate". is''dicts' element %d contains no key '%s'i(R (tdictsRRCtiRPtmy_keytmsgttup((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pytcorrelate_dictsNs  cCsŒh}d}xy|D]q}yt||ƒ}WnAtj o5d}t|ƒi||f}t||ƒ‚nX|||<|d7}qW|S(s¦Correlate several objects under one dict. E.g., If you have several objects each with a 'name' attribute, this can create a dict containing each object keyed by name. >>> class Flintstone(DumbObject): ... pass ... >>> fred = Flintstone(name="Fred", age=41) >>> barney = Flintstone(name="Barney", age=31) >>> flintstones = correlate_objects([fred, barney], "name") >>> sorted(flintstones.keys()) ['Barney', 'Fred'] >>> flintstones["Barney"].age 31 If you're having trouble spelling this method correctly, remember: "relate" has one 'l'. The 'r' is doubled because it occurs after a prefix. Thus "correlate". is7'%s' object at 'objects[%d]' contains no attribute '%s'i(tgetattrtAttributeErrorRR(tobjectstattrRCRTtobjRURVRW((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pytcorrelate_objectsos cCs‡|djotdƒ‚n|diƒ}|djo‡g}xytdt|ƒ|ƒD]_}||||!}t|ƒ}||jo"|g||} |i| ƒn|i|ƒqYW|S|djo©t|ƒ} t| |ƒ\} } | o| d7} ng} t| ƒD]}| |g|q~ }x=t|ƒD]/\}}t|| ƒ\}}|||| % for row in table: % for cell in row: ${cell} % endfor cell % endfor row In a horizontal table, each row is filled before going on to the next row. This is the same as dividing the list into chunks. .. code-block:: pycon >>> distribute([1, 2, 3, 4, 5, 6, 7, 8], 3, "H") [[1, 2, 3], [4, 5, 6], [7, 8, None]] In a vertical table, the first element of each sublist is filled before going on to the second element. This is useful for displaying an alphabetical list in columns, or when the entire column will be placed in a single with a
between each element. .. code-block:: pycon >>> food = ["apple", "banana", "carrot", "daikon", "egg", "fish", "gelato", "honey"] >>> table = distribute(food, 3, "V", "") >>> table [['apple', 'daikon', 'gelato'], ['banana', 'egg', 'honey'], ['carrot', 'fish', '']] >>> for row in table: ... for item in row: ... print "%-9s" % item, ... print "." # To show where the line ends. ... apple daikon gelato . banana egg honey . carrot fish . Alternatives to this function include a NumPy matrix of objects. isarg 'columns' must be >= 1itHtVs,arg ``direction`` must start with 'H' or 'V'N(t ValueErrortuppertrangetlentextendR:tdivmodt enumerate(tlistcolumnst directiontfilltdirttableRTtrowtrow_lentextraR%trowst remainderR.R)R5tcol((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyt distribute’s4E      . cCsi|pgSg}xPtt|dƒƒD]8}g}|D]}|||q:~}|i|ƒq)W|S(s¶Turn a list of lists sideways, making columns into rows and vice-versa. The result is undefined if the array is not rectangular; i.e., if ``len(array[n]) != len(array[0])``. You may get an ``IndexError`` or missing items. Picture the first example as: A B C => A D D E F B E C F The source array is row-major (``array[n]`` is a row, ``array[n][0]`` is the first element of the row), which is good for an HTML table which is also row-major (columns within rows). The result is column-major (``array[n]`` is a column, ``array[n][0]`` is the first row in the column), which is good for a group of
columns with
between rows. >>> transpose([["A", "B", "C"], ["D", "E", "F"]]) [['A', 'D'], ['B', 'E'], ['C', 'F']] >>> transpose([["A", "B"], ["C", "D"], ["E", "F"]]) [['A', 'C', 'E'], ['B', 'D', 'F']] >>> transpose([]) [] i(RcRdR:(tarrayRCtcR.RnRs((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyt transposeós%t__main__(RR't collectionsRt ImportErrorRtobjectRRR"R8R>RDRGRHRKtTrueRQRRRXR^RRtRwRtdoctestttestmod(((s9/usr/lib/python2.6/site-packages/webhelpers/containers.pyts. )J+      ! # a #