Re: image matching algorithms

2008-03-09 Thread castironpi
On Mar 10, 1:32 am, "Daniel Fetchinson" <[EMAIL PROTECTED]>
wrote:
> Hi all,
>
> There are a number of free tools for image matching but it's not very
> easy to decipher the actual algorithm from the code that includes db
> management, GUI, etc, etc. I have my own image database and GUI so all
> I need is the actual algorithm preferably in pseudo code and not in
> the form of a research paper (from which I also found a lot but since
> I'm not that much interested in the actual science of image
> recognition this seems like an over kill).
>
> My understanding of image matching is that it works by first
> calculating N real numbers for an image and defining a metric for
> pairs of N-tuples. Images are similar if their distance (defined by
> the metric) is small.
>
> The various free tools differ by their chosen optimization paths and
> their degree of specialization. My preference would be,
>
> 1. Doesn't really matter how long it takes to compute the N numbers per image
> 2. Lookups should be fast, consequently N should not be too large (I guess)
> 3. It should be a generic algorithm working on generic images (everyday 
> photos)
> 4. PIL should be enough for the implementation

http://www.idi.ntnu.no/~blake/gbimpdet.htm
"High level features carry information about an image in an abstracted
or propositional form"

It says it constructs a graph about the image's features.  Here's the
graph:

 Graph componentsNotes

[EMAIL PROTECTED];ext:sqr:aa(1659):mm(19815,148,0,0):<- Leading node
cg(62,86):cr(255,153,153):pl(-204,574,792,10353)]]with
attributes

[EMAIL PROTECTED]   1 ]]  <- Relation
  and strength

[EMAIL PROTECTED];ext:sqr:aa(199):mm(17759,244,1,0): <- Trailing
node
cg(98,77):cr(153,153,255):pl(966,2,258,-79198)]]$ with
attributes

It doesn't say what corner cases it leaves.  "seem to provide" and
"seems to be extremely flexible".  I like this feature:

- the equation of the best fitting plane Ax+By+Cz+D=0 to the range
  image data masked by the current region;

Where does that get you?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BitVector

2008-03-09 Thread castironpi
> > I am trying to solve a genetic algorithm problem where I want to read
> > a bitvector of very large size (say 1) and manipulate bits based
> > on certain algorithms.

Here's one on the Python website:
http://search.live.com/results.aspx?q=python+bitvector&src=IE-SearchBox
=> http://pypi.python.org/pypi/BitVector/1.3
=> http://cobweb.ecn.purdue.edu/~kak/dist/BitVector-1.3.html
code=> http://cobweb.ecn.purdue.edu/~kak/dist/BitVector_1.3_CodeOnly.py.html

"The bits of a bit array are stored in 16-bit unsigned ints."

However, Python has variable size longs.  Do you want something less
elaborate?

Here is what I think of when you say bitvector:

bA= bitvector()
bA[3]= 0
bA[7]= 1
bA[2].set()
bA[1]^= b[9]
bA[2:6].set()
rangeA= ba[2:7]
rangeA= "011101"
rangeA.clear()

bytearray is kind of close, but new in Py 3.0.  How close is it to the
perspective of the application you're writing?

Here's some of it straight off the console:

>>> b= bytearray(5)
>>> b
bytearray(b'\x00\x00\x00\x00\x00')
>>> b[1]= 1
>>> b
bytearray(b'\x00\x01\x00\x00\x00')
>>> list(b)
[0, 1, 0, 0, 0]

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


image matching algorithms

2008-03-09 Thread Daniel Fetchinson
Hi all,

There are a number of free tools for image matching but it's not very
easy to decipher the actual algorithm from the code that includes db
management, GUI, etc, etc. I have my own image database and GUI so all
I need is the actual algorithm preferably in pseudo code and not in
the form of a research paper (from which I also found a lot but since
I'm not that much interested in the actual science of image
recognition this seems like an over kill).

My understanding of image matching is that it works by first
calculating N real numbers for an image and defining a metric for
pairs of N-tuples. Images are similar if their distance (defined by
the metric) is small.

The various free tools differ by their chosen optimization paths and
their degree of specialization. My preference would be,

1. Doesn't really matter how long it takes to compute the N numbers per image
2. Lookups should be fast, consequently N should not be too large (I guess)
3. It should be a generic algorithm working on generic images (everyday photos)
4. PIL should be enough for the implementation

So if anyone knows of a good resource that is close to being pseudo
code I would be very grateful!

Cheers,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Distributed App - C++ with Python for Portability?

2008-03-09 Thread Paddy
On Mar 9, 11:41 pm, Roopan <[EMAIL PROTECTED]> wrote:
> Hello!
>
> I am looking at developing an enterprise-grade distributed data
> sharing application - key requirements are productivity and platform
> portability.
>
> Will it be sensible to use C++ for performance-critical sections and
> Python for all the glue logic.
>
> Pls comment from your *experiences* how Python scales to large
> projects( > 200KLOC).
> I assume the C++/Python binding is fairly painless.
>
> Regards
> Elam.

You might try prototyping as much as possible in Python as soon as
possible.
Then, and only after getting something that computes the right
results,
profile your prototype to see where the real bottlenecks are.
Sometimes it
it is not evident at the beginning where the bottlenecks in the
prototype
will be.
If you write most of the prototype in Python then you will write less
lines of code, in a shorter time and so should be more inclined to
experiment with different algorithms, and do more testing. (Doctest
can
be great).
After profiling their may be other ways to remove a bottleneck, such
as
using existing highly-optimised libraries such as Numpy; Psycho, an
optimising interpreter that can approach C type speeds for Python
code;
and you could create your own C++ based libraries.

You might want to ask the Mercurial development team how they got
their
impressive speed and functionality out of using mainly Python with
critical regions in C. - Or watch this:
  http://video.google.com/videoplay?docid=-7724296011317502612

- Paddy.


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


Re: How to factor using Python?

2008-03-09 Thread Gabriel Genellina
On 10 mar, 02:08, Nathan Pinno <[EMAIL PROTECTED]> wrote:

> How do I factor a number? I mean how do I translate x! into proper
> Python code, so that it will always do the correct math?

Do you want to compute x! (factorial of x)? That is, you want a
program that given a 4, returns 24?
Think how would you compute it by hand and try to write the same thing
using Python instructions.

If you come with a program and have a specific problem someone here
will be able to help you, but don't expect your homework to be done
for free...

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


Re: Intelligent Date & Time parsing

2008-03-09 Thread castironpi
On Mar 8, 12:57 pm, Tim Chase <[EMAIL PROTECTED]> wrote:
> > I am a GNU newbie.  (I know C &o.)  Can you point me to a
> > place to find the source for 'date'?
>
> It's part of the GNU Coreutils:
>
> http://ftp.gnu.org/gnu/coreutils/
>
> Within the file, you're likely interested in lib/getdate.*
>
> It helps if you have a working knowledge of Yacc.
>
> -tkc

Ah excellent.  I am looking at the part with:

static table const meridian_table[] =
{
  { "AM",   tMERIDIAN, MERam },
...
  { "JANUARY",  tMONTH,  1 },
  { "FEBRUARY", tMONTH,  2 },
...
  { "YEAR", tYEAR_UNIT,  1 },
  { "MONTH",tMONTH_UNIT, 1 },

(where is 'lunar month'? ;) )

How do you like it?  Certainly Python cleans it up by a multiple, but
what about the rest?
-- 
http://mail.python.org/mailman/listinfo/python-list


tcp client socket bind problem

2008-03-09 Thread natambu
I have a linux box with multiple ip addresses. I want to make my
python client connect from one of the ip addresses. Here is my code,
no matter what valid information I put in the bind it always comes
from the default ip address on the server. Am I doing something wrong?


-
#!/usr/bin/python

import socket

host = "server"
port = 1190

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.bind(("",0))
sock.connect((host, port))
-


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


Re: gc question

2008-03-09 Thread Gabriel Genellina
On 9 mar, 15:37, I V <[EMAIL PROTECTED]> wrote:
> On Sun, 09 Mar 2008 01:57:38 -0800, Vince wrote:

> > Well, that suits me. The most unnatural thing about Python was adapting
> > to the idea of just letting unreleased resources go jogging off
> > wherever. :)
>
> Yes, that's a bad habit that garbage collection can encourage. GC is good
> for managing memory, but not good for managing other resources, so if an
> object holds some other resource, it's important to make sure the
> resource is released in a timely fashion rather than relying on the
> finalizer (the __del__ function).
>
> Although, you still don't need f.close, with the new with statement:
>
> with open('myfile') as f:
>         string = f.readline()
> # f.close() gets called automatically here, without waiting for        
> # garbage collection.

Just for completeness, on earlier Python versions, the way to ensure
that resources are always released is using try/finally:

f = open(...)
try:
  ...work with file...
finally:
  f.close()

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


Re: del class with recursive list

2008-03-09 Thread Gabriel Genellina
On 9 mar, 17:20, [EMAIL PROTECTED] wrote:

> Thanks! I just need to remember to del the variables after "for in".

And when working on the interactive interpreter, it's easy to forget
the _ variable too (that holds the last printed expression)

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


How to factor using Python?

2008-03-09 Thread Nathan Pinno
How do I factor a number? I mean how do I translate x! into proper
Python code, so that it will always do the correct math?

Thanks in advance,
Nathan P.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Returning values from function to Python shell/IPython

2008-03-09 Thread Gabriel Genellina
On 9 mar, 20:51, [EMAIL PROTECTED] wrote:

> While you're at it, can you call up prior source, and edit it?  BASIC
> had line numbers:
>
> 10 def f( a ):
> 20   return a+ 1
>
> >>> 15 print( a )

Not so easy. The current CPython implementation assumes that once an
object is allocated, it is never moved to another memory location. If
doing that were allowed, all the object references had to be updated,
or another level of indirection would be required, and neither
alternative looks very promising.
The reload function tries to reuse the module object itself, but its
contents are destroyed and recreated. Maybe for some simple changes
like the above the *same* function object could be re-utilized, but
not in the general case.

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


Re: What c.l.py's opinions about Soft Exception?

2008-03-09 Thread John Nagle
Steven D'Aprano wrote:
> On Sat, 08 Mar 2008 22:24:36 -0800, Kay Schluehr wrote:
> 
>> On 9 Mrz., 06:30, Steven D'Aprano <[EMAIL PROTECTED]
>> cybersource.com.au> wrote:

>> Is it really so exotic that it requires the demand for more use cases?
> 
> 
> Are the existing solutions really so incomplete that we need yet another 
> solution?
> 
> What problem are you trying to solve with SoftExceptions?

I actually implemented something like "soft exceptions" in a LISP
program long ago. I called them "gripes".  They were a way that a function
could complain about something it wanted the caller to fix. The caller
could either fix it or decline to do so.

This was for a robotic planning application, where one module had detected
that some precondition that it needed wasn't satisfied.  This was usually
something like some physical object being in the wrong place for a later
operation, and a previously planned move needed to be modified. Passing
the problem back to the caller sometimes allowed an easy fix, rather than
aborting the whole plan and building a new one.

This isn't a common problem.

In the rare cases that it is needed, it can be implemented with callbacks.
It doesn't require a language extension.

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


Re: BitVector

2008-03-09 Thread Gabriel Genellina
On 10 mar, 01:26, DanielJohnson <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I am trying to solve a genetic algorithm problem where I want to read
> a bitvector of very large size (say 1) and manipulate bits based
> on certain algorithms.
>
> I am a newbie in Python. What data structure are good to read such
> huge data set. Are there any built in classes for bit fiddling.
>
> Every help is greatly appreciated,
>
> Thanks

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


Re: Checking if a variable is a dictionary

2008-03-09 Thread Gabriel Genellina
On 9 mar, 11:23, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sun, 09 Mar 2008 06:58:15 -0700, Guillermo wrote:
> > Okay, so I think I know where's the catch now -- you must rely on the
> > fact that the protocol is implemented, there's no way to enforce it if
> > you're expecting a parrot-like object. You'd try to call the speak()
> > method and deal with the error if there's no such method?
>
> That's right. That's called "duck typing" -- if all you want is something
> that quacks like a duck, then it doesn't matter if it actually is a duck
> or not.

In addition to duck typing, in some cases an explicit declaration may
be useful: "I implement the Parrot protocol". The zope.interface
package does that: there is a way to define interfaces (a set of
methods any implementation must provide), and classes can assert "I
implement this interface", and one can determine whether a class
implements or not certain interface. See 
http://pypi.python.org/pypi/zope.interface

Abstract Base Classes (ABC, for Python 3.0) provide a similar concept
(but they're not the same thing). See http://www.python.org/dev/peps/pep-3119/

Of course there is some overlapping between all of these techniques -
one should choose the best method in each case.

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


Re: any chance regular expressions are cached?

2008-03-09 Thread John Machin
On Mar 10, 11:42 am, [EMAIL PROTECTED] wrote:
> I've got a bit of code in a function like this:
>
> s=re.sub(r'\n','\n'+spaces,s)
> s=re.sub(r'^',spaces,s)
> s=re.sub(r' *\n','\n',s)
> s=re.sub(r' *$','',s)
> s=re.sub(r'\n*$','',s)
>
> Is there any chance that these will be cached somewhere, and save
> me the trouble of having to declare some global re's if I don't
> want to have them recompiled on each function invocation?
>

Yes they will be cached. But do yourself a favour and check out the
string methods.

E.g.
>>> import re
>>> def opfunc(s, spaces):
... s=re.sub(r'\n','\n'+spaces,s)
... s=re.sub(r'^',spaces,s)
... s=re.sub(r' *\n','\n',s)
... s=re.sub(r' *$','',s)
... s=re.sub(r'\n*$','',s)
... return s
...
>>> def myfunc(s, spaces):
... return '\n'.join(spaces + x.rstrip() if x.rstrip() else '' for
x in s.splitlines())
...
>>> t1 = 'foo\nbar\nzot\n'
>>> t2 = 'foo\nbar \nzot\n'
>>> t3 = 'foo\n\nzot\n'
>>> [opfunc(s, '   ') for s in (t1, t2, t3)]
['   foo\n   bar\n   zot', '   foo\n   bar\n   zot', '   foo\n\n
zot']
>>> [myfunc(s, '   ') for s in (t1, t2, t3)]
['   foo\n   bar\n   zot', '   foo\n   bar\n   zot', '   foo\n\n
zot']
>>>
-- 
http://mail.python.org/mailman/listinfo/python-list


dot() and tensordot()

2008-03-09 Thread royG
hi
can numpy.dot() be used instead of tensordot()? is there any
performance difference? I am talking about operation btw numpy arrays
of dimensions 50 X 20,000 where elements are of float type.

i tried posting in numpy group where i had gotten membership..but when
i post a msg it says posting by non member and so doesn't show up :-(

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


BitVector

2008-03-09 Thread DanielJohnson
Hi,

I am trying to solve a genetic algorithm problem where I want to read
a bitvector of very large size (say 1) and manipulate bits based
on certain algorithms.

I am a newbie in Python. What data structure are good to read such
huge data set. Are there any built in classes for bit fiddling.

Every help is greatly appreciated,

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


Re: Import - interpreter works but .py import does not

2008-03-09 Thread John Machin
On Mar 10, 1:59 pm, John Boy <[EMAIL PROTECTED]> wrote:
> First post and very much a newbie to Python. Have 2.5 on Linux (GG). I
> think I have set up PYTHONPATH correctly in that I can import a module
> apply_bp and it complains about line 20 in apply_bp which is:
>
> import sys, aipy, numpy, os

Please get used to showing the error message. "it complains about line
x" is not very helpful. Fortunately in this case we can guess that it
is "complaining" about inability to import either aipy or numpy (sys
and os are built-in).

>
> At the interpreter prompt, however, I can import sys, numpy etc. and
> can do dir() and see the entry points so I think my overall
> installation is OK.
>
> Why does line not work ?

More information please.

At the interpreter prompt, do this:
import sys
sys.path
import aipy; aipy.__file__
import numpy; numpy.__file__
and show us the result.
Change the offending line in your apply_bp module to
import sys
print sys.path
import os, aipy, numpy
and show us ALL of the output.
At the shell prompt, do whatever it takes to display the contents of
PYTHONPATH, and show us the results.

> Also I would have thought that when I pre-
> imported sys et al that they would be in the symbol table so that the
> import line would be a noop.

The concept of "preimporting" a module is novel to me. Importing a
module at the interpreter prompt doesn't persist when you exit the
interpreter and then (implicitly) start up another interpreter task to
run your script. Importing a module in your script puts the module in
the script's namespace, which is quite distinct from the namespace of
the apply_bp (or any other) module. If those two possibilities don't
cover what you mean, please explain.
-- 
http://mail.python.org/mailman/listinfo/python-list


SV: SV: Changing the size of a Button

2008-03-09 Thread K Viltersten
>> What i wish to do is to affect the size
>> of the button but not due to change of
>> text but due to resize of the frame it
>> resides in.
> 
> This is done by the layout manager, too:
> 
> import Tkinter as tk
> 
> root = tk.Tk()
> button = tk.Button(root, text="42")
> button.pack(fill=tk.BOTH, expand=True)
> root.mainloop()
> 
> Alternatively, with a grid layout:
> 
> button.grid(row=0, column=0, sticky="nsew")
> root.rowconfigure(0, weight=1)
> root.columnconfigure(0, weight=1)


Ah, great! I'll try that right away.
After breakfast, of course! Thanks!

--
Regards
Konrad Viltersten

sleep- a substitute for coffee for the poor
ambition - lack of sense to be lazy

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


Re: any chance regular expressions are cached?

2008-03-09 Thread Steven D'Aprano
On Mon, 10 Mar 2008 00:42:47 +, mh wrote:

> I've got a bit of code in a function like this:
> 
> s=re.sub(r'\n','\n'+spaces,s)
> s=re.sub(r'^',spaces,s)
> s=re.sub(r' *\n','\n',s)
> s=re.sub(r' *$','',s)
> s=re.sub(r'\n*$','',s)
> 
> Is there any chance that these will be cached somewhere, and save me the
> trouble of having to declare some global re's if I don't want to have
> them recompiled on each function invocation?


At the interactive interpreter, type "help(re)" [enter]. A page or two 
down, you will see:

purge()
Clear the regular expression cache


and looking at the source code I see many calls to _compile() which 
starts off with:

def _compile(*key):
# internal: compile pattern
cachekey = (type(key[0]),) + key
p = _cache.get(cachekey)
if p is not None:
return p

So yes, the re module caches it's regular expressions.

Having said that, at least four out of the five examples you give are 
good examples of when you SHOULDN'T use regexes.

re.sub(r'\n','\n'+spaces,s)

is better written as s.replace('\n', '\n'+spaces). Don't believe me? 
Check this out:


>>> s = 'hello\nworld'
>>> spaces = "   "
>>> from timeit import Timer
>>> Timer("re.sub('\\n', '\\n'+spaces, s)", 
... "import re;from __main__ import s, spaces").timeit()
7.4031901359558105
>>> Timer("s.replace('\\n', '\\n'+spaces)", 
... "import re;from __main__ import s, spaces").timeit()
1.6208670139312744

The regex is nearly five times slower than the simple string replacement.


Similarly:

re.sub(r'^',spaces,s)

is better written as spaces+s, which is nearly eleven times faster.

Also:

re.sub(r' *$','',s)
re.sub(r'\n*$','',s)

are just slow ways of writing s.rstrip(' ') and s.rstrip('\n').



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


Re: __iter__ yield

2008-03-09 Thread George Sakkis
On Mar 9, 7:37 pm, Paul Hankin <[EMAIL PROTECTED]> wrote:
> On Mar 9, 8:58 pm, duccio <[EMAIL PROTECTED]> wrote:
>
> > Someone knows if it's possible to make this __iter__ function with just
> > one 'yield' intead of two?
> > ...
> >  def __iter__(self):
> >  yield self #1
> >  for n in self.childs:
> >  for nn in n.__iter__():
> >  yield nn #2
>
> Only one yield and shorter (but not really any simpler):
>
> from itertools import chain
>
> class Node:
> ...
> def __iter__(self):
> for x in chain([self], *self.childs):
> yield x

Actually this doesn't need a yield at all:

class Node:
...
def __iter__(self):
return chain([self], *self.childs)

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


Re: execute

2008-03-09 Thread Benjamin
On Mar 9, 4:22 pm, Gif <[EMAIL PROTECTED]> wrote:
> i'm trying to execute a file without replacing the current process,
> but after searching the help file, documentations and the web, i can't
> a way of doing that.
>
> os.exec*() will close the current program.
Have a look at the subprocess module.
>
> ps: by executing i mean like typing "mspaint" in run dialog.. it's not
> a python file

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


Import - interpreter works but .py import does not

2008-03-09 Thread John Boy
First post and very much a newbie to Python. Have 2.5 on Linux (GG). I
think I have set up PYTHONPATH correctly in that I can import a module
apply_bp and it complains about line 20 in apply_bp which is:

import sys, aipy, numpy, os

At the interpreter prompt, however, I can import sys, numpy etc. and
can do dir() and see the entry points so I think my overall
installation is OK.

Why does line not work ? Also I would have thought that when I pre-
imported sys et al that they would be in the symbol table so that the
import line would be a noop.

  Thanks,

 Slainte,

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


Re: Solve a Debate

2008-03-09 Thread castironpi
> days_in_month 12:
> 31
> 30
> 28
> 31
> ...
> 30
> 31
> assign $days days_in_month[$month]
>
> This program consists of 2 operations (table jump and assignment)
> and 12 values. This makes a memory consumption of 12+2 = 14

Along the same lines, you could populate the table somewhat sparsely,
and goto a modulo key.

You could even put functions in it:

setreturn $endoftable
hash month
goto
-0
-1
-2
jan.-> 3: setvjmp janfun
-4
-5
apr.-> 6: setvjmp aprfun
$endoftable

Sweet!  Are you stack-ops?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: any chance regular expressions are cached?

2008-03-09 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| I've got a bit of code in a function like this:
|
|s=re.sub(r'\n','\n'+spaces,s)
|s=re.sub(r'^',spaces,s)
|s=re.sub(r' *\n','\n',s)
|s=re.sub(r' *$','',s)
|s=re.sub(r'\n*$','',s)
|
| Is there any chance that these will be cached somewhere, and save
| me the trouble of having to declare some global re's if I don't
| want to have them recompiled on each function invocation?

The last time I looked, several versions ago, re did cache.
Don't know if still true.  Not part of spec, I don't think.

tjr



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


Python 2.5 segmentation faulting importing random

2008-03-09 Thread Bagpussnz
Hi,
Whenever I try to import random in a python module, I get a
segmentation fault.

I've traced it using,
import pdb
pdb.set_trace()
import random

When it gets to..

> /usr/lib/python2.5/random.py(57)()
-> LOG4 = _log(4.0)

It seg faults.

I'm running on OpenSuse 10.2.
Linux devhost 2.6.18.8-0.7-bigsmp #1 SMP Tue Oct 2 17:21:08 UTC 2007
i686 i686 i386 GNU/Linux

The python header says..
Python 2.5 (r25:51908, May 25 2007, 16:14:04)
[GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2

Any ideas?
Regards,
Ian.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Uninstalling Eggs

2008-03-09 Thread Mike Driscoll
On Mar 9, 8:30 am, PB <[EMAIL PROTECTED]> wrote:
> I just installed the Shove module with the monumentally crap
> setuptools. Whilst the install succeeded, imports now trigger errors,
> so clearly it did not install correctly. Can I simply delete the .egg
> file from my lib/python2.3/site-packages/ directory?
>
> Cheers,

Deleting the shove-egg folder is definitely the recommended and
easiest way I know of to "uninstall" an egg. I've used it successfully
before.

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


python-2.5.2 src rpm

2008-03-09 Thread Donald Raikes
Hello,

I am trying to install python 2.5.2 onto enterprise linux, and would like to 
start with a source rpm package so that I can build the package locally and 
make sure I have all necessary dependencies.

I have been unable to locate a source rpm package for python 2.5.2 or any 
version of 2.5 for that matter.

Any pointers would be appreciated.



  

Donald Raikes | Accessibility Specialist
Phone: +1 602 824 6213 | Fax: +1 602 824 6213 | Mobile: +1 520 271 7608 
Oracle JDeveloper QA

  
"Please
 consider your environmental responsibility before printing this e-mail"

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


Re: Timed execution in eval

2008-03-09 Thread castironpi
> Write the docs:
>
> > when two threads simultaneously increment the reference count of the same 
> > object
>
> Well, the example sucked.  Just synchronize ref count manipulation.
> Every OS has locking primitives, and a library exists to deny requests
> to block that lock dead.  How integral is the GIL to Python?
>
> > The Python interpreter is not fully thread safe
>
> Make it so.

Per-thread reference counts do the trick.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: any chance regular expressions are cached?

2008-03-09 Thread Ryan Ginstrom
> On Behalf Of Tim Chase
> Sounds like what you want is to use the compile() call to 
> compile once, and then use the resulting objects:
> 
>re1 = re.compile(r'\n')
>re2 = re.compile(r'^')
>...
>s = re1.sub('\n' + spaces, s)
>s = re2.sub(spaces, s)

Yes. And I would go a step further and suggest that regular expressions are
best avoided in favor of simpler things when possible. That will make the
code easier to debug, and probably faster.

A couple of examples:
>>> text = """spam spam spam
spam spam


 spam

spam"""
>>> # normalize newlines
>>> print "\n".join([line for line in text.splitlines() if line])
spam spam spam
spam spam
 spam
spam
>>> # normalize whitespace
>>> print " ".join(text.split())
spam spam spam spam spam spam spam
>>> # strip leading/trailing space
>>> text = "  spam  "
>>> print text.lstrip()
spam  
>>> print text.rstrip()
  spam
>>> print text.strip()
spam

Regards,
Ryan Ginstrom

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


Re: Timed execution in eval

2008-03-09 Thread castironpi
> >  > and I want to be able to stop [functions] if they run too long.
>
> > That's tricky [due to a synthetic limitation].

It would suck if you couldn't hold the GIL for as long as you need
to.  But how much is it used?

Wrote the docs:
> when two threads simultaneously increment the reference count of the same 
> object

Well, the example sucked.  Just synchronize ref count manipulation.
Every OS has locking primitives, and a library exists to deny requests
to block that lock dead.  How integral is the GIL to Python?

> The Python interpreter is not fully thread safe

-Make- it so.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: any chance regular expressions are cached?

2008-03-09 Thread Tim Chase
> s=re.sub(r'\n','\n'+spaces,s)
> s=re.sub(r'^',spaces,s)
> s=re.sub(r' *\n','\n',s)
> s=re.sub(r' *$','',s)
> s=re.sub(r'\n*$','',s)
> 
> Is there any chance that these will be cached somewhere, and save
> me the trouble of having to declare some global re's if I don't
> want to have them recompiled on each function invocation?


 >>> import this
...
Explicit is better than implicit
...


Sounds like what you want is to use the compile() call to compile 
once, and then use the resulting objects:

   re1 = re.compile(r'\n')
   re2 = re.compile(r'^')
   ...
   s = re1.sub('\n' + spaces, s)
   s = re2.sub(spaces, s)
   ...


The compile() should be done once (outside loops, possibly at a 
module level, as, in a way, they're constants) and then you can 
use the resulting object without the overhead of compiling.

-tkc



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


Re: parralel downloads

2008-03-09 Thread castironpi
> > That's it.  Far easier than threads.

I'll order a 'easyness' metric from the warehouse.  Of course,
resources are parameters to the metric, such as facility given lots of
time, facility given lots of libraries, facility given hot shots, &c.

> Easier? If you omit all the relevant details, yes, looks easy. For  
>
> def downloadfile(url, fn):
>    s = create socket for url
>    f = open filename for writing
>    shutil.copyfileobj(s.makefile(), f)
>
> for each url, filename to retrieve:
[ threadlist.addandstart( threading.Thread(target=downloadfile,
args=(url,filename)) ) ]
>
[ threadlist.joineach() ]

> Of course, don't try to download a million files at the same time -  
> neither a million sockets nor a million threads would work.

Dammit!  Then what's my million-core machine for?  If architectures
"have reached the point of diminishing returns" ( off py.ideas ), then
what's the PoDR for numbers of threads per core?

Answer: One.  Just write data structures and don't swap context.  But
when do you want it by?  What is the PoDR for amount of effort per
clock cycle saved?  Get a Frank and a Brit and ask them what language
is easiest to speak.

(Answer: Math.  Har *plonk*.)
-- 
http://mail.python.org/mailman/listinfo/python-list


any chance regular expressions are cached?

2008-03-09 Thread mh
I've got a bit of code in a function like this:

s=re.sub(r'\n','\n'+spaces,s)
s=re.sub(r'^',spaces,s)
s=re.sub(r' *\n','\n',s)
s=re.sub(r' *$','',s)
s=re.sub(r'\n*$','',s)

Is there any chance that these will be cached somewhere, and save
me the trouble of having to declare some global re's if I don't
want to have them recompiled on each function invocation?

Many TIA!
Mark

-- 
Mark Harrison
Pixar Animation Studios
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What c.l.py's opinions about Soft Exception?

2008-03-09 Thread castironpi
On Mar 9, 4:51 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> > Perhaps similar technique the compiler uses to determine whether a
> > function is a normal function or a generator function? Positive
> > forward lookup for any soft exceptions, which would then activate
> > matching soft exceptions inside the code?
>
> What would work is most probably to register soft-exception-handlers
> when encountering them at runtime, thus making raising-code aware of
> them and execute it only if there are one (or several) present.
>
> [HO snip]

Mr. Roggisch, I just said that.  You can unplonk me now.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Returning values from function to Python shell/IPython

2008-03-09 Thread castironpi
> >  > well after all it's a function so the only ways you can get things out
> >  > of it are:
> >  > - return a dict with all the objects
> >  > - use global (very messy)
> >  > - use a decorator to do either of the above.
>
> >  Messy, all of those... :(.
>
> >  > on the other hand have you consider using a proper test package?
> >  > instead of inspecting the objects manually from the shell you could
> >  > make it all automatic. with assert statements. you could use the std.
> >  > python testing moduleshttp://docs.python.org/lib/development.htmlor
> >  > something less verbosed like nose
>
> >  Usually, I'm using standard Python testing modules, but sometimes that is
> >  just an overkill. Sometimes I like to do 'exploratory programming',
> >  especially in the early phases of development - create a bunch of objects I
> >  want to play with and do that from IPython. Only way I found out to
> >  somewhat automate this procedure is to have a function that creates all of
> >  the test objects, and then raises an exception at the end. IPython starts
> >  ipdb, so I can work with the objects the function created (without copying
> >  them back to the shell). But this somehow looks too hack-ish for me, so I
> >  was wondering if there was an alternative...
>
> ohhh if that is the case then what you are doing seems to be the
> optimal. Just have module lvl code ran the testing in fact I don't
> even put those into the if __name__, the reason is that this is just
> temp testing that will later become real unit testing, and will never
> hit a production app. it gives you the most flexibility.

While you're at it, can you call up prior source, and edit it?  BASIC
had line numbers:

10 def f( a ):
20   return a+ 1

>>> 15 print( a )

10 def f( a ):
15 print( a )
20   return a+ 1

>>> 15   print( a )

10 def f( a ):
15   print( a )
20   return a+ 1

'''Interactives could some day have this too:'''

>>> edit f
Object f opened in editor
>>> close
Object f written back.  Elapsed time 5 minutes.
>>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 1.5.2 and functools or similar

2008-03-09 Thread Terry Reedy

"Troels Thomsen" <"nej tak..."@bag.python.org> wrote in message 
news:[EMAIL PROTECTED]
| def updateTimers()
|  for timerItm in timerTable:
|  ...
|
|  
|timerItm.func(*timerItm.parameters)
|
| Works well on python 2.5 but not on 1.5.2 (?)

apply(timerItm.func, timerItm.parameters) # see
http://docs.python.org/lib/non-essential-built-in-funcs.html
apply disappears in 3.0

tjr



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


Re: Intra-Package References

2008-03-09 Thread Gabriel Genellina
En Sat, 08 Mar 2008 17:36:12 -0200, xkenneth <[EMAIL PROTECTED]> escribió:

> Does your python module have to exist in the path in order for intra-
> package references to work?

No, but Python must be aware that the importing module is inside a  
package. So the script being executed (main) should live outside the  
package.

-- 
Gabriel Genellina

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


Re: Beautiful Code in Python?

2008-03-09 Thread castironpi
On Mar 2, 1:18 pm, [EMAIL PROTECTED] wrote:
> On Mar 2, 12:01 pm, John DeRosa <[EMAIL PROTECTED]> wrote:
>
> > On Mon, 3 Mar 2008 01:23:32 +0900, js <[EMAIL PROTECTED]> wrote:
> > >Hi,
>
> > >Have you ever seen Beautiful Python code?
> > >Zope? Django? Python standard lib? or else?
>
> > >Please tell me what code you think it's stunning.
>
> > Just about any Python code I look at.
>
> Decorators, with, and namedtuple.

Oh yeah, and variable arguments and keyword
dictionaries.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: execute

2008-03-09 Thread castironpi
> >  os.exec*() will close the current program.
>
> On *nix, you can use os.fork().  According 
> tohttp://effbot.org/librarybook/os.htm, you can use

Do you mean, and block for the process to terminate?  Or do you mean,
do something else in the meantime, perhaps for a certain amount (of
meantime)?

[Enter event loops.  Exeunt.]

P.S.  What do you do if you think of a comeback for something from a
week ago on the newsgroup?

P.P.S.  Why are you thinking of comebacks on a newsgroup besides
alt.flame?

P.P.P.S.  Anyone read alt.tasteless?
-- 
http://mail.python.org/mailman/listinfo/python-list


Distributed App - C++ with Python for Portability?

2008-03-09 Thread Roopan
Hello!

I am looking at developing an enterprise-grade distributed data
sharing application - key requirements are productivity and platform
portability.

Will it be sensible to use C++ for performance-critical sections and
Python for all the glue logic.

Pls comment from your *experiences* how Python scales to large
projects( > 200KLOC).
I assume the C++/Python binding is fairly painless.

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


Re: __iter__ yield

2008-03-09 Thread Paul Hankin
On Mar 9, 8:58 pm, duccio <[EMAIL PROTECTED]> wrote:
> Someone knows if it's possible to make this __iter__ function with just  
> one 'yield' intead of two?
> ...
>      def __iter__(self):
>          yield self #1
>          for n in self.childs:
>              for nn in n.__iter__():
>                  yield nn #2

Only one yield and shorter (but not really any simpler):

from itertools import chain

class Node:
...
def __iter__(self):
for x in chain([self], *self.childs):
yield x

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


Re: 1.5.2 and functools or similar

2008-03-09 Thread Paul Rubin
"Troels Thomsen"  writes:
> timerItm.func(*timerItm.parameters)
> 
> Works well on python 2.5 but not on 1.5.2 (?)

I think in 1.5.2 the *args notation wasn't present and you had to say:

   apply(timerItm.func, timerItm.parameters)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need Help Building PythonQt on Windows

2008-03-09 Thread Martin v. Löwis
> Since I'm new to compiling Qt with mingw and completely new to python,
> I was hoping for tips on why I'm getting these errors.  If anyone has
> a better suggestion for a forum/mailing list then please let me know.

These symbols are all from pythonxy.dll. You need to add the 
corresponding import library (libpythonxy.a/pythonxy.lib) into
the linker line, using a -l option.

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


Re: Regarding coding style

2008-03-09 Thread castironpi
> > >> Good comments are better than bad names. Good names are better than bad
> > >> comments.
>
> > > If you're taking the time to write good comments, why not just fix the
> > > bad names?  The compiler/interpreter can never, ever catch bad comments.
>
> > Yes, but the Python compiler can only catch bad names if you do this at
> > the top of every module:
>
> > import semantic_analysis
> > import magic.crystal_ball.read_programmers_mind
>
> dir( magic )!
> dir( magic.crystal_ball )?

Someone should try annotating code with a dictionary lookup on
identifiers.  Anyone bored on Fridays?  No one should try printing out
the definitions in real-time as the code is executing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __iter__ yield

2008-03-09 Thread Diez B. Roggisch
duccio schrieb:
> 
> Hello!
> Someone knows if it's possible to make this __iter__ function with just 
> one 'yield' intead of two?
> Is there some simpler way to make this  __iter__ iter through all nodes?
> Thanks!
> 
> class Node:
> def __init__(self, data=None):
> self.childs=[]
> self.data=data
> def appendNode(self, n):
> node=Node(n)
> self.childs.append(node)
> return node
> def __str__(self):
> return '<'+str(self.data)+'>'
> def __iter__(self):
> yield self #1
> for n in self.childs:
> for nn in n.__iter__():
> yield nn #2

Nope. There have been numerous discussions about this, introducing 
something like a yield_all-keyword or such thing that would replace the 
above boilerplate - but so far they all have been rejected. Search the 
archives for the reasons, I don't remember them :)

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


Re: Logically/Selectively Sub Class?

2008-03-09 Thread Diez B. Roggisch
xkenneth schrieb:
> On Mar 9, 4:38 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>> xkenneth schrieb:
>>
>>> Might be a silly question, but is it possible to selectively subclass,
>>> IE subclass is a supporting module is present and not otherwise.
>> Yes, something like this should work
>>
>> class Foo(some, base, classes)
>> pass
>>
>> if condition:
>> Temp = Foo
>> class Foo(Temp, otherclass): pass
>>
>> Alternatively, you can use the type-function to create classes explicit
>> with a list of base-classes.
>>
>> However it smells after bad design... what's your actual usecase?
>>
>> Diez
> 
> Yeah, it's really a non-issue, just more a curiosity. I'm using ZODB
> for a lot of my stuff now, and I need my objects to be persistent,
> however there might be a case where my classes could be used in a non-
> persistent manner. I'll just have ZODB as a requirement for my
> package.

Ah. Then this also might work

try:
from ZODB import Persistent
except ImportError:
class Persistent: pass

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


Re: What c.l.py's opinions about Soft Exception?

2008-03-09 Thread Diez B. Roggisch
> Perhaps similar technique the compiler uses to determine whether a
> function is a normal function or a generator function? Positive
> forward lookup for any soft exceptions, which would then activate
> matching soft exceptions inside the code?

The difference between generators and functions is made on the 
yield-keyword.

However, the exception-mechanism isn't governed by the compiler, but at 
runtime. You can do things like this:


eclass = HardException if full_moon() else: SoftException

raise eclass()

Which means that you don't stand a chance determining 
soft-exception-usage at compiletime.

What would work is most probably to register soft-exception-handlers 
when encountering them at runtime, thus making raising-code aware of 
them and execute it only if there are one (or several) present.

However, IMHO it's not a worthy extension to the language - for the same 
reasons Steven gave. It seems only useful for tightly coupled code, not 
as a general mechanism. And callbacks or maybe even thread-local state 
are sufficient to deal with that I'd say.


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


Re: Logically/Selectively Sub Class?

2008-03-09 Thread castironpi
On Mar 9, 4:28 pm, xkenneth <[EMAIL PROTECTED]> wrote:
> Might be a silly question, but is it possible to selectively subclass,
> IE subclass is a supporting module is present and not otherwise.
>
> Regards,
> Kenneth Miller

if mod is present:
   class Waypoint( Mine, Yours ): pass
else:
   class Waypoint( Mine ): pass

class NewClass( Waypoint ).

In 3.0, you can do

if mod is present:
   bases= Mine, Yours
else:
   bases= Mine,

class NewClass( *bases ).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Logically/Selectively Sub Class?

2008-03-09 Thread xkenneth
On Mar 9, 4:38 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> xkenneth schrieb:
>
> > Might be a silly question, but is it possible to selectively subclass,
> > IE subclass is a supporting module is present and not otherwise.
>
> Yes, something like this should work
>
> class Foo(some, base, classes)
>     pass
>
> if condition:
>     Temp = Foo
>     class Foo(Temp, otherclass): pass
>
> Alternatively, you can use the type-function to create classes explicit
> with a list of base-classes.
>
> However it smells after bad design... what's your actual usecase?
>
> Diez

Yeah, it's really a non-issue, just more a curiosity. I'm using ZODB
for a lot of my stuff now, and I need my objects to be persistent,
however there might be a case where my classes could be used in a non-
persistent manner. I'll just have ZODB as a requirement for my
package.

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


Re: 1.5.2 and functools or similar

2008-03-09 Thread castironpi
On Mar 9, 4:26 pm, "Troels Thomsen"  wrote:
> Hello,
>
> I am writing a simple delayed-call mechanism , that is causing a bit of
> headache. Works like this:
>
> myPrint(s)
>   print "..." + s
>
> myTimer.add(myPrint , "hello" , 15)
>
> This means that the myprint function is called in 15 seconds with the
> parameter "hello".
> The housekeeping of these timers is called by the main loop of the "os"
>
> This works well but i would like to be able to use it with any number of
> parameters
>
> Functools is not a part of the 1.5.2+ python that I am running on (embedded
> device),
> so i tried to pass the parameters as a tuple like this
>
> myTimer.add(myAdder , (3,6) , 15)
>
> and the housekeeping function would then call the function like this
>
> def updateTimers()
>   for timerItm in timerTable:
>   ...
>     
>       
>         timerItm.func(*timerItm.parameters)
>
> Works well on python 2.5 but not on 1.5.2 (?)
>
> Current solution is to have default parameters None for the add function
>
> def add( func , timeout , param1 = None , param2 = None)
>
> And the update function then checks if parameters is specified
>
> def updateTimers()
>   for timerItm in timerTable:
>   ...
>     
>       
>       # ugly part :
>       if timerItm.param1 is not None and timerItm.param2 is not None:
>         timerItm.func(timerItm.param1, timerItm.param2) # two parameters
>       elif ..
>         timerItm.func(timerItm.param1) # one parameter
>       else
>         timerItm.func() # no parameters
>
> This has the implication that I can not call a function with the parameter
> None if I wanted to.
> (not a huge problem)
>
> Right now it works quite well with up to two parameters, it covers 99% of
> usage. If I need to call a function with more parameters, i can always write
> a wrapper function for it. Wondering if anyone had some sugestions ?
>
> By the way, is it bad style to check for object identity instead of value
> "None".
> What aboutt integers ? if value is 0: ..
> I guess it is implementation specific / could change in future versions ?
>
> Thx,
> Troels

def g( arg1, arg2 ):
   print( arg1, arg2 )
   return arg1

def h( arg1 ):
   print( arg1 )
   return arg1

def caller( fun, *args, **kwargs ):
   return fun( *args, **kwargs )

print( caller( g, 'abc', 'def' ) )
print( caller( h, 'abc' ) )

'''
abc def
abc
abc
abc
'''
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: execute

2008-03-09 Thread Dan Upton
On Sun, Mar 9, 2008 at 5:22 PM, Gif <[EMAIL PROTECTED]> wrote:
> i'm trying to execute a file without replacing the current process,
>  but after searching the help file, documentations and the web, i can't
>  a way of doing that.
>
>  os.exec*() will close the current program.
>
>  ps: by executing i mean like typing "mspaint" in run dialog.. it's not
>  a python file

On *nix, you can use os.fork().  According to
http://effbot.org/librarybook/os.htm , you can use os.spawn to
accomplish a similar effect on Windows, although I haven't used it.
Also, you might check the subprocess module --
http://docs.python.org/lib/module-subprocess.html .

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


Re: Logically/Selectively Sub Class?

2008-03-09 Thread Diez B. Roggisch
xkenneth schrieb:
> Might be a silly question, but is it possible to selectively subclass,
> IE subclass is a supporting module is present and not otherwise.

Yes, something like this should work

class Foo(some, base, classes)
pass

if condition:
Temp = Foo
class Foo(Temp, otherclass): pass


Alternatively, you can use the type-function to create classes explicit 
with a list of base-classes.

However it smells after bad design... what's your actual usecase?

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


Re: execute

2008-03-09 Thread Gif
ok i found a workaround.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: execute

2008-03-09 Thread Gif
i know os.popen() but i want to execute a file with args
-- 
http://mail.python.org/mailman/listinfo/python-list


Logically/Selectively Sub Class?

2008-03-09 Thread xkenneth
Might be a silly question, but is it possible to selectively subclass,
IE subclass is a supporting module is present and not otherwise.

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


1.5.2 and functools or similar

2008-03-09 Thread Troels Thomsen

Hello,

I am writing a simple delayed-call mechanism , that is causing a bit of 
headache. Works like this:

myPrint(s)
  print "..." + s

myTimer.add(myPrint , "hello" , 15)

This means that the myprint function is called in 15 seconds with the 
parameter "hello".
The housekeeping of these timers is called by the main loop of the "os"

This works well but i would like to be able to use it with any number of 
parameters

Functools is not a part of the 1.5.2+ python that I am running on (embedded 
device),
so i tried to pass the parameters as a tuple like this

myTimer.add(myAdder , (3,6) , 15)

and the housekeeping function would then call the function like this

def updateTimers()
  for timerItm in timerTable:
  ...

  
timerItm.func(*timerItm.parameters)

Works well on python 2.5 but not on 1.5.2 (?)


Current solution is to have default parameters None for the add function

def add( func , timeout , param1 = None , param2 = None)

And the update function then checks if parameters is specified

def updateTimers()
  for timerItm in timerTable:
  ...

  
  # ugly part :
  if timerItm.param1 is not None and timerItm.param2 is not None:
timerItm.func(timerItm.param1, timerItm.param2) # two parameters
  elif ..
timerItm.func(timerItm.param1) # one parameter
  else
timerItm.func() # no parameters

This has the implication that I can not call a function with the parameter 
None if I wanted to.
(not a huge problem)

Right now it works quite well with up to two parameters, it covers 99% of 
usage. If I need to call a function with more parameters, i can always write 
a wrapper function for it. Wondering if anyone had some sugestions ?


By the way, is it bad style to check for object identity instead of value 
"None".
What aboutt integers ? if value is 0: ..
I guess it is implementation specific / could change in future versions ?


Thx,
Troels









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


execute

2008-03-09 Thread Gif
i'm trying to execute a file without replacing the current process,
but after searching the help file, documentations and the web, i can't
a way of doing that.

os.exec*() will close the current program.

ps: by executing i mean like typing "mspaint" in run dialog.. it's not
a python file
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regarding coding style

2008-03-09 Thread castironpi
On Mar 9, 4:25 am, Lie <[EMAIL PROTECTED]> wrote:
> On Mar 9, 3:27 am, [EMAIL PROTECTED] wrote:
>
> > To Lie:
>
> > > Personally I preferred a code that has chosen good names but have
> > > little or no comments compared to codes that makes bad names and have
>
> > Personally I don't.  Show me a good one.  Until you do, it's not that
> > I won't like it, it's that I can't.  You know, in linguistics, there's
>
> But I much prefer it that the code has good names AND concise
> comments, not too short and not too long that it becomes obscure.

What do you mean?  If 'obscure' is the right word, then it's
subjective (from metrics import obscurity?), which means that 10% of
the people disagree with you, or 90% do.  The end-all be-all, there is
no such thing.  I don't think it's obscure; I do.  Is it?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regarding coding style

2008-03-09 Thread castironpi
On Mar 8, 7:51 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sat, 08 Mar 2008 13:40:56 -0800, dave_mikesell wrote:
> > On Mar 8, 2:27 pm, [EMAIL PROTECTED] wrote:
>
> >> Good comments are better than bad names. Good names are better than bad
> >> comments.
>
> > If you're taking the time to write good comments, why not just fix the
> > bad names?  The compiler/interpreter can never, ever catch bad comments.
>
> Yes, but the Python compiler can only catch bad names if you do this at
> the top of every module:
>
> import semantic_analysis
> import magic.crystal_ball.read_programmers_mind

dir( magic )!
dir( magic.crystal_ball )?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: parralel downloads

2008-03-09 Thread Gabriel Genellina
En Sat, 08 Mar 2008 14:47:45 -0200, Gary Herron  
<[EMAIL PROTECTED]> escribi�:

> poof65 wrote:
>> For your problem you have to use threads.
>>
> Not at all true.  Thread provide one way to solve this, but another is
> the select function.  For this simple case, select() may (or may not) be
> easier to write.  Pseudo-code would look something like this:
>
>   openSockets = list of sockets one per download file:
>   while openSockets:
> readySockets = select(openSockets ...) # Identifies sockets with
> data to be read
> for each s in readSockets:
>   read from s and do whatever with the data
>   if s is at EOF: close and remove s from openSockets
>
> That's it.  Far easier than threads.

Easier? If you omit all the relevant details, yes, looks easy. For  
example, you read some data from one socket, part of the file you're  
downloading. Where do you write it? You require additional structures to  
keep track of things.
Pseudocode for the threaded version, complete with socket creation:

def downloadfile(url, fn):
   s = create socket for url
   f = open filename for writing
   shutil.copyfileobj(s.makefile(), f)

for each url, filename to retrieve:
   t = threading.Thread(target=downloadfile, args=(url,filename))
   add t to threadlist
   t.start()

for each t in threadlist:
   t.join()

The downloadfile function looks simpler to me - it's what anyone would  
write in a single threaded program, with local variables and keeping full  
state.
The above pseudocode can be converted directly into Python code - no more  
structures nor code are required.

Of course, don't try to download a million files at the same time -  
neither a million sockets nor a million threads would work.

-- 
Gabriel Genellina

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

Re: parralel downloads

2008-03-09 Thread castironpi
> > > >>  my problem is that I would like to download several files at the time.
> > > >>  As I have not much experience in programming, could you point me the
> > > >>  easier ways to do this in python ?
>
> > Thank you both for your help. Threads are working for me. However, a
> > new problem for me is that the url I want to download are in an xml
> > file (I want to download podcasts), and is not the same as the file
> > downloaded:
>
> >http://www.sciam.com/podcast/podcast.mp3?e_id=86102326-0B1F-A3D4-74B2...
>
> > will be redirected to download:
>
> >http://podcast.sciam.com/daily/sa_d_podcast_080307.mp3
>
> > is there a way, knowing the first url to get the second at runtime in
> > my script ?
>
> Found it: geturl() does the job

That's for normalizing schemes.  I believe you subclass FancyURLopener
and override the read method.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Checking if a variable is a dictionary

2008-03-09 Thread castironpi
On Mar 9, 9:23 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sun, 09 Mar 2008 06:58:15 -0700, Guillermo wrote:
> > Okay, so I think I know where's the catch now -- you must rely on the
> > fact that the protocol is implemented, there's no way to enforce it if
> > you're expecting a parrot-like object. You'd try to call the speak()
> > method and deal with the error if there's no such method?
>
> That's right. That's called "duck typing" -- if all you want is something
> that quacks like a duck, then it doesn't matter if it actually is a duck
> or not.
>
> Or if you prefer: if it quacks like a duck and swims like a duck, then
> it's close enough to a duck as to make no difference.

The syntax checker over here raised a warning on this one.  "So close
to a duck as."  (I'm using the so...as construct in my Propositional
Calculus program.)

> try:
>     something.speak
> except AttributeError:
>     # No speak() method, so it can't be a parrot.
>     do_something_else()

It might be a dead parrot.  HAR!

> else:
>     # It seems to follow the parrot protocol.
>     yummy_goodness = something.speak(5)
>     assert "spam" in yummy_goodness.lower()

P.S.  Is 'resemblant' a word?  So resemblant of a duck as.
-- 
http://mail.python.org/mailman/listinfo/python-list


__iter__ yield

2008-03-09 Thread duccio

Hello!
Someone knows if it's possible to make this __iter__ function with just  
one 'yield' intead of two?
Is there some simpler way to make this  __iter__ iter through all nodes?
Thanks!

class Node:
 def __init__(self, data=None):
 self.childs=[]
 self.data=data
 def appendNode(self, n):
 node=Node(n)
 self.childs.append(node)
 return node
 def __str__(self):
 return '<'+str(self.data)+'>'
 def __iter__(self):
 yield self #1
 for n in self.childs:
 for nn in n.__iter__():
 yield nn #2

n=Node()
n.appendNode(1).appendNode(2).appendNode(3).appendNode(4)
n.appendNode(11).appendNode(22).appendNode(33).appendNode(44)
for node in n:
 print node
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What c.l.py's opinions about Soft Exception?

2008-03-09 Thread castironpi
D'Aprano suggested callbacks.  How does this work for you?

class SomeNumeric(object):
def __div__(a, b):
if b == 0: raise ZeroDivisionError  ## Hard Exception...
if a == 0: msgboard- ZeroNumerator()
f = a / b
i = a // b
if f == float(i):
msgboard- IntegerDivision()
return a // b #? return i?
else:
msgboard- FloatDivision()
return a / b #? return f?


If it works, I can write some implementations of msgboard and discuss
its scope.

It sounded at one point like you were augmenting control flow, but you
cleared that up by saying, raise SoftException is not a true raise.
Correct?

There is a limit to how many behaviors you can fit in a single
statement in any language.  What behaviors is determined by other
choices in the language design.  Those choices have many consequences,
some linguistic, some social, and some personal.  If a dictator always
makes impersonal decisions, which linguistic + social ones should he
make?  If the answer is, "No, we will not strike note J and K because
we elected to strike notes L and M instead", then it's disappointing,
but it might ease that to know what L and M are.

Lastly, that notation I wrote was kind of sly.  I might favor
msgboard( ZeroNumerator() ) or even msgboard.add( ZeroNumerator() ).

How far are you willing to come from the OP's proposal to get it to
work?  If they add something half-way there, but you don't get exactly
what you want, is that fair?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: del class with recursive list

2008-03-09 Thread duvo

Thanks! I just need to remember to del the variables after "for in".

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


Re: the way of "import"

2008-03-09 Thread Gabriel Genellina
En Sat, 08 Mar 2008 00:30:13 -0200, smalltalk <[EMAIL PROTECTED]>  
escribi�:

> I have three files names t1.py,t2.py,t3.py in e:\test\dir1,of course
> dir2 is exsit
> the content of t1.py as follow:
> t1.py
> import os
> print 'this is t1.py'
> os.chdir('..\\dir2')
> the content of t2.py as follow:
> print "this is t2.py"
> the content of t3.py as follow:
> import t1
> import t2
>
>
> if i run t3.py in cmd of windows as follow:
> python t3.py
>
> no errors show
>
> if i run t3.py in idle:
 import t3
> this is t1.py
> Traceback (most recent call las
>   File "", line 1, in 
>   File "t3.py", line 2, in 
> ImportError: No module named t2
>
> can you give me a help?

Which Python version? Which Windows version? With IDLE from Python 2.5.1  
on XP I don't get the error (and that's the right thing)

-- 
Gabriel Genellina

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

Re: Need Help Building PythonQt on Windows

2008-03-09 Thread Diez B. Roggisch
Jeff Schiller schrieb:
> I said "PythonQt" not PyQt.  That's an important distinction, I think :)
> 
> See http://pythonqt.sourceforge.net/

It sure is. Sorry, didn't realize the difference.

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


Re: SV: Changing the size of a Button

2008-03-09 Thread Peter Otten
K Viltersten wrote:

> What i wish to do is to affect the size
> of the button but not due to change of
> text but due to resize of the frame it
> resides in.

This is done by the layout manager, too:
 
import Tkinter as tk

root = tk.Tk()
button = tk.Button(root, text="42")
button.pack(fill=tk.BOTH, expand=True)
root.mainloop()

Alternatively, with a grid layout:

button.grid(row=0, column=0, sticky="nsew")
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)

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


Re: SV: Changing the size of a Button

2008-03-09 Thread Marc 'BlackJack' Rintsch
On Sun, 09 Mar 2008 19:45:58 +0100, K Viltersten wrote:

> What i wish to do is to affect the size 
> of the button but not due to change of 
> text but due to resize of the frame it
> resides in.
> 
> This far i've managed to get a callback 
> to a function as the resize occurs and to
> print the sizes. However, i'd like to 
> assign these values to the button so it 
> always stays the same width as the frame.

Don't do it yourself, pack with the `fill` argument set to `Tkinter.X`.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [pysqlite] [ANN] pysqlite and APSW projects moved

2008-03-09 Thread Gerhard Häring
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Gerhard Häring wrote:
> [...] APSW
> 
> 
> web:http://oss.itsystementwicklung.de/trac/apsw/
> scm:Subversion: http://initd.org/svn/pysqlite/apsw/trunk/

That should have been http://oss.itsystementwicklung.de/svn/apsw/apsw/

- -- Gerhard
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFH1DL7dIO4ozGCH14RAq4gAJ9tZuB9qcPERBkGzKEVBEx8nybfXgCeK8cX
V7sH3uAskDDNBuxYG34vExI=
=IXOx
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


[ANN] pysqlite and APSW projects moved

2008-03-09 Thread Gerhard Häring
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Dear pysqlite users!

I've moved both the pysqlite and APSW project to new homes.

pysqlite


web:http://oss.itsystementwicklung.de/trac/pysqlite aka http://pysqlite.org/
scm:pysqlite now uses a Mercurial repository
http://oss.itsystementwicklung.de/hg/pysqlite/

APSW


web:http://oss.itsystementwicklung.de/trac/apsw/
scm:Subversion: http://initd.org/svn/pysqlite/apsw/trunk/

Both pysqlite and APSW have a common mailing list at

http://itsystementwicklung.de/cgi-bin/mailman/listinfo/list-pysqlite

Existing subscribers that have not set the "nomail" flag have been moved to the
new list already.

- -- Gerhard

PS: Because of spam problems on the old Trac, I've patched AccountManager so
that you will now have to verify your human-ness with a captcha when you
register an account. The old Trac accounts were not moved on purpose to avoid
spam.

-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFH1C7tdIO4ozGCH14RAjAhAKCmxm+rKkjxMalCkH2Wjs88raxuCACgiV4B
XJq+YweOK0Zh1IWHLkrl3LI=
=b6zE
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: gc question

2008-03-09 Thread I V
On Sun, 09 Mar 2008 01:57:38 -0800, Vince wrote:
> Well, that suits me. The most unnatural thing about Python was adapting
> to the idea of just letting unreleased resources go jogging off
> wherever. :)

Yes, that's a bad habit that garbage collection can encourage. GC is good 
for managing memory, but not good for managing other resources, so if an 
object holds some other resource, it's important to make sure the 
resource is released in a timely fashion rather than relying on the 
finalizer (the __del__ function).

CPython uses reference counting, so it usually destroys objects fairly 
soon after the stop being used. But JPython and IronPython don't do 
reference counting, so forgetting to clean up resources can be a 
significant problem.

> "Where's the f.close?"
> "You don't need it!"

Although, you still don't need f.close, with the new with statement:

with open('myfile') as f:
string = f.readline()
# f.close() gets called automatically here, without waiting for 
# garbage collection.

If you want to use this in 2.5, you have to write:

from __future__ import with_statement

The big advantage here is that f.close will get called if the block exits 
normally, or if there is an exception. For more, see 
http://effbot.org/pyref/with.htm .
-- 
http://mail.python.org/mailman/listinfo/python-list


SV: Changing the size of a Button

2008-03-09 Thread K Viltersten
>> How do i change the size of a Button
>> (using Tkinter), other than to set it
>> during construction?
> In Tkinter, usually the geometry managers 
> (such as pack) are the ones who size the 
> widgets. If you run something like:
>import Tkinter as tk
> 
>root = tk.Tk()
>def change_size():
>b["text"] = "More text"
> 
>b = tk.Button(root, text="Text", command=change_size)
>b.pack()
> 
>root.mainloop()

Thanks for the answer.

Unfortunately, that won't help me at all, 
since i, apparently, asked the wrong 
question. Let me refrain myself.

What i wish to do is to affect the size 
of the button but not due to change of 
text but due to resize of the frame it
resides in.

This far i've managed to get a callback 
to a function as the resize occurs and to
print the sizes. However, i'd like to 
assign these values to the button so it 
always stays the same width as the frame.

--
Regards
Konrad Viltersten

sleep- a substitute for coffee for the poor
ambition - lack of sense to be lazy

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


Re: Parse specific text in email body to CSV file

2008-03-09 Thread Miki
Hello,
>
 I have been searching all over for a solution to this. I am new to
> Python, so I'm a little lost. Any pointers would be a great help. I
> have a couple hundred emails that contain data I would like to
> incorporate into a database or CSV file. I want to search the email
> for specific text.
>
> The emails basically look like this:
>
> random text _important text:_15648 random text random text random text
> random text
> random text random text random text _important text:_15493 random text
> random text
> random text random text _important text:_11674 random text random text
> random text
> ===Date: Wednesday March 5, 2008
> name1: 15                name5: 14
>
> name2: 18                name6: 105
>
> name3: 64                name7: 2
>
> name4: 24                name8: 13
>
> I want information like "name1: 15" to be placed into the CSV with the
> name "name1" and the value "15". The same goes for the date and
> "_important text:_15493".
>
> I would like to use this CSV or database to plot a graph with the
> data.
import re

for match in re.finditer("_([\w ]+):_(\d+)", text):
print match.groups()[0], match.groups()[1]

for match in re.finditer("Date: ([^=]+)=", text):
print match.groups()[0]

for match in re.finditer("(\w+): (\d+)", text):
print match.groups()[0], match.groups()[1]


Now you have two problems :)

HTH,
--
Miki <[EMAIL PROTECTED]>
http://pythonwise.blogspot.com

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


Re: Changing the size of a Button

2008-03-09 Thread Miki
Hello Konrad,

> How do i change the size of a Button
> (using Tkinter), other than to set it
> during construction?
In Tkinter, usually the geometry managers (such as pack) are the ones
who size the widgets.
If you run something like:
import Tkinter as tk

root = tk.Tk()
def change_size():
b["text"] = "More text"

b = tk.Button(root, text="Text", command=change_size)
b.pack()

root.mainloop()

You'll see that the button changes size to accommodate the new text.

HTH,
--
Miki <[EMAIL PROTECTED]>
http://pythonwise.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Problems installing Python Imaging Library

2008-03-09 Thread Nick Day
Hi,

I'm trying to install PIL from source on my CentOS 4.5 server. The
build summary reports that I have everything installed...


PIL 1.1.6 BUILD SUMMARY

version   1.1.6
platform  linux2 2.3.4 (#1, Dec 11 2007, 05:28:55)
  [GCC 3.4.6 20060404 (Red Hat 3.4.6-9)]

--- TKINTER support ok
--- JPEG support ok
--- ZLIB (PNG/ZIP) support ok
--- FREETYPE2 support ok

... but if I try and build it I receive the following error:

/usr/bin/ld: /usr/local/lib/libjpeg.a(jcparam.o): relocation
R_X86_64_32 against `a local symbol' can not be used when making a
shared object; recompile with -fPIC

How do I fix this?  I am currently running "python setup.py build" and
don't understand how I would change the compiling options to add the "-
fPIC" flag.  I'm quite a newbie when it comes to Linux/Python so any
help you could give me would be great.

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


Re: What c.l.py's opinions about Soft Exception?

2008-03-09 Thread Lie
On Mar 9, 9:29 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote:
(snip)
> You are an appropriate person to consider the workflow in a dynamic
> language, no matter how the language is implemented internally.

I agree, but the only thing I'm not confident to talk about is how
it'll be implemented, since I think an idea should suggest how it can
be implemented in practice to show that it's not just a nonsense paper
idea that's not possible in reality.

> Just start with function calls
>
>    maybe_raise(ZeroDivisionError)
>
> The only requirement is that maybe_raise has to know when it shall
> raise ZeroDivisionError. This depends on whether the exception is
> caught. How do the program knows this in advance? There are no static
> analysis techniques available.

Perhaps similar technique the compiler uses to determine whether a
function is a normal function or a generator function? Positive
forward lookup for any soft exceptions, which would then activate
matching soft exceptions inside the code?

> When maybe_raise is entered the system must know that the exception is
> handled in the future. You can't inspect the call stack for this
> purpose because the call stack represents past events and
> continuations ( and you can't rely on names ).
>
> So you need something like this
>
>    do_softexception(ZeroDivisionError)
>    try:
>       TRY_BLOCK
>    except ZeroDivisionError:
>       EXCEPT_BLOCK
>
> But this looks odd and the solution isn't DRY. So better one macro-
> transforms a new statement into this form.

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


Re: What c.l.py's opinions about Soft Exception?

2008-03-09 Thread Lie
On Mar 9, 7:54 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sun, 09 Mar 2008 00:30:51 -0800, Lie wrote:
> > (3) Informing codes above it about what's currently happening inside,
> > the thing is just a mundane report that might be useful to codes above
>
> > Which might be a useful place to use SoftExceptions
>
> Okay, now we're getting somewhere.
>
> So, I have a function foo() which raises a HardException on error, but it
> also raises a SoftException if it wants to notify me of something
> "mundane".
>
> def foo(sequence):
>     if args == []:
>         raise SoftException("empty list")
>     return len(args)
>
> Now, how do I use that?
>
> try:
>    x = foo(something)
> except TypeError:
>    print "you should pass a sequence"
>    sys.exit()  # unrecoverable error
> except SoftException:
>    print "you passed an empty list"
> print x
>
> Am I close?
>
> But there's a problem. Once the SoftException is caught, execution will
> continue from the line "print x" -- but the function foo() never got a
> chance to actually return a result!

In that particular case above, you don't need to handle the Soft
Exception. As stated in it's original purpose, you don't need to
handle a Soft Exception, it exists there if you need to handle the
exceptional case, but ignorable on other cases. _IF_ printing the "you
passed an empty list" is an important operation, you'd make it like
this:
try:
   x = foo(something)
except TypeError:
   print "you should pass a sequence"
   sys.exit()  # unrecoverable error
except SoftException:
print "you passed an empty list"
x = 0
print x

or alternatively:

try:
   x = foo(something)
except TypeError:
   print "you should pass a sequence"
   sys.exit()  # unrecoverable error
except SoftException:
print "you passed an empty list"
else:
print x

The case you states above only mentions that you haven't fully grasped
the workflow in exception-based system.

> In order to make that work, you would need a significant change to
> Python's internals. I don't know how difficult that would be, but I'm
> guess that it would be a lot of work for not much benefit.

I too don't know how difficult that'd be, especially because the only
thing I know about Python's internal is it implements its garbage
collector by ref counting (which is barely useful here).

> But even if that happened, it would mean that the one mechanism has TWO
> different effects:
>
> try:
>     x = foo(sequence)
> except SoftException:
>     print x  # this is okay, because foo() did return
> except TypeError:
>     print x  # this is NOT okay, because foo() never returned
>
> That is a recipe for confusion.

Both are not okay since foo() never return on both cases (soft
statement doesn't return to finish the try clause except if explicitly
resumed).

(snip)
> > Perhaps relabeling it as Warning, and renaming raise SoftException as
> > give Warning might make it more acceptable?
>
> Do you realise that Python already has a warnings module?

Ah... I completely forget about it, but anyway the Warning module is
unrelated to this. Perhaps we could just think of another name, but
names doesn't seems to be important in Python modules anyway, can you
guess what pickle/zip/mutex/quopri/curses is if you're new to Python
without looking at the documentations? There are some modules in
Python that have weird names, we ought to reduce it, but we can't
reduce it... we ought to live with it.

(snip)
> > A possible solution to this problem might be to check whether distance
> > is less than P1.radius + P2.radius in the calculateforce. But, this
> > obfuscate the code since we have to separate distance calculation from
> > the main formula (see !s),
>
> I don't agree that this obfuscates the code.

For a formula as complex as this:
http://www.mapleprimes.com/blog/axel-vogt/computing-the-complex-gamma-function-using-spouges-formula
it might be useful to fragment the formula to smaller pieces

but in a simple to moderately complex that still fits in one line,
fragmenting the code confuses the eye.

> And here's a way to do it that doesn't calculate anything twice, and
> doesn't require any exceptions:
>
> def calculateforce(P1, P2, dist):
>     return (P1.mass - P2.mass)/dist
>
> And then for all pairs of particles:
>
> dist = distance(P1, P2)
> if dist <= P1.radius + P2.radius:
>     clump(P1, P2)
>     break
> F = calculateforce(P1, P2, dist)

That... is the worst solution that could ever be suggested. The
Particle objects already contain their own position, supplying dist
overrides their real distance of the particles and also it may make
bug holes by supplying bogus distance:
def calculateforce(P1, P2, dist):
return (P1.mass - P2.mass) / dist

calculateforce(P1, P2, 'bogus data')

or simply by passing dist that isn't equal (P1.X - P2.X) ** 2 + (P1.Y
- P2.Y) ** 2.

If you want to do it that way, it'd be much better 

Re: Need Help Building PythonQt on Windows

2008-03-09 Thread Michael Wieher
2008/3/9, Jeff Schiller <[EMAIL PROTECTED]>:
>
> Hello,




I'm creating an application using Qt (4.4 Beta atm).  I have pretty
> close to zero experience with Python (consisting of installing the
> Python interpreter, downloading a python programming and executing it
> on the command-line).
>
> I would like to invoke a Python script from my C++ Qt program and
> capture its output as a C++ structure.  It seems that PythonQt might
> be suitable for my needs.
>
> Being a Qt program, I want this thing to be cross-platform.  I'm
> having trouble getting things set up in Windows.  Has anyone had any
> experience with this?
>
> I've built Qt from source using the mingw32 compiler.  I installed
> Python 2.5 binary.  I am trying to build PythonQt from source.  As per
> http://pythonqt.sourceforge.net/#Building it says I need a "developer
> installation" of Python containing the header files and  the library
> files.  When I look at my system after installing the Python 2.5
> binary, I can see I have header files (C:\Python25\include), a 199k
> python25.lib (C:\Python25\libs) and a 2MB python25.dll
> (C:\Windows\System32\).  Have I got what I need?
>
> I have tried to set up my symbols (PYTHON_PATH, PYTHON_LIB,
> PYTHONQT_ROOT).  I generate the Makefile (using qmake) and it starts
> to build but then it fails:
>
> g++ -enable-stdcall-fixup -Wl,-enable-auto-import
> -Wl,-enable-runtime-pseudo-reloc -mthreads -Wl -shared
> -Wl,--out-implib,lib\libPythonQt.a -o lib\PythonQt.dll
> object_script.PythonQt.Debug  -L"c:\Qt\4.4.0-beta1\lib"
> "c:\Python25\libs"/python25.lib -lQtGuid4 -lQtCored4
> ./debug\PythonQt.o: In function `ZN8PythonQtC2Ei':
> C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to
> `_imp__Py_NoSiteFlag'
> ./debug\PythonQt.o: In function `ZN8PythonQtC1Ei':
> C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to
> `_imp__Py_NoSiteFlag'
> ./debug\PythonQt.o: In function
> `ZN15PythonQtPrivate11wrapQObjectEP7QObject':
> C:/PythonQt-1.0/src/PythonQt.cpp:256: undefined reference to
> `_imp___Py_NoneStruct'
> C:/PythonQt-1.0/src/PythonQt.cpp:257: undefined reference to
> `_imp___Py_NoneStruct'
> ./debug\PythonQt.o: In function
> `ZN15PythonQtPrivate7wrapPtrEPvRK10QByteArray':
> C:/PythonQt-1.0/src/PythonQt.cpp:281: undefined reference to
> `_imp___Py_NoneStruct'
> C:/PythonQt-1.0/src/PythonQt.cpp:282: undefined reference to
> `_imp___Py_NoneStruct'
> ./debug\PythonQt.o: In function
> `ZN8PythonQt13introspectionEP7_objectRK7QStringNS_10ObjectTypeE':
> C:/PythonQt-1.0/src/PythonQt.cpp:620: undefined reference to
> `_imp__PyClass_Type'
> C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to
> `_imp__PyClass_Type'
> C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to
> `_imp__PyCFunction_Type'
> ...
>
> Since I'm new to compiling Qt with mingw and completely new to python,
> I was hoping for tips on why I'm getting these errors.  If anyone has
> a better suggestion for a forum/mailing list then please let me know.
>
> Thanks,
> Jeff
>
> --
> http://mail.python.org/mailman/listinfo/python-list



Another thing to be aware of, although this might not be something you need
to worry about, is that there are debug-versions of the python libraries
that are not installed by the MSI installer on windows.  Sadly, the only way
to get these libraries is to compile Python from source on your Windows
machine, being sure to also create the debug libraries at this time.  I
don't know if you need them or not, because the error message you got was
not entirely descriptive.

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

Re: Need Help Building PythonQt on Windows

2008-03-09 Thread Jeff Schiller
I said "PythonQt" not PyQt.  That's an important distinction, I think :)

See http://pythonqt.sourceforge.net/

Regards,
Jeff

On 3/9/08, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
> Jeff Schiller schrieb:
>
> > Hello,
>  >
>  > I'm creating an application using Qt (4.4 Beta atm).  I have pretty
>  > close to zero experience with Python (consisting of installing the
>  > Python interpreter, downloading a python programming and executing it
>  > on the command-line).
>  >
>  > I would like to invoke a Python script from my C++ Qt program and
>  > capture its output as a C++ structure.  It seems that PythonQt might
>  > be suitable for my needs.
>  >
>  > Being a Qt program, I want this thing to be cross-platform.  I'm
>  > having trouble getting things set up in Windows.  Has anyone had any
>  > experience with this?
>  >
>  > I've built Qt from source using the mingw32 compiler.  I installed
>  > Python 2.5 binary.  I am trying to build PythonQt from source.  As per
>  > http://pythonqt.sourceforge.net/#Building it says I need a "developer
>  > installation" of Python containing the header files and  the library
>  > files.  When I look at my system after installing the Python 2.5
>  > binary, I can see I have header files (C:\Python25\include), a 199k
>  > python25.lib (C:\Python25\libs) and a 2MB python25.dll
>  > (C:\Windows\System32\).  Have I got what I need?
>  >
>  > I have tried to set up my symbols (PYTHON_PATH, PYTHON_LIB,
>  > PYTHONQT_ROOT).  I generate the Makefile (using qmake) and it starts
>  > to build but then it fails:
>  >
>  > g++ -enable-stdcall-fixup -Wl,-enable-auto-import
>  > -Wl,-enable-runtime-pseudo-reloc -mthreads -Wl -shared
>  > -Wl,--out-implib,lib\libPythonQt.a -o lib\PythonQt.dll
>  > object_script.PythonQt.Debug  -L"c:\Qt\4.4.0-beta1\lib"
>  > "c:\Python25\libs"/python25.lib -lQtGuid4 -lQtCored4
>  > ./debug\PythonQt.o: In function `ZN8PythonQtC2Ei':
>  > C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to
>  > `_imp__Py_NoSiteFlag'
>  > ./debug\PythonQt.o: In function `ZN8PythonQtC1Ei':
>  > C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to
>  > `_imp__Py_NoSiteFlag'
>  > ./debug\PythonQt.o: In function 
> `ZN15PythonQtPrivate11wrapQObjectEP7QObject':
>  > C:/PythonQt-1.0/src/PythonQt.cpp:256: undefined reference to
>  > `_imp___Py_NoneStruct'
>  > C:/PythonQt-1.0/src/PythonQt.cpp:257: undefined reference to
>  > `_imp___Py_NoneStruct'
>  > ./debug\PythonQt.o: In function 
> `ZN15PythonQtPrivate7wrapPtrEPvRK10QByteArray':
>  > C:/PythonQt-1.0/src/PythonQt.cpp:281: undefined reference to
>  > `_imp___Py_NoneStruct'
>  > C:/PythonQt-1.0/src/PythonQt.cpp:282: undefined reference to
>  > `_imp___Py_NoneStruct'
>  > ./debug\PythonQt.o: In function
>  > `ZN8PythonQt13introspectionEP7_objectRK7QStringNS_10ObjectTypeE':
>  > C:/PythonQt-1.0/src/PythonQt.cpp:620: undefined reference to
>  > `_imp__PyClass_Type'
>  > C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to
>  > `_imp__PyClass_Type'
>  > C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to
>  > `_imp__PyCFunction_Type'
>  > ...
>  >
>  > Since I'm new to compiling Qt with mingw and completely new to python,
>  > I was hoping for tips on why I'm getting these errors.  If anyone has
>  > a better suggestion for a forum/mailing list then please let me know.
>
>
>
> A few of suggestions:
>
>   - take this to the PyQt mailing list
>  (http://www.riverbankcomputing.com/mailman/listinfo/pyqt)
>
>   - you only *need* pyqt if what you want to do in python has really to
>  deal with Qt-objects - maybe "simple" embedding is enough for your needs
>
>   - I don't see why you need to compile PyQt yourself at all - are you
>  sure you can't use the stock PyQt for windows? What makes you believe
>  you really need this to be self-compiled?
>
>  Diez
>
> --
>  http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't get items out of a set?

2008-03-09 Thread Raymond Hettinger
> > The intern() builtin uses this approach:
>
> >    interned = {}
> >    def intern(s):
> >         if s in interned:
> >             return interned[s]
> >         interned[s] = s
> >         return s
>
> If you've seen it before, and have the old one, return the old one.
> Do I have this straight?

Right.

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


Re: Need Help Building PythonQt on Windows

2008-03-09 Thread Diez B. Roggisch
Jeff Schiller schrieb:
> Hello,
> 
> I'm creating an application using Qt (4.4 Beta atm).  I have pretty
> close to zero experience with Python (consisting of installing the
> Python interpreter, downloading a python programming and executing it
> on the command-line).
> 
> I would like to invoke a Python script from my C++ Qt program and
> capture its output as a C++ structure.  It seems that PythonQt might
> be suitable for my needs.
> 
> Being a Qt program, I want this thing to be cross-platform.  I'm
> having trouble getting things set up in Windows.  Has anyone had any
> experience with this?
> 
> I've built Qt from source using the mingw32 compiler.  I installed
> Python 2.5 binary.  I am trying to build PythonQt from source.  As per
> http://pythonqt.sourceforge.net/#Building it says I need a "developer
> installation" of Python containing the header files and  the library
> files.  When I look at my system after installing the Python 2.5
> binary, I can see I have header files (C:\Python25\include), a 199k
> python25.lib (C:\Python25\libs) and a 2MB python25.dll
> (C:\Windows\System32\).  Have I got what I need?
> 
> I have tried to set up my symbols (PYTHON_PATH, PYTHON_LIB,
> PYTHONQT_ROOT).  I generate the Makefile (using qmake) and it starts
> to build but then it fails:
> 
> g++ -enable-stdcall-fixup -Wl,-enable-auto-import
> -Wl,-enable-runtime-pseudo-reloc -mthreads -Wl -shared
> -Wl,--out-implib,lib\libPythonQt.a -o lib\PythonQt.dll
> object_script.PythonQt.Debug  -L"c:\Qt\4.4.0-beta1\lib"
> "c:\Python25\libs"/python25.lib -lQtGuid4 -lQtCored4
> ./debug\PythonQt.o: In function `ZN8PythonQtC2Ei':
> C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to
> `_imp__Py_NoSiteFlag'
> ./debug\PythonQt.o: In function `ZN8PythonQtC1Ei':
> C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to
> `_imp__Py_NoSiteFlag'
> ./debug\PythonQt.o: In function `ZN15PythonQtPrivate11wrapQObjectEP7QObject':
> C:/PythonQt-1.0/src/PythonQt.cpp:256: undefined reference to
> `_imp___Py_NoneStruct'
> C:/PythonQt-1.0/src/PythonQt.cpp:257: undefined reference to
> `_imp___Py_NoneStruct'
> ./debug\PythonQt.o: In function 
> `ZN15PythonQtPrivate7wrapPtrEPvRK10QByteArray':
> C:/PythonQt-1.0/src/PythonQt.cpp:281: undefined reference to
> `_imp___Py_NoneStruct'
> C:/PythonQt-1.0/src/PythonQt.cpp:282: undefined reference to
> `_imp___Py_NoneStruct'
> ./debug\PythonQt.o: In function
> `ZN8PythonQt13introspectionEP7_objectRK7QStringNS_10ObjectTypeE':
> C:/PythonQt-1.0/src/PythonQt.cpp:620: undefined reference to
> `_imp__PyClass_Type'
> C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to
> `_imp__PyClass_Type'
> C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to
> `_imp__PyCFunction_Type'
> ...
> 
> Since I'm new to compiling Qt with mingw and completely new to python,
> I was hoping for tips on why I'm getting these errors.  If anyone has
> a better suggestion for a forum/mailing list then please let me know.


A few of suggestions:

  - take this to the PyQt mailing list 
(http://www.riverbankcomputing.com/mailman/listinfo/pyqt)

  - you only *need* pyqt if what you want to do in python has really to 
deal with Qt-objects - maybe "simple" embedding is enough for your needs

  - I don't see why you need to compile PyQt yourself at all - are you 
sure you can't use the stock PyQt for windows? What makes you believe 
you really need this to be self-compiled?

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


Re: Returning values from function to Python shell/IPython

2008-03-09 Thread Jorge Vargas
On Sun, Mar 9, 2008 at 11:07 AM, Karlo Lozovina <[EMAIL PROTECTED]> wrote:
> Jorge Vargas wrote:
>
>  > well after all it's a function so the only ways you can get things out
>  > of it are:
>  > - return a dict with all the objects
>  > - use global (very messy)
>  > - use a decorator to do either of the above.
>
>  Messy, all of those... :(.
>
>
>  > on the other hand have you consider using a proper test package?
>  > instead of inspecting the objects manually from the shell you could
>  > make it all automatic. with assert statements. you could use the std.
>  > python testing modules http://docs.python.org/lib/development.html or
>  > something less verbosed like nose
>
>  Usually, I'm using standard Python testing modules, but sometimes that is
>  just an overkill. Sometimes I like to do 'exploratory programming',
>  especially in the early phases of development - create a bunch of objects I
>  want to play with and do that from IPython. Only way I found out to
>  somewhat automate this procedure is to have a function that creates all of
>  the test objects, and then raises an exception at the end. IPython starts
>  ipdb, so I can work with the objects the function created (without copying
>  them back to the shell). But this somehow looks too hack-ish for me, so I
>  was wondering if there was an alternative...
>
ohhh if that is the case then what you are doing seems to be the
optimal. Just have module lvl code ran the testing in fact I don't
even put those into the if __name__, the reason is that this is just
temp testing that will later become real unit testing, and will never
hit a production app. it gives you the most flexibility.
>  Anyway, thanks for your answer ;).
>
welcome
>
>
>  --
>  Karlo Lozovina -- Mosor
>  --
>  http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Need Help Building PythonQt on Windows

2008-03-09 Thread Jeff Schiller
Hello,

I'm creating an application using Qt (4.4 Beta atm).  I have pretty
close to zero experience with Python (consisting of installing the
Python interpreter, downloading a python programming and executing it
on the command-line).

I would like to invoke a Python script from my C++ Qt program and
capture its output as a C++ structure.  It seems that PythonQt might
be suitable for my needs.

Being a Qt program, I want this thing to be cross-platform.  I'm
having trouble getting things set up in Windows.  Has anyone had any
experience with this?

I've built Qt from source using the mingw32 compiler.  I installed
Python 2.5 binary.  I am trying to build PythonQt from source.  As per
http://pythonqt.sourceforge.net/#Building it says I need a "developer
installation" of Python containing the header files and  the library
files.  When I look at my system after installing the Python 2.5
binary, I can see I have header files (C:\Python25\include), a 199k
python25.lib (C:\Python25\libs) and a 2MB python25.dll
(C:\Windows\System32\).  Have I got what I need?

I have tried to set up my symbols (PYTHON_PATH, PYTHON_LIB,
PYTHONQT_ROOT).  I generate the Makefile (using qmake) and it starts
to build but then it fails:

g++ -enable-stdcall-fixup -Wl,-enable-auto-import
-Wl,-enable-runtime-pseudo-reloc -mthreads -Wl -shared
-Wl,--out-implib,lib\libPythonQt.a -o lib\PythonQt.dll
object_script.PythonQt.Debug  -L"c:\Qt\4.4.0-beta1\lib"
"c:\Python25\libs"/python25.lib -lQtGuid4 -lQtCored4
./debug\PythonQt.o: In function `ZN8PythonQtC2Ei':
C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to
`_imp__Py_NoSiteFlag'
./debug\PythonQt.o: In function `ZN8PythonQtC1Ei':
C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to
`_imp__Py_NoSiteFlag'
./debug\PythonQt.o: In function `ZN15PythonQtPrivate11wrapQObjectEP7QObject':
C:/PythonQt-1.0/src/PythonQt.cpp:256: undefined reference to
`_imp___Py_NoneStruct'
C:/PythonQt-1.0/src/PythonQt.cpp:257: undefined reference to
`_imp___Py_NoneStruct'
./debug\PythonQt.o: In function `ZN15PythonQtPrivate7wrapPtrEPvRK10QByteArray':
C:/PythonQt-1.0/src/PythonQt.cpp:281: undefined reference to
`_imp___Py_NoneStruct'
C:/PythonQt-1.0/src/PythonQt.cpp:282: undefined reference to
`_imp___Py_NoneStruct'
./debug\PythonQt.o: In function
`ZN8PythonQt13introspectionEP7_objectRK7QStringNS_10ObjectTypeE':
C:/PythonQt-1.0/src/PythonQt.cpp:620: undefined reference to
`_imp__PyClass_Type'
C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to
`_imp__PyClass_Type'
C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to
`_imp__PyCFunction_Type'
...

Since I'm new to compiling Qt with mingw and completely new to python,
I was hoping for tips on why I'm getting these errors.  If anyone has
a better suggestion for a forum/mailing list then please let me know.

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


Re: Returning values from function to Python shell/IPython

2008-03-09 Thread Karlo Lozovina
Jorge Vargas wrote:

> well after all it's a function so the only ways you can get things out
> of it are:
> - return a dict with all the objects
> - use global (very messy)
> - use a decorator to do either of the above.

Messy, all of those... :(.

> on the other hand have you consider using a proper test package?
> instead of inspecting the objects manually from the shell you could
> make it all automatic. with assert statements. you could use the std.
> python testing modules http://docs.python.org/lib/development.html or
> something less verbosed like nose

Usually, I'm using standard Python testing modules, but sometimes that is
just an overkill. Sometimes I like to do 'exploratory programming',
especially in the early phases of development - create a bunch of objects I
want to play with and do that from IPython. Only way I found out to
somewhat automate this procedure is to have a function that creates all of
the test objects, and then raises an exception at the end. IPython starts
ipdb, so I can work with the objects the function created (without copying
them back to the shell). But this somehow looks too hack-ish for me, so I
was wondering if there was an alternative...

Anyway, thanks for your answer ;).

-- 
Karlo Lozovina -- Mosor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help on file storage for split multi part download

2008-03-09 Thread Gabriel Genellina
En Sat, 08 Mar 2008 08:27:12 -0200, <[EMAIL PROTECTED]> escribió:
> On Mar 7, 2:14 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
>> En Fri, 07 Mar 2008 04:16:42 -0200, <[EMAIL PROTECTED]> escribi�:
>>
>> > BUT the thing thats going in my mind is thread safety. i plan to start
>> > each part of the filedownloadin a different thread. and then when
>> > each thread had downloaded more than 100kb (or eof or boundary
>> > reached) write the buffer to the disk. can this be achieved using
>> > mutex ? i have never shared objects between threads.
>>
>> Use a different (single) thread to write the file; the others put write
>> requests on a Queue.queue object, and the writer just gets the requests
>> and processes them.
>>
>> > is there a way to write this without using threads at all ???
>>
>> Using asyncore, and perhaps the Twisted framework.
>
> asyncore is basically a server thing right?

asyncore is usually used to build servers, because in a server you want to  
handle many requests with few resources, but you can use it to write a  
client too.
Here is an example: http://effbot.org/zone/asyncore-ftp-client.htm

How many files and how many simultaneous connections do you plan to  
handle? Using multiple threads to download and a single thread to write,  
connected thru a queue, looks like the "simplest thing that probably  
works" to me unless you have other constraints.

-- 
Gabriel Genellina

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

pure python hyphenator

2008-03-09 Thread Wilbert Berendsen
Hi all, I'm just new to this list and I'm a musician and hobby programmer. I 
am busy with LilyKDE, a python plugin package for KDE's editor Kate, that 
makes using the LilyPond music typesetter from within Kate easier.

While already busy writing a python module for breaking lyrics text (using 
hyphenation dicts from e.g. OpenOffice.org) I found Dr.Leo's PyHyphen. But 
just for fun I also continued my own plain python module, which now has it's 
SVN repository at: http://python-hyphenator.googlecode.com/ and it's PyPI 
page at: http://pypi.python.org/pypi/hyphenator . It needs more testing but 
seems to work nice.

LilyKDE is located at http://lilykde.googlecode.com/

all the best.
Guido and community: thanks for such a nice programming language,
Wilbert Berendsen

-- 
http://www.wilbertberendsen.nl/
"You must be the change you wish to see in the world."
-- Mahatma Gandi
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Returning values from function to Python shell/IPython

2008-03-09 Thread Jorge Vargas
On Sun, Mar 9, 2008 at 9:56 AM, Karlo Lozovina <[EMAIL PROTECTED]> wrote:
> Hi all!
>
>  I have a runTest() function inside my module, which sets up and initializes
>  lots of objects and performs some basic tests on them. Usually (from
>  IPython) I just write `run my_module.py`, and then `runTest()`. But
>  sometimes I would like to manually twiddle with objects runTest creates. Is
>  there any way I can "return" all those objects local to runTest(), and have
>  them available in IPython (or ordinary Python shell)?

well after all it's a function so the only ways you can get things out
of it are:
- return a dict with all the objects
- use global (very messy)
- use a decorator to do either of the above.


on the other hand have you consider using a proper test package?
instead of inspecting the objects manually from the shell you could
make it all automatic. with assert statements. you could use the std.
python testing modules http://docs.python.org/lib/development.html or
something less verbosed like nose
http://code.google.com/p/python-nose/
>
>  Thanks...
>
>
>  P.S.
>  I know I can do it from a:
>
>  if __name__ == '__main__':
>   # lots of object initialization...
>
>  and then have all those objects available in the interpreter.
>
>  --
>  Karlo Lozovina -- Mosor
>  --
>  http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Returning values from function to Python shell/IPython

2008-03-09 Thread Karlo Lozovina
Hi all! 

I have a runTest() function inside my module, which sets up and initializes
lots of objects and performs some basic tests on them. Usually (from
IPython) I just write `run my_module.py`, and then `runTest()`. But
sometimes I would like to manually twiddle with objects runTest creates. Is
there any way I can "return" all those objects local to runTest(), and have
them available in IPython (or ordinary Python shell)?

Thanks...


P.S.
I know I can do it from a:

if __name__ == '__main__':
  # lots of object initialization...

and then have all those objects available in the interpreter.

-- 
Karlo Lozovina -- Mosor
-- 
http://mail.python.org/mailman/listinfo/python-list


Changing the size of a Button

2008-03-09 Thread K Viltersten
How do i change the size of a Button
(using Tkinter), other than to set it
during construction?

I've found methods for getting the 
size but not applying them.

I've been laborating with .setvar(*)
but i've been unsuccessful.

--
Regards
Konrad Viltersten

sleep- a substitute for coffee for the poor
ambition - lack of sense to be lazy

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


unable to install gdal

2008-03-09 Thread luis
Hi

On Windows xp sp2 and python 2.4

Yesterday I running old versions of gdal, and I try to upgrade

I download gdalwin32exe150.zip and gdal-python-13.win32-py2.4.exe
I unzip gdalwin32exe150.zip in C:\gdalwin32-1.5

I follow install's instructions from 
http://trac.osgeo.org/gdal/wiki/GdalOgrInPython,
all is ok, I set path and path_data variables with correct values, but
whe I run a script, an error raises

from osgeo import ogr
  File "C:\Python24\Lib\site-packages\osgeo\ogr.py", line 7, in ?
import _ogr
ImportError: DLL load failed: process not found



Also I try with instructions from
http://www.urbansim.org/opus/stable-releases/opus-2006-11-21/docs/gdalinstall.html
I move _gdal.pyd (and the others *.pyd) from my Python installation's
(C:\Python24\Lib\site-packages\osgeo) into my Python installation's
DLLs folder (C:\Python24\DLLs).
When I run the script the error message persists.

Some help is welcome.


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


Re: for-else

2008-03-09 Thread egbert
On Sat, Mar 08, 2008 at 04:15:31PM -0500, Terry Reedy wrote:
> 
> I am sorry if you cannot appreciate such elegance 
> and can only spit on it as 'orwellian'.
> 
I admire the elegance of your examples and your explanation.
I will keep a copy of it in my Beazley,
for I am afraid I have to read it again.
As for orwellian, I must admit 
that I was quite happy when I thought of using that word, 
but that it was not my luckiest thought.

But I have to persist in my malice.

In the following snippet it is not at all clear
to the naive programmer (me) that the else refers to an 
iterator_is_exhausted condition,
whatever logical explanation you may offer.

.  for each_item in item_list:
.do_something()
.  else:
.do_else()

My temporary solution will be to accompany this else
with an appropriate comment: # exhausted

e
-- 
Egbert Bouwman - Keizersgracht 197 II - 1016 DS  Amsterdam - 020 6257991

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


Re: Converting a string to the most probable type

2008-03-09 Thread Malcolm Greene
Pierre,

> That's fine for people who write floats with a "." ; but others learn to 
> enter them with ","

I have also been looking for a similar Python conversion library. One of
my requirements is that such a library must be locale aware (so it can
make reasonable assumptions regarding locale properties like thousands
separators, decimal points, etc) - either via a locale attribute or by
examining the locale of the thread its running under.

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


Re: What c.l.py's opinions about Soft Exception?

2008-03-09 Thread Kay Schluehr
On 9 Mrz., 13:50, Lie <[EMAIL PROTECTED]> wrote:
> On Mar 9, 4:31 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote:
>
>
>
> > On 9 Mrz., 09:30, Lie <[EMAIL PROTECTED]> wrote:
> > > On Mar 9, 12:05 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote:
>
> > > > On 9 Mrz., 04:51, Lie <[EMAIL PROTECTED]> wrote:
>
> > > > > A more through implementation would start from the raiser inspecting
> > > > > the execution stack and finding whether there are any try block above
> > > > > it, if no try block exist it pass silently and if one exist it will
> > > > > check whether it have a matching except clause. This also circumvents
> > > > > a problem that simple implementation have, as described below.
>
> > > > This will not be easy in particular in the presence of inheritance and
> > > > dynamism. There is no way to statically decide whether an exception
> > > > BException has the type AException and will be caught by the except
> > > > clause in
>
> > > > try:
> > > > BLOCK
> > > > except AException, e:
> > > > print "SoftException %s caught"%e
> > > > A feasible solution was to invert the try...except statement and
> > > > creating a continuation.
>
> > > > catch AException, a:
> > > >print "SoftException A: %s"%a
> > > > catch BException , b:
> > > >print "SoftException B: %s"%b
> > > > ...
> > > > in:
> > > >BLOCK
>
> > > > Here each SoftException is raised initially when a catch clause is
> > > > entered and a continuation is created that returns to the catch block
> > > > of the raised SoftException if required. When a SoftException is
> > > > raised within BLOCK a lookup will be made and if a corresponding
> > > > SoftException was found that was raised by a catch-clause the current
> > > > control flow will be suspended and the continuation is called.
>
> > > I'd rather want to avoid any syntax changes, as I wished that Soft
> > > Exception can be added to the language silently[1] so that new
> > > programmers doesn't _need_ to know about it (although knowing it could
> > > change the way they write codes to be more structured and simple).
>
> > I just tried to save your proposal from being unimplementable. Maybe
> > you can comment on it?
>
> Perhaps I'm not the appropriate person to talk about whether unchanged
> syntax is feasible for such implementation since I basically have no
> idea about how Python's internals works. It's only that I think if
> current syntax could be used, we could just use it (except if there is
> a strong reason why it shouldn't be done).

You are an appropriate person to consider the workflow in a dynamic
language, no matter how the language is implemented internally.

Just start with function calls

   maybe_raise(ZeroDivisionError)

The only requirement is that maybe_raise has to know when it shall
raise ZeroDivisionError. This depends on whether the exception is
caught. How do the program knows this in advance? There are no static
analysis techniques available.

When maybe_raise is entered the system must know that the exception is
handled in the future. You can't inspect the call stack for this
purpose because the call stack represents past events and
continuations ( and you can't rely on names ).

So you need something like this

   do_softexception(ZeroDivisionError)
   try:
  TRY_BLOCK
   except ZeroDivisionError:
  EXCEPT_BLOCK

But this looks odd and the solution isn't DRY. So better one macro-
transforms a new statement into this form.


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


Re: Checking if a variable is a dictionary

2008-03-09 Thread Steven D'Aprano
On Sun, 09 Mar 2008 06:58:15 -0700, Guillermo wrote:

> Okay, so I think I know where's the catch now -- you must rely on the
> fact that the protocol is implemented, there's no way to enforce it if
> you're expecting a parrot-like object. You'd try to call the speak()
> method and deal with the error if there's no such method?

That's right. That's called "duck typing" -- if all you want is something 
that quacks like a duck, then it doesn't matter if it actually is a duck 
or not.

Or if you prefer: if it quacks like a duck and swims like a duck, then 
it's close enough to a duck as to make no difference.


Sometimes though, you need to check for a parrot up front. So I'd so this:

try:
something.speak
except AttributeError:
# No speak() method, so it can't be a parrot.
do_something_else()
else:
# It seems to follow the parrot protocol.
yummy_goodness = something.speak(5)
assert "spam" in yummy_goodness.lower()


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


Re: Checking if a variable is a dictionary

2008-03-09 Thread Guillermo

Mamma mia! My head just exploded. I've seen the light.

So you only need to ·want· to have a protocol? That's amazing... Far
beyond the claim that Python is easy. You define protocols in writing
basically! Even my grandma could have her own Python protocol.

Okay, so I think I know where's the catch now -- you must rely on the
fact that the protocol is implemented, there's no way to enforce it if
you're expecting a parrot-like object. You'd try to call the speak()
method and deal with the error if there's no such method?

Thanks a lot!

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


Uninstalling Eggs

2008-03-09 Thread PB
I just installed the Shove module with the monumentally crap
setuptools. Whilst the install succeeded, imports now trigger errors,
so clearly it did not install correctly. Can I simply delete the .egg
file from my lib/python2.3/site-packages/ directory?

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


Re: What c.l.py's opinions about Soft Exception?

2008-03-09 Thread Diez B. Roggisch
Lie schrieb:
> I'm asking about people in c.l.py's opinion about a _probably_ very
> Pythonic way of doing something if such features is implemented. It is
> to be known that I'm not a Python expert and actually relatively new
> to Python programming, so probably I'm just not thinking pythonic
> enough yet or this feature might already exist somewhere in a
> different name.
> Anyway, I'm just asking for opinions, tell me problems I haven't
> foreseen, or whether such things would be hard to implement, or
> whether you think the idea is great or plain bad (and why).
> 
> Soft Exception
> What is "Soft Exception"?
> Soft Exception is an exception that if is unhandled, pass silently as
> if nothing happened. For example, if a variable turns into NoneType,
> it'll raise Soft Exception that it have become NoneException,
> programmers that wants to handle it can handle it with a try...except
> block while programmers that doesn't care about it (or know it won't
> be a problem to his code) can just leave the code as it is.
> 
> Soft Exception differs from Hard Exceptions (the regular Exception) in
> a way that Hard Exception must be handled at all cost or the program
> will be terminated while Soft Exception allow programmers not to
> handle it if they don't want to.



Is this soft-exception implemented anywhere, so that one can see what 
experiences and best practices have evolved around using it?

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


Re: identifying and parsing string in text file

2008-03-09 Thread [EMAIL PROTECTED]
On 8 mar, 20:49, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> I have a large file that has many lines like this,
>
>  name="DoseReferenceStructureType">SITE
>
> I would like to identify the line by the tag (300a,0014) and then grab
> the name (DoseReferenceStructureType) and value (SITE).

It's obviously an XML file, so use a XML parser - there are SAX and
DOM parsers in the stdlib, as well as the ElementTree module.

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


  1   2   >