Re: Python 2.5, problems reading large ( > 4Gbyes) files on win2k

2007-03-03 Thread casevh
On Mar 2, 10:09 am, [EMAIL PROTECTED] wrote:
> Folks,
>
> I've a Python 2.5 app running on 32 bit Win 2k SP4 (NTFS volume).
> Reading a file of 13 GBytes, one line at a time.  It appears that,
> once the read line passes the 4 GByte boundary, I am getting
> occasional random line concatenations.  Input file is confirmed good
> via UltraEdit.  Groovy version of the same app runs fine.
>
> Any ideas?
>
> Cheers

It appears to be a bug. I am able to reproduce the problem with the
code fragment below. It creates a 12GB file with line lengths ranging
from 0 to 126 bytes, and repeating that set of lines 150 times. It
fails on W2K SP4 with both Python 2.4 and 2.5. It works correctly on
Linux (Ubuntu 6.10).

I have reported on SourceForge as bug 1672853.

# Read and write a huge file.
import sys

def write_file(end = 126, loops = 150, fname='bigfile'):
fh = open(fname, 'w')
buff = 'A' * end
for k in range(loops):
for t in range(end+1):
fh.write(buff[:t]+'\n')
fh.close()

def read_file(end = 126, fname = 'bigfile'):
fh = open(fname, 'r')
offset = 0
loops = 0
for rec in fh:
if offset != len(rec.strip()):
print 'Error at loop:', loops
print 'Expected record length:', offset
print 'Actual record length:', len(rec.strip())
sys.exit(0)
offset += 1
if offset > end:
offset = 0
loops += 1
if not loops % 1: print loops
fh.close()

if __name__ == '__main__':
write_file(loops=150)
read_file()

casevh

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


Re: classes and functions

2007-03-03 Thread James Stroud
Silver Rock wrote:
> Friends,
> 
> I don´t see why using classes.. functions does everything already. I
> read the Rossum tutotial and two other already.
> 
> Maybe this is because I am only writing small scripts, or some more
> serious misunderstandings of the language.
> 
> Please give me a light.
> 
> thanks guys,
> Claire

Attempt to code a gui.

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


Re: Perl and Python, a practical side-by-side example.

2007-03-03 Thread attn . steven . kuo
On Mar 2, 2:44 pm, "Shawn Milo" <[EMAIL PROTECTED]> wrote:

(snipped)

> I'm attaching both the Perl and Python versions, and I'm open to
> comments on either. The script reads a file from standard input and
> finds the best record for each unique ID (piid). The best is defined
> as follows: The newest expiration date (field 5) for the record with
> the state (field 1) which matches the desired state (field 6). If
> there is no record matching the desired state, then just take the
> newest expiration date.
>
> Thanks for taking the time to look at these.
>


My attempts:

### Perl ###

#!/usr/bin/perl
use strict;
use warnings;

use List::Util qw/reduce/;
use constant {
STATE  => 1,
DATE   => 6,
TARGET => 5,
};

sub keep_best {
my ($best, $current) = @_;
if ($current->[STATE] eq $current->[TARGET]) {
   if ($best->[STATE] eq $best->[TARGET]) {
   if ($current->[DATE] gt $best->[DATE]) {
   return 0;
   }
   } else {
   return 0;
   }
} elsif (
   $best->[STATE] ne $best->[TARGET]
   and
   $current->[DATE] gt $best->[DATE]) {
   return 0;
}
return 1;
}


my %input;

# while uses less memory than for:
# the former is an iterator

while (<>)
{
chomp;
my @results = split(/\t/, $_);
my $key = $results[0];
push @{$input{$key}}, [ @results, $_ ];
}

# while uses less memory than for:
# the former is an iterator

while (my ($key, $aref ) = each %input)
{
my $best = reduce {
   keep_best( $a, $b ) ? $a : $b
} @$aref;

print $best->[-1], "\n";
}


### Python (re-working John's code) ###

import sys

def keep_best(best, current):

ACTUAL_STATE = 1
# John had these swapped
DESIRED_STATE = 5
EXPIRY_DATE = 6

keep = True
if current[ACTUAL_STATE] == current[DESIRED_STATE]:
if best[ACTUAL_STATE] == best[DESIRED_STATE]:
if current[EXPIRY_DATE] > best[EXPIRY_DATE]:
keep = False
else:
keep = False
else:
if (best[ACTUAL_STATE] != best[ACTUAL_STATE]
and current[EXPIRY_DATE] > best[EXPIRY_DATE]):
keep = False
return keep

def process_file(opened_file=sys.stdin):

PIID = 0
recs = {}

for line in opened_file:
line = line.rstrip('\n')
row = line.split('\t')
row.append(line)
piid = row[PIID]
if piid not in recs:
recs[piid] = []
recs[piid].append(row)

for piid in recs:
best = reduce(lambda b, c: keep_best(b, c) and b or c,
recs[piid])
print best[-1]

if __name__ == "__main__":
process_file()


# "reduce" seems to be Lispish, Pythonic, and Perlish!

--
Hope this helps,
Steve


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


print a ... z, A ... Z, "\n"' in Python

2007-03-03 Thread js
HI guys,

How do you write Perl's

print a ... z, A ... Z,  "\n"' in Python


In Python?


A way I came up with is the following, but I'm sure this is ugly.

''.join(chr(c) for c in (range(ord('a'), ord('z')+1) +
range(ord('A'), ord('Z')+1)))
or
crange = lambda c1, c2: [ chr(c) for c in range(ord(c1), ord(c2)+1) ]
''.join(chr(c) for c in crange('a', 'z') + crange('A', 'Z'))


I want to feel The Zen of Python :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Perl and Python, a practical side-by-side example.

2007-03-03 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Bjoern Schliessmann wrote:

> Bruno Desthuilliers wrote:
>> Shawn Milo a écrit :
> 
>>> if recs.has_key(piid) is False:
>> 
>> 'is' is the identity operator - practically, in CPython, it
>> compares memory addresses. You *dont* want to use it here.
> 
> It's recommended to use "is None"; why not "is False"? Are there
> multiple False instances or is False generated somehow?

Before `True` and `False` existed many people defined them as aliases to 1
and 0.  And of course there are *many* other objects that can be used in a
boolean context of an ``if`` statement for testing "trueness" and
"falseness".

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

Re: Sort with extra variables

2007-03-03 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Thomas Dybdahl Ahle wrote:

> Den Fri, 02 Mar 2007 21:13:02 +0100 skrev Bjoern Schliessmann:
> 
>> Thomas Dybdahl Ahle wrote:
>> 
>>> However I'd really like not to use the lambda, as it slows down the
>>> code.
>> 
>> Did you check how much the slowdown is?
> 
> Yes, the lambda adds 50%

Compared to what?  Compared to a sort that doesn't do what you want?

Ciao,
Marc 'BlackJack' Rintsch

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


Re: print a ... z, A ... Z, "\n"' in Python

2007-03-03 Thread Troy Melhase
> How do you write Perl's
>
> print a ... z, A ... Z,  "\n"' in Python
>
>
> In Python?

you might consider this cheating, but it's packed with zen goodness:

>>> import string
>>> print string.letters
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cyclic iterators ?

2007-03-03 Thread tool69
Paul Rubin a écrit :
> 
> As Bruno says, you can use itertools.cycle, but the problem above is
> that you're not looping repeatedly through the list; you yield all the
> elements, then yield the first element again, then stop.  So for
> ['a','b','c']  you'd yield the sequence a,b,c,a.  

Yes, that was the problem.
Thanks for the explanation and for the cycle() function from itertool 
that I missed.

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


Re: html sql client

2007-03-03 Thread gert
On Mar 2, 8:33 am, "gert" <[EMAIL PROTECTED]> wrote:
> On Mar 2, 7:33 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>
> > In <[EMAIL PROTECTED]>, gert wrote:
> > > I was thinking about making a column module that names the columns, i
> > > was hoping there would be some sort of api feature that already exist
> > > because parsing sql statemants to figure out which column is refers to
> > > what is allot of work.
>
> > Are you searching for the `description` attribute of cursors?  Section
> > `Cursor Objects`:
>
> >http://www.python.org/dev/peps/pep-0249/
>
> i think so :) if cursor.description would give me for example the word
> databases when i do a query like "show databases" or gives me all the
> column names when i do "select * from mytable"

http://sourceforge.net/projects/dfo/

Alrigdy i have columns with names now thx :)

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


Re: Perl and Python, a practical side-by-side example.

2007-03-03 Thread John Machin
On Mar 3, 7:08 pm, [EMAIL PROTECTED] wrote:
> On Mar 2, 2:44 pm, "Shawn Milo" <[EMAIL PROTECTED]> wrote:
>
> (snipped)
>
> > I'm attaching both the Perl and Python versions, and I'm open to
> > comments on either. The script reads a file from standard input and
> > finds the best record for each unique ID (piid). The best is defined
> > as follows: The newest expiration date (field 5) for the record with
> > the state (field 1) which matches the desired state (field 6). If
> > there is no record matching the desired state, then just take the
> > newest expiration date.
>
> > Thanks for taking the time to look at these.
>
> My attempts:
>
>
> ### Python (re-working John's code) ###
>
> import sys
>
> def keep_best(best, current):
>
> ACTUAL_STATE = 1
> # John had these swapped
> DESIRED_STATE = 5
> EXPIRY_DATE = 6

*Bullshit* -- You are confusing me with Bruno; try (re)?reading what
the OP wrote (and which you quoted above):
"""
The newest expiration date (field 5) for the record with
the state (field 1) which matches the desired state (field 6).
"""

and his code (indented a little less boisterously):

"""
#If the current record is the correct state
if current.split("\t")[1] == current.split("\t")[6]:
#If the existing record is the correct state
if best.split("\t")[1] == best.split("\t")[6]:
#If the new record has a newer exp. date
if current.split("\t")[5] > best.split("\t")[5]:
"""

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


Re: print a ... z, A ... Z, "\n"' in Python

2007-03-03 Thread bearophileHUGS
js:
> crange = lambda c1, c2: [ chr(c) for c in range(ord(c1), ord(c2)+1) ]
> ''.join(chr(c) for c in crange('a', 'z') + crange('A', 'Z'))

Yes, managing char ranges is a bit of pain with Python.
You can also pack those chars:

xcrange = lambda cc: (chr(c) for c in xrange(ord(cc[0]), ord(cc[1])
+1))

But I don't like that much.

The calls:
''.join(xcrange('az')) + ''.join(xcrange('AZ'))

But note that you return the last item of the range too, and that goes
against the semantic of the usual Python range/xrange, so you may want
to call this function with another name.

Maybe there are better ways to solve this problem. Maybe a way to
generate (closed?) char ranges can be added to the Python standard
lib.

Bye,
bearophile

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


How to query a unicode data from sqlite database

2007-03-03 Thread Tzury
Can anyone tell the technique of composing a WHERE clause that refer
to a unicode data. e.g.  "WHERE FirstName = ABCD" where ABCD is  the
unicoded first name in the form that sqlite will match with its
records.

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


Re: Perl and Python, a practical side-by-side example.

2007-03-03 Thread William Heymann
On Saturday 03 March 2007, Ben Finney wrote:
> Bjoern Schliessmann <[EMAIL PROTECTED]> writes:
>
> if not recs.has_key(piid):  # [1]
>
Why not

if piid not in recs:

That is shorter, simpler, easier to read and very slightly faster. Plus you 
can change the data structure of recs later without changing that line so 
long as it implements containment testing.

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


Re: print a ... z, A ... Z, "\n"' in Python

2007-03-03 Thread js
> But note that you return the last item of the range too, and that goes
> against the semantic of the usual Python range/xrange, so you may want
> to call this function with another name.

That makes sense. 100% agree with you.

> Maybe there are better ways to solve this problem. Maybe a way to
> generate (closed?) char ranges can be added to the Python standard
> lib.

Maybe we don't want char range If string constants would be rich enough.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print a ... z, A ... Z, "\n"' in Python

2007-03-03 Thread js
I forgot to cc pythonlist...
#

Thanks for you quick reply.

I didn't know any string constants.

>From Python Library reference, 4.1.1 String constants:

letters
   The concatenation of the strings lowercase and uppercase described below.
  The specific value is locale-dependent, and will be updated when
locale.setlocale() is called.

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


Re: Perl and Python, a practical side-by-side example.

2007-03-03 Thread Ben Finney
William Heymann <[EMAIL PROTECTED]> writes:

> On Saturday 03 March 2007, Ben Finney wrote:
> > Bjoern Schliessmann <[EMAIL PROTECTED]> writes:
> >
> > if not recs.has_key(piid):  # [1]
> >
> Why not
>
> if piid not in recs:
>
> That is shorter, simpler, easier to read and very slightly faster.

Perhaps if I'd made my posting shorter, simpler, easier to read and
slightly faster, you might have read the footnote to which the '[1]'
referred.

-- 
 \"Choose mnemonic identifiers. If you can't remember what |
  `\ mnemonic means, you've got a problem."  -- Larry Wall |
_o__)  |
Ben Finney

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


Re: Sort with extra variables

2007-03-03 Thread Diez B. Roggisch
> Well, you'd have to define the function inside the sortMoves function, as 
> it is where the variables exists.
> 
> def sortMoves(board, table, ply, moves):
> def sortKey(move):
> return getMoveValue(board, table, ply, move)
> moves.sort(key=sortKey, reverse=True) return moves
> 
> Wouldn't that make it create the callable at each call?

Yes, it does. But it's only created _once_ per sortMoves-call, and 
afterwards doesn't affect performance.

And no, it's not slower than you lambda version - they _should_ be 
equally fast, if not it's neglible. And also doesn't affect 
sorting-performance.

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


Re: print a ... z, A ... Z, "\n"' in Python

2007-03-03 Thread MonkeeSage

js  wrote:
> A way I came up with is the following, but I'm sure this is ugly.

You could abuse __getitem__ (terribly, heh!) and use slice syntax...

class crange():
def __init__(self):
self.valid = range(47,58) + range(65,91) + range(97,123)
def __getitem__(self, s):
if isinstance(s, slice):
start, stop = s.start, s.stop
if not start: start = '0'
if isinstance(stop, int) and stop > 122: stop = 'z'
elif not stop: stop  = 'z'
clist = []
chars = range(ord(start), ord(stop)+1)
for i in range(len(chars)):
if chars[i] in self.valid:
clist.append(chr(chars[i]))
return ''.join(clist)
else:
return s

cr = crange()
print cr['A':'z']
print cr['0':'8']
print cr[:]

Regards,
Jordan

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


Re: Sort with extra variables

2007-03-03 Thread Thomas Dybdahl Ahle
Den Sat, 03 Mar 2007 11:26:08 +0100 skrev Diez B. Roggisch:

>> Well, you'd have to define the function inside the sortMoves function,
>> as it is where the variables exists.
>> 
>> def sortMoves(board, table, ply, moves):
>> def sortKey(move):
>> return getMoveValue(board, table, ply, move)
>> moves.sort(key=sortKey, reverse=True) return moves
>> 
>> Wouldn't that make it create the callable at each call?
> 
> Yes, it does. But it's only created _once_ per sortMoves-call, and
> afterwards doesn't affect performance.

Sure, but I'm having a LOT of sortMove calls ;)

> And no, it's not slower than you lambda version - they _should_ be
> equally fast, if not it's neglible.

Sure, but the lambda version was too slow also.

> And also doesn't affect sorting-performance.

I know, but the sorting itself is really not the problem, as the lists 
only contain 5-30 items.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print a ... z, A ... Z, "\n"' in Python

2007-03-03 Thread Lloyd Zusman
"js " <[EMAIL PROTECTED]> writes:

>> But note that you return the last item of the range too, and that
>> goes against the semantic of the usual Python range/xrange, so you
>> may want to call this function with another name.
>
> That makes sense. 100% agree with you.
>
>> Maybe there are better ways to solve this problem. Maybe a way to
>> generate (closed?) char ranges can be added to the Python standard
>> lib.
>
> Maybe we don't want char range If string constants would be rich
> enough.

But as soon as we want a string that doesn't correspond to any
pre-defined constants, we're hosed.  For example, there isn't
a constant that would correspond to this Perl-ism:

  print l ... w, e ... j, L ... W, E ... J, "\n";


-- 
 Lloyd Zusman
 [EMAIL PROTECTED]
 God bless you.

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


Re: Converting a c array to python list

2007-03-03 Thread zefciu
Russell E. Owen wrote:

> 
> It might help to have a clearer idea of why you want to do this. 
> 

I am writing a Mandelbrot fractal generator with Tkinter interface.  Now
the generation works like this - there is a loop in python which
iterates through fractal's pixels and for each of them calls a functions
which checks if it belongs to Mandelbrot set or how many iterations does
it take for this point to bail out.  Then the python function sets the
pixel's colour according to the result.

I was testing it first with python function, written rather for
readibility not speed, using the builtin complex class.  It took about
90 s to generate a 1152x864 fractal.  Then I used a c function and it
took 14 s.  When I told it to my friend (grad student of informatics) he
said "And probably 90% of the time takes calling the function".

So I think, that maybe I should put the whole loop into c code.  But as
before the function returned only one integer at every call, now it
would have to return a rather large array of integers (maybe chars would
be enough).

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


Re: print a ... z, A ... Z, "\n"' in Python

2007-03-03 Thread js
> > Maybe we don't want char range If string constants would be rich
> > enough.
>
> But as soon as we want a string that doesn't correspond to any
> pre-defined constants, we're hosed.  For example, there isn't
> a constant that would correspond to this Perl-ism:
>
>   print l ... w, e ... j, L ... W, E ... J, "\n";

Yes, I'm certain that l ... w, e ..j will never be a constant
because that doesn't mean a thing so nobody want them :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5, problems reading large ( > 4Gbyes) files on win2k

2007-03-03 Thread Bill Tydeman

Just curious, but since the file size limitation on NTFS is 4 GB, have you
confirmed that it isn't some other part of the interaction that is causing
the problem?   What FS is hosting the files?

On 2 Mar 2007 10:09:15 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:


Folks,

I've a Python 2.5 app running on 32 bit Win 2k SP4 (NTFS volume).
Reading a file of 13 GBytes, one line at a time.  It appears that,
once the read line passes the 4 GByte boundary, I am getting
occasional random line concatenations.  Input file is confirmed good
via UltraEdit.  Groovy version of the same app runs fine.

Any ideas?

Cheers

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





--
There is no reason for any individual to have a computer in his home.
   Ken Olsen, President, Digital Equipment, 1977
   US computer engineer & industrialist (1926 - )
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: A more navigable Python Library Reference page

2007-03-03 Thread [EMAIL PROTECTED]

>
> Google doesn't seem to let you add attachments so I've put a sample of
> the output here:http://www.qtrac.eu/libindex.html
> at the bottom of the page there is a link to the ~100 line libindex.py
> script that generated it.

I like it.  thanks.

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


Re: Perl and Python, a practical side-by-side example.

2007-03-03 Thread Paddy
On Mar 2, 10:44 pm, "Shawn Milo" <[EMAIL PROTECTED]> wrote:
> I'm new to Python and fairly experienced in Perl, although that
> experience is limited to the things I use daily.
>
> I wrote the same script in both Perl and Python, and the output is
> identical. The run speed is similar (very fast) and the line count is
> similar.
>
> Now that they're both working, I was looking at the code and wondering
> what Perl-specific and Python-specific improvements to the code would
> look like, as judged by others more knowledgeable in the individual
> languages.

Hi Shawn, there is a web page that gives examples from Perl's
Datastructures Cookbook re-implemented in Python. It might be of help
for future Python projects:
  http://wiki.python.org/moin/PerlPhrasebook

- Paddy.


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


Re: print a ... z, A ... Z, "\n"' in Python

2007-03-03 Thread Alex Martelli
js  <[EMAIL PROTECTED]> wrote:

> HI guys,
> 
> How do you write Perl's
> 
> print a ... z, A ... Z,  "\n"' in Python
> 
> In Python?

This specific one is easy, though this doesn't generalize:

import string
print string.lowercase + string.uppercase

For the general case, there's no way to avoid calling chr and ord,
because a string in Python doesn't have a "natural successor". So the
only issue is how you prefer to hide those calls &c (in some class or
function) and you already received suggestions on that.


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


Re: print a ... z, A ... Z, "\n"' in Python

2007-03-03 Thread Alex Martelli
js  <[EMAIL PROTECTED]> wrote:

> I forgot to cc pythonlist...
> #
> 
> Thanks for you quick reply.
> 
> I didn't know any string constants.
> 
> >From Python Library reference, 4.1.1 String constants:
> 
> letters
>The concatenation of the strings lowercase and uppercase described below.
>   The specific value is locale-dependent, and will be updated when
> locale.setlocale() is called.
> 
> Great...

If you want to ensure ASCII is used independently of the locale, that's
what string.ascii_letters (and string.ascii_lowercase &c) is for.


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


Randomizing in Python

2007-03-03 Thread [EMAIL PROTECTED]
 I want to randomize a certain calculation in Python but haven't
figured it out yet. To explain what i mean, I' m going to use an
example:
I want to get the numbers to do a random
experience database for a game. What would be necessary to do so?

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


qcombobox.findtext and matchflags.matchendswith

2007-03-03 Thread borntonetwork
Hi.

Using the PyQt4 library, I am trying to use the following
function("cbo" is a qtcombobox):

cbo.findText(searchStr, QtCore.MatchEndsWith)

If I don't use the "QtCore.MatchEndsWith", the function works
properly, but doesn't return partial matches ending with "searchStr".
If I use "QtCore.MatchEndsWith", I get the following error:

AttributeError: 'module' object has no attribute 'MatchEndsWith'

I've tried substituting the actual number that the enumerator
represents, which gives me a typeerror message complaining that the
argument has an invalid type.

Any suggestions?

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


Re: Randomizing in Python

2007-03-03 Thread Mark Nenadov
On Sat, 03 Mar 2007 08:46:09 -0800, [EMAIL PROTECTED] wrote:

>  I want to randomize a certain calculation in Python but haven't
> figured it out yet. To explain what i mean, I' m going to use an
> example:
> I want to get the numbers to do a random
> experience database for a game. What would be necessary to do so?


Look into the random module (http://docs.python.org/lib/module-random.html)

random.choice selects a random item out of a sequence
random.shuffle shuffles a sequence randomly
random.random gives a random floating point number

-- 
Mark Nenadov -> skype: marknenadov, web: http://www.marknenadov.com
-> "Relying on the government to protect your privacy is like asking a
peeping tom to install your window blinds." -- John Perry Barlow

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


Re: qcombobox.findtext and matchflags.matchendswith

2007-03-03 Thread Phil Thompson
On Saturday 03 March 2007 4:52 pm, borntonetwork wrote:
> Hi.
>
> Using the PyQt4 library, I am trying to use the following
> function("cbo" is a qtcombobox):
>
> cbo.findText(searchStr, QtCore.MatchEndsWith)
>
> If I don't use the "QtCore.MatchEndsWith", the function works
> properly, but doesn't return partial matches ending with "searchStr".
> If I use "QtCore.MatchEndsWith", I get the following error:
>
> AttributeError: 'module' object has no attribute 'MatchEndsWith'
>
> I've tried substituting the actual number that the enumerator
> represents, which gives me a typeerror message complaining that the
> argument has an invalid type.
>
> Any suggestions?

QtCore.Qt.MatchEndsWith

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


Re: Perl and Python, a practical side-by-side example.

2007-03-03 Thread Jussi Salmela
Shawn Milo kirjoitti:
>  
> I am not looking for the smallest number of lines, or anything else
> that would make the code more difficult to read in six months. Just
> any instances where I'm doing something inefficiently or in a "bad"
> way.
> 
> I'm attaching both the Perl and Python versions, and I'm open to
> comments on either. The script reads a file from standard input and
> finds the best record for each unique ID (piid). The best is defined
> as follows: The newest expiration date (field 5) for the record with
> the state (field 1) which matches the desired state (field 6). If
> there is no record matching the desired state, then just take the
> newest expiration date.
> 

I don't know if this attempt satisfies your criteria but here goes!

This is not a rewrite of your program but was created using your problem
description above. I've not included the reading of the data because it 
has not much to do with the problem per se.

#
input = [
 "aaa\tAAA\t...\t...\t...\t20071212\tBBB\n",
 "aaa\tAAA\t...\t...\t...\t20070120\tAAA\n",
 "aaa\tAAA\t...\t...\t...\t20070101\tAAA\n",
 "aaa\tAAA\t...\t...\t...\t20071010\tBBB\n",
 "aaa\tAAA\t...\t...\t...\t2007\tBBB\n",
 "ccc\tAAA\t...\t...\t...\t20071201\tBBB\n",
 "ccc\tAAA\t...\t...\t...\t20070101\tAAA\n",
 "ccc\tAAA\t...\t...\t...\t20071212\tBBB\n",
 "ccc\tAAA\t...\t...\t...\t20071212\tAAA\n",
 "bbb\tAAA\t...\t...\t...\t20070101\tAAA\n",
 "bbb\tAAA\t...\t...\t...\t20070101\tAAA\n",
 "bbb\tAAA\t...\t...\t...\t20071212\tAAA\n",
 "bbb\tAAA\t...\t...\t...\t20070612\tAAA\n",
 "bbb\tAAA\t...\t...\t...\t20071212\tBBB\n",
 ]

input = [x[:-1].split('\t') for x in input]
recs = {}
for row in input:
 recs.setdefault(row[0], []).append(row)

for key in recs:
 rows = recs[key]
 rows.sort(key=lambda x:x[5], reverse=True)
 for current in rows:
 if current[1] == current[6]:
 break
 else:
 current = rows[0]
 print '\t'.join(current)
#


The output is:

aaa AAA ... ... ... 20070120AAA
bbb AAA ... ... ... 20071212AAA
ccc AAA ... ... ... 20071212AAA

and it is the same as the output of your original code on this data.
Further testing would naturally be beneficial.

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


Re: class attrdict

2007-03-03 Thread Andrew Coffman
Could you do something like this?

class attrdict(dict):
 def __getattr__(self, attr):
 if self.has_key(attr):
 return self[attr]
 else:
 message = "'attrdict' object has no attribute '%s'" % attr
 raise AttributeError, message

If you have a dict item with the same name as a method in the class, you 
won't be able to get to it using syntax sugar, though.

It doesn't seem that the syntax sugar saves you much typing anyway 
(a.foo vs. a['foo']), but perhaps it seems nicer in some aesthetic sense.

- Andrew Coffman


Alex Martelli wrote:
> MonkeeSage <[EMAIL PROTECTED]> wrote:
> 
> 
>>On Mar 2, 9:25 pm, [EMAIL PROTECTED] (Alex Martelli) wrote:
>>
>>>The problem is mostly that, given an instance a of attrdict, whether you
>>>can call (e.g.) a.update(foo) depends on whether you ever set
>>>a['update'], making the whole program extremely fragile -- a very high
>>>price to pay for some modest amount of syntax sugar.
>>
>>How about something like...
>>
>>class attrdict(dict):
>>def __init__(self, *args, **kwargs):
>>dict.__init__(self, *args, **kwargs)
>>for k, v in self.items():
>>dict.__setattr__(self, str(k), v)
>>def __setitem__(self, k, v):
>>dict.__setitem__(self, k, v)
>>dict.__setattr__(self, str(k), v)
>>__setattr__ = __setitem__
> 
> 
> Same problem: after x=attrdict(), x.update(foo) will work for a while,
> then suddenly stop working after some innocuous loop such as:
> for bah in yech: x[bah] = 23
> when one of the items in yech just happens to be the word 'update'
> (similar issues with words such as 'get', 'pop', 'clear', etc, etc).
> 
> Miscegenation between attributes and items *inevitably* sucks.
> 
> 
> Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


py2exe: LoadLibrary(pythondll) failed

2007-03-03 Thread zxo102
Hi there,
   I py2exe my test.py  as test.exe with a lot of dll and pyc in that
directory. If I move the test.exe into another directory and run it
from there, it gives me an error " LoadLibrary(pythondll) failed...
python24.dll".  How can I set it up correctly for this test.exe to
run?   Thanks.

Ouyang

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

How to set docstrings for extensions supporting PyNumberMethods?

2007-03-03 Thread Nick Alexander
Hello,

I am writing a python extension (compiled C code) that defines an
extension type with PyNumberMethods.  Everything works swimmingly,
except I can't deduce a clean way to set the docstring for tp_*
methods.  That is, I always have

type.__long__.__doc__ == 'x.__long__() <==> long(x)'

which a quick glance at the Python 2.5 source shows is the default.

I have found that I can use PyObject_GetAttr and PyWrapperDescrObject
and set the descriptor objects d_base->doc to a char pointer... but I
can't tell if this is safe.  Or the right way to do it.

If I'm on the wrong list, please let me know!
Thanks,
Nick Alexander

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


Re: class attrdict

2007-03-03 Thread Alex Martelli
Andrew Coffman <[EMAIL PROTECTED]> wrote:

> Could you do something like this?
> 
> class attrdict(dict):
>  def __getattr__(self, attr):
>  if self.has_key(attr):
>  return self[attr]
>  else:
>  message = "'attrdict' object has no attribute '%s'" % attr
>  raise AttributeError, message
> 
> If you have a dict item with the same name as a method in the class, you
> won't be able to get to it using syntax sugar, though.

Yes.  In __setattr__, you can choose what to do in that case (it doesn't
seem to make sense to be able to *assign* to foo.get without being able
to *access* as foo.get whatever you've assigned).

> It doesn't seem that the syntax sugar saves you much typing anyway 
> (a.foo vs. a['foo']), but perhaps it seems nicer in some aesthetic sense.

It would be nice, yes, weren't it for the inevitable irregularity, one
way or another, caused by the clash between attributes and items.

If, instead of subclassing dict, one wrapped it (and properly coded just
a few specialmethods, no ordinary ones), the overall effect could be
more regular (probably still with some limitation, since the dict does
need to be kept somewhere, and keys clashing with the special methods'
names would still have to be forbidden or otherwise specialcased).


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


Re: print a ... z, A ... Z, "\n"' in Python

2007-03-03 Thread rzed
[EMAIL PROTECTED] (Alex Martelli) wrote in
news:[EMAIL PROTECTED]: 

> js  <[EMAIL PROTECTED]> wrote:
> 
>> HI guys,
>> 
>> How do you write Perl's
>> 
>> print a ... z, A ... Z,  "\n"' in Python
>> 
>> In Python?
> 
> This specific one is easy, though this doesn't generalize:
> 
> import string
> print string.lowercase + string.uppercase
> 
> For the general case, there's no way to avoid calling chr and
> ord, because a string in Python doesn't have a "natural
> successor". So the only issue is how you prefer to hide those
> calls &c (in some class or function) and you already received
> suggestions on that. 
> 

No ord or chr in sight:

# Inclusive character range. 
def pycrange(lo,hi):
import string
chars = string.letters + " "
rstr = ''
lp = chars.find(lo)
hp = chars.find(hi)
if lp < hp:
rstr = chars[lp:hp+1]
return rstr

print pycrange('c','n')


Lame code, though.

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


Re: pyHook or SetWindowsHookEx

2007-03-03 Thread sturlamolden
On Mar 2, 7:01 pm, "abcd" <[EMAIL PROTECTED]> wrote:
> :(

The answer depends on which GUI library you use.

E.g. if you use MFC there is an object called win32ui.PyCWnd that has
methods for hooking key strokes.

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


Re: classes and functions

2007-03-03 Thread Arnaud Delobelle
On Mar 2, 11:01 pm, Nicholas Parsons <[EMAIL PROTECTED]>
wrote:
> Hi Claire,
>
> That is the beauty of using Python.  You have a choice of using  
> classes and traditional OOP techniques or sticking to top level  
> functions.  For short, small scripts it would probably be overkill to  
> use classes.  Yet the programmer still has classes in his tool chest  
> if he/she is writing code that is going to be reused in larger  
> projects.

Exactly the same thing can be said about Lisp, C++, Perl, PHP, and no
doubt many other languages that I don't know ;)
(Well I guess C++ programs are not called 'scripts')

--
Arnaud

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


pop method question

2007-03-03 Thread Nicholas Parsons
Howdy Folks,

I was just playing around in IDLE at the interactive prompt and typed  
in dir({}) for the fun of it.  I was quite surprised to see a pop  
method defined there.  I mean is that a misnomer or what?  From the  
literature, pop is supposed to be an operation defined for a stack  
data structure.  A stack is defined to be an "ordered" list data  
structure.  Dictionaries in Python have no order but are sequences.   
Now, does anyone know why the python core has this pop method  
implemented for a dictionary type?

I realize that in this context it is used for removing a specific key  
from the current dictionary object.  But why call it pop and not  
something more intuitive like remove or delete?

Thanks for the clarification in advance :).

--Nick




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


Re: pop method question

2007-03-03 Thread Stefan Scholl
Nicholas Parsons <[EMAIL PROTECTED]> wrote:
> I realize that in this context it is used for removing a specific key  
> from the current dictionary object.  But why call it pop and not  
> something more intuitive like remove or delete?

I wasn't a python programmer back than, but I'd guess it's
because pop not just removes the key, it returns the value as
well.


-- 
Web (en): http://www.no-spoon.de/ -*- Web (de): http://www.frell.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pop method question

2007-03-03 Thread Paul Rubin
Nicholas Parsons <[EMAIL PROTECTED]> writes:
> I was just playing around in IDLE at the interactive prompt and typed
> in dir({}) for the fun of it.  I was quite surprised to see a pop
> method defined there.  I mean is that a misnomer or what?  From the
> literature, pop is supposed to be an operation defined for a stack
> data structure.  A stack is defined to be an "ordered" list data
> structure.  Dictionaries in Python have no order but are sequences.
> Now, does anyone know why the python core has this pop method
> implemented for a dictionary type?

Try typing: 

  help({}.pop)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pop method question

2007-03-03 Thread Nicholas Parsons

On Mar 3, 2007, at 3:49 PM, Paul Rubin wrote:

> Nicholas Parsons <[EMAIL PROTECTED]> writes:
>> I was just playing around in IDLE at the interactive prompt and typed
>> in dir({}) for the fun of it.  I was quite surprised to see a pop
>> method defined there.  I mean is that a misnomer or what?  From the
>> literature, pop is supposed to be an operation defined for a stack
>> data structure.  A stack is defined to be an "ordered" list data
>> structure.  Dictionaries in Python have no order but are sequences.
>> Now, does anyone know why the python core has this pop method
>> implemented for a dictionary type?
>
> Try typing:
>
>   help({}.pop)
> --  
> http://mail.python.org/mailman/listinfo/python-list

Thanks, that gives a more details explanation of what the behavior is  
but doesn't answer my question above :(

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


Re: qcombobox.findtext and matchflags.matchendswith

2007-03-03 Thread borntonetwork
On Mar 3, 12:17 pm, Phil Thompson <[EMAIL PROTECTED]>
wrote:
> On Saturday 03 March 2007 4:52 pm,borntonetworkwrote:
>
>
>
> > Hi.
>
> > Using the PyQt4 library, I am trying to use the following
> > function("cbo" is a qtcombobox):
>
> > cbo.findText(searchStr, QtCore.MatchEndsWith)
>
> > If I don't use the "QtCore.MatchEndsWith", the function works
Thank you!

> > properly, but doesn't return partial matches ending with "searchStr".
> > If I use "QtCore.MatchEndsWith", I get the following error:
>
> > AttributeError: 'module' object has no attribute 'MatchEndsWith'
>
> > I've tried substituting the actual number that the enumerator
> > represents, which gives me a typeerror message complaining that the
> > argument has an invalid type.
>
> > Any suggestions?
>
> QtCore.Qt.MatchEndsWith
>
> Phil


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


portable Python ifconfig

2007-03-03 Thread Bart Van Loon
Hi all,

I'm looking for a portable (FreeBSD and Linux) way of getting typical
ifconfig information into Python.

Some research on the web brought me to Linux only solutions

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439094
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439093

which I didn't manage to port to FreeBSD (I'm not that experienced).
Finally though, I found out about pyifconfig:

http://mail.python.org/pipermail/python-list/1999-August/009274.html

which compiles fine on Linux after changing  to
. On FreeBSD there is no SIOCGIFHWADDR, so I
just commented out that part. 

I can now do

In [1]: from pyifconfig import pyifconfig

In [2]: pyifconfig('ath0')
Out[2]:
{'addr': '192.168.50.104',
 'brdaddr': '192.168.50.255',
 'hwaddr': '00:17:f2:4c:a5:0c',
 'netmask': '255.255.255.0'}

on Linux, and

In [1]: from pyifconfig import pyifconfig

In [2]: pyifconfig('vr1')
Out[2]:
{'addr': '192.168.50.1',
 'brdaddr': '192.168.50.255',
 'hwaddr': '\xff\xff',
 'netmask': '255.255.255.0'}

on FreeBSD.

The problem now is that I get seemingly random information when I pass a
non-existing interface, a down interface or an empty string to
pyifconfig, which is very hard to figure out from inside a script:

In [3]: pyifconfig('foobar')
Out[3]:
{'addr': '104.154.165.183',
 'brdaddr': '104.154.165.183',
 'hwaddr': '00:00:68:9a:a5:b7',
 'netmask': '104.154.165.183'}

so, any pointers here on how I can go on from this point?

any help is appreciated

-- 
regards,
BBBart

   Wormwood : Calvin, how about you?  
   Calvin : Hard to say ma'am. I think my cerebellum just fused.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Questions about app design - OOP with python classes

2007-03-03 Thread Steven D'Aprano
On Fri, 02 Mar 2007 09:30:20 +0100, Diez B. Roggisch wrote:

>> A type system doesn't help. So what if they're both floats? The test
>> is still bogus, your code will still wait too long to engage the
>> retro-rockets, and the billion dollar space craft will still be travelling
>> at hundreds of miles an hour when it reaches the surface of Mars.
> 
> A type system _could_ help. 

It's easy to wave your hands and say that Microsoft could have done
something different, but they had to work with what they had, not some
hypothetical alternative language with a hypothetical type system that
didn't exist then (if it even exists now).


> Multi-Level-Specification allows you to 
> express physical quantities with their respective unit, and operations 
> on them to yield the combined unit at compile-time. There are some 
> rather complicated cases where simple unification won't solve the 
> type-equations, but then you might annotate things explicitly.

Which is what Apps Hungarian _is_.


-- 
Steven.

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


Re: py2exe: LoadLibrary(pythondll) failed

2007-03-03 Thread Sick Monkey

(1)  You may want to read the following links:
http://docs.python.org/dist/describing-extensions.html#SECTION00234

which came from:
http://docs.python.org/dist/dist.html

Here is another good resource for py2exe:
http://www.py2exe.org/index.cgi/GeneralTipsAndTricks

(2) Also, you maybe interested in PyInstaller which can wrap up everything
in one functioning exe.
http://pyinstaller.python-hosting.com/

"Single file: build a single executable file, totally self-contained, which
runs without any external dependency."

On 3 Mar 2007 10:37:19 -0800, zxo102 <[EMAIL PROTECTED]> wrote:


Hi there,
   I py2exe my test.py  as test.exe with a lot of dll and pyc in that
directory. If I move the test.exe into another directory and run it
from there, it gives me an error " LoadLibrary(pythondll) failed...
python24.dll".  How can I set it up correctly for this test.exe to
run?   Thanks.

Ouyang


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

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

are there any "Piecewise Cubic Hermite Interpolating Polynomial" in python

2007-03-03 Thread jitasi
Hi all

I want to use the matlab function "pchip" in python.
I have checked the scipy, but there is only spline Interpolating.
Are there any pchip Interpolating in python?

Thanks
Steven

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


Re: class attrdict

2007-03-03 Thread MonkeeSage
On Mar 3, 1:29 pm, [EMAIL PROTECTED] (Alex Martelli) wrote:
> It would be nice, yes, weren't it for the inevitable irregularity, one
> way or another, caused by the clash between attributes and items.

In thinking about it, I think this might fall under 'we're all
consenting adults here'. I mean, you can shadow the dict constructor
from the toplevel if you're so inclined (or don't know any better).
But you could make it harder to accidentally shadow builtin
attributes:

from warnings import warn
class attrdict(dict):
__builtins__ = dir(dict)
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
for k, v in self.items():
dict.__setattr__(self, str(k), v)
def __setitem__(self, k, v):
if k in self.__builtins__:
warn('shadowing builtin attribute: %s' % k,
RuntimeWarning, 2)
dict.__setitem__(self, k, v)
dict.__setattr__(self, str(k), v)
__setattr__ = __setitem__

a = attrdict([(1,2)], a=3, b=4)
a.update = 'test'

Regards,
Jordan

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


Python FTP server down

2007-03-03 Thread John Nagle
"ftp://ftp.python.org/pub/"; is returning "Connection Refused" today.

Does that ever work?  I need FTP access to download onto a colocated
server.


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


Re: Questions about app design - OOP with python classes

2007-03-03 Thread Paul Rubin
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> > Multi-Level-Specification allows you to 
> > express physical quantities with their respective unit, and operations 
> > on them to yield the combined unit at compile-time. There are some 
> > rather complicated cases where simple unification won't solve the 
> > type-equations, but then you might annotate things explicitly.
> Which is what Apps Hungarian _is_.

I think the idea is that the compiler can still check that your
annotations are correct, or at least consistent, even if it can't
solve the equations itself.  Hungarian notation is a variable naming
convention which can be followed manually but which the compiler makes
no attempt to enforce.

Diez, can you suggest any online references about MLS?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: py2exe: LoadLibrary(pythondll) failed

2007-03-03 Thread Thomas Heller
zxo102 schrieb:
> Hi there,
>I py2exe my test.py  as test.exe with a lot of dll and pyc in that
> directory. If I move the test.exe into another directory and run it
> from there, it gives me an error " LoadLibrary(pythondll) failed...
> python24.dll".  How can I set it up correctly for this test.exe to
> run?   Thanks.
> 
> Ouyang
> 
> 

The test.exe created by py2exe relies on everything else in the dist directory,
so you must copy these files as well.

Thomas

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

Re: pop method question

2007-03-03 Thread Steven D'Aprano
On Sat, 03 Mar 2007 15:56:39 -0500, Nicholas Parsons wrote:

> 
> On Mar 3, 2007, at 3:49 PM, Paul Rubin wrote:
> 
>> Nicholas Parsons <[EMAIL PROTECTED]> writes:
>>> I was just playing around in IDLE at the interactive prompt and typed
>>> in dir({}) for the fun of it.  I was quite surprised to see a pop
>>> method defined there.  I mean is that a misnomer or what?  From the
>>> literature, pop is supposed to be an operation defined for a stack
>>> data structure.  A stack is defined to be an "ordered" list data
>>> structure.  Dictionaries in Python have no order but are sequences.
>>> Now, does anyone know why the python core has this pop method
>>> implemented for a dictionary type?
>>
>> Try typing:
>>
>>   help({}.pop)
>> --  
>> http://mail.python.org/mailman/listinfo/python-list
> 
> Thanks, that gives a more details explanation of what the behavior is  
> but doesn't answer my question above :(

Just because pop can be defined for an ordered stack doesn't mean pop
can't be generalized to other data types too.

I personally don't see that pop has any advantage, especially since the
most useful example

while some_dict:
do_something_with(some_dict.pop()) 

doesn't work. Instead you have to write this:

for key in some_dict.keys(): 
# can't iterate over the dictionary directly!
do_something_with(some_dict.pop(key))

which is hardly any saving over:

for key in some_dict.keys(): 
# can't iterate over the dictionary directly!
do_something_with(some_dict[key])
del some_dict[key]


To my mind, having to supply a key to dict.pop makes it rather pointless.


-- 
Steven.

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


Re: cyclic iterators ?

2007-03-03 Thread MRAB
On Mar 3, 1:27 am, Paul Rubin  wrote:
> "Tool69" <[EMAIL PROTECTED]> writes:
> > I've tried something like this to have a cyclic iterator without
> > sucess:
>
> > def iterate_mylist(my_list):
> > k = len((my_list)
> > i=0
> > while i <= k :
> > yield my_list[i]
> > i += 1
> > i = 0
> > yield my_list[0]
>
> > I missed something, but I don't know what exactly.
>
> As Bruno says, you can use itertools.cycle, but the problem above is
> that you're not looping repeatedly through the list; you yield all the
> elements, then yield the first element again, then stop.  So for
> ['a','b','c']  you'd yield the sequence a,b,c,a.
>
> I'd rewrite the above something like:
>
>   def iterate_mylist(my_list):
>  while True:
>for m in my_list:
>   yield m
>
> This just loops through the list over and over again.
>
Another problem is that it should be i < k, not i <= k.

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


Re: pop method question

2007-03-03 Thread jim-on-linux
On Saturday 03 March 2007 15:56, Nicholas Parsons 
wrote:
> On Mar 3, 2007, at 3:49 PM, Paul Rubin wrote:
> > Nicholas Parsons <[EMAIL PROTECTED]> 
writes:
> >> I was just playing around in IDLE at the
> >> interactive prompt and typed in dir({}) for
> >> the fun of it.  I was quite surprised to see
> >> a pop method defined there.  I mean is that
> >> a misnomer or what?  From the literature,
> >> pop is supposed to be an operation defined
> >> for a stack data structure.  A stack is
> >> defined to be an "ordered" list data
> >> structure.  Dictionaries in Python have no
> >> order but are sequences. Now, does anyone
> >> know why the python core has this pop method
> >> implemented for a dictionary type?


aDict.pop(theKey)
  'produce the value'

pop removes the  key:value  and produces the value 
as results

jim-on-linux
http:\\www.inqvista.com




> >
> > Try typing:
> >
> >   help({}.pop)
> > --
> > http://mail.python.org/mailman/listinfo/pytho
> >n-list
>
> Thanks, that gives a more details explanation
> of what the behavior is but doesn't answer my
> question above :(
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Questions about app design - OOP with python classes

2007-03-03 Thread Steven D'Aprano
On Thu, 01 Mar 2007 21:53:09 -0800, Paul Rubin wrote:

> Steven D'Aprano <[EMAIL PROTECTED]> writes:
>> > That still sounds like an unreliable manual type system, 
>> It's unreliable in the sense that the coder has to follow the naming
>> convention, and must have some bare minimum of sense. If your coders are
>> morons, no naming convention will save you. (For that matter, nothing will
>> save you.)
> 
> Well, type systems in programming languages have generally proven more
> reliable and easier to deal with than having programmers track it all
> manually-- that's why we don't all write in Forth ;-).

Apps Hungarian is NOT a type system.

Systems Hungarian is. It is pointless: an inefficient, manual nuisance
that redundantly does what the type system already does. Even Microsoft
agrees with that now.

Unless there is a type system that can automatically deal with the
semantic difference between (say) screen coordinates and window
coordinates, or between height and width, or safe and unsafe strings, the
coder still has to deal with it themselves.

And even if there is such a type system, Python isn't it.

[snip]
> You're right that this is not exactly dimensional analysis, but it still
> seems to call for types and conversion functions, rather than naming
> conventions.

The problem with types is that as far as the compiler is concerned, the
objects are the same type. Of course it needs conversion functions. 

Now maybe you could argue that what Microsoft needed was a different
language instead of C. Maybe so, but they were working with what they
had. Just as we're working with Python.

The point I'm trying to get across isn't that Apps Hungarian is the best
imaginable solution to the problem of dealing with semantically different
kinds of data. But it is an easy solution that works quite well (not
perfectly) and (unlike relying on Haskell's type system) it can be
applied to Python quite easily.



-- 
Steven.

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


Re: pop method question

2007-03-03 Thread Steven D'Aprano
On Sat, 03 Mar 2007 18:13:18 -0500, jim-on-linux wrote:

> On Saturday 03 March 2007 15:56, Nicholas Parsons 
> wrote:
>> On Mar 3, 2007, at 3:49 PM, Paul Rubin wrote:
>> > Nicholas Parsons <[EMAIL PROTECTED]> 
> writes:
>> >> I was just playing around in IDLE at the
>> >> interactive prompt and typed in dir({}) for
>> >> the fun of it.  I was quite surprised to see
>> >> a pop method defined there.  I mean is that
>> >> a misnomer or what?  From the literature,
>> >> pop is supposed to be an operation defined
>> >> for a stack data structure.  A stack is
>> >> defined to be an "ordered" list data
>> >> structure.  Dictionaries in Python have no
>> >> order but are sequences. Now, does anyone
>> >> know why the python core has this pop method
>> >> implemented for a dictionary type?
> 
> 
> aDict.pop(theKey)
>   'produce the value'
> 
> pop removes the  key:value  and produces the value 
> as results


Amazing. Absolutely amazing. Just goes to show that the ability to use
Linux doesn't require the sense to READ THE REST OF THE POST BEFORE
HITTING SEND. Not even the rest of the thread, just the post.

The Original Poster already knows that.


-- 
Steven.

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


Re: pop method question

2007-03-03 Thread James Stroud
Steven D'Aprano wrote:
> I personally don't see that pop has any advantage, especially since the
> most useful example
> 
> while some_dict:
> do_something_with(some_dict.pop()) 
> 
> doesn't work. Instead you have to write this:
> 
> for key in some_dict.keys(): 
> # can't iterate over the dictionary directly!
> do_something_with(some_dict.pop(key))
> 
> which is hardly any saving over:
> 
> for key in some_dict.keys(): 
> # can't iterate over the dictionary directly!
> do_something_with(some_dict[key])
> del some_dict[key]
> 
> 
> To my mind, having to supply a key to dict.pop makes it rather pointless.
> 
> 


I've used it in something like this and found it worthwhile:

for akey in dict1:
   if some_condition(akey):
 dict2[akey] = dict2.pop(akey)

Which necessitates a key is a little cleaner than your latter example.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Questions about app design - OOP with python classes

2007-03-03 Thread Paul Rubin
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> Unless there is a type system that can automatically deal with the
> semantic difference between (say) screen coordinates and window
> coordinates, or between height and width, or safe and unsafe strings, the
> coder still has to deal with it themselves.
> 
> And even if there is such a type system, Python isn't it.

Python uses runtime typing, so you'd define classes for screen and
window coordinates, and have them do appropriate conversions or raise
exceptions when you do mixed operations.  The compiler wouldn't notice
this happening at compile time, but that's just like the rest of
Python.

> The point I'm trying to get across isn't that Apps Hungarian is the best
> imaginable solution to the problem of dealing with semantically different
> kinds of data. But it is an easy solution that works quite well (not
> perfectly) and (unlike relying on Haskell's type system) it can be
> applied to Python quite easily.

I think the notion above fits ok into Python's dynamic typing scheme.
Yeah, you may get runtime exceptions at unexpected times due to type
conflicts that you overlooked in testing, but again, the Pythonic
prescription for these and other errors seems to be "write more tests".

Maybe we can concoct a cross between Python and Haskell, and call it
"Paskell" after the philosopher Blaise ;-).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pop method question

2007-03-03 Thread Paul Rubin
James Stroud <[EMAIL PROTECTED]> writes:
> for akey in dict1:
>if some_condition(akey):
>  dict2[akey] = dict2.pop(akey)
> 
> Which necessitates a key is a little cleaner than your latter example.

Yeah, I also think removing keys from a dict while iterating over it
(like in Steven's examples) looks a bit dangerous dangerous.

Assuming you meant "dict1.pop" instead ot dict2.pop above, your
example might be written

dict2 = dict((k, dict1.pop(k)) for k in dict1 if some_condition(k))

avoiding some namespace pollution etc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Problem with returning prime number in a simple calculation program

2007-03-03 Thread QHorizon
Hello, I'm new to Python (I've learned everything up to iterators so
far) and fairly new to Programming.  This would be my first real
program:

#Coordinate Geometry (The whole program is not shown)

import math
import sys

print "Welcome to the Coordinate Geometry Calculator!"
print "Type 'terms' for a list of commands"

def main():
print
command = raw_input("Command? ")
if command == "terms":
terms()
main()
elif command == "distance":
distance()
main()
elif command == "slope":
slope()
main()
elif command == "endpoint":
endpoint()
main()
elif command == "midpoint":
midpoint()
main()
elif command == "prime":
prime()
main()
elif command == "quit":
sys.exit
else:
print "Not a valid command"
main()

#...Declaring functions here...

def prime():
num = input("Number ")
i = num - 1
divcounter = 0
while i > 1:
if num % i != 0:
divcounter += 1
i -= 1
if divcounter == num - 2:
print num, "is a prime number"
else:
print num, "is not a prime number"

#Start the program
main()

As it says in the title, I'm having trouble with the prime number
function.  It will print the sentence if the number is prime, but it
if isn't, the program goes into a state in the terminal where the
program never ends and you can just keep on typing.  Maybe the else
statement is ineffective?  Any ideas on how to fix this?

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


Re: pop method question

2007-03-03 Thread Steven D'Aprano
On Sat, 03 Mar 2007 23:22:10 +, James Stroud wrote:

>> To my mind, having to supply a key to dict.pop makes it rather pointless.
>> 
>> 
> 
> 
> I've used it in something like this and found it worthwhile:
> 
> for akey in dict1:
>if some_condition(akey):
>  dict2[akey] = dict2.pop(akey)

Surely that's a no-op? You pop the value, than add it back again.

Or do you mean dict2[akey] = dict1.pop(akey)?

If so, are you sure that works? When I try it, I get "RuntimeError:
dictionary changed size during iteration". You would need to take a copy
of the keys and iterate over that.

for key in dict1.keys():
if some_condition(key):
dict2[key] = dict1.pop(key)



-- 
Steven.

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


Re: Eric on XP for Newbie

2007-03-03 Thread SPE - Stani's Python Editor
On Mar 1, 11:39 am, [EMAIL PROTECTED] wrote:
> Thanks guys
>
> Found this on another blog and it seems to work - you need to run theSPE.pyo 
> file ...

Which blog? Can yo point me to the url?

Stani


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


Re: Problem with returning prime number in a simple calculation program

2007-03-03 Thread Bjoern Schliessmann
[EMAIL PROTECTED] wrote:
> [reformatted indentation]
> def prime():
> num = input("Number ")
> i = num - 1
> divcounter = 0
> while i > 1:
> if num % i != 0
> divcounter += 1 
> i -= 1
> if divcounter == num - 2:
> print num, "is a prime number"
> else:
> print num, "is not a prime number"
> [...]
> As it says in the title, I'm having trouble with the prime number
> function.  It will print the sentence if the number is prime, but
> it if isn't, the program goes into a state in the terminal where
> the program never ends and you can just keep on typing.  

Sure thing. You designed the function to behave this way.

Look at the while loop -- especially think what happens if 
(num % i == 0). i will never be decremented then and the function
will not terminate.

Try inserting print statements for debugging if you don't get what I
meant here.

> Maybe the else statement is ineffective?

No one can read your thoughts. In which way effective?

Regards,


Björn

-- 
BOFH excuse #86:

Runt packets

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


logging into forms on an ssl server using python

2007-03-03 Thread socialanxiety
Hi, I need some help, I'm trying to create a script that will fill in
the forms on an ssl website, and submit them. Could anyone help me
out, examples would be  nice.
Thanks in advance

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


Re: pop method question

2007-03-03 Thread Steven D'Aprano
On Sat, 03 Mar 2007 15:36:14 -0800, Paul Rubin wrote:

> James Stroud <[EMAIL PROTECTED]> writes:
>> for akey in dict1:
>>if some_condition(akey):
>>  dict2[akey] = dict2.pop(akey)
>> 
>> Which necessitates a key is a little cleaner than your latter example.
> 
> Yeah, I also think removing keys from a dict while iterating over it
> (like in Steven's examples) looks a bit dangerous dangerous.

It is dangerous. That's why I didn't do it.

I very carefully iterated over a list, not the dictionary, and in fact put
in a comment explicitly saying that you can't iterate over the dictionary:

for key in some_dict.keys(): 
# can't iterate over the dictionary directly!
do_something_with(some_dict.pop(key))


If you try to iterate over the dictionary directly, you get a RuntimeError
exception when the dictionary changes size. Unfortunately, the exception
isn't raised until AFTER the dictionary has changed size.

>>> D = {1:1, 2:2}
>>> for key in D:
... D.pop(key)
...
1
Traceback (most recent call last):
  File "", line 1, in 
RuntimeError: dictionary changed size during iteration
>>> D
{2: 2}


That's a gotcha to watch out for: the exception isn't raised until
the damage is done.



> Assuming you meant "dict1.pop" instead ot dict2.pop above, your
> example might be written
> 
> dict2 = dict((k, dict1.pop(k)) for k in dict1 if some_condition(k))
> 
> avoiding some namespace pollution etc.

You get a RuntimeError exception when dict1 changes size.

You know, if I were easily offended, I'd be offended that you accused _me_
of writing dangerous code when my code both worked and worked safely,
while your code failed and did damage when it did so (dict1 irretrievably
loses an item).

*wink*



-- 
Steven.

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


Re: pop method question

2007-03-03 Thread James Stroud
Steven D'Aprano wrote:
> On Sat, 03 Mar 2007 23:22:10 +, James Stroud wrote:
> 
>>> To my mind, having to supply a key to dict.pop makes it rather pointless.
>>>
>>>
>>
>> I've used it in something like this and found it worthwhile:
>>
>> for akey in dict1:
>>if some_condition(akey):
>>  dict2[akey] = dict2.pop(akey)
> 
> Surely that's a no-op? You pop the value, than add it back again.
> 
> Or do you mean dict2[akey] = dict1.pop(akey)?
> 
> If so, are you sure that works? When I try it, I get "RuntimeError:
> dictionary changed size during iteration". You would need to take a copy
> of the keys and iterate over that.
> 
> for key in dict1.keys():
> if some_condition(key):
> dict2[key] = dict1.pop(key)
> 
> 
> 

Yes. You are right, both in the typo and using keys().

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


Re: thread safe SMTP module

2007-03-03 Thread Aahz
In article <[EMAIL PROTECTED]>,
Gordon Messmer  <[EMAIL PROTECTED]> wrote:
>
>I believe that I've seen this discussed previously, so maybe there's
>some interest in it.  I wrote a threaded mail filtering framework
>a while ago, and one of the modules does address verification
>via SMTP.  Since smtplib.SMTP uses blocking IO, it can block the
>whole interpreter.  Sometimes the whole thing would stop working
>indefinitely.

That doesn't make any sense.  Blocking I/O generally releases the GIL,
which is the whole reason Python doesn't totally suck for threading.
There may be other thread problems, but I doubt that you have correctly
analyzed their source.  You can prove this for yourself by trying out my
threaded spider at
http://www.pythoncraft.com/OSCON2001/ThreadPoolSpider.py
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"I disrespectfully agree."  --SJM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: py2exe: LoadLibrary(pythondll) failed

2007-03-03 Thread zxo102
On 3月4日, 上午6时50分, Thomas Heller <[EMAIL PROTECTED]> wrote:
> zxo102 schrieb:
>
> > Hi there,
> >I py2exe my test.py  as test.exe with a lot of dll and pyc in that
> > directory. If I move the test.exe into another directory and run it
> > from there, it gives me an error " LoadLibrary(pythondll) failed...
> > python24.dll".  How can I set it up correctly for this test.exe to
> > run?   Thanks.
>
> > Ouyang
>
> The test.exe created by py2exe relies on everything else in the dist 
> directory,
> so you must copy these files as well.
>
> Thomas

Thanks. Let me try it.

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

Re: Problem with returning prime number in a simple calculation program

2007-03-03 Thread Steven D'Aprano
On Sat, 03 Mar 2007 15:36:36 -0800, QHorizon wrote:

> Hello, I'm new to Python (I've learned everything up to iterators so
> far) and fairly new to Programming.  This would be my first real
> program:
> 
> #Coordinate Geometry (The whole program is not shown)
> 
> import math
> import sys
> 
> print "Welcome to the Coordinate Geometry Calculator!"
> print "Type 'terms' for a list of commands"
> 
> def main():

[snip big boring series of if...elif... statements]

You're eventually going to run into a run time recursion error if you run
that for long enough. Can you see why?

A better way to do a command loop is something like this:


def bad_command():
# called when the user enters an unrecognized command
print "Unknown command, please try again"

class QuitException(Exception):
# used for exiting the loop
pass


def main():
# Make a "dispatch table" that maps the name of a command 
# (as typed by the user) with a function to call.
dispatcher = {'slope': do_slope,
  'primes': do_primes,
  'quit': do_quit,
  # ... and more here
 }
try:
# loop forever (until we jump out of it)
while True:
cmd = get_command_from_user()
# you have to write get_command_from_user yourself
func = dispatcher.get(cmd, bad_command)
result = func()
print result
except QuitException:
print "Goodbye, come again soon!"


Now you just need to define your individual functions do_slope, do_primes,
etc. The only "special" one is do_quit.

def do_quit():
raise QuitException


Now let's look at the do_primes function. (You call it "prime".)

> def prime():
>   num = input("Number ")

That's a good way to have malicious users do really, really really bad
things to your PC.

Safer is to do this:

num = int(raw_input("Number "))

>   i = num - 1
>   divcounter = 0
>   while i > 1:
>   if num % i != 0:
>   divcounter += 1
>   i -= 1

That's an inefficient algorithm, if it even works. I'm not sure that it
works, and I'm too lazy to find out :)


>   if divcounter == num - 2:
>   print num, "is a prime number"
>   else:
>   print num, "is not a prime number"

This will only work if divcounter happens to equal the original number
less two. If it equals something else, nothing will be printed.

Here's a simple algorithm to check if a number is prime.

# Warning: untested.
def do_primes():
num = int(raw_input("Number ")
if num <= 1:
return "%n is not prime" % num
if num == 2:
return "%n is prime" % num
elif num % 2 == 0:
# even numbers other than 2 aren't prime
return "%n is not prime" % num
for i in range(3, num, 2):
if num % i == 0:
return "%n is not prime" % num
return "%n is prime" % num


Now, this is deliberately not an efficient algorithm. There are things you
can do to make it more efficient, or you can re-write it completely.
The thing to remember is, don't PRINT the result, RETURN it. Your
do_primes() function should only calculate the result, and pass that
result up to the main loop for printing (or writing to a text file, or
emailing, or whatever).

Have fun!



-- 
Steven.

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


Re: pop method question

2007-03-03 Thread Raymond Hettinger
[Nicholas Parsons]
>  Dictionaries in Python have no order but are sequences.  
> Now, does anyone know why the python core has this pop method  
> implemented for a dictionary type?
>
> I realize that in this context it is used for removing a specific key  
> from the current dictionary object.  But why call it pop and not  
> something more intuitive like remove or delete?

The naming for pop() method followed from the naming of the previously
existing popitem() method.  Neither "remove" nor "delete" would have
been a good name for a method that looked-up and returned a value as
well as mutating the dictionary.  The word "pop" on the other hand
strongly suggests both retrieval and mutation.

The notion that "pop" is only defined for stack operations is somewhat
pedantic.  We have also successfully used the name for sets, dicts,
and deques (success meaning that most people just "get it" and are
able to learn, use, read the name without difficultly).

The rationale for the pop() method was that the pattern "v=d[k]; del
d[k]" could be collapsed to a single call, eliminating a two
successive look-ups of the same key.  Looking back, this rationale is
questionable because 1) the second lookup is not expensive because the
first lookup put the relevant hash entries in the cache, and 2) the
lookup/delete pattern for dictionaries does not seem to arise often in
practice (it does come-up every now and then in the context of set
operations).

There was also a notion that threaded programming would benefit by
having lookup-then-delete as an atomic transaction.  It is unknown to
me whether that purported benefit has ever been realized.


Raymond Hettinger

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


Re: portable Python ifconfig

2007-03-03 Thread MonkeeSage
On Mar 3, 3:38 pm, Bart Van Loon <[EMAIL PROTECTED]> wrote:
> I'm looking for a portable (FreeBSD and Linux) way of getting typical
> ifconfig information into Python.

Here's a pure python version of the C extension, based on the recipes
you posted. In this version, the 'addr' key will not exist for a non-
existent / non-active interface.

import socket, fcntl, struct, platform

def _ifinfo(sock, addr, ifname):
iface = struct.pack('256s', ifname[:15])
info  = fcntl.ioctl(sock.fileno(), addr, iface)
if addr == 0x8927:
hwaddr = []
for char in info[18:24]:
hwaddr.append(hex(ord(char))[2:])
return ':'.join(hwaddr)
else:
return socket.inet_ntoa(info[20:24])

def ifconfig(ifname):
ifreq = {'ifname': ifname}
infos = {}
osys  = platform.system()
sock  = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
if osys == 'Linux':
# offsets defined in /usr/include/linux/sockios.h on linux 2.6
infos['addr']= 0x8915 # SIOCGIFADDR
infos['brdaddr'] = 0x8919 # SIOCGIFBRDADDR
infos['hwaddr']  = 0x8927 # SIOCSIFHWADDR
infos['netmask'] = 0x891b # SIOCGIFNETMASK
elif 'BSD' in osys: # ???
infos['addr']= 0x8915
infos['brdaddr'] = 0x8919
infos['hwaddr']  = 0x8927
infos['netmask'] = 0x891b
try:
for k,v in infos.items():
ifreq[k] = _ifinfo(sock, v, ifname)
except:
pass
sock.close()
return ifreq

ifc = ifconfig('ath0')
if ifc.has_key('addr'):
print ifc

I'm pretty sure the offsets would be different for BSD, but I don't
have any BSD boxes to test on (looks like from a bit of googling that
you might need to look at /compat/linux/linux_ioctl.h for the offsets
on BSDs). I'll leave it to you to fill in the BSD stuff.

Regards,
Jordan

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


Re: portable Python ifconfig

2007-03-03 Thread MonkeeSage
On Mar 3, 7:17 pm, "MonkeeSage" <[EMAIL PROTECTED]> wrote:
> I'm pretty sure the offsets would be different for BSD

Then again, mabye not.

http://freebsd.active-venture.com/FreeBSD-srctree/newsrc/compat/linux/linux_ioctl.h.html

Regards,
Jordan

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


Re: print a ... z, A ... Z, "\n"' in Python

2007-03-03 Thread Alex Martelli
rzed <[EMAIL PROTECTED]> wrote:

> [EMAIL PROTECTED] (Alex Martelli) wrote in
> news:[EMAIL PROTECTED]: 
> 
> > js  <[EMAIL PROTECTED]> wrote:
> > 
> >> HI guys,
> >> 
> >> How do you write Perl's
> >> 
> >> print a ... z, A ... Z,  "\n"' in Python
> >> 
> >> In Python?
> > 
> > This specific one is easy, though this doesn't generalize:
> > 
> > import string
> > print string.lowercase + string.uppercase
> > 
> > For the general case, there's no way to avoid calling chr and
> > ord, because a string in Python doesn't have a "natural
> > successor". So the only issue is how you prefer to hide those
> > calls &c (in some class or function) and you already received
> > suggestions on that. 
> 
> No ord or chr in sight:
> 
> # Inclusive character range. 
> def pycrange(lo,hi):
> import string
> chars = string.letters + " "
> rstr = ''
> lp = chars.find(lo)
> hp = chars.find(hi)
> if lp < hp:
> rstr = chars[lp:hp+1]
> return rstr
> 
> print pycrange('c','n')
> 
> 
> Lame code, though.

Very (the very existence of rstr and the if block are redundant, for
example; "return chars[lp:hp+1]" will already return an empty string
when lp > hp, and it's weird for the result to be empty for equal
arguments lo and hi when it's a length-two string for arguments, say,
'a' and 'b').

Also incorrect, presumably, since it would e.g. consider pycrange('w',
'C') to be 'wxyzABC', rather than empty (as an ord/chr based solution
would) or 'wxyz' (as I believe Perl does for 'w'...'C' -- one of those
black-magical Perl things, unless they've changed it recently) -- in
ASCII, uppercase letters come before lowercase ones, but in
string.letters they're vice versa.

Sure, you can get a complete 256-char ASCII alphabet with
alp=string.maketrans('', ''), use alp.find(x) as roughly equivalent to
ord(x) and alp[y] as roughly equivalent to chr(y), and thus (or by
sillier tricks yet) you wouldn't _formally_ "be calling chr and ord"
(you'd instead use roughly equivalent but slower and murkier idioms).
However, my point was: you can't avoid transforming from characters to
numbers and back again (ord and chr are just the "one obvious way" to do
that -- correct, if you want ASCII, readable, direct, and fast).  .find
and indexing (instead of ord and chr) do give you more flexibility (to
use an underlying order that's not ASCII's) should you need that; and
slicing an appropriate string does avoid an explicit loop.

(Just trying to forestall further silliness...): other ways to avoid
"calling chr and ord" include abusing modules struct and array.


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


Re: class attrdict

2007-03-03 Thread Alex Martelli
MonkeeSage <[EMAIL PROTECTED]> wrote:

> On Mar 3, 1:29 pm, [EMAIL PROTECTED] (Alex Martelli) wrote:
> > It would be nice, yes, weren't it for the inevitable irregularity, one
> > way or another, caused by the clash between attributes and items.
> 
> In thinking about it, I think this might fall under 'we're all
> consenting adults here'. I mean, you can shadow the dict constructor
> from the toplevel if you're so inclined (or don't know any better).
> But you could make it harder to accidentally shadow builtin
> attributes:
> 
> from warnings import warn
> class attrdict(dict):
> __builtins__ = dir(dict)
> def __init__(self, *args, **kwargs):
> dict.__init__(self, *args, **kwargs)
> for k, v in self.items():
> dict.__setattr__(self, str(k), v)
> def __setitem__(self, k, v):
> if k in self.__builtins__:
> warn('shadowing builtin attribute: %s' % k,
> RuntimeWarning, 2)
> dict.__setitem__(self, k, v)
> dict.__setattr__(self, str(k), v)
> __setattr__ = __setitem__
> 
> a = attrdict([(1,2)], a=3, b=4)
> a.update = 'test'

Besides missing the warning in the __init__, this also has pretty weird
behavior whenever subject to a .pop, .update, .setdefault, del of either
item or attr, etc, etc: the attributes and items "get out of sync" (and,
catching each and every mutating-method to keep the separate dicts of
items and attrs in perfect sync is somewhat of a nightmare).

If the consenting adults in question WANT totally murky, irregular,
buggy behavior hiding under every corner -- why are they using Python in
the first place?  It's so much easier to make such utter messes in other
languages, after all.

It's impossible to make something foolproof, because fools are so
ingenious; Python tends to keep them at bay by cultural forces (a strong
collective bias towards simplicity, regularity, correctness).  The
neverending quest to confuse attributes and items (inevitably leading to
complications, irregularity, and bugs) is better pursued in other
languages -- just about ANY other language except Python.


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


Re: class attrdict

2007-03-03 Thread MonkeeSage
On Mar 3, 7:54 pm, [EMAIL PROTECTED] (Alex Martelli) wrote:
> Besides missing the warning in the __init__, this also has pretty weird
> behavior whenever subject to a .pop, .update, .setdefault, del of either
> item or attr, etc, etc: the attributes and items "get out of sync" (and,
> catching each and every mutating-method to keep the separate dicts of
> items and attrs in perfect sync is somewhat of a nightmare).

Good points. There are many complexities involved, and little actual
gain. Saving three or four chars isn't worth all the trouble. I hadn't
fully thought-out the situation.

Regards,
Jordan

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


Re: pop method question

2007-03-03 Thread Alex Martelli
Steven D'Aprano <[EMAIL PROTECTED]> wrote:
   ...
> while some_dict:
> do_something_with(some_dict.pop()) 
> 
> doesn't work. Instead you have to write this:

You have to use .popitem for this -- that's what's it's for...


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


Re: pop method question

2007-03-03 Thread Alex Martelli
Raymond Hettinger <[EMAIL PROTECTED]> wrote:
   ...
> The notion that "pop" is only defined for stack operations is somewhat
> pedantic.

Worse: it's totally wrong.  It's also defined for eyes, as a musical
genre, as a kind of soda, as an avant-garde artistic movement of the
'50s, for baloons, as a parent of the male persuasion, for email
reading, and moreover it's often used to refer to Persistent Organic
Pollutants or Points Of Presence -- not forgetting weasels, either.


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


Re: pyHook or SetWindowsHookEx

2007-03-03 Thread Jordan
On Feb 27, 9:01 am, "abcd" <[EMAIL PROTECTED]> wrote:
> I am having trouble with pyHook on python 2.4.1.  Basically I have a
> python app that uses pyHook to capture keyboard events and write them
> straight to a file.  The application is running as a service on a
> windows machine.  If I am at that windows machine the application
> works just fine, logging my keystrokes.  However, if I use Remote
> Desktop to connect to the machine and open up say Notepad it doesn't
> capture the keystrokes.  Is this a problem with pyHook?  or is it he
> way Windows handles the events?
>
> Is there a way to setup my own hook without pyHook using just python?
> i think the function I am interested in is SetWindowsHookEx.
>
> Thanks in advance.

I'm pretty sure it's not a problem with pyHook.  I'm also fairly sure
that you can't log the keystrokes of someone who is logged onto your
machine from another; that would be a major security flaw.  The only
way (I think) this would work is if you wrote your own remote desktop
program that logged keystrokes, and then sent it to the remote
computer when logging off.

Cheers,
Jordan

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


Re: class attrdict

2007-03-03 Thread Alex Martelli
MonkeeSage <[EMAIL PROTECTED]> wrote:

> On Mar 3, 7:54 pm, [EMAIL PROTECTED] (Alex Martelli) wrote:
> > Besides missing the warning in the __init__, this also has pretty weird
> > behavior whenever subject to a .pop, .update, .setdefault, del of either
> > item or attr, etc, etc: the attributes and items "get out of sync" (and,
> > catching each and every mutating-method to keep the separate dicts of
> > items and attrs in perfect sync is somewhat of a nightmare).
> 
> Good points. There are many complexities involved, and little actual
> gain. Saving three or four chars isn't worth all the trouble. I hadn't
> fully thought-out the situation.

You make a good point.  I do like being able to say foo.bar=baz rather
than foo['bar']=baz in certain cases -- not so much to save 3 chars, but
to avoid excessive punctuation; however, I don't really need this AND
all of dict's power at the same time, so, I don't inherit from dict:-).


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


Re: portable Python ifconfig

2007-03-03 Thread MonkeeSage
Bart,

Can you try this and let us know if it works for FreeBSD?

import socket, fcntl, struct

def _ifinfo(sock, addr, ifname):
iface = struct.pack('256s', ifname[:15])
info  = fcntl.ioctl(sock.fileno(), addr, iface)
if addr == 0x8927:
hwaddr = []
for char in info[18:24]:
hwaddr.append(hex(ord(char))[2:])
return ':'.join(hwaddr)
else:
return socket.inet_ntoa(info[20:24])

def ifconfig(ifname):
ifreq = {'ifname': ifname}
sock  = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
ifreq['addr']= _ifinfo(sock, 0x8915, ifname) # SIOCGIFADDR
ifreq['brdaddr'] = _ifinfo(sock, 0x8919, ifname) #
SIOCGIFBRDADDR
ifreq['netmask'] = _ifinfo(sock, 0x891b, ifname) #
SIOCGIFNETMASK
ifreq['hwaddr']  = _ifinfo(sock, 0x8927, ifname) #
SIOCSIFHWADDR
except:
pass
sock.close()
return ifreq

Regards,
Jordan

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


Re: pop method question

2007-03-03 Thread Nicholas Parsons
Hi Raymond,

Thank you for your clarification below.  I was just using "remove"  
and "delete" as possible alternatives to the name "pop" without much  
contemplation.  Like you say below, it begs the question as to why  
not have two separate operations for dictionaries (retrieval of value  
from key followed by deletion of key) instead of one method.

I'm not sure I agree with you said about the pedantic usage of pop.   
I would rather have a term mean one thing instead of several causing  
ambiguity.  Just from my computer science background when I see pop 
(), I think of a stack data structure.  Why muddle the waters by  
introducing another meaning for the term?  There are plenty of other  
words to use that could describe the behavior exhibited by the  
dictionary operation of removing a key and returning its value.  The  
notion of a stack and pop() and push() methods for it are very  
important from a historical perspective and is not just some fad.

But then again, there are other examples of ambiguity in the python  
language such as allowing operators like '+' to be overloaded.  Why  
not just have a "add()" method like Java?  Of course Java does cheat  
a little by overloading the '+' operator for string objects but that  
is a built-in feature of language.  Also some people find '+' more  
appealing to the eye than a method call like add() in their code.

Even in the case of C, we have some ambiguity with the dangling if  
statement.  So I guess you can't win for trying :).

Just call me a purist and think of me as someone who likes  
consistency.  Python is here to stay and no language is perfect...

--Nick

On Mar 3, 2007, at 7:32 PM, Raymond Hettinger wrote:

> [Nicholas Parsons]
>>  Dictionaries in Python have no order but are sequences.
>> Now, does anyone know why the python core has this pop method
>> implemented for a dictionary type?
>>
>> I realize that in this context it is used for removing a specific key
>> from the current dictionary object.  But why call it pop and not
>> something more intuitive like remove or delete?
>
> The naming for pop() method followed from the naming of the previously
> existing popitem() method.  Neither "remove" nor "delete" would have
> been a good name for a method that looked-up and returned a value as
> well as mutating the dictionary.  The word "pop" on the other hand
> strongly suggests both retrieval and mutation.
>
> The notion that "pop" is only defined for stack operations is somewhat
> pedantic.  We have also successfully used the name for sets, dicts,
> and deques (success meaning that most people just "get it" and are
> able to learn, use, read the name without difficultly).
>
> The rationale for the pop() method was that the pattern "v=d[k]; del
> d[k]" could be collapsed to a single call, eliminating a two
> successive look-ups of the same key.  Looking back, this rationale is
> questionable because 1) the second lookup is not expensive because the
> first lookup put the relevant hash entries in the cache, and 2) the
> lookup/delete pattern for dictionaries does not seem to arise often in
> practice (it does come-up every now and then in the context of set
> operations).
>
> There was also a notion that threaded programming would benefit by
> having lookup-then-delete as an atomic transaction.  It is unknown to
> me whether that purported benefit has ever been realized.
>
>
> Raymond Hettinger
>
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


distutils - script install check file existence before copy?

2007-03-03 Thread [EMAIL PROTECTED]
Not sure if it is possible to do this - I know distutils has "force"
option that can be turned on/off for install_data, but is it possible
to do something somewhat complicated - have a data file named YYY,
need to copy it to share/script/YYY only if share/script/YYY does not
already exist, otherwise, need to copy YYY to share/script/YYY.new

Does anyone have any hints on how to go about doing this?

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


Re: pop method question

2007-03-03 Thread MonkeeSage
Nick,

In regards to stack-like objects, pop() implies mutation of the
reciever and returning the item 'popped' off the stack. The same
_semantic_ meaning can be used for pop() regarding dictionaries, even
though the _implementation_ would be different: dict.pop(key) mutates
the reciever and returns the value associated with the key.

Regards,
Jordan

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


running warnings

2007-03-03 Thread memcached
I wrote these codes pieces:
 
try:
import termios, TERMIOS
except  ImportError:
try:
import  msvcrt
except  ImportError:
try:
from EasyDialogs import  AskPassword
except  ImportError:
getpass =  default_getpass
else:
getpass = AskPassword
else:
getpass =  win_getpass
else:
getpass =  unix_getpass
 
 
When running I got the error warnings:
 
/usr/lib/python2.3/TERMIOS.py:7: DeprecationWarning: the TERMIOS module is  
deprecated; please use termios
DeprecationWarning)
Traceback (most  recent call last):
File "t2.py", line 18, in ?
getpass = unix_getpass
NameError: name 'unix_getpass' is not defined
 
 
Can you tell me what're there warnings and how to avoid  them?Thanks!
** AOL now offers free 
email to everyone.  Find out more about what's free from AOL at 
http://www.aol.com.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Non Sequitur

2007-03-03 Thread Ben Finney
Dennis Lee Bieber <[EMAIL PROTECTED]> writes:

> """
>   I before E
>   Except after C
>   Or when sounded as A
>   As in Neighbor and Weigh
> """

Yes, like the "A" sound in "weird" or "ceiling".

-- 
 \"Most people don't realize that large pieces of coral, which |
  `\   have been painted brown and attached to the skull by common |
_o__) wood screws, can make a child look like a deer."  -- Jack Handey |
Ben Finney

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


Re: portable Python ifconfig

2007-03-03 Thread Bart Van Loon
It was 3 Mar 2007 18:43:57 -0800, when MonkeeSage wrote:
> Bart,
>
> Can you try this and let us know if it works for FreeBSD?

thanks for you suggestions!

> import socket, fcntl, struct
>
> def _ifinfo(sock, addr, ifname):
> iface = struct.pack('256s', ifname[:15])
> info  = fcntl.ioctl(sock.fileno(), addr, iface)
> if addr == 0x8927:
> hwaddr = []
> for char in info[18:24]:
> hwaddr.append(hex(ord(char))[2:])
> return ':'.join(hwaddr)
> else:
> return socket.inet_ntoa(info[20:24])
>
> def ifconfig(ifname):
> ifreq = {'ifname': ifname}
> sock  = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
> try:
> ifreq['addr']= _ifinfo(sock, 0x8915, ifname) # SIOCGIFADDR
> ifreq['brdaddr'] = _ifinfo(sock, 0x8919, ifname) #
> SIOCGIFBRDADDR
> ifreq['netmask'] = _ifinfo(sock, 0x891b, ifname) #
> SIOCGIFNETMASK
> ifreq['hwaddr']  = _ifinfo(sock, 0x8927, ifname) #
> SIOCSIFHWADDR
> except:
> pass
> sock.close()
> return ifreq

apparenlty, it doesn't. :-(

I changes the except block into

except Exception, e:
print e

and added

if __name__ == '__main__':
 print ifconfig('ng0')
 print ifconfig('vr0')
 print ifconfig('vr2')
 print ifconfig('xl0')

ng0 exists and has an IP (virtual interface created by mpd)
vr0 exists but does not have an IP (phisical interface for mpd)
vr2 exists and has an IP configured
xl0 does not exist

output:

[Errno 25] Inappropriate ioctl for device
{'ifname': 'ng0'}
[Errno 25] Inappropriate ioctl for device
{'ifname': 'vr0'}
[Errno 25] Inappropriate ioctl for device
{'ifname': 'vr2'}
[Errno 25] Inappropriate ioctl for device
{'ifname': 'xl0'}

however, in Linux I get the following results:

[Errno 99] Cannot assign requested address
{'ifname': 'eth0'}
{'hwaddr': '0:17:f2:4c:a5:c', 'ifname': 'ath0', 'netmask': '255.255.255.0', 
'addr': '192.168.50.104', 'brdaddr': '192.168.50.255'}
{'hwaddr': '0:0:0:0:0:0', 'ifname': 'tun0', 'netmask': '255.255.255.255', 
'addr': '192.168.3.6', 'brdaddr': '0.0.0.0'}
[Errno 19] No such device
{'ifname': 'wielewoele'}

which seems 100% correct.

-- 
regards,
BBBart

   Susie: You'd get a good grade without doing any work.  
   Calvin: So?  
   Susie: It's wrong to get rewards you haven't earned.  
   Calvin: I've never heard of anyone who couldn't live with that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python 2.5 incompatible with Fedora Core 6 - packaging problems again

2007-03-03 Thread John Nagle
   I've been installing Python and its supporting packages on
a dedicated server with Fedora Core 6 for about a day now.
This is a standard dedicated rackmount server in a colocation
facility, controlled via Plesk control panel, and turned over
to me with Fedora Core 6 in an empty state.  This is the
standard way you get a server in a colo today.

   Bringing Python up in this completely clean environment is
a huge hassle, and it doesn't really work.

   Fedora Core 6 ships with Python 2.4, which appears to be a
good decision on someone's part.  Of course, there's no
standard RPM for a Python 2.5 install on Linux.  Packaging is
someone else's problem, according to the Python developers.
So it's necessary to build from source.  And the "python.org"
FTP server is down, so even getting the source onto a remote
server is a pain.  So I have to download it on another machine
and bring it over with FTP.

   Trying to install Python 2.5 yields at least the following problems:

   Fedora Core 6 comes with GCC 4.1.1, but the README file
with Python 2.5 says this:

GCC 4.1,
GCC 4.2: There is a known incompatibility between Python and GCC,
  where GCC 4.1 and later uses an interpretation of C
  different to earlier GCC releases in an area where the C
  specification has undefined behaviour (namely, integer arithmetic
  involving -sys.maxint-1).

  As a consequence, compiling Python with GCC 4.1/4.2 is not
  recommended. It is likely that this problem will be resolved
  in future Python releases. As a work-around, it seems that
  adding -fwrapv to the compiler options restores the earlier
  GCC behaviour.

OK, given that, presumably "./configure" takes care of that problem,
right?  Anybody know for sure?

"make" runs fine after "./configure".

But "make install" does some compiles, something "install" probably
shouldn't be doing.  Some of these compiles fail, with error messages
like 
"/var/www/vhosts/sitetruth.com/private/downloads/python/Python-2.5/Modules/_curses_panel.c:271:
 
error: "PyCursesPanelObject" has no member named "pan"

But the install script plunges blindly on, presumably installing a broken
Python 2.5.  Apparently Fedora Core 6 doesn't come with "curses" preinstalled,
but the Python installer assumes it is there.  What's inexcusable is
just plowing on after failed compiles, resulting in a broken install.

It's probably necessary to install something before building Python,
but the README file is silent on this.

 OK.  Plunging onward, and not really needing the "curses" library,
we try to install MySQLdb.  We get that with FTP,
unpack it, go to the approprate directory, and run "python setup.py".
This fails because the MySQL headers aren't installed:

"_mysql.c:35:23: error: my_config.h: No such file or directory"

OK, looks like we need to install "mysql-devel", so we do that,
using "yum".   This forces an update of OpenSSL, Kerberos, and
"e2fsprogs-dev".  Which means we should reboot at some point.

But now we can build MySQLdb.  So we build and install it.

So then we try "import MySQLdb" in Python 2.5.  And we get this:

> /usr/local/lib/python2.5/site-packages/MySQL_python-1.2.2-py2.5-linux-i686.egg/_mysql.py:3:
>  UserWarning: Module _mysql was already imported from 
> /usr/local/lib/python2.5/site-packages/MySQL_python-1.2.2-py2.5-linux-i686.egg/_mysql.pyc,
>  but 
> /var/www/vhosts/sitetruth.com/private/downloads/MySQLdb/MySQL-python-1.2.2 is 
> being added to sys.path
>   import sys, pkg_resources, imp
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "MySQLdb/__init__.py", line 19, in 
> import _mysql
>   File "build/bdist.linux-i686/egg/_mysql.py", line 7, in 
>   File "build/bdist.linux-i686/egg/_mysql.py", line 4, in __bootstrap__
>   File 
> "/usr/local/lib/python2.5/site-packages/setuptools-0.6c5-py2.5.egg/pkg_resources.py",
>  line 800, in resource_filename
>   File 
> "/usr/local/lib/python2.5/site-packages/setuptools-0.6c5-py2.5.egg/pkg_resources.py",
>  line 1228, in get_resource_filename
>   File 
> "/usr/local/lib/python2.5/site-packages/setuptools-0.6c5-py2.5.egg/pkg_resources.py",
>  line 1250, in _extract_resource
>   File 
> "/usr/local/lib/python2.5/site-packages/setuptools-0.6c5-py2.5.egg/pkg_resources.py",
>  line 880, in get_cache_path
>   File 
> "/usr/local/lib/python2.5/site-packages/setuptools-0.6c5-py2.5.egg/pkg_resources.py",
>  line 846, in extraction_error
> pkg_resources.ExtractionError: Can't extract file(s) to egg cache
> 
> The following error occurred while trying to extract file(s) to the Python egg
> cache:
> 
>   [Errno 13] Permission denied: '/var/www/vhosts/sitetruth.com/.python-eggs'
> 
> The Python egg cache directory is currently set to:
> 
>   /var/www/vhosts/sitetruth.com/.python-eggs
> 
> Perhaps your account does not have write access to this directory?  You can
> change the cache directory by setting the PYTHON_EGG_CACHE environment
> v

Re: Non Sequitur

2007-03-03 Thread Alex Martelli
Ben Finney <[EMAIL PROTECTED]> wrote:

> Dennis Lee Bieber <[EMAIL PROTECTED]> writes:
> 
> > """
> > I before E
> > Except after C
> > Or when sounded as A
> > As in Neighbor and Weigh
> > """
> 
> Yes, like the "A" sound in "weird" or "ceiling".

"ceiling" falls under the "except after C" exception.

"weird" is, of course, weird (as most of English)...


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


Re: Questions about app design - OOP with python classes

2007-03-03 Thread John Nagle
Steven D'Aprano wrote:
> On Fri, 02 Mar 2007 09:30:20 +0100, Diez B. Roggisch wrote:
> 
> 
>>>A type system doesn't help. So what if they're both floats? The test
>>>is still bogus, your code will still wait too long to engage the
>>>retro-rockets, and the billion dollar space craft will still be travelling
>>>at hundreds of miles an hour when it reaches the surface of Mars.
>>
>>A type system _could_ help. 
> 
> 
> It's easy to wave your hands and say that Microsoft could have done
> something different, but they had to work with what they had, not some
> hypothetical alternative language with a hypothetical type system that
> didn't exist then (if it even exists now).

 The Pascal/Ada/Modula family of languages all had type systems
with restrictions on conversion.  Unlike C, types in Pascal
are not simply abbreviations of the type; they're unique types.

 This turns out to be too restrictive, but it's certainly been
tried.

 There are C++ class libraries that understand units.  And
the conversion factors can be dealt with at compile time, so
the overhead goes away.

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


Re: are there any "Piecewise Cubic Hermite Interpolating Polynomial" inpython

2007-03-03 Thread Terry Reedy

"jitasi" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Hi all
|
| I want to use the matlab function "pchip" in python.
| I have checked the scipy, but there is only spline Interpolating.
| Are there any pchip Interpolating in python?

Putting p.. c.. h.. i.. p... Python into Google gives 165 results.  Have 
you checked any?




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