Commits

Anonymous committed 0effaf4

removed code subdirectory for a clean start

Comments (0)

Files changed (20)

code/CodeManager.py

-# CodeManager.py
-"""
-TODO: Break check into two pieces?
-TODO: update() is still only in test mode; doesn't actually work yet.
-
-Extracts, displays, checks and updates code examples in restructured text (.rst)
-files.
-
-You can just put in the codeMarker and the (indented) first line (containing the
-file path) into your restructured text file, then run the update program to
-automatically insert the rest of the file.
-"""
-import os, re, sys, shutil, inspect, difflib
-
-restFiles = [os.path.join(d[0], f) for d in os.walk(".") if not "_test" in d[0]
-             for f in d[2] if f.endswith(".rst")]
-
-class Languages:
-    "Strategy design pattern"
-
-    class Python:
-        codeMarker = "::\n\n"
-        commentTag = "#"
-        listings = re.compile("::\n\n( {4}#.*(?:\n+ {4}.*)*)")
-
-    class Java:
-        codeMarker = "..  code-block:: java\n\n"
-        commentTag = "//"
-        listings = \
-            re.compile(".. *code-block:: *java\n\n( {4}//.*(?:\n+ {4}.*)*)")
-
-def shift(listing):
-    "Shift the listing left by 4 spaces"
-    return [x[4:] if x.startswith("    ") else x for x in listing.splitlines()]
-
-# TEST - makes duplicates of the rst files in a test directory to test update():
-dirs = set([os.path.join("_test", os.path.dirname(f)) for f in restFiles])
-if [os.makedirs(d) for d in dirs if not os.path.exists(d)]:
-    [shutil.copy(f, os.path.join("_test", f)) for f in restFiles]
-testFiles = [os.path.join(d[0], f) for d in os.walk("_test")
-             for f in d[2] if f.endswith(".rst")]
-
-class Commands:
-    """
-    Each static method can be called from the command line. Add a new static
-    method here to add a new command to the program.
-    """
-
-    @staticmethod
-    def display(language):
-        """
-        Print all the code listings in the .rst files.
-        """
-        for f in restFiles:
-            listings = language.listings.findall(open(f).read())
-            if not listings: continue
-            print('=' * 60 + "\n" + f + "\n" + '=' * 60)
-            for n, l in enumerate(listings):
-                print("\n".join(shift(l)))
-                if n < len(listings) - 1:
-                    print('-' * 60)
-
-    @staticmethod
-    def extract(language):
-        """
-        Pull the code listings from the .rst files and write each listing into
-        its own file. Will not overwrite if code files and .rst files disagree
-        unless you say "extract -force".
-        """
-        force = len(sys.argv) == 3 and sys.argv[2] == '-force'
-        paths = set()
-        for listing in [shift(listing) for f in restFiles
-                    for listing in language.listings.findall(open(f).read())]:
-            path = listing[0][len(language.commentTag):].strip()
-            if path in paths:
-                print("ERROR: Duplicate file name: %s" % path)
-                sys.exit(1)
-            else:
-                paths.add(path)
-            path = os.path.join("..", "code", path)
-            dirname = os.path.dirname(path)
-            if dirname and not os.path.exists(dirname):
-                os.makedirs(dirname)
-            if os.path.exists(path) and not force:
-                for i in difflib.ndiff(open(path).read().splitlines(), listing):
-                    if i.startswith("+ ") or i.startswith("- "):
-                        print("ERROR: Existing file different from .rst")
-                        print("Use 'extract -force' to force overwrite")
-                        Commands.check(language)
-                        return
-            file(path, 'w').write("\n".join(listing))
-
-    @staticmethod
-    def check(language):
-        """
-        Ensure that external code files exist and check which external files
-        have changed from what's in the .rst files. Generate files in the
-        _deltas subdirectory showing what has changed.
-        """
-        class Result: # Messenger
-            def __init__(self, **kwargs):
-                self.__dict__ = kwargs
-        result = Result(missing = [], deltas = [])
-        listings = [Result(code = shift(code), file = f)
-                    for f in restFiles for code in
-                    language.listings.findall(open(f).read())]
-        paths = [os.path.normpath(os.path.join("..", "code", path)) for path in
-                    [listing.code[0].strip()[len(language.commentTag):].strip()
-                     for listing in listings]]
-        if os.path.exists("_deltas"):
-            shutil.rmtree("_deltas")
-        for path, listing in zip(paths, listings):
-            if not os.path.exists(path):
-                result.missing.append(path)
-            else:
-                code = open(path).read().splitlines()
-                for i in difflib.ndiff(listing.code, code):
-                    if i.startswith("+ ") or i.startswith("- "):
-                        d = difflib.HtmlDiff()
-                        if not os.path.exists("_deltas"):
-                            os.makedirs("_deltas")
-                        html = os.path.join("_deltas",
-                            os.path.basename(path).split('.')[0] + ".html")
-                        open(html, 'w').write(
-                            "<html><h1>Left: %s<br>Right: %s</h1>" %
-                            (listing.file, path) +
-                            d.make_file(listing.code, code))
-                        result.deltas.append(Result(file = listing.file,
-                            path = path, html = html, code = code))
-                        break
-        if result.missing:
-            print("Missing %s files:\n%s" %
-                  (language.__name__, "\n".join(result.missing)))
-        for delta in result.deltas:
-            print("%s changed in %s; see %s" %
-                  (delta.file, delta.path, delta.html))
-        return result
-
-    @staticmethod
-    def update(language): # Test until it is trustworthy
-        """
-        Refresh external code files into .rst files.
-        """
-        check_result = Commands.check(language)
-        if check_result.missing:
-            print(language.__name__, "update aborted")
-            return
-        changed = False
-        def _update(matchobj):
-            listing = shift(matchobj.group(1))
-            path = listing[0].strip()[len(language.commentTag):].strip()
-            filename = os.path.basename(path).split('.')[0]
-            path = os.path.join("..", "code", path)
-            code = open(path).read().splitlines()
-            return language.codeMarker + \
-                "\n".join([("    " + line).rstrip() for line in listing])
-        for f in testFiles:
-            updated = language.listings.sub(_update, open(f).read())
-            open(f, 'w').write(updated)
-
-if __name__ == "__main__":
-    commands = dict(inspect.getmembers(Commands, inspect.isfunction))
-    if len(sys.argv) < 2 or sys.argv[1] not in commands:
-        print("Command line options:\n")
-        for name in commands:
-            print(name + ": " + commands[name].__doc__)
-    else:
-        for language in inspect.getmembers(Languages, inspect.isclass):
-            commands[sys.argv[1]](language[1])
-
-       

code/Comprehensions/os_walk_comprehension.py

-# Comprehensions/os_walk_comprehension.py
-import os
-restFiles = [os.path.join(d[0], f) for d in os.walk(".")
-             for f in d[2] if f.endswith(".rst")]
-for r in restFiles:
-    print(r)

code/Jython/GreenHouseController.java

-// Jython/GreenHouseController.java
-package jython;
-import org.python.util.PythonInterpreter;
-import org.python.core.*;
-import junit.framework.*;
-
-public class
-GreenHouseController extends TestCase  {
-  PythonInterpreter interp =
-    new PythonInterpreter();
-  public void test() throws PyException  {
-    System.out.println(
-      "Loading GreenHouse Language");
-    interp.execfile("GreenHouseLanguage.py");
-    System.out.println(
-      "Loading GreenHouse Script");
-    interp.execfile("Schedule.ghs");
-    System.out.println(
-      "Executing GreenHouse Script");
-    interp.exec("run()");
-  }
-  public static void
-  main(String[] args) throws PyException  {
-    junit.textui.TestRunner.run(GreenHouseController.class);
-  }
-}

code/Jython/GreenHouseLanguage.py

-# Jython/GreenHouseLanguage.py
-
-class Event:
-    events = [] # static
-    def __init__(self, action, time):
-        self.action = action
-        self.time = time
-        Event.events.append(self)
-    # Used by sort(). This will cause
-    # comparisons to be based only on time:
-    def __cmp__ (self, other):
-        if self.time < other.time: return -1
-        if self.time > other.time: return 1
-        return 0
-    def run(self):
-        print("%.2f: %s" % (self.time, self.action))
-
-class LightOn(Event):
-    def __init__(self, time):
-        Event.__init__(self, "Light on", time)
-
-class LightOff(Event):
-    def __init__(self, time):
-        Event.__init__(self, "Light off", time)
-
-class WaterOn(Event):
-    def __init__(self, time):
-        Event.__init__(self, "Water on", time)
-
-class WaterOff(Event):
-    def __init__(self, time):
-        Event.__init__(self, "Water off", time)
-
-class ThermostatNight(Event):
-    def __init__(self, time):
-        Event.__init__(self,"Thermostat night", time)
-
-class ThermostatDay(Event):
-    def __init__(self, time):
-        Event.__init__(self, "Thermostat day", time)
-
-class Bell(Event):
-    def __init__(self, time):
-        Event.__init__(self, "Ring bell", time)
-
-def run():
-    Event.events.sort();
-    for e in Event.events:
-        e.run()
-
-# To test, this will be run when you say:
-# python GreenHouseLanguage.py
-if __name__ == "__main__":
-    ThermostatNight(5.00)
-    LightOff(2.00)
-    WaterOn(3.30)
-    WaterOff(4.45)
-    LightOn(1.00)
-    ThermostatDay(6.00)
-    Bell(7.00)
-    run()

code/Jython/JavaClassInPython.py

-# Jython/JavaClassInPython.py
-# run with: jython.bat JavaClassInPython.py
-# Using Java classes within Jython
-from java.util import Date, HashSet, HashMap
-from jython.javaclass import JavaClass
-from math import sin
-
-d = Date() # Creating a Java Date object
-print(d) # Calls toString()
-
-# A "generator" to easily create data:
-class ValGen:
-    def __init__(self, maxVal):
-        self.val = range(maxVal)
-    # Called during 'for' iteration:
-    def __getitem__(self, i):
-        # Returns a tuple of two elements:
-        return self.val[i], sin(self.val[i])
-
-# Java standard containers:
-map = HashMap()
-set = HashSet()
-
-for x, y in ValGen(10):
-    map.put(x, y)
-    set.add(y)
-    set.add(y)
-
-print(map)
-print(set)
-
-# Iterating through a set:
-for z in set:
-    print(z, z.__class__)
-
-print(map[3]) # Uses Python dictionary indexing
-for x in map.keySet(): # keySet() is a Map method
-    print(x, map[x])
-
-# Using a Java class that you create yourself is
-# just as easy:
-jc = JavaClass()
-jc2 = JavaClass("Created within Jython")
-print(jc2.getVal())
-jc.setVal("Using a Java class is trivial")
-print(jc.getVal())
-print(jc.getChars())
-jc.val = "Using bean properties"
-print(jc.val)

code/Jython/MultipleJythons.java

-// Jython/MultipleJythons.java
-// You can run multiple interpreters, each
-// with its own name space.
-package jython;
-import org.python.util.PythonInterpreter;
-import org.python.core.*;
-import junit.framework.*;
-
-public class MultipleJythons extends TestCase  {
-  PythonInterpreter
-    interp1 =  new PythonInterpreter(),
-    interp2 =  new PythonInterpreter();
-  public void test() throws PyException {
-    interp1.set("a", new PyInteger(42));
-    interp2.set("a", new PyInteger(47));
-    interp1.exec("print(a)");
-    interp2.exec("print(a)");
-    PyObject x1 = interp1.get("a");
-    PyObject x2 = interp2.get("a");
-    System.out.println("a from interp1: " + x1);
-    System.out.println("a from interp2: " + x2);
-  }
-  public static void
-  main(String[] args) throws PyException  {
-    junit.textui.TestRunner.run(MultipleJythons.class);
-  }
-}

code/Jython/PyUtil.java

-// Jython/PyUtil.java
-// PythonInterpreter utilities
-package net.mindview.python;
-import org.python.util.PythonInterpreter;
-import org.python.core.*;
-import java.util.*;
-
-public class PyUtil {
-  /** Extract a Python tuple or array into a Java
-  List (which can be converted into other kinds
-  of lists and sets inside Java).
-  @param interp The Python interpreter object
-  @param pyName The id of the python list object
-  */
-  public static List
-  toList(PythonInterpreter interp, String pyName){
-    return new ArrayList(Arrays.asList(
-      (Object[])interp.get(
-        pyName, Object[].class)));
-  }
-  /** Extract a Python dictionary into a Java Map
-  @param interp The Python interpreter object
-  @param pyName The id of the python dictionary
-  */
-  public static Map
-  toMap(PythonInterpreter interp, String pyName){
-    PyList pa = ((PyDictionary)interp.get(
-      pyName)).items();
-    Map map = new HashMap();
-    while(pa.__len__() != 0) {
-      PyTuple po = (PyTuple)pa.pop();
-      Object first = po.__finditem__(0)
-        .__tojava__(Object.class);
-      Object second = po.__finditem__(1)
-        .__tojava__(Object.class);
-      map.put(first, second);
-    }
-    return map;
-  }
-  /** Turn a Java Map into a PyDictionary,
-  suitable for placing into a PythonInterpreter
-  @param map The Java Map object
-  */
-  public static PyDictionary
-  toPyDictionary(Map map) {
-    Map m = new HashMap();
-    Iterator it = map.entrySet().iterator();
-    while(it.hasNext()) {
-      Map.Entry e = (Map.Entry)it.next();
-      m.put(Py.java2py(e.getKey()),
-        Py.java2py(e.getValue()));
-    }
-    // PyDictionary constructor wants a Hashtable:
-    return new PyDictionary(new Hashtable(m));
-  }
-}

code/Jython/PythonDialogs.py

-# Jython/PythonDialogs.py
-# Dialogs.java from "Thinking in Java, 2nd
-# edition," Chapter 13, converted into Jython.
-# Don't run this as part of the automatic make:
-#=M @echo skipping PythonDialogs.py
-from java.awt import FlowLayout
-from javax.swing import JFrame, JDialog, JLabel
-from javax.swing import JButton
-
-class MyDialog(JDialog):
-    def __init__(self, parent=None):
-        JDialog.__init__(self,
-          title="My dialog", modal=1)
-        self.contentPane.layout = FlowLayout()
-        self.contentPane.add(JLabel("A dialog!"))
-        self.contentPane.add(JButton("OK",
-          actionPerformed =
-            lambda e, t=self: t.dispose()))
-        self.pack()
-
-frame = JFrame("Dialogs", visible=1,
-  defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
-dlg = MyDialog()
-frame.contentPane.add(
-  JButton("Press here to get a Dialog Box",
-    actionPerformed = lambda e: dlg.show()))
-frame.pack()

code/Jython/PythonInterpreterGetting.java

-// Jython/PythonInterpreterGetting.java
-// Getting data from the PythonInterpreter object.
-package jython;
-import org.python.util.PythonInterpreter;
-import org.python.core.*;
-import java.util.*;
-import net.mindview.python.*;
-import junit.framework.*;
-
-public class
-PythonInterpreterGetting extends TestCase {
-  PythonInterpreter interp =
-    new PythonInterpreter();
-  public void test() throws PyException  {
-    interp.exec("a = 100");
-    // If you just use the ordinary get(),
-    // it returns a PyObject:
-    PyObject a = interp.get("a");
-    // There's not much you can do with a generic
-    // PyObject, but you can print it out:
-    System.out.println("a = " + a);
-    // If you know the type it's supposed to be,
-    // you can "cast" it using __tojava__() to
-    // that Java type and manipulate it in Java.
-    // To use 'a' as an int, you must use
-    // the Integer wrapper class:
-    int ai= ((Integer)a.__tojava__(Integer.class))
-      .intValue();
-    // There are also convenience functions:
-    ai = Py.py2int(a);
-    System.out.println("ai + 47 = " + (ai + 47));
-    // You can convert it to different types:
-    float af = Py.py2float(a);
-    System.out.println("af + 47 = " + (af + 47));
-    // If you try to cast it to an inappropriate
-    // type you'll get a runtime exception:
-    //! String as = (String)a.__tojava__(
-    //!   String.class);
-
-    // If you know the type, a more useful method
-    // is the overloaded get() that takes the
-    // desired class as the 2nd argument:
-    interp.exec("x = 1 + 2");
-    int x = ((Integer)interp
-      .get("x", Integer.class)).intValue();
-    System.out.println("x = " + x);
-
-    // Since Python is so good at manipulating
-    // strings and files, you will often need to
-    // extract an array of Strings. Here, a file
-    // is read as a Python array:
-    interp.exec("lines = " +
-      "open('PythonInterpreterGetting.java')" +
-      ".readlines()");
-    // Pull it in as a Java array of String:
-    String[] lines = (String[])
-      interp.get("lines", String[].class);
-    for(int i = 0; i < 10; i++)
-      System.out.print(lines[i]);
-
-    // As an example of useful string tools,
-    // global expansion of ambiguous file names
-    // using glob is very useful, but it's not
-    // part of the standard Jython package, so
-    // you'll have to make sure that your
-    // Python path is set to include these, or
-    // that you deliver the necessary Python
-    // files with your application.
-    interp.exec("from glob import glob");
-    interp.exec("files = glob('*.java')");
-    String[] files = (String[])
-      interp.get("files", String[].class);
-    for(int i = 0; i < files.length; i++)
-      System.out.println(files[i]);
-
-    // You can extract tuples and arrays into
-    // Java Lists with net.mindview.PyUtil:
-    interp.exec(
-      "tup = ('fee', 'fi', 'fo', 'fum', 'fi')");
-    List tup = PyUtil.toList(interp, "tup");
-    System.out.println(tup);
-    // It really is a list of String objects:
-    System.out.println(tup.get(0).getClass());
-    // You can easily convert it to a Set:
-    Set tups = new HashSet(tup);
-    System.out.println(tups);
-    interp.exec("ints=[1,3,5,7,9,11,13,17,19]");
-    List ints = PyUtil.toList(interp, "ints");
-    System.out.println(ints);
-    // It really is a List of Integer objects:
-    System.out.println((ints.get(1)).getClass());
-
-    // If you have a Python dictionary, it can
-    // be extracted into a Java Map, again with
-    // net.mindview.PyUtil:
-    interp.exec("dict = { 1 : 'a', 3 : 'b'," +
-      "5 : 'c', 9 : 'd', 11 : 'e' }");
-    Map map = PyUtil.toMap(interp, "dict");
-    System.out.println("map: " + map);
-    // It really is Java objects, not PyObjects:
-    Iterator it = map.entrySet().iterator();
-    Map.Entry e = (Map.Entry)it.next();
-    System.out.println(e.getKey().getClass());
-    System.out.println(e.getValue().getClass());
-  }
-  public static void
-  main(String[] args) throws PyException  {
-    junit.textui.TestRunner.run(
-      PythonInterpreterGetting.class);
-  }
-}

code/Jython/PythonInterpreterSetting.java

-// Jython/PythonInterpreterSetting.java
-// Passing data from Java to python when using
-// the PythonInterpreter object.
-package jython;
-import org.python.util.PythonInterpreter;
-import org.python.core.*;
-import java.util.*;
-import net.mindview.python.*;
-import junit.framework.*;
-
-public class
-PythonInterpreterSetting extends TestCase  {
-  PythonInterpreter interp =
-    new PythonInterpreter();
-  public void test() throws PyException  {
-    // It automatically converts Strings
-    // into native Python strings:
-    interp.set("a", "This is a test");
-    interp.exec("print(a)");
-    interp.exec("print(a[5:])"); // A slice
-    // It also knows what to do with arrays:
-    String[] s = { "How", "Do", "You", "Do?" };
-    interp.set("b", s);
-    interp.exec("for x in b: print(x[0], x)");
-    // set() only takes Objects, so it can't
-    // figure out primitives. Instead,
-    // you have to use wrappers:
-    interp.set("c", new PyInteger(1));
-    interp.set("d", new PyFloat(2.2));
-    interp.exec("print(c + d)");
-    // You can also use Java's object wrappers:
-    interp.set("c", new Integer(9));
-    interp.set("d", new Float(3.14));
-    interp.exec("print(c + d)");
-    // Define a Python function to print arrays:
-    interp.exec(
-      "def prt(x): \n" +
-      "  print(x)\n" +
-      "  for i in x: \n" +
-      "    print(i,)\n" +
-      "  print(x.__class__)\n");
-    // Arrays are Objects, so it has no trouble
-    // figuring out the types contained in arrays:
-    Object[] types = {
-      new boolean[]{ true, false, false, true },
-      new char[]{ 'a', 'b', 'c', 'd' },
-      new byte[]{ 1, 2, 3, 4 },
-      new int[]{ 10, 20, 30, 40 },
-      new long[]{ 100, 200, 300, 400 },
-      new float[]{ 1.1f, 2.2f, 3.3f, 4.4f },
-      new double[]{ 1.1, 2.2, 3.3, 4.4 },
-    };
-    for(int i = 0; i < types.length; i++) {
-      interp.set("e", types[i]);
-      interp.exec("prt(e)");
-    }
-    // It uses toString() to print Java objects:
-    interp.set("f", new Date());
-    interp.exec("print(f)");
-    // You can pass it a List
-    // and index into it...
-    List x = new ArrayList();
-    for(int i = 0; i < 10; i++)
-        x.add(new Integer(i * 10));
-    interp.set("g", x);
-    interp.exec("print(g)");
-    interp.exec("print(g[1])");
-    // ... But it's not quite smart enough
-    // to treat it as a Python array:
-    interp.exec("print(g.__class__)");
-    // interp.exec("print(g[5:])"); // Fails
-    // must extract the Java array:
-    System.out.println("ArrayList to array:");
-    interp.set("h", x.toArray());
-    interp.exec("print(h.__class__)");
-    interp.exec("print(h[5:])");
-    // Passing in a Map:
-    Map m = new HashMap();
-    m.put(new Integer(1), new Character('a'));
-    m.put(new Integer(3), new Character('b'));
-    m.put(new Integer(5), new Character('c'));
-    m.put(new Integer(7), new Character('d'));
-    m.put(new Integer(11), new Character('e'));
-    System.out.println("m: " + m);
-    interp.set("m", m);
-    interp.exec("print(m, m.__class__," +
-      "m[1], m[1].__class__)");
-    // Not a Python dictionary, so this fails:
-    //! interp.exec("for x in m.keys():" +
-    //!   "print(x, m[x])");
-    // To convert a Map to a Python dictionary,
-    // use net.mindview.python.PyUtil:
-    interp.set("m", PyUtil.toPyDictionary(m));
-    interp.exec("print(m, m.__class__, " +
-      "m[1], m[1].__class__)");
-    interp.exec("for x in m.keys():print(x,m[x])");
-  }
-  public static void
-  main(String[] args) throws PyException  {
-    junit.textui.TestRunner.run(
-      PythonInterpreterSetting.class);
-  }
-}

code/Jython/PythonSwing.py

-# Jython/PythonSwing.py
-# The HTMLButton.java example from
-# "Thinking in Java, 2nd edition," Chapter 13,
-# converted into Jython.
-# Don't run this as part of the automatic make:
-#=M @echo skipping PythonSwing.py
-from javax.swing import JFrame, JButton, JLabel
-from java.awt import FlowLayout
-
-frame = JFrame("HTMLButton", visible=1,
-  defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
-
-def kapow(e):
-    frame.contentPane.add(JLabel("<html>"+
-      "<i><font size=+4>Kapow!"))
-    # Force a re-layout to
-    # include the new label:
-    frame.validate()
-
-button = JButton("<html><b><font size=+2>" +
-  "<center>Hello!<br><i>Press me now!",
-  actionPerformed=kapow)
-frame.contentPane.layout = FlowLayout()
-frame.contentPane.add(button)
-frame.pack()
-frame.size=200, 500

code/Jython/PythonToJavaClass.py

-# Jython/PythonToJavaClass.py
-#=T python\java\test\PythonToJavaClass.class
-#=M jythonc.bat --package python.java.test \
-#=M PythonToJavaClass.py
-# A Python class created to produce a Java class
-from jarray import array
-import java
-
-class PythonToJavaClass(java.lang.Object):
-    # The '@sig' signature string is used to create
-    # the proper signature in the resulting
-    # Java code:
-    def __init__(self):
-        "@sig public PythonToJavaClass()"
-        print("Constructor for PythonToJavaClass")
-
-    def simple(self):
-        "@sig public void simple()"
-        print("simple()")
-
-    # Returning values to Java:
-    def returnString(self):
-        "@sig public java.lang.String returnString()"
-        return "howdy"
-
-    # You must construct arrays to return along
-    # with the type of the array:
-    def returnArray(self):
-        "@sig public java.lang.String[] returnArray()"
-        test = [ "fee", "fi", "fo", "fum" ]
-        return array(test, java.lang.String)
-
-    def ints(self):
-        "@sig public java.lang.Integer[] ints()"
-        test = [ 1, 3, 5, 7, 11, 13, 17, 19, 23 ]
-        return array(test, java.lang.Integer)
-
-    def doubles(self):
-        "@sig public java.lang.Double[] doubles()"
-        test = [ 1, 3, 5, 7, 11, 13, 17, 19, 23 ]
-        return array(test, java.lang.Double)
-
-    # Passing arguments in from Java:
-    def argIn1(self, a):
-        "@sig public void argIn1(java.lang.String a)"
-        print("a: %s" % a)
-        print("a.__class__", a.__class__)
-
-    def argIn2(self, a):
-        "@sig public void argIn1(java.lang.Integer a)"
-        print("a + 100: %d" % (a + 100))
-        print("a.__class__", a.__class__)
-
-    def argIn3(self, a):
-        "@sig public void argIn3(java.util.List a)"
-        print("received List:", a, a.__class__)
-        print("element type:", a[0].__class__)
-        print("a[3] + a[5]:", a[5] + a[7])
-        #! print("a[2:5]:", a[2:5]) # Doesn't work
-
-    def argIn4(self, a):
-        "@sig public void \
-           argIn4(org.python.core.PyArray a)"
-        print("received type:", a.__class__)
-        print("a: ", a)
-        print("element type:", a[0].__class__)
-        print("a[3] + a[5]:", a[5] + a[7])
-        print("a[2:5]:", a[2:5] # A real Python array)
-
-    # A map must be passed in as a PyDictionary:
-    def argIn5(self, m):
-        "@sig public void \
-           argIn5(org.python.core.PyDictionary m)"
-        print("received Map: ", m, m.__class__)
-        print("m['3']:", m['3'])
-        for x in m.keys():
-            print(x, m[x])

code/Jython/Schedule.ghs

-# Jython/Schedule.ghs
-Bell(7.00)
-ThermostatDay(6.00)
-WaterOn(3.30)
-LightOn(1.00)
-ThermostatNight(5.00)
-LightOff(2.00)
-WaterOff(4.45)

code/Jython/Test.java

-// Jython/Test.java
-package net.mindview.python;
-import org.python.util.PythonInterpreter;
-import java.util.*;
-import junit.framework.*;
-
-public class Test extends TestCase  {
-  PythonInterpreter pi =
-    new PythonInterpreter();
-  public void test1() {
-    pi.exec("tup=('fee','fi','fo','fum','fi')");
-    List lst = PyUtil.toList(pi, "tup");
-    System.out.println(lst);
-    System.out.println(new HashSet(lst));
-  }
-  public void test2() {
-    pi.exec("ints=[1,3,5,7,9,11,13,17,19]");
-    List lst = PyUtil.toList(pi, "ints");
-    System.out.println(lst);
-  }
-  public void test3() {
-    pi.exec("dict = { 1 : 'a', 3 : 'b', " +
-      "5 : 'c', 9 : 'd', 11 : 'e'}");
-    Map mp = PyUtil.toMap(pi, "dict");
-    System.out.println(mp);
-  }
-  public void test4() {
-    Map m = new HashMap();
-    m.put("twas", new Integer(11));
-    m.put("brillig", new Integer(27));
-    m.put("and", new Integer(47));
-    m.put("the", new Integer(42));
-    m.put("slithy", new Integer(33));
-    m.put("toves", new Integer(55));
-    System.out.println(m);
-    pi.set("m", PyUtil.toPyDictionary(m));
-    pi.exec("print(m)");
-    pi.exec("print(m['slithy'])");
-  }
-  public static void main(String args[]) {
-    junit.textui.TestRunner.run(Test.class);
-  }
-}

code/Jython/TestPythonToJavaClass.java

-// Jython/TestPythonToJavaClass.java
-//+D python\java\test\PythonToJavaClass.class
-package jython;
-import java.lang.reflect.*;
-import java.util.*;
-import org.python.core.*;
-import junit.framework.*;
-import java.util.*;
-import net.mindview.python.*;
-// The package with the Python-generated classes:
-import python.java.test.*;
-
-public class
-TestPythonToJavaClass extends TestCase  {
-  PythonToJavaClass p2j = new PythonToJavaClass();
-  public void testDumpClassInfo() {
-    System.out.println(
-      Arrays.toString(
-        p2j.getClass().getConstructors()));
-    Method[] methods =
-      p2j.getClass().getMethods();
-    for(int i = 0; i < methods.length; i++) {
-      String nm = methods[i].toString();
-      if(nm.indexOf("PythonToJavaClass") != -1)
-        System.out.println(nm);
-    }
-  }
-  public void test1() {
-    p2j.simple();
-    System.out.println(p2j.returnString());
-    System.out.println(
-      Arrays.toString(p2j.returnArray()));
-    System.out.println(
-      Arrays.toString(p2j.ints());
-    System.out.println(
-      Arrays.toString(p2j.doubles()));
-    p2j.argIn1("Testing argIn1()");
-    p2j.argIn2(new Integer(47));
-    ArrayList a = new ArrayList();
-    for(int i = 0; i < 10; i++)
-      a.add(new Integer(i));
-    p2j.argIn3(a);
-    p2j.argIn4(
-      new PyArray(Integer.class, a.toArray()));
-    Map m = new HashMap();
-    for(int i = 0; i < 10; i++)
-      m.put("" + i, new Float(i));
-    p2j.argIn5(PyUtil.toPyDictionary(m));
-  }
-  public static void main(String[] args) {
-    junit.textui.TestRunner.run(
-      TestPythonToJavaClass.class);
-  }
-}

code/Jython/javaclass/JavaClass.java

-// Jython/javaclass/JavaClass.java
-package jython.javaclass;
-import junit.framework.*;
-import java.util.*;
-
-public class JavaClass {
-  private String s = "";
-  public JavaClass() {
-    System.out.println("JavaClass()");
-  }
-  public JavaClass(String a) {
-    s = a;
-    System.out.println("JavaClass(String)");
-  }
-  public String getVal() {
-    System.out.println("getVal()");
-    return s;
-  }
-  public void setVal(String a) {
-    System.out.println("setVal()");
-    s = a;
-  }
-  public Character[] getChars() {
-    System.out.println("getChars()");
-    Character[] r = new Character[s.length()];
-    for(int i = 0; i < s.length(); i++)
-      r[i] = new Character(s.charAt(i));
-    return r;
-  }
-  public static class Test extends TestCase  {
-    JavaClass
-      x1 = new JavaClass(),
-      x2 = new JavaClass("UnitTest");
-    public void test1() {
-      System.out.println(x2.getVal());
-      x1.setVal("SpamEggsSausageAndSpam");
-      System.out.println(
-        Arrays.toString(x1.getChars()));
-    }
-  }
-  public static void main(String[] args) {
-    junit.textui.TestRunner.run(Test.class);
-  }
-}

code/SanityCheck.py

-# SanityCheck.py
-#! /usr/bin/env python
-import string, glob, os
-# Do not include the following in the automatic
-# tests:
-exclude = ("SanityCheck.py", "BoxObserver.py",)
-
-def visitor(arg, dirname, names):
-    dir = os.getcwd()
-    os.chdir(dirname)
-    try:
-        pyprogs = [p for p in glob.glob('*.py')
-                   if p not in exclude ]
-        if not pyprogs: return
-        print('[' + os.getcwd() + ']')
-        for program in pyprogs:
-            print('\t', program)
-            os.system("python %s > tmp" % program)
-            file = open(program).read()
-            output = open('tmp').read()
-            # Append output if it's not already there:
-            if file.find("output = '''") == -1 and \
-              len(output) > 0:
-                divider = '#' * 50 + '\n'
-                file = file.replace('#' + ':~', '#<hr>\n')
-                file += "output = '''\n" + \
-                  open('tmp').read() + "'''\n"
-                open(program,'w').write(file)
-    finally:
-        os.chdir(dir)
-
-if __name__ == "__main__":
-    os.path.walk('.', visitor, None)

src/CodeManager.py

 # CodeManager.py
 """
-TODO: update() is still only in test mode; doesn't actually work yet.
-
 Extracts, displays, checks and updates code examples in restructured text (.rst)
 files.
 
 
 def difference(listing1, listing2):
     "Is there any difference between these two code listings?"
-    for line in difflib.ndiff(listing1, listing2):
-        if line.startswith("+ ") or line.startswith("- "):
+    if type(listing1) is not list:
+        listing1 = listing1.splitlines()
+    if type(listing2) is not list:
+        listing2 = listing2.splitlines()
+    for line1, line2 in zip(listing1, listing2):
+        if line1 != line2:
             return True
     return False
 
-# TEST - makes duplicates of the rst files in a test directory to test update():
-dirs = set([os.path.join("_test", os.path.dirname(f)) for f in restFiles])
-if [os.makedirs(d) for d in dirs if not os.path.exists(d)]:
-    [shutil.copy(f, os.path.join("_test", f)) for f in restFiles]
-testFiles = [os.path.join(d[0], f) for d in os.walk("_test")
-             for f in d[2] if f.endswith(".rst")]
-
 class Commands:
     """
     Each static method can be called from the command line. Add a new static
             if dirname and not os.path.exists(dirname):
                 os.makedirs(dirname)
             if os.path.exists(path) and not force:
-                if difference(open(path).read().splitlines(), listing):
+                if difference(open(path).read(), listing):
                     print("ERROR: Existing file different from .rst")
                     print("Use 'extract -force' to force overwrite")
                     Commands.check(language)
             file(path, 'w').write("\n".join(listing))
 
     @staticmethod
-    def check(language):
+    def check(language, verbose=True):
         """
         Ensure that external code files exist and check which external files
         have changed from what's in the .rst files. Generate files in the
         if result.missing:
             print("Missing %s files:\n%s" %
                   (language.__name__, "\n".join(result.missing)))
-        for delta in result.deltas:
-            print("%s changed in %s; see %s" %
-                  (delta.file, delta.path, delta.html))
+        if verbose:
+            for delta in result.deltas:
+                print("%s <==> %s; see %s" %
+                    (delta.file, delta.path, delta.html))
         return result
 
+    changed = False # Whether .rst file has changed
+
     @staticmethod
-    def update(language): # Test until it is trustworthy
+    def update(language):
         """
         Refresh external code files into .rst files.
         """
-        check_result = Commands.check(language)
+        force = len(sys.argv) == 3 and sys.argv[2] == '-force'
+        check_result = Commands.check(language, verbose=False)
         if check_result.missing:
             print(language.__name__, "update aborted")
             return
-        changed = False # Whether .rst file has changed
+        if not force and check_result.deltas:
+            print("The following files will be updated when you add -force:")
+            for delta in check_result.deltas:
+                print("%s via %s" % (delta.file, delta.path))
+            print("For details, see corresponding files in _deltas")
+            return
         def _update(matchobj):
             listing = shift(matchobj.group(1))
-            path = listing[0].strip()[len(language.commentTag):].strip()
-            #filename = os.path.basename(path).split('.')[0]
-            path = os.path.join("..", "code", path)
+            path = os.path.join("..", "code",
+                listing[0].strip()[len(language.commentTag):].strip())
             code = open(path).read().splitlines()
             if difference(listing, code):
-                global changed
-                changed = True
+                Commands.changed = True
             return language.codeMarker + \
                 "\n".join([("    " + line).rstrip() for line in code])
-        for f in testFiles:
-            changed = False
+        for f in restFiles:
+            Commands.changed = False
             updated = language.listings.sub(_update, open(f).read())
-            if changed:
-                print(f + " changed")
+            if Commands.changed:
+                print("updating %s" % f)
                 open(f, 'w').write(updated)
 
 if __name__ == "__main__":

src/Comprehensions.rst

 A More Complex Example
 ==============================================================================
 
-..  note:: This is still under development. After finishing, it will get a full
-           description of all parts.
+..  note:: This will get a full description of all parts.
 
 ::
 
             for language in inspect.getmembers(Languages, inspect.isclass):
                 commands[sys.argv[1]](language[1])
 
-           

src/UnitTesting.rst

-
-********************************************************************************
-Unit Testing & Test-Driven Development
-********************************************************************************
-
-..  note:: This chapter has not had any significant translation yet. Should
-           introduce and compare the various common test systems.
-
-One of the important recent realizations is the dramatic value of unit testing.
-
-This is the process of building integrated tests into all the code that you
-create, and running those tests every time you do a build. It's as if you are
-extending the compiler, telling it more about what your program is supposed to
-do. That way, the build process can check for more than just syntax errors,
-since you teach it how to check for semantic errors as well.
-
-C-style programming languages, and C++ in particular, have typically valued
-performance over programming safety. The reason that developing programs in Java
-is so much faster than in C++ (roughly twice as fast, by most accounts) is
-because of Java's safety net: features like better type checking, enforced
-exceptions and garbage collection. By integrating unit testing into your build
-process, you are extending this safety net, and the result is that you can
-develop faster. You can also be bolder in the changes that you make, and more
-easily refactor your code when you discover design or implementation flaws, and
-in general produce a better product, faster.
-
-Unit testing is not generally considered a design pattern; in fact, it might be
-considered a "development pattern," but perhaps there are enough "pattern"
-phrases in the world already. Its effect on development is so significant that
-it will be used throughout this book, and thus will be introduced here.
-
-My own experience with unit testing began when I realized that every program in
-a book must be automatically extracted and organized into a source tree, along
-with appropriate makefiles (or some equivalent technology) so that you could
-just type **make** to build the whole tree. The effect of this process on the
-code quality of the book was so immediate and dramatic that it soon became (in
-my mind) a requisite for any programming book-how can you trust code that you
-didn't compile? I also discovered that if I wanted to make sweeping changes, I
-could do so using search-and-replace throughout the book, and also bashing the
-code around at will. I knew that if I introduced a flaw, the code extractor and
-the makefiles would flush it out.
-
-As programs became more complex, however, I also found that there was a serious
-hole in my system. Being able to successfully compile programs is clearly an
-important first step, and for a published book it seemed a fairly revolutionary
-one-usually due to the pressures of publishing, it's quite typical to randomly
-open a programming book and discover a coding flaw. However, I kept getting
-messages from readers reporting semantic problems in my code (in *Thinking in
-Java*). These problems could only be discovered by running the code. Naturally,
-I understood this and had taken some early faltering steps towards implementing
-a system that would perform automatic execution tests, but I had succumbed to
-the pressures of publishing, all the while knowing that there was definitely
-something wrong with my process and that it would come back to bite me in the
-form of embarrassing bug reports (in the open source world, embarrassment is one
-of the prime motivating factors towards increasing the quality of one's code!).
-
-The other problem was that I was lacking a structure for the testing system.
-Eventually, I started hearing about unit testing and Junit [#]_, which provided
-a basis for a testing structure. However, even though JUnit is intended to make
-the creation of test code easy, I wanted to see if I could make it even easier,
-applying the Extreme Programming principle of "do the simplest thing that could
-possibly work" as a starting point, and then evolving the system as usage
-demands (In addition, I wanted to try to reduce the amount of test code, in an
-attempt to fit more functionality in less code for screen presentations). This
-chapter is the result.
-
-Write Tests First
-=======================================================================
-
-As I mentioned, one of the problems that I encountered-that most people
-encounter, it turns out-was submitting to the pressures of publishing and as a
-result letting tests fall by the wayside. This is easy to do if you forge ahead
-and write your program code because there's a little voice that tells you that,
-after all, you've got it working now, and wouldn't it be more
-interesting/useful/expedient to just go on and write that other part (we can
-always go back and write the tests later). As a result, the tests take on less
-importance, as they often do in a development project.
-
-The answer to this problem, which I first found described in *Extreme
-Programming Explained*, is to write the tests *before* you write the code. This
-may seem to artificially force testing to the forefront of the development
-process, but what it actually does is to give testing enough additional value to
-make it essential. If you write the tests first, you:
-
-#.  Describe what the code is supposed to do, not with some external graphical
-    tool but with code that actually lays the specification down in concrete,
-    verifiable terms.
-
-#.  Provide an example of how the code should be used; again, this is a working,
-    tested example, normally showing all the important method calls, rather than
-    just an academic description of a library.
-
-#.  Provide a way to verify when the code is finished (when all the tests run
-    correctly).
-
-Thus, if you write the tests first then testing becomes a development tool, not
-just a verification step that can be skipped if you happen to feel comfortable
-about the code that you just wrote (a comfort, I have found, that is usually
-wrong).
-
-You can find convincing arguments in *Extreme Programming Explained*, as "write
-tests first" is a fundamental principle of XP. If you aren't convinced you need
-to adopt any of the changes suggested by XP, note that according to Software
-Engineering Institute (SEI) studies, nearly 70% of software organizations are
-stuck in the first two levels of SEI's scale of sophistication: chaos, and
-slightly better than chaos. If you change nothing else, add automated testing.
-
-Simple Python Testing
-=======================================================================
-
-Sanity check for a quick test of the programs in this book, and to append the
-output of each program (as a string) to its listing::
-
-    # SanityCheck.py
-    #! /usr/bin/env python
-    import string, glob, os
-    # Do not include the following in the automatic
-    # tests:
-    exclude = ("SanityCheck.py", "BoxObserver.py",)
-
-    def visitor(arg, dirname, names):
-        dir = os.getcwd()
-        os.chdir(dirname)
-        try:
-            pyprogs = [p for p in glob.glob('*.py')
-                       if p not in exclude ]
-            if not pyprogs: return
-            print('[' + os.getcwd() + ']')
-            for program in pyprogs:
-                print('\t', program)
-                os.system("python %s > tmp" % program)
-                file = open(program).read()
-                output = open('tmp').read()
-                # Append output if it's not already there:
-                if file.find("output = '''") == -1 and \
-                  len(output) > 0:
-                    divider = '#' * 50 + '\n'
-                    file = file.replace('#' + ':~', '#<hr>\n')
-                    file += "output = '''\n" + \
-                      open('tmp').read() + "'''\n"
-                    open(program,'w').write(file)
-        finally:
-            os.chdir(dir)
-
-    if __name__ == "__main__":
-        os.path.walk('.', visitor, None)
-
-
-Just run this from the root directory of the code listings for the book; it will
-descend into each subdirectory and run the program there. An easy way to check
-things is to redirect standard output to a file, then if there are any errors
-they will be the only thing that appears at the console during program
-execution.
-
-A Very Simple Framework
-=======================================================================
-
-As mentioned, a primary goal of this code is to make the writing of unit testing
-code very simple, even simpler than with JUnit. As further needs are discovered
-*during the use* of this system, then that functionality can be added, but to
-start with the framework will just provide a way to easily create and run tests,
-and report failure if something breaks (success will produce no results other
-than normal output that may occur during the running of the test). My intended
-use of this framework is in makefiles, and **make** aborts if there is a non-
-zero return value from the execution of a command. The build process will
-consist of compilation of the programs and execution of unit tests, and if
-**make** gets all the way through successfully then the system will be
-validated, otherwise it will abort at the place of failure. The error messages
-will report the test that failed but not much else, so that you can provide
-whatever granularity that you need by writing as many tests as you want, each
-one covering as much or as little as you find necessary.
-
-In some sense, this framework provides an alternative place for all those
-"print" statements I've written and later erased over the years.
-
-To create a set of tests, you start by making a **static** inner class inside
-the class you wish to test (your test code may also test other classes; it's up
-to you). This test code is distinguished by inheriting from **UnitTest**::
-
-    # UnitTesting/UnitTest.py
-    # The basic unit testing class
-
-    class UnitTest:
-        testID = ""
-        static List errors = ArrayList()
-        # Override cleanup() if test object
-        # creation allocates non-memory
-        # resources that must be cleaned up:
-        def cleanup(self):
-        # Verify the truth of a condition:
-        def affirm(boolean condition):
-            if(!condition)
-                errors.add("failed: " + testID)
-
-
-The only testing method [[ So far ]] is **affirm( )** [#]_, which is
-**protected** so that it can be used from the inheriting class. All this method
-does is verify that something is **true**. If not, it adds an error to the list,
-reporting that the current test (established by the **static testID**, which is
-set by the test-running program that you shall see shortly) has failed. Although
-this is not a lot of information-you might also wish to have the line number,
-which could be extracted from an exception-it may be enough for most situations.
-
-Unlike JUnit (which uses **setUp( )** and **tearDown( )** methods), test objects
-will be built using ordinary Python construction. You define the test objects by
-creating them as ordinary class members of the test class, and a new test class
-object will be created for each test method (thus preventing any problems that
-might occur from side effects between tests). Occasionally, the creation of a
-test object will allocate non-memory resources, in which case you must override
-**cleanup( )** to release those resources.
-
-Writing Tests
-=======================================================================
-
-Writing tests becomes very simple. Here's an example that creates the necessary
-**static** inner class and performs trivial tests::
-
-    # UnitTesting/TestDemo.py
-    # Creating a test
-
-    class TestDemo:
-        objCounter = 0
-        id = ++objCounter
-        def TestDemo(String s):
-            print(s + ": count = " + id)
-
-        def close(self):
-            print("Cleaning up: " + id)
-
-        def someCondition(self): return True
-        class Test(UnitTest):
-            TestDemo test1 = TestDemo("test1")
-            TestDemo test2 = TestDemo("test2")
-            def cleanup(self):
-                test2.close()
-                test1.close()
-
-            def testA(self):
-                print("TestDemo.testA")
-                affirm(test1.someCondition())
-
-            def testB(self):
-                print("TestDemo.testB")
-                affirm(test2.someCondition())
-                affirm(TestDemo.objCounter != 0)
-
-            # Causes the build to halt:
-            #! def test3(): affirm(0)
-
-
-The **test3( )**  method is commented out because, as you'll see, it causes the
-automatic build of this book's source-code tree to stop.
-
-You can name your inner class anything you'd like; the only important factor is
-that it **extends UnitTest**. You can also include any necessary support code in
-other methods. Only **public** methods that take no arguments and return
-**void** will be treated as tests (the names of these methods are also not
-constrained).
-
-The above test class creates two instances of **TestDemo**. The **TestDemo**
-constructor prints something, so that we can see it being called. You could also
-define a default constructor (the only kind that is used by the test framework),
-although none is necessary here. The **TestDemo** class has a **close( )**
-method which suggests it is used as part of object cleanup, so this is called in
-the overridden **cleanup( )** method in **Test**.
-
-The testing methods use the **affirm( )** method to validate expressions, and if
-there is a failure the information is stored and printed after all the tests are
-run.  Of course, the **affirm( )** arguments are usually more complicated than
-this; you'll see more examples throughout the rest of this book.
-
-Notice that in **testB( )**, the **private** field **objCounter** is accessible
-to the testing code-this is because **Test** has the permissions of an inner
-class.
-
-You can see that writing test code requires very little extra effort, and no
-knowledge other than that used for writing ordinary classes.
-
-To run the tests, you use **RunUnitTests.py** (which will be introduced
-shortly). The command for the above code looks like this:
-
-**java com.bruceeckel.test.RunUnitTests TestDemo**
-
-It produces the following output::
-
-    test1: count = 1
-    test2: count = 2
-    TestDemo.testA
-    Cleaning up: 2
-    Cleaning up: 1
-    test1: count = 3
-    test2: count = 4
-    TestDemo.testB
-    Cleaning up: 4
-    Cleaning up: 3
-
-
-All the output is noise as far as the success or failure of the unit testing is
-concerned. Only if one or more of the unit tests fail does the program returns a
-non-zero value to terminate the **make** process after the error messages are
-produced. Thus, you can choose to produce output or not, as it suits your needs,
-and the test class becomes a good place to put any printing code you might need-
-if you do this, you tend to keep such code around rather than putting it in and
-stripping it out as is typically done with tracing code.
-
-If you need to add a test to a class derived from one that already has a test
-class, it's no problem, as you can see here::
-
-    # UnitTesting/TestDemo2.py
-    # Inheriting from a class that
-    # already has a test is no problem.
-
-    class TestDemo2(TestDemo):
-        def __init__(self, s): TestDemo.__init__(s)
-        # You can even use the same name
-        # as the test class in the base class:
-        class Test(UnitTest):
-            def testA(self):
-                print("TestDemo2.testA")
-                affirm(1 + 1 == 2)
-
-            def testB(self):
-                print("TestDemo2.testB")
-                affirm(2 * 2 == 4)
-
-
-Even the name of the inner class can be the same. In the above code, all the
-assertions are always true so the tests will never fail.
-
-White-Box & Black-Box Tests
-=======================================================================
-
-The unit test examples so far are what are traditionally called *white-box
-tests*. This means that the test code has complete access to the internals of
-the class that's being tested (so it might be more appropriately called
-"transparent box" testing). White-box testing happens automatically when you
-make the unit test class as an inner class of the class being tested, since
-inner classes automatically have access to all their outer class elements, even
-those that are **private**.
-
-A possibly more common form of testing is *black-box testing*, which refers to
-treating the class under test as an impenetrable box. You can't see the
-internals; you can only access the **public** portions of the class. Thus,
-black-box testing corresponds more closely to functional testing, to verify the
-methods that the client programmer is going to use. In addition, black-box
-testing provides a minimal instruction sheet to the client programmer - in the
-absence of all other documentation, the black-box tests at least demonstrate how
-to make basic calls to the **public** class methods.
-
-To perform black-box tests using the unit-testing framework presented in this
-book, all you need to do is create your test class as a global class instead of
-an inner class. All the other rules are the same (for example, the unit test
-class must be **public**, and derived from **UnitTest**).
-
-There's one other caveat, which will also provide a little review of Java
-packages. If you want to be completely rigorous, you must put your black-box
-test class in a separate directory than the class it tests, otherwise it will
-have package access to the elements of the class being tested. That is, you'll
-be able to access **protected** and **friendly** elements of the class being
-tested. Here's an example::
-
-    # UnitTesting/Testable.py
-
-    class Testable:
-        def f1(): pass
-        def f2(self): pass # "Friendly": package access
-        def f3(self): pass # Also package access
-        def f4(self): pass
-
-
-Normally, the only method that should be directly accessible to the client
-programmer is **f4( )**. However, if you put your black-box test in the same
-directory, it automatically becomes part of the same package (in this case, the
-default package since none is specified) and then has inappropriate access::
-
-    # UnitTesting/TooMuchAccess.py
-
-    class TooMuchAccess(UnitTest):
-        Testable tst = Testable()
-        def test1(self):
-            tst.f2() # Oops!
-            tst.f3() # Oops!
-            tst.f4() # OK
-
-
-You can solve the problem by moving **TooMuchAccess.py** into its own
-subdirectory, thereby putting it in its own default package (thus a different
-package from **Testable.py**). Of course, when you do this, then **Testable**
-must be in its own package, so that it can be imported (note that it is also
-possible to import a "package-less" class by giving the class name in the
-**import** statement and ensuring that the class is in your CLASSPATH)::
-
-    # UnitTesting/testable/Testable.py
-    package c02.testable
-
-    class Testable:
-        def f1(): pass
-        def f2(self): # "Friendly": package access
-        def f3(self): # Also package access
-        def f4(self):
-
-
-Here's the black-box test in its own package, showing how only public methods
-may be called::
-
-    # UnitTesting/BlackBoxTest.py
-
-    class BlackBoxTest(UnitTest):
-        Testable tst = Testable()
-        def test1(self):
-            #! tst.f2() # Nope!
-            #! tst.f3() # Nope!
-            tst.f4() # Only public methods available
-
-
-Note that the above program is indeed very similar to the one that the client
-programmer would write to use your class, including the imports and available
-methods. So it does make a good programming example. Of course, it's easier from
-a coding standpoint to just make an inner class, and unless you're ardent about
-the need for specific black-box testing you may just want to go ahead and use
-the inner classes (with the knowledge that if you need to you can later extract
-the inner classes into separate black-box test classes, without too much
-effort).
-
-Running tests
-=======================================================================
-
-The program that runs the tests makes significant use of reflection so that
-writing the tests can be simple for the client programmer::
-
-    # UnitTesting/RunUnitTests.py
-    # Discovering the unit test
-    # class and running each test.
-
-    class RunUnitTests:
-        def require(requirement, errmsg):
-            if(!requirement):
-                print(errmsg)
-                sys.exit()
-
-        def main(self, args):
-            require(args.length == 1,
-              "Usage: RunUnitTests qualified-class")
-            try:
-                Class c = Class.forName(args[0])
-                # Only finds the inner classes
-                # declared in the current class:
-                Class[] classes = c.getDeclaredClasses()
-                Class ut = null
-                for(int j = 0 j < classes.length j++):
-                    # Skip inner classes that are
-                    # not derived from UnitTest:
-                    if(!UnitTest.class.
-                        isAssignableFrom(classes[j]))
-                        continue
-                    ut = classes[j]
-                    break # Finds the first test class only
-
-                # If it found an inner class,
-                # that class must be static:
-                if(ut != null)
-                    require(
-                      Modifier.isStatic(ut.getModifiers()),
-                      "inner UnitTest class must be static")
-                # If it couldn't find the inner class,
-                # maybe it's a regular class (for black-
-                # box testing:
-                if(ut == null)
-                    if(UnitTest.class.isAssignableFrom(c))
-                        ut = c
-                require(ut != null,
-                  "No UnitTest class found")
-                require(
-                  Modifier.isPublic(ut.getModifiers()),
-                  "UnitTest class must be public")
-                Method[] methods = ut.getDeclaredMethods()
-                for(int k = 0 k < methods.length k++):
-                    Method m = methods[k]
-                    # Ignore overridden UnitTest methods:
-                    if(m.getName().equals("cleanup"))
-                        continue
-                    # Only public methods with no
-                    # arguments and void return
-                    # types will be used as test code:
-                    if(m.getParameterTypes().length == 0 &&
-                       m.getReturnType() == void.class &&
-                       Modifier.isPublic(m.getModifiers())):
-                        # The name of the test is
-                        # used in error messages:
-                        UnitTest.testID = m.getName()
-                        # A instance of the
-                        # test object is created and
-                        # cleaned up for each test:
-                        Object test = ut.newInstance()
-                        m.invoke(test, Object[0])
-                        ((UnitTest)test).cleanup()
-
-            except e:
-                e.printStackTrace(System.err)
-                # Any exception will return a nonzero
-                # value to the console, so that
-                # 'make' will abort:
-                System.err.println("Aborting make")
-                System.exit(1)
-
-            # After all tests in this class are run,
-            # display any results. If there were errors,
-            # abort 'make' by returning a nonzero value.
-            if(UnitTest.errors.size() != 0):
-                it = UnitTest.errors.iterator()
-                while(it.hasNext()):
-                    print(it.next())
-                sys.exit(1)
-
-
-Automatically Executing Tests
-=======================================================================
-
-Exercises
-=======================================================================
-
-#.  Install this book's source code tree and ensure that you have a **make**
-    utility installed on your system (Gnu **make** is freely available on the
-    internet at various locations). In **TestDemo.py**, un-comment **test3( )**,
-    then type **make** and observe the results.
-
-#.  Modify TestDemo.py by adding a new test that throws an exception. Type
-    **make** and observe the results.
-
-#.  Modify your solutions to the exercises in Chapter 1 by adding unit tests.
-    Write makefiles that incorporate the unit tests.
-
-.. rubric:: Footnotes
-
-.. [#] *http://www.junit.org*
-
-.. [#] I had originally called this **assert()**, but that word became reserved
-       in JDK 1.4 when assertions were added to the language.
-
-
+
+********************************************************************************
+Unit Testing & Test-Driven Development
+********************************************************************************
+
+..  note:: This chapter has not had any significant translation yet. Should
+           introduce and compare the various common test systems.
+
+One of the important recent realizations is the dramatic value of unit testing.
+
+This is the process of building integrated tests into all the code that you
+create, and running those tests every time you do a build. It's as if you are
+extending the compiler, telling it more about what your program is supposed to
+do. That way, the build process can check for more than just syntax errors,
+since you teach it how to check for semantic errors as well.
+
+C-style programming languages, and C++ in particular, have typically valued
+performance over programming safety. The reason that developing programs in Java
+is so much faster than in C++ (roughly twice as fast, by most accounts) is
+because of Java's safety net: features like better type checking, enforced
+exceptions and garbage collection. By integrating unit testing into your build
+process, you are extending this safety net, and the result is that you can
+develop faster. You can also be bolder in the changes that you make, and more
+easily refactor your code when you discover design or implementation flaws, and
+in general produce a better product, faster.
+
+Unit testing is not generally considered a design pattern; in fact, it might be
+considered a "development pattern," but perhaps there are enough "pattern"
+phrases in the world already. Its effect on development is so significant that
+it will be used throughout this book, and thus will be introduced here.
+
+My own experience with unit testing began when I realized that every program in
+a book must be automatically extracted and organized into a source tree, along
+with appropriate makefiles (or some equivalent technology) so that you could
+just type **make** to build the whole tree. The effect of this process on the
+code quality of the book was so immediate and dramatic that it soon became (in
+my mind) a requisite for any programming book-how can you trust code that you
+didn't compile? I also discovered that if I wanted to make sweeping changes, I
+could do so using search-and-replace throughout the book, and also bashing the
+code around at will. I knew that if I introduced a flaw, the code extractor and
+the makefiles would flush it out.
+
+As programs became more complex, however, I also found that there was a serious
+hole in my system. Being able to successfully compile programs is clearly an
+important first step, and for a published book it seemed a fairly revolutionary
+one-usually due to the pressures of publishing, it's quite typical to randomly
+open a programming book and discover a coding flaw. However, I kept getting
+messages from readers reporting semantic problems in my code (in *Thinking in
+Java*). These problems could only be discovered by running the code. Naturally,
+I understood this and had taken some early faltering steps towards implementing
+a system that would perform automatic execution tests, but I had succumbed to
+the pressures of publishing, all the while knowing that there was definitely
+something wrong with my process and that it would come back to bite me in the
+form of embarrassing bug reports (in the open source world, embarrassment is one
+of the prime motivating factors towards increasing the quality of one's code!).
+
+The other problem was that I was lacking a structure for the testing system.
+Eventually, I started hearing about unit testing and Junit [#]_, which provided
+a basis for a testing structure. However, even though JUnit is intended to make
+the creation of test code easy, I wanted to see if I could make it even easier,
+applying the Extreme Programming principle of "do the simplest thing that could
+possibly work" as a starting point, and then evolving the system as usage
+demands (In addition, I wanted to try to reduce the amount of test code, in an
+attempt to fit more functionality in less code for screen presentations). This
+chapter is the result.
+
+Write Tests First
+=======================================================================
+
+As I mentioned, one of the problems that I encountered-that most people
+encounter, it turns out-was submitting to the pressures of publishing and as a
+result letting tests fall by the wayside. This is easy to do if you forge ahead
+and write your program code because there's a little voice that tells you that,
+after all, you've got it working now, and wouldn't it be more
+interesting/useful/expedient to just go on and write that other part (we can
+always go back and write the tests later). As a result, the tests take on less
+importance, as they often do in a development project.
+
+The answer to this problem, which I first found described in *Extreme
+Programming Explained*, is to write the tests *before* you write the code. This
+may seem to artificially force testing to the forefront of the development
+process, but what it actually does is to give testing enough additional value to
+make it essential. If you write the tests first, you:
+
+#.  Describe what the code is supposed to do, not with some external graphical
+    tool but with code that actually lays the specification down in concrete,
+    verifiable terms.
+
+#.  Provide an example of how the code should be used; again, this is a working,
+    tested example, normally showing all the important method calls, rather than
+    just an academic description of a library.
+
+#.  Provide a way to verify when the code is finished (when all the tests run
+    correctly).
+
+Thus, if you write the tests first then testing becomes a development tool, not
+just a verification step that can be skipped if you happen to feel comfortable
+about the code that you just wrote (a comfort, I have found, that is usually
+wrong).
+
+You can find convincing arguments in *Extreme Programming Explained*, as "write
+tests first" is a fundamental principle of XP. If you aren't convinced you need
+to adopt any of the changes suggested by XP, note that according to Software
+Engineering Institute (SEI) studies, nearly 70% of software organizations are
+stuck in the first two levels of SEI's scale of sophistication: chaos, and
+slightly better than chaos. If you change nothing else, add automated testing.
+
+Simple Python Testing
+=======================================================================
+
+Sanity check for a quick test of the programs in this book, and to append the
+output of each program (as a string) to its listing::
+
+    # SanityCheck.py
+    #! /usr/bin/env python
+    import string, glob, os
+    # Do not include the following in the automatic tests:
+    exclude = ("SanityCheck.py", "BoxObserver.py",)
+
+    def visitor(arg, dirname, names):
+        dir = os.getcwd()
+        os.chdir(dirname)
+        try:
+            pyprogs = [p for p in glob.glob('*.py') if p not in exclude ]
+            if not pyprogs: return
+            print('[' + os.getcwd() + ']')
+            for program in pyprogs:
+                print('\t', program)
+                os.system("python %s > tmp" % program)
+                file = open(program).read()
+                output = open('tmp').read()
+                # Append program output if it's not already there:
+                if file.find("output = '''") == -1 and len(output) > 0:
+                    divider = '#' * 50 + '\n'
+                    file = file.replace('#' + ':~', '#<hr>\n')
+                    file += "output = '''\n" + open('tmp').read() + "'''\n"
+                    open(program,'w').write(file)
+        finally:
+            os.chdir(dir)
+
+    if __name__ == "__main__":
+        os.path.walk('.', visitor, None)
+
+
+Just run this from the root directory of the code listings for the book; it will
+descend into each subdirectory and run the program there. An easy way to check
+things is to redirect standard output to a file, then if there are any errors
+they will be the only thing that appears at the console during program
+execution.
+
+A Very Simple Framework
+=======================================================================
+
+As mentioned, a primary goal of this code is to make the writing of unit testing
+code very simple, even simpler than with JUnit. As further needs are discovered
+*during the use* of this system, then that functionality can be added, but to
+start with the framework will just provide a way to easily create and run tests,
+and report failure if something breaks (success will produce no results other
+than normal output that may occur during the running of the test). My intended
+use of this framework is in makefiles, and **make** aborts if there is a non-
+zero return value from the execution of a command. The build process will
+consist of compilation of the programs and execution of unit tests, and if
+**make** gets all the way through successfully then the system will be
+validated, otherwise it will abort at the place of failure. The error messages
+will report the test that failed but not much else, so that you can provide
+whatever granularity that you need by writing as many tests as you want, each
+one covering as much or as little as you find necessary.
+
+In some sense, this framework provides an alternative place for all those
+"print" statements I've written and later erased over the years.
+
+To create a set of tests, you start by making a **static** inner class inside
+the class you wish to test (your test code may also test other classes; it's up
+to you). This test code is distinguished by inheriting from **UnitTest**::
+
+    # UnitTesting/UnitTest.py
+    # The basic unit testing class
+
+    class UnitTest:
+        testID = ""
+        errors = []
+        # Override cleanup() if test object creation allocates non-memory
+        # resources that must be cleaned up:
+        def cleanup(self): pass
+        # Verify a condition is true:
+        def affirm(condition):
+            if(!condition)
+                UnitTest.errors.append("failed: " + UnitTest.testID)
+
+
+The only testing method [[ So far ]] is **affirm( )** [#]_, which is
+**protected** so that it can be used from the inheriting class. All this method
+does is verify that something is **true**. If not, it adds an error to the list,
+reporting that the current test (established by the **static testID**, which is
+set by the test-running program that you shall see shortly) has failed. Although
+this is not a lot of information-you might also wish to have the line number,
+which could be extracted from an exception-it may be enough for most situations.
+
+Unlike JUnit (which uses **setUp( )** and **tearDown( )** methods), test objects
+will be built using ordinary Python construction. You define the test objects by
+creating them as ordinary class members of the test class, and a new test class
+object will be created for each test method (thus preventing any problems that
+might occur from side effects between tests). Occasionally, the creation of a
+test object will allocate non-memory resources, in which case you must override
+**cleanup( )** to release those resources.
+
+Writing Tests
+=======================================================================
+
+Writing tests becomes very simple. Here's an example that creates the necessary
+**static** inner class and performs trivial tests::
+
+    # UnitTesting/TestDemo.py
+    # Creating a test
+
+    class TestDemo:
+        objCounter = 0
+        id = ++objCounter
+        def TestDemo(String s):
+            print(s + ": count = " + id)
+
+        def close(self):
+            print("Cleaning up: " + id)
+
+        def someCondition(self): return True
+        class Test(UnitTest):
+            TestDemo test1 = TestDemo("test1")
+            TestDemo test2 = TestDemo("test2")
+            def cleanup(self):
+                test2.close()
+                test1.close()
+
+            def testA(self):
+                print("TestDemo.testA")
+                affirm(test1.someCondition())
+
+            def testB(self):
+                print("TestDemo.testB")
+                affirm(test2.someCondition())
+                affirm(TestDemo.objCounter != 0)
+
+            # Causes the build to halt:
+            #! def test3(): affirm(0)
+
+
+The **test3( )**  method is commented out because, as you'll see, it causes the
+automatic build of this book's source-code tree to stop.
+
+You can name your inner class anything you'd like; the only important factor is
+that it **extends UnitTest**. You can also include any necessary support code in
+other methods. Only **public** methods that take no arguments and return
+**void** will be treated as tests (the names of these methods are also not
+constrained).
+
+The above test class creates two instances of **TestDemo**. The **TestDemo**
+constructor prints something, so that we can see it being called. You could also
+define a default constructor (the only kind that is used by the test framework),
+although none is necessary here. The **TestDemo** class has a **close( )**
+method which suggests it is used as part of object cleanup, so this is called in
+the overridden **cleanup( )** method in **Test**.
+
+The testing methods use the **affirm( )** method to validate expressions, and if
+there is a failure the information is stored and printed after all the tests are
+run.  Of course, the **affirm( )** arguments are usually more complicated than
+this; you'll see more examples throughout the rest of this book.
+
+Notice that in **testB( )**, the **private** field **objCounter** is accessible
+to the testing code-this is because **Test** has the permissions of an inner
+class.
+
+You can see that writing test code requires very little extra effort, and no
+knowledge other than that used for writing ordinary classes.
+
+To run the tests, you use **RunUnitTests.py** (which will be introduced
+shortly). The command for the above code looks like this:
+
+**java com.bruceeckel.test.RunUnitTests TestDemo**
+
+It produces the following output::
+
+    test1: count = 1
+    test2: count = 2
+    TestDemo.testA
+    Cleaning up: 2
+    Cleaning up: 1
+    test1: count = 3
+    test2: count = 4
+    TestDemo.testB
+    Cleaning up: 4
+    Cleaning up: 3
+
+
+All the output is noise as far as the success or failure of the unit testing is
+concerned. Only if one or more of the unit tests fail does the program returns a
+non-zero value to terminate the **make** process after the error messages are
+produced. Thus, you can choose to produce output or not, as it suits your needs,
+and the test class becomes a good place to put any printing code you might need-
+if you do this, you tend to keep such code around rather than putting it in and
+stripping it out as is typically done with tracing code.
+
+If you need to add a test to a class derived from one that already has a test
+class, it's no problem, as you can see here::
+
+    # UnitTesting/TestDemo2.py
+    # Inheriting from a class that
+    # already has a test is no problem.
+
+    class TestDemo2(TestDemo):
+        def __init__(self, s): TestDemo.__init__(s)
+        # You can even use the same name
+        # as the test class in the base class:
+        class Test(UnitTest):
+            def testA(self):
+                print("TestDemo2.testA")
+                affirm(1 + 1 == 2)
+
+            def testB(self):
+                print("TestDemo2.testB")
+                affirm(2 * 2 == 4)
+
+
+Even the name of the inner class can be the same. In the above code, all the
+assertions are always true so the tests will never fail.
+
+White-Box & Black-Box Tests
+=======================================================================
+
+The unit test examples so far are what are traditionally called *white-box
+tests*. This means that the test code has complete access to the internals of
+the class that's being tested (so it might be more appropriately called
+"transparent box" testing). White-box testing happens automatically when you
+make the unit test class as an inner class of the class being tested, since
+inner classes automatically have access to all their outer class elements, even
+those that are **private**.
+
+A possibly more common form of testing is *black-box testing*, which refers to
+treating the class under test as an impenetrable box. You can't see the
+internals; you can only access the **public** portions of the class. Thus,
+black-box testing corresponds more closely to functional testing, to verify the
+methods that the client programmer is going to use. In addition, black-box
+testing provides a minimal instruction sheet to the client programmer - in the
+absence of all other documentation, the black-box tests at least demonstrate how
+to make basic calls to the **public** class methods.
+
+To perform black-box tests using the unit-testing framework presented in this
+book, all you need to do is create your test class as a global class instead of
+an inner class. All the other rules are the same (for example, the unit test
+class must be **public**, and derived from **UnitTest**).
+
+There's one other caveat, which will also provide a little review of Java
+packages. If you want to be completely rigorous, you must put your black-box
+test class in a separate directory than the class it tests, otherwise it will
+have package access to the elements of the class being tested. That is, you'll
+be able to access **protected** and **friendly** elements of the class being
+tested. Here's an example::
+
+    # UnitTesting/Testable.py
+
+    class Testable:
+        def f1(): pass
+        def f2(self): pass # "Friendly": package access
+        def f3(self): pass # Also package access
+        def f4(self): pass
+
+
+Normally, the only method that should be directly accessible to the client
+programmer is **f4( )**. However, if you put your black-box test in the same
+directory, it automatically becomes part of the same package (in this case, the
+default package since none is specified) and then has inappropriate access::
+
+    # UnitTesting/TooMuchAccess.py
+
+    class TooMuchAccess(UnitTest):
+        Testable tst = Testable()
+        def test1(self):
+            tst.f2() # Oops!
+            tst.f3() # Oops!
+            tst.f4() # OK
+
+
+You can solve the problem by moving **TooMuchAccess.py** into its own
+subdirectory, thereby putting it in its own default package (thus a different
+package from **Testable.py**). Of course, when you do this, then **Testable**
+must be in its own package, so that it can be imported (note that it is also
+possible to import a "package-less" class by giving the class name in the
+**import** statement and ensuring that the class is in your CLASSPATH)::
+
+    # UnitTesting/testable/Testable.py
+    package c02.testable
+
+    class Testable:
+        def f1(): pass
+        def f2(self): # "Friendly": package access
+        def f3(self): # Also package access
+        def f4(self):
+
+
+Here's the black-box test in its own package, showing how only public methods
+may be called::
+
+    # UnitTesting/BlackBoxTest.py
+
+    class BlackBoxTest(UnitTest):
+        Testable tst = Testable()
+        def test1(self):
+            #! tst.f2() # Nope!
+            #! tst.f3() # Nope!
+            tst.f4() # Only public methods available
+
+
+Note that the above program is indeed very similar to the one that the client
+programmer would write to use your class, including the imports and available
+methods. So it does make a good programming example. Of course, it's easier from
+a coding standpoint to just make an inner class, and unless you're ardent about
+the need for specific black-box testing you may just want to go ahead and use
+the inner classes (with the knowledge that if you need to you can later extract
+the inner classes into separate black-box test classes, without too much
+effort).
+
+Running tests
+=======================================================================
+
+The program that runs the tests makes significant use of reflection so that
+writing the tests can be simple for the client programmer::
+
+    # UnitTesting/RunUnitTests.py
+    # Discovering the unit test
+    # class and running each test.
+
+    class RunUnitTests:
+        def require(requirement, errmsg):
+            if(!requirement):
+                print(errmsg)
+                sys.exit()
+
+        def main(self, args):
+            require(args.length == 1,
+              "Usage: RunUnitTests qualified-class")
+            try:
+                Class c = Class.forName(args[0])
+                # Only finds the inner classes
+                # declared in the current class:
+                Class[] classes = c.getDeclaredClasses()
+                Class ut = null
+                for(int j = 0 j < classes.length j++):
+                    # Skip inner classes that are
+                    # not derived from UnitTest:
+                    if(!UnitTest.class.
+                        isAssignableFrom(classes[j]))
+                        continue
+                    ut = classes[j]
+                    break # Finds the first test class only
+
+                # If it found an inner class,
+                # that class must be static: