Re: [Tutor] Matrix

2004-12-20 Thread Alan Gauld
> A list of lists is the most logical construction.
> But -- you don't need to assemble the rows separately --
> this works too:
>  >>> my_matrix_as_lists = [ [4, 6, 8, 1],\
> ...   [2, 5, 1, 3],\
> ...   [2, 1, 2, 8] ]

And you don't need the line continuation characters either. 
Because Python can tell that the brackets don't match you 
can just add the newlines directly:

>>> mx = [ [1,2,3,4],
...[5,6,7,8] ]
>>>

Alan g
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing two elements in a list

2004-12-20 Thread Max Noel
On Dec 19, 2004, at 06:16, Jacob S. wrote:
Would this work for you?
a = ['Name = stuff','CGTATAGCTAGCTA','Name = stuff','CGATATGCCGGCTA']
for index,thing in enumerate(a):
if "Name=" in thing:
del a[index]
I know, that it might be slow, but I thought that maybe it would hold 
its
own because it doesn't have to import the re module, everything's 
builtin,
etc.

HTH,
Jacob
A faster way to do this would be to use something like:
if thing.beginswith("Name"): del a[index]
-- Max
--
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing two elements in a list

2004-12-20 Thread Kent Johnson
Max Noel wrote:
On Dec 19, 2004, at 06:16, Jacob S. wrote:
Would this work for you?
a = ['Name = stuff','CGTATAGCTAGCTA','Name = stuff','CGATATGCCGGCTA']
for index,thing in enumerate(a):
if "Name=" in thing:
del a[index]
A faster way to do this would be to use something like:
if thing.beginswith("Name"): del a[index]
Like, maybe,
  if thing.startswith('Name')...
;)
Kent
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter questions

2004-12-20 Thread Alan Gauld
> > I find the easiest way is to create an PhotoImage object attach
> > the graphic file(jpg,bmp,gif) to that and assign the PhotoImage
> > object to the Button.image property. You can "animate" the image
> > by simply reassigning the file to the underlying PhotoImage
onject.

> Thanks, but a practical explanation will be more helpful.

OK, I assume you mean code? :-)

Here is an example modified from some experiments using
the >>> prompt.  It should work but might need a tweak
along the way...


from Tkinter import *

state = 0

def changeIt(img, fname):
   global state
   if state == 0:
   img['file']='img0.gif'
   state = 1
   else:
   img['file'] = 'img1.gif'
   state=0

top = Tk()

# now create an image object and a button
theImg = PhotoImage(file='spam.gif')
b = Button(top, command = changeIt, image=theImg)

b.pack()
top.mainloop()
#

You'll need to provide your own image files :-)
You can also see this in action with a Text box in
my book chapter on building a games framework,
the commented code for which is on the Useless
Python website as hmgui.zip

> > You mean print as in to a printer?
> > Personally I tend to generate an HTML file and use the
> > native OS Tools to print that. You can get fancy and
> > use the native OS printing libraries but since its
> > very OS specific I find HTML is easier! OUtside Tkinter
> > you may well find the GUI libraries have done the cross
> > platform stuff for you, but not in Tkinter.
> Again, a practical explanation will be more helpful...

HTML generation is just a case of creating a text file with
appropriate HTML tags inserted. There are some modules around
that can help.

Printing the file then becomes a matter of finding the
appropriate commands in your OS and using the os.system()
call to execute them. For example Windows explorer uses
this command to print HTML on my system:

"D:\msoffice\OFFICE11\msohtmed.exe" /p %1

You'll need to look to find whats in use on yours...

> > Define a full window? You mean full screen?
> > Thats usually better done as a parameter that the user can
> > set unless there is a very good reason not to. (Personally
> > I refuse to use any program that insists on opening full screen!)

> Full window or full screen is when the window of the program is all
> over the screen except the start bar

Nope, Full Window means that something fills the current window,
which could be any size. Since that didn't fit your explanation
I asked for clarity. Full screen is where a single window fills
the currently available screen.

> And why you refuse to use any program that insists on opening full
screen ?
> If it does then there must be a good reason for that...

No, quite often its simply a fascist minded programmer who thinks
his application is so important that I won't want to do anything
else while it's running - games programmers are bad for this.
But since I very rarely do only one thing at a time on my PC
I want control of the window size thankyou very much - that's
why I have a 21 inch monitor running at 1600x1200!

There are very few valid situations for an application taking
over the whole screen univited! Normally the user should be able
to make that choice. (For example when editing video I usually
do go full screen, but I decide, not the program!)

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] class overriding question

2004-12-20 Thread Alan Gauld
You've got it right Brian. It is this ability to change the way
*existing* code works that makes OOP more than a neat way to
package data and functions. This is polymorphism at its
most powerful.

Its why in a C++/Java world the convention is to write
hook methods that are called by the public methods. Thus
sub classes can override the hook methods and change the
behaviour of the public methods, without changing the
basic sequence of processing. The common example here
is a shape heirarchy:

Shape defines a move method. move() calls delete()
and draw() hooks.

New classes override delete and draw and get move for
free because it will always call the hooks in the
right sequence and each subclass will actually do
the appropriate work.

Its another reason why you should never refer to
an object or method *calling* another method
(as Pilgrim does). Rather think of the method
sending a *message* to the self object which
invokes the appropriate method. This decoupling
of message from method is a vitally important
concept in OO and onvce you understand the concept
of messages being sent resulting in methods
being invoked OOD becomes much easier to grasp.
This is explicit in Lisp, Smalltalk and Objective C
where methods may have completely different names
to messages, and multiple messages may invoke the
same method - possibly with different default
parameters - a very powerful technique! it's just
about possible to do this in Python with lambdas
etc but its messy.

Alan G.

- Original Message - 
From: "Brian van den Broek" <[EMAIL PROTECTED]>
To: "Tutor" <[EMAIL PROTECTED]>
Sent: Saturday, December 18, 2004 1:31 PM
Subject: [Tutor] class overriding question


> Hi all,
>
> instead of sleeping, I've been up all night finally attacking my
> apprehension about classes. I think I'm mostly getting the hang of
it --
> I managed to convert a 300 line procedural script into (what I think
is)
> a fully object-oriented approach. :-)
>
> I made a lot of use of Mark Pilgrim's Dive Into Python
> , but Pilgrim said something that I'd
like
> to check my understanding of. In section 5.5
> 
he
> writes:
>
> > Guido, the original author of Python, explains method overriding
this
> > way: "Derived classes may override methods of their base classes.
> > Because methods have no special privileges when calling other
methods
> > of the same object, a method of a base class that calls another
> > method defined in the same base class, may in fact end up calling
a
> > method of a derived class that overrides it. (For C++ programmers:
> > all methods in Python are effectively virtual.)" If that doesn't
make
> > sense to you (it confuses the hell out of me), feel free to ignore
> > it. I just thought I'd pass it along.
>
> I think I get this, but my inexperience with classes and Pilgrim's
> rhetorical flourish make me doubt myself. I think the following
three
> ways of saying it all say the same thing (to a greater or lesser
degree
> of precision) as the quote from Guido above. Do I have the idea?
>
> Say class spam defines a method ham, and a method eggs, where ham
calls
> eggs.  Further say class foo is derived from spam and overrides its
eggs
> method, but not its ham method. Then calling the ham method of an
> instance bar of foo (and thus calling the ham method of spam, as foo
is
> a spam), will call the eggs method of foo, despite the fact that ham
is
> a method of spam, and within spam points originally to spam's
version of
> the eggs method.
>
> Alternatively, when calling bar.ham(), Python essentially says "OK,
> bar's a foo. Does foo have a ham method? No, but it is derived from
> spam. Does spam have a ham method? Yes, and it calls an eggs method.
> Since bar's a foo, I should first look to see if foo has an eggs
method.
> (Nevermind that it was code in spam that started me off looking for
> eggs.) Golly good, it does. So I will use that and not even bother
to
> look at spam's version of eggs."
>
> One other way: if we represent class inheritance as a tree, an a
given
> instance is of a class at level n in the tree, any search for a
method
> begins with the instance class and works up the tree to the ultimate
> base class at level 1, no matter how high up the tree the search for
the
> method was initiated. And, in that search up the tree, the first
> correctly named method to be found will be used. (I'm using the
> mathematician's notion of trees with roots at the top.)
>
> Anyway, I hope I've both made sense and have got the idea right.
>
> Best to all,
>
> Brian vdB
>
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter questions

2004-12-20 Thread Mark Kels
On Mon, 20 Dec 2004 18:21:13 +1300, Liam Clarke <[EMAIL PROTECTED]> wrote:

> from Tkinter import *
> import Image, ImageTk
> root = Tk()
> img = Image.open('SonicCruiser.gif')
> phi = ImageTk.PhotoImage(img)
> button = Button(root, image=phi)
> button.pack()
> root.mainloop()

Thank you !!
But I don't have the Image module...
Is it a part of the PIL toolkit ?
If not, where can I get it ?

> 
> > Again, a practical explanation will be more helpful...
> 
> Cross platform easy printing? wxPython, which is totally different to Tkinter.
> 
> http://mail.python.org/pipermail/python-list/2004-January/205116.html
> 
> >Printing is not easy, it is a complicated matter.
> 
> >You can find 4 simplifications:
> 
> >1) wxPython has a print-framework, wxPython is cross platform (alas, I only
> used it in win32)
> 
> >2) print postscript. Ghostscript is available on "every" platform.
> (printing on PDAs and watches is  really different). Postscript is
> documented
> 
> >3) create PDF. PDF viewers & printers are available on "every" platform.
> PDF can be created by (free) ReportLab toolkit, and I'm sure there are more
> PDF-Classes
> 
> >4) create XHTML & a Print.CSS. HTML viewers are available on every
> Plattform, .CSS allows fairly good styling of printouts.
> 

Is it so hard if I only want to print plain text ?
Because I don't need anything special (only black text on white paper...).

> You mean like IE's really good reasons to insist on being my default
> browser for everything? You're putting a lot of faith in software
> developers.

Maybe I do... =)

> You do realise that -
> 
> no-one here is paid to answer queries?
> Alan Gauld is a very knowledgable person?
> Any knowledge is good knowledge?
> If at first you don't succeed, rephrase or Google?

Yes, I do.
Actually, I don't understand why you don't think its obvious to me (
must be because of my bad English =).

Thanks allot !

-- 
1. The day Microsoft makes something that doesn't suck is probably the
day they start making vacuum cleaners.
2. Unix is user friendly - it's just picky about it's friends.
3. Documentation is like sex: when it is good, it is very, very good.
And when it is bad, it is better than nothing. - Dick Brandon
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] class overriding question

2004-12-20 Thread Brian van den Broek
Alan Gauld said unto the world upon 2004-12-20 09:27:


Its another reason why you should never refer to
an object or method *calling* another method
(as Pilgrim does). Rather think of the method
sending a *message* to the self object which
invokes the appropriate method. This decoupling
of message from method is a vitally important
concept in OO and onvce you understand the concept
of messages being sent resulting in methods
being invoked OOD becomes much easier to grasp.
This is explicit in Lisp, Smalltalk and Objective C
where methods may have completely different names
to messages, and multiple messages may invoke the
same method - possibly with different default
parameters - a very powerful technique! it's just
about possible to do this in Python with lambdas
etc but its messy.
Alan G.
Thanks Alan.
I appreciate the confirmation of my stumblings towards understanding. On 
the plus side, after a few evenings of serious effort, I can't quite 
understand what about OOP and classes had me so intimidated before :-) 
(That said, I'm a long way off from having these things down.)

The contrast you suggest between calling a method and sending a message 
to an object isn't immediately clear to me. I'll put on my puzzling cap. 
But do you suggest it to emphasize that it is features of the object 
that determine which method gets invoked by the object.method() 
notation, or for some other reason? (By "features of the object" I mean 
things like facts about where the class that the object is a primary 
instance of falls in an inheritance tree.)

Thanks again,
Brian vdB
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] A better way to do it.

2004-12-20 Thread Jacob S.
Okay, here's the code.

I am completely open to suggestions as this is my first dabbling in Tk.
Please look over it when you have time.

I have a couple of questions.
1) How do I change the title of the window?
2) Why does a window pop up saying something like error, the memory could
not be "read". I'm running
Windows XP, the script window disappears, and everything, just this message
pops up.


Jacob Schmidt


-
from Tkinter import *
import tkMessageBox
import os
from filecmp import cmpfiles

class Copying:
def __init__(self,action,var,err):
self.action = action
self.pri = var
self.err = err

self.j = os.path.join
self.r = os.path.isdir
self.e = os.path.isfile


#  These are the default values for the directories. To make it
simpler you could... ##
## pseudo
##  self.usbdrive = remote folder
## self.desktop = localer folder

dirlist = os.listdir("c:\\")
if 'Jacob Laptop' in dirlist:
self.usbdrive = 'E:\\Working Python Programs'
self.desktop = 'C:\\documents and
settings\\jacob\\desktop\\Working Python Programs'
elif 'Home Computer' in dirlist:
self.usbdrive = 'F:\\Working Python Programs'
self.desktop = 'C:\\documents and
settings\\owner\\desktop\\Working Python Programs'
elif 'Sissy Computer' in dirlist:
self.usbdrive = '' ## Need to fill in
self.desktop = ''  ## Need to fill in
elif 'Michael Laptop' in dirlist:
self.usbdrive = 'E:\\Working Python Programs'
self.desktop = 'C:\\documents and
settings\\michael\\desktop\\Working Python Programs'
elif 'Office Computer' in dirlist:
self.usbdrive = 'D:\\Working Python Programs'
self.desktop = 'C:\\windows\\desktop\\Working Python Programs'
elif 'School Auction Laptop' in dirlist:
self.usbdrive = '' ## Need to fill in
self.desktop = 'C:\\windows\\desktop\\Working Python Programs'
else:
print 'Hey you need to put a folder in this computer!. '
print '''Folders include:
Jacob Laptop
Home Computer
Sissy Computer
Michael Laptop
Office Computer
School Auction Laptop
'''
folder = raw_input('Which computer is this? ')
folder = "C:\\"+folder
os.mkdir(folder)
self.usbdrive = raw_input('What is the usb drive on this
computer? ')
self.desktop = raw_input('What is the desktop on this computer?
')

# # #
if not os.path.exists(self.desktop):
os.mkdir(self.desktop)
m = {'receiving':self.receiving,'sending':self.sending}
m[self.action]()


def copyfile(self,src,des):
x = open(src,'rb').read()
y = open(des,'wb')
y.write(x)
y.close()


def receiving(self):
chiplist = os.listdir(self.usbdrive)
pclist = os.listdir(self.desktop)
filechange = cmpfiles(self.usbdrive,self.desktop,chiplist)[1]
tot = 0
for x in chiplist:
if x not in pclist:
filechange.append(x)
for x in filechange:
fullname = self.j(self.usbdrive,x)
if self.e(fullname):
self.copyfile(fullname,self.j(self.desktop, x))
self.pri.set("Copying %s." % x)
self.err.insert(END,"%s copied from chip to computer.\n" %
x)
tot = tot + 1
elif self.r(fullname):
self.err.insert(END,"%s is a directory. It has not been
copied.\n" % fullname)
self.err.insert(END,"%s file(s) copied.\n"%tot)
self.pri.set("")
pclist.sort()
chiplist.sort()
newlist = [x for x in pclist if x not in chiplist]
for x in newlist:
if tkMessageBox.askokcancel('Delete?',"Do you wish to delete %s?
" % x):
filename = self.j(self.desktop, x)
if self.e(filename):
os.remove(filename)
self.err.insert(END,"%s has been removed from your
chip.\n"%x)
elif self.r(filename):
os.rmdir(filename)
self.err.insert(END,"%s has been removed from your
chip.\n"%x)
else:
self.err.insert(END,"Did not remove %s\n"%x)

def sending(self):
pclist = os.listdir(self.desktop)
chiplist = os.listdir(self.usbdrive)
filechange = cmpfiles(self.desktop,self.usbdrive,pclist)[1]
tot = 0
for x in pclist:
if x not in chiplist:
filecha

Re: [Tutor] Printing two elements in a list

2004-12-20 Thread Jacob S.
Duh, whack myself on the head a few times.
Thanks,
Jacob

> Max Noel wrote:
> > 
> > On Dec 19, 2004, at 06:16, Jacob S. wrote:
> > 
> >> Would this work for you?
> >>
> >> a = ['Name = stuff','CGTATAGCTAGCTA','Name = stuff','CGATATGCCGGCTA']
> >> for index,thing in enumerate(a):
> >> if "Name=" in thing:
> >> del a[index]
> >>
> > 
> > A faster way to do this would be to use something like:
> > 
> > if thing.beginswith("Name"): del a[index]
> 
> Like, maybe,
>if thing.startswith('Name')...
> 
> ;)
> 
> Kent
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Printing two elements in a list

2004-12-20 Thread Jacob S.
That's interesting, I hadn't thought of that!
Jacob

> Jacob S. wrote:
> 
> > Would this work for you?
> >
> > a = ['Name = stuff','CGTATAGCTAGCTA','Name = stuff','CGATATGCCGGCTA']
> > for index,thing in enumerate(a):
> > if "Name=" in thing:
> > del a[index]
> >
> > I know, that it might be slow, but I thought that maybe it would hold 
> > its
> > own because it doesn't have to import the re module, everything's 
> > builtin,
> > etc.
> >
> Be careful here, the above code will miss deleting an element 
> containing "Name=" if there are two in a row.  Look at this simple 
> example where we attempt to delete elements equal to 2:
> 
> ###
> 
>  >>> a=[1,2,1,2]
>  >>> for i,x in enumerate(a):
> ..  if x==2:del a[i]
> ..
>  >>> a
> [1, 1]
>  >>> #
>  >>> # ok that looks right, but watch this
>  >>> #
>  >>> b=[2,2,1,1]
>  >>> for i,x in enumerate(b):
> ..   if x==2: del b[i]
> ..
>  >>> b
> [2, 1, 1]
> 
> ###
> 
> After deleting element 0 in b, all the elements "slid down" one place 
> and the 2nd 2 that was in b is now in position 0...but you are moving 
> on to index 1 with the enumerate loop:
> 
> [2, 2, 1, 1]
>   ^
>   enumerate is at index 0
> 
> we delete element 0
> 
> [2, 1, 1]
>  ^
>  enumerate is at index 1 and the 2 that was at position 1 is now at 
> position 0
> 
> An alternative is to use a list comprehension, keeping only the 
> elements that are not 2. As is shown, you can replace the list you are 
> filtering with the filtered result:
> 
> ###
> 
>  >>> b=[2,2,1,1]
>  >>> b=[x for x in b if not(x==2)]
>  >>> b
> [1, 1]
> 
> ###
> 
> /c
> 
> 
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 2.4 IDLE Windows 2000

2004-12-20 Thread Danny Yoo


On Sat, 18 Dec 2004, Jacob S. wrote:

> I think I'm going to burst out in tears. Mike Hansen gave the solution
> to the very problem I'm having, yet, when I used the console version and
> deleted the custom color theme, it stopped giving me error messages, but
> it still won't start up without the console.
>
> I'm am still stunted of my python 2.4 experience.


Hi Jacob,


Mike's bug submission into Sourceforge is getting attention; it's bug
1080387:

http://sourceforge.net/tracker/index.php?func=detail&aid=1080387&group_id=5470&atid=105470



I'm still concerned, though, about your case, since you're saying that
there are no error messages, but it's still not starting up from the icon
in your Start menu.

There should be a '.idlerc' directory in your home directory; can you try
moving or renaming it somewhere else temporarily?  Afterwards, try
starting IDLE.

But don't wipe that '.idlerc' out yet, because if it turns out that this
actually works, then we should take a closer look at the .idlerc
directory, and send it off to the bug hunters.


Good luck to you!

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 2.4 IDLE Windows 2000

2004-12-20 Thread EJP

"Jacob S." <[EMAIL PROTECTED]>

> Gee,
> I think I'm going to burst out in tears.
> Mike Hansen gave the solution to the very problem I'm having, yet, when 
> I
> used the console version and deleted the custom color theme, it stopped
> giving me error messages, but it still won't start up without the 
> console.
> 
> I'm am still stunted of my python 2.4 experience.
> Help, please!!!
> 
> Desperate,
> Jacob


Can you open IDLE and reset the color options to the defaults?  I believe 
that's how I solved it.

If not, there should be some configuration files, plain text files with names 
like "*.def" in your idlelib directory.  Here's the path to one of several on 
my machine:  
C:\Python23\Lib\idlelib\config-highlight.def

I am not sure if you can safely delete these, but reverting them to the default 
configuration should work (I think).

Caution: I am not an expert in IDLE, Python, or... even life.

EJP

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Matrix

2004-12-20 Thread Danny Yoo


On Sun, 19 Dec 2004, Bugra Cakir wrote:

> I want to create a matrix in Python. For example 3x4 how can i
> create this? thanks


Hi Bugra,

Just for reference, here's the relevant FAQ about how to do matrices in
Python:

http://python.org/doc/faq/programming.html#how-do-i-create-a-multidimensional-list


If you're planning to do a lot of matrix-y stuff, you may want to look
into the 'numarray' third-module:

http://www.stsci.edu/resources/software_hardware/numarray

The package adds powerful matrix operations to Python.


Good luck to you!

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] unittesting and nested functions

2004-12-20 Thread Christian Meesters
Hi
I've written some unittests using the unittest module for my 
'DNA-class'. This class can cope with almost every input, but with no 
'numbers' whatsoever. Well, one of the tests is:

class TestFunctions(unittest.TestCase):
...
def test__init__(self):
"""testing whether __init__ will fail if nonsense data are 
passed for initialization"""
self.failUnlessRaises(IOError,DNA('1 ATG'))
		
Now, if 'nonsense data' are passed to the testing function I expect an 
IOError to be raised. And this happens indeed. Still this test fails 
(actually it doesn't: only an error occurs), but why?

This is the Traceback I get:
==
ERROR: testing whether __init__ will fail if nonsense data are passed 
for initialization
--
Traceback (most recent call last):
  File "src/DNA.py", line 862, in test__init__
self.failUnlessRaises(IOError,DNA('1 ATG'))
  File "src/DNA.py", line 100, in __init__
raise IOError
IOError

--
Ran 35 tests in 0.485s
FAILED (errors=1)
According to the documentation everything should be just fine:
--
5.3.5 TestCase Objects
...
failUnlessRaises(exception, callable, ...)
 Test that an exception is raised when callable is called with  any 
positional or keyword arguments that are also passed to assertRaises(). 
The test passes if exception is  raised, is an error if another 
exception is raised, or fails if no  exception is raised. To catch any 
of a group of exceptions, a tuple  containing the exception classes may 
be passed as exception.
--

So, any idea, where my mistake is?
(Before I get comments about having the unittest in the same file as 
the file to be tested: I'll change that! ;-) )

Thanks a lot in advance.
Cheers
Christian
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Matrix

2004-12-20 Thread Bob Gailer

On Sun, 19 Dec 2004, Bugra Cakir wrote:
> I want to create a matrix in Python. For example 3x4 how can i
> create this? thanks
Just for the heck of it would you tell us what you want to do with the 
matrix? Sometimes there are interesting alternate ways to do things that 
might not be obvious to a relatively new Pythoneer.

Bob Gailer
[EMAIL PROTECTED]
303 442 2625 home
720 938 2625 cell 

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] unittesting and nested functions

2004-12-20 Thread Kent Johnson
Christian Meesters wrote:
Hi
I've written some unittests using the unittest module for my 
'DNA-class'. This class can cope with almost every input, but with no 
'numbers' whatsoever. Well, one of the tests is:

class TestFunctions(unittest.TestCase):
...
def test__init__(self):
"""testing whether __init__ will fail if nonsense data are 
passed for initialization"""
self.failUnlessRaises(IOError,DNA('1 ATG'))
This should be
  self.failUnlessRaises(IOError, DNA, '1 ATG')
In your usage, you are calling DNA() and passing the result of the call to failUnlessRaises(). The 
call to DNA raises IOError. This happens *before* the call to failUnlessRaises(), so it is 
interpreted as an error.

In my version, I pass the DNA function itself to failUnlessRaises(), along with the arguments. The 
actual call to DNA() will be wrapped by a try/except block in failUnlessRaises(). The expected error 
is received and the test passes.

BTW, failUnlessRaises() is implemented using the extended call syntax that came up recently in 
another thread, and it is a good example of why this syntax is useful. It's also interesting that 
the except: statement uses the class that was passed in; I had no idea an except was dynamic in this 
way.

Here is the source for failUnlessRaises():
def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
try:
callableObj(*args, **kwargs)
except excClass:
return
else:
if hasattr(excClass,'__name__'): excName = excClass.__name__
else: excName = str(excClass)
raise self.failureException, "%s not raised" % excName
Kent
   
Now, if 'nonsense data' are passed to the testing function I expect an 
IOError to be raised. And this happens indeed. Still this test fails 
(actually it doesn't: only an error occurs), but why?

This is the Traceback I get:
==
ERROR: testing whether __init__ will fail if nonsense data are passed 
for initialization
--
Traceback (most recent call last):
  File "src/DNA.py", line 862, in test__init__
self.failUnlessRaises(IOError,DNA('1 ATG'))
  File "src/DNA.py", line 100, in __init__
raise IOError
IOError

--
Ran 35 tests in 0.485s
FAILED (errors=1)
According to the documentation everything should be just fine:
--
5.3.5 TestCase Objects
...
failUnlessRaises(exception, callable, ...)
 Test that an exception is raised when callable is called with  any 
positional or keyword arguments that are also passed to assertRaises(). 
The test passes if exception is  raised, is an error if another 
exception is raised, or fails if no  exception is raised. To catch any 
of a group of exceptions, a tuple  containing the exception classes may 
be passed as exception.
--

So, any idea, where my mistake is?
(Before I get comments about having the unittest in the same file as the 
file to be tested: I'll change that! ;-) )

Thanks a lot in advance.
Cheers
Christian
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] class overriding question

2004-12-20 Thread Alan Gauld
> > Its another reason why you should never refer to
> > an object or method *calling* another method
> > (as Pilgrim does). Rather think of the method
> > sending a *message* to the self object which
> > invokes the appropriate method.

> The contrast you suggest between calling a method and sending a
message
> to an object isn't immediately clear to me. I'll put on my puzzling
cap.

In classical OOP theory - ie all the early OOP languages
(except probably Simula which was Algol based!) - the metaphor was of
a set of independant objects floating around in cyberspace. These
objects communicated by sending messages to each other. How the
receiving object responded to a message was known as its method,
and the resolution of the message into appropriate method was the
job of the receiving object (or class).

In (pseudo and simplified python-like) Lisp, for example,
you can do things like:

def methodOne(self, p1):  # code here
def methodTwo(self, fmt):  # code here

def class MyClass

myClass.addMessage("help", methodOne)
myClass.addMessage("print",methodTwo)
myClass.addMessage("display", methodTwo)

myObject = MyClass.makeInstance()

myObject.send("print", 'txt')
myObject.send("display", 'scrn')

Thus I bind the same method to two different messages.
Because I always use send() (a class function) I pass
the message name as strings and the class  does a lookup
(usually in a dictionary) and calls the associated method.
THus there is explicit separation of concept.

Unfortunately this was slow so most later OOP languages
opted for a more direct translation with message name
equalling method name. This in turn lost the theoretical
purity of the concept of objects being independant concurrent
processes and starte the idea that you could directly
call a *method* which theoretically is impossible.

But conceptually it helps to see the difference between
objects and data structures to imagine that every object
is an independant process and they communicate by sending
IPC messages to one another. ( For the mathematically
inclined this idea of concurrent sequential (state)
machines is a very powerful formal model that can be
analysed mathematically. Many of the theoretical
underpinnings of computer science stem from this idea.)

> But do you suggest it to emphasize that it is features of the object
> that determine which method gets invoked by the object.method()

In essence yes. The programmer has no control over the
code that gets executed when he "sends a message" to
an object, that is determined in the class. And it can
be a dangerous mistake to think otherwise - after all
what if someone subclasses your original class and then
passes one of the new objects into your code. If you
assume that you can send a message and execute a
specific method you might be in for a nasty surprise!

As a specific example, lets say you have a set of blodgets.
One method of the blodget superclass defines a save method
which writes to a fixed data file. You write code that accepts
a blodget (or any subclass thereof) and saves it then reads
the data file to access some aspect of the object - really
bad practice anyway but it happens! Now I come along and
define a subclass of blodget that saves by writing to a
serial comms port, now your code "saves" my blodget but
when it reads the data file it actually picks up the last
blodget details not mine - oops!

I hope that short history of OOP clarifies rather than
confuses! :-)

Alan G.

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] class overriding question

2004-12-20 Thread Brian van den Broek
Alan Gauld said unto the world upon 2004-12-20 15:51:

I hope that short history of OOP clarifies rather than
confuses! :-)
Alan G.
Thanks for that Alan. Seems to clarify thing to me ;-)
Best,
Brian vdB
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 2.4 IDLE Windows 2000

2004-12-20 Thread Jacob S.
Ah, hah!

Okay, everyone! It took two things.

1) Delete .idlerc directory
2) Uninstall and reinstall python2.4

Why I had to do step two is beyond me, but I've got it settled now!
Thank you,
Jacob Schmidt

>
> "Jacob S." <[EMAIL PROTECTED]>
>
> > Gee,
> > I think I'm going to burst out in tears.
> > Mike Hansen gave the solution to the very problem I'm having, yet, when
> > I
> > used the console version and deleted the custom color theme, it stopped
> > giving me error messages, but it still won't start up without the
> > console.
> >
> > I'm am still stunted of my python 2.4 experience.
> > Help, please!!!
> >
> > Desperate,
> > Jacob
>
>
> Can you open IDLE and reset the color options to the defaults?  I believe
that's how I solved it.
>
> If not, there should be some configuration files, plain text files with
names like "*.def" in your idlelib directory.  Here's the path to one of
several on my machine:
> C:\Python23\Lib\idlelib\config-highlight.def
>
> I am not sure if you can safely delete these, but reverting them to the
default configuration should work (I think).
>
> Caution: I am not an expert in IDLE, Python, or... even life.
>
> EJP
>
>
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 2.4 IDLE Windows 2000

2004-12-20 Thread Danny Yoo


On Mon, 20 Dec 2004, Jacob S. wrote:

> 1) Delete .idlerc directory
> 2) Uninstall and reinstall python2.4

Hi Jacob,


Ok, so there was probably something really screwy with the stuff in
.idlerc.

Can you send me a tarball or zip of it in private email?  I just want to
make sure that the issue that you were hitting is the same as Mike's.  If
this is something new, we'd better make sure the IDLE developers know that
it's something other than a previous color configuration that is causing
IDLE to break.


Talk to you later!

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Tix NoteBook programming problem

2004-12-20 Thread Guillermo Fernandez Castellanos
Hi,

I'm trying to figure out how to work with Tix. The lack of examples
and avalaibility of documentation for TCL only do not help :-(

It does not work because when I start the program, the red and gren
buttons start blinking betweeb 2 or 3 different places, no matter what
the tab is.

Here is the code:

import Tix

root = Tix.Tk()

nb=Tix.NoteBook(root)
nb.add('hd',label="hard disk",underline=0)
nb.add('gf',label="soft disk",underline=0)


hd = nb.subwidget('hd')
gf = nb.subwidget('gf')

button1 = Tix.Button(hd)
button1["text"]= "Hello, World!"
button1["background"] = "green"
button1.pack()

button1 = Tix.Button(gf)
button1["text"]= "Bye, World!"
button1["background"] = "red"
button1.pack()

hd.pack()
gf.pack()

nb.pack()

nb.mainloop()

My experience in Gui programming is pretty low, any help would be apreciated.

Thanks!

Guille
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] implementing a table data structure in python?

2004-12-20 Thread Thomas Clive Richards

Hi,

I'm trying to implement a reasonably efficient table data structure, but ith a 
few quirks...

The application I'm building is a CGI program which allows users to view a 
large table of data. In addition, users can restrict the data shown. Some 
sample data might look like this: (note you'll need a fixed width font for 
this)

D   xyz   val   q
-
1|  123   230.1
13   |  234   240.15
24   |  112   120.2
45   |  235   1 0.12
116  |  627   270.18
211  |  946   280.45

Actually, the real data I'm using is very different - but this is easy to 
type :)

The entire table is stored in a plain text file, and could contain up to 500 
KB of data.

Every time my CGI script is run, it must read this file from disk, and return 
a 2D array of values; However, I need to be able to restrict the columns 
shown.

For example, user A might not want to see the D & val columns - I need a way 
of trimming these easily..


Normally I'd use a database like mysql, postgreSQL, or even SQLite for this 
sort of application, but the server I'm working on (which is outside my 
control) does not have any of these installed.

The CGI will not see heavy use, and I'm not very worried about race conditions 
or collisions...


Does anyone have any advice for me? implementing this as a simple 2D array (or 
list of lists) seems a little silly - surely there's a better way?


Actually, python bindings to the STL (or something similar) would be useful in 
many situations



Thanks,
-- 

Thomi Richards,
[EMAIL PROTECTED]
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor