Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Imported Upstream version 1.7.6

  • Loading branch information...
commit 460514907e8f01adf49f9a4e50fa4c9c69b91a09 0 parents
@ieure ieure authored
Showing with 9,172 additions and 0 deletions.
  1. +345 −0 COPYING.GPL
  2. +80 −0 COPYING.TGPPL.html
  3. +26 −0 CREDITS
  4. +26 −0 PKG-INFO
  5. +43 −0 README.txt
  6. +25 −0 copyright
  7. +225 −0 ez_setup.py
  8. +26 −0 pyutil.egg-info/PKG-INFO
  9. +88 −0 pyutil.egg-info/SOURCES.txt
  10. +1 −0  pyutil.egg-info/dependency_links.txt
  11. +8 −0 pyutil.egg-info/entry_points.txt
  12. +1 −0  pyutil.egg-info/not-zip-safe
  13. +3 −0  pyutil.egg-info/requires.txt
  14. +2 −0  pyutil.egg-info/stdeb.cfg
  15. +1 −0  pyutil.egg-info/top_level.txt
  16. +198 −0 pyutil/PickleSaver.py
  17. +22 −0 pyutil/__init__.py
  18. +16 −0 pyutil/_version.py
  19. +60 −0 pyutil/assertutil.py
  20. +50 −0 pyutil/benchmarks/bench_json.py
  21. +54 −0 pyutil/benchmarks/bench_xor.py
  22. +193 −0 pyutil/benchutil.py
  23. +736 −0 pyutil/cache.py
  24. +597 −0 pyutil/dictutil.py
  25. +336 −0 pyutil/fileutil.py
  26. +28 −0 pyutil/find_exe.py
  27. +78 −0 pyutil/hashexpand.py
  28. +115 −0 pyutil/humanreadable.py
  29. +136 −0 pyutil/increasing_timer.py
  30. +288 −0 pyutil/iputil.py
  31. +456 −0 pyutil/jsonutil.py
  32. +59 −0 pyutil/lineutil.py
  33. +13 −0 pyutil/logutil.py
  34. +106 −0 pyutil/mathutil.py
  35. +579 −0 pyutil/memutil.py
  36. +52 −0 pyutil/nummedobj.py
  37. +98 −0 pyutil/observer.py
  38. +552 −0 pyutil/odict.py
  39. +100 −0 pyutil/platformutil.py
  40. +81 −0 pyutil/randutil.py
  41. +90 −0 pyutil/repeatable_random.py
  42. 0  pyutil/scripts/__init__.py
  43. +36 −0 pyutil/scripts/lines.py
  44. +65 −0 pyutil/scripts/memdump2dot.py
  45. +30 −0 pyutil/scripts/randcookie.py
  46. +50 −0 pyutil/scripts/randfile.py
  47. +30 −0 pyutil/scripts/tailx.py
  48. +19 −0 pyutil/scripts/unsort.py
  49. +26 −0 pyutil/scripts/verinfo.py
  50. +50 −0 pyutil/strutil.py
  51. 0  pyutil/test/__init__.py
  52. 0  pyutil/test/json_tests/__init__.py
  53. +15 −0 pyutil/test/json_tests/test_decode.py
  54. +9 −0 pyutil/test/json_tests/test_default.py
  55. +13 −0 pyutil/test/json_tests/test_dump.py
  56. +35 −0 pyutil/test/json_tests/test_encode_basestring_ascii.py
  57. +76 −0 pyutil/test/json_tests/test_fail.py
  58. +9 −0 pyutil/test/json_tests/test_float.py
  59. +41 −0 pyutil/test/json_tests/test_indent.py
  60. +71 −0 pyutil/test/json_tests/test_pass1.py
  61. +14 −0 pyutil/test/json_tests/test_pass2.py
  62. +20 −0 pyutil/test/json_tests/test_pass3.py
  63. +67 −0 pyutil/test/json_tests/test_recursion.py
  64. +42 −0 pyutil/test/json_tests/test_separators.py
  65. +15 −0 pyutil/test/json_tests/test_speedups.py
  66. +55 −0 pyutil/test/json_tests/test_unicode.py
  67. +26 −0 pyutil/test/test_assertutil.py
  68. +454 −0 pyutil/test/test_cache.py
  69. +115 −0 pyutil/test/test_dictutil.py
  70. +33 −0 pyutil/test/test_fileutil.py
  71. +31 −0 pyutil/test/test_iputil.py
  72. +18 −0 pyutil/test/test_jsonutil.py
  73. +143 −0 pyutil/test/test_mathutil.py
  74. +444 −0 pyutil/test/test_odict.py
  75. +36 −0 pyutil/test/test_picklesaver.py
  76. +36 −0 pyutil/test/test_strutil.py
  77. +32 −0 pyutil/test/test_template
  78. +97 −0 pyutil/test/test_time_format.py
  79. +32 −0 pyutil/test/test_xor.py
  80. +77 −0 pyutil/test/test_zlibutil.py
  81. +116 −0 pyutil/testutil.py
  82. +72 −0 pyutil/time_format.py
  83. +21 −0 pyutil/twistedutil.py
  84. +146 −0 pyutil/version_class.py
  85. +39 −0 pyutil/weakutil.py
  86. +1 −0  pyutil/xor/__init__.py
  87. +49 −0 pyutil/xor/xor.py
  88. +256 −0 pyutil/zlibutil.py
  89. +5 −0 setup.cfg
  90. +112 −0 setup.py
345 COPYING.GPL
@@ -0,0 +1,345 @@
+This licence also comes with the added permission that you may link this
+program with the OpenSSL library and distribute executables, as long as you
+follow the requirements of this licence in regard to all of the software in
+the executable aside from OpenSSL.
+
+
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along
+ with this program; if not, write to the Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
80 COPYING.TGPPL.html
@@ -0,0 +1,80 @@
+<!DOCtype HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html lang="en">
+
+ <head>
+ <title>transitive grace period public licence, v1.0</title>
+
+ <link rev="made" class="mailto" href="mailto:zooko[at]zooko[dot]com">
+
+ <link rel="stylesheet" href="style.css" type="text/css">
+
+ <meta name="description" content="an open source licence for commercial software">
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+
+ <meta name="keywords" content="Zooko">
+ </head>
+
+ <body>
+<h1>Transitive Grace Period Public Licence ("TGPPL") v. 1.0</h1>
+
+<p>This Transitive Grace Period Public Licence (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work:</p>
+
+<p><b>Licensed under the Transitive Grace Period Public Licence version 1.0</b></p>
+
+<ol>
+ <li><b>Grant of Copyright License.</b> Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following:</p>
+
+ <ol type="a">
+ <li>to reproduce the Original Work in copies, either alone or as part of a collective work;</p>
+
+ <li>to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work;</p>
+
+ <li>to distribute or communicate copies of the Original Work and Derivative Works to the public, with the proviso that copies of Original Work or Derivative Works that You distribute or communicate shall be licensed under this Transitive Grace Period Public Licence no later than 12 months after You distributed or communicated said copies;</p>
+
+ <li>to perform the Original Work publicly; and</p>
+
+ <li>to display the Original Work publicly.</p>
+ </ol>
+
+ <li><b>Grant of Patent License.</b> Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works.</p>
+
+ <li><b>Grant of Source Code License.</b> The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work.</p>
+
+ <li><b>Exclusions From License Grant.</b> Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license.</p>
+
+ <li><b>External Deployment.</b> The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c).</p>
+
+ <li><b>Attribution Rights.</b> You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work.</p>
+
+ <li><b>Warranty of Provenance and Disclaimer of Warranty.</b> Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer.</p>
+
+ <li><b>Limitation of Liability.</b> Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation.</p>
+
+ <li><b>Acceptance and Termination.</b> If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including 'fair use' or 'fair dealing'). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c).</p>
+
+ <li><b>Termination for Patent Action.</b> This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware.</p>
+
+ <li><b>Jurisdiction, Venue and Governing Law.</b> Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License.</p>
+
+ <li><b>Attorneys' Fees.</b> In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License.</p>
+
+ <li><b>Miscellaneous.</b> If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable.</p>
+
+ <li><b>Definition of "You" in This License.</b> "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.</p>
+
+ <li><b>Right to Use.</b> You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You.</p>
+
+ <li><b>Modification of This License.</b> This License is Copyright © 2007 Zooko Wilcox-O'Hearn. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Transitive Grace Period Public Licence" or "TGPPL" and you may not use those names in the name of your Modified License; and (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under <insert your license name here>" or with a notice of your own that is not confusingly similar to the notice in this License.</p>
+</ol>
+
+ </td>
+ </td>
+ </tr>
+
+ </table>
+ </td>
+ </tr>
+ </table>
+
+ </body>
+</html>
26 CREDITS
@@ -0,0 +1,26 @@
+ This is at least a partial credits-file of people that have
+contributed to the pyutil project. It is formatted to allow easy
+grepping and beautification by scripts. The fields are: name (N), email (E),
+web-address (W), PGP key ID and fingerprint (P), description (D), and
+snail-mail address (S).
+
+Thanks,
+
+Zooko
+----------
+
+N: The Evil Geniuses For A Better Tomorrow
+D: turned some crazy ideas into a crazy reality
+
+N: Lars the Talking Alien
+E: lars@mad-scientist.com
+D: came to us in dreams and made us become Enlightened Ones
+S: 644 Church St., Mountain View, 94041 CA, USA, 3 Sol, Milky Way, above the fireplace
+
+N: Faried Nawaz
+E: fn@hungry.org
+D: the c_xor module
+
+N: Lele Gaifax
+E: lele@nautilus.homeip.net
+D: patch to fileutil -- close tempfile fd
26 PKG-INFO
@@ -0,0 +1,26 @@
+Metadata-Version: 1.0
+Name: pyutil
+Version: 1.7.6
+Summary: a collection of mature utilities for Python programmers
+Home-page: http://tahoe-lafs.org/trac/pyutil
+Author: Zooko O'Whielacronx
+Author-email: zooko@zooko.com
+License: GNU GPL
+Description: These are a few data structures, classes and functions which we've needed over many years of Python programming and which seem to be of general use to other Python programmers. Many of the modules that have existed in pyutil over the years have subsequently been obsoleted by new features added to the Python language or its standard library, thus showing that we're not alone in wanting tools like these.
+Platform: UNKNOWN
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: License :: OSI Approved :: GNU General Public License (GPL)
+Classifier: License :: DFSG approved
+Classifier: Intended Audience :: Developers
+Classifier: Operating System :: Microsoft :: Windows
+Classifier: Operating System :: Unix
+Classifier: Operating System :: MacOS :: MacOS X
+Classifier: Operating System :: OS Independent
+Classifier: Natural Language :: English
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 2
+Classifier: Programming Language :: Python :: 2.4
+Classifier: Programming Language :: Python :: 2.5
+Classifier: Programming Language :: Python :: 2.6
+Classifier: Topic :: Utilities
+Classifier: Topic :: Software Development :: Libraries
43 README.txt
@@ -0,0 +1,43 @@
+pyutil -- a library of useful Python functions and classes
+
+Many of these utilities (or their ancestors) were developed for the Mojo Nation
+open source project, its open source successor project Mnet, its proprietary
+successor project Allmydata.com "Mountain View", or its open source successor
+project Allmydata.org "Tahoe". (In the case where the code was developed for a
+for-profit company, the copyright holder donated the pyutil code to the public
+under these open source licences.)
+
+trac:
+
+http://allmydata.org/trac/pyutil
+
+darcs repository:
+
+http://allmydata.org/source/pyutil/trunk
+
+To run tests, do
+
+python ./setup.py test
+
+Some modules have self-benchmarks provided. For example, to benchmark
+the cache module, do
+
+python -OOu -c 'from pyutil.test import test_cache; test_cache.quick_bench()'
+
+or for more complete and time-consuming results:
+
+python -OOu -c 'from pyutil.test import test_cache; test_cache.slow_bench()'
+
+(The "-O" is important when benchmarking, since cache has extensive
+self-tests that are optimized out when -O is included.)
+
+
+LICENCE
+
+You may use this package under the GNU General Public License, version 2 or, at
+your option, any later version. You may use this package under the Transitive
+Grace Period Public Licence, version 1.0, or at your option, any later version.
+(You may choose to use this package under the terms of either licence, at your
+option.) See the file COPYING.GPL for the terms of the GNU General Public
+License, version 2. See the file COPYING.TGPPL.html for the terms of the
+Transitive Grace Period Public Licence, version 1.0.
25 copyright
@@ -0,0 +1,25 @@
+This package was debianized by Zooko O'Whielacronx zooko@zooko.com on
+Tue, 30 June 2009 12:11:00 +0000.
+
+It was originally downloaded from http://allmydata.org/trac/pyutil
+
+Upstream Author: Zooko O'Whielacronx <zooko@zooko.com>
+
+Copyright:
+
+You may use this package under the GNU General Public License, version 2 or, at
+your option, any later version. You may use this package under the Transitive
+Grace Period Public Licence, version 1.0 or, at your option, any later version.
+(You may choose to use this package under the terms of either licence, at your
+option.) See the file COPYING.GPL for the terms of the GNU General Public
+License, version 2. See the file COPYING.TGPPL.html for the terms of the
+Transitive Grace Period Public Licence, version 1.0. In addition, Allmydata,
+Inc. offers other licensing terms. If you would like to inquire about a
+commercial relationship with Allmydata, Inc., please contact
+partnerships@allmydata.com and visit http://allmydata.com .
+
+The Debian packaging is © 2009 Zooko O'Whielacronx <zooko@zooko.com> - it is
+licensed under the same terms as the pyutil source code itself.
+
+On Debian systems, the complete text of the GNU General Public License
+can be found in `/usr/share/common-licenses/GPL'.
225 ez_setup.py
@@ -0,0 +1,225 @@
+#!/usr/bin/env python
+"""Bootstrap setuptools installation
+
+If you want to use setuptools in your package's setup.py, just include this
+file in the same directory with it, and add this to the top of your setup.py::
+
+ from ez_setup import use_setuptools
+ use_setuptools()
+
+If you want to require a specific version of setuptools, set a download
+mirror, or use an alternate download directory, you can do so by supplying
+the appropriate options to ``use_setuptools()``.
+
+This file can also be run as a script to install or upgrade setuptools.
+"""
+import os, sys
+DEFAULT_VERSION = "0.6c7"
+DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3]
+
+md5_data = {
+ 'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2',
+ 'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e',
+ 'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372',
+}
+
+def _validate_md5(egg_name, data):
+ if egg_name in md5_data:
+ from md5 import md5
+ digest = md5(data).hexdigest()
+ if digest != md5_data[egg_name]:
+ print >>sys.stderr, (
+ "md5 validation of %s failed! (Possible download problem?)"
+ % egg_name
+ )
+ sys.exit(2)
+ return data
+
+# The following code to parse versions is copied from pkg_resources.py so that
+# we can parse versions without importing that module.
+import re
+component_re = re.compile(r'(\d+ | [a-z]+ | \.| -)', re.VERBOSE)
+replace = {'pre':'c', 'preview':'c','-':'final-','rc':'c','dev':'@'}.get
+
+def _parse_version_parts(s):
+ for part in component_re.split(s):
+ part = replace(part,part)
+ if not part or part=='.':
+ continue
+ if part[:1] in '0123456789':
+ yield part.zfill(8) # pad for numeric comparison
+ else:
+ yield '*'+part
+
+ yield '*final' # ensure that alpha/beta/candidate are before final
+
+def parse_version(s):
+ parts = []
+ for part in _parse_version_parts(s.lower()):
+ if part.startswith('*'):
+ if part<'*final': # remove '-' before a prerelease tag
+ while parts and parts[-1]=='*final-': parts.pop()
+ # remove trailing zeros from each series of numeric parts
+ while parts and parts[-1]=='00000000':
+ parts.pop()
+ parts.append(part)
+ return tuple(parts)
+
+def setuptools_is_new_enough(required_version):
+ """Return True if setuptools is already installed and has a version
+ number >= required_version."""
+ if 'pkg_resources' in sys.modules:
+ import pkg_resources
+ try:
+ pkg_resources.require('setuptools >= %s' % (required_version,))
+ except pkg_resources.VersionConflict:
+ # An insufficiently new version is installed.
+ return False
+ else:
+ return True
+ else:
+ try:
+ import pkg_resources
+ except ImportError:
+ # Okay it is not installed.
+ return False
+ else:
+ try:
+ pkg_resources.require('setuptools >= %s' % (required_version,))
+ except pkg_resources.VersionConflict:
+ # An insufficiently new version is installed.
+ pkg_resources.__dict__.clear() # "If you want to be absolutely sure... before deleting it." --said PJE on IRC
+ del sys.modules['pkg_resources']
+ return False
+ else:
+ pkg_resources.__dict__.clear() # "If you want to be absolutely sure... before deleting it." --said PJE on IRC
+ del sys.modules['pkg_resources']
+ return True
+
+def use_setuptools(
+ version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
+ min_version=None, download_delay=15
+):
+ """Automatically find/download setuptools and make it available on sys.path
+
+ `version` should be a valid setuptools version number that is available
+ as an egg for download under the `download_base` URL (which should end with
+ a '/'). `to_dir` is the directory where setuptools will be downloaded, if
+ it is not already available. If `download_delay` is specified, it should
+ be the number of seconds that will be paused before initiating a download,
+ should one be required. If an older version of setuptools is installed,
+ this routine will print a message to ``sys.stderr`` and raise SystemExit in
+ an attempt to abort the calling script.
+ """
+ if min_version is None:
+ min_version = version
+ if not setuptools_is_new_enough(min_version):
+ egg = download_setuptools(version, min_version, download_base, to_dir, download_delay)
+ sys.path.insert(0, egg)
+ import setuptools; setuptools.bootstrap_install_from = egg
+
+def download_setuptools(
+ version=DEFAULT_VERSION, min_version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
+ delay = 15
+):
+ """Download setuptools from a specified location and return its filename
+
+ `version` should be a valid setuptools version number that is available
+ as an egg for download under the `download_base` URL (which should end
+ with a '/'). `to_dir` is the directory where the egg will be downloaded.
+ `delay` is the number of seconds to pause before an actual download attempt.
+ """
+ import urllib2, shutil
+ egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])
+ url = download_base + egg_name
+ saveto = os.path.join(to_dir, egg_name)
+ src = dst = None
+ if not os.path.exists(saveto): # Avoid repeated downloads
+ try:
+ from distutils import log
+ if delay:
+ log.warn("""
+---------------------------------------------------------------------------
+This script requires setuptools version >= %s to run (even to display
+help). I will attempt to download setuptools for you (from
+%s), but
+you may need to enable firewall access for this script first.
+I will start the download in %d seconds.
+
+(Note: if this machine does not have network access, please obtain the file
+
+ %s
+
+and place it in this directory before rerunning this script.)
+---------------------------------------------------------------------------""",
+ min_version, download_base, delay, url
+ ); from time import sleep; sleep(delay)
+ log.warn("Downloading %s", url)
+ src = urllib2.urlopen(url)
+ # Read/write all in one block, so we don't create a corrupt file
+ # if the download is interrupted.
+ data = _validate_md5(egg_name, src.read())
+ dst = open(saveto,"wb"); dst.write(data)
+ finally:
+ if src: src.close()
+ if dst: dst.close()
+ return os.path.realpath(saveto)
+
+def main(argv, version=DEFAULT_VERSION):
+ """Install or upgrade setuptools and EasyInstall"""
+
+ if setuptools_is_new_enough(version):
+ if argv:
+ from setuptools.command.easy_install import main
+ main(argv)
+ else:
+ print "Setuptools version",version,"or greater has been installed."
+ print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'
+ else:
+ egg = None
+ try:
+ egg = download_setuptools(version, min_version=version, delay=0)
+ sys.path.insert(0,egg)
+ from setuptools.command.easy_install import main
+ return main(list(argv)+[egg]) # we're done here
+ finally:
+ if egg and os.path.exists(egg):
+ os.unlink(egg)
+
+def update_md5(filenames):
+ """Update our built-in md5 registry"""
+
+ import re
+ from md5 import md5
+
+ for name in filenames:
+ base = os.path.basename(name)
+ f = open(name,'rb')
+ md5_data[base] = md5(f.read()).hexdigest()
+ f.close()
+
+ data = [" %r: %r,\n" % it for it in md5_data.items()]
+ data.sort()
+ repl = "".join(data)
+
+ import inspect
+ srcfile = inspect.getsourcefile(sys.modules[__name__])
+ f = open(srcfile, 'rb'); src = f.read(); f.close()
+
+ match = re.search("\nmd5_data = {\n([^}]+)}", src)
+ if not match:
+ print >>sys.stderr, "Internal error!"
+ sys.exit(2)
+
+ src = src[:match.start(1)] + repl + src[match.end(1):]
+ f = open(srcfile,'w')
+ f.write(src)
+ f.close()
+
+
+if __name__=='__main__':
+ if '--md5update' in sys.argv:
+ sys.argv.remove('--md5update')
+ update_md5(sys.argv[1:])
+ else:
+ main(sys.argv[1:])
26 pyutil.egg-info/PKG-INFO
@@ -0,0 +1,26 @@
+Metadata-Version: 1.0
+Name: pyutil
+Version: 1.7.6
+Summary: a collection of mature utilities for Python programmers
+Home-page: http://tahoe-lafs.org/trac/pyutil
+Author: Zooko O'Whielacronx
+Author-email: zooko@zooko.com
+License: GNU GPL
+Description: These are a few data structures, classes and functions which we've needed over many years of Python programming and which seem to be of general use to other Python programmers. Many of the modules that have existed in pyutil over the years have subsequently been obsoleted by new features added to the Python language or its standard library, thus showing that we're not alone in wanting tools like these.
+Platform: UNKNOWN
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: License :: OSI Approved :: GNU General Public License (GPL)
+Classifier: License :: DFSG approved
+Classifier: Intended Audience :: Developers
+Classifier: Operating System :: Microsoft :: Windows
+Classifier: Operating System :: Unix
+Classifier: Operating System :: MacOS :: MacOS X
+Classifier: Operating System :: OS Independent
+Classifier: Natural Language :: English
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 2
+Classifier: Programming Language :: Python :: 2.4
+Classifier: Programming Language :: Python :: 2.5
+Classifier: Programming Language :: Python :: 2.6
+Classifier: Topic :: Utilities
+Classifier: Topic :: Software Development :: Libraries
88 pyutil.egg-info/SOURCES.txt
@@ -0,0 +1,88 @@
+COPYING.GPL
+COPYING.TGPPL.html
+CREDITS
+README.txt
+copyright
+ez_setup.py
+setup.py
+pyutil/PickleSaver.py
+pyutil/__init__.py
+pyutil/_version.py
+pyutil/assertutil.py
+pyutil/benchutil.py
+pyutil/cache.py
+pyutil/dictutil.py
+pyutil/fileutil.py
+pyutil/find_exe.py
+pyutil/hashexpand.py
+pyutil/humanreadable.py
+pyutil/increasing_timer.py
+pyutil/iputil.py
+pyutil/jsonutil.py
+pyutil/lineutil.py
+pyutil/logutil.py
+pyutil/mathutil.py
+pyutil/memutil.py
+pyutil/nummedobj.py
+pyutil/observer.py
+pyutil/odict.py
+pyutil/platformutil.py
+pyutil/randutil.py
+pyutil/repeatable_random.py
+pyutil/strutil.py
+pyutil/testutil.py
+pyutil/time_format.py
+pyutil/twistedutil.py
+pyutil/version_class.py
+pyutil/weakutil.py
+pyutil/zlibutil.py
+pyutil.egg-info/PKG-INFO
+pyutil.egg-info/SOURCES.txt
+pyutil.egg-info/dependency_links.txt
+pyutil.egg-info/entry_points.txt
+pyutil.egg-info/not-zip-safe
+pyutil.egg-info/requires.txt
+pyutil.egg-info/stdeb.cfg
+pyutil.egg-info/top_level.txt
+pyutil/benchmarks/bench_json.py
+pyutil/benchmarks/bench_xor.py
+pyutil/scripts/__init__.py
+pyutil/scripts/lines.py
+pyutil/scripts/memdump2dot.py
+pyutil/scripts/randcookie.py
+pyutil/scripts/randfile.py
+pyutil/scripts/tailx.py
+pyutil/scripts/unsort.py
+pyutil/scripts/verinfo.py
+pyutil/test/__init__.py
+pyutil/test/test_assertutil.py
+pyutil/test/test_cache.py
+pyutil/test/test_dictutil.py
+pyutil/test/test_fileutil.py
+pyutil/test/test_iputil.py
+pyutil/test/test_jsonutil.py
+pyutil/test/test_mathutil.py
+pyutil/test/test_odict.py
+pyutil/test/test_picklesaver.py
+pyutil/test/test_strutil.py
+pyutil/test/test_template
+pyutil/test/test_time_format.py
+pyutil/test/test_xor.py
+pyutil/test/test_zlibutil.py
+pyutil/test/json_tests/__init__.py
+pyutil/test/json_tests/test_decode.py
+pyutil/test/json_tests/test_default.py
+pyutil/test/json_tests/test_dump.py
+pyutil/test/json_tests/test_encode_basestring_ascii.py
+pyutil/test/json_tests/test_fail.py
+pyutil/test/json_tests/test_float.py
+pyutil/test/json_tests/test_indent.py
+pyutil/test/json_tests/test_pass1.py
+pyutil/test/json_tests/test_pass2.py
+pyutil/test/json_tests/test_pass3.py
+pyutil/test/json_tests/test_recursion.py
+pyutil/test/json_tests/test_separators.py
+pyutil/test/json_tests/test_speedups.py
+pyutil/test/json_tests/test_unicode.py
+pyutil/xor/__init__.py
+pyutil/xor/xor.py
1  pyutil.egg-info/dependency_links.txt
@@ -0,0 +1 @@
+
8 pyutil.egg-info/entry_points.txt
@@ -0,0 +1,8 @@
+[console_scripts]
+randfile = pyutil.scripts.randfile:main
+lines = pyutil.scripts.lines:main
+unsort = pyutil.scripts.unsort:main
+verinfo = pyutil.scripts.verinfo:main
+randcookie = pyutil.scripts.randcookie:main
+tailx = pyutil.scripts.tailx:main
+
1  pyutil.egg-info/not-zip-safe
@@ -0,0 +1 @@
+
3  pyutil.egg-info/requires.txt
@@ -0,0 +1,3 @@
+argparse >= 0.8
+zbase32 >= 1.0
+simplejson >= 2.1.0
2  pyutil.egg-info/stdeb.cfg
@@ -0,0 +1,2 @@
+[pyutil]
+Copyright-File: copyright
1  pyutil.egg-info/top_level.txt
@@ -0,0 +1 @@
+pyutil
198 pyutil/PickleSaver.py
@@ -0,0 +1,198 @@
+# Copyright (c) 2001 Autonomous Zone Industries
+# Copyright (c) 2002-2009 Zooko Wilcox-O'Hearn
+# This file is part of pyutil; see README.txt for licensing terms.
+
+"""
+An object that makes some of the attributes of your class persistent, pickling
+them and lazily writing them to a file.
+"""
+
+# from the Python Standard Library
+import os
+import cPickle as pickle
+
+# from the pyutil library
+import fileutil
+import nummedobj
+import twistedutil
+
+# from the Twisted library
+from twisted.python import log
+
+class PickleSaver(nummedobj.NummedObj):
+ """
+ This makes some of the attributes of your class persistent, saving
+ them in a pickle and saving them lazily.
+
+ The general idea: You are going to tell PickleSaver which of your
+ attributes ought to be persistently saved, and the name of a file to
+ save them in. Those attributes will get saved to disk, and when
+ your object is instantiated those attributes will get set to the
+ values loaded from the file.
+
+ Usage: inherit from PickleSaver and call PickleSaver.__init__() in your
+ constructor. You will pass arguments to PickleSaver.__init__()
+ telling it which attributes to save, which file to save them in, and
+ what values they should have if there is no value stored for them in
+ the file.
+
+ Note: do *not* assign values to your persistent attributes in your
+ constructor, because you might thus overwrite their persistent
+ values.
+
+ Then whenever you change one of the persistent attributes, call
+ self.lazy_save() (it won't *really* save -- it'll just schedule a
+ save for DELAY minutes later.) If you update an attribute and
+ forget to call self.lazy_save() then the change will not be saved,
+ unless you later call self.lazy_save() before you shut down.
+
+ Data could be lost if the Python interpreter were to die
+ unexpectedly (for example, due to a segfault in a compiled machine
+ code module or due to the Python process being killed without
+ warning via SIGKILL) before the delay passes. However if the Python
+ interpreter shuts down cleanly (i.e., if it garbage collects and
+ invokes the __del__ methods of the collected objects), then the data
+ will be saved at that time (unless your class has the "not-collectable"
+ problem: http://python.org/doc/current/lib/module-gc.html -- search
+ in text for "uncollectable").
+
+ Note: you can pass DELAY=0 to make PickleSaver a not-so-lazy saver.
+ The advantage of laziness is that you don't touch the disk as
+ often -- touching disk is a performance cost.
+
+ To cleanly shutdown, invoke shutdown(). Further operations after that
+ will result in exceptions.
+ """
+ class ExtRes:
+ """
+ This is for holding things (external resources) that PickleSaver needs
+ to finalize after PickleSaver is killed. (post-mortem finalization)
+
+ In particular, this holds the names and values of all attributes
+ that have been changed, so that after the PickleSaver is
+ garbage-collected those values will be saved to the persistent file.
+ """
+ def __init__(self, fname, objname):
+ self.fname = fname
+ self.objname = objname
+ self.dirty = False # True iff the attrs have been changed and need to be saved to disk; When you change this flag from False to True, you schedule a save task for 10 minutes later. When the save task goes off it changes the flag from True to False.
+ self.savertask = None
+ self.valstr = None # the pickled (serialized, string) contents of the attributes that should be saved
+
+ def _save_to_disk(self):
+ if self.valstr is not None:
+ log.msg("%s._save_to_disk(): fname: %s" % (self.objname, self.fname,))
+ of = open(self.fname + ".tmp", "wb")
+ of.write(self.valstr)
+ of.flush()
+ of.close()
+ of = None
+ fileutil.remove_if_possible(self.fname)
+ fileutil.rename(self.fname + ".tmp", self.fname)
+ log.msg("%s._save_to_disk(): now, having finished write(), os.path.isfile(%s): %s" % (self, self.fname, os.path.isfile(self.fname),))
+ self.valstr = None
+ self.dirty = False
+ try:
+ self.savertask.callId.cancel()
+ except:
+ pass
+ self.savertask = None
+
+ def shutdown(self):
+ if self.dirty:
+ self._save_to_disk()
+ if self.savertask:
+ try:
+ self.savertask.callId.cancel()
+ except:
+ pass
+ self.savertask = None
+
+ def __del__(self):
+ self.shutdown()
+
+ def __init__(self, fname, attrs, DELAY=60*60, savecb=None):
+ """
+ @param attrs: a dict whose keys are the names of all the attributes to be persistently stored and whose values are the initial default value that the attribute gets set to the first time it is ever used; After this first initialization, the value will be persistent so the initial default value will never be used again.
+ @param savecb: if not None, then it is a callable that will be called after each save completes (useful for unit tests) (savecb doesn't get called after a shutdown-save, only after a scheduled save)
+ """
+ nummedobj.NummedObj.__init__(self)
+ self._DELAY = DELAY
+
+ self._attrnames = attrs.keys()
+ self._extres = PickleSaver.ExtRes(fname=fname, objname=self.__repr__())
+ self._savecb = savecb
+
+ for attrname, defaultval in attrs.items():
+ setattr(self, attrname, defaultval)
+
+ try:
+ attrdict = pickle.loads(open(self._extres.fname, "rb").read())
+ for attrname, attrval in attrdict.items():
+ if not hasattr(self, attrname):
+ log.msg("WARNING: %s has no attribute named %s on load from disk, value: %s." % (self, attrname, attrval,))
+ setattr(self, attrname, attrval)
+ except (pickle.UnpicklingError, IOError, EOFError,), le:
+ try:
+ attrdict = pickle.loads(open(self._extres.fname + ".tmp", "rb").read())
+ for attrname, attrval in attrdict.items():
+ if not hasattr(self, attrname):
+ log.msg("WARNING: %s has no attribute named %s on load from disk, value: %s." % (self, attrname, attrval,))
+ setattr(self, attrname, attrval)
+ except (pickle.UnpicklingError, IOError, EOFError,), le2:
+ log.msg("Got exception attempting to load attrs. (This is normal if this is the first time you've used this persistent %s object.) fname: %s, le: %s, le2: %s" % (self.__class__, self._extres.fname, le, le2,))
+
+ self.lazy_save()
+
+ def _store_attrs_in_extres(self):
+ d = {}
+ for attrname in self._attrnames:
+ d[attrname] = getattr(self, attrname)
+ # log.msg("%s._store_attrs_in_extres: attrname: %s, val: %s" % (self, attrname, getattr(self, attrname),))
+
+ # pickle the attrs now, to ensure that there are no reference cycles
+ self._extres.valstr = pickle.dumps(d, True)
+
+ # log.msg("%s._store_attrs_in_extres: valstr: %s" % (self, self._extres.valstr,))
+
+ self._extres.dirty = True
+
+ def _save_to_disk(self):
+ log.msg("%s._save_to_disk()" % (self,))
+ self._extres._save_to_disk()
+ if self._savecb:
+ self._savecb()
+
+ def _lazy_save(self, delay=None):
+ """ @deprecated: use lazy_save() instead """
+ return self.lazy_save(delay)
+
+ def lazy_save(self, delay=None):
+ """
+ @param delay: how long from now before the data gets saved to disk, or `None' in order to use the default value provided in the constructor
+ """
+ if delay is None:
+ delay=self._DELAY
+
+ # copy the values into extres so that if `self' gets garbage-collected the values will be written to disk during post-mortem finalization. (This also marks it as dirty.)
+ self._store_attrs_in_extres()
+
+ newsavetask = twistedutil.callLater_weakly(delay, self._save_to_disk)
+ if self._extres.savertask:
+ if self._extres.savertask.callId.getTime() < newsavetask.callId.getTime():
+ try:
+ newsavetask.callId.cancel()
+ except:
+ pass
+ else:
+ try:
+ self._extres.savertask.callId.cancel()
+ except:
+ pass
+ self._extres.savertask = newsavetask
+ else:
+ self._extres.savertask = newsavetask
+
+ def shutdown(self):
+ self.extres.shutdown()
+ self.extres = None
22 pyutil/__init__.py
@@ -0,0 +1,22 @@
+"""
+Library of useful Python functions and classes.
+
+Projects that have contributed substantial portions to pyutil:
+U{Mojo Nation<http://mojonation.net/>}
+U{Mnet<http://sf.net/projects/mnet>}
+U{Allmydata<http://allmydata.com/>}
+U{Tahoe-LAFS<http://tahoe-lafs.org/>}
+
+mailto:zooko@zooko.com
+
+pyutil web site: U{http://tahoe-lafs.org/trac/pyutil}
+"""
+
+__version__ = "unknown"
+try:
+ from _version import __version__
+except ImportError:
+ # We're running in a tree that hasn't run "./setup.py darcsver", and didn't
+ # come with a _version.py, so we don't know what our version is. This should
+ # not happen very often.
+ pass
16 pyutil/_version.py
@@ -0,0 +1,16 @@
+
+# This is the version of this tree, as created by setup.py darcsver from the Darcs patch
+# information: the main version number is taken from the most recent release
+# tag. If some patches have been added since the last release, this will have a
+# -NN "build number" suffix, or else a -rNN "revision number" suffix. Please see
+# pyutil.version_class for a description of what the different fields mean.
+
+verstr = "1.7.6"
+try:
+ from pyutil.version_class import Version as pyutil_Version
+ __version__ = pyutil_Version(verstr)
+except (ImportError, ValueError):
+ # Maybe there is no pyutil installed, or this may be an older version of
+ # pyutil.version_class which does not support SVN-alike revision numbers.
+ from distutils.version import LooseVersion as distutils_Version
+ __version__ = distutils_Version(verstr)
60 pyutil/assertutil.py
@@ -0,0 +1,60 @@
+# Copyright (c) 2003-2009 Zooko Wilcox-O'Hearn
+# This file is part of pyutil; see README.txt for licensing terms.
+
+"""
+Tests useful in assertion checking, prints out nicely formated messages too.
+"""
+
+from humanreadable import hr
+
+def _assert(___cond=False, *___args, **___kwargs):
+ if ___cond:
+ return True
+ msgbuf=[]
+ if ___args:
+ msgbuf.append("%s %s" % tuple(map(hr, (___args[0], type(___args[0]),))))
+ msgbuf.extend([", %s %s" % tuple(map(hr, (arg, type(arg),))) for arg in ___args[1:]])
+ if ___kwargs:
+ msgbuf.append(", %s: %s %s" % ((___kwargs.items()[0][0],) + tuple(map(hr, (___kwargs.items()[0][1], type(___kwargs.items()[0][1]),)))))
+ else:
+ if ___kwargs:
+ msgbuf.append("%s: %s %s" % ((___kwargs.items()[0][0],) + tuple(map(hr, (___kwargs.items()[0][1], type(___kwargs.items()[0][1]),)))))
+ msgbuf.extend([", %s: %s %s" % tuple(map(hr, (k, v, type(v),))) for k, v in ___kwargs.items()[1:]])
+
+ raise AssertionError, "".join(msgbuf)
+
+def precondition(___cond=False, *___args, **___kwargs):
+ if ___cond:
+ return True
+ msgbuf=["precondition", ]
+ if ___args or ___kwargs:
+ msgbuf.append(": ")
+ if ___args:
+ msgbuf.append("%s %s" % tuple(map(hr, (___args[0], type(___args[0]),))))
+ msgbuf.extend([", %s %s" % tuple(map(hr, (arg, type(arg),))) for arg in ___args[1:]])
+ if ___kwargs:
+ msgbuf.append(", %s: %s %s" % ((___kwargs.items()[0][0],) + tuple(map(hr, (___kwargs.items()[0][1], type(___kwargs.items()[0][1]),)))))
+ else:
+ if ___kwargs:
+ msgbuf.append("%s: %s %s" % ((___kwargs.items()[0][0],) + tuple(map(hr, (___kwargs.items()[0][1], type(___kwargs.items()[0][1]),)))))
+ msgbuf.extend([", %s: %s %s" % tuple(map(hr, (k, v, type(v),))) for k, v in ___kwargs.items()[1:]])
+
+ raise AssertionError, "".join(msgbuf)
+
+def postcondition(___cond=False, *___args, **___kwargs):
+ if ___cond:
+ return True
+ msgbuf=["postcondition", ]
+ if ___args or ___kwargs:
+ msgbuf.append(": ")
+ if ___args:
+ msgbuf.append("%s %s" % tuple(map(hr, (___args[0], type(___args[0]),))))
+ msgbuf.extend([", %s %s" % tuple(map(hr, (arg, type(arg),))) for arg in ___args[1:]])
+ if ___kwargs:
+ msgbuf.append(", %s: %s %s" % ((___kwargs.items()[0][0],) + tuple(map(hr, (___kwargs.items()[0][1], type(___kwargs.items()[0][1]),)))))
+ else:
+ if ___kwargs:
+ msgbuf.append("%s: %s %s" % ((___kwargs.items()[0][0],) + tuple(map(hr, (___kwargs.items()[0][1], type(___kwargs.items()[0][1]),)))))
+ msgbuf.extend([", %s: %s %s" % tuple(map(hr, (k, v, type(v),))) for k, v in ___kwargs.items()[1:]])
+
+ raise AssertionError, "".join(msgbuf)
50 pyutil/benchmarks/bench_json.py
@@ -0,0 +1,50 @@
+from pyutil import randutil
+import random
+from decimal import Decimal
+
+l = []
+s = None
+
+def data_strings(N):
+ del l[:]
+ for i in range(N):
+ l.append(repr(randutil.insecurerandstr(4)))
+ global s
+ s = json.dumps(l)
+
+def data_Decimals(N):
+ del l[:]
+ for i in range(N):
+ l.append(Decimal(str(random.randrange(0, 1000000000)))/random.randrange(1, 1000000000))
+ global s
+ s = jsonutil.dumps(l)
+
+def data_floats(N):
+ del l[:]
+ for i in range(N):
+ l.append(float(random.randrange(0, 1000000000))/random.randrange(1, 1000000000))
+ global s
+ s = json.dumps(l)
+
+import json
+from pyutil import jsonutil
+
+def je(N):
+ return json.dumps(l)
+
+def ue(N):
+ return jsonutil.dumps(l)
+
+def jd(N):
+ return json.loads(s)
+
+def ud(N):
+ return jsonutil.loads(s)
+
+from pyutil import benchutil
+
+for i in (data_strings, data_floats, data_Decimals):
+ for e in (ud, ue, jd, je):
+ # for e in (ue,):
+ print "i: %s, e: %s" % (i, e,)
+ benchutil.bench(e, initfunc=i, TOPXP=15, profile=False)
54 pyutil/benchmarks/bench_xor.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+
+# Copyright (c) 2002-2009 Zooko Wilcox-O'Hearn
+# This file is part of pyutil; see README.txt for licensing terms.
+
+import hmac, sys, random
+
+from pyutil.assertutil import _assert, precondition, postcondition
+from pyutil.humanreadable import hr
+from pyutil.xor import xor
+from pyutil import benchfunc
+from pyutil import randutil
+
+SFUNCS = [hmac._strxor, xor.py_xor,]
+
+SFNAMES = ["hmac", "pyutil py",]
+inputs = {}
+
+def _help_init_string(N):
+ global inputs
+ if not inputs.has_key(N):
+ inputs[N] = [randutil.insecurerandstr(N), randutil.insecurerandstr(N),]
+
+def _help_make_bench_xor(f):
+ def g(n):
+ assert inputs.has_key(n)
+ _assert(isinstance(inputs[n][0], str), "Required to be a string.", inputs[n][0])
+ assert len(inputs[n][0]) == n
+ _assert(isinstance(inputs[n][1], str), "Required to be a string.", inputs[n][1])
+ assert len(inputs[n][1]) == n
+ for SF in SFUNCS:
+ assert f(inputs[n][0], inputs[n][1]) == SF(inputs[n][0], inputs[n][1])
+
+ return f(inputs[n][0], inputs[n][1])
+ return g
+
+def bench(SETSIZES=[2**x for x in range(0, 22, 3)]):
+ random.seed(0)
+ if len(SFUNCS) <= 1: print ""
+ maxnamel = max(map(len, SFNAMES))
+ for SETSIZE in SETSIZES:
+ seed = random.random()
+ # print "seed: ", seed
+ random.seed(seed)
+ i = 0
+ if len(SFUNCS) > 1: print ""
+ for FUNC in SFUNCS:
+ funcname = SFNAMES[i] + " " * (maxnamel - len(SFNAMES[i]))
+ print "%s" % funcname,
+ sys.stdout.flush()
+ benchfunc.rep_bench(_help_make_bench_xor(FUNC), SETSIZE, initfunc=_help_init_string, MAXREPS=2**9, MAXTIME=30)
+ i = i + 1
+
+bench()
193 pyutil/benchutil.py
@@ -0,0 +1,193 @@
+# Copyright (c) 2002-2010 Zooko Wilcox-O'Hearn
+# This file is part of pyutil; see README.txt for licensing terms.
+
+"""
+Benchmark a function for its behavior with respect to N.
+
+How to use this module:
+
+1. Define a function which runs the code that you want to benchmark. The
+function takes a single argument which is the size of the task (i.e. the "N"
+parameter). Pass this function as the first argument to rep_bench(), and N as
+the second, e.g.:
+
+>>> from pyutil.benchutil import rep_bench
+>>> def fib(N):
+... if N <= 1:
+... return 1
+... else:
+... return fib(N-1) + fib(N-2)
+...
+>>> rep_bench(fib, 25)
+best: 2.777e+06, 3th-best: 2.786e+06, mean: 2.829e+06, 3th-worst: 2.817e+06, worst: 3.133e+06 (of 10)
+
+The output is reporting the number of nanoseconds that executing the function
+took, divided by N, from ten different invocations of fib(). It reports the
+best, worst, M-th best, M-th worst, and mean, where "M" is the natural log of
+the number of invocations (in this case 10).
+
+2. Now run it with different values of N and look for patterns:
+
+>>> for N in 1, 5, 9, 13, 17, 21:
+... print "%2d" % N,
+... rep_bench(fib, N)
+...
+ 1 best: 9.537e+02, 3th-best: 9.537e+02, mean: 1.287e+03, 3th-worst: 1.907e+03, worst: 1.907e+03 (of 10)
+ 5 best: 1.574e+03, 3th-best: 1.621e+03, mean: 1.774e+03, 3th-worst: 2.003e+03, worst: 2.003e+03 (of 10)
+ 9 best: 4.901e+03, 3th-best: 5.007e+03, mean: 5.327e+03, 3th-worst: 5.325e+03, worst: 7.020e+03 (of 10)
+13 best: 1.884e+04, 3th-best: 1.900e+04, mean: 2.044e+04, 3th-worst: 2.131e+04, worst: 2.447e+04 (of 10)
+17 best: 8.011e+04, 3th-best: 9.641e+04, mean: 9.847e+04, 3th-worst: 1.015e+05, worst: 1.153e+05 (of 10)
+21 best: 4.422e+05, 3th-best: 4.433e+05, mean: 4.596e+05, 3th-worst: 4.674e+05, worst: 4.948e+05 (of 10)
+
+(The pattern here is that as N grows, the time per N grows.)
+
+2. If you need to do some setting up before the code can run, then put the
+setting-up code into a separate function so that it won't be included in the
+timing measurements. A good way to share state between the setting-up function
+and the main function is to make them be methods of the same object, e.g.:
+
+>>> import random
+>>> class O:
+... def __init__(self):
+... self.l = []
+... def setup(self, N):
+... del self.l[:]
+... self.l.extend(range(N))
+... random.shuffle(self.l)
+... def sort(self, N):
+... self.l.sort()
+...
+>>> o = O()
+>>> for N in 1000, 10000, 100000, 1000000:
+... print "%7d" % N,
+... rep_bench(o.sort, N, o.setup)
+...
+ 1000 best: 4.830e+02, 3th-best: 4.950e+02, mean: 5.730e+02, 3th-worst: 5.858e+02, worst: 7.451e+02 (of 10)
+ 10000 best: 6.342e+02, 3th-best: 6.367e+02, mean: 6.678e+02, 3th-worst: 6.851e+02, worst: 7.848e+02 (of 10)
+ 100000 best: 8.309e+02, 3th-best: 8.338e+02, mean: 8.435e+02, 3th-worst: 8.540e+02, worst: 8.559e+02 (of 10)
+1000000 best: 1.327e+03, 3th-best: 1.339e+03, mean: 1.349e+03, 3th-worst: 1.357e+03, worst: 1.374e+03 (of 10)
+
+3. Things to fix:
+
+ a. I used to have it hooked up to use the "hotshot" profiler on the code being
+ measured. I recently tried to change it to use the newer cProfile profiler
+ instead, but I don't understand the interface to cProfiler so it just gives an
+ exception if you pass profile=True. Please fix this and send me a patch.
+
+ b. Wouldn't it be great if this script emitted results in a json format that
+ was understood by a tool to make pretty interactive explorable graphs? The
+ pretty graphs could look like those on http://speed.pypy.org/ . Please make
+ this work and send me a patch!
+"""
+
+import cProfile, math, operator, sys, time
+
+try:
+ import simplejson as json
+except ImportError:
+ import json
+
+if not hasattr(time, "realtime"):
+ if sys.platform in ("win32", "cygwin",):
+ time.realtime = time.clock
+ else:
+ time.realtime = time.time
+
+from assertutil import _assert
+
+def makeg(func):
+ def blah(n, func=func):
+ for i in xrange(n):
+ func()
+ return blah
+
+def rep_bench(func, n, initfunc=None, MAXREPS=10, MAXTIME=60.0, profile=False, profresults="pyutil-benchutil.prof"):
+ """
+ Will run the func up to MAXREPS times, but won't start a new run if MAXTIME
+ (wall-clock time) has already elapsed (unless MAXTIME is None).
+ """
+ starttime = time.realtime()
+ tls = [] # elapsed time in nanoseconds
+ while ((len(tls) < MAXREPS) or (MAXREPS is None)) and ((MAXTIME is None) or ((time.realtime() - starttime) < MAXTIME)):
+ if initfunc:
+ initfunc(n)
+ try:
+ tl = bench_it(func, n, profile=profile, profresults=profresults)
+ except BadMeasure:
+ pass
+ else:
+ tls.append(tl * 10**9)
+ assert tls
+ sumtls = reduce(operator.__add__, tls)
+ mean = sumtls / len(tls)
+ tls.sort()
+ worst = tls[-1]
+ best = tls[0]
+ m = min(int(math.log(len(tls)))+1, len(tls))
+ mthworst = tls[-m]
+ mthbest = tls[m-1]
+
+ res = {
+ 'worst': worst/n,
+ 'best': best/n,
+ 'm': m,
+ 'mth-best': mthbest/n,
+ 'mth-worst': mthworst/n,
+ 'mean': mean/n,
+ 'num': len(tls),
+ }
+
+ print "best: %(best)#8.03e, %(m)3dth-best: %(mth-best)#8.03e, mean: %(mean)#8.03e, %(m)3dth-worst: %(mth-worst)#8.03e, worst: %(worst)#8.03e (of %(num)6d)" % res
+
+MARGINOFERROR = 10
+
+worstemptymeasure = 0
+
+class BadMeasure(Exception):
+ """ Either the clock wrapped (which happens with time.clock()) or
+ it went backwards (which happens with time.time() on rare
+ occasions), (or the code under measure completed before a single
+ clock tick, which is probably impossible). """
+ pass
+
+def do_nothing(n):
+ pass
+
+def bench_it(func, n, profile=False, profresults="pyutil-benchutil.prof"):
+ if profile:
+ st = time.realtime()
+ cProfile.run('func(n)', profresults)
+ sto = time.realtime()
+ else:
+ st = time.realtime()
+ func(n)
+ sto = time.realtime()
+ timeelapsed = sto - st
+ if timeelapsed <= 0:
+ raise BadMeasure(timeelapsed)
+ global worstemptymeasure
+ emsta = time.realtime()
+ do_nothing(2**32)
+ emstop = time.realtime()
+ empty = emstop - emsta
+ if empty > worstemptymeasure:
+ worstemptymeasure = empty
+ _assert(timeelapsed*MARGINOFERROR > worstemptymeasure, "Invoking func %s(%s) took only %0.20f seconds, but we cannot accurately measure times much less than %0.20f seconds. Therefore we cannot produce good results here. Try benchmarking a more time-consuming variant." % (func, n, timeelapsed, worstemptymeasure,))
+ return timeelapsed
+
+def bench(func, initfunc=None, TOPXP=21, MAXREPS=5, MAXTIME=60.0, profile=False, profresults="pyutil-benchutil.prof", outputjson=False, jsonresultsfname="pyutil-benchutil-results.json"):
+ BSIZES = []
+ for i in range(TOPXP-6, TOPXP+1, 2):
+ BSIZES.append(2 ** i)
+
+ res = {}
+ for BSIZE in BSIZES:
+ print "N: %7d," % BSIZE,
+ sys.stdout.flush()
+ r = rep_bench(func, BSIZE, initfunc=initfunc, MAXREPS=MAXREPS, MAXTIME=MAXTIME, profile=profile, profresults=profresults)
+ res[BSIZE] = r
+
+ if outputjson:
+ write_file(jsonresultsfname, json.dumps(res))
+
+ return res
736 pyutil/cache.py
@@ -0,0 +1,736 @@
+# Copyright (c) 2002-2009 Zooko "Zooko" Wilcox-O'Hearn
+
+"""
+This module offers three implementations of an LRUCache, which is a dict that
+drops items according to a Least-Recently-Used policy if the dict exceeds a
+fixed maximum size.
+
+Warning: if -O optimizations are not turned on then LRUCache performs
+extensive self-analysis in every function call, which can take minutes
+and minutes for a large cache. Turn on -O, or comment out assert
+self._assert_invariants()
+"""
+
+import operator
+
+from assertutil import _assert, precondition
+from humanreadable import hr
+
+class LRUCache:
+ """
+ An efficient least-recently-used cache. It keeps an LRU queue, and when
+ the number of items in the cache reaches maxsize, it removes the least
+ recently used item.
+
+ "Looking" at an item, key, or value such as with "has_key()" makes that
+ item become the most recently used item.
+
+ You can also use "refresh()" to explicitly make an item become the most
+ recently used item.
+
+ Adding an item that is already in the dict *does* make it the most-
+ recently-used item although it does not change the state of the dict
+ itself.
+
+ See also SmallLRUCache (below), which is faster in some cases.
+ """
+ class ItemIterator:
+ def __init__(self, c):
+ self.c = c
+ self.i = c.d[c.hs][2]
+ def __iter__(self):
+ return self
+ def next(self):
+ if self.i is self.c.ts:
+ raise StopIteration
+ k = self.i
+ precondition(self.c.d.has_key(k), "The iterated LRUCache doesn't have the next key. Most likely this is because someone altered the contents of the LRUCache while the iteration was in progress.", k, self.c)
+ (v, p, n,) = self.c.d[k]
+ self.i = n
+ return (k, v,)
+
+ class KeyIterator:
+ def __init__(self, c):
+ self.c = c
+ self.i = c.d[c.hs][2]
+ def __iter__(self):
+ return self
+ def next(self):
+ if self.i is self.c.ts:
+ raise StopIteration
+ k = self.i
+ precondition(self.c.d.has_key(k), "The iterated LRUCache doesn't have the next key. Most likely this is because someone altered the contents of the LRUCache while the iteration was in progress.", k, self.c)
+ (v, p, n,) = self.c.d[k]
+ self.i = n
+ return k
+
+ class ValIterator:
+ def __init__(self, c):
+ self.c = c
+ self.i = c.d[c.hs][2]
+ def __iter__(self):
+ return self
+ def next(self):
+ if self.i is self.c.ts:
+ raise StopIteration
+ precondition(self.c.d.has_key(self.i), "The iterated LRUCache doesn't have the next key. Most likely this is because someone altered the contents of the LRUCache while the iteration was in progress.", self.i, self.c)
+ (v, p, n,) = self.c.d[self.i]
+ self.i = n
+ return v
+
+ class Sentinel:
+ def __init__(self, msg):
+ self.msg = msg
+ def __repr__(self):
+ return "<%s %s>" % (self.__class__.__name__, self.msg,)
+
+ def __init__(self, initialdata={}, maxsize=128):
+ precondition(maxsize > 0)
+ self.m = maxsize+2 # The +2 is for the head and tail nodes.
+ self.d = {} # k: k, v: [v, prev, next,] # the dict
+ self.hs = LRUCache.Sentinel("hs")
+ self.ts = LRUCache.Sentinel("ts")
+ self.d[self.hs] = [None, self.hs, self.ts,] # This allows us to use sentinels as normal nodes.
+ self.d[self.ts] = [None, self.hs, self.ts,] # This allows us to use sentinels as normal nodes.
+ self.update(initialdata)
+
+ assert self._assert_invariants()
+
+ def __repr_n__(self, n=None):
+ s = ["{",]
+ try:
+ iter = self.iteritems()
+ x = iter.next()
+ s.append(str(x[0])); s.append(": "); s.append(str(x[1]))
+ i = 1
+ while (n is None) or (i < n):
+ x = iter.next()
+ s.append(", "); s.append(str(x[0])); s.append(": "); s.append(str(x[1]))
+ except StopIteration:
+ pass
+ s.append("}")
+ return ''.join(s)
+
+ def __repr__(self):
+ return "<%s %s>" % (self.__class__.__name__, self.__repr_n__(),)
+
+ def __str__(self):
+ return "<%s %s>" % (self.__class__.__name__, self.__repr_n__(16),)
+
+ def _assert_invariants(self):
+ _assert(len(self.d) <= self.m, "Size is required to be <= maxsize.", len(self.d), self.m)
+ _assert((len(self.d) > 2) == (self.d[self.hs][2] is not self.ts) == (self.d[self.ts][1] is not self.hs), "Head and tail point to something other than each other if and only if there is at least one element in the dictionary.", self.hs, self.ts, len(self.d))
+ foundprevsentinel = 0
+ foundnextsentinel = 0
+ for (k, (v, p, n,)) in self.d.iteritems():
+ _assert(v not in (self.hs, self.ts,))
+ _assert(p is not self.ts, "A reference to the tail sentinel may not appear in prev.", k, v, p, n)
+ _assert(n is not self.hs, "A reference to the head sentinel may not appear in next.", k, v, p, n)
+ _assert(p in self.d, "Each prev is required to appear as a key in the dict.", k, v, p, n)
+ _assert(n in self.d, "Each next is required to appear as a key in the dict.", k, v, p, n)
+ if p is self.hs:
+ foundprevsentinel += 1
+ _assert(foundprevsentinel <= 2, "No more than two references to the head sentinel may appear as a prev.", k, v, p, n)
+ if n is self.ts:
+ foundnextsentinel += 1
+ _assert(foundnextsentinel <= 2, "No more than one reference to the tail sentinel may appear as a next.", k, v, p, n)
+ _assert(foundprevsentinel == 2, "A reference to the head sentinel is required appear as a prev (plus a self-referential reference).")
+ _assert(foundnextsentinel == 2, "A reference to the tail sentinel is required appear as a next (plus a self-referential reference).")
+
+ count = 0
+ for (k, v,) in self.iteritems():
+ _assert(k not in (self.hs, self.ts,))
+ count += 1
+ _assert(count == len(self.d)-2, count, len(self.d)) # -2 for the sentinels
+
+ return True
+
+ def freshen(self, k, strictkey=False):
+ assert self._assert_invariants()
+
+ if not self.d.has_key(k):
+ if strictkey:
+ raise KeyError, k
+ return
+
+ node = self.d[k]
+
+ # relink
+ self.d[node[1]][2] = node[2]
+ self.d[node[2]][1] = node[1]
+
+ # move to front
+ hnode = self.d[self.hs]
+
+ node[1] = self.hs
+ node[2] = hnode[2]
+ hnode[2] = k
+ self.d[node[2]][1] = k
+
+ assert self._assert_invariants()
+
+ def iteritems(self):
+ return LRUCache.ItemIterator(self)
+
+ def itervalues(self):
+ return LRUCache.ValIterator(self)
+
+ def iterkeys(self):
+ return self.__iter__()
+
+ def __iter__(self):
+ return LRUCache.KeyIterator(self)
+
+ def __getitem__(self, key, default=None, strictkey=True):
+ node = self.d.get(key)
+ if not node:
+ if strictkey:
+ raise KeyError, key
+ return default
+ self.freshen(key)
+ return node[0]
+
+ def __setitem__(self, k, v=None):
+ assert self._assert_invariants()
+
+ node = self.d.get(k)
+ if node:
+ node[0] = v
+ self.freshen(k)
+ return
+
+ if len(self.d) == self.m:
+ # If this insert is going to increase the size of the cache to
+ # bigger than maxsize.
+ self.pop()
+
+ hnode = self.d[self.hs]
+ n = hnode[2]
+ self.d[k] = [v, self.hs, n,]
+ hnode[2] = k
+ self.d[n][1] = k
+
+ assert self._assert_invariants()
+ return v
+
+ def __delitem__(self, key, default=None, strictkey=True):
+ """
+ @param strictkey: True if you want a KeyError in the case that
+ key is not there, False if you want a reference to default
+ in the case that key is not there
+ @param default: the object to return if key is not there; This
+ is ignored if strictkey.
+
+ @return: the value removed or default if there is not item by
+ that key and strictkey is False
+ """
+ assert self._assert_invariants()
+ if self.d.has_key(key):
+ node = self.d[key]
+ # relink
+ self.d[node[1]][2] = node[2]
+ self.d[node[2]][1] = node[1]
+ del self.d[key]
+ assert self._assert_invariants()
+ return node[0]
+ elif strictkey:
+ assert self._assert_invariants()
+ raise KeyError, key
+ else:
+ assert self._assert_invariants()
+ return default
+
+ def has_key(self, key):
+ assert self._assert_invariants()
+ if self.d.has_key(key):
+ self.freshen(key)
+ assert self._assert_invariants()
+ return True
+ else:
+ assert self._assert_invariants()
+ return False
+
+ def clear(self):
+ assert self._assert_invariants()
+ self.d.clear()
+ self.d[self.hs] = [None, self.hs, self.ts,] # This allows us to use sentinels as normal nodes.
+ self.d[self.ts] = [None, self.hs, self.ts,] # This allows us to use sentinels as normal nodes.
+ assert self._assert_invariants()
+
+ def update(self, otherdict):
+ """
+ @return: self
+ """
+ assert self._assert_invariants()
+
+ if len(otherdict) >= (self.m-2): # -2 for the sentinel nodes
+ # optimization
+ self.clear()
+ assert self._assert_invariants()
+
+ i = otherdict.iteritems()
+ try:
+ while len(self.d) < self.m:
+ (k, v,) = i.next()
+ assert self._assert_invariants()
+ self[k] = v
+ assert self._assert_invariants()
+ return self
+ except StopIteration:
+ _assert(False, "Internal error -- this should never have happened since the while loop should have terminated first.")
+ return self
+
+ for (k, v,) in otherdict.iteritems():
+ assert self._assert_invariants()
+ self[k] = v
+ assert self._assert_invariants()
+
+ def pop(self):
+ assert self._assert_invariants()
+ if len(self.d) < 2: # the +2 is for the sentinels
+ raise KeyError, 'popitem(): dictionary is empty'
+ k = self.d[self.ts][1]
+ self.remove(k)
+ assert self._assert_invariants()
+ return k
+
+ def popitem(self):
+ assert self._assert_invariants()
+ if len(self.d) < 2: # the +2 is for the sentinels
+ raise KeyError, 'popitem(): dictionary is empty'
+ k = self.d[self.ts][1]
+ val = self.remove(k)
+ assert self._assert_invariants()
+ return (k, val,)
+
+ def keys_unsorted(self):
+ assert self._assert_invariants()
+ t = self.d.copy()
+ del t[self.hs]
+ del t[self.ts]
+ assert self._assert_invariants()
+ return t.keys()
+
+ def keys(self):
+ res = [None] * len(self)
+ i = 0
+ for k in self.iterkeys():
+ res[i] = k
+ i += 1
+ return res
+
+ def values_unsorted(self):
+ assert self._assert_invariants()
+ t = self.d.copy()
+ del t[self.hs]
+ del t[self.ts]
+ assert self._assert_invariants()
+ return map(operator.__getitem__, t.values(), [0]*len(t))
+
+ def values(self):
+ res = [None] * len(self)
+ i = 0
+ for v in self.itervalues():
+ res[i] = v
+ i += 1
+ return res
+
+ def items(self):
+ res = [None] * len(self)
+ i = 0
+ for it in self.iteritems():
+ res[i] = it
+ i += 1
+ return res
+
+ def __len__(self):
+ return len(self.d) - 2
+
+ def insert(self, key, val=None):
+ assert self._assert_invariants()
+ result = self.__setitem__(key, val)
+ assert self._assert_invariants()
+ return result
+
+ def setdefault(self, key, default=None):
+ assert self._assert_invariants()
+ if not self.has_key(key):
+ self[key] = default
+ assert self._assert_invariants()
+ return self[key]
+
+ def get(self, key, default=None):
+ return self.__getitem__(key, default, strictkey=False)
+
+ def remove(self, key, default=None, strictkey=True):
+ assert self._assert_invariants()
+ result = self.__delitem__(key, default, strictkey)
+ assert self._assert_invariants()
+ return result
+
+class SmallLRUCache(dict):
+ """
+ SmallLRUCache is faster than LRUCache for small sets. How small? That
+ depends on your machine and which operations you use most often. Use
+ performance profiling to determine whether the cache class that you are
+ using makes any difference to the performance of your program, and if it
+ does, then run "quick_bench()" in test/test_cache.py to see which cache
+ implementation is faster for the size of your datasets.
+
+ A simple least-recently-used cache. It keeps an LRU queue, and
+ when the number of items in the cache reaches maxsize, it removes
+ the least recently used item.
+
+ "Looking" at an item or a key such as with "has_key()" makes that
+ item become the most recently used item.
+
+ You can also use "refresh()" to explicitly make an item become the most
+ recently used item.
+
+ Adding an item that is already in the dict *does* make it the
+ most- recently-used item although it does not change the state of
+ the dict itself.
+ """
+ class ItemIterator:
+ def __init__(self, c):
+ self.c = c
+ self.i = 0
+ def __iter__(self):
+ return self
+ def next(self):
+ precondition(self.i <= len(self.c._lru), "The iterated SmallLRUCache doesn't have this many elements. Most likely this is because someone altered the contents of the LRUCache while the iteration was in progress.", self.i, self.c)
+ precondition(dict.has_key(self.c, self.c._lru[self.i]), "The iterated SmallLRUCache doesn't have this key. Most likely this is because someone altered the contents of the LRUCache while the iteration was in progress.", self.i, self.c._lru[self.i], self.c)
+ if self.i == len(self.c._lru):
+ raise StopIteration
+ k = self.i
+ self.i += 1
+ return (k, dict.__getitem__(self.c, k),)
+
+ class KeyIterator:
+ def __init__(self, c):
+ self.c = c
+ self.i = 0
+ def __iter__(self):
+ return self
+ def next(self):
+ precondition(self.i <= len(self.c._lru), "The iterated SmallLRUCache doesn't have this many elements. Most likely this is because someone altered the contents of the LRUCache while the iteration was in progress.", self.i, self.c)
+ precondition(dict.has_key(self.c, self.c._lru[self.i]), "The iterated SmallLRUCache doesn't have this key. Most likely this is because someone altered the contents of the LRUCache while the iteration was in progress.", self.i, self.c._lru[self.i], self.c)
+ if self.i == len(self.c._lru):
+ raise StopIteration
+ k = self.i
+ self.i += 1
+ return k
+
+ class ValueIterator:
+ def __init__(self, c):
+ self.c = c
+ self.i = 0
+ def __iter__(self):
+ return self
+ def next(self):
+ precondition(self.i <= len(self.c._lru), "The iterated SmallLRUCache doesn't have this many elements. Most likely this is because someone altered the contents of the LRUCache while the iteration was in progress.", self.i, self.c)
+ precondition(dict.has_key(self.c, self.c._lru[self.i]), "The iterated SmallLRUCache doesn't have this key. Most likely this is because someone altered the contents of the LRUCache while the iteration was in progress.", self.i, self.c._lru[self.i], self.c)
+ if self.i == len(self.c._lru):
+ raise StopIteration
+ k = self.i
+ self.i += 1
+ return dict.__getitem__(self.c, k)
+
+ def __init__(self, initialdata={}, maxsize=128):
+ dict.__init__(self, initialdata)
+ self._lru = initialdata.keys() # contains keys
+ self._maxsize = maxsize
+ over = len(self) - self._maxsize
+ if over > 0:
+ map(dict.__delitem__, [self]*over, self._lru[:over])
+ del self._lru[:over]
+ assert self._assert_invariants()
+
+ def _assert_invariants(self):
+ _assert(len(self._lru) <= self._maxsize, "Size is required to be <= maxsize.")
+ _assert(len(filter(lambda x: dict.has_key(self, x), self._lru)) == len(self._lru), "Each key in self._lru is required to be in dict.", filter(lambda x: not dict.has_key(self, x), self._lru), len(self._lru), self._lru, len(self), self)
+ _assert(len(filter(lambda x: x in self._lru, self.keys())) == len(self), "Each key in dict is required to be in self._lru.", filter(lambda x: x not in self._lru, self.keys()), len(self._lru), self._lru, len(self), self)
+ _assert(len(self._lru) == len(self), "internal consistency", filter(lambda x: x not in self.keys(), self._lru), len(self._lru), self._lru, len(self), self)
+ _assert(len(self._lru) <= self._maxsize, "internal consistency", len(self._lru), self._lru, self._maxsize)
+ return True
+
+ def insert(self, key, item=None):
+ assert self._assert_invariants()
+ result = self.__setitem__(key, item)
+ assert self._assert_invariants()
+ return result
+
+ def setdefault(self, key, default=None):
+ assert self._assert_invariants()
+ if not self.has_key(key):
+ self[key] = default
+ assert self._assert_invariants()
+ return self[key]
+
+ def __setitem__(self, key, item=None):
+ assert self._assert_invariants()
+ if dict.has_key(self, key):
+ self._lru.remove(key)
+ else:
+ if len(self._lru) == self._maxsize:
+ # If this insert is going to increase the size of the cache to bigger than maxsize:
+ killkey = self._lru.pop(0)
+ dict.__delitem__(self, killkey)
+ dict.__setitem__(self, key, item)
+ self._lru.append(key)
+ assert self._assert_invariants()
+ return item
+
+ def remove(self, key, default=None, strictkey=True):
+ assert self._assert_invariants()
+ result = self.__delitem__(key, default, strictkey)
+ assert self._assert_invariants()
+ return result
+
+ def __delitem__(self, key, default=None, strictkey=True):
+ """
+ @param strictkey: True if you want a KeyError in the case that
+ key is not there, False if you want a reference to default
+ in the case that key is not there
+ @param default: the object to return if key is not there; This
+ is ignored if strictkey.
+
+ @return: the object removed or default if there is not item by
+ that key and strictkey is False
+ """
+ assert self._assert_invariants()
+ if dict.has_key(self, key):
+ val = dict.__getitem__(self, key)
+ dict.__delitem__(self, key)
+ self._lru.remove(key)
+ assert self._assert_invariants()
+ return val
+ elif strictkey:
+ assert self._assert_invariants()
+ raise KeyError, key
+ else:
+ assert self._assert_invariants()
+ return default
+
+ def clear(self):
+ assert self._assert_invariants()
+ dict.clear(self)
+ self._lru = []
+ assert self._assert_invariants()
+
+ def update(self, otherdict):
+ """
+ @return: self
+ """
+ assert self._assert_invariants()
+ if len(otherdict) > self._maxsize:
+ # Handling this special case here makes it possible to implement the
+ # other more common cases faster below.
+ dict.clear(self)
+ self._lru = []
+ if self._maxsize > (len(otherdict) - self._maxsize):
+ dict.update(self, otherdict)
+ while len(self) > self._maxsize:
+ dict.popitem(self)
+ else:
+ for k, v, in otherdict.iteritems():
+ if len(self) == self._maxsize:
+ break
+ dict.__setitem__(self, k, v)
+ self._lru = dict.keys(self)
+ assert self._assert_invariants()
+ return self
+
+ for k in otherdict.iterkeys():
+ if dict.has_key(self, k):
+ self._lru.remove(k)
+ self._lru.extend(otherdict.keys())
+ dict.update(self, otherdict)
+
+ over = len(self) - self._maxsize
+ if over > 0:
+ map(dict.__delitem__, [self]*over, self._lru[:over])
+ del self._lru[:over]
+
+ assert self._assert_invariants()
+ return self
+
+ def has_key(self, key):
+ assert self._assert_invariants()
+ if dict.has_key(self, key):
+ assert key in self._lru, "key: %s, self._lru: %s" % tuple(map(hr, (key, self._lru,)))
+ self._lru.remove(key)
+ self._lru.append(key)
+ assert self._assert_invariants()
+ return True
+ else:
+ assert self._assert_invariants()
+ return False
+
+ def refresh(self, key, strictkey=True):
+ """
+ @param strictkey: raise a KeyError exception if key isn't present
+ """
+ assert self._assert_invariants()
+ if not dict.has_key(self, key):
+ if strictkey:
+ raise KeyError, key
+ return
+ self._lru.remove(key)
+ self._lru.append(key)
+
+ def popitem(self):
+ if not self._lru:
+ raise KeyError, 'popitem(): dictionary is empty'
+ k = self._lru[-1]
+ obj = self.remove(k)
+ return (k, obj,)
+
+class LinkedListLRUCache:
+ """
+ This is slower and less featureful than LRUCache. It is included
+ here for comparison purposes.
+
+ Implementation of a length-limited O(1) LRU queue.
+ Built for and used by PyPE:
+ http://pype.sourceforge.net
+ original Copyright 2003 Josiah Carlson.
+ useful methods and _assert_invariant added by Zooko for testing and benchmarking purposes
+ """
+ class Node:
+ def __init__(self, prev, me):
+ self.prev = prev
+ self.me = me
+ self.next = None
+ def __init__(self, initialdata={}, maxsize=128):
+ self._maxsize = max(maxsize, 1)
+ self.d = {}
+ self.first = None
+ self.last = None
+ for key, value in initialdata.iteritems():
+ self[key] = value
+ def clear(self):
+ self.d = {}
+ self.first = None
+ self.last = None
+ def update(self, otherdict):
+ for (k, v,) in otherdict.iteritems():
+ self[k] = v
+ def setdefault(self, key, default=None):
+ if not self.has_key(key):
+ self[key] = default
+ return self[key]
+ def _assert_invariants(self):
+ def lliterkeys(self):
+ cur = self.first
+ while cur != None:
+ cur2 = cur.next
+ yield cur.me[0]
+ cur = cur2
+ def lllen(self):
+ # Ugh.
+ acc = 0
+ for x in lliterkeys(self):
+ acc += 1
+ return acc
+ def llhaskey(self, key):
+ # Ugh.
+ for x in lliterkeys(self):
+ if x is key:
+ return True
+ return False
+ for k in lliterkeys(self):
+ _assert(self.d.has_key(k), "Each key in the linked list is required to be in the dict.", k)
+ for k in self.d.iterkeys():
+ _assert(llhaskey(self, k), "Each key in the dict is required to be in the linked list.", k)
+ _assert(lllen(self) == len(self.d), "internal consistency", self, self.d)
+ _assert(len(self.d) <= self._maxsize, "Size is required to be <= maxsize.")
+ return True
+ def __contains__(self, obj):
+ return obj in self.d
+ def has_key(self, key):
+ return self.__contains__(key)
+ def __getitem__(self, obj):
+ a = self.d[obj].me
+ self[a[0]] = a[1]
+ return a[1]
+ def get(self, key, default=None, strictkey=False):
+ if not self.has_key(key) and strictkey:
+ raise KeyError, key
+ if self.has_key(key):
+ return self.__getitem__(key)
+ else:
+ return default
+ def __setitem__(self, obj, val):
+ if obj in self.d:
+ del self[obj]
+ nobj = self.Node(self.last, (obj, val))
+ if self.first is None:
+ self.first = nobj
+ if self.last:
+ self.last.next = nobj
+ self.last = nobj
+ self.d[obj] = nobj
+ if len(self.d) > self._maxsize:
+ if self.first == self.last:
+ self.first = None
+ self.last = None
+ return
+ a = self.first
+ a.next.prev = None
+ self.first = a.next
+ a.next = None
+ del self.d[a.me[0]]
+ del a
+ def insert(self, key, item=None):
+ return self.__setitem__(key, item)
+ def __delitem__(self, obj, default=None, strictkey=True):
+ if self.d.has_key(obj):
+ nobj = self.d[obj]
+ if nobj.prev:
+ nobj.prev.next = nobj.next
+ else:
+ self.first = nobj.next
+ if nobj.next:
+ nobj.next.prev = nobj.prev
+ else:
+ self.last = nobj.prev
+ val = self.d[obj]
+ del self.d[obj]
+ return val.me[1]
+ elif strictkey:
+ raise KeyError, obj
+ else:
+ return default
+ def remove(self, obj, default=None, strictkey=True):
+ return self.__delitem__(obj, default=default, strictkey=strictkey)