Re: Directshow in Python

2008-09-18 Thread Thomas Heller
Sayanan Sivaraman schrieb:
> Hey all,
> 
> I'm trying to use DirectShow to display videos [I'm kind of new to
> Python, from more of a C++ background on windows].  I found some
> sample code online, but I am having trouble with calling the I
> 
> import ctypes
> from ctypes import *
> from comtypes import client
> from ctypes.wintypes import *
> import sys
> import time
> 
> 
> filename = sys.argv[1]
> 
> 
> qedit = client.GetModule('qedit.dll') # DexterLib
> quartz= client.GetModule("quartz.dll")
> 
> 
> CLSID_FilterGraph = '{e436ebb3-524f-11ce-9f53-0020af0ba770}'
> filter_graph =
> client.CreateObject(CLSID_FilterGraph,interface=qedit.IFilterGraph)
> filter_builder = filter_graph.QueryInterface(qedit.IGraphBuilder)
> filter_builder.RenderFile(filename, None)
> 
> media_control = filter_graph.QueryInterface(quartz.IMediaControl)
> media_control.Run()
> 
> try:
> # Look at IMediaEvent interface for EOS notification
> while True:
> time.sleep(1)
> except KeyboardInterrupt:
> pass
> 
> # Need these because finalisers don't have enough context to clean up
> after
> # themselves when script exits.
> del media_control
> del filter_builder
> del filter_graph
> 
> This code works fine.  What I would like to know, is how do I declare
> filename in the Python program to be of type LPCWSTR, so that I don't
> need to parse the command line in order to call the function
> "RenderFile()"?

If I understand your question correctly (I'm no sure):  comtypes converts
Python strings or unicode strings to the required LPCWSTR type itself.
So, you can call
  filter_builder.RenderFile("c:\\windows\\clock.avi", None)
or
  filter_builder.RenderFile(u"c:\\windows\\clock.avi", None)

If you pass a string, comtypes converts it to unicode using the "mbcs"
codec; this can be changed by setting ctypes.conversion_mode.

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


Re: CTypes on a 64 bit machine truncates pointers to 32 bits?

2008-09-18 Thread Ron Garret
In article <[EMAIL PROTECTED]>,
 "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:

>  foolib = cdll.LoadLibrary('foo.so')
>  foolib.foo(0xF)
> > 0
> 
> Shouldn't you tell ctypes that the argument and the result
> of foo is a pointer?

Yeah... that's it.  Default return type is int, which I assumed would be 
64 bits on a 64 bit machine, but turns out it's 32.  Stupid.

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

Re: CTypes on a 64 bit machine truncates pointers to 32 bits?

2008-09-18 Thread Martin v. Löwis
 foolib = cdll.LoadLibrary('foo.so')
 foolib.foo(0xF)
> 0

Shouldn't you tell ctypes that the argument and the result
of foo is a pointer?

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


Re: dict generator question

2008-09-18 Thread Paul Rubin
"Simon Mullis" <[EMAIL PROTECTED]> writes:
> l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]
> ...
> dict_of_counts = dict([(v[0:3], "count") for v in l])

Untested:

def major_version(version_string):
   "convert '1.2.3.2' to '1.2'"
   return '.'.join(version_string.split('.')[:2])

dict_of_counts = defaultdict(int)

for x in l:
   dict_of_counts[major_version(l)] += 1
--
http://mail.python.org/mailman/listinfo/python-list


Re: Program works great, except under less, cron or execl (Unicode?)

2008-09-18 Thread Sam
Diez for the win...  :)

sys.stdout.encoding does indeed have the proper value when called from
the command line of UTF-8.

But when piped into anything or called from anywhere it's None.

Just for completeness, here's my test program:
#!/usr/bin/env python
import sys
print sys.stdout.encoding

And here are the results:
$ ./encoding.py
UTF-8
$ ./encoding.py | cat
None

Really, really annoying!

So how can I set sys.stdout.encoding so it's UTF-8 when piped through
cat (or anything else).

I tried assigning to it, but no dice.

On Sep 18, 2:12 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Sam wrote:
> > I have a program which works great when run from the command line.
>
> > But when I run it combined with something else such as:
> > - piping it through less
> > - cron
> > - execl (i.e. calling it from another python program)
>
> > it gives me a unicode error
>
> >  File "../myparser.py", line 261, in set_attributes
> >     print "self.atd['Name'] is: ", self.atd['Name']
> > UnicodeEncodeError: 'ascii' codec can't encode character u'\xeb' in
> > position 7: ordinal not in range(128)
>
> > I'd post the whole program here, except it involves weird Unicode
> > strings.
>
> > I could probably change the program to get it working under less/cron/
> > etc.
>
> > But I'd rather understand exactly what the issue is.  Why does it work
> > fine when run directly from the command line, but not otherwise?
>
> Most probably because when to running directly inside a terminal, it gets
> it's stdin/stdout as pipes - and python can't attempt to guess the proper
> encoding on that, as it does on a terminal.
>
> And thus, when you print unicode to the pipe, it can't decide which encoding
> to use.
>
> To circumvene this, try & wrap stdout into a codecs-module wrapper with a
> proper encoding applied (e.g. utf-8).
>
> You might make that conditionally based on the sys.stdout.encoding-variable
> being set or not, albeit I'm not 100% sure to what it actually gets set
> when used in a subprocess. But this should give you the idea where to look.
>
> Diez

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


Re: Launching a subprocess without waiting around for the result?

2008-09-18 Thread John Fabiani
erikcw wrote:

> On Sep 18, 3:33 pm, Ben Finney <[EMAIL PROTECTED]>
> wrote:
>> erikcw <[EMAIL PROTECTED]> writes:
>> > I have a cgi script where users are uploading large files for
>> > processing. I want to launch a subprocess to process the file so the
>> > user doesn't have to wait for the page to load.
>>
>> For "how do I deal with subprocesses from Python", the (new in Python
>> 2.4) 'subprocess' module is the default go-to answer
>> http://www.python.org/doc/lib/module-subprocess>, replacing a
>> rather fragmented set of modules before it.
>>
>> > What is the correct way to launch subprocess without waiting for the
>> > result to return?
>>
>> Creating an instance of 'subprocess.Popen' will launch the process and
>> return the Popen instance. You then have the option of polling it or
>> waiting for it to complete.
>>
>> --
>> \     “To stay young requires unceasing cultivation of the ability to |
>> `\                   unlearn old falsehoods.” —Robert Anson Heinlein |
>> _o__)                                                                  |
>> Ben Finney
> 
> So if I create a Popen object and then just ignore the object and exit
> the program the subproccess will finish it's work and then exit itself
> cleanly?
Just so happens that I ran into the same problem recently.  I started with
exec(), then os.system(), next os.popen(), and last os.spawn().
This is what I discovered on a windows platform.  The exec() replaced the
current running process. os.system did not start a completely new process. 
os.popen() created a new process but did not open a command box to display
any print statements.  Lastly os.spawn() worked - it created a new process
and opened a command box to display any print statements I needed.

Johnf

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

Re: curses.setsyx()?

2008-09-18 Thread Tim Roberts
[EMAIL PROTECTED] wrote:
>
>I tried curses.setsyx(2,3) in my script and it doesn't move the curses
>cursor. Any alternatives/solutions?

Did you call doupdate after?  setsyx just manipulates the data structures.
It takes a call to doupdate to force those changes to take effect visually.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: improving a huge double-for cycle

2008-09-18 Thread Tino Wildenhain

Hi,

Terry Reedy wrote:
...
Yes, after figuring out what to do from the original post, I saw yours 
and then Pruebono's and decided that since two people had submitted the 
jackpot algorithm, I need not say more.  I will say this: this solution 
amounts to finding equivalence classes (the sets of items with a given 
'key') and then finding the classes (sets) with more than one member. 
Defaultdict is great for this.


I must say mine works with at least similar performance. Maybe its a
timezone issue but I also provided a simple test to my solution.

Also I never saw a list where the threading often goes wrong like
this here - is there any special setup or is it just peoples MUA
which screws up?

T.


smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list

Re: improving a huge double-for cycle

2008-09-18 Thread Terry Reedy

Steven D'Aprano wrote:

On Thu, 18 Sep 2008 20:43:00 +0200, Bruno Desthuilliers wrote:


Now the obvious winner is pruebono - even unoptimized, using sets seems
to be *way* faster than even the most optimized corrected version of
your algorithm.


I'm not being snarky about losing priority here, but I submitted 
essentially the same solution two hours earlier than pruebono.


Are people not seeing my posts? Have I been kill-filed by everyone except 
Mensator? I also asked a question about HTTPError and I haven't seen any 
responses at all.


Yes, after figuring out what to do from the original post, I saw yours 
and then Pruebono's and decided that since two people had submitted the 
jackpot algorithm, I need not say more.  I will say this: this solution 
amounts to finding equivalence classes (the sets of items with a given 
'key') and then finding the classes (sets) with more than one member. 
Defaultdict is great for this.


tjr

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


Re: Extracting hte font name from a TrueType font file

2008-09-18 Thread Aaron "Castironpi" Brady
On Sep 18, 7:48 pm, Steve Holden <[EMAIL PROTECTED]> wrote:
> Fredrik Lundh wrote:
> > Steve Holden wrote:
>
> >> Does anyone have a Python recipe for this?
>
>  from PIL import ImageFont
>  f = ImageFont.truetype("/windows/fonts/verdanai.ttf", 1)
>  f.font.family
> > 'Verdana'
>  f.font.style
> > 'Italic'
>
> Thanks so much, Fredrik. The reason I asked is because I found the
> specification completely opaque ...
>
> regards
>  Steve
> --
> Steve Holden        +1 571 484 6266   +1 800 494 3119
> Holden Web LLC              http://www.holdenweb.com/

Here's the code to parse the spec.

#customize path
f= open( '\\windows\\fonts\\arial.ttf', 'rb' )
from struct import *

#header
shead= Struct( '>I' )
fhead= f.read( shead.size )
dhead= shead.unpack_from( fhead, 0 )

#font directory
stable= Struct( '>4sIII' )
ftable= f.read( stable.size* dhead[ 1 ] )
for i in range( dhead[1] ): #directory records
dtable= stable.unpack_from(
ftable, i* stable.size )
if dtable[0]== 'name': break
assert dtable[0]== 'name'

#name table
f.seek( dtable[2] ) #at offset
fnametable= f.read( dtable[3] ) #length
snamehead= Struct( '>HHH' ) #name table head
dnamehead= snamehead.unpack_from( fnametable, 0 )

sname= Struct( '>HH' )
for i in range( dnamehead[1] ): #name table records
dname= sname.unpack_from(
fnametable, snamehead.size+ i* sname.size )
if dname[3]== 4: #key == 4: "full name of font"
s= unpack_from(
'%is'% dname[4], fnametable,
dnamehead[2]+ dname[5] )[0]
print dname, s

This outputs:

(0, 3, 0, 4, 10, 318)  A r i a l
(1, 0, 0, 4, 5, 4081) Arial
(3, 1, 1033, 4, 10, 318)  A r i a l

First 3 fields:

0, 3, 0= Unicode, Unicode 2.0, English
1, 0, 0= Macintosh, Default, English
3, 1, 1033= Windows, Version 1.1, Language "1033"
--
http://mail.python.org/mailman/listinfo/python-list


Re: Do HTTPError objects always have a read method?

2008-09-18 Thread Gabriel Genellina
En Thu, 18 Sep 2008 23:12:22 -0300, Gabriel Genellina  
<[EMAIL PROTECTED]> escribió:


En Wed, 17 Sep 2008 22:48:27 -0300, Steven D'Aprano  
<[EMAIL PROTECTED]> escribió:



Under what circumstances do HTTPError objects not have a valid file
object? How common is this? Does anyone have an example of a URL that
fails in that fashion?


Well, there is at least one case (AbstractDigestAuthHandler at line 864  
in urllib2.py) where HTTPError is raised explicitely with fp=None. It's  
not a common case, I think. If you rely on the exception having a read()  
method, add it a fake one yourself:


try: ...
except urllib2.HTTPError, e:
 if not hasattr(e, 'read'):
 e.read = e.readline = lambda self: '' # or perhaps e.msg
 conn = e


Oops, that should have been e.read = lambda: ''

--
Gabriel Genellina

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


Re: Deflate with urllib2...

2008-09-18 Thread Sam
For those that are interested, but don't want to bother running the
program themselves, here's the output I get.

Trying:  http://slashdot.org
  http://slashdot.org - Apache/1.3.41 (Unix) mod_perl/1.31-rc4
(deflate)
  Errored out on this site.

Trying:  http://www.hotmail.com
  http://www.hotmail.com - Microsoft-IIS/6.0 (deflate)
  Errored out on this site.

Trying:  http://www.godaddy.com
  http://www.godaddy.com - Microsoft-IIS/6.0 (deflate)
  Errored out on this site.

Trying:  http://www.linux.com
  http://www.linux.com - Apache/2.2.8 (Unix) PHP/5.2.5 (deflate)
  Errored out on this site.

Trying:  http://www.lighttpd.net
  http://www.lighttpd.net - lighttpd/1.5.0 (deflate)
  Errored out on this site.

Trying:  http://www.kenrockwel.com
  http://www.kenrockwel.com - lighttpd (deflate)
  Able to decompress...went from 414 to 744.



On Sep 18, 7:29 pm, Sam <[EMAIL PROTECTED]> wrote:
> On Sep 18, 2:10 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
> wrote:
>
> > En Tue, 16 Sep 2008 21:58:31 -0300, Sam <[EMAIL PROTECTED]> escribió:
> > The code is correct - try with another server. I tested it with a  
> > LightHTTPd server and worked fine.
>
> Gabriel...
>
> I found a bunch of servers to test it on.  It fails on every server I
> could find (sans one).
>
> Here's the ones it fails on:
> slashdot.org
> hotmail.com
> godaddy.com
> linux.com
> lighttpd.net
>
> I did manage to find one webserver it succeeded on---that is
> kenrockwel.com --- a domain squatter with a typoed domain of one of my
> favorite photographer's websites (the actual website should be
> kenrockwell.com)
>
> This squatter's site is indeed running lighttpd---but it appears to be
> an earlier version, because the official lighttpd site fails on this
> test.
>
> We have all the major web servers failing the test:
> * Apache 1.3
> * Apache 2.2
> * Microsoft-IIS/6.0
> * lighttpd/1.5.0
>
> So I think it's the python side that is wrong, regardless of what the
> standard is.
>
> What should I do next?
>
> I've rewritten the code to make it easier to test.  Just run it as is
> and it will try all my test cases; or pass in a site on the command
> line, and it will try just that.
>
> Thanks!
>
> #!/usr/bin/env python
> """Put the site you want to test as a command line parameter.
> Otherwise tests the list of defaults."""
>
> import urllib2
> import zlib
> import sys
>
> opener = urllib2.build_opener()
> opener.addheaders = [('Accept-encoding', 'deflate')]
>
> try:
>     sites = [sys.argv[1]]
> except IndexError:
>     sites = ['http://slashdot.org', 'http://www.hotmail.com',
>              'http://www.godaddy.com', 'http://www.linux.com',
>              'http://www.lighttpd.net', 'http://www.kenrockwel.com']
>
> for site in sites:
>     print "Trying: ", site
>     stream = opener.open(site)
>     data = stream.read()
>     encoded = stream.headers.get('Content-Encoding')
>     server = stream.headers.get('Server')
>
>     print "  %s - %s (%s)" % (site, server, encoded)
>
>     if encoded == 'deflate':
>         before = len(data)
>         try:
>             data = zlib.decompress(data)
>             after = len(data)
>             print "  Able to decompress...went from %i to %i." %
> (before, after)
>         except zlib.error:
>             print "  Errored out on this site."
>     else:
>         print "  Data is not deflated."
>     print

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


Re: Deflate with urllib2...

2008-09-18 Thread Sam
On Sep 18, 2:10 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Tue, 16 Sep 2008 21:58:31 -0300, Sam <[EMAIL PROTECTED]> escribió:
> The code is correct - try with another server. I tested it with a  
> LightHTTPd server and worked fine.

Gabriel...

I found a bunch of servers to test it on.  It fails on every server I
could find (sans one).

Here's the ones it fails on:
slashdot.org
hotmail.com
godaddy.com
linux.com
lighttpd.net

I did manage to find one webserver it succeeded on---that is
kenrockwel.com --- a domain squatter with a typoed domain of one of my
favorite photographer's websites (the actual website should be
kenrockwell.com)

This squatter's site is indeed running lighttpd---but it appears to be
an earlier version, because the official lighttpd site fails on this
test.

We have all the major web servers failing the test:
* Apache 1.3
* Apache 2.2
* Microsoft-IIS/6.0
* lighttpd/1.5.0

So I think it's the python side that is wrong, regardless of what the
standard is.

What should I do next?

I've rewritten the code to make it easier to test.  Just run it as is
and it will try all my test cases; or pass in a site on the command
line, and it will try just that.

Thanks!

#!/usr/bin/env python
"""Put the site you want to test as a command line parameter.
Otherwise tests the list of defaults."""

import urllib2
import zlib
import sys

opener = urllib2.build_opener()
opener.addheaders = [('Accept-encoding', 'deflate')]

try:
sites = [sys.argv[1]]
except IndexError:
sites = ['http://slashdot.org', 'http://www.hotmail.com',
 'http://www.godaddy.com', 'http://www.linux.com',
 'http://www.lighttpd.net', 'http://www.kenrockwel.com']

for site in sites:
print "Trying: ", site
stream = opener.open(site)
data = stream.read()
encoded = stream.headers.get('Content-Encoding')
server = stream.headers.get('Server')

print "  %s - %s (%s)" % (site, server, encoded)

if encoded == 'deflate':
before = len(data)
try:
data = zlib.decompress(data)
after = len(data)
print "  Able to decompress...went from %i to %i." %
(before, after)
except zlib.error:
print "  Errored out on this site."
else:
print "  Data is not deflated."
print
--
http://mail.python.org/mailman/listinfo/python-list


Re: Do HTTPError objects always have a read method?

2008-09-18 Thread Gabriel Genellina
En Wed, 17 Sep 2008 22:48:27 -0300, Steven D'Aprano  
<[EMAIL PROTECTED]> escribió:



I understood that HTTPError objects always have a read method, so they
can be treated as if they were a webpage. E.g. something like this
simplified snippet:


address = 'http://www.yahoo.com/spamspamspamspamspam'
try:
conn = urllib2.urlopen(address)
except urllib2.HTTPError, e:
conn = e
print conn.read()  # Print the requested page, or the error page.



But in the source code to urllib2 (Python 2.5):


class HTTPError(URLError, addinfourl):
"""Raised when HTTP error occurs, but also acts like non-error
return"""
__super_init = addinfourl.__init__

def __init__(self, url, code, msg, hdrs, fp):
self.code = code
self.msg = msg
self.hdrs = hdrs
self.fp = fp
self.filename = url
# The addinfourl classes depend on fp being a valid file
# object.  In some cases, the HTTPError may not have a valid
# file object.  If this happens, the simplest workaround is to
# not initialize the base classes.
if fp is not None:
self.__super_init(fp, hdrs, url)

That tells me that HTTPError objects aren't guaranteed to include a file-
like interface. That makes me unhappy.

Under what circumstances do HTTPError objects not have a valid file
object? How common is this? Does anyone have an example of a URL that
fails in that fashion?


Well, there is at least one case (AbstractDigestAuthHandler at line 864 in  
urllib2.py) where HTTPError is raised explicitely with fp=None. It's not a  
common case, I think. If you rely on the exception having a read() method,  
add it a fake one yourself:


try: ...
except urllib2.HTTPError, e:
if not hasattr(e, 'read'):
e.read = e.readline = lambda self: '' # or perhaps e.msg
conn = e

--
Gabriel Genellina

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


Re: improving a huge double-for cycle

2008-09-18 Thread bearophileHUGS
bearophile:
> doubles12 : 0.00184026840268

For fun, and to have an almost baseline reference, I have done a
little benchmark in D too:

import std.stdio: writefln;

// Using Tango std lib you don't need all this
version (Win32) {
import std.c.windows.windows;
double clock() {
long t;
QueryPerformanceCounter(&t);
return cast(double)t / queryPerformanceFrequency;
}

long queryPerformanceFrequency;
static this() {
QueryPerformanceFrequency(&queryPerformanceFrequency);
}
}

union N {
struct { int x, y; }
long xy;
}

auto IN = [
 N(4, 9), N(5, 0), N(6, 6), N(7, 2), N(3, 6), N(9, 6), N(0, 1), N(1,
6),
 N(0, 5), N(1, 2), N(8, 9), N(5, 4), N(1, 6), N(7, 6), N(9, 1), N(7,
6),
 N(0, 1), N(7, 4), N(7, 4), N(8, 4), N(8, 4), N(3, 5), N(9, 6), N(6,
1),
 N(3, 4), N(4, 5), N(0, 5), N(6, 3), N(2, 4), N(1, 6), N(9, 5), N(1,
2),
 N(5, 8), N(8, 5), N(3, 1), N(9, 4), N(9, 4), N(3, 3), N(4, 8), N(9,
7),
 N(8, 4), N(6, 2), N(1, 5), N(5, 8), N(8, 6), N(0, 8), N(5, 2), N(3,
4),
 N(0, 5), N(4, 4), N(2, 9), N(7, 7), N(1, 0), N(4, 2), N(5, 7), N(0,
4),
 N(2, 5), N(0, 8), N(7, 3), N(9, 1), N(0, 4), N(5, 0), N(4, 9), N(0,
6),
 N(3, 0), N(3, 0), N(3, 9), N(8, 3), N(7, 9), N(8, 5), N(7, 6), N(1,
5),
 N(0, 6), N(5, 9), N(6, 8), N(0, 0), N(4, 1), N(3, 3), N(5, 4), N(5,
3),
 N(6, 1), N(5, 4), N(4, 5), N(5, 8), N(4, 1), N(3, 6), N(1, 9), N(0,
5),
 N(6, 5), N(5, 5), N(6, 0), N(0, 9), N(2, 6), N(0, 7), N(5, 9), N(7,
3),
 N(7, 9), N(5, 4), N(4, 9), N(2, 9)
];

N[] doubles13() {
 size_t[N] dup; // used as set
 N[] SN;
 foreach (item; IN) {
 if (item in dup)
 SN ~= item;
 else
 dup[item] = 0;
 }
 return SN;
}

N[] doubles0() {
N[] SN;
for (int i; i < IN.length; i++)
for (int j; j < IN.length; j++)
if (i != j)
if (IN[i] == IN[j])
SN ~= IN[i];
return SN;
}

void test_results() {
size_t[N] set1, set2;
foreach (n; doubles0())
set1[n] = 0;
foreach (n; doubles13())
set2[n] = 0;
if (set1.keys.sort != set2.keys.sort)
throw new Error("ERROR");
}

void main() {
int n = 150_000;
test_results();

int count = n;
auto t0 = clock();
while (count--)
doubles13();
auto t1 = clock();

writefln("%0.10f", cast(double)(t1 - t0) / n);
}

doubles13() needs 0.27-0.37 seconds (*), about 60-75 times
faster than doubles12, this means about 3-4 seconds instead of 15h (on
the original computer).
Using C++ with GCC (using a  for dup and a  for SN)
you can probably go 10-40% faster still :-)

(*) Probably there's such variability of timings because the current
DMD compiler I have used doesn't add "align" instructions in the asm
it produces as GCC does. With modern CPUs very sensitive to code
alignment this leads to even 20-30% runtime differences in small tight
loops.

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


Re: Launching a subprocess without waiting around for the result?

2008-09-18 Thread Ben Finney
erikcw <[EMAIL PROTECTED]> writes:

> On Sep 18, 3:33 pm, Ben Finney <[EMAIL PROTECTED]>
> wrote:
> > erikcw <[EMAIL PROTECTED]> writes:
> > > What is the correct way to launch subprocess without waiting for
> > > the result to return?
> >
> > Creating an instance of 'subprocess.Popen' will launch the process
> > and return the Popen instance. You then have the option of polling
> > it or waiting for it to complete.
> 
> So if I create a Popen object and then just ignore the object and
> exit the program the subproccess will finish it's work and then exit
> itself cleanly?

Ah, no, that's a different thing. If the parent exits, the child will
also be killed I believe.

If you want to spawn a process and have it live on independent of the
parent, you want to make the child process a "daemon", detatching
itself from the parent's environment. I don't recall how that's done
immediately, but those are the terms to search for.

-- 
 \  “Pinky, are you pondering what I'm pondering?” “Yes Brain, but |
  `\if our knees bent the other way, how would we ride a bicycle?” |
_o__)   —_Pinky and The Brain_ |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

CTypes on a 64 bit machine truncates pointers to 32 bits?

2008-09-18 Thread Ron Garret
CTypes on a 64-bit machine appears to be truncating pointers to 32 bits:

[EMAIL PROTECTED]:~]$ uname -a
Linux monster1 2.6.18-6-amd64 #1 SMP Mon Jun 16 22:30:01 UTC 2008 x86_64 
GNU/Linux
[EMAIL PROTECTED]:~]$ cat foo.c
void* foo(void* x) { return x; }
[EMAIL PROTECTED]:~]$ gcc -fPIC -shared foo.c -o foo.so
[EMAIL PROTECTED]:~]$ file foo.so
foo.so: ELF 64-bit LSB shared object, AMD x86-64, version 1 (SYSV), not 
stripped
[EMAIL PROTECTED]:~]$ python
Python 2.5 (release25-maint, Jul 23 2008, 18:15:29) 
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import *
>>> foolib = cdll.LoadLibrary('foo.so')
>>> foolib.foo(0xF)
0
>>> sizeof(c_void_p)
8
>>> 

I am aware of http://bugs.python.org/issue1703286 but I get the same 
result in Python2.5.2:

[EMAIL PROTECTED]:~]$ py252/bin/python
Python 2.5.2 (r252:60911, Sep 18 2008, 10:48:29) 
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import *
>>> foolib = cdll.LoadLibrary('foo.so')
>>> foolib.foo(0xF)
0
>>> sizeof(c_void_p)
8
>>>
--
http://mail.python.org/mailman/listinfo/python-list


webbrowser fragment identifier

2008-09-18 Thread scottbvfx
Hi,

I'm trying to launch a web browser along with an html file with a
fragment identifier in its path. I'm using the webbrowser module for
this.
ie. webbrowser.open('file:///C:/myfile.html#SomeEntryInTheHTML')

for some reason it is truncating the path to 'file:///C:/myfile.html'.

Does anyone know a way of getting the fragment identifier in there
(with webbrowser module or any other)?

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


Re: Extracting hte font name from a TrueType font file

2008-09-18 Thread Steve Holden
Fredrik Lundh wrote:
> Steve Holden wrote:
> 
>> Does anyone have a Python recipe for this?
> 
 from PIL import ImageFont
 f = ImageFont.truetype("/windows/fonts/verdanai.ttf", 1)
 f.font.family
> 'Verdana'
 f.font.style
> 'Italic'
> 
Thanks so much, Fredrik. The reason I asked is because I found the
specification completely opaque ...

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: PEP proposal optparse

2008-09-18 Thread James Mills
On Thu, Sep 18, 2008 at 9:02 PM, James Nicolson <[EMAIL PROTECTED]> wrote:
> Perhaps it is better to keep descriptions short and store longer
> descriptions elsewhere, but there are many programs that have long
> descriptions, for example try: ls --help (at least on my machine a lot
> of these descriptions are quite long).

The longer (program) description is generally
provided by the Usage help string. This
(in my tools) is generally a long-ish docstring
describing the tool, and it's usage.

cheers
James

-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Re: Twisted vs Python Sockets

2008-09-18 Thread James Mills
On Fri, Sep 19, 2008 at 6:24 AM, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> James Matthews wrote:
>
>> I am wondering what are the major points of twisted over regular python
>> sockets. I am looking to write a TCP server and want to know the pros can
>> cons of using one over the other.
>
> Twisted is a communication framework with lots of ready-made components:
>
>   http://twistedmatrix.com/trac/wiki/TwistedAdvantage
>
> Regular sockets are, well, regular sockets.  No more, no less.

There is also one more alternative:

pymills - current version 3.4

It has a different design goal to twisted
and is in no competition with twisted,
however provides:
 * An event framework
 * A component driven architecture
 * A set of components including:
  * TCPServer, TCPClient
  * UDPServer, UDPClient
  * Some protocol components:
   * IRC
   * HTTP
   * SMTP
  * Some other components:
   * Environment
   * Logger
   * Stdin
   * Config

A simple EchoServer is as simple as:
http://hg.shortcircuit.net.au/index.wsgi/pymills/file/4247696a5633/examples/net/echoserer.py

If anyone is interested in trying this library
out, feel free. I recommend you use the
latest development branch available via
Mercurial at:
http://hg.shortcircuit.net.au/pymills/

hg clone http://hg.shortcircuit.net.au/pymills/

If you have any questions, don't hesitate
to ask me. Enjoy :)

cheers
James

-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python newbie question re Strings and integers

2008-09-18 Thread rmac

Ah!  Arghh!!! You are so correct on the usage of the ':'

Python syntax is a little different from what I am used to.

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


Re: improving a huge double-for cycle

2008-09-18 Thread Steven D'Aprano
On Thu, 18 Sep 2008 20:43:00 +0200, Bruno Desthuilliers wrote:

> Now the obvious winner is pruebono - even unoptimized, using sets seems
> to be *way* faster than even the most optimized corrected version of
> your algorithm.

I'm not being snarky about losing priority here, but I submitted 
essentially the same solution two hours earlier than pruebono.

Are people not seeing my posts? Have I been kill-filed by everyone except 
Mensator? I also asked a question about HTTPError and I haven't seen any 
responses at all.


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


Re: Python newbie question re Strings and integers

2008-09-18 Thread Miki
>     currentSymbol=filename[int(filenameStart),int(extensionStart)]
Should be
currentSymbol=filename[int(filenameStart):int(extensionStart)]
(change , to :)

You don't need to convert to int all the time, rfind will return an
integer.

Also you can use os.path for this

from os.path import basename, splitext
currentSymbol = splitext(basename(filename))[0]

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


Re: Python newbie question re Strings and integers

2008-09-18 Thread Christian Heimes

rmac wrote:


the following code attempts to extract a symbol name from a string:
extensionStart = int(filename.rfind('.'))
filenameStart = int(filename.rfind('/'))
#print 'Extension Start - ' + str(extensionStart)
#print 'FileName Start - ' + str(filenameStart)
currentSymbol=filename[int(filenameStart),int(extensionStart)]

Uncommenting the print statements clearly show the values to be
integers (and without the str casts actually provide int+string
errors)

However, executing this code results in...
opening - /Users/rmac/Documents/Sandbox/data/MarketData/AA.csv
Traceback (most recent call last):
  File "rHistFileToDB_Equities.py", line 25, in 
currentSymbol=filename[int(filenameStart),int(extensionStart)]
TypeError: string indices must be integers


You are using , inside filename[]. The splicing syntax is start:end, not 
start,end.


You are better off with using the appropriate APIs from the os.path module.

http://docs.python.org/lib/module-os.path.html

import os.path
filename = os.path.basename(path)
prefix, extension = os.path.splitext(filename)

Christian

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


Re: Launching a subprocess without waiting around for the result?

2008-09-18 Thread erikcw
On Sep 18, 3:33 pm, Ben Finney <[EMAIL PROTECTED]>
wrote:
> erikcw <[EMAIL PROTECTED]> writes:
> > I have a cgi script where users are uploading large files for
> > processing. I want to launch a subprocess to process the file so the
> > user doesn't have to wait for the page to load.
>
> For "how do I deal with subprocesses from Python", the (new in Python
> 2.4) 'subprocess' module is the default go-to answer
> http://www.python.org/doc/lib/module-subprocess>, replacing a
> rather fragmented set of modules before it.
>
> > What is the correct way to launch subprocess without waiting for the
> > result to return?
>
> Creating an instance of 'subprocess.Popen' will launch the process and
> return the Popen instance. You then have the option of polling it or
> waiting for it to complete.
>
> --
>  \     “To stay young requires unceasing cultivation of the ability to |
>   `\                   unlearn old falsehoods.” —Robert Anson Heinlein |
> _o__)                                                                  |
> Ben Finney

So if I create a Popen object and then just ignore the object and exit
the program the subproccess will finish it's work and then exit itself
cleanly?
--
http://mail.python.org/mailman/listinfo/python-list


Re: improving a huge double-for cycle

2008-09-18 Thread bearophileHUGS
Bruno Desthuilliers:
> def doubles9():
> ...
>  SN = []
>  sn_append = SN.append

Few more:

import psyco

def doubles10():
 dup = set()
 SN = []
 for item in IN:
 c = item.coordinates
 if c in dup:
 SN.append(item)
 else:
 dup.add(c)
 return SN

psyco.bind(doubles10)


from collections import deque

def doubles11():
 dup = set()
 dup_add = dup.add
 SN = deque()
 sn_append = SN.append

 for item in IN:
 c = item.coordinates
 if c in dup:
 sn_append(item)
 else:
 dup_add(c)
 return SN


def doubles12():
 dup = set()
 SN = deque()
 for item in IN:
 c = item.coordinates
 if c in dup:
 SN.append(item)
 else:
 dup.add(c)
 return SN

psyco.bind(doubles12)


Timings:

doubles00 : 0.522365288653
doubles01 : 0.247219812198
doubles02 : 0.237889823898
doubles03 : 0.238638921389
doubles04 : 0.23821698217
doubles05 : 0.177042495425
doubles06 : 0.13166199162
doubles08 : 0.00569725197252
doubles09 : 0.00418566685667
doubles10 : 0.00192086920869
doubles11 : 0.00403324533245
doubles12 : 0.00184026840268

Hopefully that's fast enough :-)

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


Python newbie question re Strings and integers

2008-09-18 Thread rmac


the following code attempts to extract a symbol name from a string:
extensionStart = int(filename.rfind('.'))
filenameStart = int(filename.rfind('/'))
#print 'Extension Start - ' + str(extensionStart)
#print 'FileName Start - ' + str(filenameStart)
currentSymbol=filename[int(filenameStart),int(extensionStart)]

Uncommenting the print statements clearly show the values to be
integers (and without the str casts actually provide int+string
errors)

However, executing this code results in...
opening - /Users/rmac/Documents/Sandbox/data/MarketData/AA.csv
Traceback (most recent call last):
  File "rHistFileToDB_Equities.py", line 25, in 
currentSymbol=filename[int(filenameStart),int(extensionStart)]
TypeError: string indices must be integers

Running Python 2.5.2_5 on OSX
--
http://mail.python.org/mailman/listinfo/python-list


curses.setsyx()?

2008-09-18 Thread linkmaster032000
I tried curses.setsyx(2,3) in my script and it doesn't move the curses
cursor. Any alternatives/solutions?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Automated Build System ?

2008-09-18 Thread Martin v. Löwis
> I'm working on a python Package which includes some extension modules
> and unit tests. I want to automate some tasks like "build extsion
> module, then copy xxx.pyd to folder yyy and run all unit tests from
> folder ".
> 
> I used google but found no hints to existing solutions.
> Can anybody help me ?

I recommend to use distutils. It can already build extension modules
and install them. For testing, you would need to supply your own test
command. Alternatively, try setuptools - there seems to be a test
command already included.

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


Re: Launching a subprocess without waiting around for the result?

2008-09-18 Thread Ben Finney
erikcw <[EMAIL PROTECTED]> writes:

> I have a cgi script where users are uploading large files for
> processing. I want to launch a subprocess to process the file so the
> user doesn't have to wait for the page to load.

For "how do I deal with subprocesses from Python", the (new in Python
2.4) 'subprocess' module is the default go-to answer
http://www.python.org/doc/lib/module-subprocess>, replacing a
rather fragmented set of modules before it.

> What is the correct way to launch subprocess without waiting for the
> result to return?

Creating an instance of 'subprocess.Popen' will launch the process and
return the Popen instance. You then have the option of polling it or
waiting for it to complete.

-- 
 \ “To stay young requires unceasing cultivation of the ability to |
  `\   unlearn old falsehoods.” —Robert Anson Heinlein |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Intercepting printed strings

2008-09-18 Thread Robert Dailey
Hi,

I'm currently using Python 3.0 b3 and I'm curious as to how I can go about
intercepting things send to print() for some intermediate processing before
they're actually sent to sys.stdout. Right now I've thought of the
following:

Replace sys.stdout with a class named PrintStream. PrintStream is defined as
follows:

class PrintStream:
def write( self, message ):
sys.__stdout__.write( '\t{0}'.format( message ) )

Will this work? Basically I want to add a tab character in front of every
message printed. Thanks.
--
http://mail.python.org/mailman/listinfo/python-list

Directshow in Python

2008-09-18 Thread Sayanan Sivaraman
Hey all,

I'm trying to use DirectShow to display videos [I'm kind of new to
Python, from more of a C++ background on windows].  I found some
sample code online, but I am having trouble with calling the I

import ctypes
from ctypes import *
from comtypes import client
from ctypes.wintypes import *
import sys
import time


filename = sys.argv[1]


qedit = client.GetModule('qedit.dll') # DexterLib
quartz= client.GetModule("quartz.dll")


CLSID_FilterGraph = '{e436ebb3-524f-11ce-9f53-0020af0ba770}'
filter_graph =
client.CreateObject(CLSID_FilterGraph,interface=qedit.IFilterGraph)
filter_builder = filter_graph.QueryInterface(qedit.IGraphBuilder)
filter_builder.RenderFile(filename, None)

media_control = filter_graph.QueryInterface(quartz.IMediaControl)
media_control.Run()

try:
# Look at IMediaEvent interface for EOS notification
while True:
time.sleep(1)
except KeyboardInterrupt:
pass

# Need these because finalisers don't have enough context to clean up
after
# themselves when script exits.
del media_control
del filter_builder
del filter_graph

This code works fine.  What I would like to know, is how do I declare
filename in the Python program to be of type LPCWSTR, so that I don't
need to parse the command line in order to call the function
"RenderFile()"?

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


Launching a subprocess without waiting around for the result?

2008-09-18 Thread erikcw
Hi,

I have a cgi script where users are uploading large files for
processing.  I want to launch a subprocess to process the file so the
user doesn't have to wait for the page to load.

What is the correct way to launch subprocess without waiting for the
result to return?

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


Re: Deflate with urllib2...

2008-09-18 Thread Gabriel Genellina

En Tue, 16 Sep 2008 21:58:31 -0300, Sam <[EMAIL PROTECTED]> escribió:


Gabriel, et al.

It's hard to find a web site that uses deflate these days.

Luckily, slashdot to the rescue.

I even wrote a test script.

If someone can tell me what's wrong that would be great.

Here's what I get when I run it:
Data is compressed using deflate.  Length is:   107160
Traceback (most recent call last):
  File "my_deflate_test.py", line 19, in 
data = zlib.decompress(data)
zlib.error: Error -3 while decompressing data: incorrect header check


And that's true. The slashdot server is sending bogus data:

py> s = socket.socket()
py> s.connect(('slashdot.org',80))
py> s.sendall("GET / HTTP/1.1\r\nHost: slashdot.org\r\nAccept-Encoding:  
deflate\

r\n\r\n")
py> s.recv(500)
'HTTP/1.1 200 OK\r\nDate: Thu, 18 Sep 2008 20:48:34 GMT\r\nServer:  
Apache/1.3.41
 (Unix) mod_perl/1.31-rc4\r\nSLASH_LOG_DATA: shtml\r\nX-Powered-By: Slash  
2.0050
01220\r\nX-Bender: Alright! Closure!\r\nCache-Control: private\r\nPragma:  
privat
e\r\nConnection: close\r\nContent-Type: text/html;  
charset=iso-8859-1\r\nVary: A
ccept-Encoding, User-Agent\r\nContent-Encoding:  
deflate\r\nTransfer-Encoding: ch
unked\r\n\r\n1c76\r\n\x02\x00\x00\x00\xff\xff\x00\xc1\x0f>\xf0HTML PUB
LIC "-//W3C//DTD HTML 4.01//EN"\n 
"http://www.w3.org/TR/html4/str...'


Note those 11 bytes starting with "\x02\x00\x00\xff..." followed by the  
page contents in plain text.
According to RFC 2616 (HTTP 1.1), the deflate content coding consists of  
the "zlib" format defined in RFC 1950 in combination with the "deflate"  
compression mechanism described in RFC 1951. RFC 1950 says that the lower  
4 bits of the first byte in a zlib stream represent the compression  
method; the only compression method defined is "deflate" with value 8. The  
slashdot data contains a 2 instead, so it is not valid.



#!/usr/bin/env python

import urllib2
import zlib

opener = urllib2.build_opener()
opener.addheaders = [('Accept-encoding', 'deflate')]

stream = opener.open('http://www.slashdot.org')
data = stream.read()
encoded = stream.headers.get('Content-Encoding')

if encoded == 'deflate':
print "Data is compressed using deflate.  Length is:  ",
str(len(data))
data = zlib.decompress(data)
print "After uncompressing, length is: ", str(len(data))
else:
print "Data is not deflated."


The code is correct - try with another server. I tested it with a  
LightHTTPd server and worked fine.


--
Gabriel Genellina

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


Re: improving a huge double-for cycle

2008-09-18 Thread Bruno Desthuilliers

Alexzive a écrit :

Hello there :) ,

I am a python newbie and need to run following code for a task in an
external simulation programm called "Abaqus" which makes use of python
to access the mesh (ensamble of nodes with xy coordinates) of a
certain geometrical model.

[IN is the starting input containing the nodes to be check, there are
some double nodes with the same x and y coordinates which need to be
removed. SN is the output containing such double nodes]

Code: Select all
for i in range(len(IN)): #scan all elements of the list IN
  for j in range(len(IN)):
if i <> j:
 if IN[i].coordinates[0] == IN[j].coordinates[0]:
   if IN[i].coordinates[1] == IN[j].coordinates[1]:
  SN.append(IN[i].label)



Unfortunately my len(IN) is about 100.000 and the running time about
15h  :(

Any idea to improve it?


A couple ones have been submitted. Harald gets a point about the 
redundant tests (even if his solution seems to be broken, cf below) - 
your inner loop should have looked like :


  for j in xrange(i+1, len(IN))

Now the obvious winner is pruebono - even unoptimized, using sets seems 
to be *way* faster than even the most optimized corrected version of 
your algorithm.


Here's a quick bench - please everyone doublecheck it to make sure it's ok:

from timeit import Timer
import random

class Node(object):
def __init__(self, x, y):
self.coordinates = (x, y)
def __repr__(self):
return repr(self.coordinates)


# how to build src:
# src = [(random.randrange(10),random.randrange(10)) for x in xrange(100)]
src = [
(4, 9), (5, 0), (6, 6), (7, 2), (3, 6), (9, 6), (0, 1), (1, 6),
(0, 5), (1, 2), (8, 9), (5, 4), (1, 6), (7, 6), (9, 1), (7, 6),
(0, 1), (7, 4), (7, 4), (8, 4), (8, 4), (3, 5), (9, 6), (6, 1),
(3, 4), (4, 5), (0, 5), (6, 3), (2, 4), (1, 6), (9, 5), (1, 2),
(5, 8), (8, 5), (3, 1), (9, 4), (9, 4), (3, 3), (4, 8), (9, 7),
(8, 4), (6, 2), (1, 5), (5, 8), (8, 6), (0, 8), (5, 2), (3, 4),
(0, 5), (4, 4), (2, 9), (7, 7), (1, 0), (4, 2), (5, 7), (0, 4),
(2, 5), (0, 8), (7, 3), (9, 1), (0, 4), (5, 0), (4, 9), (0, 6),
(3, 0), (3, 0), (3, 9), (8, 3), (7, 9), (8, 5), (7, 6), (1, 5),
(0, 6), (5, 9), (6, 8), (0, 0), (4, 1), (3, 3), (5, 4), (5, 3),
(6, 1), (5, 4), (4, 5), (5, 8), (4, 1), (3, 6), (1, 9), (0, 5),
(6, 5), (5, 5), (6, 0), (0, 9), (2, 6), (0, 7), (5, 9), (7, 3),
(7, 9), (5, 4), (4, 9), (2, 9)
]
IN = [Node(x, y) for x, y in src]


def doubles0():
SN = []
for i in range(len(IN)): #scan all elements of the list IN
for j in range(len(IN)):
#print i, j
if i <> j:
if IN[i].coordinates[0] == IN[j].coordinates[0]:
if IN[i].coordinates[1] == IN[j].coordinates[1]:
SN.append(IN[i])
return SN

def doubles1():
"first solve an algoritmic problem"
SN = []
for i in range(len(IN)):
for j in range(i+1, len(IN)):
#print i, j
#if i != j:
if IN[i].coordinates[0] == IN[j].coordinates[0]:
if IN[i].coordinates[1] == IN[j].coordinates[1]:
SN.append(IN[i])
return SN

def doubles2():
"then avoid buildin useless lists"
SN = []
for i in xrange(len(IN)):
for j in xrange(i+1, len(IN)):
if IN[i].coordinates[0] == IN[j].coordinates[0]:
if IN[i].coordinates[1] == IN[j].coordinates[1]:
SN.append(IN[i])
return SN


def doubles3():
"then avoid uselessly calling a constant operation"
SN = []
in_len = len(IN)
for i in xrange(in_len):
for j in xrange(i+1, in_len):
if IN[i].coordinates[0] == IN[j].coordinates[0]:
if IN[i].coordinates[1] == IN[j].coordinates[1]:
SN.append(IN[i])
return SN

def doubles4():
"then alias commonly used methods"
SN = []
sn_append = SN.append
in_len = len(IN)
for i in xrange(in_len):
for j in xrange(i+1, in_len):
if IN[i].coordinates[0] == IN[j].coordinates[0]:
if IN[i].coordinates[1] == IN[j].coordinates[1]:
sn_append(IN[i])
return SN

def doubles5():
"then alias a couple other things"
SN = []
sn_append = SN.append
in_len = len(IN)
for i in xrange(in_len):
node_i = IN[i]
coords_i = node_i.coordinates
for j in xrange(i+1, in_len):
if coords_i[0] == IN[j].coordinates[0]:
if coords_i[1] == IN[j].coordinates[1]:
sn_append(node_i)
return SN

def doubles6():
"then simplify tests"
SN = []
sn_append = SN.append
in_len = len(IN)
for i in xrange(in_len):
node_i = IN[i]
coords_i = node_i.coordinates
for j in xrange(i+1, in_len):
if coords_i == IN[j].coordinates:
sn_append(node_i)
return SN

# Harald : uncomment this a

Re: Extracting hte font name from a TrueType font file

2008-09-18 Thread Fredrik Lundh

Steve Holden wrote:


Does anyone have a Python recipe for this?


>>> from PIL import ImageFont
>>> f = ImageFont.truetype("/windows/fonts/verdanai.ttf", 1)
>>> f.font.family
'Verdana'
>>> f.font.style
'Italic'



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


Re: creating an (inefficent) alternating regular expression from a list of options

2008-09-18 Thread metaperl.com
On Sep 9, 12:42 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:

>
> you may also want to do re.escape on all the words, to avoid surprises
> when the choices contain special characters.

yes, thank you very much:

import re

def oneOf(s):
alts = sorted(s.split(), reverse=True)
alts = [re.escape(s) for s in alts]
return "|".join(alts)

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


Re: Twisted vs Python Sockets

2008-09-18 Thread Fredrik Lundh

James Matthews wrote:

I am wondering what are the major points of twisted over regular python 
sockets. I am looking to write a TCP server and want to know the pros 
can cons of using one over the other.


Twisted is a communication framework with lots of ready-made components:

   http://twistedmatrix.com/trac/wiki/TwistedAdvantage

Regular sockets are, well, regular sockets.  No more, no less.



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


Re: improving a huge double-for cycle

2008-09-18 Thread Bruno Desthuilliers

Harald Luessen a écrit :
(snip)

I did not test the syntax,
but here is an idea with sorted lists.
It should be O(NlogN).

def sk(x):
return x.coordinates[0]

IN.sort(key=sk)
for i in xrange(len(IN)):
for j in xrange(i+1, len(IN)):
if IN[i].coordinates[0] == IN[j].coordinates[0]:
if IN[i].coordinates[1] == IN[j].coordinates[1]:
SN.append(IN[i].label)
else:
break


The syntax is ok. Not the results, or so it seems (cf my other post in 
this thread). But you still get a good point for noticing the redundant 
tests in the inner loop !-)



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


Re: improving a huge double-for cycle

2008-09-18 Thread Paul Hankin
On Sep 18, 2:25 pm, Alexzive <[EMAIL PROTECTED]> wrote:
> Hello there :) ,
>
> I am a python newbie and need to run following code for a task in an
> external simulation programm called "Abaqus" which makes use of python
> to access the mesh (ensamble of nodes with xy coordinates) of a
> certain geometrical model.
>
> [IN is the starting input containing the nodes to be check, there are
> some double nodes with the same x and y coordinates which need to be
> removed. SN is the output containing such double nodes]
>
> Code: Select all
>     for i in range(len(IN)): #scan all elements of the list IN
>       for j in range(len(IN)):
>         if i <> j:
>          if IN[i].coordinates[0] == IN[j].coordinates[0]:
>            if IN[i].coordinates[1] == IN[j].coordinates[1]:
>               SN.append(IN[i].label)

Using only a little extra storage to compute IN (but O(N log N)
time complexity):

import itertools

IN.sort()
SN = [k for k, v in itertools.groupby(IN) if len(list(v)) > 1]

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


Twisted vs Python Sockets

2008-09-18 Thread James Matthews
Hi

I am wondering what are the major points of twisted over regular python
sockets. I am looking to write a TCP server and want to know the pros can
cons of using one over the other.


Thanks
James

-- 
http://www.goldwatches.com/
--
http://mail.python.org/mailman/listinfo/python-list

Re: creating an (inefficent) alternating regular expression from a list of options

2008-09-18 Thread metaperl.com
On Sep 9, 9:23 am, [EMAIL PROTECTED] wrote:
>     >> I really dont care if theexpressionis optimal. So the goal is
>     >> something like:
>
>     >> vowel_regexp = oneOf("a aa i ii u uu".split())  # yielding r'(aa|a|uu|
>     >> u|ii|i)'
>
>     >> Is there a public module available for this purpose?
>
> Check Ka-Ping Yee's rxb module:
>
>    http://lfw.org/python/

Ok 
suffers from the possibility of putting shorter match before longer
one:

def either(*alternatives):
options = []
for option in alternatives:
options.append(makepat(option).regex)
return Pattern('\(' + string.join(options, '|') + '\)')


> Also, check PyPI to see if
> someone has already updated rxb for use with re.

No one has - http://pypi.python.org/pypi?%3Aaction=search&term=rxb&submit=search

no results returned



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


Re: improving a huge double-for cycle

2008-09-18 Thread Paul Hankin
On Sep 18, 2:25 pm, Alexzive <[EMAIL PROTECTED]> wrote:
> Hello there :) ,
>
> I am a python newbie and need to run following code for a task in an
> external simulation programm called "Abaqus" which makes use of python
> to access the mesh (ensamble of nodes with xy coordinates) of a
> certain geometrical model.
>
> [IN is the starting input containing the nodes to be check, there are
> some double nodes with the same x and y coordinates which need to be
> removed. SN is the output containing such double nodes]
>
> Code: Select all
>     for i in range(len(IN)): #scan all elements of the list IN
>       for j in range(len(IN)):
>         if i <> j:
>          if IN[i].coordinates[0] == IN[j].coordinates[0]:
>            if IN[i].coordinates[1] == IN[j].coordinates[1]:
>               SN.append(IN[i].label)
>
> Unfortunately my len(IN) is about 100.000 and the running time about
> 15h  :(
>
> Any idea to improve it?
>
> I have already tried to group the "if statements" in a single one:
>
> Code: Select all
>     if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and
> if IN[i].coordinates[1] == IN[j].coordinates[1]:

A simple O(N) algorithm:

from collections import defaultdict

d = defaultdict(int)
for x in IN:
d[x] += 1

SN = [x for (x, c) in d.iteritems() if c > 1]

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


Re: Python and Open Office

2008-09-18 Thread David Boddie
On Wednesday 17 September 2008 21:59, Terry Reedy wrote:
> Hartmut Goebel wrote:
>> Terry Reedy schrieb:
>> 
>> The API docs are a bit hidden on the webpage. Here is the link:
>> 
> 
> I wrote my comment *after* looking at the above, which I found easily
> enough.  After 7 pages of (helpful) explanatory text, there follow 88
> pages with hundreds of entries like this:

[...]

> which are translated to a more readable form from the Relax-NG schema
> (formal specs) in the standard.  But I have no idea what a Ruby property
> is in this context.  It would be much like reading the grammar entries
> in the Python Reference without the explanatory text that follows.

I started using odfpy for a project, and I found that I spent a lot of time
flicking back and forth in the API manual and cross-referencing it with the 
specification. The simple examples were useful enough to get started with,
but I could have used more information about how to use certain classes
and what elements and attributes they required.

I also wanted to add equations to the documents I was producing and that
requires some knowledge of MathML.

Certainly, it's not a very high level API for documentation creation - you
need to know something about the format to be able to construct documents.

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


Re: SMTP via GMAIL

2008-09-18 Thread Chris Babcock

> >> Traceback (most recent call last):
> >>   File "mail5.py", line 21, in 
> >> session = smtplib.SMTP(SMTPserver,port)
> >>   File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__
> >> (code, msg) = self.connect(host, port)
> >>   File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect
> >> self.sock.connect(sa)
> >>   File "", line 1, in connect
> >> then conncetion time out.
> >
> > Could it be your ISP is blocking outgoing connections to port
> > 25?
> 
> gmail doesn't accept mail via SMTP on port 25.
 
So what is the value of "port" when you are running this program?

Chris


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


Re: Blanket font setting?

2008-09-18 Thread giltay
On Sep 18, 12:55 pm, RGK <[EMAIL PROTECTED]> wrote:
> Is there any sort of blanket font setting, perhaps like:
>
>    wx.SystemSettings_SetFont(font)   #this doesn't exist
>
> that could set everything with one fell swoop?
>
> Thanks for your attention...
>
> Ross.

I do this by setting the font in each frame (or dialog); the font
propogates to its descendants.

http://lists.wxwidgets.org/pipermail/wxpython-users/2008-September/080099.html

Geoff G-T
--
http://mail.python.org/mailman/listinfo/python-list


Python, Factset, and Excel - Oh my!

2008-09-18 Thread Desmond Scott E
I'm still a Python novice.
I'm still attempting to migrate a Python-based process from
Windows2000/Python v2.4.2 (#67)/Excel2000 to WindowsXP/Python v2.5.2
(r252:60911)/Excel2003.
I now have a new "opportunity"!
I need some help with the step in the Python script that calls Excel and
invokes the Factset API to download data into a spreadsheet.  I'm
thinking that this is a Python / Factset API setup issue.  Is the
Factset API installed as a component of Python?  Or does the Factset API
exist in Windows and available to any application, like Python? 
Any insights would be greatly appreciated!

Scott E. Desmond
Director & Manager Equity Systems Development
IT Integration Lead
Mellon Capital Management Corporation
500  Grant Street, Suite 4200
Pittsburgh, PA  15258
T 412.236.0405 | F 412.236.1703
[EMAIL PROTECTED] | www.mcm.com
 
The information contained in this e-mail may be confidential and is intended 
solely for the use of the named addressee.
Access, copying or re-use of the e-mail or any information contained therein by 
any other person is not authorized.
If you are not the intended recipient please notify us immediately by returning 
the e-mail to the originator.(16b)
 
Disclaimer Version MB.US.1
--
http://mail.python.org/mailman/listinfo/python-list

Re: dict generator question

2008-09-18 Thread Gerard flanagan

George Sakkis wrote:

On Sep 18, 11:43 am, Gerard flanagan <[EMAIL PROTECTED]> wrote:

Simon Mullis wrote:

Hi,
Let's say I have an arbitrary list of minor software versions of an
imaginary software product:
l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]
I'd like to create a dict with major_version : count.
(So, in this case:
dict_of_counts = { "1.1" : "1",
   "1.2" : "2",
   "1.3" : "2" }

[...]
data = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]

from itertools import groupby

datadict = \
   dict((k, len(list(g))) for k,g in groupby(data, lambda s: s[:3]))
print datadict


Note that this works correctly only if the versions are already sorted
by major version.



Yes, I should have mentioned it. Here's a fuller example below. There's 
maybe better ways of sorting version numbers, but this is what I do.



data = [ "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.1.1.1", "1.3.14.5", 
"1.3.21.6" ]


from itertools import groupby
import re

RXBUILDSORT = re.compile(r'\d+|[a-zA-Z]')

def versionsort(s):
key = []
for part in RXBUILDSORT.findall(s.lower()):
try:
key.append(int(part))
except ValueError:
key.append(ord(part))
return tuple(key)

data.sort(key=versionsort)
print data

datadict = \
dict((k, len(list(g))) for k,g in groupby(data, lambda s: s[:3]))
print datadict




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


Re: minimum install & pickling

2008-09-18 Thread Aaron "Castironpi" Brady
On Sep 18, 5:20 am, Paul Boddie <[EMAIL PROTECTED]> wrote:
> On 17 Sep, 22:18, "Aaron \"Castironpi\" Brady" <[EMAIL PROTECTED]>
> wrote:
>
> > On Sep 17, 4:43 am, Paul Boddie <[EMAIL PROTECTED]> wrote:
>
> > >http://wiki.python.org/moin/How_can_I_run_an_untrusted_Python_script_...)
>
> > These solutions have at least the same bugs that the bare bones
> > solution in the corresponding framework has.  Malicious code has fewer
> > options, but constructive code does too.  If you're running foreign
> > code, what do you want it to do?  What does it want to do?  The more
> > options it needs, the more code you have to trust.
>
> As I noted, instead of just forbidding access to external resources,
> what you'd want to do is to control access instead. This idea is not
> exactly new: although Brett Cannon was working on a sandbox capability
> for CPython, the underlying concepts involving different privilege
> domains have been around since Safe-Tcl, if not longer. The advantage
> of using various operating system features, potentially together with
> tools like fakechroot or, I believe, Plash, is that they should work
> for non-Python programs. Certainly, the chances of successfully
> introducing people to such capabilities are increased if you don't
> have to persuade the CPython core developers to incorporate your
> changes into their code.
>
> > The only way a Python script can return a value is with sys.exit, and
> > only an integer at that.  It is going to have output; maybe there's a
> > way to place a maximum limit on its consumption.  It's going to have
> > input, so that the output is relative to something.  You just make
> > copies to prevent it from destroying data.  Maybe command-line
> > parameters are enough.  IIRC if I recall correctly, Win32 has a way to
> > examine how much time a process has owned so far, and a way to
> > terminate it, which could be in Python's future.
>
> There is support for imposing limits on processes in the Python
> standard library:
>
> http://docs.python.org/lib/node521.html
>
> My experimental package, jailtools, relies on each process's sandbox
> being set up explicitly before the process is run, so you'd definitely
> want to copy data into the sandbox. Setting limits on the amount of
> data produced would probably require support from the operating
> system. Generally, when looking into these kinds of systems, most of
> the solutions ultimately come from the operating system: process
> control, resource utilisation, access control, and so on. (This is the
> amusing thing about Java: that Sun attempted to reproduce lots of
> things that a decent operating system would provide *and* insist on
> their use when deploying Java code in a controlled server environment,
> despite actually having a decent operating system to offer already.)
>
> > PyPy sandbox says:  "The C code generated by PyPy is not
> > segfaultable."  I find that to be a bold claim (whether it's true or
> > not).
>
> > I'm imagining in the general case, you want the foreign code to make
> > changes to objects in your particular context, such as exec x in
> > vars.  In that case, x can still be productive without any libraries,
> > just less productive.
>
> Defining an interface between trusted and untrusted code can be
> awkward. When I looked into this kind of thing for my undergraduate
> project, I ended up using something similar to CORBA, and my
> conclusion was that trusted code would need to expose an interface
> that untrusted "agents" would rely on to request operations outside
> the sandbox. That seems restrictive, but as the situation with rexec
> has shown, if you expose a broad interface to untrusted programs, it
> becomes increasingly difficult to verify whether or not the solution
> is actually secure.
>
> Paul

I think you could autogenerate a file with a copy of the data, then
run a bare bones Python installation with the foreign code that
imports the copy, or just concatenate the foreign code and copy.  At
least for input.  For output, you'd need a file that had an upper
bound on its size.

The problem with Python is that if an agent has access to a part of an
object, it has the whole thing.  Such as the trusted agents-- if they
can perform an operation, then anything with access to the agent can.
If they're just policy makers, then however an authorized agent
performs the action, is available to an unauthorized one.  You'd still
need a 'struct' instance to write your output, since memory is upper-
bounded, and you can't permit foreign code to store any form of Python
objects.
--
http://mail.python.org/mailman/listinfo/python-list


Re: improving a huge double-for cycle

2008-09-18 Thread Harald Luessen
On Thu, 18 Sep 2008 Alexzive wrote:

>I am a python newbie and need to run following code for a task in an
>external simulation programm called "Abaqus" which makes use of python
>to access the mesh (ensamble of nodes with xy coordinates) of a
>certain geometrical model.
>
>[IN is the starting input containing the nodes to be check, there are
>some double nodes with the same x and y coordinates which need to be
>removed. SN is the output containing such double nodes]
>
>Code: Select all
>for i in range(len(IN)): #scan all elements of the list IN
>  for j in range(len(IN)):
>if i <> j:
> if IN[i].coordinates[0] == IN[j].coordinates[0]:
>   if IN[i].coordinates[1] == IN[j].coordinates[1]:
>  SN.append(IN[i].label)

I did not test the syntax, but here is an idea with sorted lists.
It should be O(NlogN).

def sk(x):
return x.coordinates[0]

IN.sort(key=sk)
for i in xrange(len(IN)):
for j in xrange(i+1, len(IN)):
if IN[i].coordinates[0] == IN[j].coordinates[0]:
if IN[i].coordinates[1] == IN[j].coordinates[1]:
SN.append(IN[i].label)
else:
break

Harald

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


Re: Cython dynamic library problem

2008-09-18 Thread Tommy Grav


On Sep 18, 2008, at 12:35 PM, Rob Wolfe wrote:



I would try to use `distutils` because this package is much wiser
than me and knows all necessary switches for gcc. ;)


That worked! Thanks

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


PyCon 2009 (US) - Call for Tutorials

2008-09-18 Thread Greg Lindstrom
*Pycon 2009 (US) – Call for Tutorials*

The period for submitting tutorial proposals for Pycon 2009 (US) is now open
and will continue through Friday, October 31th. This year features two
"pre-conference" days devoted to tutorials on Wednesday March 25 & Thursday
March 26 in Chicago. This allows for more classes than ever.

Tutorials are 3-hours long on a specific topic of your choice. Last year we
featured classes on Learning Python, Web Development, Scientific Computing,
and many more. Class size varied from 10 to over 60 students. The extended
time spent in class allows teachers to cover a lot of material while
allowing for interaction with students.

The full Call for Tutorial Proposals, including submission details, an
example proposal as well as a template, is available at <
http://us.pycon.org/2009/tutorials/proposals/>.


Tutorial selections will be announced in early December to give you time to
prepare your class.

PyCon will compensate instructors US$1,500 per tutorial.

If you have any questions, please contact [EMAIL PROTECTED]


Greg Lindstrom
Tutorial Coordinator, PyCon 2009
--
http://mail.python.org/mailman/listinfo/python-list

RE: Extracting hte font name from a TrueType font file

2008-09-18 Thread Andreas Tawn
> -Original Message-
> From: [EMAIL PROTECTED] 
> [mailto:[EMAIL PROTECTED]
g] On Behalf Of Steve Holden
> Sent: Thursday, September 18, 2008 5:59 PM
> To: python-list@python.org
> Subject: Extracting hte font name from a TrueType font file
> 
> Does anyone have a Python recipe for this?
> 
> regards
>  Steve
> -- 
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC  http://www.holdenweb.com/
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

Can't help with a recipe, but here's the formal spec if want to figure
it out yourself.

http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6.html

Hope that helps.

Cheers,

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


Re: PEP proposal optparse

2008-09-18 Thread Grant Edwards
On 2008-09-18, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Thu, 18 Sep 2008 11:07:45 -0500, Grant Edwards wrote:
>
>> While we're making suggestions, I've always wished that the --help
>> output displayed the default values for options in addition to the help
>> text specified by the user.  I end up having to enter the default values
>> twice -- once as a keyword argument and again in the help text.
>
> '%default' in the help text will be replaced by the default value.  See 
> the last option in the first example here:
>
> http://docs.python.org/lib/optparse-generating-help.html

Great!  I guess I should scan the doc pages for changes more
often.

-- 
Grant Edwards   grante Yow! The Korean War must
  at   have been fun.
   visi.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Zsi interoperability

2008-09-18 Thread Marco Bizzarri
On Thu, Sep 18, 2008 at 7:10 PM, Dieter Maurer <[EMAIL PROTECTED]> wrote:
> "Marco Bizzarri" <[EMAIL PROTECTED]> writes on Mon, 15 Sep 2008 20:26:27 
> +0200:
>> On Mon, Sep 15, 2008 at 8:15 PM, Stefan Behnel <[EMAIL PROTECTED]> wrote:
>> > Mailing List SVR wrote:
>> >> I have to implement a soap web services from wsdl, the server is
>> >> developed using oracle, is zsi or some other python library for soap
>> >> interoperable with oracle soa?
>> >
>> > No idea, but I'd definitely try soaplib before ZSI.
>> >
>> > Stefan
>>
>> I'm working on a project where I need to write a client for SOAP with
>> Attachments; I can see ZSI does not support it
>
> The ZSI documentation (2.0) says that SOAP attachments are supported --
> but I never tried it.
>
>
> Dieter
> --
> http://mail.python.org/mailman/listinfo/python-list
>

That's right; but if you look at the code, it seems like it is able to
create a server which behaves in that way, but not to create a client
for it. But I'm still exploring...



-- 
Marco Bizzarri
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to Determine Name of the Day in the Week

2008-09-18 Thread Mensanator
On Sep 18, 12:01 am, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
> On Wed, 17 Sep 2008 20:34:02 -0700, Mensanator wrote:
> > And technically, weeks begin on Sunday, not Monday, but business likes
> > to think of Monday as day 0 of the week and it doesn't conflict with any
> > prior date format.
>
> There's no "technically" about it.

Sure there is, within the tradition I was refering to.
Within that tradition, the start of the week isn't arbitray.

Besides, the documentation specifically says it's using
the European system


By default, these calendars have Monday as the first day
of the week, and Sunday as the last (the European convention).
Use setfirstweekday() to set the first day of the week to
Sunday (6) or to any other weekday.


So, by default, Python doesn't use the American convention
of weeks starting on Sunday (an American technicality).
This does not contradict what I said.

> It's an arbitrary starting point,

Amongst different systems, it's never arbitrary within a system.

> and
> consequently there are different traditions to it, even in English.

I know, that's why I added the caveat.

>
> Besides, I don't think many businesses think of "day 0" at all. Most
> people outside of IT start counting from 1, not 0.

The accounting software I use to fill out my timesheet
electronically was obviously created by IT people and
the week begins on Monday. Their will is, of course,
forced on all employees whether they are IT or not.

>
> In British Commonwealth countries, Sunday is the last day of the week,
> not the first, although under American influence that's changing in
> Australia at least.
>
> In Poland, the week begins with Monday ("poniedziałek"). Tuesday,
> "wtorek", means "second day". Other Slavic countries also start with
> Monday.
>
> Similarly, the Lithuanian calendar simple enumerates the days of the
> week, starting with Monday, "pirmadienis" ("first day").
>
> In China, there are at least three different systems of naming the week
> days. In two of them, the week starts with Sunday, but in the third
> system, Sunday is "zhoumo" ("cycle's end") and Monday is zhouyi ("first
> of cycle").

Last time I was in Borders, I don't recall seeing any
Polish, Lithuanian or Chinese calendars for sale.

>
> --
> Steven

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


Re: improving a huge double-for cycle

2008-09-18 Thread giltay
On Sep 18, 11:18 am, [EMAIL PROTECTED] wrote:
> dup=set()
> SN=[]
> for item in IN:
>    c=item.coordinates[0], item.coordinates[1]
>    if c in dup:
>       SN.append(item.label)
>    else:
>       dup.add(c)

+1 for O(N)

If item.coordinates is just an (x, y) pair, you can skip building c
and save a little memory:

seen_coords = set()

for node in IN:
if node.coordinates in seen_coords:
SN.append(node.label)
else:
seen_coords.add(node.coordinates)

seen_coords gets populated with references to the existing
node.coordinates objects, instead of new tuples.

Geoff G-T

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


Re: append on lists

2008-09-18 Thread Steve Holden
Armin wrote:
> Duncan Booth wrote:
>> "Chris Rebert" <[EMAIL PROTECTED]> wrote:
>>> On Tue, Sep 16, 2008 at 1:20 AM, Armin <[EMAIL PROTECTED]> wrote:
  [1,2,3,4,7].append(c) -> Is this a valid expression?
>>> Literally, no, because you can't call methods on literals.
>>
>> Rubbish. There is no restriction about calling methods on literals.
>> That expression is perfectly valid but has no practical use that I can
>> see.
> 
> The semantic of [1,2,3,4,7].append(c) and [1,2,3,4,7] + c
> (with c = [8,9]) is identical, but the first expression doesn't provide
> a value. Strange by design ...
> 
Have a care, there. The semantics are different.

lst = [1, 2, 3, 4, 7]
lst.append([8, 9])

makes lst

[1, 2, 3, 4, 7, [8, 9]]

whereas

lst = [1, 2, 3, 4, 7]
lst = lst + [8, 9]

makes lst

[1, 2, 3, 4, 5, 7, 8, 9]

I suspect you meant [1, 2, 3, 4, 5, 7] + [c]

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Cython dynamic library problem

2008-09-18 Thread Tommy Grav

On Sep 18, 2008, at 12:35 PM, Rob Wolfe wrote:


I would try to use `distutils` because this package is much wiser
than me and knows all necessary switches for gcc. ;)


That worked! Thanks

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


Re: Zsi interoperability

2008-09-18 Thread Dieter Maurer
"Marco Bizzarri" <[EMAIL PROTECTED]> writes on Mon, 15 Sep 2008 20:26:27 +0200:
> On Mon, Sep 15, 2008 at 8:15 PM, Stefan Behnel <[EMAIL PROTECTED]> wrote:
> > Mailing List SVR wrote:
> >> I have to implement a soap web services from wsdl, the server is
> >> developed using oracle, is zsi or some other python library for soap
> >> interoperable with oracle soa?
> >
> > No idea, but I'd definitely try soaplib before ZSI.
> >
> > Stefan
> 
> I'm working on a project where I need to write a client for SOAP with
> Attachments; I can see ZSI does not support it

The ZSI documentation (2.0) says that SOAP attachments are supported --
but I never tried it.


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


Re: Zsi interoperability

2008-09-18 Thread Dieter Maurer
Mailing List SVR <[EMAIL PROTECTED]> writes on Tue, 16 Sep 2008 08:31:13 +0200:
> ...
> however my server require client
> certificate authentication,
> 
> does soaplib or zsi work in this environment?

ZSI allows you to provide an alternative transport.
That's the usual way to let ZSI work over "https" rather than "http".

I do not know whether Python supports a client certificate authentication
transport out of the box -- but at least the problem is split into
two easier parts.

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


Re: Tkinter Bold Text

2008-09-18 Thread Guilherme Polo
On Thu, Sep 18, 2008 at 1:06 PM, April Lekin <[EMAIL PROTECTED]> wrote:
> Is there any way to highlight, bold or change the color of one word in a
> variable to be displayed on a Tkinter GUI?

Yes.

>
> Like:
>
> material = "Plastic"
> introVal = "This report describes the construction of the %s." % (material)
>

You could separate them in two labels (if you are using labels), or
apply a different tag if you are using a Text widget.

> this is what I want:
> This report describes the construction of the Plastic.
> Plastic is Bold or Blue or Green
>

Changing the color is easier, you only change the foreground option.
Changing to bold may not work for you, because depending on your Tk
version and platform it will already be bold, so you won't notice
anything. There is also a "catch" in changing text to bold, if you
only set the text option of your Label to "-weight bold" it will
probably get you a bold text, but with a different font than the one
being used by other Labels.

Now, something you could use as a base:

import Tkinter
import tkFont

root = Tkinter.Tk()

otherpart = Tkinter.Label(text="some text here")
special = Tkinter.Label(text="special", foreground='blue')
otherpart.pack(side='left')
special.pack(side='left')

f = tkFont.Font(font=otherpart['font'])
f['weight'] = 'bold'
f['underline'] = True

special['font'] = f.name

root.mainloop()


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



-- 
-- Guilherme H. Polo Goncalves
--
http://mail.python.org/mailman/listinfo/python-list


Tkinter Bold Text

2008-09-18 Thread April Lekin
Is there any way to highlight, bold or change the color of one word 
in a variable to be displayed on a Tkinter GUI?


Like:

material = "Plastic"
introVal = "This report describes the construction of the %s." % (material)

this is what I want:
This report describes the construction of the Plastic.
Plastic is Bold or Blue or Green

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

Re: append on lists

2008-09-18 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> On Sep 16, 6:03 am, Peter Anderson <[EMAIL PROTECTED]>
> wrote:
>> "/... I don't think you've thought this one through, really./"
>> snip
>>
>> We ought to try and be a little kinder to others on the list, don't you
>> think? :-)
>>
>> snip
> 
> Well said!

>From personal experience I find that honest attempts to straighten
people out lead to accusations of exploiting "seniority" to attack people.

There goes the neighborhood, I guess.

Of course we should try to maintain c.l.py's deserved reputation for
civil behavior, but things like that aren't easy to police.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Cython dynamic library problem

2008-09-18 Thread bearophileHUGS
Rob Wolfe:
> # setup.py
> from distutils.core import setup
> from distutils.extension import Extension
> from Cython.Distutils import build_ext as build_pyx
>
> setup(name = 'pyx_test',
>   ext_modules=[Extension('pyx_test', ['test_cython.pyx'])],
>   cmdclass = { 'build_ext': build_pyx })
>
> $ python2.5 setup.py build_ext -i
> running build_ext
> cythoning test_cython.pyx to test_cython.c
> building 'pyx_test' extension
> creating build/temp.linux-i686-2.5
> gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O2 -Wall -Wstrict-prototypes 
> -fPIC -I/usr/include/python2.5 -c test_cython.c -o 
> build/temp.linux-i686-2.5/test_cython.o
> test_cython.c:86: warning: function declaration isn’t a prototype
> test_cython.c:241: warning: function declaration isn’t a prototype
> test_cython.c:59: warning: ‘__pyx_skip_dispatch’ defined but not used
> gcc -pthread -shared -Wl,-O1 build/temp.linux-i686-2.5/test_cython.o -o 
> pyx_test.so
> $ python2.5 test_cython.py
> 0
> 100

With some intelligence added to Cython, probably there are ways to
reduce all this, and most of the times avoid any setup.py module too.

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


Re: PEP proposal optparse

2008-09-18 Thread Marc 'BlackJack' Rintsch
On Thu, 18 Sep 2008 11:07:45 -0500, Grant Edwards wrote:

> While we're making suggestions, I've always wished that the --help
> output displayed the default values for options in addition to the help
> text specified by the user.  I end up having to enter the default values
> twice -- once as a keyword argument and again in the help text.

'%default' in the help text will be replaced by the default value.  See 
the last option in the first example here:

http://docs.python.org/lib/optparse-generating-help.html

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


Extracting hte font name from a TrueType font file

2008-09-18 Thread Steve Holden
Does anyone have a Python recipe for this?

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Blanket font setting?

2008-09-18 Thread RGK
I'm doing an app with the AUI manager capabilities (using some of the 
wxPython demo's for help).  All is well, except I'm a bit disappointed 
with the font management.


The default font for all the widgets (TextCtrl's, StaticText's etc) are 
a bit large for my design intent and as I try to adjust that, it appears 
I have to do a


  font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT)
  font.SetPointSize(9)

Then, for every texty thing:

  myTextThing.setfont(font)
  someOtherThing.setfont(font)

Thus if I have hundreds of texty things, I've got to assign that 
hundreds of times.


Is there any sort of blanket font setting, perhaps like:

  wx.SystemSettings_SetFont(font)   #this doesn't exist

that could set everything with one fell swoop?

Thanks for your attention...

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


Re: Cython dynamic library problem

2008-09-18 Thread Rob Wolfe
Tommy Grav <[EMAIL PROTECTED]> writes:

> I am trying to learn how to use cython, and while I am following the
> cython-dev
> mailing list I didn't feel like this question was totally appropriate
> for its audience
> so I am trying here first.

[...]

> Does anyone know what the ImportError means and how to correct it?

I would try to use `distutils` because this package is much wiser
than me and knows all necessary switches for gcc. ;)

# test_cython.pyx
def test(x):
return x * x

# test_cython.py
from pyx_test import test

print test(0)
print test(10)

# setup.py
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext as build_pyx

setup(name = 'pyx_test',
  ext_modules=[Extension('pyx_test', ['test_cython.pyx'])],
  cmdclass = { 'build_ext': build_pyx })


$ python2.5 setup.py build_ext -i
running build_ext
cythoning test_cython.pyx to test_cython.c
building 'pyx_test' extension
creating build/temp.linux-i686-2.5
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O2 -Wall -Wstrict-prototypes 
-fPIC -I/usr/include/python2.5 -c test_cython.c -o 
build/temp.linux-i686-2.5/test_cython.o
test_cython.c:86: warning: function declaration isn’t a prototype
test_cython.c:241: warning: function declaration isn’t a prototype
test_cython.c:59: warning: ‘__pyx_skip_dispatch’ defined but not used
gcc -pthread -shared -Wl,-O1 build/temp.linux-i686-2.5/test_cython.o -o 
pyx_test.so
$ python2.5 test_cython.py
0
100


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


Out of memory issue with dialog box

2008-09-18 Thread numan . salati
Hi,

We have a mutilthreaded process in which one of the threads uses too
much memory causing the process to run out of memory. However when
this happens we see a dialog box pop up with the message "fatal error
in GC : too many heap sections." When you click "ok" only then does
the process die.

Is there a way for the process to crash directly without going through
the dialog box.

Any help would be appreciated?

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


TCP Server

2008-09-18 Thread James Matthews
Dear List,

I am looking to write a TCP socket server and was wondering what are the
pros and cons of using twisted over the sockets modules bundled in python?

Thanks

James

-- 
http://www.goldwatches.com/
--
http://mail.python.org/mailman/listinfo/python-list

Re: PEP proposal optparse

2008-09-18 Thread Tim Chase

Grant Edwards wrote:

While we're making suggestions, I've always wished that the
--help output displayed the default values for options in
addition to the help text specified by the user.  I end up
having to enter the default values twice -- once as a keyword
argument and again in the help text.  Then later when I decide
to change the default value, things get out-of-sync.


Tangential to this thread, what's the preferred way to get 
changes into optparse?  Based on the comments I've read in the 
optparse.py file, it looks like it's the generated output of some 
other process.  I've patched my local version to include some 
changes for handling newlines in help text (which has cropped up 
on the list occasionally, as the current version eats newlines), 
but am not sure whether I need to be patching against the 
optparse.py or against the file that generated it (which I don't 
have in my install, AFAIK).


Perhaps one of the core devs that works on optparse could tell me 
how they'd prefer such changes submitted?


Thanks,

-tkc



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


Re: locks

2008-09-18 Thread kalin m


yea...  sorry...  i just have all python stuff in the same folder and 
messed up...



[EMAIL PROTECTED] wrote:

kalin> mailman has been locking one list out.  the web interface just
kalin> hangs and it generates a bunch of locks. it seems that it can not
kalin> write to a log but not sure which one. errors are like:
...

You'd probably be better off asking about Mailman problems on
[EMAIL PROTECTED]

  

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


Re: Installing pySerial

2008-09-18 Thread Grant Edwards
On 2008-09-18, Joe G (Home) <[EMAIL PROTECTED]> wrote:
> Hi All,
>
> Background
>===
> I have installed Python for windows today from the python web site  .I also 
> installed pySerial using the Windows installer from the sourceforge web 
> site. Both installs use the default directories.
>
> Phyton  version: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC 
> v.1310 32 bit (Intel)] on win32
>
> pySerial   2.4   July 6th
>
>
> Problem :  Errors Screen output
>
 import serial
>
> Traceback (most recent call last):
>   File "", line 1, in 
> import serial
>   File "C:\Python25\Lib\site-packages\serial\__init__.py", line 18, in 
>
> from serialwin32 import *
>   File "C:\Python25\Lib\site-packages\serial\serialwin32.py", line 9, in 
>
> import win32file  # The base COM port and file IO functions.
> ImportError: No module named win32file

>
> So it looks like Python can not see some of the modules

Do you have the win32 modules installed?

> Here's the active paths
>
 print sys.path
> ['C:\\Python25\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python25.zip', 
> 'C:\\Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', 
> 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 
> 'C:\\Python25\\lib\\site-packages']

>
> It seems that   C:\Python25\Lib\site-packages\serial   needs to be added to 
> the PYTHONPATH

I don't see how you came to that conclusion.  Is the "missing"
module (win32file) located in C:\Python25\Lib\site-packages\serial?

> QUESTION
>=
> Q1.  How do I add C:\Python25\Lib\site-packages\serial  to the PYTHONPATH ?

Dunno.

> Q2. How do I check that I have installed pySerial corretly
> (using the Windows installer)

If you used the installer, you almost undoubtedly have it
installed correctly.  I think you're missing the win32 package.

http://python.net/crew/mhammond/win32/Downloads.html

-- 
Grant Edwards   grante Yow! I'm not an Iranian!!
  at   I voted for Dianne
   visi.comFeinstein!!
--
http://mail.python.org/mailman/listinfo/python-list


Tkinter Bold Text

2008-09-18 Thread April Lekin
Is there any way to highlight, bold or change the color of one word 
in a variable to be displayed on a Tkinter GUI?


Like:

material = "Plastic"
introVal = "This report describes the construction of the %s." % (material)

this is what I want:
This report describes the construction of the Plastic.
Plastic is Bold or Blue or Green

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

Re: PEP proposal optparse

2008-09-18 Thread Grant Edwards
While we're making suggestions, I've always wished that the
--help output displayed the default values for options in
addition to the help text specified by the user.  I end up
having to enter the default values twice -- once as a keyword
argument and again in the help text.  Then later when I decide
to change the default value, things get out-of-sync.

-- 
Grant Edwards   grante Yow! Did you move a lot of
  at   KOREAN STEAK KNIVES this
   visi.comtrip, Dingy?
--
http://mail.python.org/mailman/listinfo/python-list


Automated Build System ?

2008-09-18 Thread Uwe Schmitt
Hi,

I'm working on a python Package which includes some extension modules
and unit tests. I want to automate some tasks like "build extsion
module, then copy xxx.pyd to folder yyy and run all unit tests from
folder ".

I used google but found no hints to existing solutions.
Can anybody help me ?

Greetings, Uwe

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


Re: Installing pySerial

2008-09-18 Thread Richard Brodie

"Joe G (Home)" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> I have installed Python for windows today from the python web site  .I also 
> installed 
> pySerial using the Windows installer from the sourceforge web site.

You need to read the pySerial smallprint, where it says:

"The files in this package are 100% pure Python. They depend on non standard but
common packages on Windows (pywin32) and Jython (JavaComm).
POSIX (Linux, BSD) uses only modules from the standard Python distribution)"



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


Re: Installing pySerial

2008-09-18 Thread Tim Golden

Joe G (Home) wrote:

Hi All,

Background
===
I have installed Python for windows today from the python web site  .I also 
installed pySerial using the Windows installer from the sourceforge web 
site. Both installs use the default directories.


Phyton  version: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC 
v.1310 32 bit (Intel)] on win32


pySerial   2.4   July 6th


Problem :  Errors Screen output


import serial


Traceback (most recent call last):
  File "", line 1, in 
import serial
  File "C:\Python25\Lib\site-packages\serial\__init__.py", line 18, in 


from serialwin32 import *
  File "C:\Python25\Lib\site-packages\serial\serialwin32.py", line 9, in 


import win32file  # The base COM port and file IO functions.
ImportError: No module named win32file


You need to install the pywin32 extensions from:

 http://pywin32.sf.net

They're so commonly used (and, if you install the ActiveState
distro of Python, even bundled) that I imagine many Windows
Pythoneers like myself simply install them automatically as
soon as we've installed the main python.org Python.

Once you've done that, the rest should just work: it's
clear from the traceback that the serial module is getting
imported; it's just trying to find the win32file module.

TJG

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


ANN: Wing IDE for Python v. 3.1.4 released

2008-09-18 Thread Wingware

Hi,

Wingware has released version 3.1.4 of Wing IDE.  This bug fix release is
available for all three product levels of Wing IDE.

*Release Highlights*

This release includes the following:

* Debugger support for Python 2.6
* Support zope buildout directories not named "instance"
* Added highlighted keywords for caml, d, escript, lisp, ps, and yaml files
* Don't display message that save is unavailable before running pylint
* VI mode fix: After / de-select the search match once Enter is pressed
* About 20 other bug fixes: see the change log for details
  http://wingware.com/pub/wingide/3.1.4/CHANGELOG.txt

*Downloads*

Wing IDE Professional and Wing IDE Personal are commercial software and
require a license to run. A free trial license can be obtained directly from
the product when launched.

Wing IDE Pro 3.1.4 http://wingware.com/downloads/wingide/3.1

Wing IDE Personal 3.1.4http://wingware.com/downloads/wingide-personal/3.1

Wing IDE 101 3.1.4 http://wingware.com/downloads/wingide-101/3.1

*About Wing IDE*

Wing IDE is an integrated development environment for the Python programming
language.  It provides powerful debugging, editing, code intelligence,
testing, and search capabilities that reduce development and debugging
time, cut down on coding errors, and make it easier to understand
and navigate Python code.

Wing IDE is available in three product levels:  Wing IDE Professional is
the full-featured Python IDE, Wing IDE Personal offers a reduced feature
set at a low price, and Wing IDE 101 is a free simplified version designed
for teaching entry level programming courses with Python.

System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or
Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit).
Wing IDE 3.1 supports Python versions 2.0.x through 2.5.x.

*New Features in Wing 3.1*

This release adds the following features not found in Wing 3.0.x:

* Support for zip archives
* Support for pkg_resources name spaces and eggs
* Support for doctest and nose style unit tests (*)
* Scan for sys.path changes such as those used in buildout
* How-To and support for Google App Engine
* Inline context appropriate templates/snippets integrated with autocompleter 
(*)
* Word list driven auto-completion in non-Python files (**)
* Quick navigation to files and symbols by typing a fragment (**)
* Improved support for Stackless Python
* Preference to strip trailing white space on save
* Display gi_running and gi_frame for generators
* Improved code analysis for Python 2.5
* Other minor features and bug fixes not found in Wing 3.0.x

(*)'d items are available in Wing IDE Professional only.
(**)'d items are available in Wing IDE Personal or Professional only.

Please see the change log for a detailed list of changes:
http://wingware.com/pub/wingide/3.1.4/CHANGELOG.txt

*Purchasing and Upgrading*

Wing 3.1 is a free upgrade for all Wing IDE 3.0 users. Any 2.x license sold
after May 2nd 2006 is free to upgrade; others cost 1/2 the normal price to
upgrade.

Upgrade a 2.x license:https://wingware.com/store/upgrade

Purchase a 3.x license:   https://wingware.com/store/purchase

--

The Wingware Team
Wingware | Python IDE
Advancing Software Development

www.wingware.com

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


Re: dict generator question

2008-09-18 Thread Simon Mullis
Haha!

Thanks for all of the suggestions... (I love this list!)

SM

2008/9/18  <[EMAIL PROTECTED]>:
> On Sep 18, 10:54 am, "Simon Mullis" <[EMAIL PROTECTED]> wrote:
>> Hi,
>>
>> Let's say I have an arbitrary list of minor software versions of an
>> imaginary software product:
>>
>> l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]
>>
>> I'd like to create a dict with major_version : count.
>>
>> (So, in this case:
>>
>> dict_of_counts = { "1.1" : "1",
>>"1.2" : "2",
>>"1.3" : "2" }
>>
>> Something like:
>>
>> dict_of_counts = dict([(v[0:3], "count") for v in l])
>>
>> I can't seem to figure out how to get "count", as I cannot do x += 1
>> or x++ as x may or may not yet exist, and I haven't found a way to
>> create default values.
>>
>> I'm most probably not thinking pythonically enough... (I know I could
>> do this pretty easily with a couple more lines, but I'd like to
>> understand if there's a way to use a dict generator for this).
>>
>> Thanks in advance
>>
>> SM
>>
>> --
>> Simon Mullis
>
> Considering 3 identical "simultpost" solutions I'd say:
>  "one obvious way to do it" FTW :-)
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Simon Mullis
_
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: dict generator question

2008-09-18 Thread George Sakkis
On Sep 18, 11:43 am, Gerard flanagan <[EMAIL PROTECTED]> wrote:
> Simon Mullis wrote:
> > Hi,
>
> > Let's say I have an arbitrary list of minor software versions of an
> > imaginary software product:
>
> > l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]
>
> > I'd like to create a dict with major_version : count.
>
> > (So, in this case:
>
> > dict_of_counts = { "1.1" : "1",
> >"1.2" : "2",
> >"1.3" : "2" }
>
> [...]
> data = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]
>
> from itertools import groupby
>
> datadict = \
>dict((k, len(list(g))) for k,g in groupby(data, lambda s: s[:3]))
> print datadict

Note that this works correctly only if the versions are already sorted
by major version.

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


Re: improving a huge double-for cycle

2008-09-18 Thread Tino Wildenhain

Tino Wildenhain wrote:

Hi,

Alexzive wrote:

Hello there :) ,

I am a python newbie and need to run following code for a task in an
external simulation programm called "Abaqus" which makes use of python
to access the mesh (ensamble of nodes with xy coordinates) of a
certain geometrical model.

[IN is the starting input containing the nodes to be check, there are
some double nodes with the same x and y coordinates which need to be
removed. SN is the output containing such double nodes]

Code: Select all
for i in range(len(IN)): #scan all elements of the list IN
  for j in range(len(IN)):
if i <> j:
 if IN[i].coordinates[0] == IN[j].coordinates[0]:
   if IN[i].coordinates[1] == IN[j].coordinates[1]:
  SN.append(IN[i].label)



data=dict()
for item in IN: # (what a name! ;)
data.setdefault(item.coordinates,[]).append(item)
# provided coordinates is a tuple

dupes=[items for items in data.values() if len(items)>1]

should give you a resulting list of lists of elements in IN
which occur more then once per coordinates.
You can then decide which ones to remove or whatever.

If you want to have the output only containing nodes to remove,
the following would work:

dupes=[]
for items in data.values():
dupes.extend(items[1:])



I did a small test - I don't know if it reflects
the actual problem good enough but it seems it
all runs below 1 sec each so this would be very
fast compared to 15h:

>>> import random
>>> class Node(object):
... def __init__(self,x,y):
... self.coordinates=(x,y)

>>> IN=[Node(random.randint(0,100),random.randint(0,100)) for i in 
xrange(10)]


>>> data=dict()
>>> for item in IN: data.setdefault(item.coordinates,[]).append(item)
...

>>> dupes=[items for items in data.values() if len(items)>1]
>>> len(dupes)
10190
>>>

Cheers
Tino


smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list

Installing pySerial

2008-09-18 Thread Joe G (Home)
Hi All,

Background
===
I have installed Python for windows today from the python web site  .I also 
installed pySerial using the Windows installer from the sourceforge web 
site. Both installs use the default directories.

Phyton  version: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC 
v.1310 32 bit (Intel)] on win32

pySerial   2.4   July 6th


Problem :  Errors Screen output

>>> import serial

Traceback (most recent call last):
  File "", line 1, in 
import serial
  File "C:\Python25\Lib\site-packages\serial\__init__.py", line 18, in 

from serialwin32 import *
  File "C:\Python25\Lib\site-packages\serial\serialwin32.py", line 9, in 

import win32file  # The base COM port and file IO functions.
ImportError: No module named win32file
>>>

So it looks like Python can not see some of the modules

Here's the active paths

>>> print sys.path
['C:\\Python25\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python25.zip', 
'C:\\Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', 
'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 
'C:\\Python25\\lib\\site-packages']
>>>

It seems that   C:\Python25\Lib\site-packages\serial   needs to be added to 
the PYTHONPATH


QUESTION
=
Q1.  How do I add C:\Python25\Lib\site-packages\serial  to the PYTHONPATH ?

Q2. How do I check that I have installed  pySerial  corretly  (using the 
Windows installer)

Thanks in advance


Joe






 


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


Re: dict generator question

2008-09-18 Thread pruebauno
On Sep 18, 10:54 am, "Simon Mullis" <[EMAIL PROTECTED]> wrote:
> Hi,
>
> Let's say I have an arbitrary list of minor software versions of an
> imaginary software product:
>
> l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]
>
> I'd like to create a dict with major_version : count.
>
> (So, in this case:
>
> dict_of_counts = { "1.1" : "1",
>"1.2" : "2",
>"1.3" : "2" }
>
> Something like:
>
> dict_of_counts = dict([(v[0:3], "count") for v in l])
>
> I can't seem to figure out how to get "count", as I cannot do x += 1
> or x++ as x may or may not yet exist, and I haven't found a way to
> create default values.
>
> I'm most probably not thinking pythonically enough... (I know I could
> do this pretty easily with a couple more lines, but I'd like to
> understand if there's a way to use a dict generator for this).
>
> Thanks in advance
>
> SM
>
> --
> Simon Mullis

Considering 3 identical "simultpost" solutions I'd say:
 "one obvious way to do it" FTW :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: improving a huge double-for cycle

2008-09-18 Thread Tino Wildenhain

Hi,

Alexzive wrote:

Hello there :) ,

I am a python newbie and need to run following code for a task in an
external simulation programm called "Abaqus" which makes use of python
to access the mesh (ensamble of nodes with xy coordinates) of a
certain geometrical model.

[IN is the starting input containing the nodes to be check, there are
some double nodes with the same x and y coordinates which need to be
removed. SN is the output containing such double nodes]

Code: Select all
for i in range(len(IN)): #scan all elements of the list IN
  for j in range(len(IN)):
if i <> j:
 if IN[i].coordinates[0] == IN[j].coordinates[0]:
   if IN[i].coordinates[1] == IN[j].coordinates[1]:
  SN.append(IN[i].label)



data=dict()
for item in IN: # (what a name! ;)
data.setdefault(item.coordinates,[]).append(item)
# provided coordinates is a tuple

dupes=[items for items in data.values() if len(items)>1]

should give you a resulting list of lists of elements in IN
which occur more then once per coordinates.
You can then decide which ones to remove or whatever.

If you want to have the output only containing nodes to remove,
the following would work:

dupes=[]
for items in data.values():
dupes.extend(items[1:])

HTH
Tino



smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list

Re: dict generator question

2008-09-18 Thread Gerard flanagan

Simon Mullis wrote:

Hi,

Let's say I have an arbitrary list of minor software versions of an
imaginary software product:

l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]

I'd like to create a dict with major_version : count.

(So, in this case:

dict_of_counts = { "1.1" : "1",
   "1.2" : "2",
   "1.3" : "2" }



[...]
data = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]

from itertools import groupby

datadict = \
  dict((k, len(list(g))) for k,g in groupby(data, lambda s: s[:3]))
print datadict




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


Re: improving a huge double-for cycle

2008-09-18 Thread Jake Anderson




psyco might help a fair bit (10x-40x) here ;->
perhaps look at dumping the data into sqlite then pulling it back out.
It (or the other databases) are designed for tossing around large lumps
of data.
Alexzive wrote:

  Hello there :) ,

I am a python newbie and need to run following code for a task in an
external simulation programm called "Abaqus" which makes use of python
to access the mesh (ensamble of nodes with xy coordinates) of a
certain geometrical model.

[IN is the starting input containing the nodes to be check, there are
some double nodes with the same x and y coordinates which need to be
removed. SN is the output containing such double nodes]

Code: Select all
for i in range(len(IN)): #scan all elements of the list IN
  for j in range(len(IN)):
if i <> j:
 if IN[i].coordinates[0] == IN[j].coordinates[0]:
   if IN[i].coordinates[1] == IN[j].coordinates[1]:
  SN.append(IN[i].label)



Unfortunately my len(IN) is about 100.000 and the running time about
15h  :(

Any idea to improve it?

I have already tried to group the "if statements" in a single one:

Code: Select all
if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and
if IN[i].coordinates[1] == IN[j].coordinates[1]:


but no improvements.

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



-- 


Vapour Forge



Jake Anderson


Project Manager


Mobile:   0412 897 125
Email: [EMAIL PROTECTED]
Web Page:  www.vapourforge.com


Your source
for custom IT services




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

Re: dict generator question

2008-09-18 Thread George Sakkis
On Sep 18, 10:54 am, "Simon Mullis" <[EMAIL PROTECTED]> wrote:
> Hi,
>
> Let's say I have an arbitrary list of minor software versions of an
> imaginary software product:
>
> l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]
>
> I'd like to create a dict with major_version : count.
>
> (So, in this case:
>
> dict_of_counts = { "1.1" : "1",
>"1.2" : "2",
>"1.3" : "2" }
>
> Something like:
>
> dict_of_counts = dict([(v[0:3], "count") for v in l])
>
> I can't seem to figure out how to get "count", as I cannot do x += 1
> or x++ as x may or may not yet exist, and I haven't found a way to
> create default values.
>
> I'm most probably not thinking pythonically enough... (I know I could
> do this pretty easily with a couple more lines, but I'd like to
> understand if there's a way to use a dict generator for this).

Not everything has to be a one-liner; also v[0:3] is wrong if any sub-
version is greater than 9. Here's a standard idiom (in 2.5+ at least):

from collection import defaultdict
versions = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]

major2count = defaultdict(int)
for v in versions:
major2count['.'.join(v.split('.',2)[:2])] += 1
print major2count

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


Re: dict generator question

2008-09-18 Thread pruebauno
On Sep 18, 10:54 am, "Simon Mullis" <[EMAIL PROTECTED]> wrote:
> Hi,
>
> Let's say I have an arbitrary list of minor software versions of an
> imaginary software product:
>
> l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]
>
> I'd like to create a dict with major_version : count.
>
> (So, in this case:
>
> dict_of_counts = { "1.1" : "1",
>"1.2" : "2",
>"1.3" : "2" }
>
> Something like:
>
> dict_of_counts = dict([(v[0:3], "count") for v in l])
>
> I can't seem to figure out how to get "count", as I cannot do x += 1
> or x++ as x may or may not yet exist, and I haven't found a way to
> create default values.
>
> I'm most probably not thinking pythonically enough... (I know I could
> do this pretty easily with a couple more lines, but I'd like to
> understand if there's a way to use a dict generator for this).
>
> Thanks in advance
>
> SM
>
> --
> Simon Mullis

3 lines:

from collections import defaultdict
dd=defaultdict(int)
for x in l: dd[x[0:3]]+=1
--
http://mail.python.org/mailman/listinfo/python-list


Re: unicode in multi-line strings

2008-09-18 Thread Diez B. Roggisch
Jiri Barton wrote:

> Hello,
> 
> I have a problem with international characters in multi-line strings.
> 
> 
> Works: '''á'''
> 
> Works: '''
> a'''
> 
> Does not work: '''
> á'''
> 
> 
> By does not work I mean the infamous
> 
> 'ascii' codec can't encode character u'\xe1' in position 4: ordinal not
> in range(128)
> 
> I'm using Ubuntu 8.04 with Python 2.5. It does not work in terminal,
> from scripts, or from scripts with the encoding specified at the top.
> Making the string unicode (u''' ... ''') does not change anything.
> 
> It could be an interpreter issue but I didn't know where else I should
> turn for help.

Please show a self-contained example that does not work. The above won't
puke on you as you claim - because they are simple byte-strings, and thus
aren't subject to any automatic en/decoding whatsoever, unless somehow
*used*. Which you don't show how you do it.

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

Re: dict generator question

2008-09-18 Thread marek . rocki
Simon Mullis napisał(a):
> Something like:
>
> dict_of_counts = dict([(v[0:3], "count") for v in l])
>
> I can't seem to figure out how to get "count", as I cannot do x += 1
> or x++ as x may or may not yet exist, and I haven't found a way to
> create default values.

It seems to me that the "count" you're looking for is the number of
elements from l whose first 3 characters are the same as the v[0:3]
thing. So you may try:
>>> dict_of_counts = dict((v[0:3], sum(1 for x in l if x[:3] == v[:3])) for v 
>>> in l)

But this isn't particularly efficient. The 'canonical way' to
construct such histograms/frequency counts in python is probably by
using defaultdict:
>>> dict_of_counts = collections.defaultdict(int)
>>> for x in l:
>>> dict_of_counts[x[:3]] += 1

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


Re: ANN: Python GUI development using XULRunner

2008-09-18 Thread Don Spaulding
On Sep 17, 5:53 pm, Todd Whiteman <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > On Sep 17, 1:21 pm, Todd Whiteman <[EMAIL PROTECTED]> wrote:
> >> Don Spaulding wrote:
> >>> On Sep 16, 8:29 pm, Todd Whiteman <[EMAIL PROTECTED]> wrote:
>  I've put together a tutorial that shows off how to build a GUI
>  application using XULRunner (same architectural components as Firefox
>  uses) that can be used in conjunction with the Python programming 
>  language.
>  The tutorial covers how to build a Python/XULRunner GUI 
>  application:http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul...
> >>> I get to the "Running" step and run into "Couldn't load XPCOM."
> >>> Does this work on x86_64?  Or have I made a rookie mistake?
> >> Hi Don,
>
> >> A good question. Mozilla only provide 32-bit XulRunner applications by
> >> default, you you'll need to install the necessary 32-bit compatability
> >> libraries on your Linux machine, i.e. for Ubuntu it's something like:
> >> sudo apt-get install ia32-libs ia32-libs-gtk
>
> >> Then you should be able to run the example. You can check the
> >> dependencies using something the following commands, there should be no
> >> missing dependencies:
> >> $ cd pyxpcom_gui_app/xulrunner
> >> $ LD_LIBRARY_PATH=. ldd ./xulrunner-bin
>
> >> It is possible to use a 64-bit version, but you'll need to compile this
> >> yourself (or find somewhere that provides these x86_64 versions). Note
> >> that the PythonExt project does not offer Python bindings for x86_64
> >> either (it's on my todo list), you can compile the PythonExt part
> >> yourself as well if you need a 64-bit version.
>
> >> Cheers,
> >> Todd
>
> > Interesting, I'm running Ubuntu Intrepid here, and have both ia32-libs
> > and ia32-libs-gtk installed.
>
> > ldd shows that I'm missing the following libs, even though the proper
> > packages are installed, and the files show up in /usr/lib.
>
> >    libxcb-render-util.so.0 => not found
> >    libxcb-render.so.0 => not found
>
> > There's also /usr/lib/libxcb-render.so.0.0.0 and the same for render-
> > util, so I wonder if that could be part of the problem?
>
> > Don
>
> Hi Don,
>
> I'm thinking there may be additional 32-bit packages necessary then (I'm
> not sure which package).
>
> Not sure about Ubuntu 8.10 (it's still alpha). I'm using a Ubuntu 8.04
> x86_64 machine and my dependencies list the following for the latest
> 32-bit build of XulRunner:
>
> $ LD_LIBRARY_PATH=. ldd ./xulrunner-bin | grep libxcb
>         libxcb-xlib.so.0 => /usr/lib32/libxcb-xlib.so.0 (0xf6493000)
>         libxcb.so.1 => /usr/lib32/libxcb.so.1 (0xf647b000)
>
> Cheers,
> Todd

No worries Todd, it is alpha.  It was a very recent bug in the 8.10
ia32-libs package, which is now fixed  :-D

Thanks for the excellent writeup, BTW!  I've been wondering what was
involved in doing this for a while, it just never made it up my
priority list to figure out.  Again, thanks!
--
http://mail.python.org/mailman/listinfo/python-list


unicode in multi-line strings

2008-09-18 Thread Jiri Barton

Hello,

I have a problem with international characters in multi-line strings.


Works: '''á'''

Works: '''
a'''

Does not work: '''
á'''


By does not work I mean the infamous

'ascii' codec can't encode character u'\xe1' in position 4: ordinal not 
in range(128)


I'm using Ubuntu 8.04 with Python 2.5. It does not work in terminal, 
from scripts, or from scripts with the encoding specified at the top. 
Making the string unicode (u''' ... ''') does not change anything.


It could be an interpreter issue but I didn't know where else I should 
turn for help.


Thank you!
Jiri


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


Re: improving a huge double-for cycle

2008-09-18 Thread pruebauno
On Sep 18, 8:25 am, Alexzive <[EMAIL PROTECTED]> wrote:
> Hello there :) ,
>
> I am a python newbie and need to run following code for a task in an
> external simulation programm called "Abaqus" which makes use of python
> to access the mesh (ensamble of nodes with xy coordinates) of a
> certain geometrical model.
>
> [IN is the starting input containing the nodes to be check, there are
> some double nodes with the same x and y coordinates which need to be
> removed. SN is the output containing such double nodes]
>
> Code: Select all
> for i in range(len(IN)): #scan all elements of the list IN
>   for j in range(len(IN)):
> if i <> j:
>  if IN[i].coordinates[0] == IN[j].coordinates[0]:
>if IN[i].coordinates[1] == IN[j].coordinates[1]:
>   SN.append(IN[i].label)
>
> Unfortunately my len(IN) is about 100.000 and the running time about
> 15h  :(
>
> Any idea to improve it?
>
> I have already tried to group the "if statements" in a single one:
>
> Code: Select all
> if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and
> if IN[i].coordinates[1] == IN[j].coordinates[1]:
>
> but no improvements.
>
> Many thanks, Alex


dup=set()
SN=[]
for item in IN:
   c=item.coordinates[0], item.coordinates[1]
   if c in dup:
  SN.append(item.label)
   else:
  dup.add(c)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Modifying the system menu

2008-09-18 Thread raj . indian . 08
On Sep 18, 6:39 am, [EMAIL PROTECTED] wrote:
> I tested it again and found that the behaviour is a little different
> from what I mentioned previously in the mailchain.
> The item is working perfectly the first time around. Now if I close
> the application and run it again (which was what I did earlier), if
> that application system menu is already modified, it is causing this
> issue.
>
> Why would this happen? If it is that the file handle is not obtained,
> it wouldnt have gone through the following check at all?
>
> >     hw = win32gui.GetSystemMenu(hwnd, False)
> >     if hw != None:
> >         win32gui.AppendMenu(hw,win32con.MF_SEPARATOR,0,'-');
>
> Not only did it go through, it failed with an invalid menu handle
> error.

More worryingly, this happens randomly. Am I doing some mistake here?
--
http://mail.python.org/mailman/listinfo/python-list


Re: A unique instance of Python GUI program

2008-09-18 Thread Grant Edwards
On 2008-09-16, akineko <[EMAIL PROTECTED]> wrote:

> This may not be a Python specific challenge. I have a GUI
> program written in Python + Tkinter. It works very well.
>
> Now, I would like to start it from a shell script. As my GUI
> program includes a server, it should not have more than one
> instance. Is there any easy way to check if another instance
> of the program is already running.
>
> I vaguely remember that Windows programming provides a way to
> check.

On unix the solution is usually a lockfile placed in a
predefined location.  Other people use a socket, but that's a
bit more susceptible to namespace collisions with unrelated
programs.

> A platform independent approach would be nice but a solution
> for X is sufficient for my application.

I don't see what X has to do with it.

> Any comments will be greatly appreciated.

This question is asked and answered about once a week, and I'm
always surprised at how frequently it comes up.  I've been
doing sw development for decades and apart from Unix system
daemons, I don't remember ever needing to prevent multiple
instances of an application from running.  Can somebody lend me
a clue as to why this question comes up so often? There can't
be that many people writing Unix daemons in Python (and if they
were, they'd probably already know about lockfiles).

Just curious...

-- 
Grant Edwards   grante Yow! Is something VIOLENT
  at   going to happen to a
   visi.comGARBAGE CAN?
--
http://mail.python.org/mailman/listinfo/python-list


dict generator question

2008-09-18 Thread Simon Mullis
Hi,

Let's say I have an arbitrary list of minor software versions of an
imaginary software product:

l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]

I'd like to create a dict with major_version : count.

(So, in this case:

dict_of_counts = { "1.1" : "1",
   "1.2" : "2",
   "1.3" : "2" }

Something like:

dict_of_counts = dict([(v[0:3], "count") for v in l])

I can't seem to figure out how to get "count", as I cannot do x += 1
or x++ as x may or may not yet exist, and I haven't found a way to
create default values.

I'm most probably not thinking pythonically enough... (I know I could
do this pretty easily with a couple more lines, but I'd like to
understand if there's a way to use a dict generator for this).

Thanks in advance

SM


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


Re: Problem occured while sending mail

2008-09-18 Thread Peter Pearson
On Wed, 17 Sep 2008 23:53:36 -0700 (PDT), sui <[EMAIL PROTECTED]> wrote:
> On Sep 17, 8:04 pm, Peter Pearson <[EMAIL PROTECTED]> wrote:
>> On Wed, 17 Sep 2008 05:28:05 -0700 (PDT), sui <[EMAIL PROTECTED]> wrote:
[snip]
>> > socket.error: (110, 'Connection timed out')
[snip]
>> As a simple connectivity test, you might see whether you can connect
>> using telnet:
[snip]
> even i couldnt connect using telnet
> msg comes host is down

Then your problem is a networking problem.  I know even less about
networking than I know about Python.  Can you ping the destination?
Perhaps tracepath or traceroute will help you find where your
messages are being refused.  Perhaps you are trying to work through
an internet access provider (e.g., ISP) that doesn't allow direct
connections to remote mail servers.

If I might add a grouchy comment, you really should learn a
little about netiquette.  When you don't bother to trim the
quoted context or even to punctuate your text, you broadcast
a conspicuous implication that you value your own time much
more than you value the time of the people whose help you're
soliciting, which is incongruous and insulting.  A more
carefully presented request might have gotten a response
from someone more knowledgeable -- and less grouchy -- than
me.

-- 
To email me, substitute nowhere->spamcop, invalid->net.
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >