Re: [Tutor] domain logic and avoiding setters and setters.

2005-07-12 Thread Alan G
> So I have been trying to figure out how to get around doing getters
> and setters and still have an oo way to inherit and apply business
> rules. 

I think you are missing the point a wee bit.

The object should not allow you to access its internal data.

You should not *need* to access its internal data.

The object has responsibilities in the form of behaviours.
The internal data is only there to support those behaviours, 
it should be of no interest to external objects, therefore 
you do not need setters and getters. Its not the setXXX getXXX 
thing thats wromg its the very idea that users of the object 
would want to access the internal data that is wrong.

In the words of Peter Coad, "Objects do it to themselves"

Now in some applications you do need the internal values, 
but usually its as a group. For example an Address class 
might have a method to return the full address content, 
but rather than provide individuual set/get methods per 
field it would return the whole address as a string or 
a tuple.(Note that both of these are immutable types!)

In some cases you may actually choose to expose one 
particular attribute, in which case a get/set pair for that 
one attribute is OK - they represent a genuine responsibility 
of the class. (Making it a property might be better still...) 
Its providing get/set pairs for *every attribute* that breaks 
good OOP practice.

PS. For a more formal description of the above principle 
look up "The Law of Demeter" on Google.

HTH,

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


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Giant Calc runs, but need advice on how to make the menu repopup.

2005-07-12 Thread Nathan Pinno



It runs but now how do I make it go back to the previous menu (e.g. from 
Add to Calculate Menu?)
 
Here is the latest screenshot:
 
The Giant Calculator
 
Copyright 2005 Written and debugged by Nathan Pinno
 
OPTIONS MENU1) Calculate2) Shapes3) Temperature4) 
Formulas5) QuitWhat option would you like:1CALCULATE MENU1) 
Add2) Subraction3) Multiplication4) Division w/o remainder5) 
Division with remaider6) Exponation7) Square roots8) Back to the 
previous menu.What option would you like:3First number:3Second 
number:23 * 2 =  6CALCULATE MENU1) Add2) Subraction3) 
Multiplication4) Division w/o remainder5) Division with remaider6) 
Exponation7) Square roots8) Back to the previous menu.What option 
would you like:7
 
>>> 
 
and the current code:
 
# This program is designed as a big calculator with functions.
 
# This first bunch of code is for the various menus. I decided to divide 
the calculations into seperate sub-menus,#so that the main menus would not 
be that long.def main_menu():   global option   
print "OPTIONS MENU"   print "1) Calculate"   print 
"2) Shapes"   print "3) Temperature"   print "4) 
Formulas"   print "5) Quit"   option = input("What 
option would you like:" ) 
 
def cal_menu():    global cal_opt    
print "CALCULATE MENU"    print "1) 
Add"    print "2) Subraction"    print "3) 
Multiplication"    print "4) Division w/o 
remainder"    print "5) Division with 
remaider"    print "6) Exponation"    
print "7) Square roots"    print "8) Back to the previous 
menu."    cal_opt = input("What option would you like:" 
)
 
def shape_menu():    global 
shape_opt    print "SHAPES MENU"    print 
"Important: The figure that is used for pi is 3.14."    print 
"1) Squares"    print "2) Circles"    
print "3) Rectangles"    print "4) 
Triangles"    print "5) Cones"    print 
"6) Cylinders"    print "7) 
Semicircles"    print "8) Main menu"    
shape_opt = input("What option would you like?" )
 
def temp_menu():    global 
temp_opt    print "1) Convert degrees Kevins to degrees 
Celsius"    print "2) Contvert Fahrenheit to 
Celsius"    print "3) Convert Celsius to 
Fahrenheit"    print "4) Convert Celsius to 
Kelvins"    print "5) Convert Kelvins to 
Fahrenheit"    print "6) Convert Fahrenheit to 
Kelvins"    print "7) Main Menu"    
temp_option = input("Choice: ")
 
def formula_menu():    global 
formula_opt    print "1) Interest"    
print "2) Distance"    print "3) Uniform 
motion"    print "4) Momentum"    print 
"5) Uniformly accelerated motion"    print "6) Falling 
bodies"    print "7) Weight"    print "8) 
Main menu"    fourmula_option = input("Choice: ")
 
#Code for main part of program.print "The Giant 
Calculator"printprint "Copyright 2005 Written and debugged by Nathan 
Pinno"print main_menu()if option == 1:    
cal_menu()    if cal_opt == 
1:    X = input("First number:" 
)    Y = input("Second number:" 
)    print X, "+", Y, "= ",X + 
Y    cal_menu()    
elif cal_opt == 2:    X = 
input("First number:" )    Y = 
input("Second number:" )    print X, 
"-", Y, "= ",X - Y    
cal_menu()    elif cal_opt == 
3:    X = input("First number:" 
)    Y = input("Second number:" 
)    print X, "*", Y, "= ",X * 
Y    cal_menu()    
elif cal_opt == 4:    X = 
input("First number:" )    Y = 
input("Second number:" )    if Y == 
0:    print 
"Division by zero ot 
allowed!"    
Y = input("Second number:" )    
else:    
print X, "/", Y, "= ",X / 
Y    
cal_menu()    elif cal_opt == 
5:    X = input("First number:" 
)    Y = input("Second number:" 
)    if Y == 
0:    print 
"Division by zero ot 
allowed!"    
Y = input("Second number:" )    
else:    
print X, "/", Y, "= ",X / Y," R ", X % 
Y    
cal_menu()    elif cal_opt == 
6:    X = input("First number:" 
)    Y = input("Power:" 
)    print X, "**", Y, "= 
",X**Y    
cal_menu()    elif cal_opt == 
7:    X = input("Number to be 
squared:" )    print "The square root 
of", X, " = ",X**0.5    
cal_menu()    elif cal_opt == 
8:    
main_menu()    
else:    print "That's not an option. 
Try again."    cal_menuelif 
option == 2:    shape_menu()    if 
shape_opt == 1:    print "1) 
Circumference"    print "2) 
Area"    print "3) Shapes 
Menu"    op = input("Choice: 
")    if op == 
1:    side = 
input("Side: 
")    print 
"Circumference = 
",4*side    
shape_menu()    elif op == 
2:    side = 
input("Side: 
")    print 
"Area = 
",side**2    
shape_menu()    elif op == 
3:    
shape_menu()    
else:    
print "That's not an 
option."    
op = input("Choice: ")    elif shape_opt == 
2:    print "1) 
Circumference"    print "2) 
Area"    print "3) Shapes 
Menu"    d = input("Choice: 
")    if d == 
1:    
diameter = input("Diameter: 
")  

Re: [Tutor] Giant Calc runs, but need advice on how to make the menu repopup.

2005-07-12 Thread Pujo Aji
you can wrap your code with while statement that check a user input
received at the end of every calculation you made whether go back to
main menu or not.

pujo

On 7/12/05, Nathan Pinno <[EMAIL PROTECTED]> wrote:
>  
> It runs but now how do I make it go back to the previous menu (e.g. from Add
> to Calculate Menu?) 
>   
> Here is the latest screenshot: 
>   
> The Giant Calculator 
>   
> Copyright 2005 Written and debugged by Nathan Pinno 
>   
> OPTIONS MENU
> 1) Calculate
> 2) Shapes
> 3) Temperature
> 4) Formulas
> 5) Quit
> What option would you like:1
> CALCULATE MENU
> 1) Add
> 2) Subraction
> 3) Multiplication
> 4) Division w/o remainder
> 5) Division with remaider
> 6) Exponation
> 7) Square roots
> 8) Back to the previous menu.
> What option would you like:3
> First number:3
> Second number:2
> 3 * 2 =  6
> CALCULATE MENU
> 1) Add
> 2) Subraction
> 3) Multiplication
> 4) Division w/o remainder
> 5) Division with remaider
> 6) Exponation
> 7) Square roots
> 8) Back to the previous menu.
> What option would you like:7 
>   
> 
> >>> 
>   
> and the current code: 
>   
> # This program is designed as a big calculator with functions. 
>   
> # This first bunch of code is for the various menus. I decided to divide the
> calculations into seperate sub-menus,
> #so that the main menus would not be that long.
> def main_menu():
>global option
>print "OPTIONS MENU"
>print "1) Calculate"
>print "2) Shapes"
>print "3) Temperature"
>print "4) Formulas"
>print "5) Quit"
>option = input("What option would you like:" ) 
>   
> def cal_menu():
> global cal_opt
> print "CALCULATE MENU"
> print "1) Add"
> print "2) Subraction"
> print "3) Multiplication"
> print "4) Division w/o remainder"
> print "5) Division with remaider"
> print "6) Exponation"
> print "7) Square roots"
> print "8) Back to the previous menu."
> cal_opt = input("What option would you like:" ) 
>   
> def shape_menu():
> global shape_opt
> print "SHAPES MENU"
> print "Important: The figure that is used for pi is 3.14."
> print "1) Squares"
> print "2) Circles"
> print "3) Rectangles"
> print "4) Triangles"
> print "5) Cones"
> print "6) Cylinders"
> print "7) Semicircles"
> print "8) Main menu"
> shape_opt = input("What option would you like?" ) 
>   
> def temp_menu():
> global temp_opt
> print "1) Convert degrees Kevins to degrees Celsius"
> print "2) Contvert Fahrenheit to Celsius"
> print "3) Convert Celsius to Fahrenheit"
> print "4) Convert Celsius to Kelvins"
> print "5) Convert Kelvins to Fahrenheit"
> print "6) Convert Fahrenheit to Kelvins"
> print "7) Main Menu"
> temp_option = input("Choice: ") 
>   
> def formula_menu():
> global formula_opt
> print "1) Interest"
> print "2) Distance"
> print "3) Uniform motion"
> print "4) Momentum"
> print "5) Uniformly accelerated motion"
> print "6) Falling bodies"
> print "7) Weight"
> print "8) Main menu"
> fourmula_option = input("Choice: ") 
>   
> #Code for main part of program.
> print "The Giant Calculator"
> print
> print "Copyright 2005 Written and debugged by Nathan Pinno"
> print 
> main_menu()
> if option == 1:
> cal_menu()
> if cal_opt == 1:
> X = input("First number:" )
> Y = input("Second number:" )
> print X, "+", Y, "= ",X + Y
> cal_menu()
> elif cal_opt == 2:
> X = input("First number:" )
> Y = input("Second number:" )
> print X, "-", Y, "= ",X - Y
> cal_menu()
> elif cal_opt == 3:
> X = input("First number:" )
> Y = input("Second number:" )
> print X, "*", Y, "= ",X * Y
> cal_menu()
> elif cal_opt == 4:
> X = input("First number:" )
> Y = input("Second number:" )
> if Y == 0:
> print "Division by zero ot allowed!"
> Y = input("Second number:" )
> else:
> print X, "/", Y, "= ",X / Y
> cal_menu()
> elif cal_opt == 5:
> X = input("First number:" )
> Y = input("Second number:" )
> if Y == 0:
> print "Division by zero ot allowed!"
> Y = input("Second number:" )
> else:
> print X, "/", Y, "= ",X / Y," R ", X % Y
> cal_menu()
> elif cal_opt == 6:
> X = input("First number:" )
> Y = input("Power:" )
> print X, "**", Y, "= ",X**Y
> cal_menu()
> elif cal_opt == 7:
> X = input("Number to be squared:" )
> print "The square root of", X, " = ",X**0.5
> cal_menu()
> elif cal_opt == 8:
> main_menu()
> else:
> print "That's not an option. Try again."
> cal_menu
> elif option == 2:
> shape_menu()
> if shape_opt == 1:
> print "1) Circumference"
> print "2) Area"
> print "3) Shapes Menu"
>

[Tutor] OT python Licences

2005-07-12 Thread Dave S
This is a bit OT but here goes.

My work wants me to write a fairly large python script to analyze some
technical ASCII data files. Python and its libraries are GPL.

That being the case am I right in thinking that my script would also
have to be GPL and I would have to inform my employer as I hand it over ?

Secondly it would have to run in Windows, The results could pop up on a
DOS window. However I was looking at QT until I read the Windows
license. Are there any widget libraries that would allow me to program
for windows commercially without any license or fees ?

Thanks in advance
Dave


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OT python Licences

2005-07-12 Thread Brian van den Broek
Dave S said unto the world upon 12/07/2005 05:49:
> This is a bit OT but here goes.
> 
> My work wants me to write a fairly large python script to analyze some
> technical ASCII data files. Python and its libraries are GPL.
> 
> That being the case am I right in thinking that my script would also
> have to be GPL and I would have to inform my employer as I hand it over ?
> 
> Secondly it would have to run in Windows, The results could pop up on a
> DOS window. However I was looking at QT until I read the Windows
> license. Are there any widget libraries that would allow me to program
> for windows commercially without any license or fees ?
> 
> Thanks in advance
> Dave
> 

Apologies if this is a dupe; flaky wifi connection on my end.

Python's not GPL. It is under the Python license, which allows for 
non-free (speech sense) uses that the GPL doesn't. It is 
GPL-compatible. (And, just in case, its use for anything other than 
Python is strongly discouraged.)



Best,

Brian vdB

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OT python Licences

2005-07-12 Thread Kent Johnson
Dave S wrote:
> This is a bit OT but here goes.
> 
> My work wants me to write a fairly large python script to analyze some
> technical ASCII data files. Python and its libraries are GPL.
> 
> That being the case am I right in thinking that my script would also
> have to be GPL and I would have to inform my employer as I hand it over ?

No, Python is not released under the GPL and there are very few restrictions on 
redistributing it. See
http://www.python.org/doc/faq/general.html#are-there-copyright-restrictions-on-the-use-of-python

AFAIK you can license your *scripts* in any way you choose.

> Secondly it would have to run in Windows, The results could pop up on a
> DOS window. However I was looking at QT until I read the Windows
> license. Are there any widget libraries that would allow me to program
> for windows commercially without any license or fees ?

Tkinter (included with Python) and wxPython are both popular for this. The 
general consensus seems to be that Tkinter is easier to use for small projects 
while wxPython is more complete and better at creating apps that match users' 
expectations of look-and-feel.
http://www.wxpython.org

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] domain logic and avoiding setters and setters.

2005-07-12 Thread Kent Johnson
David Driver wrote:
> So I have been trying to figure out how to get around doing getters
> and setters and still have an oo way to inherit and apply business
> rules. This is what I have some up with so far. Is there any better
> way?

Hmm. I'm not sure what this has to do with getters and setters...maybe I would 
have to see the way you *didn't* show us to understand...

The only thing that I don't like about the code below is the need for 
subclasses to add rules to self._rules in the __init__() method. IMO this is 
fragile - it is too easy to forget to add or remove a rule from the list when 
the code changes.

An alternative is to use some form of auto-discovery of the rules. If you use a 
naming convention for the rule methods this is pretty easy. You can see an 
example in the unittest module; it finds all TestCase methods that start with 
'test' and runs them. The code to find the tests is in Lib\unittest.py in the 
function getTestCaseNames().

Kent
 
> 
> class RuleViolationError(Exception):
> def __init__(self, msg):
> self.msg = msg
> def __str__(self):
> return 'Rule violated in rule object: %s' %self.msg
> 
> class someObject(object):
> def __init__(self,a):
> self._voilatedRules = {}
> self._rules = [self.aRuleForA]
> self.a = a
> 
> def applyRules(self):
> self._voilatedRules.clear()
> for rule in self._rules:
> try:
> rule()
> except RuleViolationError, err:
> self._voilatedRules[rule.__name__] = err.msg
> if self._voilatedRules:
> # do something dramatic to deal with all of the
> # voilated business rules
> print 'error(s): '
> print self._voilatedRules
> 
> def aRuleForA(self):
> try:
> self.a = int(self.a)
> except ValueError:
> raise RuleViolationError('a is not an integer')
> 
> class someObjectChild(someObject):
> def __init__(self, a,b):
> someObject.__init__(self,a)
> self.b = b
> self._rules.extend((self.aRuleForB,
>self.anotherRuleForB))
> 
> def aRuleForB(self):
> # apply some business logic for d
> # check that it starts with b, very silly
> if not self.b.startswith('b'):
> raise RuleViolationError('b does not start with b')
> 
> def anotherRuleForB(self):
> #test string for length constraints
> min,max,l=2,15,len(self.b)
> print min,max,l
> if not(l>=min and l<=max):
> raise RuleViolationError('b is out of min or max')
> 
> class someObjectChild2(someObjectChild):
> #j ust change one of the rules for b
> def aRuleForB(self):
> # apply some business logic for d
> # check that it starts with d, very silly
> if not self.b.startswith('d'):
> raise RuleViolationError('b does not start with d')
> 
> 
> x = someObjectChild(123,'bob jones')
> 
> # this should return nothing
> x.applyRules()
> x.b = 'obladiobladalifegoeson'
> 
> # this should fail twice on b
> x.applyRules()
> 
> y = someObjectChild2(123,'bob jones')
> y.applyRules()
> 
> z = someObjectChild('happydance','bob jones')
> z.applyRules()
> 
> This isn't near complete, but I think it gets the idea across.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Giant Calc runs, but need advice on how to make the menu repopup.

2005-07-12 Thread Ewald Ertl
Hi!

As allready shown in your request for the "The Password Program" some day's 
ago, 
which has nearly the same problem as here. 

Wrap your code into loop's:

why are you setting the select-Values directly in the functions defining the 
menu's?
Why not just returning the selected value 
e.g.:
 def temp_menu():
 print "1) Convert degrees Kevins to degrees Celsius"
 print "2) Contvert Fahrenheit to Celsius"
 print "3) Convert Celsius to Fahrenheit"
 print "4) Convert Celsius to Kelvins"
 print "5) Convert Kelvins to Fahrenheit"
 print "6) Convert Fahrenheit to Kelvins"
 print "7) Main Menu"
 return (input("Choice: "))

and make the assignment in the main-Part:

  temp_option=temp_menu()

So the function does not need to know which option the input should be assigned 
and 
it is also useable in other part's of the code. 



Here's an extract of your calc-Part with while-Loops: 
there is only one call to the menu-functions necessary and not in all 
branches, because we return every time in the loop except, when the 
return-Option is selected. There is simple a "break"-Statement to leave 
the loop and go on outside the loop.

In my opinion, it would als be more readable, when you extract the 
calculcation-Code 
somewhere out of the big loop. Create a function for calculation and so on and 
handle 
in the functions the code, so it will become more "readable". 

It would also be somewhat better, to have a unique Number for the "Main 
Menu"-Option and not 
everytime a different number to select the "Main Menu". 

option=1
while option != 5:
option=main_menu()
if option == 1:
cal_opt=1
while cal_opt != 8:
cal_opt=cal_menu()
if cal_opt == 1:
X = input("First number:" )
Y = input("Second number:" )
print X, "+", Y, "= ",X + Y
elif cal_opt == 2:
X = input("First number:" )
Y = input("Second number:" )
print X, "-", Y, "= ",X - Y
elif cal_opt == 3:
X = input("First number:" )
Y = input("Second number:" )
print X, "*", Y, "= ",X * Y
elif cal_opt == 4:
X = input("First number:" )
Y = input("Second number:" )
if Y == 0:
print "Division by zero ot allowed!"
Y = input("Second number:" )
else:
print X, "/", Y, "= ",X / Y
elif cal_opt == 5:
X = input("First number:" )
Y = input("Second number:" )
if Y == 0:
print "Division by zero ot allowed!"
Y = input("Second number:" )
else:
print X, "/", Y, "= ",X / Y," R ", X % Y
elif cal_opt == 6:
X = input("First number:" )
Y = input("Power:" )
print X, "**", Y, "= ",X**Y
elif cal_opt == 7:
X = input("Number to be squared:" )
print "The square root of", X, " = ",X**0.5
elif cal_opt == 8:
break;
else:
print "That's not an option. Try again."
if option == 2:
...



One additional step is to make an independent menu-Function

def menu( args):
count=xrange(len(args))
for mycount,arg in zip( count,args):
print "%d) %s" % ( mycount, arg)
print "99) Main Menu"
return( input("Choice: "))

and just calling with the arguments
main_menu=[ "Calculate","Shapes","Temperature","Formulas","Quit" ]
calc_menu=["Add","Subraction","Multiplication","Division w/o remainder",
   "Division with remaider","Exponation","Square roots" ]

option=menu(main_menu)
...

calc_option=menu(calc_menu)




HTH Ewald 


on Tue, 12 Jul 2005 02:11:47 -0600  "Nathan Pinno" <[EMAIL PROTECTED]> wrote :
-

Nathan Pinno > It runs but now how do I make it go back to the previous menu 
(e.g. from Add to Calculate Menu?)
Nathan Pinno > 
Nathan Pinno > Here is the latest screenshot:
Nathan Pinno > 
Nathan Pinno > The Giant Calculator
Nathan Pinno > 
Nathan Pinno > Copyrig

[Tutor] Tkinter Q's

2005-07-12 Thread Joseph Quigley




Hi first off, here's my code:

# -*- coding: utf-8 -*-
from Tkinter import *
import random
import time
import about
import quotes


def closeprog():
    raise SystemExit

class main:
    root = Tk()
    frame = Frame()
    root.title("Quoter %s" % (about.ver))
    root.minsize(300, 50)

    showquote = Label(root, text=random.choice(quotes.quote))
    showquote.pack()

    exit = Button(root, text="Exit", command=closeprog)
    exit.pack(side=LEFT)

    aboutprg = Button(root, text="About", command=about.main)
    aboutprg.pack(side=LEFT)


    totalq = Label(root, text=quotes.qts)
    totalq.pack(side=BOTTOM)
    
    root.mainloop()

(I'd appreciate some suggestions, or notifications on how bad
something is)

I have a small problem: I don't know how to make a button that would
redisplay another quote in the same window, ie I need a button that
says: Show Another Quote. (Actually I don't know how to make it show
another quote even in a new window!!). I got the interface from Catfood
Fortune Cookie.

Here's a tid-bit of the quotes module:
 # Brian Kernighan
bk1 = """Controlling complexity is the essence of computer programming.

-- Brian Kernighan"""

yadayada = """Foo/bar"""

quote = [bk1, yadayada]

Thanks,
    Joe
-- 
Unix Love, Linux Pride



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OT python Licences

2005-07-12 Thread Byron
Dave S wrote:

>That being the case am I right in thinking that my script would also
>have to be GPL and I would have to inform my employer as I hand it over ?
>  
>

I don't believe so.  Python prefers to encourage its developers to 
contribute to the general community.  However, you can commercially 
write apps in Python and then sell them -- without having to make them 
open source or give-awayable to the general community.

Hope this helps,

Byron
---



-- 
No virus found in this outgoing message.
Checked by AVG Anti-Virus.
Version: 7.0.323 / Virus Database: 267.8.12/46 - Release Date: 7/11/2005

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] module with static global

2005-07-12 Thread János Juhász
Dear Guys!

I am using a class for connecting to an sql database via odbc.
It is like this:

import dbi, odbc

class scalaDB:
  def __init__(self):
self.cn =
odbc.odbc('DSN=scalaDB;UID=query;PWD=query;DATABASE=scalaDB')

  def closeDB(self):
self.cn.close()

  def Execute(self, sql):
cr = self.cn.cursor()
cr.execute(sql)
cr.close()

  def Query(self, sql):
try:
  cr = self.cn.cursor()
  cr.execute(sql)
  self.colnames = [field_prop[0] for field_prop in
cr.description]
  self.result = cr.fetchall()
  self.rownum = len(self.result)
  return self.result
except:
  self.colnames = [None]
  self.result = [[None]]
  self.rownum = 0
  return [[None]]

  def QueryValue(self, sql):
try:
  cr = self.cn.cursor()
  cr.execute(sql)
  self.colnames = [field_prop[0] for field_prop in
cr.description]
  self.result = cr.fetchall()
  self.rownum = len(self.result)
  return self.result[0][0]
except:
  self.colnames = [None]
  self.result = None
  self.rownum = 0
  return None

I also have some other classes represented in this database as records. As
the records are in the database, they has to have a scalaDB instance for
running any sql statement on it. Currently I send a scalaDB instance to
every record-based class in the __init__(): proc.

class Component:
  def __init__(self, scalaDB, StockCode, Qty=1, Parent=None):
self.scalaDB = scalaDB
self.StockCode = StockCode
self.Parent = Parent
self.Qty = Qty## Qty in
the BOM
self.Components = self.GetComponents()

  def GetParent(self):
return self.Parent

  def __getattr__(self, name):
if 'SC' in name:k
  value = self.scalaDB.QueryValue("select %s from SC010100
where SC01001 = '%s'" % (name, self.StockCode) )
  return value



How have I modify this to use my scalaDB class in this way:

>>>import scalaDB
>>>xy  = scalaDB.Query(sql)



Best regards,
Janos Juhasz

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] module with static global

2005-07-12 Thread Cedric BRINER
give an eyes to sqlobject.org.


-- 

Cedric BRINER
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] First Project - Ping Sweeper!

2005-07-12 Thread Trent Rigsbee
Hi! I've completed Learning to Program (off the website) and I've started to 
play around with code that I've found on Useless Python. I'm ready to start 
my first project! This may be way over my head, but I want to make a ping 
sweeper (put a range of IP addresses & ping to see which are vaild). I'm 
playing around with Mark Kels' Port Scanner off of Useless Python and I 
wanted to modify this for pinging but I'm stuck. I've ordered Network 
Programming for Python but I've started to play around with this until the 
book arrives. Any suggestions? Should I throw in the towel and make 
something simpler instead? Thanks! Here's the code that I'm tinkering with:

#A simple port scanner to scan a range of ports on a single host.

#Developers:
# 1.Mark Kels ([EMAIL PROTECTED]) - The basic port scanner
#Last updated:
# 21.5.2005

#--Imports--
from Tkinter import * #Used to make the GUI
import tkMessageBox #Used for error display
import socket #Used for connecting to ports
import threading #Used to make a difrent thread for the scan so it could be 
stopped

#--- Function to start a scan ---
def go():
global app
result.delete(1.0,END)
app=scan()
app.start() #start() is definde in threading.Thread
#--- Function to stop a scan ---
def stop():
app.flag='stop'
#--- Function to clear the input and output ---
def clear():
host_e.delete(0,END)
start_port_e.delete(0,END)
end_port_e.delete(0,END)
result.delete(1.0,END)

#---The scan class which does the port scan itself---
class scan(threading.Thread):
def _init_(self):
threading.thread._init_(self)
def run(self):
self.host=host_e.get()
self.start_port=int(start_port_e.get())
self.end_port=int(end_port_e.get())
self.open_counter=0
self.flag='scan'
start.config(text="Stop",command=stop)
root.update()
result.insert(END,"Scanning "+str(self.host)+"...\n\n")
root.update()
while self.start_port<=self.end_port and self.flag=='scan':
self.sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sk.settimeout(0.01) #closed ports take a long time to 
connect to, so if there is no connection after 0.01 seconds the port is 
closed
try:
self.sk.connect((self.host,self.start_port))
except:
pass #if connection fails (port is closed) pass and try with 
another port
else:
result.insert(END,str(self.start_port)+"\n")
root.update()
self.open_counter=self.open_counter+1
self.sk.close()
self.start_port=self.start_port+1
if self.flag=='scan':
result.insert(END,"\nDone !!\nFound "+str(self.open_counter)+" 
opened ports")
root.update()
start.config(text="Scan",command=go)
root.update()
elif self.flag=='stop':
result.insert(END,"\n Scan stopped.")
start.config(text="Scan",command=go)
root.update()

#---The GUI---
root=Tk()
Label(root,text="Host: ").grid(row=1,column=1,sticky="w")
host_e=Entry(root)
host_e.grid(row=1,column=2,sticky="WE")
Label(root,text="Start port: ").grid(row=2,column=1,sticky="w")
start_port_e=Entry(root)
start_port_e.grid(row=2,column=2,sticky="WE")
Label(root,text="End port: ").grid(row=3,column=1,sticky="w")
end_port_e=Entry(root)
end_port_e.grid(row=3,column=2,sticky="WE")
start=Button(root,text="Scan",command=go)
start.grid(row=5,columnspan=3,sticky="WE")
clear=Button(root,text="Clear",command=clear)
clear.grid(row=6,columnspan=3,sticky="WE")
result=Text(root,width=20,height=20)
result.grid(row=7,columnspan=3,sticky="WENS")


root.wm_maxsize(width='190',height='370') #Set max size
root.wm_minsize(width='190',height='370') #Sat min size same as max size (so 
the window is unresizeable)
root.title("PPS 0.1") #Set the title of the window

root.mainloop()


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OT python Licences

2005-07-12 Thread Don Parris
On Tue, 12 Jul 2005 10:49:22 +0100
Dave S <[EMAIL PROTECTED]> wrote:

> This is a bit OT but here goes.
> 
> My work wants me to write a fairly large python script to analyze some
> technical ASCII data files. Python and its libraries are GPL.
> 
> That being the case am I right in thinking that my script would also
> have to be GPL and I would have to inform my employer as I hand it over ?
> 
> Secondly it would have to run in Windows, The results could pop up on a
> DOS window. However I was looking at QT until I read the Windows
> license. Are there any widget libraries that would allow me to program
> for windows commercially without any license or fees ?
> 
> Thanks in advance
> Dave
> 
> 

While Python is not GPL'ed, any work you do release under a GPL license can
be used in-house without being redistributed.  In a sense, that makes it
proprietary, but it's still libre for the user - the main point of the GPL. 
As long as the program is not being redistributed, the GPL does not apply. 
IOW, your company is not forced to release the code.  As soon as your
employer distributes the code outside the company (public release), it falls
under the terms of the GPL.  

The GPL FAQ is available at the FSF website, and offers some excellent
answers to interesting questions.  As stated in another e-mail the current
Python license is compatible with the GPL.  There were a couple of versions
of Python (1.?.?) that the FSF considered incompatible.  The GPL is
copyleft, the Python License is a non-copyleft license, meaning that the
code can be made proprietary.

Don, who is preparing for his presentation on FOSS licenses at next month's
CharLUG meeting. :-)
-- 
evangelinuxGNU Evangelist
http://matheteuo.org/   http://www.lulu.com/dcparris
"Free software is like God's love - you can share it with anyone anytime
anywhere."
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OT python Licences

2005-07-12 Thread Sandip Bhattacharya
Dave S wrote:
> This is a bit OT but here goes.
> 
> My work wants me to write a fairly large python script to analyze some
> technical ASCII data files. Python and its libraries are GPL.
> 
> That being the case am I right in thinking that my script would also
> have to be GPL and I would have to inform my employer as I hand it over ?
> 
> Secondly it would have to run in Windows, The results could pop up on a
> DOS window. However I was looking at QT until I read the Windows
> license. Are there any widget libraries that would allow me to program
> for windows commercially without any license or fees ?
> 

Avoid QT on Windows in that case. It is prohibitivly expensive for most
small applications.

You have three choices for widgets programming:
1. Tk. No external libraries to be installed. But limited widgets i.e.
not much featureful, but adequate for simple GUIs.
2. Gtk. Simple API. A great RAD GUI builder (Glade). Cons are that you
have to have Pygtk installed on windows for your apps to run (I am not
sure if py2exe will package them for you as a standalone). Another con
is that it lacks a native windows look. On that other hand Gtk2 is quite
featureful.
3. wxpython. A bit complex than Gtk. Again external libraries needed to
be installed. However, it is very featureful and provides an exact
windows app look. There is a wxglade, but i am not sure whether it is as
good as gtkglade.

But again, if your app just needs to open a dos window, you can simply
execute it in a bat file, or execute the "start xxx" command isnt it?

About licence, regardless of the compiler or interpretor licence, you
are normally never bound to use the same licence ... UNLESS you are
*linking* to dev libraries, which happens only when you make a binary.
So if you distribute the code (and in the case of scripts like python
you probably do), you can licence it in any way. But if you distribute a
py2exe generated windows application, then your code might be bound by
the linked libraries. So if you are using PyGtk or wxpython, and
creating windows executables using py2exe, you should look at the
licences of these libraries too. AFAIK, these two widgets are quite
liberal in linking and there is no restrictions in making commercial
apps with them.

- Sandip

-- 
Sandip Bhattacharya  *Puroga Technologies   * [EMAIL PROTECTED]
Work: http://www.puroga.com  *   Home/Blog: http://www.sandipb.net/blog

PGP/GPG Signature: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Storing Data Records in XML File

2005-07-12 Thread Gooch, John
I have a Python script that stores the results of the processing that it
does in a 
database, but it has to have an alternate way of storing its data in a
database-friendly way (XML)in case the database is not available ( connected
down, data store full, etc. ).


Any recommendations on a way to do this? i.e. what modules what methods? 


Thanks in advance, 


John A. Gooch
Systems Administrator
IT - Tools
EchoStar Satellite L.L.C.
9601 S. Meridian Blvd.
Englewood, CO  80112
Desk: 720-514-5708 

-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf
Of Don Parris
Sent: Tuesday, July 12, 2005 9:58 AM
To: Python tutor
Subject: Re: [Tutor] OT python Licences


On Tue, 12 Jul 2005 10:49:22 +0100
Dave S <[EMAIL PROTECTED]> wrote:

> This is a bit OT but here goes.
> 
> My work wants me to write a fairly large python script to analyze some 
> technical ASCII data files. Python and its libraries are GPL.
> 
> That being the case am I right in thinking that my script would also 
> have to be GPL and I would have to inform my employer as I hand it 
> over ?
> 
> Secondly it would have to run in Windows, The results could pop up on 
> a DOS window. However I was looking at QT until I read the Windows 
> license. Are there any widget libraries that would allow me to program 
> for windows commercially without any license or fees ?
> 
> Thanks in advance
> Dave
> 
> 

While Python is not GPL'ed, any work you do release under a GPL license can
be used in-house without being redistributed.  In a sense, that makes it
proprietary, but it's still libre for the user - the main point of the GPL. 
As long as the program is not being redistributed, the GPL does not apply. 
IOW, your company is not forced to release the code.  As soon as your
employer distributes the code outside the company (public release), it falls
under the terms of the GPL.  

The GPL FAQ is available at the FSF website, and offers some excellent
answers to interesting questions.  As stated in another e-mail the current
Python license is compatible with the GPL.  There were a couple of versions
of Python (1.?.?) that the FSF considered incompatible.  The GPL is
copyleft, the Python License is a non-copyleft license, meaning that the
code can be made proprietary.

Don, who is preparing for his presentation on FOSS licenses at next month's
CharLUG meeting. :-)
-- 
evangelinuxGNU Evangelist
http://matheteuo.org/   http://www.lulu.com/dcparris
"Free software is like God's love - you can share it with anyone anytime
anywhere." ___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Storing Data Records in XML File

2005-07-12 Thread Max Noel


On Jul 12, 2005, at 18:44, Gooch, John wrote:

I have a Python script that stores the results of the processing  
that it

does in a
database, but it has to have an alternate way of storing its data in a
database-friendly way (XML)in case the database is not available  
( connected

down, data store full, etc. ).


Any recommendations on a way to do this? i.e. what modules what  
methods?


For all your XML processing needs, you need ElementTree (http:// 
effbot.org/).


-- 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?"







___ 
Appel audio GRATUIT partout dans le monde avec le nouveau Yahoo! Messenger 
Téléchargez cette version sur http://fr.messenger.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Storing Data Records in XML File

2005-07-12 Thread Danny Yoo


On Tue, 12 Jul 2005, Gooch, John wrote:

> I have a Python script that stores the results of the processing that it
> does in a database, but it has to have an alternate way of storing its
> data in a database-friendly way (XML)in case the database is not
> available ( connected down, data store full, etc. ).
>
> Any recommendations on a way to do this? i.e. what modules what methods?

Hi John,

Could you use the Sqlite library instead?  It's also a database engine,
but it's very embeddable:

http://www.sqlite.org/

and if you have an application that's already talking through the db-api,
it might be easiest to use sqlite as the alternative data store.


Otherwise, I've heard very good things about the Amara library for doing
XML data binding stuff:

http://uche.ogbuji.net/tech/4Suite/amara/


Best of wishes!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] First Project - Ping Sweeper!

2005-07-12 Thread Python
ping uses icmp.  icmp does not have port numbers.  icmp is a host-to-
host protocol for managing the flow of packets and reporting errors.
http://en.wikipedia.org/wiki/ICMP_Echo_Request
describes the outgoing "ping packet", but is probably too low-level to
be useful.

Port numbers are used in UDP and TCP.  The port scanning program will
not help you with ping.  UDP and TCP have port numbers because they are
application-to-application protocols and use the port number to identify
the target application.

I checked the index of "Foundations of Python Network Programming" and
did not see entries for icmp or ping.  I have not noticed icmp support
in the Python libraries.

-- 
Lloyd Kvam
Venix Corp

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] First Project - Ping Sweeper!

2005-07-12 Thread Reed L. O'Brien
Python wrote:
> ping uses icmp.  icmp does not have port numbers.  icmp is a host-to-
> host protocol for managing the flow of packets and reporting errors.
> http://en.wikipedia.org/wiki/ICMP_Echo_Request
> describes the outgoing "ping packet", but is probably too low-level to
> be useful.
>
> Port numbers are used in UDP and TCP.  The port scanning program will
> not help you with ping.  UDP and TCP have port numbers because they are
> application-to-application protocols and use the port number to identify
> the target application.
>
> I checked the index of "Foundations of Python Network Programming" and
> did not see entries for icmp or ping.  I have not noticed icmp support
> in the Python libraries.
>
>   

http://www.monkey.org/~dugsong/dpkt/pydoc/icmp.html
http://pynms.sourceforge.net/icmp.html
And look around twistedmatrix

~r

-- 
4.6692916090
'cmVlZG9icmllbkBnbWFpbC5jb20=\n'.decode('base64')
http://www.spreadfirefox.com/?q=affiliates&id=16474&t=1
keyID: 0x0FA09FCE

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] domain logic and avoiding setters and setters.

2005-07-12 Thread David Driver
I appreciate your input. You are correct. I read a bunch of LoD stuff
Northeastern website. It codified a bunch of things that I had been
working through.

But what you are not seeing (I must be terrible at this, always hard
to tell how much code to post) is this chunk of code represents an
idea about ways to hang business rules in an inheritable way onto a
persisted (sqlobject) object. It is really in the model. This is a
sketch of what I am trying to accomplish.

Application (Output)
Presenter (renders HTML or other UI)
Persisted object/default generator
Editor (what we are looking at, is specific to the persisted
object, holds the rules and updates/creates persisted object)
Application (Input)

Presenter and Editor will have some knowledge of the persisted object.
They will directly access attributes in the persisted object. They
will not directly unveil attributes to the application (or any layers
that may be in between). So conceptually the domain object is just
split into three classes and Demeter  is
observed everywhere else, at least as far as I understand it's
principles.


On 7/12/05, Alan G <[EMAIL PROTECTED]> wrote:
> I think you are missing the point a wee bit.
> 
> The object should not allow you to access its internal data.
> 
> You should not *need* to access its internal data.
> 
> The object has responsibilities in the form of behaviours.
> The internal data is only there to support those behaviours,
> it should be of no interest to external objects, therefore
> you do not need setters and getters. Its not the setXXX getXXX
> thing thats wromg its the very idea that users of the object
> would want to access the internal data that is wrong.
> 
> In the words of Peter Coad, "Objects do it to themselves"
> 
> Now in some applications you do need the internal values,
> but usually its as a group. For example an Address class
> might have a method to return the full address content,
> but rather than provide individuual set/get methods per
> field it would return the whole address as a string or
> a tuple.(Note that both of these are immutable types!)
> 
> In some cases you may actually choose to expose one
> particular attribute, in which case a get/set pair for that
> one attribute is OK - they represent a genuine responsibility
> of the class. (Making it a property might be better still...)
> Its providing get/set pairs for *every attribute* that breaks
> good OOP practice.
> 
> PS. For a more formal description of the above principle
> look up "The Law of Demeter" on Google.
> 
> HTH,
> 
> Alan G
> Author of the Learn to Program web tutor
> http://www.freenetpages.co.uk/hp/alan.gauld
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] domain logic and avoiding setters and setters.

2005-07-12 Thread Alan G
OK, I'll take a chance because as you say I don't know the
details of what you are building. And if its a Framework
for persistence, or an IDE for building persistence then
get/set may be your best bet - after all that's why Java
Beans have them so that Java IDEs can manipulate object
properties at design time.

But...

> Application (Output)
> Presenter (renders HTML or other UI)
>Persisted object/default generator

So the persisted object returns a string representation
of its state (maybe as a csv?) which the Presenter parses
and adds tags as needed?

>Editor (what we are looking at, is specific to the persisted
>object, holds the rules and updates/creates
>persisted object)

Not sure about this one? Why is 'editing' not a function of the
persisted object? It might be valid if its not a relevant business
function but if the object inherits a persistent mixin it should
be an attribute of the mixin which object inherits.

The rules should either be objects in their own right ot methods
of the objects attributes or methods of the object - after all
thats what objects are for: to hold their own business rules.
If you really mean the storage rules (database constraints),
then that might be a valid exception, but at that point the
persistence mechanism is operating at the raw data level
- ie the attributes of the object not the object itself. How
do we get from the object to the data? By having a csv, or tlv
or similar method on ll persistent objects. The tlv method of
the object returns a tlv representation of the current object
then the tlv of the superclass. This is standard object serialisation
type upward delegation through an inheriance lattice.

> Presenter and Editor will have some knowledge of the persisted 
> object.

By doing so they cease to be either generic or reusable.
They should communicate with the object via a standard protocol.
They should not need to be aware of individual attributes they
should only need the total state of the object. Editing implies
changes of attribute value but those should only be made through
the object's own protocol, even if that implies instantiating the
object, calling the relevant operation and then persisting it
again. Only where there are proven performamce issues should direct
attribute access at the data level even be considered.

> that may be in between). So conceptually the domain object is just
> split into three classes and Demeter  is
> observed everywhere else, at least as far as I understand it's
> principles.

The question is why should it be broken here? The Framework/IDE 
scenario
is the only one where it may be valid to beak demeter (and even then 
only
rarely), but very few real world scenarios need to go down that route.

But, it does rely totally on your domain and issues such as 
performance.
Theoretical principles are fine until they hit the real world then 
they
have to bend or be broken. But we should always try to follow them 
first,
bend them next and break them as a ;ast resort - we will suffer later
if we do otherwise.

Good luck,

Alan G. 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OT python Licences

2005-07-12 Thread Dave S
Many thanks for all your input, you have been great.

At the moment Tkinter is a favorite, I have started reading the
documentation and it seems fairly straightforward + can do what I need.

Many thanks once again :-)

Dave
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter Q's

2005-07-12 Thread Michael Lange
On Mon, 11 Jul 2005 17:22:57 +
Joseph Quigley <[EMAIL PROTECTED]> wrote:

Hi, Joseph,


> Hi first off, here's my code:
> 
> # -*- coding: utf-8 -*-
> from Tkinter import *
> import random
> import time
> import about
> import quotes
> 
> 
> def closeprog():
> raise SystemExit
> 
> class main:
> root = Tk()
> frame = Frame()
> root.title("Quoter %s" % (about.ver))
> root.minsize(300, 50)
> 
> showquote = Label(root, text=random.choice(quotes.quote))
> showquote.pack()
> 
> exit = Button(root, text="Exit", command=closeprog)
> exit.pack(side=LEFT)
> 
> aboutprg = Button(root, text="About", command=about.main)
> aboutprg.pack(side=LEFT)
> 
> 
> totalq = Label(root, text=quotes.qts)
> totalq.pack(side=BOTTOM)
>
> root.mainloop()
> 
> (I'd appreciate some suggestions, or notifications on how bad something is)
> 

I think you should change the way you define the main class, so you keep 
references to the class attributes;
it looks like your main class fires up a Tk() window, so it's probably best to 
subclass Tk() :

class Main(Tk):# this doesn't really matter, but upper case letters are 
generally preferrred for class names

def __init__(self, *args, **kw):
Tk.__init__(self, *args, **kw)
# at this point the Main() class practically is a Tk(), so it can be 
handled just like a regular
# Tk() window from the outside; the "*args, **kw" construct allows to 
pass an arbitrary amount of
# arguments and keyword arguments to the parent class. "self" is a 
placeholder for the class instance
# that will be actually used in the code.
# To get a benefit over a normal Tk() window you can now start adding 
attributes:
self.showquote = Label(self, text=random.choice(quotes.quote))
self.showquote.pack()
< etc. >
# of course you can use the parent classes methods on "self", too:
self.title("Quoter %s" % (about.ver))
self.minsize(300, 50)
# now you can add a button which uses a "class-specific" command:
self.switchbutton = Button, text="Switch quote", 
command=self.switch_quote)
self.switchbutton.pack()
# finally the class method has to be defined:

def switch_quote(self):
newquote = get_the_new_quote()# it's up to you how to do this of course
self.showquote.configure(text=newquote)

Now the Main() class can be used like a regular Tk() :

root = Main()
root.mainloop()

And for something completely different:
be careful mixing pack(side = LEFT / RIGHT) with pack(side = BOTTOM / TOP),
you might not get the results you expected. For complex layouts you are 
probably better off
using grid() ( or you will find that you have to use extra Frames to pack() 
your widgets in.

I hope this helps

Michael

> I have a small problem: I don't know how to make a button that would 
> redisplay another quote in the same window, ie I need a button that 
> says: Show Another Quote. (Actually I don't know how to make it show 
> another quote even in a new window!!). I got the interface from Catfood 
> Fortune Cookie.
> 




> Here's a tid-bit of the quotes module:
>  # Brian Kernighan
> bk1 = """Controlling complexity is the essence of computer programming.
> 
> -- Brian Kernighan"""
> 
> yadayada = """Foo/bar"""
> 
> quote = [bk1, yadayada]
> 
> Thanks,
> Joe
> 
> -- 
> Unix Love, Linux Pride
> 
> 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] recursion odities accross diferent versions of the 2.4.1 interpreter

2005-07-12 Thread Brian van den Broek
Hi all,

I'm playing about with some recursive functions where I am getting 
near the recursion limit. This caused me to do a test, and I am 
puzzled by the different results when run in the prompt, IDLE and 
PythonWin.

My simple test code is:
 >>> c = 0
 >>> def recursion_test():
global c
c+=1
try:
recursion_test()
except:
print c

When this very same code is run in the different interpreters (or, 
different Python environments; I'm not sure of the correct terminology 
here) I get different results. I'll show those, skipping the identical 
code that created them:


Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] 
on win32
 >>> recursion_test()
999
 >>>


IDLE 1.1.1
 >>> recursion_test()
996996


PythonWin 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit 
(Intel)] on win32.  
 >>> recursion_test()
993
  993
  993
 >>>


That the printed numbers differ doesn't worry me; I assume since IDLE 
and PythonWin are implemented in Python, the overhead of running them 
eats up a recursion level or 6, according to how exactly they are 
implemented.

But the two puzzles are:

1) Why the difference in printing format (IDLE prints twice on one 
line, PythonWin thrice with different alignment)?

and,

2) With (and only with) IDLE, I never regain control of the shell 
(note the lack of a terminal '>>>' and have to restart to do anything 
else. That feels bug-like.


It seems a fair bet that the hypothesis for why the printed numbers 
are different is also at play in the last two puzzles. But, I was 
wondering if anyone could say something to shed a bit more light. In 
particular, is my sense of possible bug well grounded?

Thanks and best,

Brian vdB
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter Q's

2005-07-12 Thread jfouhy
Quoting Joseph Quigley <[EMAIL PROTECTED]>:

> Hi first off, here's my code:
> 
> # -*- coding: utf-8 -*-
> from Tkinter import *
> import random
> import time
> import about
> import quotes
> 
> 
> def closeprog():
>  raise SystemExit
> 
> class main:
>  root = Tk()
>  frame = Frame()
>  root.title("Quoter %s" % (about.ver))
>  root.minsize(300, 50)
> 
>  showquote = Label(root, text=random.choice(quotes.quote))
>  showquote.pack()
> 
>  exit = Button(root, text="Exit", command=closeprog)
>  exit.pack(side=LEFT)
> 
>  aboutprg = Button(root, text="About", command=about.main)
>  aboutprg.pack(side=LEFT)
> 
> 
>  totalq = Label(root, text=quotes.qts)
>  totalq.pack(side=BOTTOM)
>  
>  root.mainloop()
> 
> (I'd appreciate some suggestions, or notifications on how bad something
> is)

Some comments ---

You create a Frame, but you never use it.

You've put a whole lot of code in a class, but it's not in a class method.  This
is kinda missing the point of using classes in the first place (and it just
flat-out wouldn't work in the majority of OO languages).

Here's what I would do:

class Main(Frame):
def __init__(self, master=None, **kw):
Frame.__init__(self, master, **kw)

showquote = Label(self, text=random.choice(quotes.quote))
showquote.pack()

# etc

if __name__ == '__main__':
root = Tk()
main = Main(root)
main.pack(fill=BOTH, expand=True)
root.mainloop()
###

Do you see what I am doing there, and why it is different from your approach?

> I have a small problem: I don't know how to make a button that would 
> redisplay another quote in the same window, ie I need a button that 
> says: Show Another Quote. (Actually I don't know how to make it show 
> another quote even in a new window!!). I got the interface from Catfood

Once you've got a label, you can change its text attribute by using its
.config() method.

So, you could do something like this:

# ...
showquote = Label(self, text=random.choice(quotes.quote))
showquote.pack()

def changeQuote():
currQuote = showquote.cget('config')  # Get the current quote
newQuote = random.choice(quotes.quote)
while newQuote == currQuote:  # Make sure the new quote differs
newQuote = random.choice(quotes.quote)
showquote.config(text=newQuote)
Button(self, text='Show another quote', command=changeQuote).pack()

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] python newbie..system call help

2005-07-12 Thread Mike Pindzola
I am writing a small program to speed up the efficiency of me on my home 
linux machine. I need it to communicate serveral times to the bash shell 
to issue and retrieve info. I took a guess and tryed the system() 
function call, but python quickly rejected that.

Should I be even trying to make a system call? Is there a better way to 
talk to the shell? Either way, please enlighten me. Thanks.

Also, this is my first time using the python tutor and I am new to 
python itself also, although I have done small amounts of programming in 
other languages before...Please fill me in on any procedures in the 
mailing list.

-Mike
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python newbie..system call help

2005-07-12 Thread jfouhy
Quoting Mike Pindzola <[EMAIL PROTECTED]>:

> Should I be even trying to make a system call? Is there a better way to
> talk to the shell? Either way, please enlighten me. Thanks.

There may be a better way to achieve what you want to do, without using the
shell at all.  For example, the os and os.path modules include a range of
functions for manipulating files and directories (listing, walking, moving,
renaming, et cetera).  Perhaps, if you say what you are trying to achieve, we
can give some pointers.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python newbie..system call help

2005-07-12 Thread Mike Pindzola
Yes, I have did 'import os'. For starters I want to read the result of 
'pwd' and print it out in the program for the user to see what path is 
being read. Also, I need to have a function to handle root access if the 
user does not have such privledges since I will be mounting and 
unmounting hardware. So a call to 'su' would be in order as well as 
sending the user provided password back to it.

Aside from that, just so copying of files, making dirs, and changing 
file permissions.

[EMAIL PROTECTED] wrote:

>Quoting Mike Pindzola <[EMAIL PROTECTED]>:
>
>  
>
>>Should I be even trying to make a system call? Is there a better way to
>>talk to the shell? Either way, please enlighten me. Thanks.
>>
>>
>
>There may be a better way to achieve what you want to do, without using the
>shell at all.  For example, the os and os.path modules include a range of
>functions for manipulating files and directories (listing, walking, moving,
>renaming, et cetera).  Perhaps, if you say what you are trying to achieve, we
>can give some pointers.
>
>  
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python newbie..system call help

2005-07-12 Thread Mike Pindzola
I have figured many things out. system works, i just forgot to type 
os.system(). I have been looking into the os module and am finding alot 
of useful stuff. I still need to workout the best way to ask a user for 
a root password, show  when typed and then pass it to the system...

thanks for any responses

Mike Pindzola wrote:

> Yes, I have did 'import os'. For starters I want to read the result of 
> 'pwd' and print it out in the program for the user to see what path is 
> being read. Also, I need to have a function to handle root access if 
> the user does not have such privledges since I will be mounting and 
> unmounting hardware. So a call to 'su' would be in order as well as 
> sending the user provided password back to it.
>
> Aside from that, just so copying of files, making dirs, and changing 
> file permissions.
>
> [EMAIL PROTECTED] wrote:
>
>> Quoting Mike Pindzola <[EMAIL PROTECTED]>:
>>
>>  
>>
>>> Should I be even trying to make a system call? Is there a better way to
>>> talk to the shell? Either way, please enlighten me. Thanks.
>>>   
>>
>>
>> There may be a better way to achieve what you want to do, without 
>> using the
>> shell at all.  For example, the os and os.path modules include a 
>> range of
>> functions for manipulating files and directories (listing, walking, 
>> moving,
>> renaming, et cetera).  Perhaps, if you say what you are trying to 
>> achieve, we
>> can give some pointers.
>>
>>  
>>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OT python Licences

2005-07-12 Thread Chuck Allison
Hello Sandip,

Tuesday, July 12, 2005, 10:38:09 AM, you wrote:

SB> Dave S wrote:
>> This is a bit OT but here goes.
>> 
>> My work wants me to write a fairly large python script to analyze some
>> technical ASCII data files. Python and its libraries are GPL.
>> 
>> That being the case am I right in thinking that my script would also
>> have to be GPL and I would have to inform my employer as I hand it over ?
>> 
>> Secondly it would have to run in Windows, The results could pop up on a
>> DOS window. However I was looking at QT until I read the Windows
>> license. Are there any widget libraries that would allow me to program
>> for windows commercially without any license or fees ?
>> 

What about wxWindows, for which we have wxPython?

-- 
Best regards,
 Chuck

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python newbie..system call help

2005-07-12 Thread Danny Yoo


On Tue, 12 Jul 2005, Mike Pindzola wrote:

> I have figured many things out. system works, i just forgot to type
> os.system(). I have been looking into the os module and am finding alot
> of useful stuff. I still need to workout the best way to ask a user for
> a root password, show  when typed and then pass it to the system...

Hi Mike,

For the password thing, you may find the getpass module useful:

http://www.python.org/doc/lib/module-getpass.html

It'll do that password obscuring stuff for you.


You mentioned earlier, though, that you might want to execute stuff using
su --- have you considered using sudo?

http://www.courtesan.com/sudo/sudo.html

It might eliminate the need to type root passwords all the time, and if
used properly, sudo's can be safer since it can be configured to provide
access to a subset of commands.


> > Aside from that, just so copying of files, making dirs, and changing
> > file permissions.

For the rest of these, it is possible to use utilities in Python's
standard library instead of shelling out.  Some of these functions live in
the 'shutil' library:

http://www.python.org/doc/lib/module-shutil.html

and others in the 'os' module that you've been looking at earlier.  For
example, changing the current working directory can be a matter of calling
the os.chdir() function.


If you have more questions, please feel to bring them to the Tutor group.
Good luck to you!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor