Re: [Tutor] playing around with function

2006-07-28 Thread Luke Paireepinart
Where is self.ui initialized?
are these functions part of a class?
Why didn't you send the __init__ method?
why didn't you send the whole class structure?


>def gotoNextFuzzy(self):
>state = "isfuzzy"
>self.navigationNext(state)

>def gotoNextFuzzy(self):
>state = "isapproved"
>self.navigationNext(state)


These functions both have the same name.
They'll just overwrite each other.


 >def navigationNext(self,state):
 > if (self.getCurrentItem() == 0):
 > return 0
 > id = int(self.item.text(0))
 > for i in range(id,775):
 > i += 1
 > state =
state = what?

> and error said:
> Attribute Error: no attribute state
>
>   
If you give us the whole source (ideally) and the full stack trace of 
the error message it's more helpful.
I know you explain further down where the error occurs.
> 
> Please understand my idea that I just want to replace the state in line
>
> if self.store.units[i].state():
>
> with isfuzzy or isapproved or istranslated...
>
> and if I do as follow:
>
> if self.store.units[i].isfuzzy():
> then it works.
>   
it works but it doesn't work how you want it to work or what?
> 
> please also note that:
> isfuzzy()
> isapproved()
> istranslated()
>
> are the boolean function in other class.
>   
...
> 
>
> Does anybody have any solution on this coding style?
>
>   
I don't understand your coding style.
I suspect it's because you didn't include all of your code,
but if you did, I have no idea what you're trying to accomplish.
> Thanks,
>   
Just tryin' to help.
> da
>   
Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] playing around with function

2006-07-28 Thread Alan Gauld

"kakada" <[EMAIL PROTECTED]> wrote
> I have problem with function jumping:

I'm not sure what you mean by "function jumping" but I'll
make a few comments...

> in my class, I have three function here:
>
> def gotoNextFuzzy(self):
>state = "isfuzzy"
>self.navigationNext(state)
>
> def gotoNextFuzzy(self):
>state = "isapproved"
>self.navigationNext(state)

As Luke pointed out these are the same so only
the second one will actually be present.

Note that you set state but it is only a local variable
within the method, it will not persist outside the method
so you cannot access it, I suspect you meant to write

self.state = "isapproved"

> def navigationNext(self,state):
>if (self.getCurrentItem() == 0):
>return 0
>id = int(self.item.text(0))
>for i in range(id,775):
>i += 1

I'm not sure why you immediately add one.
you could change the values in range() to get the
same result:

for i in range(1,776):


>state =

Its not clear what you are assigning here? An unprintable
character or a typo?

>if (i == 775):
>self.warningMessage()
>else:
>if self.store.units[i].state():
>curItem = self.ui.treeWidget.topLevelItem(i)
>self.ui.treeWidget.setCurrentItem(curItem)
>
> self.ui.txtSource.setHtml(self.store.units[i].source)
>
> self.ui.txtTarget.setHtml(self.store.units[i].target)
>break

The indentation changes here but you refer to self which
suggests they should be inside the class. I'm not sure if
thats intentional(and thus an error?) or just a freak of email...

> and one calling built-in function:
>
> QtCore.QObject.connect(self.ui.btnNF,QtCore.SIGNAL("pressed()"),self.gotoNextFuzzy)
> and error said:
> Attribute Error: no attribute state

OK, but at what point did it say that? What does the stack trace in 
the error say?

> and if I do as follow:
>
> if self.store.units[i].isfuzzy():
> then it works.

So what is the problem? Like Luke I'm not sure I understand what
you are trying to do here.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



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


Re: [Tutor] playing around with function

2006-07-28 Thread kakada
Thank Alan and Luke,

My coding is divided up into many modules and import from one to another.
Here is my editor.py interface.


#!/usr/bin/python
# -*- coding: utf8 -*-

import sys
import application_rc
from PyQt4 import QtCore, QtGui
from ui_editor import Ui_MainWindow
from translate.storage import factory
import Display


class MainWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)

self.ui = Ui_MainWindow()
self.ui.setupUi(self)

self.numApproved = 0
self.numFuzzy = 0
self.numTranslated = 0

#events go here
QtCore.QObject.connect(self.ui.treeWidget,
QtCore.SIGNAL("itemSelectionChanged()"), self.updateField)
QtCore.QObject.connect(self.ui.cmbMsgFilter,
QtCore.SIGNAL("activated(int)"), self.setFilter)
   
QtCore.QObject.connect(self.ui.chkfuzzy,QtCore.SIGNAL("stateChanged(int)"),self.toggleFuzzy)
   
QtCore.QObject.connect(self.ui.chkapproved,QtCore.SIGNAL("toggled(bool)"),self.toggleApproved)
   
QtCore.QObject.connect(self.ui.btnsource2target,QtCore.SIGNAL("pressed()"),self.source2target)
   
QtCore.QObject.connect(self.ui.btnRemoveAllTU,QtCore.SIGNAL("pressed()"),self.removeAllTrans)
   
QtCore.QObject.connect(self.ui.btnNA,QtCore.SIGNAL("pressed()"),self.gotoNA)
   
QtCore.QObject.connect(self.ui.btnPA,QtCore.SIGNAL("pressed()"),self.gotoPA)
   
QtCore.QObject.connect(self.ui.btnNF,QtCore.SIGNAL("pressed()"),self.gotoNF)
   
QtCore.QObject.connect(self.ui.btnNT,QtCore.SIGNAL("pressed()"),self.gotoNT)
   
QtCore.QObject.connect(self.ui.btnNU,QtCore.SIGNAL("pressed()"),self.gotoNU)
   
QtCore.QObject.connect(self.ui.btnPF,QtCore.SIGNAL("pressed()"),self.gotoPF)
   
QtCore.QObject.connect(self.ui.btnPU,QtCore.SIGNAL("pressed()"),self.gotoPU)
   
QtCore.QObject.connect(self.ui.btnPT,QtCore.SIGNAL("pressed()"),self.gotoPT)
QtCore.QMetaObject.connectSlotsByName(self)




def newWindows(self):
print "new windows"
self.other = Ui_MainWindow()
self.other.windowList.append(other)
self.other.show()

def openFile(self):
fileName = QtGui.QFileDialog.getOpenFileName(self, self.tr("Open
Xliff File"),

QtCore.QDir.currentPath(),
 self.tr("XLIFF
Files (*.xliff *.xml *.xlf);;All File(*.*)"))

if fileName.isEmpty():
self.setWindowTitle( self.tr("WordForge Translation Editor
v.05 - ") + "untitle")
else:
self.setWindowTitle( self.tr("WordForge Translation Editor
v.05 - ") + str(fileName))
self.title = fileName
self.store = factory.getobject(str(fileName))
self.uf = Display.Display(self.ui, self.store)

import FirstShow
fs = FirstShow.FirstShow(self.ui, self.store)
fs.firstShow()

def save(self):
if self.title.isEmpty():
return self.saveAs()
else:
return self.store.savefile(str(self.title))

def saveAs(self):
fileName = QtGui.QFileDialog.getSaveFileName(self, self.tr("Save
Xliff File"),

QtCore.QDir.currentPath(),
 self.tr("XLIFF
Files (*.xliff *.xml *.xlf)"))
if fileName.isEmpty():
return

self.store.savefile(str(fileName))

self.ui.cmbMsgFilter.addItem ('Not filtered')
self.ui.cmbMsgFilter.addItem ('fuzzy')
self.ui.cmbMsgFilter.addItem ('translated')
self.ui.cmbMsgFilter.addItem ('untranslated')


def getCurrentItem(self):
try:
self.item = self.ui.treeWidget.selectedItems()[0]
except IndexError:
return False
   
# I have change my code style like this:

def gotoNF(self):
self.state = "NF"
self.navigationNext(self.state)
def gotoNT(self):
self.state = "NT"
self.navigationNext(self.state)
def gotoNU(self):
self.state = "NU"
self.navigationNext(self.state)
def gotoNA(self):
self.state = "NA"
self.navigationNext(self.state)

def gotoPA(self):
self.state = "PA"
self.navigationPrevious(self.state)
def gotoPT(self):
self.state = "PT"
self.navigationPrevious(self.state)
def gotoPU(self):
self.state = "PU"
self.navigationPrevious(self.state)
def gotoPF(self):
self.state = "PF"
self.navigationPrevious(self.state)
def navigated(self):
if (self.state == 'NF') and
(self.store.units[int(self.id)].isfuzzy()):
return True
if (self.state == 'PF') and
(self.store.units[int(self.id)].isfuzzy()):
return True
if (self.state == 'NT') and
(self.store.units[int(self.id)].istranslated()):
return True

Re: [Tutor] playing around with function

2006-07-28 Thread kakada
បានសរសេរ kakada:
> Thank Alan and Luke,
>
> My coding is divided up into many modules and import from one to another.
> Here is my editor.py interface.
>
>
> #!/usr/bin/python
> # -*- coding: utf8 -*-
>
> import sys
> import application_rc
> from PyQt4 import QtCore, QtGui
> from ui_editor import Ui_MainWindow
> from translate.storage import factory
> import Display
>
>
> class MainWindow(QtGui.QMainWindow):
> def __init__(self):
> QtGui.QMainWindow.__init__(self)
>
> self.ui = Ui_MainWindow()
> self.ui.setupUi(self)
>
> self.numApproved = 0
> self.numFuzzy = 0
> self.numTranslated = 0
>
> #events go here
> QtCore.QObject.connect(self.ui.treeWidget,
> QtCore.SIGNAL("itemSelectionChanged()"), self.updateField)
> QtCore.QObject.connect(self.ui.cmbMsgFilter,
> QtCore.SIGNAL("activated(int)"), self.setFilter)
>
> QtCore.QObject.connect(self.ui.chkfuzzy,QtCore.SIGNAL("stateChanged(int)"),self.toggleFuzzy)
>
> QtCore.QObject.connect(self.ui.chkapproved,QtCore.SIGNAL("toggled(bool)"),self.toggleApproved)
>
> QtCore.QObject.connect(self.ui.btnsource2target,QtCore.SIGNAL("pressed()"),self.source2target)
>
> QtCore.QObject.connect(self.ui.btnRemoveAllTU,QtCore.SIGNAL("pressed()"),self.removeAllTrans)
>
> QtCore.QObject.connect(self.ui.btnNA,QtCore.SIGNAL("pressed()"),self.gotoNA)
>
> QtCore.QObject.connect(self.ui.btnPA,QtCore.SIGNAL("pressed()"),self.gotoPA)
>
> QtCore.QObject.connect(self.ui.btnNF,QtCore.SIGNAL("pressed()"),self.gotoNF)
>
> QtCore.QObject.connect(self.ui.btnNT,QtCore.SIGNAL("pressed()"),self.gotoNT)
>
> QtCore.QObject.connect(self.ui.btnNU,QtCore.SIGNAL("pressed()"),self.gotoNU)
>
> QtCore.QObject.connect(self.ui.btnPF,QtCore.SIGNAL("pressed()"),self.gotoPF)
>
> QtCore.QObject.connect(self.ui.btnPU,QtCore.SIGNAL("pressed()"),self.gotoPU)
>
> QtCore.QObject.connect(self.ui.btnPT,QtCore.SIGNAL("pressed()"),self.gotoPT)
> QtCore.QMetaObject.connectSlotsByName(self)
>
>
>
>
> def newWindows(self):
> print "new windows"
> self.other = Ui_MainWindow()
> self.other.windowList.append(other)
> self.other.show()
>
> def openFile(self):
> fileName = QtGui.QFileDialog.getOpenFileName(self, self.tr("Open
> Xliff File"),
> 
> QtCore.QDir.currentPath(),
>  self.tr("XLIFF
> Files (*.xliff *.xml *.xlf);;All File(*.*)"))
>
> if fileName.isEmpty():
> self.setWindowTitle( self.tr("WordForge Translation Editor
> v.05 - ") + "untitle")
> else:
> self.setWindowTitle( self.tr("WordForge Translation Editor
> v.05 - ") + str(fileName))
> self.title = fileName
> self.store = factory.getobject(str(fileName))
> self.uf = Display.Display(self.ui, self.store)
>
> import FirstShow
> fs = FirstShow.FirstShow(self.ui, self.store)
> fs.firstShow()
> 
> def save(self):
> if self.title.isEmpty():
> return self.saveAs()
> else:
> return self.store.savefile(str(self.title))
>
> def saveAs(self):
> fileName = QtGui.QFileDialog.getSaveFileName(self, self.tr("Save
> Xliff File"),
> 
> QtCore.QDir.currentPath(),
>  self.tr("XLIFF
> Files (*.xliff *.xml *.xlf)"))
> if fileName.isEmpty():
> return
>
> self.store.savefile(str(fileName))
>
> self.ui.cmbMsgFilter.addItem ('Not filtered')
> self.ui.cmbMsgFilter.addItem ('fuzzy')
> self.ui.cmbMsgFilter.addItem ('translated')
> self.ui.cmbMsgFilter.addItem ('untranslated')
>
>
> def getCurrentItem(self):
> try:
> self.item = self.ui.treeWidget.selectedItems()[0]
> except IndexError:
> return False
>
> # I have change my code style like this:
>
> def gotoNF(self):
> self.state = "NF"
> self.navigationNext(self.state)
> def gotoNT(self):
> self.state = "NT"
> self.navigationNext(self.state)
> def gotoNU(self):
> self.state = "NU"
> self.navigationNext(self.state)
> def gotoNA(self):
> self.state = "NA"
> self.navigationNext(self.state)
> 
> def gotoPA(self):
> self.state = "PA"
> self.navigationPrevious(self.state)
> def gotoPT(self):
> self.state = "PT"
> self.navigationPrevious(self.state)
> def gotoPU(self):
> self.state = "PU"
> self.navigationPrevious(self.state)
> def gotoPF(self):
> self.state = "PF"
> self.navigationPrevious(self.state)
> def navigated(self):
> if (self.state == 'NF') 

[Tutor] how to run python's Graphical User Interface for Environments in agents.py

2006-07-28 Thread Сергій

 
I am reading "
Artificial Intelligence: A Modern Approach" now (http://aima.cs.berkeley.edu/), and there are some ready python code from this book (
http://aima.cs.berkeley.edu/python/readme.html).
And I have some problems with the code http://aima.cs.berkeley.edu/python/agents.py
 
 
It is said in the http://aima.cs.berkeley.edu/python/agents.html:
# GUI - Graphical User Interface for Environments# If you do not have Tkinter installed, either get a new installation ofPython# (Tkinter is standard in all new releases), or delete the rest of this file# and muddle through without a GUI.
I have python24.But just "*v = VacuumEnvironment(); w = EnvFrame(v);*" do nothing - I don't see any Graphical User Interface for Environments.
What am I doing wrong and how to compel this piece of code to return a Graphical User Interface for Environments?Thanks in advance for help.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] playing around with function

2006-07-28 Thread Kent Johnson
kakada wrote:
> # I have change my code style like this:
>
> def gotoNF(self):
> self.state = "NF"
> self.navigationNext(self.state)
> def gotoNT(self):
> self.state = "NT"
> self.navigationNext(self.state)
> def gotoNU(self):
> self.state = "NU"
> self.navigationNext(self.state)
> def gotoNA(self):
> self.state = "NA"
> self.navigationNext(self.state)
> 
> def gotoPA(self):
> self.state = "PA"
> self.navigationPrevious(self.state)
> def gotoPT(self):
> self.state = "PT"
> self.navigationPrevious(self.state)
> def gotoPU(self):
> self.state = "PU"
> self.navigationPrevious(self.state)
> def gotoPF(self):
> self.state = "PF"
> self.navigationPrevious(self.state)
>   
All of the above could store a method as well as or instead of a state. 
Then you can get rid of the big conditional below.

You don't show the code to create self.store.units so I don't know what 
kind of object is there. I'll assume they are instances of class Unit. 
Then you could write for example

def gotoPF(self):
self.state = "PF" # You may not need this
self.test = Unit.isfuzzy # This stores a reference to the correct 
method of Unit
self.navigationPrevious(self.state)

If you change all the gotoXX() methods this way, then navigated becomes just
def navigated(self):
if self.test(self.store.units[int(self.id)]:
return True

Kent
> def navigated(self):
> if (self.state == 'NF') and
> (self.store.units[int(self.id)].isfuzzy()):
> return True
> if (self.state == 'PF') and
> (self.store.units[int(self.id)].isfuzzy()):
> return True
> if (self.state == 'NT') and
> (self.store.units[int(self.id)].istranslated()):
> return True
> if (self.state == 'PT') and
> (self.store.units[int(self.id)].istranslated()):
> return True
> if (self.state == 'NU') and
> (self.store.units[int(self.id)].isuntranslated()):
> return True
> if (self.state == 'PU') and
> (self.store.units[int(self.id)].isuntranslated()):
> return True
> if (self.state == 'NA') and
> (self.store.units[int(self.id)].isapproved()):
> return True
> if (self.state == 'PA') and
> (self.store.units[int(self.id)].isapproved()):
> return True
>   


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


Re: [Tutor] how to run python's Graphical User Interface for Environments in agents.py

2006-07-28 Thread Kent Johnson
Сергій wrote:
>
>
> 
> 
>
>
> I am reading " Artificial Intelligence: A Modern Approach 
> http://aima.cs.berkeley.edu/ \n\nThis file was 
> not retrieved by Teleport Pro, because it is addressed on a domain or 
> path outside the boundaries set for its Starting Address. \n\nDo you 
> want to open it from the 
> server?'))window.location='http://aima.cs.berkeley.edu/'>" now 
> (http://aima.cs.berkeley.edu/), and there are some ready python code 
> from this book ( http://aima.cs.berkeley.edu/python/readme.html).
> And I have some problems with the code 
> http://aima.cs.berkeley.edu/python/agents.py
> It is said in the http://aima.cs.berkeley.edu/python/agents.html:
>
> # GUI - Graphical User Interface for Environments
> # If you do not have Tkinter installed, either get a new installation of
> Python
> # (Tkinter is standard in all new releases), or delete the rest of 
> this file
> # and muddle through without a GUI.
>
> I have python24.
> But just "*v = VacuumEnvironment(); w = EnvFrame(v);*" do nothing - I 
> don't see any Graphical User Interface for Environments.
> What am I doing wrong and how to compel this piece of code to return a 
> Graphical User Interface for Environments?

The entire last section of the code - from "import Tkinter as tk" to the 
end - is enclosed in triple-quotes ('''). This makes it into a string 
constant rather than code, effectively commenting it out. Try removing 
the two lines that just contain '''.

Kent

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


Re: [Tutor] playing around with function

2006-07-28 Thread Danny Yoo


>def navigated(self):
>if (self.state == 'NF') and
> (self.store.units[int(self.id)].isfuzzy()):
>return True
>if (self.state == 'PF') and
> (self.store.units[int(self.id)].isfuzzy()):
>return True
>if (self.state == 'NT') and
> (self.store.units[int(self.id)].istranslated()):
>return True
>if (self.state == 'PT') and
> (self.store.units[int(self.id)].istranslated()):
>return True
[code cut]


This code here looks highly repetitive, and there's really nothing bigger 
than a case analysis going on here.  I'd strongly recommend using a data 
structure to record the core essense of this code.

One possible refactoring is:


navigationTable = {'NF': 'isfuzzy',
'PF': 'isfuzzy',
'NT': 'istranslated',
...}
test = navigationTable(self.state)
unit = self.store.units[int(self.id)])
if test == 'isfuzzy':
 return unit.isfuzzy()
elif test == 'istranslated':
 return unit.istranslated()
...


The heart of that code is the mapping between states and the function to 
call at that state, so we can keep that knowledge centralized in a data 
structure.


I get the feeling that the remainder of the code is really too closely 
tied with GUI stuff; there's the finite-state automata thing that I see 
here, but it's entangled with Qt widget logic.  You may want to consider 
how to break the GUI stuff out of the navigational code.

>def navigationNext(self,state):
>if (self.getCurrentItem() == 0):
>return 0
>self.id = int(self.item.text(0))
>self.id += 1
>for i in range(self.id,775):
>self.id = i
>if (i == 775):
>pass
>#self.warningMessage()


Other comments: the condition testing for i == 775 seems impossible to me. 
775 is outside of the for loop's domain.  That code won't ever fire.

navigationNext() and navigationPrevious() look like the exact same 
function.  The only significant difference I see is the increment or 
decrement used to move 'id' around.  Have you considered turning that into 
a parameter?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to run python's Graphical User Interface for Environments in agents.py

2006-07-28 Thread Сергій
The entire last section of the code - from "import Tkinter as tk" to the end - is enclosed in triple-quotes ('''). This makes it into a string 
constant rather than code, effectively commenting it out. Try removing the two lines that just contain '''.Kent
 
I removed triple-quotes.
And after learning more about Tkinter I saw that a little changed code
 

v = VacuumEnvironment()w = EnvFrame(v)w.mainloop() 
shows the grid (it is graphical "environment" for agents).
 
But I am still working on how to put agents in this environment and to see their life in this environment...
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to run python's Graphical User Interface forEnvironments in agents.py

2006-07-28 Thread Alan Gauld
> I have python24.
> But just "*v = VacuumEnvironment(); w = EnvFrame(v);*" do nothing - 
> I don't
> see any Graphical User Interface for Environments.
> What am I doing wrong and how to compel this piece of code to return 
> a
> Graphical User Interface for Environments?

Did you delete the triple quotes around the Tkinter section?
Just after the quotation you posted and just before the end of the 
file?

Alan G. 

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


Re: [Tutor] how to run python's Graphical User Interface forEnvironments in agents.py

2006-07-28 Thread Сергій

2006/7/28, Alan Gauld <[EMAIL PROTECTED]>:
> I have python24.> But just "*v = VacuumEnvironment(); w = EnvFrame(v);*" do nothing -
> I don't> see any Graphical User Interface for Environments.> What am I doing wrong and how to compel this piece of code to return> a> Graphical User Interface for Environments?
Did you delete the triple quotes around the Tkinter section?Just after the quotation you posted and just before the end of thefile?Alan G.
 
yes, I did. (http://mail.python.org/pipermail/tutor/2006-July/048268.html) 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] MySQLdb question.

2006-07-28 Thread Ron Phillips


I am trying to write a script that adds data to a table using MySQLdb.py.  For some reason, "INSERT" seems to work temporarily. I run a command to insert a row, and then do a select query, and it's there. After the program shuts down, though, it's gone. No rows are permanently created. SELECT works fine from MySQLdb, CREATE TABLE too, but when I add data, it's only there while the script is executing, then it's gone.
 
I can add data from the MySQL Query Browser, and it's fine. 
 
I googled, but couldn't find anything. I'm running MySQL5, and the latest MySQLdb.py, too. Python 2.4.
 
I am using animal.py from http://www.kitebird.com/articles/pydbapi.html, but it's been the same thing with other scripts. Is it a setting, or a thinko, or what?
 
Ron
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] MySQLdb question.

2006-07-28 Thread Kent Johnson
Ron Phillips wrote:
> I am trying to write a script that adds data to a table using 
> MySQLdb.py.  For some reason, "INSERT" seems to work temporarily. I 
> run a command to insert a row, and then do a select query, and it's 
> there. After the program shuts down, though, it's gone. No rows are 
> permanently created. SELECT works fine from MySQLdb, CREATE TABLE too, 
> but when I add data, it's only there while the script is executing, 
> then it's gone.
Try calling conn.commit() before conn.close(). IIRC older versions of 
MySQL were set to auto-commit by default but newer versions require the 
explicit commit.

Kent

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


Re: [Tutor] MySQLdb question.

2006-07-28 Thread Ron Phillips

That was it all right! Thanks, Kent! Ron___Ron Phillips wrote:
> I am trying to write a script that adds data to a table using 
> MySQLdb.py.  For some reason, "INSERT" seems to work temporarily. I 
> run a command to insert a row, and then do a select query, and it's 
> there. After the program shuts down, though, it's gone. No rows are 
> permanently created. SELECT works fine from MySQLdb, CREATE TABLE too, 
> but when I add data, it's only there while the script is executing, 
> then it's gone.
Try calling conn.commit() before conn.close(). IIRC older versions of 
MySQL were set to auto-commit by default but newer versions require the 
explicit commit.

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


Re: [Tutor] MySQLdb question.

2006-07-28 Thread shawn bright
you may be missing db.commit(). When you do insert, update, etc.. you call commit() to make the changes stick.-skOn 7/28/06, Kent Johnson <
[EMAIL PROTECTED]> wrote:Ron Phillips wrote:> I am trying to write a script that adds data to a table using
> MySQLdb.py.  For some reason, "INSERT" seems to work temporarily. I> run a command to insert a row, and then do a select query, and it's> there. After the program shuts down, though, it's gone. No rows are
> permanently created. SELECT works fine from MySQLdb, CREATE TABLE too,> but when I add data, it's only there while the script is executing,> then it's gone.Try calling conn.commit() before conn.close
(). IIRC older versions ofMySQL were set to auto-commit by default but newer versions require theexplicit commit.Kent___Tutor maillist  -  
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Notes on namespaces, scopes, etc

2006-07-28 Thread Dave Kuhlman
On Thu, Jul 27, 2006 at 05:34:13PM +0100, Alan Gauld wrote:
> Hi Dave,
> 
> You are causing yourself some confusion by still treating variables
> as something other than a name. Your first paragraph says:
> 
> (Actually, functions and classes are just variables that hold
> references to function and class objects.)
> 
> Which is wrong. variables are simply names that refer to objects,
> which includes functions and classes(and instances of classes)
> Thus a function is never a variable. variables refer to functions.
> 
> In Computer Science terms a function is a lamda expression
> and a def in Python should be a shorthand way of doing
> 
> var = lambda params... : expression
> 
> Unfortunately, in practice, in Python it's the other way around.
> The lambda is really an alternative for
> 
> def var(params...):
> return expression
> 
> But it is important to realize that names in Python - all names - are
> simply references to objects of some kind. and that classes, 
> instances,
> functions, numbers, lists, characters etc  are all objects in this 
> sense.
> 

Rats.  I wish I'd said it that way.  Can I steal that quote?

Thanks, Alan and Kent, for trying to straighten me out on this.
And, by the way, since I'll be trying to explain this in the next
class I teach, you are doing more than just clear the darkness of
confusion from *my* mind; you may also be helping to prevent me
from confusing students in my next class.

Let me try to summarize a few points that Alan has tried to
explain about variables, names, namespaces, values, and objects.
Let's see if I can get it right this time:

A variable is a name bound to a value in a namespace.

A namespace is a dictionary in which Python can look up a name
(possibly) to obtain its value.

Names refer to objects.  Objects can be integers, tuples, lists,
dictionaries, strings, instances of classes, functions, classes
(themselves), other Python built-in types, and instances of
classes.

In Python, (and here I'm trying to go a bit beyond Alan) since the
use of objects and references to them are so pervasive and
consistent, we sometimes conflate a variable and the object it
refers to.  So, for example, if we have the following code::

total = 25
items = [11, 22, 33]
def func1():
pass
class Class1:
pass

we sometimes say:

- ``total`` is an integer.

- ``items`` is an list.

- ``func1`` is a function.

- ``Class1`` is a class.

But, if we were more careful, we might say:

- ``total`` is a variable that refers to an integer object.

- ``items`` is a variable that refers to a list object.

- ``func1`` is a variable that refers to a function object.

- ``Class1`` is a variable that refers to a class object.

Or, even:

- ``total`` is a name bound to an integer object in the current
  namespace.

- ``items`` is a name bound to a list object in the current namespace.

- ``func1`` is a name bound to an function object in the current
  namespace.

- ``Class1`` is a name bound to an class object in the current
  namespace.

And, it is important to remember:

1. Names are references to objects and

2. Objects are first class, which means that we can:

   - Store them in variables.

   - Store them in data structures.

   - Pass them to functions and methods.

   - Return them from functions and methods.

There, am I any closer?

The point that ``def func1: ...`` creates a variable "func1" is
one that I believe is not clear to someone new to programming or
even to someone familiar only with languages like C, C++, or Java.

Give me a little more time to address and respond to the rest of
Alan's comments.

Dave

[more good comments snipped]

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Notes on namespaces, scopes, etc

2006-07-28 Thread Dave Kuhlman
On Thu, Jul 27, 2006 at 12:46:44PM -0400, Kent Johnson wrote:
> Dave Kuhlman wrote:
> > I've written up a few notes on Python namespaces and scopes.  If
> > anyone has corrections, comments, or suggestions, I'd appreciate
> > them. You can find my comments here:
> >
> > http://www.rexx.com/~dkuhlman/python_comments.html#namespaces
> 
> You wrote, "If a variable is assigned a value /anywhere/ in a scope 
> (...), then that variable is local to that scope. Otherwise, the 
> variable is global."
> 
> You omit the enclosing scope and the builtin namespace. A variable can 
> be defined in
> - local scope
> - any of zero or more enclosing scopes
> - global scope
> - builtin namespace

Thanks.  I've added the built-in namespace to my notes.

But, I don't believe in the existence of nested namespaces.  I
think they are a hoax.  Some people believe that nested namespaces
were added sometime around Python 2.1 or 2.2.  But, that's just a
fraud.  If there were really such a thing as nested
scopes/namespaces, we would have a function that would give us
access to them, similar to the way that locals() and globals()
give us access to the local and global namespace.

> 
> Names are also bound by for statements and except clauses.

Right.  I've added that, now.

> 
> You might note that augmented assignment (e.g. a += 1) counts as 
> assignment in the local scope. This is a common cause of UnboundLocalError:
> 
> In [5]: a=1
> 
> In [6]: def foo():
>...: a+=1
>...:
>...:
> 
> In [7]: foo()
> ---
> exceptions.UnboundLocalError Traceback (most 
> recent call last)
> 
> D:\Projects\e3po\
> 
> D:\Projects\e3po\ in foo()
> 
> UnboundLocalError: local variable 'a' referenced before assignment
> 
> 
> I think modifying globals() is guaranteed to work. Modifying locals() 
> only works at global scope, i.e. when locals() is globals().
> 
> You wrote, "Note that for lexically/statically nested scopes (for 
> example, a function defined inside a function), it seems that globals() 
> and locals() still give access to all items in the accessible 
> namespaces." I'm not sure what you mean by this. locals() doesn't give 
> access to items in nested scopes:
> 

You are right.  I'm confused about this.  But, it is Python's
fault.  See more below.

> In [1]: x=1
> 
> In [2]: def maker():
>...: y=2
>...: def showLocals():
>...: z=3
>...: print locals()
>...: return showLocals
>...:
> 
> In [3]: sl=maker()
> 
> In [4]: sl()
> {'z': 3}
> 

Oh yeah?  Well, what about this?

In [1]: def maker():
   ...: y=2
   ...: def showLocals():
   ...: z=3
   ...: keys = locals().keys()
   ...: keys.sort()
   ...: print 'locals:', keys
   ...: keys = globals().keys()
   ...: keys.sort()
   ...: print 'globals:', keys
   ...: return showLocals
   ...:
In [2]: sl = maker()
In [3]: sl()
locals: ['z']
globals: ['In', 'Out', '_', '__', '__IP', '___', '__builtins__', 
'__name__', '__nonzero__', '_dh', '_i', '_i0', '_i1', '_i2', 
'_i3', '_ih', '_ii', '_iii', '_oh', 'help', 'maker', 'sl']

So, were is y?  See, nested scopes do not exist.

> See also
> http://docs.python.org/ref/naming.html
> 

OK.  Trying to be a little more serious ... Maybe Python now
*does* have nested scopes, but Python does not give us a function
to access them.  Or does it?

Thanks again for the help.

Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Notes on namespaces, scopes, etc

2006-07-28 Thread Danny Yoo
> If there were really such a thing as nested scopes/namespaces, we would 
> have a function that would give us access to them, similar to the way 
> that locals() and globals() give us access to the local and global 
> namespace.

It would be _convenient_ to have such a function for inspection, but it's 
not a requirement.

Here's a function that shows lexical scope in action:

##
>>> def pair(x, y):
... def f(b):
... if b: return x
... return y
... return f
...
>>> p = pair(3, 4)
>>> p(True)
3
>>> p(False)
4
##
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] visualization

2006-07-28 Thread Сергій
I have a world (environment), where live different objects.
And all objects like to move.
 
This is the code:
"""

import random, time, Tkinter
class Object:    def __init__ (self, x=10, y=10):    self.name = random.randint(0, 10)    self.x = x    self.y = y
    def __repr__ (self):    return str(self.name)        def display(self, canvas, x, y, width, height):    """Display an image of this Object on the canvas."""
    pass
    def rand_vec(self):    return random.randint(-1, 1), random.randint(-1, 1)    
class Environment:    def __init__ (self):    self.objects = []
    def step(self):    for obj in self.objects:    old_x, old_y = obj.x, obj.y    change_x, change_y = obj.rand_vec()    obj.x, obj.y = old_x + change_x, old_y + change_y
    print obj.name, '\t:\t ', old_x, old_y,' -> ', obj.x, obj.y  
    def run(self, steps=10):    """Run the Environment for given number of time steps."""    for step in range(steps):    self.step()    time.sleep
(2)  
    def add_object(self, object):    print object.name, ' was added to environment'    self.objects.append(object)
print '\tBORN'env = Environment()for obj in range(10):    child = Object()    print child, ' was born'    env.add_object(child)
print '\tLIFE'env.run(100)
"""
 
And now I want to visualizate this world.
What modules can you advise me for "easy" visualization?
"Easy" means that it would be really nice if I could do vizualization with minimum change of existing classes.
 
Thanks in advance.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Problems with encoding

2006-07-28 Thread mjekl
>kent37 at tds.net wrote:

>>mjekl at iol.pt wrote:
>> Hi,
>>
>>
>> My interpreter in set via sitecustomize.py to use utf-8 as default encoding.
>>
>> I'm reading fields from a dbf table to a firebird db with encoding set to 
>> win1252.
>> I guess it's original encoding is cp850, but am not sure, and have been 
>> addressing exceptions one by one with lines of:
>>
>> r = r.replace(u'offending_code', u'ok_code')
>>   
>Why don't you just convert from cp850 to cp1252 directly? Python 
>supports both encodings, it's as simple as
>some_string.decode('cp850').encode('cp1252')

In the mean while somewhat accidently (read some stuff) I followed a similar 
approach.

[...] ORIGINAL POST DELETED HERE [...]

>My guess is a coding error on your part, otherwise something would have 
>changed...can you show some context in import_pcfcli.py?

I also expect it's my error ;-(   ;-)

The following snippet of my present code isn't giving me any problems. Although 
I'm not really sure why it works. Also I had some problems encoding to 'cp1252' 
and not to 'utf-8'.

Anyone as a pointer to a nice resource that can help me understand this decode 
/ encode biz better?

 try:
# TODO: Check the str.translate() method
r = recordSet.Fields(fieldsDict[f]).Value.strip()
r.decode('cp850')
r = r.replace(u'\x8f', u'')
r = r.replace(u'\u20ac', u'\xc7')
r = r.replace(u'\xa6', u'\xaa')
r = r.replace(u'\u2122', u'\xd5')
r = r.replace(u'\u017d', u'\xc3')
r = r.replace(u'\xa7', u'\xba')
# The following line does not work if with 'cp1252' !?
rec.append(r.encode('utf-8')) # kinterbasdb makes 
conversions by itself ;-)
except UnicodeDecodeError, UnicodeEncodeError:
print f
return None

Txs,
Miguel

___
Uma mensalidade a medida da sua carteira.
Saber mais em http://www.iol.pt/correio/rodape.php?dst=0607191

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


Re: [Tutor] Notes on namespaces, scopes, etc

2006-07-28 Thread Kent Johnson
Dave Kuhlman wrote:
> On Thu, Jul 27, 2006 at 05:34:13PM +0100, Alan Gauld wrote:
>   
>> Hi Dave,
>>
>> You are causing yourself some confusion by still treating variables
>> as something other than a name. Your first paragraph says:
>>
>> (Actually, functions and classes are just variables that hold
>> references to function and class objects.)
>>
>> Which is wrong. variables are simply names that refer to objects,
>> which includes functions and classes(and instances of classes)
>> Thus a function is never a variable. variables refer to functions.
>>
>> In Computer Science terms a function is a lamda expression
>> and a def in Python should be a shorthand way of doing
>>
>> var = lambda params... : expression
>>
>> Unfortunately, in practice, in Python it's the other way around.
>> The lambda is really an alternative for
>>
>> def var(params...):
>> return expression
>>
>> But it is important to realize that names in Python - all names - are
>> simply references to objects of some kind. and that classes, 
>> instances,
>> functions, numbers, lists, characters etc  are all objects in this 
>> sense.
>>
>> 
>
> Rats.  I wish I'd said it that way.  Can I steal that quote?
>
> Thanks, Alan and Kent, for trying to straighten me out on this.
> And, by the way, since I'll be trying to explain this in the next
> class I teach, you are doing more than just clear the darkness of
> confusion from *my* mind; you may also be helping to prevent me
> from confusing students in my next class.
>
> Let me try to summarize a few points that Alan has tried to
> explain about variables, names, namespaces, values, and objects.
> Let's see if I can get it right this time:
>
> A variable is a name bound to a value in a namespace.
>
> A namespace is a dictionary in which Python can look up a name
> (possibly) to obtain its value.
>
> Names refer to objects.  Objects can be integers, tuples, lists,
> dictionaries, strings, instances of classes, functions, classes
> (themselves), other Python built-in types, and instances of
> classes.
>
> In Python, (and here I'm trying to go a bit beyond Alan) since the
> use of objects and references to them are so pervasive and
> consistent, we sometimes conflate a variable and the object it
> refers to.  So, for example, if we have the following code::
>
> total = 25
> items = [11, 22, 33]
> def func1():
> pass
> class Class1:
> pass
>
> we sometimes say:
>
> - ``total`` is an integer.
>
> - ``items`` is an list.
>
> - ``func1`` is a function.
>
> - ``Class1`` is a class.
>
> But, if we were more careful, we might say:
>
> - ``total`` is a variable that refers to an integer object.
>
> - ``items`` is a variable that refers to a list object.
>
> - ``func1`` is a variable that refers to a function object.
>
> - ``Class1`` is a variable that refers to a class object.
>
> Or, even:
>
> - ``total`` is a name bound to an integer object in the current
>   namespace.
>
> - ``items`` is a name bound to a list object in the current namespace.
>
> - ``func1`` is a name bound to an function object in the current
>   namespace.
>
> - ``Class1`` is a name bound to an class object in the current
>   namespace.
>
> And, it is important to remember:
>
> 1. Names are references to objects and
>
> 2. Objects are first class, which means that we can:
>   
Right up to here, I'm standing on my chair and cheering.
>- Store them in variables.
>   
Ouch! No! Variables don't store values, they refer to values. Thinking 
of variables as containers doesn't work in Python.
>- Store them in data structures.
>   
That's a little better, but really you store a reference to a value in a 
data structure. It's references all the way down ;)
>- Pass them to functions and methods.
>
>- Return them from functions and methods.
>
> There, am I any closer?
>   
Lots closer.
> The point that ``def func1: ...`` creates a variable "func1" is
> one that I believe is not clear to someone new to programming or
> even to someone familiar only with languages like C, C++, or Java.
>   
Better to say "def func1:" creates a function object and binds it to the 
name "func1". And your point is a good one, that this takes a little 
getting used to. By the way "class k2:" creates a class object and binds 
it to a name also. Namespaces and name binding are pervasive in Python.

Kent

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


Re: [Tutor] Notes on namespaces, scopes, etc

2006-07-28 Thread Kent Johnson
Dave Kuhlman wrote:
> If there were really such a thing as nested
> scopes/namespaces, we would have a function that would give us
> access to them, similar to the way that locals() and globals()
> give us access to the local and global namespace.
>   
Nested namespaces are actually stored with the nested function. They are 
also called closures. For example:

In [1]: def m(x):
   ...: y=3
   ...: def f(z):
   ...: print x, y, z
   ...: return f
   ...:

In [2]: ff=m(2)

Just to prove that the closure exists:
In [3]: ff(5)
2 3 5

The closure is stored in the func_closure attribute of the function:
In [5]: ff.func_closure
Out[5]:
(,
 )

In [6]: ff.func_closure[0]
Out[6]: 

This is pretty opaque. There is a way to get the values out; see this 
recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439096

For more discussion, search comp.lang.python for func_closure.

Kent

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