Skip to content
This repository
Browse code

Added a fresh copy of CPython 2.7.2 and emscripten as a submodule.

  • Loading branch information...
commit ef1575c0bd53cd6805c7c22facafd098d201c250 0 parents
Max Shawabkeh authored June 29, 2011

Showing 291 changed files with 32,550 additions and 0 deletions. Show diff stats Hide diff stats

  1. 3  .gitmodules
  2. 61  cpython/Demo/README
  3. 11  cpython/Demo/cgi/README
  4. 8  cpython/Demo/cgi/cgi0.sh
  5. 14  cpython/Demo/cgi/cgi1.py
  6. 22  cpython/Demo/cgi/cgi2.py
  7. 10  cpython/Demo/cgi/cgi3.py
  8. 123  cpython/Demo/cgi/wiki.py
  9. 320  cpython/Demo/classes/Complex.py
  10. 227  cpython/Demo/classes/Dates.py
  11. 66  cpython/Demo/classes/Dbm.py
  12. 12  cpython/Demo/classes/README
  13. 93  cpython/Demo/classes/Range.py
  14. 95  cpython/Demo/classes/Rev.py
  15. 68  cpython/Demo/classes/Vec.py
  16. 333  cpython/Demo/classes/bitvec.py
  17. 60  cpython/Demo/comparisons/README
  18. 4  cpython/Demo/comparisons/patterns
  19. 47  cpython/Demo/comparisons/regextest.py
  20. 45  cpython/Demo/comparisons/sortingtest.py
  21. 74  cpython/Demo/comparisons/systemtest.py
  22. 25  cpython/Demo/curses/README
  23. 216  cpython/Demo/curses/life.py
  24. 273  cpython/Demo/curses/ncurses.py
  25. 94  cpython/Demo/curses/rain.py
  26. 58  cpython/Demo/curses/repeat.py
  27. 147  cpython/Demo/curses/tclock.py
  28. 906  cpython/Demo/curses/xmas.py
  29. 57  cpython/Demo/embed/Makefile
  30. 19  cpython/Demo/embed/README
  31. 74  cpython/Demo/embed/demo.c
  32. 17  cpython/Demo/embed/importexc.c
  33. 33  cpython/Demo/embed/loop.c
  34. 10  cpython/Demo/md5test/README
  35. 1  cpython/Demo/md5test/foo
  36. 123  cpython/Demo/md5test/md5driver.py
  37. 113  cpython/Demo/metaclasses/Eiffel.py
  38. 169  cpython/Demo/metaclasses/Enum.py
  39. 118  cpython/Demo/metaclasses/Meta.py
  40. 45  cpython/Demo/metaclasses/Simple.py
  41. 256  cpython/Demo/metaclasses/Synch.py
  42. 144  cpython/Demo/metaclasses/Trace.py
  43. 605  cpython/Demo/metaclasses/index.html
  44. 256  cpython/Demo/metaclasses/meta-vladimir.txt
  45. 141  cpython/Demo/newmetaclasses/Eiffel.py
  46. 177  cpython/Demo/newmetaclasses/Enum.py
  47. 6  cpython/Demo/parser/FILES
  48. 32  cpython/Demo/parser/README
  49. 2  cpython/Demo/parser/docstring.py
  50. 190  cpython/Demo/parser/example.py
  51. 1  cpython/Demo/parser/simple.py
  52. 27  cpython/Demo/parser/source.py
  53. 48  cpython/Demo/parser/test_parser.py
  54. 213  cpython/Demo/parser/test_unparse.py
  55. 606  cpython/Demo/parser/unparse.py
  56. 301  cpython/Demo/pdist/FSProxy.py
  57. 198  cpython/Demo/pdist/RCSProxy.py
  58. 121  cpython/Demo/pdist/README
  59. 157  cpython/Demo/pdist/client.py
  60. 144  cpython/Demo/pdist/cmdfw.py
  61. 208  cpython/Demo/pdist/cmptree.py
  62. 364  cpython/Demo/pdist/cvslib.py
  63. 280  cpython/Demo/pdist/cvslock.py
  64. 19  cpython/Demo/pdist/mac.py
  65. 109  cpython/Demo/pdist/makechangelog.py
  66. 33  cpython/Demo/pdist/rcsbump
  67. 71  cpython/Demo/pdist/rcsclient.py
  68. 334  cpython/Demo/pdist/rcslib.py
  69. 8  cpython/Demo/pdist/rcvs
  70. 477  cpython/Demo/pdist/rcvs.py
  71. 8  cpython/Demo/pdist/rrcs
  72. 160  cpython/Demo/pdist/rrcs.py
  73. 33  cpython/Demo/pdist/security.py
  74. 145  cpython/Demo/pdist/server.py
  75. 24  cpython/Demo/pdist/sumtree.py
  76. 57  cpython/Demo/pysvr/Makefile
  77. 9  cpython/Demo/pysvr/README
  78. 370  cpython/Demo/pysvr/pysvr.c
  79. 124  cpython/Demo/pysvr/pysvr.py
  80. 10  cpython/Demo/rpc/MANIFEST
  81. 31  cpython/Demo/rpc/README
  82. 22  cpython/Demo/rpc/T.py
  83. 202  cpython/Demo/rpc/mountclient.py
  84. 201  cpython/Demo/rpc/nfsclient.py
  85. 98  cpython/Demo/rpc/rnusersclient.py
  86. 893  cpython/Demo/rpc/rpc.py
  87. 24  cpython/Demo/rpc/test
  88. 200  cpython/Demo/rpc/xdr.py
  89. 22  cpython/Demo/scripts/README
  90. 20  cpython/Demo/scripts/beer.py
  91. 198  cpython/Demo/scripts/eqfix.py
  92. 49  cpython/Demo/scripts/fact.py
  93. 40  cpython/Demo/scripts/find-uname.py
  94. 35  cpython/Demo/scripts/from.py
  95. 102  cpython/Demo/scripts/lpwatch.py
  96. 21  cpython/Demo/scripts/makedir.py
  97. 121  cpython/Demo/scripts/markov.py
  98. 124  cpython/Demo/scripts/mboxconvert.py
  99. 138  cpython/Demo/scripts/morse.py
  100. 59  cpython/Demo/scripts/newslist.doc
  101. 362  cpython/Demo/scripts/newslist.py
  102. 33  cpython/Demo/scripts/pi.py
  103. 129  cpython/Demo/scripts/pp.py
  104. 30  cpython/Demo/scripts/primes.py
  105. 85  cpython/Demo/scripts/queens.py
  106. 42  cpython/Demo/scripts/script.py
  107. 104  cpython/Demo/scripts/unbirthday.py
  108. 92  cpython/Demo/scripts/update.py
  109. 14  cpython/Demo/sockets/README
  110. 15  cpython/Demo/sockets/broadcast.py
  111. 31  cpython/Demo/sockets/echosvr.py
  112. 58  cpython/Demo/sockets/finger.py
  113. 146  cpython/Demo/sockets/ftp.py
  114. 347  cpython/Demo/sockets/gopher.py
  115. 80  cpython/Demo/sockets/mcast.py
  116. 14  cpython/Demo/sockets/radio.py
  117. 35  cpython/Demo/sockets/rpython.py
  118. 52  cpython/Demo/sockets/rpythond.py
  119. 109  cpython/Demo/sockets/telnet.py
  120. 93  cpython/Demo/sockets/throughput.py
  121. 63  cpython/Demo/sockets/udpecho.py
  122. 14  cpython/Demo/sockets/unicast.py
  123. 12  cpython/Demo/sockets/unixclient.py
  124. 24  cpython/Demo/sockets/unixserver.py
  125. 159  cpython/Demo/threads/Coroutine.py
  126. 92  cpython/Demo/threads/Generator.py
  127. 11  cpython/Demo/threads/README
  128. 64  cpython/Demo/threads/fcmp.py
  129. 155  cpython/Demo/threads/find.py
  130. 105  cpython/Demo/threads/squasher.py
  131. 603  cpython/Demo/threads/sync.py
  132. 114  cpython/Demo/threads/telnet.py
  133. 89  cpython/Demo/tix/INSTALL.txt
  134. 19  cpython/Demo/tix/README.txt
  135. 50  cpython/Demo/tix/bitmaps/about.xpm
  136. 6  cpython/Demo/tix/bitmaps/bold.xbm
  137. 6  cpython/Demo/tix/bitmaps/capital.xbm
  138. 6  cpython/Demo/tix/bitmaps/centerj.xbm
  139. 14  cpython/Demo/tix/bitmaps/combobox.xbm
  140. 49  cpython/Demo/tix/bitmaps/combobox.xpm
  141. 47  cpython/Demo/tix/bitmaps/combobox.xpm.1
  142. 14  cpython/Demo/tix/bitmaps/drivea.xbm
  143. 43  cpython/Demo/tix/bitmaps/drivea.xpm
  144. 48  cpython/Demo/tix/bitmaps/exit.xpm
  145. 14  cpython/Demo/tix/bitmaps/filebox.xbm
  146. 49  cpython/Demo/tix/bitmaps/filebox.xpm
  147. 6  cpython/Demo/tix/bitmaps/italic.xbm
  148. 6  cpython/Demo/tix/bitmaps/justify.xbm
  149. 6  cpython/Demo/tix/bitmaps/leftj.xbm
  150. 14  cpython/Demo/tix/bitmaps/netw.xbm
  151. 45  cpython/Demo/tix/bitmaps/netw.xpm
  152. 48  cpython/Demo/tix/bitmaps/optmenu.xpm
  153. 6  cpython/Demo/tix/bitmaps/rightj.xbm
  154. 52  cpython/Demo/tix/bitmaps/select.xpm
  155. BIN  cpython/Demo/tix/bitmaps/tix.gif
  156. 6  cpython/Demo/tix/bitmaps/underline.xbm
  157. 28  cpython/Demo/tix/grid.py
  158. 68  cpython/Demo/tix/samples/Balloon.py
  159. 44  cpython/Demo/tix/samples/BtnBox.py
  160. 196  cpython/Demo/tix/samples/CmpImg.py
  161. 102  cpython/Demo/tix/samples/ComboBox.py
  162. 122  cpython/Demo/tix/samples/Control.py
  163. 131  cpython/Demo/tix/samples/DirList.py
  164. 117  cpython/Demo/tix/samples/DirTree.py
  165. 119  cpython/Demo/tix/samples/NoteBook.py
  166. 68  cpython/Demo/tix/samples/OptMenu.py
  167. 98  cpython/Demo/tix/samples/PanedWin.py
  168. 57  cpython/Demo/tix/samples/PopMenu.py
  169. 131  cpython/Demo/tix/samples/SHList1.py
  170. 168  cpython/Demo/tix/samples/SHList2.py
  171. 80  cpython/Demo/tix/samples/Tree.py
  172. 1,003  cpython/Demo/tix/tixwidgets.py
  173. 11  cpython/Demo/tkinter/README
  174. 452  cpython/Demo/tkinter/guido/AttrDialog.py
  175. 220  cpython/Demo/tkinter/guido/ManPage.py
  176. 143  cpython/Demo/tkinter/guido/MimeViewer.py
  177. 147  cpython/Demo/tkinter/guido/ShellWindow.py
  178. 50  cpython/Demo/tkinter/guido/brownian.py
  179. 55  cpython/Demo/tkinter/guido/brownian2.py
  180. 244  cpython/Demo/tkinter/guido/canvasevents.py
  181. 109  cpython/Demo/tkinter/guido/dialog.py
  182. 91  cpython/Demo/tkinter/guido/electrons.py
  183. 154  cpython/Demo/tkinter/guido/hanoi.py
  184. 17  cpython/Demo/tkinter/guido/hello.py
  185. 23  cpython/Demo/tkinter/guido/imagedraw.py
  186. 12  cpython/Demo/tkinter/guido/imageview.py
  187. 98  cpython/Demo/tkinter/guido/kill.py
  188. 37  cpython/Demo/tkinter/guido/listtree.py
  189. 285  cpython/Demo/tkinter/guido/mbox.py
  190. 47  cpython/Demo/tkinter/guido/newmenubardemo.py
  191. 27  cpython/Demo/tkinter/guido/optionmenu.py
  192. 60  cpython/Demo/tkinter/guido/paint.py
  193. 159  cpython/Demo/tkinter/guido/rmt.py
  194. 637  cpython/Demo/tkinter/guido/solitaire.py
  195. 634  cpython/Demo/tkinter/guido/sortvisu.py
  196. 845  cpython/Demo/tkinter/guido/ss1.py
  197. 128  cpython/Demo/tkinter/guido/svkill.py
  198. 55  cpython/Demo/tkinter/guido/switch.py
  199. 267  cpython/Demo/tkinter/guido/tkman.py
  200. 27  cpython/Demo/tkinter/guido/wish.py
  201. 27  cpython/Demo/tkinter/matt/00-HELLO-WORLD.py
  202. 30  cpython/Demo/tkinter/matt/README
  203. 35  cpython/Demo/tkinter/matt/animation-simple.py
  204. 44  cpython/Demo/tkinter/matt/animation-w-velocity-ctrl.py
  205. 44  cpython/Demo/tkinter/matt/bind-w-mult-calls-p-type.py
  206. 28  cpython/Demo/tkinter/matt/canvas-demo-simple.py
  207. 61  cpython/Demo/tkinter/matt/canvas-gridding.py
  208. 62  cpython/Demo/tkinter/matt/canvas-moving-or-creating.py
  209. 55  cpython/Demo/tkinter/matt/canvas-moving-w-mouse.py
  210. 78  cpython/Demo/tkinter/matt/canvas-mult-item-sel.py
  211. 49  cpython/Demo/tkinter/matt/canvas-reading-tag-info.py
  212. 36  cpython/Demo/tkinter/matt/canvas-w-widget-draw-el.py
  213. 60  cpython/Demo/tkinter/matt/canvas-with-scrollbars.py
  214. 64  cpython/Demo/tkinter/matt/dialog-box.py
  215. 24  cpython/Demo/tkinter/matt/entry-simple.py
  216. 46  cpython/Demo/tkinter/matt/entry-with-shared-variable.py
  217. 42  cpython/Demo/tkinter/matt/killing-window-w-wm.py
  218. 244  cpython/Demo/tkinter/matt/menu-all-types-of-entries.py
  219. 112  cpython/Demo/tkinter/matt/menu-simple.py
  220. 28  cpython/Demo/tkinter/matt/not-what-you-might-think-1.py
  221. 30  cpython/Demo/tkinter/matt/not-what-you-might-think-2.py
  222. 41  cpython/Demo/tkinter/matt/packer-and-placer-together.py
  223. 32  cpython/Demo/tkinter/matt/packer-simple.py
  224. 39  cpython/Demo/tkinter/matt/placer-simple.py
  225. 54  cpython/Demo/tkinter/matt/pong-demo-1.py
  226. 61  cpython/Demo/tkinter/matt/printing-coords-of-items.py
  227. 62  cpython/Demo/tkinter/matt/radiobutton-simple.py
  228. 58  cpython/Demo/tkinter/matt/rubber-band-box-demo-1.py
  229. 51  cpython/Demo/tkinter/matt/rubber-line-demo-1.py
  230. 36  cpython/Demo/tkinter/matt/slider-demo-1.py
  231. 28  cpython/Demo/tkinter/matt/subclass-existing-widgets.py
  232. 110  cpython/Demo/tkinter/matt/two-radio-groups.py
  233. 35  cpython/Demo/tkinter/matt/window-creation-more.py
  234. 31  cpython/Demo/tkinter/matt/window-creation-simple.py
  235. 45  cpython/Demo/tkinter/matt/window-creation-w-location.py
  236. 46  cpython/Demo/tkinter/ttk/combo_themes.py
  237. 93  cpython/Demo/tkinter/ttk/dirbrowser.py
  238. BIN  cpython/Demo/tkinter/ttk/img/close.gif
  239. BIN  cpython/Demo/tkinter/ttk/img/close_active.gif
  240. BIN  cpython/Demo/tkinter/ttk/img/close_pressed.gif
  241. 37  cpython/Demo/tkinter/ttk/listbox_scrollcmd.py
  242. 78  cpython/Demo/tkinter/ttk/mac_searchentry.py
  243. 78  cpython/Demo/tkinter/ttk/notebook_closebtn.py
  244. 269  cpython/Demo/tkinter/ttk/plastik_theme.py
  245. 111  cpython/Demo/tkinter/ttk/roundframe.py
  246. 61  cpython/Demo/tkinter/ttk/theme_selector.py
  247. 107  cpython/Demo/tkinter/ttk/treeview_multicolumn.py
  248. 231  cpython/Demo/tkinter/ttk/ttkcalendar.py
  249. 83  cpython/Demo/tkinter/ttk/widget_state.py
  250. 77  cpython/Demo/turtle/about_turtle.txt
  251. 14  cpython/Demo/turtle/about_turtledemo.txt
  252. 75  cpython/Demo/turtle/demohelp.txt
  253. 58  cpython/Demo/turtle/tdemo_I_dontlike_tiltdemo.py
  254. 162  cpython/Demo/turtle/tdemo_bytedesign.py
  255. 59  cpython/Demo/turtle/tdemo_chaos.py
  256. 132  cpython/Demo/turtle/tdemo_clock.py
  257. 58  cpython/Demo/turtle/tdemo_colormixer.py
  258. 137  cpython/Demo/turtle/tdemo_fractalcurves.py
  259. 119  cpython/Demo/turtle/tdemo_lindenmayer_indian.py
  260. 76  cpython/Demo/turtle/tdemo_minimal_hanoi.py
  261. 227  cpython/Demo/turtle/tdemo_nim.py
  262. 50  cpython/Demo/turtle/tdemo_paint.py
  263. 65  cpython/Demo/turtle/tdemo_peace.py
  264. 181  cpython/Demo/turtle/tdemo_penrose.py
  265. 113  cpython/Demo/turtle/tdemo_planet_and_moon.py
  266. 63  cpython/Demo/turtle/tdemo_tree.py
  267. 65  cpython/Demo/turtle/tdemo_wikipedia.py
  268. 49  cpython/Demo/turtle/tdemo_yinyang.py
  269. 10  cpython/Demo/turtle/turtle.cfg
  270. 280  cpython/Demo/turtle/turtleDemo.py
  271. 49  cpython/Demo/turtle/turtledemo_two_canvases.py
  272. 42  cpython/Demo/xml/elem_count.py
  273. 46  cpython/Demo/xml/roundtrip.py
  274. 97  cpython/Demo/xml/rss2html.py
  275. 133  cpython/Demo/zlib/minigzip.py
  276. 48  cpython/Demo/zlib/zlibdemo.py
  277. 223  cpython/Doc/ACKS.txt
  278. 180  cpython/Doc/Makefile
  279. 144  cpython/Doc/README.txt
  280. 36  cpython/Doc/about.rst
  281. 73  cpython/Doc/bugs.rst
  282. 26  cpython/Doc/c-api/abstract.rst
  283. 122  cpython/Doc/c-api/allocation.rst
  284. 559  cpython/Doc/c-api/arg.rst
  285. 54  cpython/Doc/c-api/bool.rst
  286. 450  cpython/Doc/c-api/buffer.rst
  287. 87  cpython/Doc/c-api/bytearray.rst
  288. 150  cpython/Doc/c-api/capsule.rst
  289. 62  cpython/Doc/c-api/cell.rst
  290. 65  cpython/Doc/c-api/class.rst
3  .gitmodules
... ...
@@ -0,0 +1,3 @@
  1
+[submodule "emscripten"]
  2
+	path = emscripten
  3
+	url = git://github.com/max99x/emscripten.git
61  cpython/Demo/README
... ...
@@ -0,0 +1,61 @@
  1
+This directory contains various demonstrations of what you can do with
  2
+Python.  They were all written by me except where explicitly stated
  3
+otherwise -- in general, demos contributed by others ends up in the
  4
+../Contrib directory, unless I think they're of utmost general
  5
+importance (like Matt Conway's Tk demos).
  6
+
  7
+A fair number of utilities that are useful when while developing
  8
+Python code can be found in the ../Tools directory -- some of these
  9
+can also be considered good examples of how to write Python code.
  10
+
  11
+Finally, in order to save disk space and net bandwidth, not all
  12
+subdirectories listed here are distributed.  They are listed just
  13
+in case I change my mind about them.
  14
+
  15
+
  16
+cgi             CGI examples (see also ../Tools/faqwiz/.)
  17
+
  18
+classes		Some examples of how to use classes.
  19
+
  20
+comparisons	A set of responses to a really old language-comparison
  21
+		challenge.
  22
+
  23
+curses		A set of curses demos.
  24
+
  25
+embed		An example of embedding Python in another application
  26
+		(see also pysvr).
  27
+
  28
+imputil		Demonstration subclasses of imputil.Importer.
  29
+
  30
+md5test		Test program for the optional md5 module.
  31
+
  32
+metaclasses	The code from the 1.5 metaclasses paper on the web.
  33
+
  34
+parser		Example using the parser module.
  35
+
  36
+pdist		Old, unfinished code messing with CVS, RCS and remote
  37
+		files.
  38
+
  39
+pysvr		An example of embedding Python in a threaded
  40
+		application.
  41
+
  42
+rpc		A set of classes for building clients and servers for
  43
+		Sun RPC.
  44
+
  45
+scripts		Some useful Python scripts that I put in my bin
  46
+		directory.  No optional built-in modules needed.
  47
+
  48
+sockets		Examples for the new built-in module 'socket'.
  49
+
  50
+threads		Demos that use the 'thread' module.  (Currently these
  51
+		only run on SGIs, but this may change in the future.)
  52
+
  53
+tix		Demos using the Tix widget set addition to Tkinter.
  54
+
  55
+tkinter		Demos using the Tk interface (including Matt Conway's
  56
+		excellent set of demos).
  57
+
  58
+xml		Some XML demos.
  59
+
  60
+zlib		Some demos for the zlib module (see also the standard
  61
+		library module gzip.py).
11  cpython/Demo/cgi/README
... ...
@@ -0,0 +1,11 @@
  1
+CGI Examples
  2
+------------
  3
+
  4
+Here are some example CGI programs.  For a larger example, see
  5
+../../Tools/faqwiz/.
  6
+
  7
+cgi0.sh -- A shell script to test your server is configured for CGI
  8
+cgi1.py -- A Python script to test your server is configured for CGI
  9
+cgi2.py -- A Python script showing how to parse a form
  10
+cgi3.py -- A Python script for driving an arbitrary CGI application
  11
+wiki.py -- Sample CGI application: a minimal Wiki implementation
8  cpython/Demo/cgi/cgi0.sh
... ...
@@ -0,0 +1,8 @@
  1
+#! /bin/sh
  2
+
  3
+# If you can't get this to work, your web server isn't set up right
  4
+
  5
+echo Content-type: text/plain
  6
+echo
  7
+echo Hello world
  8
+echo This is cgi0.sh
14  cpython/Demo/cgi/cgi1.py
... ...
@@ -0,0 +1,14 @@
  1
+#!/usr/bin/env python
  2
+
  3
+"""CGI test 1 - check server setup."""
  4
+
  5
+# Until you get this to work, your web server isn't set up right or
  6
+# your Python isn't set up right.
  7
+
  8
+# If cgi0.sh works but cgi1.py doesn't, check the #! line and the file
  9
+# permissions.  The docs for the cgi.py module have debugging tips.
  10
+
  11
+print "Content-type: text/html"
  12
+print
  13
+print "<h1>Hello world</h1>"
  14
+print "<p>This is cgi1.py"
22  cpython/Demo/cgi/cgi2.py
... ...
@@ -0,0 +1,22 @@
  1
+#!/usr/bin/env python
  2
+
  3
+"""CGI test 2 - basic use of cgi module."""
  4
+
  5
+import cgitb; cgitb.enable()
  6
+
  7
+import cgi
  8
+
  9
+def main():
  10
+    form = cgi.FieldStorage()
  11
+    print "Content-type: text/html"
  12
+    print
  13
+    if not form:
  14
+        print "<h1>No Form Keys</h1>"
  15
+    else:
  16
+        print "<h1>Form Keys</h1>"
  17
+        for key in form.keys():
  18
+            value = form[key].value
  19
+            print "<p>", cgi.escape(key), ":", cgi.escape(value)
  20
+
  21
+if __name__ == "__main__":
  22
+    main()
10  cpython/Demo/cgi/cgi3.py
... ...
@@ -0,0 +1,10 @@
  1
+#!/usr/bin/env python
  2
+
  3
+"""CGI test 3 (persistent data)."""
  4
+
  5
+import cgitb; cgitb.enable()
  6
+
  7
+from wiki import main
  8
+
  9
+if __name__ == "__main__":
  10
+    main()
123  cpython/Demo/cgi/wiki.py
... ...
@@ -0,0 +1,123 @@
  1
+"""Wiki main program.  Imported and run by cgi3.py."""
  2
+
  3
+import os, re, cgi, sys, tempfile
  4
+escape = cgi.escape
  5
+
  6
+def main():
  7
+    form = cgi.FieldStorage()
  8
+    print "Content-type: text/html"
  9
+    print
  10
+    cmd = form.getvalue("cmd", "view")
  11
+    page = form.getvalue("page", "FrontPage")
  12
+    wiki = WikiPage(page)
  13
+    method = getattr(wiki, 'cmd_' + cmd, None) or wiki.cmd_view
  14
+    method(form)
  15
+
  16
+class WikiPage:
  17
+
  18
+    homedir = tempfile.gettempdir()
  19
+    scripturl = os.path.basename(sys.argv[0])
  20
+
  21
+    def __init__(self, name):
  22
+        if not self.iswikiword(name):
  23
+            raise ValueError, "page name is not a wiki word"
  24
+        self.name = name
  25
+        self.load()
  26
+
  27
+    def cmd_view(self, form):
  28
+        print "<h1>", escape(self.splitwikiword(self.name)), "</h1>"
  29
+        print "<p>"
  30
+        for line in self.data.splitlines():
  31
+            line = line.rstrip()
  32
+            if not line:
  33
+                print "<p>"
  34
+            else:
  35
+                print self.formatline(line)
  36
+        print "<hr>"
  37
+        print "<p>", self.mklink("edit", self.name, "Edit this page") + ";"
  38
+        print self.mklink("view", "FrontPage", "go to front page") + "."
  39
+
  40
+    def formatline(self, line):
  41
+        words = []
  42
+        for word in re.split('(\W+)', line):
  43
+            if self.iswikiword(word):
  44
+                if os.path.isfile(self.mkfile(word)):
  45
+                    word = self.mklink("view", word, word)
  46
+                else:
  47
+                    word = self.mklink("new", word, word + "*")
  48
+            else:
  49
+                word = escape(word)
  50
+            words.append(word)
  51
+        return "".join(words)
  52
+
  53
+    def cmd_edit(self, form, label="Change"):
  54
+        print "<h1>", label, self.name, "</h1>"
  55
+        print '<form method="POST" action="%s">' % self.scripturl
  56
+        s = '<textarea cols="70" rows="20" name="text">%s</textarea>'
  57
+        print s % self.data
  58
+        print '<input type="hidden" name="cmd" value="create">'
  59
+        print '<input type="hidden" name="page" value="%s">' % self.name
  60
+        print '<br>'
  61
+        print '<input type="submit" value="%s Page">' % label
  62
+        print "</form>"
  63
+
  64
+    def cmd_create(self, form):
  65
+        self.data = form.getvalue("text", "").strip()
  66
+        error = self.store()
  67
+        if error:
  68
+            print "<h1>I'm sorry.  That didn't work</h1>"
  69
+            print "<p>An error occurred while attempting to write the file:"
  70
+            print "<p>", escape(error)
  71
+        else:
  72
+            # Use a redirect directive, to avoid "reload page" problems
  73
+            print "<head>"
  74
+            s = '<meta http-equiv="refresh" content="1; URL=%s">'
  75
+            print s % (self.scripturl + "?cmd=view&page=" + self.name)
  76
+            print "<head>"
  77
+            print "<h1>OK</h1>"
  78
+            print "<p>If nothing happens, please click here:",
  79
+            print self.mklink("view", self.name, self.name)
  80
+
  81
+    def cmd_new(self, form):
  82
+        self.cmd_edit(form, label="Create")
  83
+
  84
+    def iswikiword(self, word):
  85
+        return re.match("[A-Z][a-z]+([A-Z][a-z]*)+", word)
  86
+
  87
+    def splitwikiword(self, word):
  88
+        chars = []
  89
+        for c in word:
  90
+            if chars and c.isupper():
  91
+                chars.append(' ')
  92
+            chars.append(c)
  93
+        return "".join(chars)
  94
+
  95
+    def mkfile(self, name=None):
  96
+        if name is None:
  97
+            name = self.name
  98
+        return os.path.join(self.homedir, name + ".txt")
  99
+
  100
+    def mklink(self, cmd, page, text):
  101
+        link = self.scripturl + "?cmd=" + cmd + "&page=" + page
  102
+        return '<a href="%s">%s</a>' % (link, text)
  103
+
  104
+    def load(self):
  105
+        try:
  106
+            f = open(self.mkfile())
  107
+            data = f.read().strip()
  108
+            f.close()
  109
+        except IOError:
  110
+            data = ""
  111
+        self.data = data
  112
+
  113
+    def store(self):
  114
+        data = self.data
  115
+        try:
  116
+            f = open(self.mkfile(), "w")
  117
+            f.write(data)
  118
+            if data and not data.endswith('\n'):
  119
+                f.write('\n')
  120
+            f.close()
  121
+            return ""
  122
+        except IOError, err:
  123
+            return "IOError: %s" % str(err)
320  cpython/Demo/classes/Complex.py
... ...
@@ -0,0 +1,320 @@
  1
+# Complex numbers
  2
+# ---------------
  3
+
  4
+# [Now that Python has a complex data type built-in, this is not very
  5
+# useful, but it's still a nice example class]
  6
+
  7
+# This module represents complex numbers as instances of the class Complex.
  8
+# A Complex instance z has two data attribues, z.re (the real part) and z.im
  9
+# (the imaginary part).  In fact, z.re and z.im can have any value -- all
  10
+# arithmetic operators work regardless of the type of z.re and z.im (as long
  11
+# as they support numerical operations).
  12
+#
  13
+# The following functions exist (Complex is actually a class):
  14
+# Complex([re [,im]) -> creates a complex number from a real and an imaginary part
  15
+# IsComplex(z) -> true iff z is a complex number (== has .re and .im attributes)
  16
+# ToComplex(z) -> a complex number equal to z; z itself if IsComplex(z) is true
  17
+#                 if z is a tuple(re, im) it will also be converted
  18
+# PolarToComplex([r [,phi [,fullcircle]]]) ->
  19
+#       the complex number z for which r == z.radius() and phi == z.angle(fullcircle)
  20
+#       (r and phi default to 0)
  21
+# exp(z) -> returns the complex exponential of z. Equivalent to pow(math.e,z).
  22
+#
  23
+# Complex numbers have the following methods:
  24
+# z.abs() -> absolute value of z
  25
+# z.radius() == z.abs()
  26
+# z.angle([fullcircle]) -> angle from positive X axis; fullcircle gives units
  27
+# z.phi([fullcircle]) == z.angle(fullcircle)
  28
+#
  29
+# These standard functions and unary operators accept complex arguments:
  30
+# abs(z)
  31
+# -z
  32
+# +z
  33
+# not z
  34
+# repr(z) == `z`
  35
+# str(z)
  36
+# hash(z) -> a combination of hash(z.re) and hash(z.im) such that if z.im is zero
  37
+#            the result equals hash(z.re)
  38
+# Note that hex(z) and oct(z) are not defined.
  39
+#
  40
+# These conversions accept complex arguments only if their imaginary part is zero:
  41
+# int(z)
  42
+# long(z)
  43
+# float(z)
  44
+#
  45
+# The following operators accept two complex numbers, or one complex number
  46
+# and one real number (int, long or float):
  47
+# z1 + z2
  48
+# z1 - z2
  49
+# z1 * z2
  50
+# z1 / z2
  51
+# pow(z1, z2)
  52
+# cmp(z1, z2)
  53
+# Note that z1 % z2 and divmod(z1, z2) are not defined,
  54
+# nor are shift and mask operations.
  55
+#
  56
+# The standard module math does not support complex numbers.
  57
+# The cmath modules should be used instead.
  58
+#
  59
+# Idea:
  60
+# add a class Polar(r, phi) and mixed-mode arithmetic which
  61
+# chooses the most appropriate type for the result:
  62
+# Complex for +,-,cmp
  63
+# Polar   for *,/,pow
  64
+
  65
+import math
  66
+import sys
  67
+
  68
+twopi = math.pi*2.0
  69
+halfpi = math.pi/2.0
  70
+
  71
+def IsComplex(obj):
  72
+    return hasattr(obj, 're') and hasattr(obj, 'im')
  73
+
  74
+def ToComplex(obj):
  75
+    if IsComplex(obj):
  76
+        return obj
  77
+    elif isinstance(obj, tuple):
  78
+        return Complex(*obj)
  79
+    else:
  80
+        return Complex(obj)
  81
+
  82
+def PolarToComplex(r = 0, phi = 0, fullcircle = twopi):
  83
+    phi = phi * (twopi / fullcircle)
  84
+    return Complex(math.cos(phi)*r, math.sin(phi)*r)
  85
+
  86
+def Re(obj):
  87
+    if IsComplex(obj):
  88
+        return obj.re
  89
+    return obj
  90
+
  91
+def Im(obj):
  92
+    if IsComplex(obj):
  93
+        return obj.im
  94
+    return 0
  95
+
  96
+class Complex:
  97
+
  98
+    def __init__(self, re=0, im=0):
  99
+        _re = 0
  100
+        _im = 0
  101
+        if IsComplex(re):
  102
+            _re = re.re
  103
+            _im = re.im
  104
+        else:
  105
+            _re = re
  106
+        if IsComplex(im):
  107
+            _re = _re - im.im
  108
+            _im = _im + im.re
  109
+        else:
  110
+            _im = _im + im
  111
+        # this class is immutable, so setting self.re directly is
  112
+        # not possible.
  113
+        self.__dict__['re'] = _re
  114
+        self.__dict__['im'] = _im
  115
+
  116
+    def __setattr__(self, name, value):
  117
+        raise TypeError, 'Complex numbers are immutable'
  118
+
  119
+    def __hash__(self):
  120
+        if not self.im:
  121
+            return hash(self.re)
  122
+        return hash((self.re, self.im))
  123
+
  124
+    def __repr__(self):
  125
+        if not self.im:
  126
+            return 'Complex(%r)' % (self.re,)
  127
+        else:
  128
+            return 'Complex(%r, %r)' % (self.re, self.im)
  129
+
  130
+    def __str__(self):
  131
+        if not self.im:
  132
+            return repr(self.re)
  133
+        else:
  134
+            return 'Complex(%r, %r)' % (self.re, self.im)
  135
+
  136
+    def __neg__(self):
  137
+        return Complex(-self.re, -self.im)
  138
+
  139
+    def __pos__(self):
  140
+        return self
  141
+
  142
+    def __abs__(self):
  143
+        return math.hypot(self.re, self.im)
  144
+
  145
+    def __int__(self):
  146
+        if self.im:
  147
+            raise ValueError, "can't convert Complex with nonzero im to int"
  148
+        return int(self.re)
  149
+
  150
+    def __long__(self):
  151
+        if self.im:
  152
+            raise ValueError, "can't convert Complex with nonzero im to long"
  153
+        return long(self.re)
  154
+
  155
+    def __float__(self):
  156
+        if self.im:
  157
+            raise ValueError, "can't convert Complex with nonzero im to float"
  158
+        return float(self.re)
  159
+
  160
+    def __cmp__(self, other):
  161
+        other = ToComplex(other)
  162
+        return cmp((self.re, self.im), (other.re, other.im))
  163
+
  164
+    def __rcmp__(self, other):
  165
+        other = ToComplex(other)
  166
+        return cmp(other, self)
  167
+
  168
+    def __nonzero__(self):
  169
+        return not (self.re == self.im == 0)
  170
+
  171
+    abs = radius = __abs__
  172
+
  173
+    def angle(self, fullcircle = twopi):
  174
+        return (fullcircle/twopi) * ((halfpi - math.atan2(self.re, self.im)) % twopi)
  175
+
  176
+    phi = angle
  177
+
  178
+    def __add__(self, other):
  179
+        other = ToComplex(other)
  180
+        return Complex(self.re + other.re, self.im + other.im)
  181
+
  182
+    __radd__ = __add__
  183
+
  184
+    def __sub__(self, other):
  185
+        other = ToComplex(other)
  186
+        return Complex(self.re - other.re, self.im - other.im)
  187
+
  188
+    def __rsub__(self, other):
  189
+        other = ToComplex(other)
  190
+        return other - self
  191
+
  192
+    def __mul__(self, other):
  193
+        other = ToComplex(other)
  194
+        return Complex(self.re*other.re - self.im*other.im,
  195
+                       self.re*other.im + self.im*other.re)
  196
+
  197
+    __rmul__ = __mul__
  198
+
  199
+    def __div__(self, other):
  200
+        other = ToComplex(other)
  201
+        d = float(other.re*other.re + other.im*other.im)
  202
+        if not d: raise ZeroDivisionError, 'Complex division'
  203
+        return Complex((self.re*other.re + self.im*other.im) / d,
  204
+                       (self.im*other.re - self.re*other.im) / d)
  205
+
  206
+    def __rdiv__(self, other):
  207
+        other = ToComplex(other)
  208
+        return other / self
  209
+
  210
+    def __pow__(self, n, z=None):
  211
+        if z is not None:
  212
+            raise TypeError, 'Complex does not support ternary pow()'
  213
+        if IsComplex(n):
  214
+            if n.im:
  215
+                if self.im: raise TypeError, 'Complex to the Complex power'
  216
+                else: return exp(math.log(self.re)*n)
  217
+            n = n.re
  218
+        r = pow(self.abs(), n)
  219
+        phi = n*self.angle()
  220
+        return Complex(math.cos(phi)*r, math.sin(phi)*r)
  221
+
  222
+    def __rpow__(self, base):
  223
+        base = ToComplex(base)
  224
+        return pow(base, self)
  225
+
  226
+def exp(z):
  227
+    r = math.exp(z.re)
  228
+    return Complex(math.cos(z.im)*r,math.sin(z.im)*r)
  229
+
  230
+
  231
+def checkop(expr, a, b, value, fuzz = 1e-6):
  232
+    print '       ', a, 'and', b,
  233
+    try:
  234
+        result = eval(expr)
  235
+    except:
  236
+        result = sys.exc_type
  237
+    print '->', result
  238
+    if isinstance(result, str) or isinstance(value, str):
  239
+        ok = (result == value)
  240
+    else:
  241
+        ok = abs(result - value) <= fuzz
  242
+    if not ok:
  243
+        print '!!\t!!\t!! should be', value, 'diff', abs(result - value)
  244
+
  245
+def test():
  246
+    print 'test constructors'
  247
+    constructor_test = (
  248
+        # "expect" is an array [re,im] "got" the Complex.
  249
+            ( (0,0), Complex() ),
  250
+            ( (0,0), Complex() ),
  251
+            ( (1,0), Complex(1) ),
  252
+            ( (0,1), Complex(0,1) ),
  253
+            ( (1,2), Complex(Complex(1,2)) ),
  254
+            ( (1,3), Complex(Complex(1,2),1) ),
  255
+            ( (0,0), Complex(0,Complex(0,0)) ),
  256
+            ( (3,4), Complex(3,Complex(4)) ),
  257
+            ( (-1,3), Complex(1,Complex(3,2)) ),
  258
+            ( (-7,6), Complex(Complex(1,2),Complex(4,8)) ) )
  259
+    cnt = [0,0]
  260
+    for t in constructor_test:
  261
+        cnt[0] += 1
  262
+        if ((t[0][0]!=t[1].re)or(t[0][1]!=t[1].im)):
  263
+            print "        expected", t[0], "got", t[1]
  264
+            cnt[1] += 1
  265
+    print "  ", cnt[1], "of", cnt[0], "tests failed"
  266
+    # test operators
  267
+    testsuite = {
  268
+            'a+b': [
  269
+                    (1, 10, 11),
  270
+                    (1, Complex(0,10), Complex(1,10)),
  271
+                    (Complex(0,10), 1, Complex(1,10)),
  272
+                    (Complex(0,10), Complex(1), Complex(1,10)),
  273
+                    (Complex(1), Complex(0,10), Complex(1,10)),
  274
+            ],
  275
+            'a-b': [
  276
+                    (1, 10, -9),
  277
+                    (1, Complex(0,10), Complex(1,-10)),
  278
+                    (Complex(0,10), 1, Complex(-1,10)),
  279
+                    (Complex(0,10), Complex(1), Complex(-1,10)),
  280
+                    (Complex(1), Complex(0,10), Complex(1,-10)),
  281
+            ],
  282
+            'a*b': [
  283
+                    (1, 10, 10),
  284
+                    (1, Complex(0,10), Complex(0, 10)),
  285
+                    (Complex(0,10), 1, Complex(0,10)),
  286
+                    (Complex(0,10), Complex(1), Complex(0,10)),
  287
+                    (Complex(1), Complex(0,10), Complex(0,10)),
  288
+            ],
  289
+            'a/b': [
  290
+                    (1., 10, 0.1),
  291
+                    (1, Complex(0,10), Complex(0, -0.1)),
  292
+                    (Complex(0, 10), 1, Complex(0, 10)),
  293
+                    (Complex(0, 10), Complex(1), Complex(0, 10)),
  294
+                    (Complex(1), Complex(0,10), Complex(0, -0.1)),
  295
+            ],
  296
+            'pow(a,b)': [
  297
+                    (1, 10, 1),
  298
+                    (1, Complex(0,10), 1),
  299
+                    (Complex(0,10), 1, Complex(0,10)),
  300
+                    (Complex(0,10), Complex(1), Complex(0,10)),
  301
+                    (Complex(1), Complex(0,10), 1),
  302
+                    (2, Complex(4,0), 16),
  303
+            ],
  304
+            'cmp(a,b)': [
  305
+                    (1, 10, -1),
  306
+                    (1, Complex(0,10), 1),
  307
+                    (Complex(0,10), 1, -1),
  308
+                    (Complex(0,10), Complex(1), -1),
  309
+                    (Complex(1), Complex(0,10), 1),
  310
+            ],
  311
+    }
  312
+    for expr in sorted(testsuite):
  313
+        print expr + ':'
  314
+        t = (expr,)
  315
+        for item in testsuite[expr]:
  316
+            checkop(*(t+item))
  317
+
  318
+
  319
+if __name__ == '__main__':
  320
+    test()
227  cpython/Demo/classes/Dates.py
... ...
@@ -0,0 +1,227 @@
  1
+# Class Date supplies date objects that support date arithmetic.
  2
+#
  3
+# Date(month,day,year) returns a Date object.  An instance prints as,
  4
+# e.g., 'Mon 16 Aug 1993'.
  5
+#
  6
+# Addition, subtraction, comparison operators, min, max, and sorting
  7
+# all work as expected for date objects:  int+date or date+int returns
  8
+# the date `int' days from `date'; date+date raises an exception;
  9
+# date-int returns the date `int' days before `date'; date2-date1 returns
  10
+# an integer, the number of days from date1 to date2; int-date raises an
  11
+# exception; date1 < date2 is true iff date1 occurs before date2 (&
  12
+# similarly for other comparisons); min(date1,date2) is the earlier of
  13
+# the two dates and max(date1,date2) the later; and date objects can be
  14
+# used as dictionary keys.
  15
+#
  16
+# Date objects support one visible method, date.weekday().  This returns
  17
+# the day of the week the date falls on, as a string.
  18
+#
  19
+# Date objects also have 4 read-only data attributes:
  20
+#   .month  in 1..12
  21
+#   .day    in 1..31
  22
+#   .year   int or long int
  23
+#   .ord    the ordinal of the date relative to an arbitrary staring point
  24
+#
  25
+# The Dates module also supplies function today(), which returns the
  26
+# current date as a date object.
  27
+#
  28
+# Those entranced by calendar trivia will be disappointed, as no attempt
  29
+# has been made to accommodate the Julian (etc) system.  On the other
  30
+# hand, at least this package knows that 2000 is a leap year but 2100
  31
+# isn't, and works fine for years with a hundred decimal digits <wink>.
  32
+
  33
+# Tim Peters   tim@ksr.com
  34
+# not speaking for Kendall Square Research Corp
  35
+
  36
+# Adapted to Python 1.1 (where some hacks to overcome coercion are unnecessary)
  37
+# by Guido van Rossum
  38
+
  39
+# Note that as of Python 2.3, a datetime module is included in the stardard
  40
+# library.
  41
+
  42
+# vi:set tabsize=8:
  43
+
  44
+_MONTH_NAMES = [ 'January', 'February', 'March', 'April', 'May',
  45
+                 'June', 'July', 'August', 'September', 'October',
  46
+                 'November', 'December' ]
  47
+
  48
+_DAY_NAMES = [ 'Friday', 'Saturday', 'Sunday', 'Monday',
  49
+               'Tuesday', 'Wednesday', 'Thursday' ]
  50
+
  51
+_DAYS_IN_MONTH = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]
  52
+
  53
+_DAYS_BEFORE_MONTH = []
  54
+dbm = 0
  55
+for dim in _DAYS_IN_MONTH:
  56
+    _DAYS_BEFORE_MONTH.append(dbm)
  57
+    dbm = dbm + dim
  58
+del dbm, dim
  59
+
  60
+_INT_TYPES = type(1), type(1L)
  61
+
  62
+def _is_leap(year):           # 1 if leap year, else 0
  63
+    if year % 4 != 0: return 0
  64
+    if year % 400 == 0: return 1
  65
+    return year % 100 != 0
  66
+
  67
+def _days_in_year(year):      # number of days in year
  68
+    return 365 + _is_leap(year)
  69
+
  70
+def _days_before_year(year):  # number of days before year
  71
+    return year*365L + (year+3)//4 - (year+99)//100 + (year+399)//400
  72
+
  73
+def _days_in_month(month, year):      # number of days in month of year
  74
+    if month == 2 and _is_leap(year): return 29
  75
+    return _DAYS_IN_MONTH[month-1]
  76
+
  77
+def _days_before_month(month, year):  # number of days in year before month
  78
+    return _DAYS_BEFORE_MONTH[month-1] + (month > 2 and _is_leap(year))
  79
+
  80
+def _date2num(date):          # compute ordinal of date.month,day,year
  81
+    return _days_before_year(date.year) + \
  82
+           _days_before_month(date.month, date.year) + \
  83
+           date.day
  84
+
  85
+_DI400Y = _days_before_year(400)      # number of days in 400 years
  86
+
  87
+def _num2date(n):             # return date with ordinal n
  88
+    if type(n) not in _INT_TYPES:
  89
+        raise TypeError, 'argument must be integer: %r' % type(n)
  90
+
  91
+    ans = Date(1,1,1)   # arguments irrelevant; just getting a Date obj
  92
+    del ans.ord, ans.month, ans.day, ans.year # un-initialize it
  93
+    ans.ord = n
  94
+
  95
+    n400 = (n-1)//_DI400Y                # # of 400-year blocks preceding
  96
+    year, n = 400 * n400, n - _DI400Y * n400
  97
+    more = n // 365
  98
+    dby = _days_before_year(more)
  99
+    if dby >= n:
  100
+        more = more - 1
  101
+        dby = dby - _days_in_year(more)
  102
+    year, n = year + more, int(n - dby)
  103
+
  104
+    try: year = int(year)               # chop to int, if it fits
  105
+    except (ValueError, OverflowError): pass
  106
+
  107
+    month = min(n//29 + 1, 12)
  108
+    dbm = _days_before_month(month, year)
  109
+    if dbm >= n:
  110
+        month = month - 1
  111
+        dbm = dbm - _days_in_month(month, year)
  112
+
  113
+    ans.month, ans.day, ans.year = month, n-dbm, year
  114
+    return ans
  115
+
  116
+def _num2day(n):      # return weekday name of day with ordinal n
  117
+    return _DAY_NAMES[ int(n % 7) ]
  118
+
  119
+
  120
+class Date:
  121
+    def __init__(self, month, day, year):
  122
+        if not 1 <= month <= 12:
  123
+            raise ValueError, 'month must be in 1..12: %r' % (month,)
  124
+        dim = _days_in_month(month, year)
  125
+        if not 1 <= day <= dim:
  126
+            raise ValueError, 'day must be in 1..%r: %r' % (dim, day)
  127
+        self.month, self.day, self.year = month, day, year
  128
+        self.ord = _date2num(self)
  129
+
  130
+    # don't allow setting existing attributes
  131
+    def __setattr__(self, name, value):
  132
+        if self.__dict__.has_key(name):
  133
+            raise AttributeError, 'read-only attribute ' + name
  134
+        self.__dict__[name] = value
  135
+
  136
+    def __cmp__(self, other):
  137
+        return cmp(self.ord, other.ord)
  138
+
  139
+    # define a hash function so dates can be used as dictionary keys
  140
+    def __hash__(self):
  141
+        return hash(self.ord)
  142
+
  143
+    # print as, e.g., Mon 16 Aug 1993
  144
+    def __repr__(self):
  145
+        return '%.3s %2d %.3s %r' % (
  146
+              self.weekday(),
  147
+              self.day,
  148
+              _MONTH_NAMES[self.month-1],
  149
+              self.year)
  150
+
  151
+    # Python 1.1 coerces neither int+date nor date+int
  152
+    def __add__(self, n):
  153
+        if type(n) not in _INT_TYPES:
  154
+            raise TypeError, 'can\'t add %r to date' % type(n)
  155
+        return _num2date(self.ord + n)
  156
+    __radd__ = __add__ # handle int+date
  157
+
  158
+    # Python 1.1 coerces neither date-int nor date-date
  159
+    def __sub__(self, other):
  160
+        if type(other) in _INT_TYPES:           # date-int
  161
+            return _num2date(self.ord - other)
  162
+        else:
  163
+            return self.ord - other.ord         # date-date
  164
+
  165
+    # complain about int-date
  166
+    def __rsub__(self, other):
  167
+        raise TypeError, 'Can\'t subtract date from integer'
  168
+
  169
+    def weekday(self):
  170
+        return _num2day(self.ord)
  171
+
  172
+def today():
  173
+    import time
  174
+    local = time.localtime(time.time())
  175
+    return Date(local[1], local[2], local[0])
  176
+
  177
+class DateTestError(Exception):
  178
+    pass
  179
+
  180
+def test(firstyear, lastyear):
  181
+    a = Date(9,30,1913)
  182
+    b = Date(9,30,1914)
  183
+    if repr(a) != 'Tue 30 Sep 1913':
  184
+        raise DateTestError, '__repr__ failure'
  185
+    if (not a < b) or a == b or a > b or b != b:
  186
+        raise DateTestError, '__cmp__ failure'
  187
+    if a+365 != b or 365+a != b:
  188
+        raise DateTestError, '__add__ failure'
  189
+    if b-a != 365 or b-365 != a:
  190
+        raise DateTestError, '__sub__ failure'
  191
+    try:
  192
+        x = 1 - a
  193
+        raise DateTestError, 'int-date should have failed'
  194
+    except TypeError:
  195
+        pass
  196
+    try:
  197
+        x = a + b
  198
+        raise DateTestError, 'date+date should have failed'
  199
+    except TypeError:
  200
+        pass
  201
+    if a.weekday() != 'Tuesday':
  202
+        raise DateTestError, 'weekday() failure'
  203
+    if max(a,b) is not b or min(a,b) is not a:
  204
+        raise DateTestError, 'min/max failure'
  205
+    d = {a-1:b, b:a+1}
  206
+    if d[b-366] != b or d[a+(b-a)] != Date(10,1,1913):
  207
+        raise DateTestError, 'dictionary failure'
  208
+
  209
+    # verify date<->number conversions for first and last days for
  210
+    # all years in firstyear .. lastyear
  211
+
  212
+    lord = _days_before_year(firstyear)
  213
+    y = firstyear
  214
+    while y <= lastyear:
  215
+        ford = lord + 1
  216
+        lord = ford + _days_in_year(y) - 1
  217
+        fd, ld = Date(1,1,y), Date(12,31,y)
  218
+        if (fd.ord,ld.ord) != (ford,lord):
  219
+            raise DateTestError, ('date->num failed', y)
  220
+        fd, ld = _num2date(ford), _num2date(lord)
  221
+        if (1,1,y,12,31,y) != \
  222
+           (fd.month,fd.day,fd.year,ld.month,ld.day,ld.year):
  223
+            raise DateTestError, ('num->date failed', y)
  224
+        y = y + 1
  225
+
  226
+if __name__ == '__main__':
  227
+    test(1850, 2150)
66  cpython/Demo/classes/Dbm.py
... ...
@@ -0,0 +1,66 @@
  1
+# A wrapper around the (optional) built-in class dbm, supporting keys
  2
+# and values of almost any type instead of just string.
  3
+# (Actually, this works only for keys and values that can be read back
  4
+# correctly after being converted to a string.)
  5
+
  6
+
  7
+class Dbm:
  8
+
  9
+    def __init__(self, filename, mode, perm):
  10
+        import dbm
  11
+        self.db = dbm.open(filename, mode, perm)
  12
+
  13
+    def __repr__(self):
  14
+        s = ''
  15
+        for key in self.keys():
  16
+            t = repr(key) + ': ' + repr(self[key])
  17
+            if s: t = ', ' + t
  18
+            s = s + t
  19
+        return '{' + s + '}'
  20
+
  21
+    def __len__(self):
  22
+        return len(self.db)
  23
+
  24
+    def __getitem__(self, key):
  25
+        return eval(self.db[repr(key)])
  26
+
  27
+    def __setitem__(self, key, value):
  28
+        self.db[repr(key)] = repr(value)
  29
+
  30
+    def __delitem__(self, key):
  31
+        del self.db[repr(key)]
  32
+
  33
+    def keys(self):
  34
+        res = []
  35
+        for key in self.db.keys():
  36
+            res.append(eval(key))
  37
+        return res
  38
+
  39
+    def has_key(self, key):
  40
+        return self.db.has_key(repr(key))
  41
+
  42
+
  43
+def test():
  44
+    d = Dbm('@dbm', 'rw', 0600)
  45
+    print d
  46
+    while 1:
  47
+        try:
  48
+            key = input('key: ')
  49
+            if d.has_key(key):
  50
+                value = d[key]
  51
+                print 'currently:', value
  52
+            value = input('value: ')
  53
+            if value is None:
  54
+                del d[key]
  55
+            else:
  56
+                d[key] = value
  57
+        except KeyboardInterrupt:
  58
+            print ''
  59
+            print d
  60
+        except EOFError:
  61
+            print '[eof]'
  62
+            break
  63
+    print d
  64
+
  65
+
  66
+test()
12  cpython/Demo/classes/README
... ...
@@ -0,0 +1,12 @@
  1
+Examples of classes that implement special operators (see reference manual):
  2
+
  3
+Complex.py	Complex numbers
  4
+Dates.py	Date manipulation package by Tim Peters
  5
+Dbm.py		Wrapper around built-in dbm, supporting	arbitrary values
  6
+Range.py	Example of a generator: re-implement built-in range()
  7
+Rev.py		Yield the reverse of a sequence
  8
+Vec.py		A simple vector class
  9
+bitvec.py	A bit-vector class by Jan-Hein B\"uhrman
  10
+
  11
+(For straightforward examples of basic class features, such as use of
  12
+methods and inheritance, see the library code.)
93  cpython/Demo/classes/Range.py
... ...
@@ -0,0 +1,93 @@
  1
+"""Example of a generator: re-implement the built-in range function
  2
+without actually constructing the list of values.
  3
+
  4
+OldStyleRange is coded in the way required to work in a 'for' loop before
  5
+iterators were introduced into the language; using __getitem__ and __len__ .
  6
+
  7
+"""
  8
+def handleargs(arglist):
  9
+    """Take list of arguments and extract/create proper start, stop, and step
  10
+    values and return in a tuple"""
  11
+    try:
  12
+        if len(arglist) == 1:
  13
+            return 0, int(arglist[0]), 1
  14
+        elif len(arglist) == 2:
  15
+            return int(arglist[0]), int(arglist[1]), 1
  16
+        elif len(arglist) == 3:
  17
+            if arglist[2] == 0:
  18
+                raise ValueError("step argument must not be zero")
  19
+            return tuple(int(x) for x in arglist)
  20
+        else:
  21
+            raise TypeError("range() accepts 1-3 arguments, given", len(arglist))
  22
+    except TypeError:
  23
+        raise TypeError("range() arguments must be numbers or strings "
  24
+        "representing numbers")
  25
+
  26
+def genrange(*a):
  27
+    """Function to implement 'range' as a generator"""
  28
+    start, stop, step = handleargs(a)
  29
+    value = start
  30
+    while value < stop:
  31
+        yield value
  32
+        value += step
  33
+
  34
+class oldrange:
  35
+    """Class implementing a range object.
  36
+    To the user the instances feel like immutable sequences
  37
+    (and you can't concatenate or slice them)
  38
+
  39
+    Done using the old way (pre-iterators; __len__ and __getitem__) to have an
  40
+    object be used by a 'for' loop.
  41
+
  42
+    """
  43
+
  44
+    def __init__(self, *a):
  45
+        """ Initialize start, stop, and step values along with calculating the
  46
+        nubmer of values (what __len__ will return) in the range"""
  47
+        self.start, self.stop, self.step = handleargs(a)
  48
+        self.len = max(0, (self.stop - self.start) // self.step)
  49
+
  50
+    def __repr__(self):
  51
+        """implement repr(x) which is also used by print"""
  52
+        return 'range(%r, %r, %r)' % (self.start, self.stop, self.step)
  53
+
  54
+    def __len__(self):
  55
+        """implement len(x)"""
  56
+        return self.len
  57
+
  58
+    def __getitem__(self, i):
  59
+        """implement x[i]"""
  60
+        if 0 <= i <= self.len:
  61
+            return self.start + self.step * i
  62
+        else:
  63
+            raise IndexError, 'range[i] index out of range'
  64
+
  65
+
  66
+def test():
  67
+    import time, __builtin__
  68
+    #Just a quick sanity check
  69
+    correct_result = __builtin__.range(5, 100, 3)
  70
+    oldrange_result = list(oldrange(5, 100, 3))
  71
+    genrange_result = list(genrange(5, 100, 3))
  72
+    if genrange_result != correct_result or oldrange_result != correct_result:
  73
+        raise Exception("error in implementation:\ncorrect   = %s"
  74
+                         "\nold-style = %s\ngenerator = %s" %
  75
+                         (correct_result, oldrange_result, genrange_result))
  76
+    print "Timings for range(1000):"
  77
+    t1 = time.time()
  78
+    for i in oldrange(1000):
  79
+        pass
  80
+    t2 = time.time()
  81
+    for i in genrange(1000):
  82
+        pass
  83
+    t3 = time.time()
  84
+    for i in __builtin__.range(1000):
  85
+        pass
  86
+    t4 = time.time()
  87
+    print t2-t1, 'sec (old-style class)'
  88
+    print t3-t2, 'sec (generator)'
  89
+    print t4-t3, 'sec (built-in)'
  90
+
  91
+
  92
+if __name__ == '__main__':
  93
+    test()
95  cpython/Demo/classes/Rev.py
... ...
@@ -0,0 +1,95 @@
  1
+'''
  2
+A class which presents the reverse of a sequence without duplicating it.
  3
+From: "Steven D. Majewski" <sdm7g@elvis.med.virginia.edu>
  4
+
  5
+It works on mutable or inmutable sequences.
  6
+
  7
+>>> chars = list(Rev('Hello World!'))
  8
+>>> print ''.join(chars)
  9
+!dlroW olleH
  10
+
  11
+The .forw is so you can use anonymous sequences in __init__, and still
  12
+keep a reference the forward sequence. )
  13
+If you give it a non-anonymous mutable sequence, the reverse sequence
  14
+will track the updated values. ( but not reassignment! - another
  15
+good reason to use anonymous values in creating the sequence to avoid
  16
+confusion. Maybe it should be change to copy input sequence to break
  17
+the connection completely ? )
  18
+
  19
+>>> nnn = range(3)
  20
+>>> rnn = Rev(nnn)
  21
+>>> for n in rnn: print n
  22
+...
  23
+2
  24
+1
  25
+0
  26
+>>> for n in range(4, 6): nnn.append(n)   # update nnn
  27
+...
  28
+>>> for n in rnn: print n     # prints reversed updated values
  29
+...
  30
+5