[FAQTS] Python Knowledge Base Update -- May 23rd, 2000

Fiona Czuczman fiona at sitegnome.com
Tue May 23 09:05:53 EDT 2000


Hi!

Below are the entries I've entered tonight into http://python.faqts.com

- Fiona


## New Entries #################################################


-------------------------------------------------------------
How can I link python code to a GUI interface generated by Glade or GTK or whatever please?
http://www.faqts.com/knowledge-base/view.phtml/aid/3171
-------------------------------------------------------------
Fiona Czuczman
Mitch Chapman

Here's an example.  Two files are attached.

GladeBase.py provides two base classes.  Class UI creates a widget 
hierarchy from a Glade file.  Class Controller provides an  MVC-style 
controller for the UI.  The main() function of the module  shows how to 
use these base classes to build and control a GUI.

ui.glade is a simple user interface created using Glade.  If you plop it 
into the same directory with GladeBase.py and then run GladeBase.py, you 
should get an application window on your display.

The cool part about James Henstridge's libglade, on which this example
is based, is the way it wires up callback routines.  You pass it a 
dictionary of callable objects, keyed by name.  It roots through the 
Glade-based user interface hierarchy, and for every connected signal 
declared in the interface, it looks for a callable of the same name in 
the callback dictionary.  If it finds one, it plugs it in.  It's cheap 
and easy.

In the example, Controller._connectToUI() assumes that you will 
derive from class Controller and define all of the callback methods 
in the derived class.

Hoping this helps...

---

#!/usr/bin/env python
"""This is an example of accessing Glade-built UIs from Python."""
import gnome.ui, gtk, libglade

class UI(libglade.GladeXML):
    """Base class for all UIs loaded from glade."""
    def __init__(self, filename, rootname):
        """Initialize a new instance."""
        libglade.GladeXML.__init__(self, filename=filename, 
root=rootname)
        self.root = self.get_widget(rootname)

    def show(self):
        """Make the UI visible."""
        self.root.show()

class Controller:
    """Base class for all controllers of glade-derived UIs."""
    def __init__(self, ui):
        """Initialize a new instance.  `ui' is the GladeXML UI to 
control."""
        self.ui = ui
        self._connectToUI()

    def _connectToUI(self):
        """Wire up self to its UI.

        This method assumes that any method defined by self's class
        could be a Gtk+ callback.  It wires up any methods referenced by
        self's ui."""
        names = dir(self.__class__)
        d = {}
        for name in names:
            d[name] = getattr(self, name)

        self.ui.signal_autoconnect(d)

    def show(self):
        """Show the user interface."""
        self.ui.show()

def main():
    """Module mainline (for standalone execution)"""
    class SampleController(Controller):
        def on_pushBtn_clicked(self, *args):
            """Called when the 'push me' button is clicked."""
            print "Thanks for pushing me."
            gtk.mainquit()

        def on_win_delete_event(self, *args):
            """Called when the window is deleted."""
            gtk.mainquit()
            
    theUI = UI("ui.glade", "win")
    theController = SampleController(theUI)
    theController.show()
    gtk.mainloop()
    
if __name__ == "__main__":
    main()

---

CreateWorkspace create_workspace src pixmaps C True True GtkWindow win 
delete_event on_win_delete_event Wed, 03 May 2000 00:16:13
GMT GTK_WINDOW_TOPLEVEL GTK_WIN_POS_NONE False False True False GtkVBox 
vbox1 False 0 GtkLabel label1 Go on, push the
button. GTK_JUSTIFY_CENTER False 0.5 0.5 0 0 0 False False GtkButton 
pushBtn True clicked on_pushBtn_clicked Mon, 22 May 2000
15:28:00 GMT Push Me 0 False False


-------------------------------------------------------------
How can I find out the father class of a given class?
http://www.faqts.com/knowledge-base/view.phtml/aid/3175
-------------------------------------------------------------
Fiona Czuczman
Emile van Sebille

>>> class A:
        pass

>>> class B(A):
        pass

>>> B.__bases__
(<class __main__.A at fc03f0>,)


-------------------------------------------------------------
Is there any difference between the random number generator in the'random' module and that in the 'whrandom' one?
Is there a way to get a reproducible sequence of random numbers?
What's the quality of the numbers generated?
http://www.faqts.com/knowledge-base/view.phtml/aid/3173
-------------------------------------------------------------
Fiona Czuczman
Emile van Sebille, Tim Peters,Jim Richardson, Ivan Frohne

If I'm not mistaken, whrandom is imported by random, and importing
random would be the normal way of accessing it.

You shouldn't use whrandom:  whrandom is an interal implementation 
detail of random.py.  whrandom.py should probably be renamed to 
_whrandom.py (or something) to stop people from tripping over it.

Repeatable sequences can be generated by reseeding with the same value:

>>> import random
>>> random.seed("Spam")
>>> print random.random()
0.188524911272
>>> print random.random()
0.795451892756
>>> print random.random()
0.191986312458
>>> random.seed("Spam")
>>> print random.random()
0.188524911272
>>> print random.random()
0.795451892756
>>> print random.random()
0.191986312458

>>> print random.seed.__doc__
Seed the default generator from any hashable value.

  None or no argument returns (0, 0, 0) to seed from current time.

Regarding the quality:

If you know enough about random numbers to understand an answer to that
question, then telling you it's the standard Wichman-Hill (that's where 
"wh" comes from) generator is all the answer you need <wink>.  
Seriously, test it and determine whether it's adequate for your 
application; if you can't test it objectively, then you have no way of 
knowing whether any other package is adequate either (and neither does 
anyone else, so don't ask).

Ivan Frohne wrote a very nice package of stronger generators, which 
should be available from his Starship page.  But unless you're doing 
extreme work, WH should be adequate for a start.  Any serious program 
relying on random numbers should be tested with at least two distinct 
generators, though, and Ivan's pkg is great for that.

You can find the algorithm used in whrandom.py and random.py (in Fortran 
77) at http://lib.stat.cmu.edu/apstat/183 .  It was published in the 
Journal of Applied Statistics in 1982, and is now a little long in the 
tooth.  The period is about 7e12, which you might think is large, but, 
when you get right down to it, it's not large enough.  In fact, an 
alternative algorithm with period 2e18 is now recommended at the site 
listed above. But the truth of the matter is, random.py will give you 
perfectly fine uniform random numbers for most purposes, if you're not 
too fussy, and don't need hundreds of millions of them.

As an aside, for those using linux, then /dev/random and /dev/urandom
are good reseources for (very nearly) random numbers.


## Edited Entries ##############################################


-------------------------------------------------------------
What's the best way to obtain seeds for random number generators?
http://www.faqts.com/knowledge-base/view.phtml/aid/2770
-------------------------------------------------------------
Fiona Czuczman
Fredrik Lundh, Mike Steed, Ivan Van Laningham, Will Ware, Paul Jackson

RFC 1750 provides a whole lot of information on this topic:

    http://www.faqs.org/rfcs/rfc1750.html

   "Computer clocks, or similar operating system or hardware values,
   provide significantly fewer real bits of unpredictability than might
   appear from their specifications."

Depending on how serious you are about randomness, you may want to use a
hardware source (e.g., an audio input device).  See 8.7 in the following
document:

   http://www.faqs.org/faqs/cryptography-faq/part08/

Also, under linux, see /dev/random.  random.c claims:
 * This routine gathers environmental noise from device drivers, etc.,
 * and returns good random numbers, suitable for cryptographic use.

Will Ware wrote:

If you really need a lot of randomness, and you don't mind spending
an evening or two with a soldering iron, I once made up a pretty
good random bit generator circuit, described at:
http://world.std.com/~wware/hw-rng.html

You can bring the bits in one of the pins of your printer port. I
have some information about a Linux device driver for the thing, if
you're interested in pursuing it, that was developed by some students
who recently used the circuit for a course project.

-----------------

A Random Number web site from SGI is:

    http://lavarand.sgi.com/







More information about the Python-list mailing list