cross-compile PIL

2006-05-16 Thread NicolasP
Hello,

I need to compile PIL (python imaging library) package for an ARM based linux 
system.
Does anyone can tell me how to do this ?

Thanks

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


Re: A Unicode problem -HELP

2006-05-16 Thread Ben Finney
"manstey" <[EMAIL PROTECTED]> writes:

> 1. Here is my input data file, line 2:
> gn1:1,1.2 R")$I73YT R")[EMAIL PROTECTED]

Your program is reading this using the 'utf-8' encoding. When it does
so, all the characters you show above will be read in happily as you
see them (so long as you view them with the 'utf-8' encoding), and
converted to Unicode characters representing the same thing.

Do you have any other information that might indicate this is *not*
utf-8 encoded data?

> 2. Here is my output data file, line 2:
> u'gn', u'1', u'1', u'1', u'2', u'-', u'R")$I73YT', u'R")$IYT',
> u'R")$IYT', u'@', u'ncfsa', u'nc', '', '', '', u'f', u's', u'a', '',
> '', '', '', '', '', '', '', u'B.:R")$I^YT', u'b.:cv)cv^yc', '\xc9\x94'

As you can see, reading the file with 'utf-8' encoding and writing it
out again as 'utf-8' encoding, the characters (as you posted them in
the message) have been faithfully preserved by Unicode processing and
encoding.


Bear in mind that when you present the "input data file, line 2" to
us, your message is itself encoded using a particular character
encoding. (In the case of the message where you wrote the above, it's
'utf-8'.) This means we may or may not be seeing the exact same bytes
you see in the input file; we're seeing characters in the encoding you
used to post the message.

You need to know what encoding was used when the data in that file was
written. You can then read the file using that encoding, and convert
the characters to unicode for processing inside your program. When you
write them out again, you can choose the 'utf-8' encoding as you have
done.

Have you read this excellent article on understanding the programming
implications of character sets and Unicode?

"The Absolute Minimum Every Software Developer Absolutely,
Positively Must Know About Unicode and Character Sets (No
Excuses!)"
http://www.joelonsoftware.com/articles/Unicode.html>

-- 
 \ "I'd like to see a nude opera, because when they hit those high |
  `\   notes, I bet you can really see it in those genitals."  -- Jack |
_o__)   Handey |
Ben Finney

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


Re: A Unicode problem -HELP

2006-05-16 Thread Tim Roberts
"manstey" <[EMAIL PROTECTED]> wrote:
>
>I have done more reading on unicode and then tried my code in IDLE
>rather than WING IDE, and discovered that it works fine in IDLE, so I
>think WING has a problem with unicode.

Rather, its output defaults to ASCII.

>So, assuming I now work in IDLE, all I want help with is how to read in
>an ascii string and convert its letters to various unicode values and
>save the resulting 'string' to a utf-8 text file. Is this clear?
>
>so in pseudo code
>1.  F is converted to \u0254, $ is converted to \u0283, C is converted
>to \u02A6\02C1, etc.
>(i want to do this using a dictionary TRANSLATE={'F':u'\u0254', etc)
>2. I read in a file with lines like:
>F$
>FCF$
>$$C$ etc
>3. I convert this to
>\u0254\u0283
>\u0254\u02A6\02C1\u0254 etc
>4. i save the results in a new file
>
>when i read the new file in a unicode editor (EmEditor), i don't see
>\u0254\u02A6\02C1\u0254, but I see the actual characters (open o, esh,
>ts digraph, modified letter reversed glottal stop, etc.

Of course.  Isn't that exactly what you wanted?  The Python string
u"\u0254" contains one character (Latin small open o).  It does NOT contain
6 characters.  If you write that to a file, that file will contain 1
character -- 2 bytes.

If you actually want the 6-character string \u0254 written to a file, then
you need to escape the \u special code:  "\\u0254".  However, I don't see
what good that would do you.  The \u escape is a Python source code thing.

>I'm sure this is straightforward but I can't get it to work.

I think it is working exactly as you want.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Unicode problem -HELP

2006-05-16 Thread Martin v. Löwis
manstey wrote:
>   a=str(word_info + parse + gloss).encode('utf-8')
>   a=a[1:len(a)-1]
> 
> Is this clearer?

Indeed. The problem is your usage of str() to "render" the output.
As word_info+parse+gloss is a list (or is it a tuple?), str() will
already produce "Python source code", i.e. an ASCII byte string
that can be read back into the interpreter; all Unicode is gone
from that string. If you want comma-separated output, you should
do this:

def comma_separated_utf8(items):
result = []
for item in items:
result.append(item.encode('utf-8'))
return ", ".join(result)

and then
 a = comma_separated_utf8(word_info + parse + gloss)

Then you don't have to drop the parentheses from a anymore, as
it won't have parentheses in the first place.

As the encoding will be done already in the output file,
the following should also work:

  a = u", ".join(word_info + parse + gloss)

This would make "a" a comma-separated unicode string, so that
the subsequent output_file.write(a) encodes it as UTF-8.

If that doesn't work, I would like to know what the exact
value of gloss is, do

  print "GLOSS IS", repr(gloss)

to print it out.

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


Re: assignment in a for loop

2006-05-16 Thread Ben Finney
"MackS" <[EMAIL PROTECTED]> writes:

> Thank you for your reply.

A pleasure to help.

> > What's preventing the use of list comprehensions?
> >
> > new_list = [x+1 for x in old_list]
> 
> Suppose I want to do anything as trivial as modify the values of the
> list members _and_ print their new values. List comprehensions must
> not contain statements, I think.

You're correct, but that's because you're creating a new list, not
modifying the existing one. The list comprehension can do anything you
like to generate each element, so long as it's an expression::

>>> foo = [3, 5, 8]
>>> print [x+1 for x in foo]
[4, 6, 9]
>>> print [x**2 for x in foo]
[9, 25, 64]
>>> print [str(x**2) for x in foo]
['9', '25', '64']
>>> print [len(str(x**2)) for x in foo]
[1, 2, 2]

If it's too complex to be readable in a single expression, make it a
function which returns a value, since calling a function is itself an
expression::

>>> def get_result_of_complex_stuff(n):
... quad = n**4
... if len(str(quad)) % 2:
... word = "spam"
... else:
... word = "eggs"
... result = word.strip("s").title()
... return result
...
>>> foo = [3, 5, 8]
>>> print [get_result_of_complex_stuff(x) for x in foo]
['Egg', 'Pam', 'Egg']

Once you have your new list being created by a list comprehension, do
what you like with it. If you want it to be stored, assigned back to
the original name, each value printed, or whatever you like, then do
so::

>>> bar = [get_result_of_complex_stuff(x) for x in foo]
>>> foo = bar
>>> for x in foo:
... print x,
...
Egg Pam Egg

-- 
 \  "One time a cop pulled me over for running a stop sign. He |
  `\said, 'Didn't you see the stop sign?' I said, 'Yeah, but I |
_o__) don't believe everything I read.'"  -- Steven Wright |
Ben Finney

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


Re: python vs perl lines of code

2006-05-16 Thread Edward Elliott
Ala Qumsieh wrote:

> Btw, do you include space chars that go toward indentating Python code
> in your count? If not, you should since they are required. Not so for
> Perl.

All chars are counted on lines which are counted.  The perl and python
versions use the same amount and type of indentation, which in this case is
tab characters.  In any case, I wouldn't strip the whitespace out of the
perl code just because it's unnecessary for the interpreter.  How people
deal with code is far more interesting than how machines do, and for us
whitespace is necessary (not strictly, but a really really good idea).

-- 
Edward Elliott
UC Berkeley School of Law (Boalt Hall)
complangpython at eddeye dot net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Unicode problem -HELP

2006-05-16 Thread manstey
OK, I apologise for not being clearer.

1. Here is my input data file, line 2:
gn1:1,1.2 R")$I73YT R")[EMAIL PROTECTED]

2. Here is my output data file, line 2:
u'gn', u'1', u'1', u'1', u'2', u'-', u'R")$I73YT', u'R")$IYT',
u'R")$IYT', u'@', u'ncfsa', u'nc', '', '', '', u'f', u's', u'a', '',
'', '', '', '', '', '', '', u'B.:R")$I^YT', u'b.:cv)cv^yc', '\xc9\x94'

3. Here is my main program:
# -*- coding: UTF-8 -*-
import codecs

import splitFunctions
import surfaceIPA

# Constants for file location

# Working directory constants
dir_root = 'E:\\'
dir_relative = '2 Core\\2b Data\\Data Working\\'

# Input file constants
input_file_name = 'in.grab.txt'
input_file_loc = dir_root + dir_relative + input_file_name
# Initialise input file
input_file = codecs.open(input_file_loc, 'r', 'utf-8')

# Output file constants
output_file_name = 'out.grab.txt'
output_file_loc = dir_root + dir_relative + output_file_name
# Initialise output file
output_file = codecs.open(output_file_loc, 'w', 'utf-8') # unicode

i = 0
for line in input_file:
if line[0] != '>': # Ignore headers
i += 1
if i != 1:
word_info = splitFunctions.splitGrab(line, i)
parse=splitFunctions.splitParse(word_info[10])

gloss=surfaceIPA.surfaceIPA(word_info[6],word_info[8],word_info[9],parse)
a=str(word_info + parse + gloss).encode('utf-8')
a=a[1:len(a)-1]
output_file.write(a)
output_file.write('\n')

input_file.close()
output_file.close()

print 'done'


4. Here is my problem:
At the end of my output file, where my unicode character \u0254 (OPEN
O) appears, the file has '\xc9\x94'

What I want is an output file like:

'gn', '1', '1', '1', '2', '-', . 'ɔ'

where ɔ is an open O, and would display correctly in the appropriate
font.

Once I can get it to display properly, I will rewrite gloss so that it
returns a proper translation of 'R")$I73YT', which will be a string of
unicode characters.

Is this clearer? The other two functions are basic. splitGrab turns
'gn1:1,1.2 R")$I73YT R")[EMAIL PROTECTED]' into 'gn 1 1 1 2 R")$I73YT R")$IYT
@ ncfsa' and splitParse turns the final piece of this 'ncfsa' into 'n c
f s a'. They have to be done separately as splitParse involves some
translation and program logic. SurfaceIPA reads in 'R")$I73YT' and
other data to produce the unicode string. At the moment it just returns
two dummy strings and u'\u0254'.encode('utf-8').

All help is appreciated!

Thanks

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

Re: assignment in a for loop

2006-05-16 Thread MackS
Thank you for your reply.


> > 1) Is what I wrote above (minimally) correct?
>
> Correct for what? You can tell if it's *syntactically* correct by
> simply running it.
>
> As for any other "correct", define that. Does it do what you want it
> to do?

I was referring to my attempted explanation, not the code snippet.

> [...]
>
> What's preventing the use of list comprehensions?
>
> new_list = [x+1 for x in old_list]

Suppose I want to do anything as trivial as modify the values of the
list members _and_ print their new values. List comprehensions must not
contain statements, I think. 


Mack

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


Re: python vs perl lines of code

2006-05-16 Thread Edward Elliott
Charles DeRykus wrote:

> This subject thread  may be of great interest but I think an language
> advocacy mailing  list would be a better forum.

Fair enough, but advocacy isn't at all what I'm after.  Anecdotes are fine,
after all what is data but a collection of anecdotes? :)  Seriously,
anecdotes are valuable: they give you another perspective, reflect common
wisdom, and can tell you what/where/how to look for hard data.  Of course
if anyone already has hard data that would be welcome too, but it's hard to
even pin down what 'hard data' means in this situation.

I'll grant you though, asking for non-value-judgement-laden anecdotes on
newsgroups may be asking too much.

-- 
Edward Elliott
UC Berkeley School of Law (Boalt Hall)
complangpython at eddeye dot net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: assignment in a for loop

2006-05-16 Thread Ben Finney
"MackS" <[EMAIL PROTECTED]> writes:

[MackS, please don't top-post.]

> Suppose I want to do modify all arguments which are passed to a
> function. Do I need to use a list comprehension such as
> 
> def f(arg1,arg2,arg3):
> 
>  arg1,arg2,arg3 = [i+1 for i in (arg1,arg2,arg3)]
>  ...
> 
> This would be awful when, eg, one adds an argument to the function
> definition. It would require edition of the code at two different
> locations.

If you anticipate increasing the number of values passed to the
function, and you're doing the same operation on all of them, why not
pass in a list::

>>> def add_one_to_each(nums):
... """ Makes a new list with each value incremented by one. """
...
... incremented_nums = [x+1 for x in nums]
... return incremented_nums
...
>>> foo = [3, 5, 8]
>>> bar = add_one_to_each(foo)
>>> bar
[4, 6, 9]

-- 
 \ "Some mornings, it's just not worth chewing through the leather |
  `\  straps."  -- Emo Philips |
_o__)  |
Ben Finney

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


Re: A Unicode problem -HELP

2006-05-16 Thread Martin v. Löwis
manstey wrote:
> input_file = open(input_file_loc, 'r')
> output_file = open(output_file_loc, 'w')
> for line in input_file:
> output_file.write(str(word_info + parse + gloss))  # = three
> functions that return tuples
> 
> (u'F', u'\u0254')  are two of the many unicode tuple elements returned
> by the three functions.
> 
> What am I doing wrong?

Well, the primary problem is that you don't tell us what you are really
doing. For example, it is very hard to believe that this is the actual
code that you are running:

If word_info, parse, and gloss are functions, the code should read

input_file = open(input_file_loc, 'r')
output_file = open(output_file_loc, 'w')
for line in input_file:
output_file.write(str(word_info() + parse() + gloss()))

I.e. you need to call the functions for this code to make any sense.
You have probably chosen to edit the code in order to not show us
your real code. Unfortunately, since you are a newbie in Python,
you make errors in doing so, and omit important details. That makes
it very difficult to help you.

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


Re: assignment in a for loop

2006-05-16 Thread Ben Finney
"MackS" <[EMAIL PROTECTED]> writes:

> >>> l = [1,2]
> >>> for i in l:
> ... i = i + 1
> ...
> >>> l
> [1, 2]
> 
> I understand (I think!) that this is due to the fact that in Python
> what looks like "assignment" really is binding a name to an
> object. The result is that inside the loop I am creating an object
> with value (i+1) and then "pointing" the name i at it. Therefore,
> the object to which i previously pointed (an element of list l)
> remains unchanged.

That's a fair explanation, yes.

> Two brief questions:
> 
> 1) Is what I wrote above (minimally) correct?

Correct for what? You can tell if it's *syntactically* correct by
simply running it.

As for any other "correct", define that. Does it do what you want it
to do?

> 2) Independently of the answer to 1, is there a way for me to assign
> to elements of a list inside a loop and without resorting to C-style
> ugliness of
> 
> for i in range(len(l))
>  l[i] = l[i] + 1

You can build a new list from your operations on the old one.

new_list = []
for x in old_list:
new_list.append(x+1)

You can also do it more succinctly with a list comprehension
expression.

> (Note: not using a list comprehension.)

What's preventing the use of list comprehensions?

new_list = [x+1 for x in old_list]

-- 
 \  "Smoking cures weight problems. Eventually."  -- Steven Wright |
  `\   |
_o__)  |
Ben Finney

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


Re: python vs perl lines of code

2006-05-16 Thread Ala Qumsieh
Edward Elliott wrote:
> John Bokma wrote:
>>
>>Without seeing the actual code this is quite meaningless.
> 
> 
> Evaluating my experiences yes, relating your own no.

Well, quality of code is directly related to its author. Without knowing 
the author personally, or at least seeing the code, your anecdote 
doesn't really mean anything.

A colleague of mine, who is efficient at programming, and pretty decent 
at Perl, routinely does something like:

   if ($var =~ /something and something else/) {
 $var =~ /(something) and (something else)/;
 my $match1 = $1;
 my $match2 = $2;
 ...
   }

Needless to say, this adds a lot of unnecessary redundancy, which will 
go towards increasing your character count. Being an avid Perl Golfer 
(although not one of the best) I can almost guarantee that any python 
code can be written more succinctly in Perl, although readability will 
suffer. Plus, the extensibility argument is very subjective, and is 
closely related to personal coding style.

Btw, do you include space chars that go toward indentating Python code 
in your count? If not, you should since they are required. Not so for Perl.

--Ala

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


Re: Time to bundle PythonWin

2006-05-16 Thread Martin v. Löwis
Dave Benjamin wrote:
> Sure. I wasn't proposing that this be done behind Mark's back. I wasn't
> even proposing a fork; rather, just two installers bundled into one. The
> user, upon running the .msi file, would simply be asked if they'd like
> PythonWin also. PythonWin could be automatically combined into the
> installer by downloading the latest version from SourceForge, perhaps.

That is technologically challenging. Contributions are welcome.

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


Re: python vs perl lines of code

2006-05-16 Thread Charles DeRykus
Edward Elliott wrote:
> John Bokma wrote:
> 
>> Edward Elliott <[EMAIL PROTECTED]> wrote:
>>
>>> This is just anecdotal, but I still find it interesting.  Take it for
>>> what it's worth.  I'm interested in hearing others' perspectives, just
>>> please don't turn this into a pissing contest.
>> Without seeing the actual code this is quite meaningless.
> 
> Evaluating my experiences yes, relating your own no.
> 

But why would anecdotal accounts be of interest... unless there's
an agenda :)  Differing skill levels and problem scenarios would
tangle the results so much no one could ever unravel the skein or
pry out any meaningful conclusions.  I'm not sure what's to be gained 
...even if you're just evaluating your own experiences. And, as you
suspect, it almost certainly would devolve into a pissing contest.

This subject thread  may be of great interest but I think an language 
advocacy mailing  list would be a better forum.

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


Re: A better way of making subsclassing of built-in types stick for attributes?

2006-05-16 Thread Ben Finney
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> Is there a better way to make the subclassing of built-in types
> stick?

They stick. Your new classes are available until you get rid of them.

> The goal is to have the the fields of a class behave like strings
> with extra methods attached. That is, I want the fact that the
> fields are not strings to be invisible to the client
> programmers. But I always want the extras to be there for the
> clients too.
> 
> What I'm doing is subclassing str.

Sounds like the right way to do what you're describing. Your subclass
can then be used to instantiate objects that behave like 'str'
objects, except for the different behaviour you define in your class.

> Of course, whenever you then set mystr = 'a string'

... you're instantiating a 'str' object, since that's what the syntax
you use will do.

> you loose the extra goodies that I have attached in the
> subclass.

Because you haven't created an object of that subclass.

>>> class GroovyStr(str):
... """ Our groovy extended string class """
... pass
...
>>> foo = "Larry"
>>> bar = str("Curly")
>>> baz = GroovyStr("Moe")
>>> print [type(x) for x in foo, bar, baz]
[, , ]

The syntax used to make the object assigned to 'foo' is just a
shortcut for the syntax used to assign to 'bar'. If you want to
instantiate anything else, you need to use that explicit syntax, such
as for the object assigned to 'baz'.

If you're hoping that "subclass" means "modify the behaviour of the
original class", you're mistaken. It makes a *new* class that has
behaviour *inherited from* the original class.

-- 
 \  "I stayed up all night playing poker with tarot cards. I got a |
  `\   full house and four people died."  -- Steven Wright |
_o__)  |
Ben Finney

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


Re: assignment in a for loop

2006-05-16 Thread MackS
Sorry, my previous post probably was not very good at explaining _why_
I want to do this.

Suppose I want to do modify all arguments which are passed to a
function. Do I need to use a list comprehension such as

def f(arg1,arg2,arg3):

 arg1,arg2,arg3 = [i+1 for i in (arg1,arg2,arg3)]
 ...

This would be awful when, eg, one adds an argument to the function
definition. It would require edition of the code at two different
locations.

Thanks

Mack

MackS wrote:
> Hello everyone
>
> Consider the following
>
> >>> l = [1,2]
> >>> for i in l:
> ... i = i + 1
> ...
> >>> l
> [1, 2]
>
> I understand (I think!) that this is due to the fact that in Python
> what looks like "assignment" really is binding a name to an object. The
> result is that inside the loop I am creating an object with value (i+1)
> and then "pointing" the name i at it. Therefore, the object to which i
> previously pointed (an element of list l) remains unchanged.
>
> Two brief questions:
>
> 1) Is what I wrote above (minimally) correct?
>
> 2) Independently of the answer to 1, is there a way for me to assign to
> elements of a list inside a loop and without resorting to C-style
> ugliness of
>
> for i in range(len(l))
>  l[i] = l[i] + 1
>
> ?
>
> (Note: not using a list comprehension.)
> 
> Thanks in advance
> 
> Mack

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


Re: Creating an Active Desktop Window

2006-05-16 Thread Roger Upole
rodmc wrote:
> Hi,
>
> Does anyone know how I can create  an Active Desktop window from within
> a Python script? It would also be good to know how to refresh that
> window and nothing else.
>
> At present I have an application which writes to a file which is read
> by the Active Desktop (embeded IE), then a refresh command is issued
> which refreshes the whole screen. This is a bit clumsy and also the
> user needs to manually set up the Active Desktop component.
>
> I have been looking around for some solutions to this and as of today
> my book on PyWin32 has still not arrived.
>
> Thanks in advance for any pointers.
>
> Best,
>
> rod

The ActiveDesktop interfaces aren't in Pywin32 yet, but
they should be in the next release, as part of the win32com.shell
package.

 Roger




== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 
Newsgroups
---= East/West-Coast Server Farms - Total Privacy via Encryption =---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Unicode problem -HELP

2006-05-16 Thread Ben Finney
"manstey" <[EMAIL PROTECTED]> writes:

> I'm a newbie at python, so I don't really understand how your answer
> solves my unicode problem.

Since your replies fail to give any context of the existing
discussion, I could only go by the content of what you'd written in
that message. I didn't see a problem with anything Unicode -- I saw
three objects being added together, which you told us were function
objects. That's the problem I pointed out.

-- 
 \   "When a well-packaged web of lies has been sold to the masses |
  `\over generations, the truth will seem utterly preposterous and |
_o__) its speaker a raving lunatic."  -- Dresden James |
Ben Finney

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


assignment in a for loop

2006-05-16 Thread MackS
Hello everyone

Consider the following

>>> l = [1,2]
>>> for i in l:
... i = i + 1
...
>>> l
[1, 2]

I understand (I think!) that this is due to the fact that in Python
what looks like "assignment" really is binding a name to an object. The
result is that inside the loop I am creating an object with value (i+1)
and then "pointing" the name i at it. Therefore, the object to which i
previously pointed (an element of list l) remains unchanged.

Two brief questions:

1) Is what I wrote above (minimally) correct?

2) Independently of the answer to 1, is there a way for me to assign to
elements of a list inside a loop and without resorting to C-style
ugliness of

for i in range(len(l))
 l[i] = l[i] + 1

?

(Note: not using a list comprehension.)

Thanks in advance

Mack

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


Re: build now requires Python exist before the build starts

2006-05-16 Thread [EMAIL PROTECTED]
Toon Knapen wrote:
> I'm trying to build the svn-trunk version of python on a Solaris box.
> However I do not have a python installed yet and apparantly the build of
> python requires a python to be accessible (as also annotated in the
> Makefile generated during the ./configure). How can I solve this situation?

It shouldn't actually be required.  I'm assuming the problem is while
trying to run asdlgen.py.  The generated files are checked in, but the
timestamps are wrong and the Makefile is trying to be helpful.

Try:
  touch Include/Python-ast.h Python/Python-ast.c
  make

I believe those are the two files that are generated.  If not, try
posting the error message.

HTH,
n

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


Re: common practice for creating utility functions?

2006-05-16 Thread BartlebyScrivener
Hey, thanks. I got the writing thing down:

http://dooling.com

Now I'm trying to pick up the programming part.

Thanks for links.

rick

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


Re: pythoncom and IDispatch

2006-05-16 Thread Roger Upole

"fraca7" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> Hello. I got a little problem while using pythoncom to automate IE; for some 
> reason, changing the 'selectedIndex' on an 
> instance of IHTMLSelectElement doesn't fire the 'onchange' event (I guess 
> this is a bug in mshtml).

As I understand it, this was done as a security measure to foil script
exploits.

> So, I tried to get the 'onchange' event handler and call it myself. According 
> to the docs, this is a simple IDispatch 
> implementation and calling Invoke() should do the trick; I actually have a 
> working example of this in Delphi.
>
> But I can't manage to get it work in Python; the following code
>
>
> idisp = pythoncom.WrapObject(elt.onchange)
> idisp.Invoke(pythoncom.DISPID_VALUE,
>  0x400, # LOCALE_USER_DEFAULT
>  pythoncom.DISPATCH_METHOD,
>  False)
>
> fails with an AttributeError:
>

You can access the underlying IDispatch using the
_oleobj_ property, ie elt.onchange._oleobj_.Invoke(..)

Alternately, you can also use FireEvent, which would look
something like this (untested):
elt.FireEvent('onchange',elt.onchange)


   Roger



== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Unicode problem -HELP

2006-05-16 Thread manstey
I'm a newbie at python, so I don't really understand how your answer
solves my unicode problem.

I have done more reading on unicode and then tried my code in IDLE
rather than WING IDE, and discovered that it works fine in IDLE, so I
think WING has a problem with unicode. For example, in WING this code
returns an error:

a={'a':u'\u0254'}
print a['a']


UnicodeEncodeError: 'ascii' codec can't encode character u'\u0254' in
position 0: ordinal not in range(128)

but in IDLE it correctly prints open o

So, assuming I now work in IDLE, all I want help with is how to read in
an ascii string and convert its letters to various unicode values and
save the resulting 'string' to a utf-8 text file. Is this clear?

so in pseudo code
1.  F is converted to \u0254, $ is converted to \u0283, C is converted
to \u02A6\02C1, etc.
(i want to do this using a dictionary TRANSLATE={'F':u'\u0254', etc)
2. I read in a file with lines like:
F$
FCF$
$$C$ etc
3. I convert this to
\u0254\u0283
\u0254\u02A6\02C1\u0254 etc
4. i save the results in a new file

when i read the new file in a unicode editor (EmEditor), i don't see
\u0254\u02A6\02C1\u0254, but I see the actual characters (open o, esh,
ts digraph, modified letter reversed glottal stop, etc.

I'm sure this is straightforward but I can't get it to work.

All help appreciated!

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


A better way of making subsclassing of built-in types stick for attributes?

2006-05-16 Thread [EMAIL PROTECTED]
Is there a better way to make the subclassing of built-in types stick?

The goal is to have the the fields of a class behave like strings with
extra methods attached. That is, I want the fact that the fields are
not strings to be invisible to the client programmers. But I always
want the extras to be there for the clients too.

What I'm doing is subclassing str. Of course, whenever you then set
mystr = 'a string' you loose the extra goodies that I have attached in
the subclass. So, to get around this I set up __get__ers and __set__ers
for the fields.

The question is there a more succinct way to have the extended string
behavior stick than using descriptors?

Just to make things concrete here's some abbreviated sample code:

class Person(Table.Table):
 def __init__(self, tcs, gender=None, first=None, last=None,
status=None):
self.gender = gender
self.first  = first
self.last   = last
self.status = status

# Using mix-ins to get the desired behavior
class Gender(Field.InitAlways, Field.SqlVarchar):
table= ('F', 'M')
fillNext = -1
@classmethod
def fill(cls, rec):
cls.fillNext += 1
return cls.table[cls.fillNext % 2]

#classes First, Last, & Status are analogous but more complicated

# The descriptors are set up at the bottom of the module like so:
Person.first  = Field.Descriptor(First)
Person.gender = Field.Descriptor(Gender)
Person.status = Field.Descriptor(Status)

# Moving along to other stripped supporting code

class Descriptor(object):
def __init__(self, cls, name=None):
self.cls = cls
if name == None:
self.name  = cls.__name__.lower()
else:
self.name = name.lower()

def __set__(self, inst, value):
if inst.__dict__.has_key(self.name):
inst.__dict__[self.name] = self.cls(inst, value, True)
else:
inst.__dict__[self.name] = self.cls(inst, value, False)

class InitAlways(str):
def __new__(cls, rec, value, reset):
if reset:
return str.__new__(cls, value)
if value == Empty:
return str.__new__(cls, '')
if value == Fill or value == None: #if value in (None, Fill,
''):
return str.__new__(cls, cls.fill(rec) or '')
return str.__new__(cls, value or '')

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


Re: help with this simple DB script

2006-05-16 Thread John Salerno
John Salerno wrote:
> Ok, before I contact my server host, I figured I should make sure I'm 
> not just making a Python mistake. I get an Internal Server Error with 
> this script:

Ok, got some help from Dennis Bieber and he solved it. I was using 
number(), which is a SQL but not a MySQL command. I needed to use 
something else, like int().

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


Re: help with this simple DB script

2006-05-16 Thread John Salerno
BartlebyScrivener wrote:
> Are you able to connect to the DB using MySQL administrator?
> 

Yes, through my hosting control panel. That's how I created the DB, but 
I want to try to do everything else with mysqldb.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help System For Python Applications

2006-05-16 Thread BartlebyScrivener
At the commandline, run:

pydoc -g

In the interpreter:

help("modulename")

or help ()

for interactive.

Are you on Windows? Using ActivePython? Or the Python.org download?

rd

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


Re: Is the only way to connect Python and Lua through a C interface?

2006-05-16 Thread Pierre Rouleau
Casey Hawthorne wrote:

> Is the only way to connect Python and Lua through a C interface?


Take a look at Lunatic Python (http://labix.org/lunatic-python)

--

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


Re: [silly] Does the python mascot have a name ?

2006-05-16 Thread Edward Elliott
Carl J. Van Arsdall wrote:

> Well, we could call the perl camel Joe but I don't know if the perlcores
> (read: hardcore PERL users) would be down for that ;)

Hmmm.  Perl is like smoking, it feels great and gives you cancer.  Yes,
there's definitely potential here. ;)

-- 
Edward Elliott
UC Berkeley School of Law (Boalt Hall)
complangpython at eddeye dot net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using target words from arrays in regex, pythons version of perls 'map'

2006-05-16 Thread Edward Elliott
John Machin wrote:

> Would you believe "steps 3 & 4"?

How about "two pops and a pass?"

Quick!  Lower the cone of silence!

-- 
Edward Elliott
UC Berkeley School of Law (Boalt Hall)
complangpython at eddeye dot net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help with a function

2006-05-16 Thread Paul McGuire
"Paul McGuire" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> "Lance Hoffmeyer" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > Hey all,
> >
> > I'm new to python.  I keep getting an error when running this.
> > I'm sure there is an easy fix but I can't figure it out.
> > What am I doing wrong?  How do I fix it?
> >
> > def even_odd_round(num):
> >   if(round(num,2) + .5 == int(round(num,2)) + 1):
> >if(int(num,0) % 2): #an odd number
> >rounded_num = round(num,2) + .1
> >else:  #an even number
> >  rounded_num = round(num,2) - .1
> > rounded_num = int(rounded_num)
> > return rounded_num
> >
> > even_odd_round(5.5)
> >
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> >   File "", line 3, in even_odd_round
> > TypeError: int() can't convert non-string with explicit base
> > >>>
>
>  1 def even_odd_round(num):
>  2   if(round(num,2) + .5 == int(round(num,2)) + 1):
>  3if(int(num,0) % 2): #an odd number
>  4rounded_num = round(num,2) + .1
>  5else:  #an even number
>  6  rounded_num = round(num,2) - .1
>  7 rounded_num = int(rounded_num)
>  8 return rounded_num
>  9
> 10 even_odd_round(5.5)
>
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> >   File "", line 3, in even_odd_round
> > TypeError: int() can't convert non-string with explicit base
>

This error message tells us there is a problem on line 3, something to do
with the int() method call.

You have posted a number of posts this week, and it feels like you write a
bunch of code, run into a problem, then post it without trying to figure it
out.  I don't mean to offend, but really, many of your questions are pretty
basic:
- how do I use regex's (to extract data from an easily split string of
space-delimited numbers)?
- how do I round a number?
- I get this traceback, what's wrong with my program?
Please read up on the Python tutorials, and learn how to use the interactive
help.

Overall, c.l.py is pretty newbie-friendly, and a "n00b" question every so
often is no big deal - but you've got to make more of an effort yourself.
There is also a tutorial mailing list that is - I started to say "more
geared for beginners", but we have plenty of lurker beginners on c.l.py, I'm
sure - I'd say the tutorial mailing list is more willing to handhold new
Python programmers.

And a posted "thanks" once in a while is not bad etiquette either.

-- Paul


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


Re: common practice for creating utility functions?

2006-05-16 Thread Edward Elliott
Bruno Desthuilliers wrote:

> Then it would be better to just alias it:
> 
> # def convert_quote(quote):
> # return make_code(quote)
> convert_quote = make_code

The former makes sense if you're planning to do more with the calling
function later.
 
> About the "fine to do" part, remember that Python's function calls are
> rather expansive...

Indeed, their expansiveness makes them great.  Unfortunately they're
somewhat expensive too. ;)

-- 
Edward Elliott
UC Berkeley School of Law (Boalt Hall)
complangpython at eddeye dot net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help with this simple DB script

2006-05-16 Thread John Salerno
[EMAIL PROTECTED] wrote:
> This is probably causing a problem:
> !#/usr/bin/python
> 
> It should be "#!", not "!#".

Ugh! So stupid! Thanks for correcting that, but it wasn't the only problem.

> If that doesnt' work, add this line at the top of your script, to check
> that the script is begin executed:
> 
> print "Content-Type: text/html\n\n"
> print "Hello, World!"

Yes, this part gets executed.

> If you still get an Internal Server Error put the following before you
> import MySQLdb:
> 
> import cgitb; cgitb.enable()

This produces a page with a ProgrammingError 
(http://www.johnjsalerno.com/server_db_test.py), but the main part I 
guess is this:

ProgrammingError: (1064, "You have an error in your SQL syntax. Check 
the manual that corresponds to your MySQL server version for the right 
syntax to use near 'number(2))' at line 1")

I'm not sure what I'm doing wrong with the syntax though. I don't think 
I need semicolons (a sample I saw didn't use them).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: common practice for creating utility functions?

2006-05-16 Thread Edward Elliott
BartlebyScrivener wrote:

> QOTW
> 
> "Programming is not just creating strings of instructions for a
> computer to execute.  It's also 'literary' in that you are trying to
> communicate a program structure to other humans reading the code." Paul
> Rubin

I take it you've never heard of Donald Knuth or literate programming:

"The main idea is to regard a program as a communication to human beings
rather than as a set of instructions to a computer."

"So you need somebody who's not afraid to write an essay, as well as not
afraid to write a computer program.  They work together perfectly, but you
have to be able to communicate to the computer, and you have to be able to
communicate to the human being, and if you don't do both, then you can't
expect your program to be as successful. Literate programming is just the
best way I know to do both at the same time."

"My schtick is to promote the idea that humans, not computers, read
programs I ask programmers to think of themselves as writers, teachers,
expositors. When you're programming, the very act of trying to explain it
to another human being forces you to get more clarity. And then later on,
you can maintain, modify, and port your programs to other platforms much
more easily. Even if your only audience is yourself, everything gets
better."

http://www-cs-faculty.stanford.edu/~knuth/
http://www-cs-faculty.stanford.edu/~uno/lp.html

-- 
Edward Elliott
UC Berkeley School of Law (Boalt Hall)
complangpython at eddeye dot net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Unicode problem -HELP

2006-05-16 Thread Ben Finney
"manstey" <[EMAIL PROTECTED]> writes:

> input_file = open(input_file_loc, 'r')
> output_file = open(output_file_loc, 'w')
> for line in input_file:
> output_file.write(str(word_info + parse + gloss))  # = three functions 
> that return tuples

If you mean that 'word_info', 'parse' and 'gloss' are three functions
that return tuples, then you get that return value by calling them.

>>> def foo():
... return "foo's return value"
...
>>> def bar(baz):
... return "bar's return value (including '%s')" % baz
...
>>> print foo()
foo's return value
>>> print bar

>>> print bar("orange")
bar's return value (including 'orange')

-- 
 \ "A man must consider what a rich realm he abdicates when he |
  `\becomes a conformist."  -- Ralph Waldo Emerson |
_o__)  |
Ben Finney

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


Re: help with a function

2006-05-16 Thread Paul McGuire
"Lance Hoffmeyer" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Hey all,
>
> I'm new to python.  I keep getting an error when running this.
> I'm sure there is an easy fix but I can't figure it out.
> What am I doing wrong?  How do I fix it?
>
> def even_odd_round(num):
>   if(round(num,2) + .5 == int(round(num,2)) + 1):
>if(int(num,0) % 2): #an odd number
>rounded_num = round(num,2) + .1
>else:  #an even number
>  rounded_num = round(num,2) - .1
> rounded_num = int(rounded_num)
> return rounded_num
>
> even_odd_round(5.5)
>
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "", line 3, in even_odd_round
> TypeError: int() can't convert non-string with explicit base
> >>>

 1 def even_odd_round(num):
 2   if(round(num,2) + .5 == int(round(num,2)) + 1):
 3if(int(num,0) % 2): #an odd number
 4rounded_num = round(num,2) + .1
 5else:  #an even number
 6  rounded_num = round(num,2) - .1
 7 rounded_num = int(rounded_num)
 8 return rounded_num
 9
10 even_odd_round(5.5)

> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "", line 3, in even_odd_round
> TypeError: int() can't convert non-string with explicit base

This


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


Re: help with a function

2006-05-16 Thread Ben Finney
Lance Hoffmeyer <[EMAIL PROTECTED]> writes:

> def even_odd_round(num):
>   if(round(num,2) + .5 == int(round(num,2)) + 1):
>if(int(num,0) % 2):#an odd number  
>   rounded_num = round(num,2) + .1
>else:  #an even number
>   rounded_num = round(num,2) - .1
>   rounded_num = int(rounded_num)
>   return rounded_num
> 
> even_odd_round(5.5)
> 
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "", line 3, in even_odd_round
> TypeError: int() can't convert non-string with explicit base
> >>>

Two problems.

One is the simple fact reported by the error message: you're
attempting to specify that a number object (already represented inside
Python as a number) should be converted using a particular base. (Why
you've chosen 0 as the base is beyond me.)

That only makes sense with a string of digit characters, where Python
needs to be told what numeric base each digit is (decimal, octal,
hexadecimal, whatever). It makes no sense for objects that are already
numbers, since they're not represented as digits in a base.

The other problem is specifying a base at all. Why not just convert
the object to an int using the default base?

If you're confused about how built-in types or functions work, you
should become familiar with the help system in the interpreter:

help(int)

-- 
 \  "Any sufficiently advanced bug is indistinguishable from a |
  `\   feature."  -- Rich Kulawiec |
_o__)  |
Ben Finney

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


Re: A Unicode problem -HELP

2006-05-16 Thread manstey
Hi Martin,

HEre is how I write:

input_file = open(input_file_loc, 'r')
output_file = open(output_file_loc, 'w')
for line in input_file:
output_file.write(str(word_info + parse + gloss))  # = three
functions that return tuples

(u'F', u'\u0254')  are two of the many unicode tuple elements returned
by the three functions.

What am I doing wrong?

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


Re: constucting a lookup table

2006-05-16 Thread mhodkin

Larry Bates wrote:
> [EMAIL PROTECTED] wrote:
> > I'm new to Python and want to contruct a "lookup table" which would be
> > similar to a spreadsheet in that a value is read along the first
> > column, then along the top row, and the intersection of the two gives a
> > value that is hard-coded, i.e. not mathmatically related.  An example
> > would be a table with HEIGHT in the first column, WEIGHT in the first
> > row, and estimated SUITSIZE with the body of the table.
> >
> > Which Python type would be most appropriate and/or efficient?
> >
> > thanks
> >
> I would not worry about being "efficient" at this point.  There are not
> enough combinations of height/weight to make even a linear search through
> a list be a performance problem.  One way would be to set up a dictionary
> that is keyed on height/weight and have it return suit size.  To work
> properly you would need to express height in inches and weight in pounds
> (in US measurements).  Something like:
>
> hwdict={(60, 80): ,
> (61, 80): ,
> (62, 80): ,
> .
> .
> .
> (88, 400): }
>
> This would be fast because lookup would consist of only (not tested):
>
> try:  suitsize=hwdict[(heightininches, weightinpounds)]
> except IndexError:
>  print "height/weight combination not found in lookup table"
> 
> 
> -Larry Bates

thanks...much appreciated

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


help with a function

2006-05-16 Thread Lance Hoffmeyer
Hey all,

I'm new to python.  I keep getting an error when running this.
I'm sure there is an easy fix but I can't figure it out.
What am I doing wrong?  How do I fix it?

def even_odd_round(num):
if(round(num,2) + .5 == int(round(num,2)) + 1):
 if(int(num,0) % 2):#an odd number  
rounded_num = round(num,2) + .1
 else:  #an even number
rounded_num = round(num,2) - .1
rounded_num = int(rounded_num)
return rounded_num

even_odd_round(5.5)

Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 3, in even_odd_round
TypeError: int() can't convert non-string with explicit base
>>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do/while structure needed

2006-05-16 Thread Edward Elliott
Dennis Lee Bieber wrote:

> Would you put the condition at the top of the loop -- and confuse
> those people who believe the exit condition should appear at the point
> the exit activates?

Confusion is not the issue.  You can put the condition smack dab in the
middle of the loop, as long as the location is consistent people will know
where to look for it.  Rejecting because "some are confused the first time
since other languages do it differently" gets you nowhere: some group will
always be confused by something.  They learn, problem solved.

I agree that do/while is unnecessary.  But I'd argue against it on grounds
of simplicity and readability instead of confusion.

-- 
Edward Elliott
UC Berkeley School of Law (Boalt Hall)
complangpython at eddeye dot net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help with this simple DB script

2006-05-16 Thread trebucket
This is probably causing a problem:
!#/usr/bin/python

It should be "#!", not "!#".

If that doesnt' work, add this line at the top of your script, to check
that the script is begin executed:

print "Content-Type: text/html\n\n"
print "Hello, World!"

If you still get an Internal Server Error put the following before you
import MySQLdb:

import cgitb; cgitb.enable()

Hope this helps,

- Alex Ross

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


Re: any plans to make pprint() a builtin?

2006-05-16 Thread Edward Elliott
Ant wrote:

> Longer, messy, and what's the actual point? Wouldn't:
> 
> import pprint as pp
> pp.pprint(x)
> 
> be better, standard *and* shorter?

why not just:

from pprint import pprint
pprint (x)

No need to modify the interpreter when you can pollute the global namespace
yourself just as easily.

-- 
Edward Elliott
UC Berkeley School of Law (Boalt Hall)
complangpython at eddeye dot net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help with this simple DB script

2006-05-16 Thread John Machin
Please learn to provide needed information when asking questions.
1. What does "run it directly with my URL" mean??
2. Show the traceback that you got.

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


Re: help with this simple DB script

2006-05-16 Thread BartlebyScrivener
Are you able to connect to the DB using MySQL administrator?

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


Re: python vs perl lines of code

2006-05-16 Thread Edward Elliott
John Bokma wrote:

> Edward Elliott <[EMAIL PROTECTED]> wrote:
> 
>> This is just anecdotal, but I still find it interesting.  Take it for
>> what it's worth.  I'm interested in hearing others' perspectives, just
>> please don't turn this into a pissing contest.
> 
> Without seeing the actual code this is quite meaningless.

Evaluating my experiences yes, relating your own no.

-- 
Edward Elliott
UC Berkeley School of Law (Boalt Hall)
complangpython at eddeye dot net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python vs perl lines of code

2006-05-16 Thread John Bokma
Edward Elliott <[EMAIL PROTECTED]> wrote:

> This is just anecdotal, but I still find it interesting.  Take it for
> what it's worth.  I'm interested in hearing others' perspectives, just
> please don't turn this into a pissing contest.

Without seeing the actual code this is quite meaningless.
 
-- 
John   MexIT: http://johnbokma.com/mexit/
   personal page:   http://johnbokma.com/
Experienced programmer available: http://castleamber.com/
Happy Customers: http://castleamber.com/testimonials.html
-- 
http://mail.python.org/mailman/listinfo/python-list


python vs perl lines of code

2006-05-16 Thread Edward Elliott
This is just anecdotal, but I still find it interesting.  Take it for what
it's worth.  I'm interested in hearing others' perspectives, just please
don't turn this into a pissing contest.

I'm in the process of converting some old perl programs to python.  These
programs use some network code and do a lot of list/dict data processing. 
The old ones work fine but are a pain to extend.  After two conversions,
the python versions are noticeably shorter.

The first program does some http retrieval, sort of a poor-man's wget with
some extra features.  In fact it could be written as a bash script with
wget, but the extra processing would make it very messy.  Here are the
numbers on the two versions:

   Raw   -Blanks -Comments
   lines  chars   lines  chars lines  chars
mirror.py  16746321324597  1184009
mirror.pl  30958362115647  1844790
 
I've listed line and character counts for three forms.  Raw is the source
file as-is.  -Blanks is the source with blank lines removed, including
lines with just a brace.  -Comments removes both blanks and comment lines. 
I think -Blanks is the better measure because comments are a function of
code complexity, but either works.

By the numbers, the python code appears roughly 60% as long by line and 80%
as long by characters.  The chars percentage being (higher relative to line
count) doesn't surprise me since things like list comprehensions and
explicit module calling produce lengthy but readable lines.

I should point out this wasn't a straight line-for-line conversion, but the
basic code structure is extremely similar.  I did make a number of
improvements in the Python version with stricter arg checks and better
error handling, plus added a couple minor new features.

The second program is an smtp outbound filtering proxy.  Same categories as
before:

Raw -Blanks   -Comments
lines  chars lines  chars   lines  chars
smtp-proxy.py   2617788  222 7749   205 6964
smtp-proxy.pl   96624110 66023469   45214869

The numbers here look much more impressive but it's not a fair comparison. 
I wasn't happy with any of the cpan libraries for smtp sending at the time
so I rolled my own.  That accounts for 150 raw lines of difference. Another
70 raw lines are logging functions that the python version does with the
standard library.  The new version performs the same algorithms and data
manipulations as the original.  I did do some major refactoring along the
way, but it wasn't the sort that greatly reduces line count by eliminating
redundancy; there is very little redundancy in either version.  In any
case, these factors alone don't account for the entire difference, even if
you take 220 raw lines directly off the latter columns.

The two versions were written about 5 years apart, all by me.  At the time
of each, I had about 3 years experience in the given language and would
classify my skill level in it as midway between intermediate and advanced. 
IOW I'm very comfortable with the language and library reference docs (minus
a few odd corners), but generally draw the line at mucking with interpreter
internals like symbol tables.

I'd like to here from others what their experience converting between perl
and python is (either direction).  I don't have the sense that either
language is particularly better suited for my problem domain than the
other, as they both handle network io and list/dict processing very well. 
What are the differences like in other domains?  Do you attribute those
differences to the language, the library, the programmer, or other
factors?  What are the consistent differences across space and time, if
any?  I'm interested in properties of the code itself, not performance.

And just what is the question to the ultimate answer to life, the universe,
and everything anyway? ;)

-- 
Edward Elliott
UC Berkeley School of Law (Boalt Hall)
complangpython at eddeye dot net
-- 
http://mail.python.org/mailman/listinfo/python-list


help with this simple DB script

2006-05-16 Thread John Salerno
Ok, before I contact my server host, I figured I should make sure I'm 
not just making a Python mistake. I get an Internal Server Error with 
this script:

!#/usr/bin/python

import MySQLdb

db = MySQLdb.connect(host='xxx',
  user='xxx',
  passwd='xxx',
  db='xxx') # changed this stuff

cursor = db.cursor()
cursor.execute("CREATE TABLE test (first varchar(10), second number(2))")
cursor.execute("INSERT INTO test (first, second) VALUES ('Hello', 33)")
cursor.execute("SELECT first, second FROM test")
cursor.fetchall()
cursor.close()
db.close()



All I do is run it directly with my URL, not sure if there's more to it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Is the only way to connect Python and Lua through a C interface?

2006-05-16 Thread Casey Hawthorne
Is the only way to connect Python and Lua through a C interface?
--
Regards,
Casey
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: advice modifying re library to support more than 100 named captures.

2006-05-16 Thread Tim Peters
[Richard Meraz]
> We need to capture more than 99 named groups using python regular
> expressions.
> ...
> its clear why the language designers have decided on this limitation.  For
> our system, however, it is essential that we be able to capture an arbitrary
> number of groups.
>
> Could anyone on the list suggest what parts of the library code make
> assumptions about this restriction? We'd like to make some local changes to
> the core library to allow us to continue the development of our system (we
> don't want to switch to another language). We removed the condition in
> sre_compile.py that raises an exception for compiled regexps with more than
> 100 groups.  This allowed us to compile a regular expression with more than
> 100 groups, but subsequent attempts to match or search with that regular
> expression resulted in segfaults.

Which is a good clue that you'll have to understand the C code
implementing regexps.  That's in Modules/_sre.c.  In the absence of
understanding, your best bet is to get in a debugger, see where it's
segfaulting, guess at the cause, try to fix it, and start over.

For a start, you'll certainly need to boost the value of this #define in sre.h:

#define SRE_MARK_SIZE 200

Sorry, but I have no idea whether you'll need more than just that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For Large Dictionaries Could One Use Separate Dictionaries Where Each Dictionary Covers an Interval of the Input Range?

2006-05-16 Thread skip

bob> If you have the same number of entries as buckets, and you have a
bob> good hash function, then if you have n buckets your longest chain
bob> should have length around ln(n).  The average length of a nonempty
bob> bucket would be somewhere around 1 1/2.

Yes, and it achieves that nice short chain length by consuming gobs of
memory.  A dictionary with 10**7 keys is going to chew up lots of memory.
There's nothing particularly magical about dictionaries in this respect.
They are good examples of a classic time-space tradeoff.

Skip

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


Re: Unable to extract Python source code using Windows

2006-05-16 Thread John Machin
Elric02 wrote:
"""
I'm currently trying to get access to the Python source code, however
whenever I try to extract the files using the latest version of WinZip
(version 10) I get the following error "error reading however after
processing 0 entries
"""

I've managed to reproduce this behaviour:
1. Browser = Firefox
2. go to www.python.org
3. click on quick links / source code [on the left side of the home
page]
4. Firefox pops up a box which says 'You have chosen to download
blahblah.tar.bz2 which is a: WinZip File". [It is is gravely mistaken].

5. The default presented is "open" (as opposed to save to disk).
6. If you click on OK, you get "Error reading header [not 'however'!!]
after 0 entries."

In defense/mitigation of FireFox: IE is equally mistaken at step 4. At
step 6, it doesn't complain but starts off downloading [painfully
slowly]. I didn't wait around to find out what sort of error message
ensued.

So:
(1) like I said in an earlier post, go for the .tgz file -- look for
the line gzip-compressed source code: python-2.4.3.tgz
on the home page
(2) download the file, don't open archives online, even from trusted
sources like python.org
(3) understand that WinZip *does* handle .tar, .gz, .tar.gz, and .tgz
files. It doesn't handle .bz2 files.
(4) When asking a question, try stating what you have been doing, with
some precision -- like in this case, *WHICH* archive and *HOW* ...

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


Re: For Large Dictionaries Could One Use Separate Dictionaries Where Each Dictionary Covers an Interval of the Input Range?

2006-05-16 Thread skip

Roy> If you're getting long hash chains, you're either using a bad hash
Roy> function, or your table isn't big enough.

Sure.  The original poster said something about 10 million keys I think.
Unless the key distribution is amazingly fortuitous and the number of unique
values is small, the dictionary is going to have a huge memory footprint.

On my Mac laptop this code:

>>> d = {}
>>> for n in xrange(10**7):
...   d[n] = hex(n)
... 

yields a process with 647MB of VM.  If I trim that to 1000 unique values:

>>> d = {}
>>> for n in xrange(10**7):
...   d[n] = hex(n % 1000)
... 

I still wind up with 647MB VM.  The dictionary and its keys are what consume
all the memory, and those keys are as simple as you can get.

Skip

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


advice modifying re library to support more than 100 named captures.

2006-05-16 Thread Richard Meraz
Dear group members,We need to capture more than 99 named groups using python regular expressions.  From the docs and from this thread (
http://groups.google.com/group/comp.lang.python/browse_thread/thread/a39a91b4bf8e3df4/2ad4a7e01b60215d?lnk=st&q=python+regular+_expression_+group+limit&rnum=3#2ad4a7e01b60215d) its clear why the language designers have decided on this limitation.  For our system, however, it is essential that we be able to capture an arbitrary number of groups.  
Could anyone on the list suggest what parts of the library code make assumptions about this restriction? We'd like to make some local changes to the core library to allow us to continue the development of our system (we don't want to switch to another language). We removed the condition in sre_compile.py that raises an exception for compiled regexps with more than 100 groups.  This allowed us to compile a regular _expression_ with more than 100 groups, but subsequent attempts to match or search with that regular _expression_ resulted in segfaults.
Thanks,Richard MerazI realize this has been discussed before here: 
http://groups.google.com/group/comp.lang.python/browse_thread/thread/a39a91b4bf8e3df4/2ad4a7e01b60215d?lnk=st&q=python+regular+_expression_+group+limit&rnum=3#2ad4a7e01b60215d-- Never think there is anything impossible for the soul. It is the greatest heresy to think so. If there is sin, this is the only sin – to say that you are weak, or others are weak.
Swami Vivekananda 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: calling upper() on a string, not working?

2006-05-16 Thread Paul Rubin
John Salerno <[EMAIL PROTECTED]> writes:
> Now, I know the actual upper() function works, but I can't understand
> if there's a problem with *when* it's being called, or what's being
> done with it to get the second result above.

You are translating "original" which still has lower case letters:

 return original.translate(trans_table)

You want:

 return original.upper().translate(trans_table)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using python for a CAD program

2006-05-16 Thread Ben Finney
baalbek <[EMAIL PROTECTED]> writes:

> If you really want to revolutionize the CAD business, PLEASE don't
> base your CAD system on a file based system (ala Autocad).
> 
> CAD systems available today (Autocad, Archicad, Architectural
> Desktop, etc) have one huge flaw: they don't store data to a SQL
> database, but to binary files.

Using Python 2.5, one could store (and distribute to others) the data
in a binary file that *is* an SQL database:

http://docs.python.org/dev/lib/module-sqlite3.html>

-- 
 \   "I was sleeping the other night, alone, thanks to the |
  `\exterminator."  -- Emo Philips |
_o__)  |
Ben Finney

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


Re: Tabs versus Spaces in Source Code

2006-05-16 Thread Aaron Gray
I was once a religous tabber until working on multiple source code sources, 
now I am a religious spacer :)

My 2bits worth,

Aaron


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


Re: Unable to extract Python source code using Windows

2006-05-16 Thread John Machin
Elric02 wrote:
"""
 I tried downloading for different archives, (different versions of
Python) I can't believe they are all garbled.  But they all don't work
with WinZip.
"""

I can't believe that they're all garbled either. The likelihood of that
is small. Further, the probablility that all-pervasive garbling of tgz
files would go unnoticed is about three-tenths of five-eighths of an
extremely small number.

Reminds me of the story of the proud mother watching her son's regiment
on parade: "Look, everybody, my Tommy's the only one marching in
step!".

Let's rewrite your last sentence as "My copy of WinZip v10 doesn't work
with any of them", and go with the most plausible explanation.

HTH,
John

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


Python and GLSL

2006-05-16 Thread Simon Bunker
Hi

I was wondering if there is a Python module for running GLSL (OpenGL 
shader language) in OpenGL through Python.

I think that Cg is available through PyCg - most likely using PyGame for 
the OpenGL.

Has anyone done this with GLSL shaders?

thanks

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


Re: calling upper() on a string, not working?

2006-05-16 Thread Scott David Daniels
John Salerno wrote:

Others have shown you where the bug was.

You might want to change encrypt_quote like this:

XXX> def encrypt_quote(original):
   def encrypt_quote(original, casemap=True):
XXX>  original_letters = filter_letters(original)
   if casemap:
   original_letters = filter_letters(original.upper())
   else:
   original_letters = filter_letters(original)
XXX>  new_letters = list(string.ascii_uppercase)
   if len(original_letters) > 26:
   new_letters = list(string.ascii_uppercase + 
string.ascii_lowercase)
   casemap = False
   else:
   new_letters = list(string.ascii_uppercase)
> while True:
> random.shuffle(new_letters)
> trans_letters = ''.join(new_letters)[:len(original_letters)]
> if test_code(original_letters, trans_letters):
XXX>  trans_table = string.maketrans(original_letters, 
trans_letters)
   if casemap:
   trans_table = string.maketrans(
 original_letters + original_letters.lower(),
 trans_letters + trans_letters.lower())
   else:
   trans_table = string.maketrans(original_letters, 
trans_letters)
> break
> return original.translate(trans_table)


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


Re: Using python for a CAD program

2006-05-16 Thread baalbek
> 1.  Databases.  I don't mean sql type database, but design databases,

If you really want to revolutionize the CAD business, PLEASE don't base 
your CAD system on a file based system (ala Autocad).

CAD systems available today (Autocad, Archicad, Architectural Desktop, 
etc) have one huge flaw: they don't store data to a SQL database, but to 
binary files.

This fact has created so much problems (user problems as well as 
technical problems) in projects that involve several people.

I know, I have 15 years of experience supporting teams using CAD, as 
well as CAD programming (mostly C++).

The fact that Autodesk still to this day has not produced an Autocad 
version for a SQL database, shows how little innovation there is in 
large companies.

I don't know where to start to list the numerous problems with a CAD 
system based on raw binary files, so I won't bother.

Regards, and Good Luck,
Baalbek
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: arrays, even, roundup, odd round down ?

2006-05-16 Thread Ben Finney
Lance Hoffmeyer <[EMAIL PROTECTED]> writes:

> So, I have using the following to grab numbers from MS Word.  I
> discovered that that there is a "special" rule being used for
> rounding.
> 
> If a ??.5 is even the number is to rounded down (20.5 = 20)
> if a ??.5 is odd the number is to rounded up (21.5 = 22)

This sounds specific enough that I'd want it in a separate function.

def specially_rounded_integer(num):
""" Round a number using our special rules """
rounded_num = num * phase_of_moon()# or whatever else you need to do
return rounded_num

> Brands = ["B1","B2"]
> A1 = []
> A1 = [ re.search(r"(?m)(?s)\r%s.*?SECOND.*?(?:(\d{1,3}\.\d)\s+){2}" % i, 
> target_table).group(1)  for i in Brands ]
> A1 = [int(float(str(x))+0.5) for x in A1 ]
> print A1

original_nums = however_you_get_them()
rounded_nums = [specially_rounded_integer(n) for n in original_nums]

If it's not quickly obvious on a single line, express it more
fully. Future readers, including yourself, will thank you.

-- 
 \"Nothing in life is so exhilarating as to be shot at without |
  `\result."  -- Winston Churchill |
_o__)  |
Ben Finney

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


Re: Option parser question - reading options from file as well as command line

2006-05-16 Thread Andrew Robert
Max Erickson wrote:

> I don't know much about optparse, but since I was bored:
> 
 help(o.parse_args)
> Help on method parse_args in module optparse:
> 
> parse_args(self, args=None, values=None) method of 
> optparse.OptionParser instance
> parse_args(args : [string] = sys.argv[1:],
>values : Values = None)
> -> (values : Values, args : [string])
> 
> Parse the command-line options found in 'args' (default:
> sys.argv[1:]).  Any errors result in a call to 'error()', which
> by default prints the usage message to stderr and calls
> sys.exit() with an error message.  On success returns a pair
> (values, args) where 'values' is an Values instance (with all
> your option values) and 'args' is the list of arguments left
> over after parsing options.
> 
 o.parse_args('seven')
> Traceback (most recent call last):
>   File "", line 1, in ?
> o.parse_args('seven')
>   File "C:\bin\Python24\lib\optparse.py", line 1275, in parse_args
> stop = self._process_args(largs, rargs, values)
>   File "C:\bin\Python24\lib\optparse.py", line 1322, in _process_args
> del rargs[0]
> TypeError: object doesn't support item deletion
> 
> That's the result of poking an optionParser instance in Idle. 
> parse_args is expecting something that looks like sys.argv[1:], which 
> is a list. You are passing it a string.
> 
> max
> 
Yup.. the code now works as:

parser = OptionParser()

if len(sys.argv) == 2:
lines = open(sys.argv[1],"rb").readlines()
for line in lines:
line=line.strip()
if not line:
continue
short, long, dest, help, default = line.split(";")
help = "\t\t" + help # Prepend tabs to help message
parser.add_option(short, long, dest=dest, help=help, 
default=default)
else:
parser.add_option("-m","--qmanager", dest="qmanager",
help="\t\tQueue Manager to inquire against"),
parser.add_option("-q","--queue", dest="queue",
help="\t\tQueue the message will be sent to"),
parser.add_option("-d","--dest", dest="dest",
help="\t\tDestination File Name"),
parser.add_option("-f", "--file",
action="store", type="string", dest="filename",
help="File to be transmitted", metavar="FILE")

(options, args) = parser.parse_args()


thanks all for the insight
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unable to extract Python source code using Windows

2006-05-16 Thread John Machin
> http://www.python.org/ftp/python/2.4.3/Python-2.4.3.tar.bz2

And the reason for posting that would be what? WinZip doesn't support
bzip2 compression.

http://www.python.org/ftp/python/2.4.3/Python-2.4.3.tgz (a gzipped tar
file) is what the OP would be better pointed at.

FWIW, I have just downloaded the above tgz file and successfully
unpacked it with WinZip versions 9 and 10, and with 7-Zip.

FWIW2, 7-Zip is *free* and handles bz2 files.

I would suggest that the OP's copy of WinZip v10 is stuffed, or his
whole download mechanism is stuffed. If he were to investigate properly
(as suggested by ScottDD) instead of thrashing about, 

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


Re: taking qoutes in arguments

2006-05-16 Thread Ben Finney
"Lee Caine" <[EMAIL PROTECTED]> writes:

> yea thanks alot for your help, gonna read up on 'Konsole' :)

Be advised that 'Konsole' is not a command shell, it's a GUI program
for running a command shell.

On POSIX systems, find out what your current command shell is with
this command:

echo $SHELL

-- 
 \   "Working out the social politics of who you can trust and why |
  `\  is, quite literally, what a very large part of our brain has |
_o__)evolved to do."  -- Douglas Adams |
Ben Finney

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


Re: Time to bundle PythonWin

2006-05-16 Thread Dave Benjamin
Martin v. Löwis wrote:
> Dave Benjamin wrote:
>> Why is PythonWin (win32all) still a separate download from a third
>> party? Is it legal, technical, or what? I think it's about time it be
>> part of the standard distribution.
> 
> Both legal and technical. The PythonWin author and maintainer (Mark
> Hammond) hasn't contributed this package for inclusion into Python.
> Without him explicitly saying that he wants that to happen, and prefers
> that over maintaining it outside Python himself, there is no way it
> could ever get included. This is a basic rule of politeness in open
> source software: don't fork, not even if you are legally allowed to.
> [of course, forks happen, typically because people don't consider
>  it important enough to be polite to the original author]

Sure. I wasn't proposing that this be done behind Mark's back. I wasn't 
even proposing a fork; rather, just two installers bundled into one. The 
user, upon running the .msi file, would simply be asked if they'd like 
PythonWin also. PythonWin could be automatically combined into the 
installer by downloading the latest version from SourceForge, perhaps.

> Now, if Mark did indeed offer it for inclusion, I would request (and
> also work on if I find the time) that the structure of these libraries
> is revised. I know that the current structure tries to be "natural"
> in some sense, but I find the assignment of API functions to modules
> quite arbitrary. I also think that some of the API functions should
> be replaced with their *Ex versions that Microsoft added over time.

Well, I'm sure the structure could be improved, but there's really 
nothing else quite like PythonWin out there. And I could think of parts 
of Python's standard library that evolved organically (os.popen2 thru 12 
comes to mind ;-) ) which could stand some reorganization. But anyway, I 
digress...

> Coming back to organizational issues: it would surely help if people
> would actively contribute to PythonWin. I believe this still is
> primarily a one-man show, and that Mark does an excellent job should
> not be an excuse for you to not contribute.

If only I had his expertise on the win32 API...

>> There are many useful things that you ought to be able to do without
>> downloading third-party libraries. Terminating a process, for example.
> 
> You can use subprocess.TerminateProcess for that (in some limited way).

Good to know, although this requires Python 2.5. I'm getting rather 
excited about Python 2.5... looks like a lot of useful new tools are in 
the pipeline.

>> Communicating with other applications via a standard, common protocol
>> (COM). We demand these things from our UNIX environments--why do we
>> tolerate their omission on the Windows platform?
> 
> We tolerate them because they aren't omitted. They are readily
> available, and we are all lazy enough to never do more than just
> post to a newsgroup complaining about it.

Well, good, at least I'm not the only lazy complainer around here. =)

>> It's time to bundle PythonWin.
> 
> So go and work on that.

Nah. Sounds like the better option is to wait for ctypes in 2.5...

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


Re: Large Dictionaries

2006-05-16 Thread Klaas
>22.2s  20m25s[3]

20m to insert 1m keys?  You are doing something wrong.

With bdb's it is crucial to insert keys in bytestring-sorted order.
Also, be sure to give it a decent amount of cache.

-Mike

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


Re: For Large Dictionaries Could One Use Separate Dictionaries Where Each Dictionary Covers an Interval of the Input Range?

2006-05-16 Thread bob_jenkins
If you have the same number of entries as buckets, and you have a good
hash function, then if you have n buckets your longest chain should
have length around ln(n).  The average length of a nonempty bucket
would be somewhere around 1 1/2.

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


Re: round numbers in an array without importing Numeric or Math? - SOLVED, sort of

2006-05-16 Thread Scott David Daniels
Paul McGuire wrote:
> ... or if you prefer the functional approach (using map)...
> 
> roundToInt = lambda z : int(z+0.5)
> Topamax = map( roundToInt, map( float, map(str, Topamax) ) )

Somehow, the list comprehension looks simpler and clearer to me:

 Topamax = [int(float(uni) + .5) for uni in Topamax]

I really dislike lines like:
 roundToInt = lambda z : int(z+0.5)

You've already chosen a name, but you'd rather write in the lisp style.

 def roundToInt(z):return int(z+0.5)

takes all of _one_ more character.

I also don't understand why you convert to string from unicode in:

 ... map(str, Topamax) ) )

float works on all string types (including unicode), and will accept 
some non-ASCII digit values.

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


Re: Time to bundle PythonWin

2006-05-16 Thread Dave Benjamin
[EMAIL PROTECTED] wrote:
> The ctypes.com package is no longer part of ctypes.
> It has been split by Thomas Heller into a separate package comtypes.
> See: http://sourceforge.net/projects/comtypes/
> 
> Still in its childhood but as easy as com can get, I guess, way easier
> and better than pythonWin at least.

What makes you say it's way easier? PythonWin is pretty darn easy, from 
my experience.

If ctypes is going to be standard, and ctypes.com is pure-Python, I 
really have no reason left to complain. I do have to rewrite some 
scripts, but this isn't a big deal.

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


Re: Time to bundle PythonWin

2006-05-16 Thread Dave Benjamin
Ten wrote:
> Respectfully, that sounds like a reason for *you* to bundle pythonwin (and 
> python, to be honest :) ), not a reason for everyone else to have to download 
> an extra 40-50% of potentially superfluous cruft with their standard python 
> setup.

Certainly, I could bundle Python and PythonWin myself. I'll even admit 
that my little office utilities would be better distributed as frozen 
.exe files with all the necessary libraries bundled inside. But my 
original problem as stated was this:

   1. I release a Python script (a .py file)
   2. My user upgrades or switches computers
   3. They (logically) download and install Python
   4. My script still doesn't work
   5. They ask me for help

At this point, I dig through four or five web sites to find where 
PythonWin is hosted these days, and it's obvious that my user never 
would have guessed to download it, or found the right place to retrieve 
it. If the windows installer for Python came with PythonWin, they might 
not have needed my help at all.

I realize that other people's needs aren't the same as mine, but this 
scenario isn't contrived. This has happened numerous times. Bundling 
PythonWin myself wouldn't solve this particular problem as stated.

> In more general terms I can see why it would be useful to some windows people
> to have more winapi stuff available. I can still think of quite a few things 
> I'd rather be spending that extra download time on myself, though, like a 
> sexed-up tkinter or maybe even a new gui toolkit.

I'd happily download a larger installer for any or all of these things. 
In the time it took me to write this, I'd probably already have finished 
the download anyway.

> Still, it's not an either/or choice, I suppose.

Yep. =)

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


Re: Unable to extract Python source code using Windows

2006-05-16 Thread Scott David Daniels
[EMAIL PROTECTED] wrote:
> Scott ,
> I tried downloading for different archives, (different versions of
> Python) I can't believe they are all garbled.  But they all don't work
> with WinZip.
> 
OK, against my better judgment (you haven't shown your work so far):

I get an md5 for python-2.4.3.tar.bz2 of:
  141c683447d5e76be1d2bd4829574f02

Next read about the tarfile module, where you may discover:

 import tarfile
 archive = tarfile.TarFile.open('python-2.4.3.tar.bz2', 'r:bz2')

might give you something interesting.


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


Re: Tabs versus Spaces in Source Code

2006-05-16 Thread achates
Duncan Booth wrote:

>However the important thing is that a tab does
>not map to a single indentation level in Python: it can map to any number
>of indents, and unless I know the convention you are using to display the
>tabs I cannot know how many indents are equivalent to a tabstop.

Sorry but this is just wrong. Python works out the indentation level
for a source file dynamically: see
http://docs.python.org/ref/indentation.html. The particular algorithm
it uses is designed to accommodate people who mix tabs and spaces
(which is unfortunate, and should probably be changed). Nevertheless,
using tabs only, one tab does indeed map to exactly one indentation
level. One tabstop == one indent, on your editor and on mine. You do
not need to know my display convention to run my code.

All I can suggest is that you try it out: create a short source file
indented with tabs only, and play around with your editor's tabstop
setting (and make sure it is writing tab characters, not spaces, to the
source file). I promise you the Python interpreter will neither know
nor care what your editor display settings were when you last wrote the
file.

I realise that a lot of code out there uses spaces only. That's
unfortunate, but it doesn't mean we should stop explaining to people
why tab-indenting is a better standard. This is about freedom:
indenting with spaces lets you control over how other people view your
code; indenting with tabs give them that control.

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


Re: Tabs versus Spaces in Source Code

2006-05-16 Thread Kaz Kylheku
achates wrote:
> Kaz Kylheku wrote:
>
> > If you want to do nice typesetting of code, you have to add markup
> > which has to be stripped away if you actually want to run the code.
>
> Typesetting code is not a helpful activity outside of the publishing
> industry.

Be that as it may, code writing involves an element of typesetting. If
you are aligning characters, you are typesetting, however crudely.

> You might like the results of your typsetting; I happen not
> to. You probably wouldn't like mine. Does that mean we shouldn't work
> together? Only if you insist on forcing me to conform to your way of
> displaying code.

Someone who insists that everyone should separate line indentation into
tabs which achieve the block level, and spaces that achieve additional
alignment, so that code could be displayed in more than one way based
on the tab size without loss of alignment, is probably a "space cadet",
who has a bizarre agenda unrelated to developing the product.

There is close to zero value in maintaining such a scheme, and
consequently, it's hard to justify with a business case.

Yes, in the real world, you have to conform to someone's way of
formatting and displaying code. That's how it is.

You have to learn to read, write and even like more than one style.

> You are correct in pointing out that tabs don't allow for 'alignment'
> of the sort you mention:

That alignment has a name: hanging indentation.

All forms of aligning the first character of a line to some requirement
inherited from the previous line are called indentation.

Granted, a portion of that indentation is derived from the nesting
level of some logically enclosing programming language construct, and
part of it may be derived from the position of a character of some
parallel constituent within the construct.

> (lisp
>(nested list
> with symbols
> and things))
> But then neither does Python. I happen to think that's a feature.

Python has logical line continuation which gives rise to the need for
hanging indents to line up with parallel constituents in a folded
expression.

Python also allows for the possibility of statements separated by
semicolons on one line, which may need to be lined up in columns.

   var = 42; foo = 53
   x   =  2; y   = 10

> (And of course you can do what you like inside a comment. That's
> because tabs are for indentation, and indentation is meanigless in that
> context.

A comment can contain example code, which contains indentation.

What, I can't change the tab size to display that how I want? Waaah!!!
(;_;)

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


Re: Unable to extract Python source code using Windows

2006-05-16 Thread Scott David Daniels
[EMAIL PROTECTED] wrote:
> Scott ,
> I tried downloading for different archives, (different versions of
> Python) I can't believe they are all garbled.  But they all don't work
> with WinZip.

And what checksum did you get?


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


arrays, even, roundup, odd round down ?

2006-05-16 Thread Lance Hoffmeyer
So, I have using the following to grab numbers from MS Word.  I discovered that 
that there is a "special"
rule being used for rounding.

If a ??.5 is even the number is to rounded down (20.5 = 20)
if a ??.5 is odd the number is to rounded up (21.5 = 22)

Brands = ["B1","B2"]
A1 = []
A1 = [ re.search(r"(?m)(?s)\r%s.*?SECOND.*?(?:(\d{1,3}\.\d)\s+){2}" % i, 
target_table).group(1)  for i in Brands ]
A1 = [int(float(str(x))+0.5) for x in A1 ]
print A1


Any solutions for this line with the above conditions?
Just as a note, any other number ??.3,??.7 follows the normal pattern
of rounding (21.3 = 21, 20.3 = 20, 21.7 = 22, 20.7 = 21)

A1 = [int(float(str(x))+0.5) for x in A1 ]

Lance


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


Re: Beautiful parse joy - Oh what fun

2006-05-16 Thread Larry Bates

rh0dium wrote:
> Hi all,
> 
> I am trying to parse into a dictionary a table and I am having all
> kinds of fun.  Can someone please help me out.
> 
> What I want is this:
> 
> dic={'Division Code':'SALS','Employee':'LOO ABLE'}
> 
> Here is what I have..
> 
> html="""  src="/icons/ecblank.gif" border="0" height="1" width="1" alt=""
> />Division Code:
>  face="Arial">SALS  src="/icons/ecblank.gif" border="0" height="1" width="1" alt="" />  width="129">Employee:
>   face="Arial">LOO  size="2" face="Arial">ABLE """
> 
> 
> from BeautifulSoup import BeautifulSoup
> soup = BeautifulSoup()
> soup.feed(html)
> 
> dic={}
> for row in soup('table')[0]('tr'):
> column = row('td')
> print column[1].findNext('font').string.strip(),
> column[2].findNext('font').string.strip()
> dic[column[1].findNext('font').string.strip()]=
> column[2].findNext('font').string.strip()
> 
> for key in dic.keys():
> print key,  dic[key]
> 
>  The problem is I am missing the last name ABLE.  How can I get "ALL"
> of the text.  Clearly I have something wrong with my font string..  but
> what it is I am not sure of.
> 
> Please and thanks!!
> 
In the last row you have 3  tags.  The first one
contains LOO the second one is empty and the third one
contains ABLE.

LOO
   
  ABLE

Your code is not expecting the second (empty) tag.

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


Re: Python and Combinatorics

2006-05-16 Thread Peter Otten
Nic wrote:

> In my example I've chosen the number 3.
> How should I change the Python code in order to select another number
> (e.g. 7)?

Here is a parameterized render().

def render(w, h, suffixes="ab"):
pairs = list(unique(range(1, h+1), 2))
for item in unique(pairs, w):
for suffix in repeat(*[suffixes]*w):
yield tuple((a, b, s) for (a, b), s in izip(item, suffix))

if __name__ == "__main__":
for item in render(3, 4, "abc"):
print " ".join("%s%s%s" % t for t in item)

Experiment with the numbers to see the effects

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


still don't get unicode and xml - help!

2006-05-16 Thread jmdeschamps
I have to work with XML data containing accented characters (ISO-8859-1
encoding)
Using ElementTree, the only way i found to get the text attribute of a
node was to encode it individually, if you want. It doubles the amount
of time to process :-(
i surely doing this wrong...
What is the good way to do it? I didn't see an obvious way to do it
this time...
Thanks


## My XML Encoding Program
#! c:/python24/python -u
# -*- coding: iso-8859-1 -*-
import elementtree.ElementTree as ET
import time

def getMyXML(accentedTest):
filename="pagemembre.xml"
tree = ET.parse(filename)
elem = tree.getroot()
if accentedTest:
for i in elem:
f= i.text.encode("iso-8859-1") #encode pour lire les
accents
else:
for i in elem:
f= i.text
print f

def writeMyXML(myrange,accentedTest):
root = ET.Element("mondoc")
if accentedTest:
for i in range(myrange):
ch=ET.SubElement(root, "monchapitre")
ch.text="bel été et je serai la prêmière de la classe"
else:
for i in range(myrange):
ch=ET.SubElement(root, "monchapitre")
ch.text="bel ete et je serai la premiere de la classe"
tree = ET.ElementTree(root)
tree.write("pageMembre.xml","iso-8859-1")

if __name__ =="__main__":
accentedTest=int(raw_input("set 1 for accented test, 0 for ascii"))
print "First, writing"
t1=time.clock()
writeMyXML(2,accentedTest)
t2=time.clock()
print "Now, reading"
t3=time.clock()
getMyXML(accentedTest)
t4=time.clock()
print "accents
are",accentedTest,"writing=",str(t2-t1),"reading=",str(t4-t3)
s=raw_input("END XML TEST")
# End XML Encoding Program

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


Beautiful parse joy - Oh what fun

2006-05-16 Thread rh0dium
Hi all,

I am trying to parse into a dictionary a table and I am having all
kinds of fun.  Can someone please help me out.

What I want is this:

dic={'Division Code':'SALS','Employee':'LOO ABLE'}

Here is what I have..

html=""" Division Code:
SALS  Employee:
 LOO ABLE """


from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup()
soup.feed(html)

dic={}
for row in soup('table')[0]('tr'):
column = row('td')
print column[1].findNext('font').string.strip(),
column[2].findNext('font').string.strip()
dic[column[1].findNext('font').string.strip()]=
column[2].findNext('font').string.strip()

for key in dic.keys():
print key,  dic[key]

 The problem is I am missing the last name ABLE.  How can I get "ALL"
of the text.  Clearly I have something wrong with my font string..  but
what it is I am not sure of.

Please and thanks!!

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


Re: Tabs versus Spaces in Source Code

2006-05-16 Thread Duncan Booth
achates wrote:

>>In particular a common convention is to have indentations at 4
>>spaces and tabs expanding to 8 spaces.
> 
> Like all space-indenters, you seem to be hung up on the idea of a tab
> 'expanding' to n spaces. It only does that if you make your editor
> delete the tab character and replace it with spaces! Really, that is
> the only sense in which your statement makes any sense. If you want
> your indentation to have the width of four, eight, or nineteen spaces,
> set your tabstops accordingly.

It is strange. You use many of the same words as me, but they don't make 
any sense.

The point is about separating the presentation of the source file from the 
semantic content. When displaying the file you can choose to expand tabs to 
any suitable positions. These may be evenly spaced every n characters, or 
may vary across the page. However the important thing is that a tab does 
not map to a single indentation level in Python: it can map to any number 
of indents, and unless I know the convention you are using to display the 
tabs I cannot know how many indents are equivalent to a tabstop.

> Seriously people, this is about separating the content of a source file
> from how it is displayed. It's about letting people work together while
> also allowing them to have control over their own environments,
> something which is and always has been central to the hacker ethos.

Precisely. Using spaces everywhere allows this, using tabs everywhere 
allows this, mixing spaces and tabs is a bad thing. You have to agree a 
convention for the project and conform to it. My experience is that 'spaces 
only' is more common, but your experience may differ.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: calling upper() on a string, not working?

2006-05-16 Thread John Salerno
Bruno Desthuilliers wrote:

>> def encrypt_quote(original):
>   # Since it's here that we define that the new letters
>   # will be uppercase only, it's our responsability
>   # to handle any related conditions and problems
>   # The other functions shouldn't have to even know this.
>   original = original.upper()

>> def filter_letters(original):
>   # here, we *dont* have to do anything else than filtering
>   # upper/lower case is *not* our problem.
>> return ''.join(set(original) - PUNCT_SPACE_SET)

Thanks, I was wondering if it only needed to be done in a single place 
like that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: calling upper() on a string, not working?

2006-05-16 Thread Bruno Desthuilliers
John Salerno a écrit :
> Can someone tell me what's happening here. This is my code:
>  
> PUNCT_SPACE_SET = set(string.punctuation + string.whitespace)
> 
> def filter_letters(original):
> return ''.join(set(original) - PUNCT_SPACE_SET)
> 
> 'original' is a string. The above works as expected, but when I change 
> it to
> 
> return ''.join(set(original.upper()) - PUNCT_SPACE_SET)
> 
> it doesn't seem to work. The full code is below if it helps to understand.
> 

Don't assume str.upper() is broken !-)

In fact, your problem is that you create the translation table based on 
uppercase letters, and apply it to a non uppercased string :

> import string
> import random
> import itertools
> 
> PUNCT_SPACE_SET = set(string.punctuation + string.whitespace)
> 
> def convert_quote(quote):
> return encrypt_quote(quote).split('|')
> 
> def encrypt_quote(original):
   # Since it's here that we define that the new letters
   # will be uppercase only, it's our responsability
   # to handle any related conditions and problems
   # The other functions shouldn't have to even know this.
   original = original.upper()
> original_letters = filter_letters(original)
> new_letters = list(string.ascii_uppercase)
> while True:
> random.shuffle(new_letters)
> trans_letters = ''.join(new_letters)[:len(original_letters)]
> if test_code(original_letters, trans_letters):
> trans_table = string.maketrans(original_letters, trans_letters)
> break
> return original.translate(trans_table)
> 
> def filter_letters(original):
   # here, we *dont* have to do anything else than filtering
   # upper/lower case is *not* our problem.
> return ''.join(set(original) - PUNCT_SPACE_SET)
> 
> def test_code(original_letters, trans_letters):
> for pair in itertools.izip(original_letters, trans_letters):
> if pair[0] == pair[1]:
> return False
> return True
> 
> if __name__ == '__main__':
> print convert_quote("The past is not dead. In fact, it's not even 
> past.|William Faulkner")

["XCD ONKX AK IGX LDNL. AI WNBX, AX'K IGX DYDI ONKX.", 'UAEEANP WNREQIDS']
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: calling upper() on a string, not working?

2006-05-16 Thread Larry Bates
John Salerno wrote:
> Can someone tell me what's happening here. This is my code:
> 
> 
> 
> PUNCT_SPACE_SET = set(string.punctuation + string.whitespace)
> 
> def filter_letters(original):
> return ''.join(set(original) - PUNCT_SPACE_SET)
> 
> 
> 
> 'original' is a string. The above works as expected, but when I change
> it to
> 
> return ''.join(set(original.upper()) - PUNCT_SPACE_SET)
> 
> it doesn't seem to work. The full code is below if it helps to understand.
> 
> 
> 
> import string
> import random
> import itertools
> 
> PUNCT_SPACE_SET = set(string.punctuation + string.whitespace)
> 
> def convert_quote(quote):
> return encrypt_quote(quote).split('|')
> 
> def encrypt_quote(original):
> original_letters = filter_letters(original)
> new_letters = list(string.ascii_uppercase)
> while True:
> random.shuffle(new_letters)
> trans_letters = ''.join(new_letters)[:len(original_letters)]
> if test_code(original_letters, trans_letters):
> trans_table = string.maketrans(original_letters, trans_letters)
> break
> return original.translate(trans_table)
> 
> def filter_letters(original):
> return ''.join(set(original) - PUNCT_SPACE_SET)
> #return ''.join(set(original.upper()) - PUNCT_SPACE_SET)
> 
> def test_code(original_letters, trans_letters):
> for pair in itertools.izip(original_letters, trans_letters):
> if pair[0] == pair[1]:
> return False
> return True
> 
> if __name__ == '__main__':
> print convert_quote("The past is not dead. In fact, it's not even
> past.|William Faulkner")

Not exactly sure why you think its not working.  When you create a set
from the original.upper() you get a smaller number of characters because
you no longer get both 'T' and 't' as well as 'I' and 'i' as you do in
the lower case version of the string.

>>> set(original.split('|')[0])
set(['a', ' ', 'c', 'e', 'd', "'", 'f', 'i', 'h', ',', 'o', 'n', 'p', 's', 'T',
'v', 'I', '.', 't'])
>>> set(original.split('|')[0].upper())
set(['A', ' ', 'C', 'E', 'D', "'", 'F', 'I', 'H', ',', 'O', 'N', 'P', 'S', 'T',
'V', '.'])
>>>

sets can only contain "unique" entries.  Letters that are repeated only get
added once.  When you do .upper() you convert lowercase 't' to 'T' and lower
case 'i' to 'I' so that letter only gets added to the set a single time.

Hope info helps.

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


Re: SystemError: ... cellobject.c:22: bad argument to internal ?

2006-05-16 Thread robert
[EMAIL PROTECTED] wrote:
> robert wrote:
> 
>>From the trace of a 2.3.5 software i got:
>>
>>\'SystemError:
>>C:sfpythondist23srcObjectscellobject.c:22: bad
>>argument to internal
>>function\\n\']
> 
> 
> ...
> 
> 
>>Will there be another bug-fix release of Python 2.3   ?
> 
> 
> No, is this still a problem in 2.4?  2.4.4 is planned to be released

( Am bound to py2.3 for this app - as py2.4 more than doubled 
distributable app sizes with MSVCRTL71, CJK codecs in core etc... )

> this summer.  Can you post the entire code (that doesn't reference
> anything outside the stdlib) that causes this problem?
> 

Solved - no Python error.

The bug turned out to be a refcount bug in PythonWin's 
win32ui.HookMessage internals: the Python callback upon WM_TIMER didn't 
INCREF the called function object itself. When the function removed 
itself from the hook list (indirectly), the executing functions 
closure/cells.. were recycled while the function was still executing.

https://sourceforge.net/tracker/index.php?func=detail&aid=1489690&group_id=78018&atid=551954

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


Re: calling upper() on a string, not working?

2006-05-16 Thread John Salerno
Michal Kwiatkowski wrote:

> And here you're translating 'original' (which contains a lot of
> lowercase letters) with use of trans_table that maps only uppercase
> characters. This return should be:
> 
> return original.upper().translate(trans_table)

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


Re: Tabs versus Spaces in Source Code

2006-05-16 Thread achates
Duncan Booth wrote:

>Because it doesn't mean 'one level of indentation', it means 'move to next
>tabstop' and a tabstop isn't necessarily the same as a level of
>indentation.

'move to next tabstop' is how your editor interprets a tab character.
'one level of indentation' is how the language parser interprets it.
The two are entirely consistent, in that they are both isomorphic
mappings of the same source file.

>In particular a common convention is to have indentations at 4
>spaces and tabs expanding to 8 spaces.

Like all space-indenters, you seem to be hung up on the idea of a tab
'expanding' to n spaces. It only does that if you make your editor
delete the tab character and replace it with spaces! Really, that is
the only sense in which your statement makes any sense. If you want
your indentation to have the width of four, eight, or nineteen spaces,
set your tabstops accordingly.

Seriously people, this is about separating the content of a source file
from how it is displayed. It's about letting people work together while
also allowing them to have control over their own environments,
something which is and always has been central to the hacker ethos.

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


Re: calling upper() on a string, not working?

2006-05-16 Thread Michal Kwiatkowski
John Salerno wrote:
> def encrypt_quote(original):
>  original_letters = filter_letters(original)

You call filter_letters() which makes upper() on all letters, so
original_letters contain only uppercase letters.

>  new_letters = list(string.ascii_uppercase)
>  while True:
>  random.shuffle(new_letters)
>  trans_letters = ''.join(new_letters)[:len(original_letters)]
>  if test_code(original_letters, trans_letters):
>  trans_table = string.maketrans(original_letters,
>  trans_letters) break
>  return original.translate(trans_table)

And here you're translating 'original' (which contains a lot of
lowercase letters) with use of trans_table that maps only uppercase
characters. This return should be:

return original.upper().translate(trans_table)

mk
-- 
 . o .   >>  http://joker.linuxstuff.pl  <<
 . . o   It's easier to get forgiveness for being wrong
 o o o   than forgiveness for being right.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: calling upper() on a string, not working?

2006-05-16 Thread John Salerno
Felipe Almeida Lessa wrote:
> Em Ter, 2006-05-16 às 20:25 +, John Salerno escreveu:
>> it doesn't seem to work. The full code is below if it helps to understand.
> 
> Why doesn't it work? What does it do, what did you expect it to do?

If you run the whole script with the first line (the one not commented), 
you get output similar to this, which is correct:

 >>>
["AMN RIPQ LP WOQ SNIS. BW VIDQ, LQ'P WOQ NHNW RIPQ.", 'ULJJLIY TIZJXWNE']
 >>>

But if you use the line with the upper() call, you get this:

 >>>
["Bhe past is not dead. Dn fact, it's not even past.", 'Killiam Qaulkner']
 >>>

Now, I know the actual upper() function works, but I can't understand if 
there's a problem with *when* it's being called, or what's being done 
with it to get the second result above.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: IDLE confusion

2006-05-16 Thread Terry Reedy

"Christophe" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Try in the IDLE menu [Shell] "Restart Shell" (Ctrl+F6) each time you
> have changed something in your files - this "resets" anything previously
> imported, which stays the same way otherwise.

And I though that "bug" was fixed already :)

On my system, the current 2.4.3 version of Python+IDLE *does* auto restart 
with each run (F5).  So either the OP is using a much older version (did 
not specify) or the respondant mis-diagnosed the problem.

tjr



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


Re: How to log only one level to a FileHandler using python logging module.

2006-05-16 Thread zacherates
Try looking into logging.Filters:
http://docs.python.org/lib/node358.html

An example:

import logging

class InfoFilter(logging.Filter):
def filter(self, record):
return record.levelno == 20

if __name__ == "__main__":
logger = logging.getLogger()
hdlr = logging.FileHandler("blah.log")
hdlr.addFilter(InfoFilter())
logger.addHandler(hdlr)

logger.exception("ERROR WILL ROBINSON")

Cheers,
  Aaron


fuzzylollipop wrote:
> I want a FileHandler to only log a single level say for example
> logging.INFO, and nothing else.
> do I need to create a custom Handler for this or is this doable with
> some magic that is not documeneted somewhere?

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


Re: Option parser question - reading options from file as well as command line

2006-05-16 Thread Max Erickson
Andrew Robert <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Any ideas?

I don't know much about optparse, but since I was bored:

>>> help(o.parse_args)
Help on method parse_args in module optparse:

parse_args(self, args=None, values=None) method of 
optparse.OptionParser instance
parse_args(args : [string] = sys.argv[1:],
   values : Values = None)
-> (values : Values, args : [string])

Parse the command-line options found in 'args' (default:
sys.argv[1:]).  Any errors result in a call to 'error()', which
by default prints the usage message to stderr and calls
sys.exit() with an error message.  On success returns a pair
(values, args) where 'values' is an Values instance (with all
your option values) and 'args' is the list of arguments left
over after parsing options.

>>> o.parse_args('seven')
Traceback (most recent call last):
  File "", line 1, in ?
o.parse_args('seven')
  File "C:\bin\Python24\lib\optparse.py", line 1275, in parse_args
stop = self._process_args(largs, rargs, values)
  File "C:\bin\Python24\lib\optparse.py", line 1322, in _process_args
del rargs[0]
TypeError: object doesn't support item deletion
>>> 

That's the result of poking an optionParser instance in Idle. 
parse_args is expecting something that looks like sys.argv[1:], which 
is a list. You are passing it a string.

max

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


Re: calling upper() on a string, not working?

2006-05-16 Thread Felipe Almeida Lessa
Em Ter, 2006-05-16 às 20:25 +, John Salerno escreveu:
> it doesn't seem to work. The full code is below if it helps to understand.

Why doesn't it work? What does it do, what did you expect it to do?

>>> ''.join(set('hi'))
'ih'
>>> ''.join(set('HI'))
'IH'
>>> ''.join(set('hiHI'))
'ihIH'
>>> ''.join(set('hiHI'.upper()))
'IH'


-- 
Felipe.

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

calling upper() on a string, not working?

2006-05-16 Thread John Salerno
Can someone tell me what's happening here. This is my code:



PUNCT_SPACE_SET = set(string.punctuation + string.whitespace)

def filter_letters(original):
 return ''.join(set(original) - PUNCT_SPACE_SET)



'original' is a string. The above works as expected, but when I change 
it to

return ''.join(set(original.upper()) - PUNCT_SPACE_SET)

it doesn't seem to work. The full code is below if it helps to understand.



import string
import random
import itertools

PUNCT_SPACE_SET = set(string.punctuation + string.whitespace)

def convert_quote(quote):
 return encrypt_quote(quote).split('|')

def encrypt_quote(original):
 original_letters = filter_letters(original)
 new_letters = list(string.ascii_uppercase)
 while True:
 random.shuffle(new_letters)
 trans_letters = ''.join(new_letters)[:len(original_letters)]
 if test_code(original_letters, trans_letters):
 trans_table = string.maketrans(original_letters, trans_letters)
 break
 return original.translate(trans_table)

def filter_letters(original):
 return ''.join(set(original) - PUNCT_SPACE_SET)
 #return ''.join(set(original.upper()) - PUNCT_SPACE_SET)

def test_code(original_letters, trans_letters):
 for pair in itertools.izip(original_letters, trans_letters):
 if pair[0] == pair[1]:
 return False
 return True

if __name__ == '__main__':
 print convert_quote("The past is not dead. In fact, it's not even 
past.|William Faulkner")
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using python for a CAD program

2006-05-16 Thread Grant Edwards
On 2006-05-16, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> Yes, I figured I should be pretty expert at what's out there
> first before redoing something and making in inferior to the
> existing solution.

Eagle from Cadsoft.de is a pretty decent (and free for
educational/hobby use) integrated schematic capture and board
layout package (including a quite usable auto-router).  It
doesn't have integrated simulation, but after messing about
with both gEDA and Eagle for an hour or two the you get a good
feel for the difference between an integrated tool-set and
something cobbled together from disparate utilities.

-- 
Grant Edwards   grante Yow!  Of course, you
  at   UNDERSTAND about the PLAIDS
   visi.comin the SPIN CYCLE --
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For Large Dictionaries Could One Use Separate Dictionaries Where Each Dictionary Covers an Interval of the Input Range?

2006-05-16 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 <[EMAIL PROTECTED]> wrote:
>
>Graham> Looking up a key in a dictionary is done in constant-time,
>Graham> i.e. it doesn't matter how large the dictionary is.
>
>Doesn't that depend on how many keys hash to the same value?  For small
>dictionaries keeping the max keys that hash to the same value small isn't a
>huge problem.  For large dictionaries (millions of keys) might you have some
>long chains?  Or in an effort to reduce the chain length, wind up using so
>much virtual memory that you wind up wrecking performance by swapping?

If you're getting long hash chains, you're either using a bad hash
function, or your table isn't big enough.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A critic of Guido's blog on Python's lambda

2006-05-16 Thread Ken Tilton


Lasse Rasinen wrote:
> Ken Tilton <[EMAIL PROTECTED]> writes:
> 
> 
>>If you want to insist on how perfect your code is, please go find
>>ltktest-cells-inside.lisp in the source you downloaded and read the long
>>comment detailing the requirements I have identified for "data integrity".
>>Then (a) tell me how your code fails at integrity, (b) fix it, and (c)
>>tell me again how easy Cells is. :)
> 
> 
> Found it and read it; it was most enlightening. I claim my system fulfills
> the first three requirements(*), while most likely failing gloriously on
> the two last ones.



 From #1: "recompute all and (for efficiency) only state computed off X 
(directly or indirectly through some intermediate datapoint)"

Bzzzt! Another 47hrs, directions from a mentor, and a reference 
implementation and you /still/ do not even understand the requirements, 
let alone have a working port. The good news is that it is not an 
integrity requirement that is being missed, it is the efficiency 
requirement I snuck in there. The bad news is, see below.

Want to find the efficiency shortcoming yourself, or should I tell you? 
You are entitled to the latter given the rules of the game (simulating a 
pythonista student making off with five thousand undeserved dollars). :)

> 
> I'll postpone (b) while I've had a chance to think it over(**), but in the
> face of the evidence I'm willing to admit my earlier work estimates (which
> should have had a smiley next to them anyway ;-) were in error.

Aw, shucks, then I will admit that, before today, I never actually 
looked at your code. :)

Well, I followed the URL and glanced at it, but I missed the use of the 
timestamp. Speaking of which, Holy Granularity, Batman! You use 
Time.time() to determine currency of a computation?!:

"time()
 Return the time as a floating point number expressed in seconds 
since the epoch, in UTC. Note that even though the time is always 
returned as a floating point number, not all systems provide time with a 
better precision than 1 second."

One /second/?! Exactly how slow is Python? I know you guys love that 
issue as much as Lispniks. In un-compiled Lisp:

  CTK(4): (loop repeat 2 do (print (get-internal-real-time)))
  464033837
  464033837

And you have no idea how slow PRINT is. btw, I thought Python was 
portable. What is with the Time class and "not all systems..."? Check 
out the Lisp:

(defun zoom ()
   (loop with start = (get-internal-real-time)
 while (= start (get-internal-real-time))
 count 1 into cities-destroyed
 finally (format t "~a cities destroyed in 1/~a of a second"
   cities-destroyed internal-time-units-per-second)))

internal-time-units-per-second is (from the standard):

"Constant Value:
A positive integer, the magnitude of which is 
implementation-dependent. "

So we vary, too, but my Lisp has to tell me so I can normalize. Anyway, 
running that repeatedly I get pretty wild variation. My high score is:

CTK(18): 11637 cities destroyed in 1/1000 of a second

My low was under a thousand! I guess I have to wait until we cross a 
millisecond boundary:

(defun zoom ()
   (symbol-macrolet ((now (get-internal-real-time)))
 (loop with start = (loop for mid = now
while (= mid now)
finally (return now))
 while (= start now)
 count 1 into cities-destroyed
 finally (format t "~a cities destroyed in 1/~a of a second"
   cities-destroyed
   internal-time-units-per-second

Ok, now I am consistently taking out about 11.5k Russian cities. And you 
need to fix your system.

Just use a counter -- does Python have bignums? if not, you'll have to 
worry about wrapping. (the sound you hear is a project schedule 
slipping. )

> 
> I won't admit to destroying Moscow, though. See (*).

Sorry, you actually /have/ violated the data integrity requirement. You 
confess below to missing this one:

"a corollary: should a client observer SETF a datapoint Y, all the above 
must happen with values current with not just X, but also with the value 
of Y /prior/ to the change to Y."

Well, how can you claim integrity when some values do not get 
recalculated until the world has moved on to state N+2, if you will? 
State N+1 had the information that headed off the launch.

Bye bye, Kremlin.

The easiest way to construct such a scenario would be with an ephemeral 
cell. As you know... oops. Maybe you do not. Well, spreadsheets are 
kinda steady state in orientation. Given a world of other values, this 
is what my value should be. But what about events? You have been using 
your version of PyCells in real-world applications for a while... oops. 
No you have not. Well, when you start trying to handle events from an 
event loop, you will discover a need to model events. (Trust your 
mentor.) You need a slot that can be assigned normally, propagate 
according to the above rules and regulations, and 

Re: Using python for a CAD program

2006-05-16 Thread 63q2o4i02
Yes, I figured I should be pretty expert at what's out there first
before redoing something and making in inferior to the existing
solution.  I took a quick peek at cadence courses, and they're out of
my personal price range.  I have a new job coming up which should lead
into IC design after some time, and I should probably ask them to send
me to the course.

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


  1   2   3   >