Re: Rendering HTML

2005-09-17 Thread Jorgen Grahn
On 16 Sep 2005 22:56:06 -0700, Harlin Seritt <[EMAIL PROTECTED]> wrote:
> Hi DH,
>
> Thanks for this blurb from ASPN. I am really looking, however, to do

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52297

> this on a Windows machine as opposed to a Unix one at this point. This
> will come in handy down the road I am sure.

If it's popen()ing tput that worries you, you can probably replace bold,
underline and reset with the corresponding ANSI escape sequences. Or the
empty string! Assuming you will print to a cmd.exe window, that is.

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Possible bug in "metaclass resolution order" ?

2005-09-17 Thread Simon Percivall
Have you read the "Metaclasses" part of "Unifying types and classes in
Python 2.2"? (http://www.python.org/2.2.3/descrintro.html#metaclasses)

It discusses and explains the issues you seem to have.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 2.3 -> 2.4: long int too large to convert to int

2005-09-17 Thread Reinhold Birkenfeld
Grant Edwards wrote:
> I give up, how do I make this not fail under 2.4?
> 
>   fcntl.ioctl(self.dev.fileno(),0xc0047a80,struct.pack("HBB",0x1c,0x00,0x00))
> 
> I get an OverflowError: long int too large to convert to int
> 
> ioctl() is expecting a 32-bit integer value, and 0xc0047a80 has
> the high-order bit set.  I'm assuming Python thinks it's a
> signed value.  How do I tell Python that 0xc0047a80 is an
> unsigned 32-bit value?

This is fixed in the 2.5 CVS branch, where the ioctl() Python C wrapper
expects an unsigned integer instead of a signed one.

Reinhold
-- 
http://mail.python.org/mailman/listinfo/python-list


Wrapping float

2005-09-17 Thread Sybren Stuvel
Hi all,

I'm trying to make a float-like class (preferably a subclass of
'float') that wraps around. The background: I'm modeling a
multi-dimensional space, and some of those dimensions are circular.

Here is my code so far:

class WrapFloat(float):
def __init__(self, value, wrap = None):
float.__init__(self, value)
self.wrap = wrap

The problem is this:

Python 2.4.1 (#2, Mar 30 2005, 21:51:10) 
[GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from engine.geometry import WrapFloat
>>> WrapFloat(45)
45.0
>>> WrapFloat(45, 3)
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: float() takes at most 1 argument (2 given)

So my question to you is: how can I change my code so I can pass two
values to the WrapFloat constructor?

Thanks in advance,
Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Software bugs aren't inevitable

2005-09-17 Thread Sybren Stuvel
phil hunt enlightened us with:
> If a program is too slow to respond isn't that about "system time"?

Not by definition. Could be anything. If it's slow to respond due to a
slow harddisk, then you're right. If it's slow to respond due to not
putting the I/O and the GUI main loop in different threads, then it's
not about "system time".

> What does "CPU time" mean again?

The time the CPU takes to run (part of) a program. And this means the
time the CPU actually spends on running that program, and not some
other piece of software.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Do thread die?

2005-09-17 Thread Sybren Stuvel
Maurice LING enlightened us with:
> So, at the end of run(), what happens to the thread? Just die?

Yep.

> While I am on it, can threading.Thread.run() accept any parameters?

Nope. Pass them to the constructor and remember them.

> class myThread(threading.Thread):
>  def __init__(self, func):
>  self.func = func
>  threading.Thread.__init__(self)
>  def run(self):
>  print '%s function running' % self.func
>  self.func()

You don't need to do this, since you can pass a callable object to the
Thread constructor. Read the first lines of
http://docs.python.org/lib/thread-objects.html again. That would
change your code to:

class myClass:
 def __init__(self): pass
 def aFunc(self): pass
 def bFunc(self): pass

 def runAll(self):
 threading.Thread(self.aFunc).start()
 threading.Thread(self.bFunc).start()

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Brute force sudoku cracker

2005-09-17 Thread Sybren Stuvel
Bas enlightened us with:
> I came across some of these online sudoku games and thought after
> playing a game or two that I'd better waste my time writing a solver
> than play the game itself any longer. I managed to write a pretty
> dumb brute force solver that can at least solve the easy cases
> pretty fast.

I've got a solver too - I'm joining the Linux Format programming
contest. My program can solve and create Sudoku puzzles - and not only
9x9 ones. Check http://www.unrealtower.org/sodoku. In the LFX
programming contest they call the puzzle Sodoku, not Sudoku, so that's
why I'm sticking with the name Sodoku for now.

> -any improvements possible for the current code? I didn't play a lot
> with python yet, so I probably missed some typical python tricks,
> like converting for-loops to list expressions.

It all depends on what you want to do. My program can create & solve
puzzles from any size, load and save them to disk, check them for
validity and rank them ('easy', 'medium', 'hard', 'near impossible').
It also implements a puzzle in a class, so it can be used in an OOP
fashion.

> def all(seq, pred=bool):

What's this? What is bool?

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wrapping float

2005-09-17 Thread Bengt Richter
On Sat, 17 Sep 2005 11:12:34 +0200, Sybren Stuvel <[EMAIL PROTECTED]> wrote:

>Hi all,
>
>I'm trying to make a float-like class (preferably a subclass of
>'float') that wraps around. The background: I'm modeling a
>multi-dimensional space, and some of those dimensions are circular.
>
>Here is my code so far:
>
>class WrapFloat(float):
>def __init__(self, value, wrap = None):
>float.__init__(self, value)
>self.wrap = wrap
>
>The problem is this:
>
>Python 2.4.1 (#2, Mar 30 2005, 21:51:10) 
>[GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2
>Type "help", "copyright", "credits" or "license" for more information.
 from engine.geometry import WrapFloat
 WrapFloat(45)
>45.0
 WrapFloat(45, 3)
>Traceback (most recent call last):
>  File "", line 1, in ?
>TypeError: float() takes at most 1 argument (2 given)
>
>So my question to you is: how can I change my code so I can pass two
>values to the WrapFloat constructor?
>
Float is an immutable, so you need to override __new__

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Do thread die?

2005-09-17 Thread Bryan Olson
Maurice LING wrote:
 > Hi,
 >
 > I just have a simple question about threads. My classes inherits from
 > threading.Thread class. I am calling threading.Thread.run() method to
 > spawn a few threads to parallel some parts of my program. No thread
 > re-use, pooling, joining ... just plainly spawn a thread, run a routine.
 >
 > So, at the end of run(), what happens to the thread? Just die?

Just die, mostly. It may do a bit of clean-up, setting its
affairs in order, arraning for burial/cremation/organ-donation
and such, to avoid leaving any problem for posterity.


Incidentally, the "threading" module, with its "Thread" class,
has one major advantage over the "thread" module: the "setDaemon"
method of class Thread.


 > While I am on it, can threading.Thread.run() accept any parameters?

Not unless you override it; but you can pass parameters when
constructing the Thread, like this:

t = Thread(target=work_to_do, args=(67, 'Bill Johnston'), kwargs=some_dict)

t.start() will then execute the default Thread.run(), which
will execute work_to_do with two positional arguments -- 67 and
'Bill Johston' -- and whatever key-word arguments were in some_dict.

If you override 'Thread.run', you can define your override to take
whatever parameters you want.


 > My current implementation may be ugly. I have a class
 >
 > class myThread(threading.Thread):
 > def __init__(self, func):
 > self.func = func
 > threading.Thread.__init__(self)
 > def run(self):
 > print '%s function running' % self.func
 > self.func()

[...]

 > Is this a good way?

I don't see anything wrong with it, though to me, it seems a
little heavy. To run your func, all you need to do is:

 Thread(target=func).start()

Though nine times out of ten, you'd want:

 t = Thread(target=func, args=(arg1, arg2, and_so_on))
 t.setDaemon(True)
 t.start()

If you really need that "print", you could build it into your
'target' function; or you could subclass Thread more generally,
so your subclass adds the print and behaves exactly the same
otherwise. I regard debugging as important, but I do not
believe that this  particular print warrants the general
inclusion implied.


Other Pythoners have disagree with me on various matters at
issue here. In particular, others have disagreed with my
advocacy of multiple lines of execution.


-- 
--Bryan
-- 
http://mail.python.org/mailman/listinfo/python-list


problem with setup.py

2005-09-17 Thread andrea valle
Hi to all,
and sorry for cross-posting.

I'm having troubles with installing packages.
I'm on macosx 10.3.8 and I have activestate python 2.4

For example, pyrtf an pyx.
it is the first time I install packages so pardon me if it's obvious.

I call python from terminal, I pass the absolute path of the setup.py 
with command install, and results are always:
error: $MACOSX_DEPLOYMENT_TARGET mismatch: now "" but "10.3" during 
configure

For example with pyrtf:

apples-Computer:~ apple$ python 
/Users/apple/Desktop/PyRTF-0.45/setup.py installrunning install
error: $MACOSX_DEPLOYMENT_TARGET mismatch: now "" but "10.3" during 
configure

What should I do? I guess I have to hack some configuration, but don't 
know which.

  Thanks a lot

-a-


Andrea Valle
Laboratorio multimediale "G. Quazza"
Facoltà di Scienze della Formazione
Università degli Studi di Torino
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wrapping float

2005-09-17 Thread Robert Kern
Sybren Stuvel wrote:
> Hi all,
> 
> I'm trying to make a float-like class (preferably a subclass of
> 'float') that wraps around. The background: I'm modeling a
> multi-dimensional space, and some of those dimensions are circular.
> 
> Here is my code so far:
> 
> class WrapFloat(float):
> def __init__(self, value, wrap = None):
> float.__init__(self, value)
> self.wrap = wrap
> 
> The problem is this:
> 
> Python 2.4.1 (#2, Mar 30 2005, 21:51:10) 
> [GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> 
from engine.geometry import WrapFloat
WrapFloat(45)
> 
> 45.0
> 
WrapFloat(45, 3)
> 
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: float() takes at most 1 argument (2 given)
> 
> So my question to you is: how can I change my code so I can pass two
> values to the WrapFloat constructor?

You also have to override __new__ I think. It automatically gets passed
the arguments to __init__. C.f.
http://www.python.org/2.2/descrintro.html#__new__

In [11]: class WrapFloat(float):
   : def __new__(cls, value, *args, **kwds):
   : return float.__new__(cls, value)
   : def __init__(self, value, wrap=None):
   : float.__init__(self, value)
   : self.wrap = wrap
   :

In [12]: x = WrapFloat(45, 3)

In [13]: x
Out[13]: 45.0

In [14]: x.wrap
Out[14]: 3

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wrapping float

2005-09-17 Thread Sybren Stuvel
Bengt Richter enlightened us with:
> Float is an immutable, so you need to override __new__

Thanks, that works!

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with setup.py

2005-09-17 Thread Robert Kern
andrea valle wrote:
> Hi to all,
> and sorry for cross-posting.
> 
> I'm having troubles with installing packages.
> I'm on macosx 10.3.8 and I have activestate python 2.4
> 
> For example, pyrtf an pyx.
> it is the first time I install packages so pardon me if it's obvious.
> 
> I call python from terminal, I pass the absolute path of the setup.py 
> with command install, and results are always:
> error: $MACOSX_DEPLOYMENT_TARGET mismatch: now "" but "10.3" during 
> configure
> 
> For example with pyrtf:
> 
> apples-Computer:~ apple$ python 
> /Users/apple/Desktop/PyRTF-0.45/setup.py installrunning install
> error: $MACOSX_DEPLOYMENT_TARGET mismatch: now "" but "10.3" during 
> configure
> 
> What should I do? I guess I have to hack some configuration, but don't 
> know which.

Add the following line to your ~/.bashrc (assuming that you are using
bash as your shell):

  export MACOSX_DEPLOYMENT_TARGET=10.3

Then start a new Terminal.app window (the change doesn't take effect
until a new shell is started).

I haven't needed to do this with the official 2.4.1 build, so you should
complain to ActiveState. Or use the official build.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary sorting problem

2005-09-17 Thread Duncan Booth
Bengt Richter wrote:

> or tell sorted what to do ;-)
> 
> >>> original= {
>  ... 'hello':135,
>  ... 'goodbye':30,
>  ... 'lucy':4,
>  ... 'sky':55,
>  ... 'diamonds':239843,
>  ... 'yesterday':4 }
> >>> list(sorted(original.iteritems(), None, lambda t:t[1], True))
>  [('diamonds', 239843), ('hello', 135), ('sky', 55), ('goodbye', 30),
>  ('yesterday', 4), ('lucy',4)] 

or a slight variation on this theme which just gives you the keys in value 
order rather than the tuples:

>>> for k in sorted(original, key=original.get, reverse=True):
print k, original[k]


diamonds 239843
hello 135
sky 55
goodbye 30
yesterday 4
lucy 4
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Brute force sudoku cracker

2005-09-17 Thread Tom Anderson
On Fri, 16 Sep 2005, Bas wrote:

> -any ideas how to easily incorporate advanced solving strategies? 
> solve(problem1) and solve(problem2) give solutions, but solve(problem3) 
> gets stuck...

the only way to solve arbitrary sudoku problems is to guess.

of course, you have to deal with guessing wrongly, and it helps if you can 
make good guesses!

i wrote a solver based entirely on guessing and backtracking a few months 
ago; it's fairly simple, although i wrote it in fairly fine-grained java, 
so there's actually quite a lot of code. i had a very different program 
structure to you, since i was only doing guesswork; i had a recursive 
function that looked like this:

def solve(grid):
"""Solves a grid.

The solution is written in the grid; if no solution can be found, does 
nothing to the grid. Returns True if a solution was found, False if not. 
"""
x, y = pick_an_empty_cell_to_try(grid)
letters = letters_which_can_be_written_in_this_cell(grid, x, y)
if (letters == []):
return False # there are no legal moves; give up
for letter in letters:
grid.write(x, y, letter) # try a move ...
if (solve(grid)):
return True # we win!
grid.erase(x, y) # ... undo it if it didn't work
return False # none of the legal moves work; give up

the implementation of the grid class is pretty straightforward - it's just 
a two-dimensional matrix with some bells and whistles. 
letters_which_can_be_written_in_this_cell is also fairly simple, although 
it can be made a lot faster by keeping summary information in the grid 
object: i had a set for each row, column and region saying which letters 
had been written already, so the set of available letters was the inverse 
of the union of the sets relevant to the cell; the sets were implemented 
as bitmaps, so this was all very fast.

the only tricky bit is pick_an_empty_cell_to_try; you can have fun trying 
different heuristics here! the nice thing is that it's okay to use quite 
computationally expensive heuristics, since a modestly better choice can 
save huge numbers of recursions.

there are a number of much, much more advanced algorithms out there, doing 
all sorts of clever stuff. however, my algorithm solves any sudoku i can 
throw at it (barring seriously unreasonable stuff) in under a second, so 
i'm happy with it.

tom

-- 
I content myself with the Speculative part [...], I care not for the Practick. 
I seldom bring any thing to use, 'tis not my way. Knowledge is my ultimate end. 
-- Sir Nicholas Gimcrack
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lines of Strings

2005-09-17 Thread Tom Anderson
On Thu, 15 Sep 2005, Reem Mohammed wrote:

> Suppose we have data file like this one (Consider all lines as strings )
>
> 1 2 3 3 4 4 4 4 5 6
> 2 2 2 5 5 5 6
> 3 2 1 1 1 3 3 3 4 6
>
> I would like to remove line if its belong to another one, and will be 
> able to do this if longer line come after a short one.

when you say "belong to another one", do you mean "is a substring of 
another one"? so 4 5 6 would belong to 1 2 3 4 5 6 7 8?

if so, what you're asking for is the set of upper bounds of a partially 
ordered set. i often find that i need to compute things like this; i 
haven't figured out a way to do it any faster than the obvious:

def upperbounds(set, order):
"""Finds the upper bounds of a set under a partial order.

Set is an iterable (which may contain duplicates - it doesn't actually 
need to be a set), and order is a function of two arguments such that 
order(a, b) returns True if a is greater than b, and False otherwise.

"""
bounds = [] # this would be better as a set, really
for item in set:
for bound in bounds:
if (order(bound, item)):
break
if (order(item, bound)):
bounds.remove(bound)
else:
bounds.append(item)
return bounds

you could use this as follows:

lines = map(str.strip, inputfile.readlines())
print upperbounds(lines, str.__contains__)

tom

-- 
I content myself with the Speculative part [...], I care not for the Practick. 
I seldom bring any thing to use, 'tis not my way. Knowledge is my ultimate end. 
-- Sir Nicholas Gimcrack
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: FTP status problems. (Again)

2005-09-17 Thread Nainto
Thanks, I'll give this a try. This will print a period right?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Do thread die?

2005-09-17 Thread Steve Horsley
Maurice LING wrote:
> Hi,
> 
> I just have a simple question about threads. My classes inherits from 
> threading.Thread class. I am calling threading.Thread.run() method to 
> spawn a few threads to parallel some parts of my program. No thread 
> re-use, pooling, joining ... just plainly spawn a thread, run a routine.
> 
> So, at the end of run(), what happens to the thread? Just die?

As far as you are concerned, yes. They really just return to 
wherever they came from. How they get created before they call 
the run() method, and where they go after run() returns is down 
to the implementation of the interpreter. Your code never sees 
them before or after.
> 
> While I am on it, can threading.Thread.run() accept any parameters?
> 
No. But you can override it in a subclass.

> My current implementation may be ugly. I have a class
> 
> class myThread(threading.Thread):
> def __init__(self, func):
> self.func = func
> threading.Thread.__init__(self)
> def run(self):
> print '%s function running' % self.func
> self.func()
> 
> which is used in
> 
> class myClass: #using myThread
> def __init__(self): pass
> def aFunc(self): pass
> def bFunc(self): pass
> def runAll(self):
> myThread(self.aFunc).start()
> myThread(self.bFunc).start()


There is a school of thought that says that a derived object 
should never be altered such that it cannot be used as its parent 
could. I happen to agree largely with this. Now, your MyThread 
implementation is _reducing_ the functionality of its ancestor 
Thread object such that you could not use a myThread in place of 
a Thread. I believe that you should not be subclassing Thread to 
do this. Your myClass doesn't need it anyway. Look at this 
modified myClass:

class myClass2:
 def aFunc(self): pass
 def bFunc(self): pass
 def runAll(self):
 threading.Thread(target=self.aFunc).start()
 threading.Thread(target=self.bFunc).start()


Steve
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: FTP status problems. (Again)

2005-09-17 Thread Nainto
When I execute  the folllowing code with all of the address, username,
and passwords filled out I gt an error saying:
"/Library/Frameworks/Python.framework/Versions/2.4/Resources/Python.app/Contents/MacOS/Python"
"/Users/zacim/Documents/FireUpFTP/foramttedthing" ; exit
Traceback (most recent call last):
  File "/Users/zacim/Documents/FireUpFTP/foramttedthing", line 26, in ?
fname = sys.argv[1]
IndexError: list index out of range
logout
[Process completed]

This is the code:

import ftplib
class ProgressFile(file):
def read(self, size = None):
from sys import stdout

if size is not None:
buff = file.read(self, size)
if buff:
stdout.write('.')
else:
stdout.write('\n')
return buff
else:
buff = ''
while True:
new_str = file.read(self, 1024)
stdout.write('.')
if new_str:
buff = buff + new_str
else:
stdout.write('\n')
break
return buff
if __name__ == '__main__':
import sys
fname = sys.argv[1]
f = ProgressFile(fname)
f.read()

ftp = ftplib.FTP("ftp.sadpanda.cjb.cc")
ftp.login("sadpanda","s4dp4nd4b1g")
file = "/FrenchBrochure.pages.zip.gz"
ftp.storbinary("STOR " + file, ProgressFile(file, "rb"), 1024)
ftp.quit()

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Do thread die?

2005-09-17 Thread Maurice LING

> 
>> My current implementation may be ugly. I have a class
>>
>> class myThread(threading.Thread):
>> def __init__(self, func):
>> self.func = func
>> threading.Thread.__init__(self)
>> def run(self):
>> print '%s function running' % self.func
>> self.func()
>>
>> which is used in
>>
>> class myClass: #using myThread
>> def __init__(self): pass
>> def aFunc(self): pass
>> def bFunc(self): pass
>> def runAll(self):
>> myThread(self.aFunc).start()
>> myThread(self.bFunc).start()
> 
> 
> 
> There is a school of thought that says that a derived object should 
> never be altered such that it cannot be used as its parent could. I 
> happen to agree largely with this. Now, your MyThread implementation is 
> _reducing_ the functionality of its ancestor Thread object such that you 
> could not use a myThread in place of a Thread. I believe that you should 
> not be subclassing Thread to do this. Your myClass doesn't need it 
> anyway. Look at this modified myClass:
> 
> class myClass2:
> def aFunc(self): pass
> def bFunc(self): pass
> def runAll(self):
> threading.Thread(target=self.aFunc).start()
> threading.Thread(target=self.bFunc).start()
> 
Thanks everyone. Furthering that, is the following legal?

class myClass3:
 def aFunc(self, a): pass
 def bFunc(self, b): pass
 def runAll(self, a, b):
 threading.Thread(target=self.aFunc, args = (a)).start()
 threading.Thread(target=self.bFunc, args = (b)).start()

I do have another dumb question which is OT here. Say aFunc method 
instantiates a SOAP server that serves forever, will it prevent bFunc 
from running as a separate thread?

For example,

class myClass4:
 def repeat(self, s): return s+s
 def aFunc(self, a):
 import SOAPpy
 serv = SOAPpy.SOAPServer((a[0], a[1]))
 serv.registerFunction(repeat)
 serv.serve_forever()
 def bFunc(self, b): pass
 def runAll(self, a, b):
 threading.Thread(target=self.aFunc, args = (a)).start()
 threading.Thread(target=self.bFunc, args = (b)).start()

if __name__=='__main__': myClass4().runAll(['localhost', 8000], 'hi')

Will the 2nd thread (bFunc) ever run since the 1st thread is running 
forever? Intuitively, I think that both threads will run but I just want 
to be doubly sure, because some of my program logic depends on the 2nd 
thread running while the 1st thread acts as a SOAP server or something.

Thanks and Cheers
Maurice
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Brute force sudoku cracker

2005-09-17 Thread Pierre Barbier de Reuille
Tom Anderson a écrit :
> On Fri, 16 Sep 2005, Bas wrote:
> 
>> -any ideas how to easily incorporate advanced solving strategies?
>> solve(problem1) and solve(problem2) give solutions, but
>> solve(problem3) gets stuck...
> 
> 
> the only way to solve arbitrary sudoku problems is to guess.

Well, that's true, but most of the sudoku puzzles can be solved in
linear time ! And also having a linear time solving algorithm allows you
to really reduce the time used when you need backtracking.

BTW, the three given examples can be solved without backtracking.

I made one very recently (mmhh ... first complete version made
yesterday, still need a little bit of debug on the backtracking part),
and it's pretty quick (made in Ruby but well, I suppose timing are
similar), it never get stuck for long even if it fails, it fails quickly ...

Pierre
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Brute force sudoku cracker

2005-09-17 Thread Benji York
Sybren Stuvel wrote:
>>def all(seq, pred=bool):
> 
> What's this? What is bool?

See http://docs.python.org/lib/built-in-funcs.html#l2h-10
--
Benji York
-- 
http://mail.python.org/mailman/listinfo/python-list


sorting tuples...

2005-09-17 Thread nidhog
Hello guys,

I made a script that extracts strings from a binary file. It works.

My next problem is sorting those strings.

Output is like:

 snip 
200501221530
John
*** long string here ***

200504151625
Clyde
*** clyde's long string here ***

200503130935
Jeremy
*** jeremy string here 
 snip 

How can I go about sorting this list based on the date string that
marks the start of each message?

Should I be using lists, dictionaries or tuples?

What should I look into?

Is there a way to generate variables in a loop? Like:

x=0
while (x<10):
# assign variable-x = [...list...]
x = x+1

Thanks.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Brute force sudoku cracker

2005-09-17 Thread David Durkee

Hi Bas,

I came across Soduko puzzles recently too and had the same reaction:  
why waste my time solving the things when it would be much more fun  
to write a Python program to do so?


#!/usr/bin/python


import sys
import copy
import EasyDialogs


# Solve functions return these result codes:
kImpossible		 = -1	# Impossible to solve (a cell has no possible values)
kIndeterminate		= 0	 # No solution found (a guess will be required)
kSomeFound			= 1	 # Some solutions found
kAllSolutionsFound	= 2	 # Puzzle is solved


class CellPossibilities:

	def initCell(self, x, y):
		self.cellX = x
		self.cellY = y
		self.values = []
		
	def setPossibleValues(self, values):
		self.values = values
	
	def __lt__(self, other):
		return len(self.values) < len(other.values)
	
	def appendPossibilities(self, possibilities):
		for val in self.values:
			possibility = CellPossibility()
			possibility.setPossibility(self.cellX, self.cellY, val)
			possibilities.append(possibility)
		
	
class CellPossibility:

	def setPossibility(self, x, y, value):
		self.cellX = x
		self.cellY = y
		self.value = value
	

class Soduko:
	def printpuzzle(self):
		print "---"
		for by in range(0, 3):
			for ry in range(0, 3):
y = by * 3 + ry
rowstr = "|"
for bx in range(0, 3):
	for cx in range(0, 3):
		x = bx * 3 + cx
		cellval =  self.puzzle[y][x]
		if cellval == 0:
			rowstr = rowstr + "  "
		else:
			rowstr = rowstr + str(cellval) + " "
	rowstr = rowstr[0:-1] + "|"
print rowstr
			print "---"
		
	
	def leftToSolve(self):
		left = 0;
		for row in self.puzzle:
			for cell in row:
if cell is 0:
	left += 1
		return left
	
	def puzzleSolved(self):
		for row in self.puzzle:
			for cell in row:
if cell is 0:
	return False
		return True
	
	def cellValueUsedInRow(self, x, y, testval):
		for x1 in range(0,9):
			if x1 != x and self.puzzle[y][x1] == testval:
return True;
		return False
	
	def cellValueUsedInColumn(self, x, y, testval):
		for y1 in range(0,9):
			if y1 != y and self.puzzle[y1][x] == testval:
return True;
		return False
	
	def enumerateBox(self, x, y):
		x1 = x - x % 3
		y1 = y - y % 3
		for y2 in range(y1, y1+3):
			for x2 in range(x1, x1+3):
if x2 != x or y2 != y:
	yield self.puzzle[y2][x2]
		
		
	def cellValueUsedInBox(self, x, y, testval):
		for cellval in self.enumerateBox(x, y):
			if cellval == testval:
return True
		return False
	
	
	def isCellValuePossible(self, x, y, testval):
		if self.cellValueUsedInRow(x, y, testval):
			return False
		if self.cellValueUsedInColumn(x, y, testval):
			return False
		if self.cellValueUsedInBox(x, y, testval):
			return False
		return True;
	
	
	def findPossibleValues(self, x, y):
		possibles = []
		for v in range(1, 10):
			if self.isCellValuePossible(x, y, v):
possibles.append(v)
		return possibles
	
	def findAllPossibleValues(self):
		results = []
		for x in range(0, 9):
			for y in range(0, 9):
if self.puzzle[y][x] == 0:
	possibles = CellPossibilities()
	possibles.initCell(x, y)
	possibles.setPossibleValues(self.findPossibleValues(x, y))
	results.append(possibles)
		return results

	def validatePuzzle(self):
		ok = True;
		for x in range(0, 9):
			for y in range(0, 9):
if self.puzzle[y][x]:
	if not self.isCellValuePossible(x, y, self.puzzle[y][x]):
		print "Cell %i, %i contains conflicting value." % (x, y)
		ok = False
else:
	possibles = self.findPossibleValues(x, y)
	if len(possibles) == 0:
		print "Cell %i, %i has no possible value." % (x, y)
		ok = False
		return ok
	
	
	def solveByPossible(self):
		anyfound = False
		for x in range(0, 9):
			for y in range(0, 9):
if self.puzzle[y][x] == 0:
	possibles = self.findPossibleValues(x, y)
	if len(possibles) == 1:
		self.puzzle[y][x] = possibles[0]
		anyfound = True
	elif len(possibles) == 0:
		print "No possible values for %i, %i." % (x, y)
		return kImpossible
		if anyfound:
			if self.puzzleSolved():
return kAllSolutionsFound
			else:
return kSomeFound
		else:
			return kIndeterminate
	
	
	def checkSet(self, cellSet):
		# Find list of needed values in set
		anyfound = False
		needed = []
		for val in range(1, 10):
			for cell in cellSet:
if self.puzzle[cell[1]][cell[0]] == val:
	break
			else:
needed.append(val)
		# For each needed value, count how many cells in the set it can
		# possibly be in. If the number is 1, put the value in that cell.
		for val in needed:
			possibleCell = False
			numPossible = 0
			for cell in cellSet:
if self.puzzle[cell[1]][cell[0]] == 0:
	if self.isCellValuePossible(cell[0], cell[1], val):
		possibleCell = cell;
		numPossible += 1
			if numPossible == 1:
anyfound = True
self.puzzle[possibleCell[1]][possibleCell[0]] = val
			elif numPossible == 0:
return kImpossible
		if anyfound:
			if self.puzzleSolved():
return kAllSolutionsFound
			else:
return kS

Re: problem with setup.py

2005-09-17 Thread andrea valle
Thanks a lot.
I have bash as shell but I ignore what

> your ~/.bashrc

means.

Have I to edit a file?
Where should it be?


Thanks again


-a-

On 17 Sep 2005, at 12:46, Robert Kern wrote:

> andrea valle wrote:
>> Hi to all,
>> and sorry for cross-posting.
>>
>> I'm having troubles with installing packages.
>> I'm on macosx 10.3.8 and I have activestate python 2.4
>>
>> For example, pyrtf an pyx.
>> it is the first time I install packages so pardon me if it's obvious.
>>
>> I call python from terminal, I pass the absolute path of the setup.py
>> with command install, and results are always:
>> error: $MACOSX_DEPLOYMENT_TARGET mismatch: now "" but "10.3" during
>> configure
>>
>> For example with pyrtf:
>>
>> apples-Computer:~ apple$ python
>> /Users/apple/Desktop/PyRTF-0.45/setup.py installrunning install
>> error: $MACOSX_DEPLOYMENT_TARGET mismatch: now "" but "10.3" during
>> configure
>>
>> What should I do? I guess I have to hack some configuration, but don't
>> know which.
>
> Add the following line to your ~/.bashrc (assuming that you are using
> bash as your shell):
>
>   export MACOSX_DEPLOYMENT_TARGET=10.3
>
> Then start a new Terminal.app window (the change doesn't take effect
> until a new shell is started).
>
> I haven't needed to do this with the official 2.4.1 build, so you 
> should
> complain to ActiveState. Or use the official build.
>
> -- 
> Robert Kern
> [EMAIL PROTECTED]
>
> "In the fields of hell where the grass grows high
>  Are the graves of dreams allowed to die."
>   -- Richard Harter
>
> -- 
> http://mail.python.org/mailman/listinfo/python-list
>
>
Andrea Valle
Laboratorio multimediale "G. Quazza"
Facoltà di Scienze della Formazione
Università degli Studi di Torino
[EMAIL PROTECTED]

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sorting tuples...

2005-09-17 Thread bearophileHUGS
Uhm, if the file is clean you can use something like this:

data = """\
200501221530
John
*** long string here ***

200504151625
Clyde
*** clyde's long string here ***

200503130935
Jeremy
*** jeremy string here """

records = [rec.split("\n") for rec in data.split("\n\n")]
records.sort()
print records

If it's not clean, you have to put some more cheeks/cleanings.

Bye,
bearophile

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't IDLE editor windows have horizontal scrollbars?

2005-09-17 Thread Jussi Jumppanen
chuck wrote:
> 
> The browser windows do.  Why not the editor windows?
> 
> I hate to complain but is there any way to get IDLE to 
> run in more of an MDI mode?

FWIW the Zeus editor uses the MDI interface model:

   http://www.zeusedit.com/lookmain.html

Zeus also has syntax highlighting and code folding for 
the Python language. You can even write Zeus macros in
Python.

NOTE: Zeus is shareware (45 day trial period).

Jussi Jumppanen
Author of: Zeus for Windows Editor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with setup.py

2005-09-17 Thread Robert Kern
andrea valle wrote:
> Thanks a lot.
> I have bash as shell but I ignore what
> 
>>your ~/.bashrc
> 
> means.
> 
> Have I to edit a file?
> Where should it be?

It's a file. ~/ means your home directory. The name of the file is
.bashrc . You can't see it with the finder, so you have to edit it from
the terminal.

$ open ~/.bashrc

That should open it in TextEdit.app .

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Brute force sudoku cracker

2005-09-17 Thread Bas
>> def all(seq, pred=bool):

>What's this? What is bool?

That came straight out of the manual for itertools:
http://docs.python.org/lib/itertools-recipes.html

-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: eric3 3.7.2 released

2005-09-17 Thread Detlev Offenbach
Hi,

this is to let you know about the release of eric3 3.7.2. This is a
bugfix release, which is compatible with PyQt 3.15. It is available at

http://www.die-offenbachs.de/detlev/eric3.html

What is it?
---
Eric3 is a Python and Ruby IDE written in Python and PyQt. It comes with
all batteries included. Please see the above URL for more info.

Regards,
Detlev
-- 
Detlev Offenbach
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode-aware file shortcuts in Windows

2005-09-17 Thread Martin v. Löwis
John Bauman wrote:
> I see that another way is available here: 
> http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/programmersguide/shell_int/shell_int_programming/shortcuts/shortcut.asp
> I haven't tried, and I don't have the knowledge to convert the C++ to 
> Python, but it works at a lower level and may get around the bugs. It does 
> seem that the name of the file isn't Unicode in their method, either, so I'm 
> not sure if it'll work. 

There are two versions of the IShellLink interface: IShellLinkA and
IShellLinkW. You need to use the *W version to pass characters outside
the ANSI code page.

Regards,
Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: First release of Shed Skin, a Python-to-C++ compiler.

2005-09-17 Thread Luis M. Gonzalez
This is great news. Congratulations!

By the way, I read in your blog that you would be releasing a windows
intaller soon.
Have you, or anyone else, managed to do it?

Cheers,
Luis

-- 
http://mail.python.org/mailman/listinfo/python-list


traceback from embedded python

2005-09-17 Thread Skink
hi,

I'm using boost::python for calling some python code and when the
exception is thrown I want to get type, value and traceback of it.

The problem is with traceback: I got only *one* frame (the first one)

// this always returns Py_None
tb_frame = PyObject_GetAttrString(tb_frame, "f_back");

What I'm doing wrong?

void
Deployer::showError() {
//PyErr_Print();

PyObject *exc_type, *exc_value, *exc_traceback, *pystring;

PyErr_Fetch(&exc_type, &exc_value, &exc_traceback);

// type works
pystring = PyObject_Str(exc_type);
char *type = QString(python::extract(pystring));
Py_XDECREF(pystring);

// value works
pystring = PyObject_Str(exc_value);
char *value = QString(python::extract(pystring));
Py_XDECREF(pystring);

// traceback does't work ;(
PyObject *tb_frame = PyObject_GetAttrString(exc_traceback, "tb_frame");
while (tb_frame != Py_None) {
PyObject *f_lineno = PyObject_GetAttrString(tb_frame, "f_lineno");
int lineno = python::extract(f_lineno);
Py_XDECREF(f_lineno);

PyObject *f_code = PyObject_GetAttrString(tb_frame, "f_code");
PyObject *co_filename = PyObject_GetAttrString(f_code,
"co_filename");
char *filename = python::extract(co_filename);
Py_XDECREF(f_code);
Py_XDECREF(co_filename);

PyObject *tmp = tb_frame;
//PyObject_Print(tb_frame, stderr, Py_PRINT_RAW);
//fprintf(stderr, "\n");
tb_frame = PyObject_GetAttrString(tb_frame, "f_back");
//PyObject_Print(tb_frame, stderr, Py_PRINT_RAW);
//fprintf(stderr, "\n");
Py_XDECREF(tmp);
}

Py_XDECREF(exc_type);
Py_XDECREF(exc_value);
Py_XDECREF(exc_traceback);
}


thanks,
Skink
-- 
http://mail.python.org/mailman/listinfo/python-list


Shed Skin under Windows and OSX

2005-09-17 Thread Mark Dufour
> By the way, I read in your blog that you would be releasing a windows
> intaller soon.
> Have you, or anyone else, managed to do it?

I just finished making a 20 MB (!) package for Windows XP (I'm not
sure which older versions of Windows it will run on.) It includes the
Boehm garbage collector and a C++ compiler (MingW), which hopefully
will make it  really easy to create executables. However, I'm not
releasing it until somebody with XP can test it for me :-) If you'd
like to try what I have so far,  please download
http://kascade.org/shedskin-0.0.2.zip, unzip it and follow some simple
steps in the README file. I would really like to know about anything
that doesn't work, or is unclear!

BTW, I also fixed all OSX problems, but I'm waiting for a friend to
give it a final test.

What kind of program would you like to compile?


thanks!
mark.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Possible bug in "metaclass resolution order" ?

2005-09-17 Thread Pedro Werneck
On 17 Sep 2005 02:04:39 -0700
"Simon Percivall" <[EMAIL PROTECTED]> wrote:

> Have you read the "Metaclasses" part of "Unifying types and classes in
> Python 2.2"? (http://www.python.org/2.2.3/descrintro.html#metaclasses)

Yes, I read. Have you read and understood my message ? :)

A class B, subclass of class A, with a metaclass M_A should have M_A or
a subclass of it as metaclass. If you try with anything else, you get a
TypeError exception as expected. OK. But if you try with 'type', nothing
happens. 

Python 2.4.1 (#1, Sep 16 2005, 17:47:47) 
[GCC 3.3.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class M_A(type): pass
... 
>>> class A: __metaclass__ = M_A
... 
>>> class B(A): __metaclass__ = type
... 
>>> B.__class__

>>> B.__metaclass__



Regards,

-- 
Pedro Werneck
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Britney Spears nude

2005-09-17 Thread robin
"Ian Osgood" <[EMAIL PROTECTED]> wrote:

>Wouldn't Natasha Kinski be more apropos for this newsgroup?  (In case
>Python needs a poster girl...)
>
>http://snakeskins0.tripod.com/eden.html

That would be Nastassja Kinski.

But you are correct, it is a python. Photo by Richard Avedon.

-
robin
noisetheatre.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Possible bug in "metaclass resolution order" ?

2005-09-17 Thread Michele Simionato
I think this is more of a documentation issue than of a bug.
It may seems strange at first, but __metaclass__ and __class__ may be
different.

For instance, if M is metaclass

>>> class C(object): pass

>>> C.__metaclass__ = M

you get a class with metaclass hook equal to M, but C.__class__ is
still 'type'.

In you example, setting the __metaclass__ to 'type' does not change the
metaclass of
the created class, which is inherited from the base class. I suggest
you to file a documentation
bug. Unfortunately the basic documentation about metaclasses is a bit
lacking and you have
to discover many things by trial and errors.

   Michele Simionato

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary sorting problem

2005-09-17 Thread Bengt Richter
On 17 Sep 2005 11:01:41 GMT, Duncan Booth <[EMAIL PROTECTED]> wrote:

>Bengt Richter wrote:
>
>> or tell sorted what to do ;-)
>> 
>> >>> original= {
>>  ... 'hello':135,
>>  ... 'goodbye':30,
>>  ... 'lucy':4,
>>  ... 'sky':55,
>>  ... 'diamonds':239843,
>>  ... 'yesterday':4 }
>> >>> list(sorted(original.iteritems(), None, lambda t:t[1], True))
>>  [('diamonds', 239843), ('hello', 135), ('sky', 55), ('goodbye', 30),
>>  ('yesterday', 4), ('lucy',4)] 
>
>or a slight variation on this theme which just gives you the keys in value 
>order rather than the tuples:
>
 for k in sorted(original, key=original.get, reverse=True):
>   print k, original[k]
>
Nice. I like the keyword usage too. Much clearer than my hastypaste ;-)

>   
>diamonds 239843
>hello 135
>sky 55
>goodbye 30
>yesterday 4
>lucy 4

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: p2exe using wine/cxoffice

2005-09-17 Thread Tim Roberts
James Stroud <[EMAIL PROTECTED]> wrote:
>
>I think the motivation is to ween people off of M$ products altogether, 

Well, CrossOver Office doesn't really do that.  You're still running
Microsoft Office.

>...to get 
>them used to working an a unix environment and to the idea of using open 
>alternatives rather than thinking that commercial software is somehow 
>"better".

Regardless of your opinion on their operating systems, only a religious
zealot would try to argue that Microsoft Office is not better than any of
the open source alternatives.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Software bugs aren't inevitable

2005-09-17 Thread Aahz
In article <[EMAIL PROTECTED]>, Mike Meyer  <[EMAIL PROTECTED]> wrote:
>[EMAIL PROTECTED] (Aahz) writes:
>> In article <[EMAIL PROTECTED]>,
>> Paul Rubin   wrote:
>>>
>>>Every serious FP language implementation optimizes tail calls and thus
>>>using recursion instead of iteration doesn't cost any stack space and
>>>it probably generates the exact same machine code.
>>
>> While that's true, one of the reasons Guido has historically rejected
>> this optimization is because there are plenty of recursive algorithms
>> not amenable to tail-call optimization.
>
>That seems amazingly silly. Sort of like refusing to hoist function
>definitions because not all function definitions can be hoisted. Or
>choose your favorite "sometimes-I-can-sometimes-I-can't" optimization.
>
>Since the BDFL is *not* known for doing even mildly silly things when
>it comes to Python's design and implementation, I suspect there's more
>to the story than that.

Note that I said "one reason".  The primary reason is that tail-call
optimization destroys the call stack, which means that exception
semantics would have to change.  If tail-call optimization were more
useful, he might be willing to consider the tradeoff, but since it
isn't...
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

The way to build large Python applications is to componentize and
loosely-couple the hell out of everything.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: FTP status problems. (Again)

2005-09-17 Thread Kartic
That is because you have just taken marduk's program and included your 
ftp code... please see what he has done in the if __name__ == '__main__' 
part.

He expects the file name as an commandline argument (sys.argv[1]) and 
since you just copied his code, you are invoking the script *without* 
the argument. This is what the exception means when it says "list index 
out of range".

To make ProgressFile class work for you with the filename you have 
hardcoded... make the following modification to the "if __name ==" part:

if __name__ == '__main__':
ftp = ftplib.FTP("ftp.sadpanda.cjb.cc")
ftp.login("sadpanda","s4dp4nd4b1g")
file = "/FrenchBrochure.pages.zip.gz"
ftp.storbinary("STOR " + file, ProgressFile(file, "rb"), 1024)
ftp.quit()

Thanks,
-Kartic

The Great 'Nainto' uttered these words on 9/17/2005 9:08 AM:
> When I execute  the folllowing code with all of the address, username,
> and passwords filled out I gt an error saying:
> "/Library/Frameworks/Python.framework/Versions/2.4/Resources/Python.app/Contents/MacOS/Python"
> "/Users/zacim/Documents/FireUpFTP/foramttedthing" ; exit
> Traceback (most recent call last):
>   File "/Users/zacim/Documents/FireUpFTP/foramttedthing", line 26, in ?
> fname = sys.argv[1]
> IndexError: list index out of range
> logout
> [Process completed]
> 
> This is the code:
> 
> import ftplib
> class ProgressFile(file):
>   def read(self, size = None):
>   from sys import stdout
> 
>   if size is not None:
>   buff = file.read(self, size)
>   if buff:
>   stdout.write('.')
>   else:
>   stdout.write('\n')
>   return buff
>   else:
>   buff = ''
>   while True:
>   new_str = file.read(self, 1024)
>   stdout.write('.')
>   if new_str:
>   buff = buff + new_str
>   else:
>   stdout.write('\n')
>   break
>   return buff
> if __name__ == '__main__':
>   import sys
>   fname = sys.argv[1]
>   f = ProgressFile(fname)
>   f.read()
> 
> ftp = ftplib.FTP("ftp.sadpanda.cjb.cc")
> ftp.login("sadpanda","s4dp4nd4b1g")
> file = "/FrenchBrochure.pages.zip.gz"
> ftp.storbinary("STOR " + file, ProgressFile(file, "rb"), 1024)
> ftp.quit()
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't IDLE editor windows have horizontal scrollbars?

2005-09-17 Thread D H
chuck wrote:
> Well I don't want to start yet another thread on IDE's.  I've googled
> and all of that an am aware of most of the IDE's that are out there.  I
> am curious if there is someplace where statistics have been captured on
> what IDE's most people are using.  Since IDLE ships with Python I
> assume a lot of people use it.  I've been a PythonWin user for years
> but it has shortcomings, isnt' being developed further and doesn't run
> on FreeBSD, my other platform.
> 

I like the JEdit editor, which is free and cross-platform ( 
http://www.jedit.org/ ), and for the interpreter if you ever use that, 
there is the normal console (cmd.exe in windows) or see also IPython. 
There is also a console plugin for JEdit.

But if you want a more full-featured IDE with project management, etc., 
there is a Python addin for the Eclipse IDE called pydev I believe.  I 
haven't tried it myself though.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Possible bug in "metaclass resolution order" ?

2005-09-17 Thread Pedro Werneck
On 17 Sep 2005 08:51:50 -0700
"Michele Simionato" <[EMAIL PROTECTED]> wrote:

Hi

> I think this is more of a documentation issue than of a bug.

No... I don't think it's a documentation issue. What's the problem with
the documentation in this case ? Trying to use 'type' as a metaclass
with a subclass of another class using a custom metaclass is an error
and should raise the same exception the metaclass conflict does. In
fact, is the same error.

> It may seems strange at first, but __metaclass__ and __class__ may be
> different.
> 
> For instance, if M is metaclass
> 
> >>> class C(object): pass
> 
> >>> C.__metaclass__ = M
> 
> you get a class with metaclass hook equal to M, but C.__class__ is
> still 'type'.

But in this case, it's a __metaclass__ attribute defined after class
creation, after the call to the metaclass found in object.__class__, not
dict["__metaclass__"] which have priority over object.__class__. The
interpreter is not aware of this __metaclass__ attribute during class
creation, since it's not in the dict passed on the type(name, bases,
dict) call.

> In you example, setting the __metaclass__ to 'type' does not change
> the metaclass of the created class, which is inherited from the base
> class. 

Yes, but, as I said, dict["__metaclass__"] has priority over the base
class __class__. If I use a metaclass which is not a subclass of my base
classes metaclass I get a TypeError: metaclass conflict exception. If I
use 'type' which is also not a subclass of my base classes metaclass, I
was supposed to get the same exception, but the interpreter ignores
dict["__metaclass__"] and use the metaclass in base class __class__. 

Seems like the problem is in Objects/typeobject.c, PyType_IsSubtype
(814-846) or the for loop in 1604-1621. Seems like PyType_IsSubtype is
returning true for a type being a subtype of it's own subtypes and it
never reaches the exception and return NULL. The problem seems to be the
third if statement and after it, when the winner and metatype are
exchanged if different.

It's more evident using 'type' because it's the base of all types, but
after looking the source code, I tested with this code:

Python 2.4.1 (#1, Sep 16 2005, 17:47:47) 
[GCC 3.3.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
c>>> class M_A(type): pass
... 
>>> class A: __metaclass__ = M_A
... 
>>> class M_B(M_A): pass
... 
>>> class B(A): __metaclass__ = M_B
... 
>>> class C(B): __metaclass__ = M_A
... 
>>> C.__class__

>>> C.__metaclass__

>>> 

Is this supposed to happen ? C's metaclass must be a subclass of M_B. If
I try with any other class not related to this hierarchy, I will get a
metaclass conflict error. But with M_A, the error is ignored, probably
because PyType_IsSubtype is returning 1 for M_A being a subtype of M_B
and the winner and metatype are exchanged later, so we end with M_B as
C's real type.


> I suggest you to file a documentation bug. Unfortunately the basic
> documentation about metaclasses is a bit lacking and you have to
> discover many things by trial and errors.

I still think this is a bug, not a documentation issue. 

Regards

-- 
Pedro Werneck

> 
>Michele Simionato
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sorting tuples...

2005-09-17 Thread Bengt Richter
On 17 Sep 2005 06:41:08 -0700, [EMAIL PROTECTED] wrote:

>Hello guys,
>
>I made a script that extracts strings from a binary file. It works.
>
>My next problem is sorting those strings.
>
>Output is like:
>
> snip 
>200501221530
>John
>*** long string here ***
>
>200504151625
>Clyde
>*** clyde's long string here ***
>
>200503130935
>Jeremy
>*** jeremy string here 
> snip 
>
>How can I go about sorting this list based on the date string that
>marks the start of each message?
>
>Should I be using lists, dictionaries or tuples?
>
>What should I look into?
>
>Is there a way to generate variables in a loop? Like:
>
>x=0
>while (x<10):
># assign variable-x = [...list...]
>x = x+1
>
>Thanks.
>
Assuming your groups of strings are all non-blank lines delimited by blank 
lines,
and using StringIO as a line iterable playing the role of your source of lines,
(not tested beyond what you see ;-)

 >>> from StringIO import StringIO
 >>> lines = StringIO("""\
 ... 200501221530
 ... John
 ... *** long string here ***
 ...
 ... 200504151625
 ... Clyde
 ... *** clyde's long string here ***
 ...
 ... 200503130935
 ... Jeremy
 ... *** jeremy string here 
 ... """)
 >>>
 >>> from itertools import groupby
 >>> for t in sorted(tuple(g) for k, g in groupby(lines,
 ... lambda line:line.strip()!='') if k):
 ... print t
 ...
 ('200501221530\n', 'John\n', '*** long string here ***\n')
 ('200503130935\n', 'Jeremy\n', '*** jeremy string here \n')
 ('200504151625\n', 'Clyde\n', "*** clyde's long string here ***\n")

The lambda computes a grouping key that groupby uses to collect group members
as long as the value doesn't change, so this groups non-blank vs blank lines,
and the "if k" throws out the blank-line groups.

Obviously you could do something else with the sorted line tuples t, e.g.,

 >>> lines.seek(0)
(just needed that to rewind the StringIO data here)

 >>> for t in sorted(tuple(g) for k, g in groupby(lines,
 ... lambda line:line.strip()!='') if k):
 ... width = max(map(lambda x:len(x.rstrip()), t))
 ... topbot = '+-%s-+'%('-'*width)
 ... print topbot
 ... for line in t: print '| %s |' % line.rstrip().ljust(width)
 ... print topbot
 ... print
 ...
 +--+
 | 200501221530 |
 | John |
 | *** long string here *** |
 +--+ 

 +-+
 | 200503130935|
 | Jeremy  |
 | *** jeremy string here  |
 +-+

 +--+
 | 200504151625 |
 | Clyde|
 | *** clyde's long string here *** |
 +--+

Or of course you can just print the sorted groups bare:

 >>> lines.seek(0)
 >>> for t in sorted(tuple(g) for k, g in groupby(lines,
 ... lambda line:line.strip()!='') if k):
 ... print ''.join(t)
 ...
 200501221530
 John
 *** long string here ***

 200503130935
 Jeremy
 *** jeremy string here 

 200504151625
 Clyde
 *** clyde's long string here ***

 >>>

If your source of line groups is not delimited by blank lines,
or has other non-blank lines, you will have to change the source
or change the lambda to some other key function that produces one
value for the lines to include (True if you want to use if k as above)
and another (False) for the ones to exclude.

HTH

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inserting tuple from text file into database fields

2005-09-17 Thread Ed Hotchkiss
So I changed the code a little, still throwing the SQL syntax error. I still cannot seem to identify the problem.
 

# Script to add links from a comma deliminated file to a MySQL database# 9/16/05
import MySQLdb
conn=MySQLdb.connect( host="www.freesql.org",   user="edhotchkiss",   port=3306,   passwd="test1",   db="links")
cursor = conn.cursor()stmt = "DROP TABLE IF EXISTS links"cursor.execute(stmt)stmt = """CREATE TABLE links (    ID INT NOT NULL,    Name TEXT,    URL LONGTEXT,    Category LONGTEXT,
    primary key (ID))"""cursor.execute(stmt)
arr=[]inp = open ("sites1.txt","r")#read line into arrayfor line in inp.readlines():    links = map(str, line.split(","))    arr.append(links)    cursor.execute
 (""" INSERT INTO links (Name, URL, category) VALUES (%s, %s, %s) % tuple(links[0:3])    """)cursor.close()conn.close()
 -- edward hotchkiss 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Possible bug in "metaclass resolution order" ?

2005-09-17 Thread Terry Reedy

"Pedro Werneck" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> I still think this is a bug, not a documentation issue.

As an sometimes bug report reviewer, I appreciate your posting this issue 
here to get a wider and quicker variety of responses than you might have on 
SF.  If, after any further responses, you still think you have discovered a 
bug, do file a report on SourceForge.  Since the examples and your 
speculations on what is wrong are relatively lengthy, you might consider 
putting a summary in the somewhat cramped report box and attaching a 
separate 'metaclass.txt' file with a complete report.  Do mention your post 
here and any relavant responses.  Since this is a relatively specialized 
and advanced issue (one I can't comment on, for instance), please don't be 
too impatient for responses.

Terry J. Reedy



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Software bugs aren't inevitable

2005-09-17 Thread Terry Reedy

"Aahz" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Note that I said "one reason".  The primary reason is that tail-call
> optimization destroys the call stack, which means that exception
> semantics would have to change.  If tail-call optimization were more
> useful, he might be willing to consider the tradeoff, but since it
> isn't...

The prime reason I remember Guido giving, as I reported previously, is that 
tail-call optimization is semantically wrong otherwise, given the language 
as now defined, and would require a semantic change that he does not want 
to make.

Terry J. Reedy



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb - create table problem

2005-09-17 Thread Ed Leafe
On Sep 17, 2005, at 3:04 PM, Ed Hotchkiss wrote:

> There is no oreilly in the code ... I still get an error, any other  
> ideas? sorry ...

 Strange; can you explain where the text quoted (reilly, Python,  
Archive, http://
python.oreilly.com/archive.html) came from, then?

 Also I noticed in another message on the list (this one drifted  
off-list, due to the poor choice of Reply-To: setting by the list  
admins; I'm moving it back) that you had another error:

 cursor.execute ("""
  INSERT INTO links (Name, URL, category)
  VALUES (%s, %s, %s) % tuple(links[0:3])
 """)

 This should be:

 cursor.execute ("""
  INSERT INTO links (Name, URL, category)
  VALUES (%s, %s, %s)""", links[0:3]
   )

You don't even need to cast the args into a tuple when you use  
MySQLdb's parameter handling. It will automatically add quotes to any  
string values, and will automatically escape any problematic  
characters, such as single quotes, semi-colons, etc.

-- Ed Leafe
-- http://leafe.com
-- http://dabodev.com



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: FTP status problems. (Again)

2005-09-17 Thread Nainto
I'm really sorry that I keep having problems with this. :-( Now I get:
TypeError: Error when calling the metaclass bases[] str() takes at most
1 arguement (3 given)

and the Traceback is:

file "formattedthing", line 2, in '?'
classProgressFile(file)

With the following code:

import ftplib
class ProgressFile(file):
def read(self, size = None):
from sys import stdout
if size is not None:
buff = file.read(self, size)
if buff:
stdout.write('.')
else:
stdout.write('\n')
return buff
else:
buff = ''
while True:
new_str = file.read(self, 1024)
stdout.write('.')
if new_str:
buff = buff + new_str
else:
stdout.write('\n')
break
return buff
if __name__ == '__main__':
ftp = ftplib.FTP("ftp.sadpanda.cjb.cc")
ftp.login("sadpanda","PASSWORDEDITEDOUT")
file = "/FrenchBrochure.pages.zip"
ftp.storbinary("STOR " + file, ProgressFile(file, "rb"), 1024)
ftp.quit()

Thanks so muchy for help guys. :-)

-- 
http://mail.python.org/mailman/listinfo/python-list


MySQLdb error - PLEASE SAVE ME!

2005-09-17 Thread Ed Hotchkiss
Ok. I am trying to read a csv file with three strings separated by commas.
I am trying to insert them into a MySQL DB online.
MySQLdb is installed, no problems.

I think that I am having some kind of error with my csv going into the
fields and being broken apart correctly. Can someone please help? I
attached the code below, it does work with that SQL server also if you
want to try and run it. Thanks in advance ..

-

# Script to add links from a comma deliminated file to a MySQL database
# 9/16/05

import MySQLdb

conn=MySQLdb.connect( host="www.freesql.org",
user="edhotchkiss",
port=3306,
passwd="test1",
db="links")

cursor = conn.cursor()
stmt = "DROP TABLE IF EXISTS links"
cursor.execute(stmt)
stmt = """CREATE TABLE links (
   ID INT NOT NULL,
   Name TEXT,
   URL LONGTEXT,
   Category LONGTEXT,
   primary key (ID)
)"""
cursor.execute(stmt)


arr=[]
inp = open ("sites1.txt","r")
#read line into array
for line in inp.readlines():
   links = map(str, line.split(","))
   arr.append(links)
   cursor.execute ("""
INSERT INTO links (Name, URL, category)
   VALUES (%s, %s, %s)""" % tuple(links[0:3])
   )
cursor.close()
conn.close()


--
edward hotchkiss




-- 
edward hotchkiss

# Script to add links from a comma deliminated file to a MySQL database
# 9/16/05

import MySQLdb

conn=MySQLdb.connect(   host="www.freesql.org",
user="edhotchkiss",
port=3306,
passwd="test1",
db="links")

cursor = conn.cursor()
stmt = "DROP TABLE IF EXISTS links"
cursor.execute(stmt)
stmt = """CREATE TABLE links (
ID INT NOT NULL,
Name TEXT,
URL LONGTEXT,
Category LONGTEXT,
primary key (ID)
)"""
cursor.execute(stmt)


arr=[]
inp = open ("sites1.txt","r")
#read line into array
for line in inp.readlines():
links = map(str, line.split(","))
arr.append(links)
cursor.execute ("""
INSERT INTO links (Name, URL, category)
VALUES (%s, %s, %s)""" % tuple(links[0:3])
)
cursor.close()
conn.close()








  
O'reilly Python Archive,http://python.oreilly.com/archive.html,python
Python Tutorials,http://www.awaretek.com/tutorials.html,python
MySQL Python,http://sourceforge.net/projects/mysql-python,python
Python Vaults of Parnassus,http://www.vex.net/parnassus/,python
PyCrypto,http://www.amk.ca/python/code/crypto,Python-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python:C++ interfacing. Tool selection recommendations

2005-09-17 Thread Jorgen Grahn
On Fri, 16 Sep 2005 12:04:40 -0400, Neal Becker <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
>
>> Hi,
>> 
>> I am embedding Python with a C++ app and need to provide the Python
>> world with access to objects & data with the C++ world.
>> 
>> I am aware or SWIG, BOOST, SIP. Are there more?
>> 
>> I welcome comments of the pros/cons of each and recommendations on when
>> it appropriate to select one over the others.
>
> boost::python is alien technology.  It is amazingly powerful.  Once you
> learn how to use it it's wonderful, but unless you are comfortable with
> modern c++ you may find the learning curve steep.

That last part sounds like a good thing -- if the OP dealing with C++ code,
he should be, or become, comfortable with modern C++.

In my other life as a C++ programmer, I'm thoroughly fed up with people who
keep writing 1980s-style C++ ...

(I wonder, by the way, if it's a good idea to provide a very rich interface
between an application and embedded Python. I have no experience in the
area, but intuition tells me that simplicity and minimalism is important.
How well has this worked out in past projects?)

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for a database. Sugestions?

2005-09-17 Thread Jorgen Grahn
On 15 Sep 2005 22:22:30 -0700, Jeff Shell <[EMAIL PROTECTED]> wrote:
> If it's embedded, is there any reason why it should be SQL? A solid
> alternative could me MetaKit, which has Python bindings:

Or Berkeley DB, which has bindings in the standard Python library: the bsddb
module.

But we know almost nothing about the original poster's requirements, so
any advice may be completely meaningless.

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for a database. Sugestions?

2005-09-17 Thread Jarek Zgoda
ionel napisał(a):

> I'm looking for a thread-safe database.
> Preferably an embedded, sql database.
> 
> What are the best choices in terms of speed ?

Interbase/Firebird is thread-safe, is SQL-compliant. And once it was
embedded. In a tank. M1 Abrams, specifically. At least the tale tells
that... ;)

-- 
Jarek Zgoda
http://jpa.berlios.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Wanted: mutable bitmap

2005-09-17 Thread Tom Anderson
Hello!

One thing that would be rather useful in various bits of programming i've 
done would be a mutable bitmap type. Basically, this would behave like a 
set, where the items were constrained to be positive integers (perhaps 
less than some limit set at construction time). The advantage over a set 
would be performance (both time- and space-wise), pure and simple - this 
object would be an optimisation tool. However, the performance it delivers 
is pretty much essential for implementing things like Bloom filters, the 
sieve of Eratosthenes, and other computer science staples.

Am i right in thinking there's no such thing in the standard library? Is 
there an implementation out there somewhere else? Is there a hack for 
doing it with the stuff that is in the standard library?

tom

-- 
Ensure a star-man is never constructed!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wanted: mutable bitmap

2005-09-17 Thread Paul Rubin
Tom Anderson <[EMAIL PROTECTED]> writes:
> One thing that would be rather useful in various bits of programming
> i've done would be a mutable bitmap type. 
> Am i right in thinking there's no such thing in the standard library?
> Is there an implementation out there somewhere else? Is there a hack
> for doing it with the stuff that is in the standard library?

The obvious way is with the array module.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: disabling TCP connections, just for one script

2005-09-17 Thread dify . ltd
>From the post I gather that you are looking for a solution under Linux.
I don't know much linux, but under Windows you could patch the IAT
(import address table) of the running process temporarly to redirect
calls to the socket winsock api to a stup function, which simply fails.
If you are interested, drop me a letter.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "week-year" conversion to date

2005-09-17 Thread Jorgen Grahn
On 14 Sep 2005 06:26:01 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> I was wondering if it there is an "easy" way to get the dd-mm- from
> ww-.

Note that there are different standards[0] for assigning numbers to weeks in a
year. Whatever software or algorithm you use, make sure it documents which
one it implements.

/Jorgen

[0] If I recall correctly, one is an ISO standard and is the used in Sweden
and in BSD ncal(1), but there are others that could be in common use in
parts of the world.

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib.open problem

2005-09-17 Thread Astan Chee




OKay, but how do I check (and possibly change) _proxy environment
variables in python? I know in perl its somewhere along the lines of 
$ENV{'env_name'}, is it the same in python?
Thanks again
Cheers

Fredrik Lundh wrote:

  Astan Chee wrote:

  
  
I have a python script which runs perfectly on my machine.
However a machine that I tested it on gives the following error
message:

Traceback (most recent call last):
  File "whip.py", line 616, in OnRebootRunning
  File "whip.py", line 626, in RebootCustom
  File "urllib.pyc", line 77, in urlopen
  File "urllib.pyc", line 170, in open
TypeError: cannot concatenate 'str' and 'NoneType' objects

The code snipplet where this error
happens is
f = urllib.urlopen("http://www.hotmail.com/)
notes= f.readlines()

Does anyone know what causes this error? Im perplexed because it works
on some machines and it doesnt work on other computers although they all
have the same spec.

  
  
assuming you're using Python 2.4, the relevant portion of urllib.py
looks like this:

urltype, url = ""
if not urltype:
urltype = 'file'
if urltype in self.proxies:
proxy = self.proxies[urltype]
urltype, proxyhost = splittype(proxy)
host, selector = splithost(proxyhost)
url = "" fullurl) # Signal special case to open_*()
else:
proxy = None
name = 'open_' + urltype # <-- this is line 170

the error message indicates that urltype is None when you get to
line 170, and the only way it can get set to None is a bogus proxy
setting (causing splittype to fail).

checking the environment for things that end with "_proxy" should
help.





  



-- 
http://mail.python.org/mailman/listinfo/python-list

Re: xml2schema

2005-09-17 Thread jegenye2001
Er, do you mean to generate a Relax NG (or possibly a DTD in fact) from
some XML file??

If you do mean this then just think of that how you could generate
grammar from some paragraphs of English text...  Sorta non-trivial, if
possible at all, isn't it? :-)

Best regards,
 Miklos
--
The ring of the friendly serpent in business suit: Python, Zope, Plone
http://www.jegenye.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pcapy listen on multiple devices

2005-09-17 Thread Jorgen Grahn
On Mon, 12 Sep 2005 17:02:31 +0200, billiejoex <[EMAIL PROTECTED]> wrote:
> Hi all. I noticed that with the original pcap sniffing library it is 
> possible to listen on multiple devices by using "select()" or "poll()" 
> function.

Yes; you can ask pcap for the file descriptor which corresponds to your
sniffed device. That works at least on Unixes.

(There is also the 'any' pseudo-interface, if you are on Linux (and other
Unixes?). You get to listen /everywhere/ in one session.)

> These function aren't present in pcapy module. Do you got any suggestion to 
> avoid this problem?

Modify pcapy so you can get the file descriptor from it. Pcapy is great, but
it doesn't expose libpcap literally. Maybe the original authors had no use
for getfd().

I've been meaning to write The Pcap Bindings To End All Pcap Bindings for
almost a year now, but I never seem to get around to it ;-)

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pinging from within python

2005-09-17 Thread Jorgen Grahn
On Mon, 12 Sep 2005 01:36:35 +0200, billiejoex <[EMAIL PROTECTED]> wrote:
> Impacket module can helps you to construct the ip/icmp packet structure, 
> then you can send the packet and wait for the ECHOREPLY by using a 
> RAW_SOCKET.
> Here's an example:
> http://oss.coresecurity.com/impacket/ping.py

Yeah, but is he willing to be root, and ditch Windows, just to be able to
ping?  Exec()ing the ping utility is often better, but beware -- different
pings take different options.

[the original poster]
>> I need a simple script to run the ping command with some parameters and be 
>> able to read the return value of the ping function.

What is "the return value of the ping function"? You can use the ping
utility for many different things, and it reports many different kinds of
outcomes. It's not black and white.

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: FTP status problems. (Again)

2005-09-17 Thread Kartic
Hello,

 >  file = "/FrenchBrochure.pages.zip"
 >  ftp.storbinary("STOR " + file, ProgressFile(file, "rb"), 1024)

You are using file = "/FrenchBrochure.pages.zip" (sorry I did not notice 
earlier).

You can not use file as variable name like you have, as it represents a 
file object in python.

Please change your variable name from file to filename.

Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python 2.5 alpha

2005-09-17 Thread D.Hering
Generally, what sort of compatibility problems should I expect if I
were to replace 2.4.1 with 2.5 alpha (current cvs dist)? I'm working
under gentoo linux 2.6.

Specifically, should I expect any problems with Numarray, Scipy, or
Pytables or IDE's. My degree of understanding such things is limited,
and I'm anxious to use the new generator/coroutine functionality.

Thanks for your comments,
Dieter

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: FTP status problems. (Again)

2005-09-17 Thread Nainto
Unfortunatly I stiill get the same error. :-(
Here is the code:
import ftplib
class ProgressFile(file):
def read(self, size = None):
from sys import stdout
if size is not None:
buff = file.read(self, size)
if buff:
stdout.write('.')
else:
stdout.write('\n')
return buff
else:
buff = ''
while True:
new_str = file.read(self, 1024)
stdout.write('.')
if new_str:
buff = buff + new_str
else:
stdout.write('\n')
break
return buff
if __name__ == '__main__':
ftp = ftplib.FTP("ftp.sadpanda.cjb.cc")
ftp.login("sadpanda","PASSWORDEDITIEDOUT")
filename = "/FrenchBrochure.pages.zip"
ftp.storbinary("STOR " + filename, ProgressFile(filename, "rb"), 1024)

ftp.quit()


Thanks again.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: which is more 'pythonic' / 'better' ?

2005-09-17 Thread Jorgen Grahn
On Mon, 12 Sep 2005 12:52:52 +0200, gabor <[EMAIL PROTECTED]> wrote:
> hi,
>
> there are 2 versions of a simple code.
> which is preferred?

I don't know. Who cares?

> ===
> try:
>   text = line[n]
> except IndexError:
>   text = 'nothing'
> ===
>
>
> which is the one you would use?

The 'try' version. But I'd also ask myself how I could end up in a state where
this part of the code is asked to find a string that doesn't exist, and if I
really want it to keep running, with a made-up value.

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: FTP status problems. (Again)

2005-09-17 Thread Kartic
> Unfortunatly I stiill get the same error. :-(

The same "metaclass bases[]" error??

> Here is the code:
> import ftplib
-snip-
> if __name__ == '__main__':
>   ftp = ftplib.FTP("ftp.sadpanda.cjb.cc")
>   ftp.login("sadpanda","PASSWORDEDITIEDOUT")
>   filename = "/FrenchBrochure.pages.zip"
>   ftp.storbinary("STOR " + filename, ProgressFile(filename, "rb"), 1024)
> 
>   ftp.quit()


Your code works for me.. I just made one minor change.

I gave a different target name:

  filename = "/FrenchBrochure.pages.zip"
  target = "FrenchBrochure.pages.zip"
  ftp.storbinary("STOR " + target, ProgressFile(filename, "rb"), 1024)

Thanks,
-Kartic
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Software bugs aren't inevitable

2005-09-17 Thread Scott David Daniels
Sybren Stuvel wrote:
> ... Computers aren't happy. They couldn't care less about the
> programming language.

This reminds me of a quote I love (and wish I could cite the
originator):

 Don't anthropomorphize computers, they don't like that.

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


threading.Thread vs. signal.signal

2005-09-17 Thread Jack Orenstein
I'd like to create a program that invokes a function once a second,
and terminates when the user types ctrl-c. So I created a signal
handler, created a threading.Thread which does the invocation every
second, and started the thread. The signal handler seems to be
ineffective. Any idea what I'm doing wrong? This is on Fedora FC4 and
Python 2.4.1. The code appears below.

If I do the while ... sleep in the main thread, then the signal
handler works as expected. (This isn't really a satisfactory
implementation because the function called every second might
take a significant fraction of a second to execute.)

Jack Orenstein


import sys
import signal
import threading
import datetime
import time

class metronome(threading.Thread):
 def __init__(self, interval, function):
 threading.Thread.__init__(self)
 self.interval = interval
 self.function = function
 self.done = False

 def cancel(self):
 print '>>> cancel'
 self.done = True

 def run(self):
 while not self.done:
 time.sleep(self.interval)
 if self.done:
 print '>>> break!'
 break
 else:
 self.function()

def ctrl_c_handler(signal, frame):
 print '>>> ctrl c'
 global t
 t.cancel()
 sys.stdout.close()
 sys.stderr.close()
 sys.exit(0)

signal.signal(signal.SIGINT, ctrl_c_handler)

def hello():
 print datetime.datetime.now()

t = metronome(1, hello)
t.start()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wanted: mutable bitmap

2005-09-17 Thread Tom Anderson
On Sat, 17 Sep 2005, it was written:

> Tom Anderson <[EMAIL PROTECTED]> writes:
>
>> One thing that would be rather useful in various bits of programming 
>> i've done would be a mutable bitmap type. Am i right in thinking 
>> there's no such thing in the standard library? Is there an 
>> implementation out there somewhere else? Is there a hack for doing it 
>> with the stuff that is in the standard library?
>
> The obvious way is with the array module.

*bangs head against keyboard*

i've had a niggling feeling i should be paying more attention to that 
module for months now. yes, it would be very simple to implement a 
bitset on top of an array of integers. doh.

tom

-- 
There is no strange thing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: threading.Thread vs. signal.signal

2005-09-17 Thread Jp Calderone
On Sat, 17 Sep 2005 19:24:54 -0400, Jack Orenstein <[EMAIL PROTECTED]> wrote:
>I'd like to create a program that invokes a function once a second,
>and terminates when the user types ctrl-c. So I created a signal
>handler, created a threading.Thread which does the invocation every
>second, and started the thread. The signal handler seems to be
>ineffective. Any idea what I'm doing wrong? This is on Fedora FC4 and
>Python 2.4.1. The code appears below.
>
>If I do the while ... sleep in the main thread, then the signal
>handler works as expected. (This isn't really a satisfactory
>implementation because the function called every second might
>take a significant fraction of a second to execute.)
>
>Jack Orenstein
>
>
>import sys
>import signal
>import threading
>import datetime
>import time
>
>class metronome(threading.Thread):
> def __init__(self, interval, function):
> threading.Thread.__init__(self)
> self.interval = interval
> self.function = function
> self.done = False
>
> def cancel(self):
> print '>>> cancel'
> self.done = True
>
> def run(self):
> while not self.done:
> time.sleep(self.interval)
> if self.done:
> print '>>> break!'
> break
> else:
> self.function()
>
>def ctrl_c_handler(signal, frame):
> print '>>> ctrl c'
> global t
> t.cancel()
> sys.stdout.close()
> sys.stderr.close()
> sys.exit(0)
>
>signal.signal(signal.SIGINT, ctrl_c_handler)
>
>def hello():
> print datetime.datetime.now()
>
>t = metronome(1, hello)
>t.start()

The problem is that you allowed the main thread to complete.  No longer 
running, it can no longer process signals.  If you add something like this to 
the end of the program, you should see the behavior you wanted:

while not t.done:
time.sleep(1)

Incidentally, the last 3 lines of ctrl_c_handler aren't really necessary.

That said, here's a simpler version of the same program, using Twisted:

import datetime
from twisted.internet import reactor, task

def hello():
print datetime.datetime.now()

task.LoopingCall(hello).start(1, now=False)
reactor.run()

Hope this helps!

Jp
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wanted: mutable bitmap

2005-09-17 Thread vel . accel
You'd might be better off with Numarray or Scipy. Image and sparse
matrix modules are with in the package, and there is direct
functionality for PIL integration.

Numarray is better documented:
http://stsdas.stsci.edu/numarray/numarray-1.3.html/index.html

-- 
http://mail.python.org/mailman/listinfo/python-list


End or Identify (EOI) character ?

2005-09-17 Thread Madhusudan Singh
Hi

I was wondering how does one detect the above character. It is returned by
an instrument I am controlling via GPIB.

Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Possible bug in "metaclass resolution order" ?

2005-09-17 Thread Pedro Werneck
On Sat, 17 Sep 2005 15:07:01 -0400
"Terry Reedy" <[EMAIL PROTECTED]> wrote:

> If, after any further responses, you still think you have discovered a
> bug, do file a report on SourceForge.  

Thanks... report id 1294232, Error in metaclass search order

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


-- 
Pedro Werneck
-- 
http://mail.python.org/mailman/listinfo/python-list


Can someone explain what I've done wrong...

2005-09-17 Thread Jason
Hi,

I'm following a tutorial about classes, and have created the following 
(well, copied it from the manual buy added my own and wifes names)...

class Person:
 population=0

 def __init__(self,name):
 self.name=name
 print '(Initialising %s)' % self.name
 Person.population += 1

 def __del__(self):
 print "%s says bye." % self.name

 Person.population -= 1

 if Person.population == 0:
 print "I am the last one"
 else:
 print "There are still %d people left." % Person.population

 def sayHi(self):
 '''Greeting by the person.

 That's all it does.'''
 print "Hi, my name is %s" % self.name

 def howMany(self):
 if Person.population==1:
 print "I am on the only person here."
 else:
 print "We have %d persons here." % Person.population

Jason=Person("Jason")
Jason.sayHi()
Jason.howMany()

Sophie=Person("Sophie")
Sophie.sayHi()
Sophie.howMany()

Jason.sayHi()

The code, when run, should produce the following...

Hi, my name is Jason.
I am the only person here.
(Initializing Sophie)
Hi, my name is Sophie.
We have 2 persons here.
Hi, my name is Jason.
We have 2 persons here.
Jason says bye.
There are still 1 people left.
Sophie says bye.
I am the last one.

But what I actually get is...

(Initialising Jason)
Hi, my name is Jason
I am on the only person here.
(Initialising Sophie)
Hi, my name is Sophie
We have 2 persons here.
Hi, my name is Jason
We have 2 persons here.
Jason says bye.
There are still 1 people left.
Sophie says bye.
Exception exceptions.AttributeError: "'NoneType' object has no attribute 
'popula
tion'" in > ignored

I've looked through the code but can't find anything obvious.

I also want to apologise if this isn't the write newsgroup to post on, 
but it's the only one I know of.  IF anyone knows a good newsgroup, I'd 
appreciate it.

TIA

-- 
http://mail.python.org/mailman/listinfo/python-list


reading files with error

2005-09-17 Thread Maurice LING
Hi,

I'm trying to read some files (video files) that seems to have some 
errors in it. Basically, I cannot copy it out of discs as that gives me 
an error message but I can still play the file using a media player like 
VLC or QuickTime. I understand that copying a file will also invoke 
checking routines as well, and I am guessing that the file may have some 
parity-bit error or something.

Am I able to use Python to force read the entire file (full length)? 
That is, do not check the read for errors. I know that this is insideous 
in many uses but in media files, it may only result in a skipped frame 
or something. What I've done is something like this:

 >>> f = open('/Volumes/NEW/gameday/morning.dat', 'rb')
 >>> data = f.read()
 >>> o = open('/Users/mauriceling/Desktop/o.dat', 'wb')
 >>> f.close()
 >>> o.write(data)
 >>> o.close()

What I've noticed is this:
1. sometimes it (Python) only reads to roughly the point of initial copy 
error (I try to take note of how far drag-and-drop copying proceeds 
before it fails)
2. sometimes it is able to read pass the drag-and-drop copying 
fail-point but may or may not be full length.

What determines if Python is able to make it pass drag-and-drop copying 
fail-point?

Is there anyway to do what I want, force read full length?

Thanks and cheers
Maurice
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can someone explain what I've done wrong...

2005-09-17 Thread Jp Calderone
On Sun, 18 Sep 2005 02:10:50 +0100, Jason <[EMAIL PROTECTED]> wrote:
>Hi,
>
>I'm following a tutorial about classes, and have created the following
>(well, copied it from the manual buy added my own and wifes names)...
>
>class Person:
> population=0
>
> def __init__(self,name):
> self.name=name
> print '(Initialising %s)' % self.name
> Person.population += 1
>
> def __del__(self):
> print "%s says bye." % self.name
>
> Person.population -= 1
>
> if Person.population == 0:
> print "I am the last one"
> else:
> print "There are still %d people left." % Person.population
>
> def sayHi(self):
> '''Greeting by the person.
>
> That's all it does.'''
> print "Hi, my name is %s" % self.name
>
> def howMany(self):
> if Person.population==1:
> print "I am on the only person here."
> else:
> print "We have %d persons here." % Person.population
>
>Jason=Person("Jason")
>Jason.sayHi()
>Jason.howMany()
>
>Sophie=Person("Sophie")
>Sophie.sayHi()
>Sophie.howMany()
>
>Jason.sayHi()
>
>The code, when run, should produce the following...
>
>Hi, my name is Jason.
>I am the only person here.
>(Initializing Sophie)
>Hi, my name is Sophie.
>We have 2 persons here.
>Hi, my name is Jason.
>We have 2 persons here.
>Jason says bye.
>There are still 1 people left.
>Sophie says bye.
>I am the last one.
>
>But what I actually get is...
>
>(Initialising Jason)
>Hi, my name is Jason
>I am on the only person here.
>(Initialising Sophie)
>Hi, my name is Sophie
>We have 2 persons here.
>Hi, my name is Jason
>We have 2 persons here.
>Jason says bye.
>There are still 1 people left.
>Sophie says bye.
>Exception exceptions.AttributeError: "'NoneType' object has no attribute
>'popula
>tion'" in 0x0097B53
>0>> ignored
>
>I've looked through the code but can't find anything obvious.
>
>I also want to apologise if this isn't the write newsgroup to post on,
>but it's the only one I know of.  IF anyone knows a good newsgroup, I'd
>appreciate it.
>
>TIA

The __del__ method is not a reliable cleanup mechanism.  It runs when an object 
is garbage collected, but garbage collection is unpredictable and not 
guaranteed to ever occur.

In your particular case, __del__ is running during interpreter shut down.  
Another part of interpreter shutdown is to set the attributes of all modules to 
None.  Your code executes after this, tries to change None.population (since 
Person is now None), and explodes.

Your best bet is not to use __del__ at all.  Instead, add a method to be 
invoked when a person is going away, and then invoke it.

Jp
-- 
http://mail.python.org/mailman/listinfo/python-list


complex data types?

2005-09-17 Thread richard
I'd like to have an array in which the elements are various data types. 
How do I do this in Python?  

For example:

array[0].artist = 'genesis'
array[0].album = 'foxtrot'
array[0].songs = ['watcher', 'time table', 'friday']
array[1].artist = 'beatles'
array[1].album = 'abbey road'
array[1].songs = ['come', 'something', 'maxwell']

Everything I try generates errors or results in array[0].songs equaling 
array[1].songs. I feel I'm missing something obvious.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can someone explain what I've done wrong...

2005-09-17 Thread Jason
Thanks for the explanation JP Calderone.

Have to say, I was confused with the post (I received via email, can't 
see it on the newsgroup yet) from Astan Chee saying he couldn't 
understand how the Person class was destroyed.  I'm still new(ish) with 
Python but I was lead to believe the __del__ call was pretty reliable. 
Thanks for the heads up on that.

Thanks again.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading files with error

2005-09-17 Thread jepler
I have written a program to do something similar.  My strategy is:
 * use os.read() to read 512 bytes at a time
 * when os.read fails, seek to the next multiple of 512 bytes
   and write '\0' * 512 to the output
I notice this code doesn't deal properly with short reads, but in my experience
they never happen (because the disk error makes an entire block unreadable, and
a block is never less than 512 bytes)

I use this code on a unix-style system.

def dd(src, target, bs=512):
src = os.open(src, os.O_RDONLY)
if os.path.exists(target):
target = os.open(target, os.O_WRONLY | os.O_APPEND, 0600)
existing = os.lseek(target, 0, SEEK_END)
else:
existing = 0
target = os.open(target, os.O_WRONLY | os.O_CREAT, 0600)

total = os.lseek(src, 0, SEEK_END) / bs
os.lseek(src, existing, SEEK_SET)
os.lseek(target, existing, SEEK_SET)

if existing: print "starting at", existing
i = existing / bs
f = 0
lastrem = -1

last = start = time.time()
while 1:
try:
block = os.read(src, bs)
except os.error, detail:
if detail.errno == errno.EIO:
block = "\0" * bs
os.lseek(src, (i+1) * bs, SEEK_SET)
f = f + 1
else:
raise  
if block == "": break

i = i + 1
os.write(target, block)

now = time.time()
if i % 1000 or now - last < 1: continue
last = now

frac = i * 1. / total
rem = int((now-start) * (1-frac) / frac)
if rem < 60 or abs(rem - lastrem) > .5:
rm, rs = divmod(rem, 60)
lastrem = rem
spd = i * 512. / (now - start) / 1024 / 1024
sys.stderr.write("%8d %8d %8d %3.1f%% %6d:%02d %6.1fMB/s\r"
% (i, f, i-f, i * 100. / total, rm, rs, spd))
sys.stderr.write("\n")


pgpsinNQxCisS.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python:C++ interfacing. Tool selection recommendations

2005-09-17 Thread Diez B. Roggisch
> (I wonder, by the way, if it's a good idea to provide a very rich interface
> between an application and embedded Python. I have no experience in the
> area, but intuition tells me that simplicity and minimalism is important.
> How well has this worked out in past projects?)

Check out SIP and the PyQt/PyKDE binding for an example of a 
full-fledged C++ library wrapped. But I still think your point is valid :)


Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: influence platorm during install -end user question

2005-09-17 Thread Tim Roberts
Peter Hartmann <[EMAIL PROTECTED]> wrote:

>How do I influence the platform type during install?  Could you look
>at this and tell me what I'm doing wrong?  It's still using
>information from get_platform instead of using my preference.
>
>[EMAIL PROTECTED] pyosd-0.2.14]# python setup.py install
>--install-purelib=lib.linux=i686-2.3 
>--install-lib=/usr/lib/python2.3/site-packages

The answer was given to you previously.  To get Python to build a 32-bit
extension, you must use the 32-bit version of Python to run setup.py.
Otherwise, it's always going to use the 64-bit compiler.

Also note that there is a typo in your command line.  You have an equals
sign in lib.linux=i686-2.3 where you should have a dash.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


socket.gethostbyaddr problem

2005-09-17 Thread Mohammed Smadi
hi;
I am trying to do some very basic socket programming and i get the 
following error.  Any help will be appreciated:

Code:
import socket
x = socket.gethostbyaddr("www.google.ca")

return an error: socket.herror: (1, 'Unknown host')

I tried replacing the web URL with an IP address on the net, on my LAN and 
it does not work.  It only works with "localhost" which is not very 
useful.  Am using Python 2.3.4 if that matters.

any direction will be great

moe smadi

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5 alpha

2005-09-17 Thread Aahz
In article <[EMAIL PROTECTED]>,
D.Hering <[EMAIL PROTECTED]> wrote:
>
>Generally, what sort of compatibility problems should I expect if I
>were to replace 2.4.1 with 2.5 alpha (current cvs dist)? I'm working
>under gentoo linux 2.6.

There is no Python 2.5 alpha.  There is CVS head, which is currently
labeled 2.5a1 (or something like that), but it's nothing like an alpha.
In your shoes, I might consider a parallel installation of Python CVS,
but I certainly would *NOT* consider replacing a stable release with the
development branch.

>Specifically, should I expect any problems with Numarray, Scipy, or
>Pytables or IDE's. My degree of understanding such things is limited,
>and I'm anxious to use the new generator/coroutine functionality.

You'll almost certainly have to recompile them.  Nobody knows about that
kind of compatibility problem, because almost nobody does that kind of
testing until there is an alpha release.  I suggest looking at Misc/NEWS
for info about changes.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

The way to build large Python applications is to componentize and
loosely-couple the hell out of everything.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket.gethostbyaddr problem

2005-09-17 Thread jepler
Perhaps you mean to use the function socket.gethostbyname instead.

>>> import socket
>>> socket.gethostbyaddr("www.google.ca")
Traceback (most recent call last):
  File "", line 1, in ?
socket.herror: (1, 'Unknown host')
>>> socket.gethostbyname("www.google.ca")
'64.233.167.147'

Jeff


pgpsZ1m3OcqVP.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: socket.gethostbyaddr problem

2005-09-17 Thread Irmen de Jong
Mohammed Smadi wrote:
> hi;
> I am trying to do some very basic socket programming and i get the 
> following error.  Any help will be appreciated:
> 
> Code:
> import socket
> x = socket.gethostbyaddr("www.google.ca")
> 
> return an error: socket.herror: (1, 'Unknown host')

You're using the wrong method.

 >>> socket.gethostbyname("www.google.ca")
'66.102.9.147'


--Irmen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading files with error

2005-09-17 Thread Maurice Ling

[EMAIL PROTECTED] wrote:


I have written a program to do something similar.  My strategy is:
* use os.read() to read 512 bytes at a time
* when os.read fails, seek to the next multiple of 512 bytes
  and write '\0' * 512 to the output
I notice this code doesn't deal properly with short reads, but in my experience
they never happen (because the disk error makes an entire block unreadable, and
a block is never less than 512 bytes)

I use this code on a unix-style system.

def dd(src, target, bs=512):
   src = os.open(src, os.O_RDONLY)
   if os.path.exists(target):
   target = os.open(target, os.O_WRONLY | os.O_APPEND, 0600)
   existing = os.lseek(target, 0, SEEK_END)
   else:
   existing = 0
   target = os.open(target, os.O_WRONLY | os.O_CREAT, 0600)

   total = os.lseek(src, 0, SEEK_END) / bs
   os.lseek(src, existing, SEEK_SET)
   os.lseek(target, existing, SEEK_SET)

   if existing: print "starting at", existing
   i = existing / bs
   f = 0
   lastrem = -1

   last = start = time.time()
   while 1:
   try:
   block = os.read(src, bs)
   except os.error, detail:
   if detail.errno == errno.EIO:
   block = "\0" * bs
   os.lseek(src, (i+1) * bs, SEEK_SET)
   f = f + 1
   else:
   raise  
   if block == "": break


   i = i + 1
   os.write(target, block)

   now = time.time()
   if i % 1000 or now - last < 1: continue
   last = now

   frac = i * 1. / total
   rem = int((now-start) * (1-frac) / frac)
   if rem < 60 or abs(rem - lastrem) > .5:
   rm, rs = divmod(rem, 60)
   lastrem = rem
   spd = i * 512. / (now - start) / 1024 / 1024
   sys.stderr.write("%8d %8d %8d %3.1f%% %6d:%02d %6.1fMB/s\r"
   % (i, f, i-f, i * 100. / total, rm, rs, spd))
   sys.stderr.write("\n")
 


Sorry but what are SEEK_END and SEEK_SET?

Maurice

--
Maurice Han Tong LING, BSc(Hons)(Biochem), AdvDipComp, CPT, SSN, FIFA, 
MASBMB, MAMBIS, MACM

Doctor of Philosophy (Science) Candidate, The University of Melbourne
mobile: +61 4 22781753, +65 96669233
mailing address: Department of Zoology, The University of Melbourne
 Royal Parade, Parkville, Victoria 3010, Australia
residence: 9/41 Dover Street, Flemington, Victoria 3031, Australia
resume: http://maurice.vodien.com/maurice_resume.pdf
www: http://www.geocities.com/beldin79/

begin:vcard
fn:Maurice Ling
n:Ling;Maurice
org:The University of Melbourne;Department of Zoology
adr:;;Gate 12, Genetics Lane;Parkville;Victoria;3010;Australia
email;internet:[EMAIL PROTECTED]
title:Ph.D. Candidate
tel;cell:+61 4 22781753
x-mozilla-html:FALSE
url:http://www.geocities.com/beldin79/
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: complex data types?

2005-09-17 Thread [EMAIL PROTECTED]
richard wrote:
> I'd like to have an array in which the elements are various data types.
> How do I do this in Python?
>
> For example:
>
> array[0].artist = 'genesis'
> array[0].album = 'foxtrot'
> array[0].songs = ['watcher', 'time table', 'friday']
> array[1].artist = 'beatles'
> array[1].album = 'abbey road'
> array[1].songs = ['come', 'something', 'maxwell']
>
> Everything I try generates errors or results in array[0].songs equaling
> array[1].songs. I feel I'm missing something obvious.

If you show us where array[0] and array[1] are being initialized, it
would be easier to diagnose the problem.

At the same time, if array[0].songs equals array[1] songs, you are
probably initializing both array[0] and array[1] with the same object.
Since array[0] and array[1] both refer to the same object, a change to
one will be reflected in the other.

I hope this is what you're looking for.

Michael Loritsch

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb error - PLEASE SAVE ME!

2005-09-17 Thread Carsten Haese
On Sat, 17 Sep 2005 15:50:29 -0400, Ed Hotchkiss wrote
> Ok. I am trying to read a csv file with three strings separated by commas.
> I am trying to insert them into a MySQL DB online.
> MySQLdb is installed, no problems.
> 
> I think that I am having some kind of error with my csv going into 
> the fields and being broken apart correctly. Can someone please 
> help? I attached the code below, it does work with that SQL server 
> also if you want to try and run it. Thanks in advance ..

There are two obvious faults in your code:

1) You're using the % operator to plug your parameters directly into the query
string. Don't do that. Pass the parametrized query as the first argument to
execute(), pass the parameter tuple as the second argument to execute(), and
leave it to execute() to plug in the parameters.

Once 1) is fixed, you'll run into...

2) The ID column is a NOT NULL column. There is no default value for it, nor
is there an AUTO_INCREMENT flag on it. You're not specifying a value for ID in
the insert statement. Either this will fail on the first insert (attempting to
insert a NULL value into a NOT NULL column), or in case MySQL helpfully
defaults the ID to 0, it'll fail on the second row when the primary key
constraint is violated by attempting to insert another 0.

To fix 2), you'll wither want to make the ID column an AUTO_INCREMENT column
or explicitly specify a value for the ID column in the insert statement.
(Using AUTO_INCREMENT is easier.)


Hope this helps,

Carsten.


P.S. You need to learn how to describe your problem accurately. Phrases like
"no problems" and "it does work" juxtaposed with "some kind of error" do
nothing to describe what actually works and what doesn't work. I'm betting
python raised an exception when you ran your code. Instead of guessing
randomly (and incorrectly) that there is some kind of error in your csv
parsing, you could have, for example, included a copy of the exception message.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: complex data types?

2005-09-17 Thread Gustavo Picon
On Sat, 2005-09-17 at 20:49 -0500, richard wrote:
> I'd like to have an array in which the elements are various data types. 
> How do I do this in Python?  
> 
> For example:
> 
> array[0].artist = 'genesis'
> array[0].album = 'foxtrot'
> array[0].songs = ['watcher', 'time table', 'friday']
> array[1].artist = 'beatles'
> array[1].album = 'abbey road'
> array[1].songs = ['come', 'something', 'maxwell']
>   
> Everything I try generates errors or results in array[0].songs equaling 
> array[1].songs. I feel I'm missing something obvious.

Maybe something like this?

class music(object):
def __init__(self):
self.lst = {}
def __setattr__(self, name, value):
self.__dict__[name] = value

array = []
array.append(music())
array.append(music())

# begin quoting your code
array[0].artist = 'genesis'
array[0].album = 'foxtrot'
array[0].songs = ['watcher', 'time table', 'friday']
array[1].artist = 'beatles'
array[1].album = 'abbey road'
array[1].songs = ['come', 'something', 'maxwell']
# end quoting your code

print array[0].artist
print array[1].artist
print array[0].songs
print array[1].songs


-- 
Gustavo Picon (http://tabo.aurealsys.com/)
Aureal Systems S.A.C. (http://www.aureal.com.pe/)
[EMAIL PROTECTED]
Tlf: (511) 243-0131
Nextel: 9824*4625


signature.asc
Description: This is a digitally signed message part
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: complex data types?

2005-09-17 Thread Gustavo Picon
On Sat, 2005-09-17 at 23:34 -0500, Gustavo Picon wrote:
> Maybe something like this?
> 
> class music(object):
> def __init__(self):
> self.lst = {}
> def __setattr__(self, name, value):
> self.__dict__[name] = value
> 
> array = []
> array.append(music())
> array.append(music())
> 
> # begin quoting your code
> array[0].artist = 'genesis'
> array[0].album = 'foxtrot'
> array[0].songs = ['watcher', 'time table', 'friday']
> array[1].artist = 'beatles'
> array[1].album = 'abbey road'
> array[1].songs = ['come', 'something', 'maxwell']
> # end quoting your code
> 
> print array[0].artist
> print array[1].artist
> print array[0].songs
> print array[1].songs
> 

Actually, forget about that music class, all you need in that example
is:

class music:
pass

--
Gustavo


signature.asc
Description: This is a digitally signed message part
-- 
http://mail.python.org/mailman/listinfo/python-list

Python game coding

2005-09-17 Thread Lucas Raab
Saw this on Slashdot 
(http://developers.slashdot.org/article.pl?sid=05/09/17/182207&from=rss) 
and thought some people might be interested in it. Direct link to the 
article is 
http://harkal.sylphis3d.com/2005/08/10/multithreaded-game-scripting-with-stackless-python/

-- 
--
Lucas Raab
lvraab"@"earthlink.net
dotpyFE"@"gmail.com
AIM:Phoenix11890
MSN:dotpyfe "@" gmail.com
IRC:lvraab
ICQ:324767918
Yahoo:  Phoenix11890
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Software bugs aren't inevitable

2005-09-17 Thread Terry Hancock
On Saturday 17 September 2005 06:03 pm, Scott David Daniels wrote:
> Sybren Stuvel wrote:
> > ... Computers aren't happy. They couldn't care less about the
> > programming language.
> 
> This reminds me of a quote I love (and wish I could cite the
> originator):
> 
>  Don't anthropomorphize computers, they don't like that.

Actually, I wrote a long (and very off-topic) reply justifying the
philosophical point that whether or not computers can feel "happy"
is an article of faith, either way, and depends heavily on what
sense you are using for the word "happy" not to mention "feel"
or "be". I thought maybe it would be best to drop it, but since
this bone is still being worried, perhaps it's worth summarizing ...

Fascinating subject, actually. There is a widely held *faith* among
materialist atheists that the criterion for "being able to feel"
is an as-yet undefined, but definable level or form of computing
complexity mythologized as a "true AI".  The need for this belief
is an artifact of the materialist atheist belief -- or rather the
disbelief in any form of spiritualism or animism.

I contend that there is no such thing as a "true AI", or a "true
natural intelligence" for that matter in the sense of there being
some sharp line between "sentient" and "non-sentient" matter.

Obviously there is *something* going on, in continuity of memory and
reasoning capacity that has something to do with the objective
capability to react in complex ways, and thus to express one's own
sense of being in a way that is more comprehensible to "others".
Thus far, however, there is no need for any sharp line -- just a
gradually increasing level of intelligent responsiveness.

But, the actual state of sensation?  We know nothing about that,
and science cannot illuminate it, because it's not an objective
statement. We by definition cannot know what someone or something
else "feels".  We can only know how he/she/it *reacts*.

It seems a simpler and more natural assumption to think that 
sensation *pre-exists* the reasoning power to express or remember
that sensation.  Indeed, it seems more sensible to regard it as
a fundamental property of matter (or energy or space -- it being
hard to define which bit of reality the soul adheres to, but
"matter" will do for sake of argument).

It's no more unreasonable, I would contend, then, to say that a
computer is "happy" when it acts on data it "understands".  If
"thought" is a "mechanism", then a "mechanism" can be "thought".

I do not "anthropomorphize" the machine in that I do not regard
thought as a uniquely Human capacity.  That I have some "theory
of mind" for a PC does not mean that I think it's a Human, nor
that I would be stupid enough to credit it with a Human mind's
capabilities.

So I personally find it completely sane and often more natural
to speak of what a computer "knows" or "understands" or in this
case, "is happy with".

But if you really insist on a reductionist, mechanistic explanation,
then my point is simply this: a computer, in order to act on ANY
program, must first be made to act on a prior program (a compiler or
an interpreter -- in addition to the BIOS and operating system which
must first run in order to initiate the said program), which contains
instructions for converting said program into a format which the
computer is able to directly process.

I personally found "the computer is happier with binary" to 
be a much more concise and understandable way to say that, but
clearly, some people on the list find it heretical to use any
statement which assigns "agent status" to computers or programs.

But getting back to the point -- the fact that the computer itself
would be "happier" with binary program instructions shows that there
is certainly NO objective, technical sense in which ANY computer
programming language is "inherently" superior.

Programming languages can ONLY be evaluated in "psychological"
terms.  The "technical" design of programming languages -- and
indeed ALL systems for describing and characterizing cognition
of all forms is ultimately a "psychological" discipline. It
obviously depends on the function of the mind of the programmer,
and the ability of programmers' minds to process the
information is the *metric of success* of that programming
language.

Given that programmers' minds are neither identical nor
unchanging, it pretty much goes without saying that the choice
of programming language, notation, or technique will be
subjective -- and also changeable.

I said this, because an earlier poster had *dismissed* mere
"psychological" reasons as unimportant, claiming that
functional programming was superior on "technical" grounds.

I hope I have demonstrated that that statement is nonsensical --
ALL statements about programming languages or techniques are
ultimately dependent on "psychological reasons". If functional
programming reduces bugs, then it also does so for
*psychological* reasons.

--
Terry Hancock ( hancock at anansispaceworks.com 

Re: reading files with error

2005-09-17 Thread Christian Stapfer
Maurice Ling <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> [EMAIL PROTECTED] wrote:
>
>>I have written a program to do something similar.  My strategy is:
>> * use os.read() to read 512 bytes at a time
>> * when os.read fails, seek to the next multiple of 512 bytes
>>   and write '\0' * 512 to the output
>>I notice this code doesn't deal properly with short reads, but in my 
>>experience
>>they never happen (because the disk error makes an entire block 
>>unreadable, and
>>a block is never less than 512 bytes)
>>
>>I use this code on a unix-style system.
>>
>>def dd(src, target, bs=512):
>>src = os.open(src, os.O_RDONLY)
>>if os.path.exists(target):
>>target = os.open(target, os.O_WRONLY | os.O_APPEND, 0600)
>>existing = os.lseek(target, 0, SEEK_END)
>>else:
>>existing = 0
>>target = os.open(target, os.O_WRONLY | os.O_CREAT, 0600)
>>
>>total = os.lseek(src, 0, SEEK_END) / bs
>>os.lseek(src, existing, SEEK_SET)
>>os.lseek(target, existing, SEEK_SET)
>>
>>if existing: print "starting at", existing
>>i = existing / bs
>>f = 0
>>lastrem = -1
>>
>>last = start = time.time()
>>while 1:
>>try:
>>block = os.read(src, bs)
>>except os.error, detail:
>>if detail.errno == errno.EIO:
>>block = "\0" * bs
>>os.lseek(src, (i+1) * bs, SEEK_SET)
>>f = f + 1
>>else:
>>raise
>>if block == "": break
>>
>>i = i + 1
>>os.write(target, block)
>>
>>now = time.time()
>>if i % 1000 or now - last < 1: continue
>>last = now
>>
>>frac = i * 1. / total
>>rem = int((now-start) * (1-frac) / frac)
>>if rem < 60 or abs(rem - lastrem) > .5:
>>rm, rs = divmod(rem, 60)
>>lastrem = rem
>>spd = i * 512. / (now - start) / 1024 / 1024
>>sys.stderr.write("%8d %8d %8d %3.1f%% %6d:%02d %6.1fMB/s\r"
>>% (i, f, i-f, i * 100. / total, rm, rs, spd))
>>sys.stderr.write("\n")
>>
>>
> Sorry but what are SEEK_END and SEEK_SET?

The Python 2.3 documentation seems to specify the *numeric*
values of these constants only. But since Python's file
objects are "implemented using C's stdio package", you
can read

http://www.opengroup.org/onlinepubs/009695399/functions/lseek.html

Regards,
Christian Stapfer


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: complex data types?

2005-09-17 Thread [EMAIL PROTECTED]
That is a great example Gustavo...

One way that Richard's error of array[0] equaling array[1] could be
introduced would be by accidentally appending the 'music' class object
onto his list, rather than creating a new instance of music each time.
Changing the code:

array.append(music())
array.append(music())

to:

array.append(music)
array.append(music)

would produce the symptom described by Richard, as both array[0] and
array[1] would be references for the music class object.

ML

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: complex data types?

2005-09-17 Thread Steven D'Aprano
On Sat, 17 Sep 2005 20:49:32 -0500, richard wrote:

> I'd like to have an array in which the elements are various data types. 
> How do I do this in Python?  
> 
> For example:
> 
> array[0].artist = 'genesis'
> array[0].album = 'foxtrot'
> array[0].songs = ['watcher', 'time table', 'friday']
> array[1].artist = 'beatles'
> array[1].album = 'abbey road'
> array[1].songs = ['come', 'something', 'maxwell']
>   
> Everything I try generates errors or results in array[0].songs equaling 
> array[1].songs. I feel I'm missing something obvious.

Would you like to tell us what you have already tried, or should we guess?

To get good answers, it helps to ask good questions. What have you tried.
What errors did you generate? Most importantly, what are you hoping to do
with your data structure after you've got it?

One hint is to split the problem into two halves, then solve each one. It
looks to me like you are trying to store a list of albums. So half the
problem is solved: the list of albums is just a list. Each item is an
album. Now you just have to decide on how you store each album. Here is
one solution:

# Create a single album.
album = {"artist": "beetles", "title": "abbey road", \
"songlist" = ['come together', 'something', 'maxwell']}

# Store it in the album list.
albums.append(album)

You can change an item like this:

# Oops, wrong artist...
albums[0]["artist"] = "beatles"
albums[0]["songlist"].append("mean mr mustard")

Does this solution work for you? If not, what does it not do that you need
it to do?


-- 
Steven.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: End or Identify (EOI) character ?

2005-09-17 Thread Terry Reedy

"Madhusudan Singh" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi
>
> I was wondering how does one detect the above character. It is returned 
> by
> an instrument I am controlling via GPIB.

EOI = chr(n) # where n is ASCII number of the character.
# then whenever later
if gpid_in == EOI: #do whatever

Terry J. Reedy



-- 
http://mail.python.org/mailman/listinfo/python-list


Roguelike programmers needed

2005-09-17 Thread rpgnethack
Hi everyone,

A few of us over at RPGnet (http://www.rpg.net) have been talking about
writing an open-source roguelike in Python. Right now, I'm looking for
a few people join the dev team. All I'm asking is that you post one
piece of code for the game per week. If we get enough people, the
collaborative effort should give us a functional game pretty quickly
(at least compared to the recent pace of the project).

I'm pretty sure we'll be using PyGames for the graphics, although a
traditional ASCII roguelike interface would be nice to have too.

I myself am just a programming dabbler, and I'm actually learning
Python just for the sake of this project. Needless to say, programmers
of all skill levels are welcome.

If you're interested, sign up at RPGnet and let us know.

The thread looking for Dev Team members is here:

 http://forum.rpg.net/showthread.php?t=218209

The main RPGnethack thread is stickied at the top of the Art of Game
Design forum here:

 http://forum.rpg.net/forumdisplay.php?f=11

We've also got a wiki at:

 http://rpgnethack.wikispaces.org

Program files will be hosted at Sourceforge. 

Thanks! 

Stonebrook

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Roguelike programmers needed

2005-09-17 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> I'm pretty sure we'll be using PyGames for the graphics, although a
> traditional ASCII roguelike interface would be nice to have too.

??!!!  How can you call it roguelike if it's not ascii ???
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Roguelike programmers needed

2005-09-17 Thread rpgnethack
LOL...

I know, I know"true" roguelikes only use ASCII. But a number of
people seem to want to add graphics eventually, probably via tiles, and
I don't see the harm in it.

-- 
http://mail.python.org/mailman/listinfo/python-list