Re: What are __slots__ used for?

2005-07-05 Thread Simon Percivall
Most have already been said, but have a look at
http://docs.python.org/ref/slots.html for authoritative documentation.

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


what is __init__.py used for?

2005-07-05 Thread [EMAIL PROTECTED]
I am a new learner of Python Programming Language.
Now. I am reading a book.
In the  section relating to module, I see an example.
the directory tree looks like below:
root\
system1\
__init__.py
utilities.py
main.py
other.py
system2\
__init__.py
utilities.py
main.py
other.py
system3\ # Here or elsewhere
__init__.py   # Your new code here
myfile.py

question
==
   I was wonderring ... what is the __init__.py used for ?
   This question may seems to be stupid for an expert.
   But, if you can give the answer, it will be helpful for me.

  thanks.

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


Re: what is __init__.py used for?

2005-07-05 Thread Simon Brunning
On 5 Jul 2005 01:31:09 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> I am a new learner of Python Programming Language.

Welcome!

>I was wonderring ... what is the __init__.py used for ?
>This question may seems to be stupid for an expert.
>But, if you can give the answer, it will be helpful for me.

The __init__.py files make Python treat the directories as packages -
see http://docs.python.org/tut/node8.html#SECTION00840.

We have to do something about those URLs!

-- 
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what is __init__.py used for?

2005-07-05 Thread Lutz Horn
* [EMAIL PROTECTED]:
> root\
> system1\
> __init__.py
> utilities.py
> main.py
> other.py
...
>I was wonderring ... what is the __init__.py used for ?
>This question may seems to be stupid for an expert.

The __init__.py is needed for Python to recognize the system1 directory
as an importable module.

Lutz

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


Re: Outlook COM: how to create a MailItem from a .msg file

2005-07-05 Thread Guy Lateur
Thanks for the suggestion, Tim. Unfortunately, I get a 'connection refused' 
error on the line 'M = imaplib.IMAP4(server)'. It says "socket.error: 
(10061, 'Connection refused')". I've tried both the external IP adress and 
the internal one (10.0.0.2). I'm sure there's a way to get over this, isn't 
there?

One more question: can I avoid having (plain text) passwords in my code? I 
guess I could make a special account for this with a password known by 
everybody.

Cheers,
g




"Tim Williams (gmail)" <[EMAIL PROTECTED]> schreef in bericht 
news:[EMAIL PROTECTED]

Lateral thinking ?

=== untested ===

import imaplib, time, sys

f = open(msg_file)
r = f.readlines()
f.close()
msg1 = ''.join(r)
server = 'my.exchangeserver.com' # or IP address

user = 'user'
pw = 'pw'

M = imaplib.IMAP4(server)
M.sock.settimeout(120)
M.login(user,pw)[1][0]
M.select()
M.append('INBOX',None ,time.time() , msg1) # Inbox or other folder name
print "MESSAGE successfully saved"
#M.close()  Don't use close,  deletes/purges items
M.logout()[1][0] 


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


RE: Outlook COM: how to create a MailItem from a .msg file

2005-07-05 Thread Tim Golden
[Guy Lateur]

| Thanks for the suggestion, Tim. Unfortunately, I get a 
| 'connection refused' 
| error on the line 'M = imaplib.IMAP4(server)'. It says "socket.error: 
| (10061, 'Connection refused')". I've tried both the external 
| IP adress and 
| the internal one (10.0.0.2). I'm sure there's a way to get 
| over this, isn't 
| there?

Could simply be that the Exchange server isn't running an
IMAP service (or whatever it's called). Ours doesn't.

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: Considering moving from Delphi to Python [Some questions]

2005-07-05 Thread Harald Armin Massa
> I want some feedback on folllwing:
> anybody who has experience in writing SOAP servers in Python and data
> entry heavy web applications.
> Any suggestions?
> darkcowherd
>
I have never written SOAP Servers. But I have very very good experience
in creating entry heavy web application using Python and Quixote;
Webserver Medusa.

The current entry forms have at maximum 700 distinct entries, of which
groups can be multiplied via XMLHTTPRequest and DOM-Modifikation
without page reloading.
Speed is great. Because of very slow rendering and various buggies
within IE (beast took longer to render then me to deliver) we switched
to Firefox.

System is performing adequately well and is being constantly extended;
Pythons clear structure makes that easy.

Hope that helps,

Harald

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


Re: Outlook COM: how to create a MailItem from a .msg file

2005-07-05 Thread Richard Brodie

"Tim Golden" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]

> Could simply be that the Exchange server isn't running an
> IMAP service (or whatever it's called). Ours doesn't.

I would have thought most wouldn't run IMAP in the clear;
over SSL maybe.


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


Re: Outlook COM: how to create a MailItem from a .msg file

2005-07-05 Thread Guy Lateur
Are you saying it's unsafe to do that? I only need this for an application 
running locally, I mean, from within our LAN domain. We do have Exchange 
webmail.

I've asked our Exchange expert wether or not IMAP is running; awaiting an 
answer..



"Richard Brodie" <[EMAIL PROTECTED]> schreef in bericht 
news:[EMAIL PROTECTED]
>
> I would have thought most wouldn't run IMAP in the clear;
> over SSL maybe.
>
> 


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


Re: what is __init__.py used for?

2005-07-05 Thread Walter Dörwald
[EMAIL PROTECTED] wrote:

> I am a new learner of Python Programming Language.
> Now. I am reading a book.
> In the  section relating to module, I see an example.
> the directory tree looks like below:
> root\
> system1\
> __init__.py
> utilities.py
> main.py
> other.py
> system2\
> __init__.py
> utilities.py
> main.py
> other.py
> system3\ # Here or elsewhere
> __init__.py   # Your new code here
> myfile.py
> 
> question
> ==
>I was wonderring ... what is the __init__.py used for ?
>This question may seems to be stupid for an expert.
>But, if you can give the answer, it will be helpful for me.

If the root directory is on the Python search path, you can do "import 
system2.other" or "from system2 import other", to import the other.py 
module. But you can also do "import system2". This means that the source 
code for the system2 module has to live somewhere. __init.py inside the 
directory with the same name is this "somewhere". Without this 
__init__.py inside the system2 directoy you couldn't import other.py 
because Python doesn't know where the source code for system2 lives and 
refuses to treat system2 as a package.

Hope that helps,
Walter Dörwald
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Outlook COM: how to create a MailItem from a .msg file

2005-07-05 Thread Richard Brodie

"Guy Lateur" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]

> Are you saying it's unsafe to do that? I only need this for an application
> running locally, I mean, from within our LAN domain. We do have Exchange
> webmail.

I wasn't offering security advice but merely observing that your Exchange server
could be running SSL secured IMAP only (which would be on a different port
from normal IMAP). In that case an IMAP4_SSL instance would be what you
need.


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


Re: Outlook COM: how to create a MailItem from a .msg file

2005-07-05 Thread Tim Williams (gmail)
On 7/5/05, Guy Lateur <[EMAIL PROTECTED]> wrote:
> Thanks for the suggestion, Tim. Unfortunately, I get a 'connection refused'
> error on the line 'M = imaplib.IMAP4(server)'. It says "socket.error:
> (10061, 'Connection refused')". I've tried both the external IP adress and
> the internal one (10.0.0.2). I'm sure there's a way to get over this, isn't
> there?

I just tried this and it failed with IP addresses but not
hostnames/machine names,  try it again with the server name. :)
  
> One more question: can I avoid having (plain text) passwords in my code? I
> guess I could make a special account for this with a password known by
> everybody.

Depends how secure you need it to be.For my simple stuff I just do
something like this

In idle/pythonwin/interactive

>>> p = 'password_string'
>>> p = p.encode("utf16")
>>> p
'\xff\xfep\x00a\x00s\x00s\x00w\x00o\x00r\x00d\x00_\x00s\x00t\x00r\x00i\x00n\x00g\x00'

Then in the script
user = mylogin
pw = 
'\xff\xfep\x00a\x00s\x00s\x00w\x00o\x00r\x00d\x00_\x00s\x00t\x00r\x00i\x00n\x00g\x00'
M = imaplib.IMAP4(server)
M.login(mylogin,pw.decode("utf16")
('OK', ['LOGIN completed.'])

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


distutils is able to handle...

2005-07-05 Thread mg
Hello

I work on an finite element framework and Python bindings have been 
developped.
Actually, we use Boost.Build as build system but we would like to change 
it.

We have two kinds of problems. First, the framework is used for generate 
pure C++ applications with static libraries ; second, the framework have 
some dependencies to fortran projects.
Then, in order to know if Distutils can be use in our case, I would like 
to know if :
- Can distutil compile static C/C++ libraries ?
- Can distutil compile C/C++ applications ?
- Can distutil manage fortran compiler and compile fortran libraries and 
applications ?

Thank for your answers
-- 
http://mail.python.org/mailman/listinfo/python-list


(Win32 API) callback to Python, threading hiccups

2005-07-05 Thread Francois De Serres
Hiho,

could somebody please enlighten me about the mechanics of C callbacks to 
Python? My domain is more specifically callbacks from the win32 API, but 
I'm not sure that's where the problem lies. Here's a description...

I want a callback-based MIDI input/processing, so PortMidi was not an 
alternative. I have written a C extension module that links to the mmsys 
MIDI API. I separated the win32-dependant code from the Python extension 
code, so a) the module interface is system-neutral, b) the 
implementation can be tested (re-used) outside of Python. So, that code 
is tested OK, but it might be useful to sketch it's design:
- as you may know, the MIDI input on win32 is already managed thru a 
callback mechanism; the driver calls back your program with data buffers
- yet, I don't call directly into Python from the callback, since some 
restrictions apply on what system calls you can make from there, and I 
don't know what Python's interpreter / scripts might call.
- so, on callback, I create a new thread, after checking that the 
previous one has returned already (WaitOnSingleObject(mythread)) so we 
only have one thread involved.
- this is this thread that calls the user callback, yet this callback 
isn't yet a Python callable, we're still in native C code.
- on the side of the extension module now, I merely copied the callback 
example from the Python/C API doc, and added GIL management around the call:

static PyObject * my_callback = NULL; //this gets fixed by a 
setCallback() func
static void external_callback(const MidiData * const data) {   
if (my_callback && (my_callback != Py_None)) {
if (! data) {
PyErr_SetString(PyExc_IndexError, getLastErrorMessage());
} else {  
PyObject * arglist = NULL;
PyObject * result = NULL;
arglist = Py_BuildValue("(i,i,s#)", data->deviceIndex, 
data->timestamp, data->buffer, data->size);// 0, 0, "test", 4);//
   
PyGILState_STATE gil = PyGILState_Ensure();
result = PyEval_CallObject(my_callback, arglist);   
PyGILState_Release(gil);
   
Py_DECREF(arglist);
Py_DECREF(result);  
}
}
}

- this one above is what is actually passed as callback to the 'native' 
C part. So, here's what (I presume) happens:
1. the driver calls into my C code
2. my C code spawns a thread that calls into the extension
3. the extension calls into Python, after acquiring the GIL

Now, here's the hiccup:
inside a Python script, anytime a Python object is accessed by both the 
(Python) callback and the main program, I get a GPF :/

You bet I tried to use locks, Queues and whatnot, but nothing will do, 
it seems I get protection faults on accessing... thread exclusion objects.

Yet, there is a way where it works seamlessly: it's when the __main__ 
actually spawns a threading.Thread to access the shared object. Hence I 
am lost.

This works:

def input_callback(msg):
midiio.send(msg) ##MIDI thru, a call into my extension that wraps 
the implementation call with BEGIN_ALLOW_THREADS and END_...
__main__:
raw_input()

This results in GPF as soon as the callback is fired:

tape = Queue.Queue()
def input_callback(msg):
tape.put(msg)
__main__:
while True:
   print tape.get()

This works like a charm:

tape = Queue.Queue()
def input_callback(msg):
tape.put(msg)
def job():
while True:
   print tape.get()
__main__:
t = threading.Thread(target = job)
t.start()
raw_input()

Note that I also get a GPF in the later case if I stop the program with 
KeyInterrupt, but I guess it's something I'll look into afterwards...

While I can think of hiding away the added threading within a wrapper 
module, I won't sleep well untill I figure out what's really happening. 
Could someone save my precious and already sparse sleeping time, by 
pointing me to what I'm missing here?

WinXP SP1
Python 2.4.1
MinGW GCC 3.4.2

TIA,
Francois De Serres


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


Re: what is __init__.py used for?

2005-07-05 Thread John Roth

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>I am a new learner of Python Programming Language.
> Now. I am reading a book.

...

> ==
>   I was wonderring ... what is the __init__.py used for ?
>   This question may seems to be stupid for an expert.
>   But, if you can give the answer, it will be helpful for me.

__init__.py is used for two things. One is as a flag to
indicate that the python programs in the directory are
part of a module.

The other is as the module itself. Let's take a simple
example. Assume you have a directory named breakfast
which contains modules named spam.py, eggs.py,
toast.py and jam.py, and that the directory containing
breakfast is on the PYTHONPATH.

If it try to import spam.py by writing

import breakfast.spam

it won't work because the breakfast directory
doesn't contain an __init__.py file.

If I then add __init__.py to the breakfast directory,
the import will work, and the result will be *two*
modules loaded. The first module will be bound to
the identifier 'breakfast' in your module. It will be
completely empty except for the identifier 'spam'
which will have the spam module bound to it.

This means that if the spam module contains,
for example, an identifier named "vikings", then I
can refer to it as breakfast.spam.vikings.

The real kicker here is that when I say that the
first module will be completely empty, it's not
quite true. First, it will have some standard
identifiers that all modules have, and second
it will have anything you put into the __init__.py
module file. This last is an advanced feature, and
you're well advised to stay away from it until
you've got a lot more experiance.

HTH

John Roth


>
>  thanks.
> 

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


Re: math.nroot [was Re: A brief question.]

2005-07-05 Thread Michael Hudson
Tim Peters <[EMAIL PROTECTED]> writes:

> All Python behavior in the presence of infinities, NaNs, and signed
> zeroes is a platform-dependent accident, mostly inherited from that
> all C89 behavior in the presence of infinities, NaNs, and signed
> zeroes is a platform-dependent crapshoot.

As you may have noticed by now, I'd kind of like to stop you saying
this :) -- at least on platforms where doubles are good old-fashioned
754 8-byte values.

But first, I'm going to whinge a bit, and lay out some stuff that Tim
at least already knows (and maybe get some stuff wrong, we'll see).

Floating point standards lay out a number of "conditions": Overflow
(number too large in magnitude to represent), Underflow (non-zero
number to small in magnitude to represent), Subnormal (non-zero number
to small in magnitude to represent in a normalized way), ...

For each condition, it should (at some level) is possible to trap each
condition, or continue in some standard-mandated way (e.g. return 0
for Underflow).

While ignoring the issue of allowing the user to control this, I do
wish sometimes that Python would make up it's mind about what it does
for each condition.  There are a bunch of conditions which we
shouldn't and don't trap by default -- Underflow for example.  For the
conditions that probably should result in an exception, there are
inconsistencies galore:

>>> inf = 1e300 * 1e300 # <- Overflow, no exception
>>> nan = inf/inf # <- InvalidOperation, no exception
>>> pow(1e100, 100) <- Overflow, exception
Traceback (most recent call last):
  File "", line 1, in ?
OverflowError: (34, 'Numerical result out of range')
>>> math.sqrt(-1) # <- InvalidOperation, exception
Traceback (most recent call last):
  File "", line 1, in ?
ValueError: math domain error

At least we're fairly consistent on DivisionByZero...

If we're going to trap Overflow consistently, we really need a way of
getting the special values reliably -- which is what pep 754 is about,
and its implementation may actually work more reliably in 2.5 since my
recent work...

On the issue of platforms that start up processes with traps enabled,
I think the correct solution is to find the incantation to turn them
off again and use that in Py_Initialize(), though that might upset
embedders.

Cheers,
mwh

-- 
   rasterman is the millionth monkey
-- from Twisted.Quotes
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Outlook COM: how to create a MailItem from a .msg file

2005-07-05 Thread Guy Lateur
> I just tried this and it failed with IP addresses but not
> hostnames/machine names,  try it again with the server name. :)

Nope, same problem. I think TJG might be right, and our server probably 
doesn't have IMAP running (yet).



> Depends how secure you need it to be.For my simple stuff I just do
> something like this
> [snip]

That's a nice thought, although the pw is still pretty visible. Maybe 
there's a way to encode/decode it using some sort of key (that only I know), 
that produces a truly unrecognisable pw?

Thanks for the input,
g


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


Re: How do you program in Python?

2005-07-05 Thread Harald Armin Massa
Peter,

> I do all my work using Scite
Me too!

> So, any time I need to test the changes, I hit four keys (which at this
> point is understandably more like a "chord" that I hit without direct
> awareness of it) and I'm done.  Sounds pretty close to old-style BASIC
> and since I've come that route too (in the distant past), this may not
> be a coincidence.

in addition I have set up scite and paths so that "F5", the scite run
command, invokes python , with output given in the scite
output area (and saving before)
in addition, ctrl+1 does a compile (checking for syntax errors)

and exceptions are printed out in the scite output, colourcoded and
with double-click on them scite opens the appropriate script at the
offending position.

VERY quick.

Harald

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-05 Thread mcherm
Steven D'Aprano writes:
> Lambda is no more an obscure name than "function", "decorator", "closure",
> "class", or "module". The first time you come across it, you don't know
> what it means. Then you learn what it means, and then you know.

I believe you've made two errors here. First of all, "lambda" is part
of the Python language, while "function", "decorator", "closure", and
"module" are not. The fact that some words which are NOT part of the
Python language are obscure has no bearing whatsoever on "lambda". The
obnubilation created by this comparison is an obscure word also, but,
it isn't relevent to the Python language.

The second error is that I believe most english speakers COULD provide
a definition for the fairly common words "function", "class", and
"decorator". The exact meaning of "class" might not be what they expect
at first, but exposure to any object oriented language would make the
concept quickly familiar. But "lambda" has a very clear meaning... it's
a letter of the greek alphabet. The connection between that letter and
anonymous functions is tenuous at best, and fails the test of making
Python read like "executable pseudocode".

-- Michael Chermside

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


Re: f*cking re module

2005-07-05 Thread François Pinard
[D H]
> Gustavo Niemeyer wrote:
> > That's what I love in that news group. Someone comes with a
> > stupid and arrogant question, and someone else answers in a
> > calm and reasonable way.

> ...and then someone else comes along and calls the first person stupid
> and arrogant, which is deemed QOTW. :)

Hey!  The "question", not the "person"!  One might say "the subject",
but then, it has to be the subject of the message, of course! :-)

-- 
François Pinard   http://pinard.progiciels-bpi.ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: f*cking re module

2005-07-05 Thread Greg Lindstrom
> That's what I love in that news group. Someone comes with a
> stupid and arrogant question, and someone else answers in a
> calm and reasonable way.

Me, too. Indeed, that's a great reason to be a part of this community.
I didn't see the original question as either stupid or arrogant; I read
it as being from a frustrated user not knowing the regular expression
package.  We've all been there.  While it would be nice if the question
could be expressed without the explatives, it does no good at all to
return the hostile tone.  Another thing I like is that after the
question was answered, other ways to approach the problem were offered
along with reasons as to why the new way is a better approach.  And no
one had to get hurt!

Perhaps Python is a victim of it's own design here.  We, or at least I,
have grown to expect things to be clear and easy to understand/use.
Regular expressions are not either, though I use them all the time (I
learned them when I was a system admin on a Sun network and tend to
fall back on them when I need a "quick fix").  I hear that Perl 6 is
going to have a rewrite of regular expressions; it will be interesting
to see what their hard work produces.

--greg

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-05 Thread Tom Anderson
On Mon, 4 Jul 2005, George Sakkis wrote:

> "Tom Anderson" <[EMAIL PROTECTED]> wrote:
>
>> I'll just chip in and say i'd quite like a flatten(), too; at the moment,
>> i have one like this:
>>
>> def flatten(ll):
>>   return reduce(lambda a, l: a.extend(l), ll, [])
>
> This doesn't work; a.extend() returns None, not the extended list a:

Ah, no, very good, i was hoping someone would notice that. Well done.

I think my lambda looks more like lambda a, b: a + b, but i realised the 
other day that extend could make it more efficient, and didn't think it 
through properly.

tom

-- 
The revolution will not be televised. The revolution will be live.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-05 Thread Steven D'Aprano
On Tue, 05 Jul 2005 05:03:32 -0700, mcherm wrote:

> Steven D'Aprano writes:
>> Lambda is no more an obscure name than "function", "decorator", "closure",
>> "class", or "module". The first time you come across it, you don't know
>> what it means. Then you learn what it means, and then you know.
> 
> I believe you've made two errors here. First of all, "lambda" is part
> of the Python language, while "function", "decorator", "closure", and
> "module" are not. 

Sorry, but you are mistaken. "lambda" is a _reserved_ word in the
Python language, while "function" etc are not, but they are certainly
part of the language. Try explaining what def and import do without
using the words "function" or "module". Maybe you can do it, using
circumlocutions, but it isn't easy, and costs clarity.

[snip]
> The second error is that I believe most english speakers COULD provide
> a definition for the fairly common words "function", "class", and
> "decorator". The exact meaning of "class" might not be what they expect
> at first, 

Function, in the sense of a mathematical function, I agree. Class as in
the thing you go to at school and decorator as in the person who advises
you what colour curtains to have, certainly. But in the Python sense? No.
Especially not decorator, which I believe most _programmers_ would have
trouble explaining, let alone non-programmer English speakers. I know I do.


> but exposure to any object oriented language would make the
> concept quickly familiar. 

Just as exposure to functional languages would make lambda very familiar.

> But "lambda" has a very clear meaning... it's
> a letter of the greek alphabet. The connection between that letter and
> anonymous functions is tenuous at best, and fails the test of making
> Python read like "executable pseudocode".

Think back to when you were a schoolboy at your first day of school.
Unless you had a very unusual upbringing, you probably had never heard the
word "function" before. There is nothing about the word "function" that
brings to mind "a mathematical entity which transforms a variable into a
different variable", let alone "a programming subroutine that returns a
result". (Or for that matter, "the purpose which a person or thing is
for", as in the function of a spanner is to tighten nuts on bolts.)

You had to learn that word, discover what it means, and then it becomes
familiar. You don't notice the process only because it happened so long
ago, at an age that your brain was operating in "language acquisition
mode" and picking up vocabulary at an incredible rate.

There is nothing about the word "string" that especially brings to mind
"an array of bytes representing characters". The analogy of "string of
characters" to "string of beads" breaks down as soon as you have multiple
lines of text. And as for float, that's what boats do, heaven only knows
what it has to do with numbers.

(Yes, I know what it has to do with numbers. But that is something I had
to learn, and even now I still have difficulty because I expect floats to
operate like mathematical real numbers, and they don't.)

And dare I say it, what do constricting snakes have to do with programming?

I won't say that the anonymous function meaning of lambda comes to my mind
before the Greek letter, but it isn't very far behind, and rapidly
catching up. (I use lambda a lot more than I speak Greek.) It wouldn't
surprise me if one day I think of Python programming before the Greek
letter, just as the world aleph brings to my mind the sense of infinity
before the sense of it being a Hebrew letter.


-- 
Steven.

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


[Auto Response] Returned mail: see transcript for details

2005-07-05 Thread Internet Draft Submission Manager

Greetings:

This message is being sent to acknowledge receipt of your Internet-Draft
submission or message to [EMAIL PROTECTED]
If you submitted an Internet-Draft, then it will be posted
on the Internet-Drafts page of the IETF Web site, and an I-D Action 
message will be sent to the I-D-Announce List.  If you need to track the 
status of your Internet-Draft submission at a later date, then please 
send a note to [EMAIL PROTECTED] (using the suggested subject line 
Status of I-D Submission: ) and reference this auto-response 
acknowledgement in the body.

Please note that all Internet-Drafts offered for publication
as RFCs must conform to the requirements specified in I-D Checklist
() or they will be returned
to the author(s) for revision.  Therefore, the IETF Secretariat strongly 
recommends that you address all of the issues raised in this document 
before submitting a request to publish your Internet-Draft to the IESG.

The IETF Secretariat

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-05 Thread Tom Anderson
On Mon, 4 Jul 2005, Ron Adam wrote:

> George Sakkis wrote:
>
>> And finally for recursive flattening:
>> 
>> def flatten(seq):
>> return reduce(_accum, seq, [])
>> 
>> def _accum(seq, x):
>> if isinstance(x,list):
>> seq.extend(flatten(x))
>> else:
>> seq.append(x)
>> return seq
>> 
>> 
> flatten(seq)
>> 
>> [1, 2, 3, 4, 5, 6]
>
> How about this for a non recursive flatten.
>
> def flatten(seq):
>s = []
>while seq:
>while isinstance(seq[0],list):
>seq = seq[0]+seq[1:]
>s.append(seq.pop(0))
>return s
>
> seq = [[1,2],[3],[],[4,[5,6]]]
> flatten(seq)

The trouble with these is that they make a lot of temporary lists - 
George's version does it with the recursive calls to flatten, and Ron's 
with the slicing and concatenating. How about a version which never makes 
new lists, only appends the base list? We can use recursion to root 
through the lists ...

def isiterable(x):
return hasattr(x, "__iter__") # close enough for government work

def visit(fn, x): # perhaps better called applytoall
if (isiterable(x)):
for y in x: visit(fn, y)
else:
fn(x)

def flatten(seq):
a = []
def appendtoa(x):
a.append(x)
visit(appendtoa, seq)
return a

If you hate recursion, you can write a non-recursive version of visit; 
you'll have to manage a stack of lists yourself, though. Something like:

def visit(fn, x):
if (not isiterable(x)): x = (x,)
stack = [None] # stack of iterators
cur = iter(x) # current iterator
while (cur != None):
try:
thing = cur.next()
if (isiterable(thing)):
stack.append(cur)
cur = iter(thing)
else:
fn(thing)
except StopIteration:
cur = stack.pop()

There might be a cleverer way to do this.

tom

-- 
The revolution will not be televised. The revolution will be live.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do you program in Python?

2005-07-05 Thread Tom Anderson
On Mon, 4 Jul 2005, Aahz wrote:

> In article <[EMAIL PROTECTED]>,
> Peter Hansen  <[EMAIL PROTECTED]> wrote:
>
>> After 25 years doing this, I've become something of a Luddite as far as 
>> fancy IDEs and non-standard features go... and a huge believer in 
>> strict decoupling between my tools, to the point of ignoring things 
>> that bundle them together in ways that are, in my opinion, too tight. 
>> Sorry! :-)
>
> +1 QOTW

+1 insight of the century. This is the heart of the unix way - lots of 
simple little programs that do exactly one thing well, and can be composed 
through simple, clean interfaces. For actually getting things done, a 
toolkit beats a swiss army knife.

tom

-- 
This isn't right. This isn't even wrong.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: distutils is able to handle...

2005-07-05 Thread George Sakkis
"mg" <[EMAIL PROTECTED]> wrote:

> Hello
>
> I work on an finite element framework and Python bindings have been
> developped.
> Actually, we use Boost.Build as build system but we would like to change
> it.
>
> We have two kinds of problems. First, the framework is used for generate
> pure C++ applications with static libraries ; second, the framework have
> some dependencies to fortran projects.
> Then, in order to know if Distutils can be use in our case, I would like
> to know if :
> - Can distutil compile static C/C++ libraries ?
> - Can distutil compile C/C++ applications ?
> - Can distutil manage fortran compiler and compile fortran libraries and
> applications ?
>
> Thank for your answers

I don't think distutils can handle all these, especially the last one,
so I doubt it's the right tool in your case. I would suggest SCons
(http://www.scons.org/), a modern make/automake/autoconf replacement
that uses python for its configuration files instead of yet another
cryptic half-baked mini-language or XML.

George

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


Re: what is __init__.py used for?

2005-07-05 Thread George Sakkis
"John Roth" <[EMAIL PROTECTED]> wrote:

> The other is as the module itself. Let's take a simple
> example. Assume you have a directory named breakfast
> which contains modules named spam.py, eggs.py,
> toast.py and jam.py, and that the directory containing
> breakfast is on the PYTHONPATH.
>
> If it try to import spam.py by writing
>
> import breakfast.spam
>
> it won't work because the breakfast directory
> doesn't contain an __init__.py file.
>
> If I then add __init__.py to the breakfast directory,
> the import will work, and the result will be *two*
> modules loaded. The first module will be bound to
> the identifier 'breakfast' in your module. It will be
> completely empty except for the identifier 'spam'
> which will have the spam module bound to it.

There is also an alternative form of import that does not load the
intermediate modules (actually packages), only the last one:
>>> import breakfast.spam as spam

Here you can refer to names defined in breakfast.spam as spam.eat(),
spam.slice, etc. However you can't refer to breakfast; if you do,
you'll get a NameError exception:

>>> import breakfast.spam as spam
>>> breakfast.spam
NameError: name 'breakfast' is not defined

In either form of import though, the __init__.py has to be in the
breakfast directory.

HTH,
George

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


More On - deepcopy, Tkinter

2005-07-05 Thread phil
I posted the following yesterday and got no response
and did some testing simplifying the circumstances
and it appears that deepcopy fails when the object
to be copied contains a reference to a Canvas Object.
Perhaps any Tkinter object, didn't get that far.

The problem arises because I have a geometry tutorial
with a progression of drawings and want the students to
be able to go "back".  Creating "snapshots" of points
in time in the tutorial makes a clean and elegant solution
possible.  Other solutions I am trying to come up with are
very messy.

It is frustrating to think that in a language like python
there might be things which you can't make a copy of.
That is bizarre enough to wonder about a deep flaw or
hopefully I'm just doing something very wrong.

Any ideas appreciated.

phil wrote:

> I wrote the following to prove to myself that
> deepcopy would copy an entire dictionary
> which contains an instance of a class to
> one key of another dictionary.
> Note that after copying adict to ndict['x']
> I delete adict.
> Then ndict['x'] contains a good copy of adict.
> works great.
> 
> 
> class aclass:
>  def __init__(s):
>   s.anint = 123
> aninstance = aclass()
> adict = {}
> adict['y'] = aninstance
> 
> ndict = {}
> ndict['x'] =  copy.deepcopy(adict)
> del adict
> print ndict
> print ndict['x']['y']
> print ndict['x']['y'].anint # this line prints 123
> print
> 
> Then in the following code when I try to deepcopy
> s.glob.objs I get following error
> Note that s.glob.objs is a dictionary and I am
> attempting to copy to a key of s.save, another dict,
> just like above.
> ??
> s.glob.objs may have several keys, the data for each
> will be instance of classes like line and circle.
> Those instances will have tkinter canvas objects in them.
> 
> class Graph:
>  def __init__(s):
>  class DummyClass: pass
>  s.glob = DummyClass()
>  s.glob.objs = {}
>  .. # here add some instance of objects like
>  .. # circles and lines to s.glob.objs
>  # instantiate dialog
>  s.DI = dialog(s.glob)
> 
>  class dialog:
>  def __init__(s,glob):
>  s.glob = glob
>  s.save = {}
> 
>  def proc(s):
>  cur = someint
>  s.save[cur] = copy.deepcopy(s.glob.objs)
> 
> Exception in Tkinter callback
> Traceback (most recent call last):
>File "/usr/local/lib/python2.3/lib-tk/Tkinter.py", line 1345, in __call__
>  return self.func(*args)
>File "/home/phil/geo/g.py", line 303, in enter
>  else:s.proc()
>File "/home/phil/geo/g.py", line 245, in proc
>  s.save[cur][k] = copy.deepcopy(s.glob.objs[k][0])
>File "/usr/local/lib/python2.3/copy.py", line 179, in deepcopy
>  y = copier(x, memo)
>File "/usr/local/lib/python2.3/copy.py", line 307, in _deepcopy_inst
>  state = deepcopy(state, memo)
>File "/usr/local/lib/python2.3/copy.py", line 179, in deepcopy
>  y = copier(x, memo)
>File "/usr/local/lib/python2.3/copy.py", line 270, in _deepcopy_dict
>  y[deepcopy(key, memo)] = deepcopy(value, memo)
>File "/usr/local/lib/python2.3/copy.py", line 179, in deepcopy
>  y = copier(x, memo)
>File "/usr/local/lib/python2.3/copy.py", line 307, in _deepcopy_inst
>  state = deepcopy(state, memo)
>File "/usr/local/lib/python2.3/copy.py", line 179, in deepcopy
>  y = copier(x, memo)
>File "/usr/local/lib/python2.3/copy.py", line 270, in _deepcopy_dict
>  y[deepcopy(key, memo)] = deepcopy(value, memo)
>File "/usr/local/lib/python2.3/copy.py", line 206, in deepcopy
>  y = _reconstruct(x, rv, 1, memo)
>File "/usr/local/lib/python2.3/copy.py", line 338, in _reconstruct
>  y = callable(*args)
>File "/usr/local/lib/python2.3/copy_reg.py", line 92, in __newobj__
>  return cls.__new__(cls, *args)
> TypeError: function() takes at least 2 arguments (0 given)
> 
> 



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


Re: readline: edit-and-execute-command

2005-07-05 Thread Michael Hoffman
josh wrote:
> anybody know why "edit-and-execute-command" doesn't work in python's 
> readline?  
> it doesn't even show up in a dump of readline functions:  
>   

Is that a standard readline command? It's not in my readline(3). It 
might just be added for bash.

That said, this would be very useful. You should submit an RFE on the 
Sourceforge tracker.
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: f*cking re module

2005-07-05 Thread Michael Hoffman
Greg Lindstrom wrote:

 > I hear that Perl 6 is
> going to have a rewrite of regular expressions; it will be interesting
> to see what their hard work produces.

 From what I saw a while ago, it didn't look like it would be any 
simpler or more elegant. But that was a while ago.
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Py2Exe and the log file...

2005-07-05 Thread [EMAIL PROTECTED]
Hi !

1. Thanx for your answer in the theme of Unicode, and other things.
2. The problem:
I need to create an application that not need Python libs to install.
Py2Exe is good for that, but I need to copy the "dist" to the network 
drive what mapped readonly.
This is a protection.

So: in this time I have been use same applications, but they are created 
by Delphi.
These apps make logs into user's temp to avoid the log merging, and log 
creation problems (in readonly drive).

Py2Exe have an exception catcher "module", that log the errors in the 
log file that created in app dir.
This is problem, because the log file creation have been failed in RO drive.

How to I redirect this log file, or can I do anything to aviod the log 
file creation error ?

Thanx for your help: ft

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


Python exception hook simple example needed

2005-07-05 Thread [EMAIL PROTECTED]
Hi !

I wrote some mails to wxPy, and this list about "wxPython and global 
exception handling" theme.
I need to port my Delphi apps to wxPy, and I want to use same exception 
mechanism like Delphi use.

When any exception get unhandled, the app's main cycle get it, and show 
in a dialog (and I can catch it, and I can write it to a log file with 
many developer information).

So: I need to create this in wx+Py.

But my computer crashed yesterday, some local emails, files deleted, etc...

If anyone has an idea, how to I catch exceptions globally, please write me.

I think they are wrote about Python exception hook...
If you have a simple example how to use it, write to me !

Thanx for your help: ft
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pickle broken: can't handle NaN or Infinity under win32

2005-07-05 Thread Michael Hudson
"Terry Reedy" <[EMAIL PROTECTED]> writes:

> "Grant Edwards" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> > I'm working on it.  I should have said it's trivial if you have
> > access to the platforms to be supported.  I've tested a fix
> > that supports pickle streams generated under Win32 and glibc.
> > That's using the "native" string representation of a NaN or
> > Inf.
> >
> > A perhaps simpler approach would be to define a string
> > representation for Python to use for NaN and Inf.  Just because
> > something isn't defined by the C standard doesn't mean it can't
> > be defined by Python.
> 
> I believe that changes have been made to marshal/unmarshal in 2.5 CVS with 
> respect to NAN/INF to eliminate annoying/surprising behavior differences 
> between corresponding .py and .pyc files.  Perhaps these revisions would be 
> relevant to pickle changes.

If you use a binary protocol for pickle, yes.

Cheers,
mwh

-- 
  Java sucks. [...] Java on TV set top boxes will suck so hard it
  might well inhale people from off  their sofa until their heads
  get wedged in the card slots.  --- Jon Rabone, ucam.chat
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python exception hook simple example needed

2005-07-05 Thread Thomas Guettler
Am Tue, 05 Jul 2005 16:07:44 +0200 schrieb [EMAIL PROTECTED]:

> Hi !
> 
> I wrote some mails to wxPy, and this list about "wxPython and global 
> exception handling" theme.
> I need to port my Delphi apps to wxPy, and I want to use same exception 
> mechanism like Delphi use.
> 
> When any exception get unhandled, the app's main cycle get it, and show 
> in a dialog (and I can catch it, and I can write it to a log file with 
> many developer information).

Hi,

maybe a look at the "cgitb" module helps you. It uses an exception handler
to create a HTML page if an uncaught exception is raised.

HTH,
  Thomas


-- 
Thomas Güttler, http://www.thomas-guettler.de/


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


Re: Tkinter + Tcl help

2005-07-05 Thread Jeff Epler
I think you need to write
root.tk.eval('load', '...\\libtcldot.so.0')

When you write
root.tk.eval("x y z")
it's like doing this at the wish/tclsh prompt:
# {x y z}
Not like this:
# x y z
Now, how useful it is to have a command called "x y z", I can't
guess... but tcl would let you do it.

I've also doubled the backslash in your library filename.  When using
windows-style paths in string literals, you must either double the
backslashes, or use r'' strings.  When you don't, it will often work,
but if the character after the un-doubled backslash is one with special
meaning (including the commonly-seen \r and \t, but also other letters)
then you'll get a pathname and an error that leave you scratching your
head.

Jeff


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

Re: More On - deepcopy, Tkinter

2005-07-05 Thread Duncan Booth
phil wrote:

> It is frustrating to think that in a language like python
> there might be things which you can't make a copy of.
> That is bizarre enough to wonder about a deep flaw or
> hopefully I'm just doing something very wrong.

To be honest, it doesn't really surprise me that you cannot copy Tkinter 
objects. If you could make a copy of an object which is displayed on the 
screen I would expect that copying would create another object on the 
screen, and that probably isn't what you want. Other uncopyable objects 
include files, stack frames and so on.

The deepcopy protocol does allow you to specify how complicated objects 
should be copied. Try defining __deepcopy__() in your objects to just copy 
the reference to the Canvas object instead of the object itself.

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


Re: Python exception hook simple example needed

2005-07-05 Thread Benji York
[EMAIL PROTECTED] wrote:
> If anyone has an idea, how to I catch exceptions globally, please write me.

I believe there is an example of this in the demo that comes with 
wxPython (don't have an install handy to check).
--
Benji York

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


Re: Py2Exe and the log file...

2005-07-05 Thread Thomas Heller
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> Hi !
>
> 1. Thanx for your answer in the theme of Unicode, and other things.
> 2. The problem:
> I need to create an application that not need Python libs to install.
> Py2Exe is good for that, but I need to copy the "dist" to the network
> drive what mapped readonly.
> This is a protection.
>
> So: in this time I have been use same applications, but they are
> created by Delphi.
> These apps make logs into user's temp to avoid the log merging, and
> log creation problems (in readonly drive).
>
> Py2Exe have an exception catcher "module", that log the errors in the
> log file that created in app dir.
> This is problem, because the log file creation have been failed in RO drive.
>
> How to I redirect this log file, or can I do anything to aviod the log
> file creation error ?
>
> Thanx for your help: ft

The code that creates the logfile is in 
"Lib/site-packages/py2exe/boot_common.py".
This code is executed before the main script is started.

You can override it by assigning another object to sys.stderr, at the
start of your main script, which has a write method doing what YOU want.

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-05 Thread Terry Hancock
On Tuesday 05 July 2005 08:17 am, Steven D'Aprano wrote:
> Sorry, but you are mistaken. "lambda" is a _reserved_ word in the
> Python language, while "function" etc are not, but they are certainly
> part of the language. Try explaining what def and import do without
> using the words "function" or "module". Maybe you can do it, using
> circumlocutions, but it isn't easy, and costs clarity.

This is still a relevant distinction.   One relevant point is that I am
perfectly free to use, say, the Spanish or Chinese word to describe
"module" or "function", but the keywords "def" and "import" will
remain the same.

> > The second error is that I believe most english speakers COULD provide
> > a definition for the fairly common words "function", "class", and
> > "decorator". The exact meaning of "class" might not be what they expect
> > at first, 
> 
> Function, in the sense of a mathematical function, I agree. Class as in
> the thing you go to at school and decorator as in the person who advises
> you what colour curtains to have, certainly. But in the Python sense? No.
> Especially not decorator, which I believe most _programmers_ would have
> trouble explaining, let alone non-programmer English speakers. I know I do.

The "Python sense" is not arbitrary.  There are very direct visual or logical
(i.e. INTUITIVE) connections between these words' *English* meanings (not
just mathematical, either) and their meanings in Python.

A "Function" is (in English) (kdict-gcide*):
1.) The act of executing or performing any duty, office, or
  calling; performance
2.) The appropriate action of any special organ or
  part of an animal or vegetable organism...
[...]
5.) (math) A quantity so connected with another quantity,
  that if any alteration be made in the latter there will be
  a consequent alteration in the former.

The programming use is probably *closer* to the English meaning
than the math jargon meaning (except in the sense of "functional
programming" which leans more on the math meaning.

Similarly, "decorate" is 'make more attractive by adding ornament, colour, etc.'
In Python, a "decorator" applies a wrapper to a function to provide it with
some additional functionality.  The function definition is furthermore
"decorated" with the decorator declaration to give it more meaning, which
is arguably more aesthetically pleasing (otherwise, why not literally wrap
with a function after defining the function?).  These meanings are very
connected with the English definition of the word.

"Class" can, of course, mean a room in which you teach classes, but again
Webster's will certainly provide meaning much closer to the programming
term:

1. A group of individuals ranked together as possessing
  common characteristics...

[2 is the class of students sense]

3. A comprehensive division of animate or inanimate objects,
  grouped together on account of their common
  characteristics
4. A set; a kind or description, species or variety.

Meanings 1,3, & 4 are all arguably intimately connected to the OOP meaning,
especially meaning #3 which even mentions "objects". (And I won't bother
to point out that the English meaning of "object" is tied closely to what it
means in programming).

A similar argument can be made for "object", "module", "script", and
even "method" and "program".

Now, if you are armed ONLY with the English definition, you will possibly
run into some trouble, because the programming usage is a *specialization*
of the term -- we strictly take only *one* of the English definitions to apply,
and we narrow its meaning a bit.  "Objects" in computer science never means
"the purpose of the program" nor does it ever refer to "a small brick", even
though the English word can mean both of those things. But it's not exactly
a shocker that a programming term is going to apply to things you can find
in a program, so I don't think we're stumping the newbie with such terms.


"lambda" has no such advantage.  Here's the *entire* gcide definition:

Lambda \Lamb"da\, n. [NL., fr. Gr. la`mbda.]
   1. The name of the Greek letter [Lambda], [lambda],
  corresponding with the English letter L, l.
  [1913 Webster]

   2. (Anat.) The point of junction of the sagittal and lambdoid
  sutures of the skull.
  [1913 Webster]

   3. (Phys.) A subatomic particle carrying no charge, having a
  mass equal to 2183 times that of an electron; it decays
  rapidly, typically forming a nucleon and a pion. --MW10
  [PJC]

   Lambda moth (Zool.), a moth so called from a mark on its
  wings, resembling the Greek letter lambda ([Lambda]).
  [1913 Webster]

> > but exposure to any object oriented language would make the
> > concept quickly familiar. 
> 
> Just as exposure to functional languages would make lambda very familiar.

Yeah, well, there *is* an entry in the "Online Dictionary of Computing":

LAMBDA
A version of typed lambda-calculus, used to describe
semantic dom

Re: math.nroot [was Re: A brief question.]

2005-07-05 Thread Tim Peters
[Tim Peters]
>> All Python behavior in the presence of infinities, NaNs, and signed
>> zeroes is a platform-dependent accident, mostly inherited from that
>> all C89 behavior in the presence of infinities, NaNs, and signed
>> zeroes is a platform-dependent crapshoot.
 
[Michael Hudson]
> As you may have noticed by now, I'd kind of like to stop you saying
> this :) -- at least on platforms where doubles are good old-fashioned
> 754 8-byte values.

Nope, I hadn't noticed!  I'll stop saying it when it stops being true,
though .  Note that since there's not even an alpha out for 2.5
yet, none of the good stuff you did in CVS counts for users yet.

> But first, I'm going to whinge a bit, and lay out some stuff that Tim
> at least already knows (and maybe get some stuff wrong, we'll see).
>
> Floating point standards lay out a number of "conditions": Overflow
> (number too large in magnitude to represent), Underflow (non-zero
> number to small in magnitude to represent), Subnormal (non-zero number
> to small in magnitude to represent in a normalized way), ...

The 754 standard has five of them:  underflow, overflow, invalid
operation, inexact, and "divide by 0" (which should be understood more
generally as a singularity; e.g., divide-by-0 is also appropriate for
log(0)).

> For each condition, it should (at some level) is possible to trap each
> condition, or continue in some standard-mandated way (e.g. return 0
> for Underflow).

754 requires that, yes.

> While ignoring the issue of allowing the user to control this, I do
> wish sometimes that Python would make up it's mind about what it does
> for each condition.

Guido and I agreed long ago that Python "should", by default, raise an
exception on overflow, invalid operation, and divide by 0, and "should
not", by default, raise an exception on underflow or inexact.  Such
defaults favor non-expert use.  Experts may or may not be happy with
them, so Python "should" also allow changing the set.

> There are a bunch of conditions which we shouldn't and don't trap by
> default -- Underflow for example.  For the conditions that probably should
> result in an exception, there are inconsistencies galore:

> >>> inf = 1e300 * 1e300 # <- Overflow, no exception
> >>> nan = inf/inf # <- InvalidOperation, no exception

Meaning you're running on a 754 platform whose C runtime arranged to
disable the overflow and invalid operation traps.  You're seeing
native HW fp behavior then.

> >>> pow(1e100, 100) <- Overflow, exception
> Traceback (most recent call last):
>  File "", line 1, in ?
> OverflowError: (34, 'Numerical result out of range')
> >>> math.sqrt(-1) # <- InvalidOperation, exception
> Traceback (most recent call last):
>  File "", line 1, in ?
> ValueError: math domain error

Unlike the first two examples, these call libm functions.  Then it's a
x-platform crapshoot whether and when the libm functions set errno to
ERANGE or EDOM, and somewhat of a mystery whether it's better to
reproduce what the native libm considers to be "an error", or try to
give the same results across platforms.  Python makes a weak attempt
at the latter.

> At least we're fairly consistent on DivisionByZero...

When it's a division by 0, yes.  It's cheap and easy to test for that.
 However, many expert uses strongly favor getting back an infinity
then instead, so it's not good that Python doesn't support a choice
about x/0.

> If we're going to trap Overflow consistently, we really need a way of
> getting the special values reliably -- which is what pep 754 is about,
> and its implementation may actually work more reliably in 2.5 since my
> recent work...

I don't know what you have in mind.  For example, checking the result
of x*y to see whether it's an infinity is not a reliable way to detect
overflow, and it fails in more than one way (e.g., one of the inputs
may have been an infinity (in which case OverflowError is
inappropriate), and overflow doesn't always result in an infinity
either (depends on the rounding mode in effect)).

> On the issue of platforms that start up processes with traps enabled,
> I think the correct solution is to find the incantation to turn them
> off again and use that in Py_Initialize(), though that might upset
> embedders.

Hard to know.  Python currently has a hack to disable traps on
FreeBSD, in python.c's main().
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: threads and sleep?

2005-07-05 Thread Jeffrey Maitland
Hello all,

First off Thanks for the responses on the sleep() part  I suspected as
much but I wasn't 100% sure.

To continue this I just want to pre thank anyone that contributes to
this thread(lol).

Ok here goes. The problem I have is I had an application
(wrote/co-wrote) that has a long run time dependant on some variables
passed to it (mainly accuracy variables, the more accurate the longer
the run time - makes sense). However in the hopes to speed it up I
decided to write a threaded version  of the program to try and speed
it up.  How ever what I am noticing is that the threaded version is
taking as long possibly longer to run.  The thing is the threaded
version is running on an 8 ia-64 proccessor system and it seems to
only be using 2 or 3 porcessors at about 30% (fluxiates).  My guess is
that 6 threads are running they are using 30% sprox each of a 2 given
CPUS.

What I would like to do is have say 1 thread use as much of a given
CPU as possible and if a new thread is started (added) that if a CPU
is available use it instead of using the same cpu. That way it should
speed the application up.  The standalone (non-threaded) app uses 90+
% of a single cpu when in this part of the algorithm, that is why I
split and threaded that part of the algorithm there to try and speed
it up because this part is repeated several times.   I can post
generic code of what I am doing but can't post the actuall code
because of the confidentially of it.  Thanks again in advance for any
and all comments (even any spitefull ones)

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


Re: More On - deepcopy, Tkinter

2005-07-05 Thread phil
 
> The deepcopy protocol does allow you to specify how complicated objects 
> should be copied. Try defining __deepcopy__() in your objects to just copy 
> the reference to the Canvas object instead of the object itself.
 
I can't figure out from the docs what __deepcopy__ is or how it

works.
I have about 25 classes of drawn objects. for instance
class linefromslope  creates an instance of class line.
One of my "ugly solutions" involves a  class prop: within each class,
put properties like slope and midpoint within the self.prop instance
and making a copy of that.
Would __deepcopy__ facilitate this?
Or am I assuming too much: is __deepcopy__ just a method
I invent to do what I want?




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


Re: f*cking re module

2005-07-05 Thread jwaixs
To reply to the last part of the discussion and esspecially to Gustavo
Niemeyer, I really apriciate the way in which I had been answered. And
I won't have any questions about the re module that I had before I post
this threat.

I was frustration and should, probebly, not post this frustration. But
it was never my purpous to ask something stupid or asking it arrogant.

The python re module is, in my opinion, a non beginner user friendly
module. And it's not meant for beginning python programmers. I don't
have any experience with perl or related script/programming languages
like python. (I prefer to do things in c) So the re module is
completely new for me.

If I upset someones clean mind posting a "stupid" and "arrogant"
question, I'm sorry and won't post my frustrasion on this usenet group
anymore.

But thank you for all your help about the re module,

Noud Aldenhoven

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


Re: math.nroot [was Re: A brief question.]

2005-07-05 Thread Terry Hancock
On Sunday 03 July 2005 10:47 pm, Steven D'Aprano wrote:
> Any floating point package that supports the IEEE 
> standard should give you a test to see if a float 
> represents a NaN. That's what you need. You certainly 
> can't rely on "x == SOME_NAN" because there are 254 
> different NaNs.
> 
> There is no sensible reason to test equality of NaNs. 
> It is logically nonsense to say that one NaN is equal 
> to another, as such a thing implies contradictions like 
> -1==-2. If you support IEEE, you will have a test for 
> NaNs, so you can detect them when you need to.

I have to mention that the idea of a math package that 
allows NaN to propagate as though it were a number 
scares the willies out of me.  God help me if I were to use
it on something like Engineering where lives might
depend on the answer being right.

That'd be like having a math package that allowed,
say 0/0 = 1 or Inf/Inf = 1.  It's not hard at all to come
up with dozens of problems for which that is the WRONG
guess -- getting an actual answer for dividing two
infinities requires using limits and calculus.  The reason
Inf/Inf isn't defined is that it can actually be just about
any number --- finite or infinite.

I can seriously imagine structures breaking and collapsing
because they were designed using such a package, and
a NaN was generated and missed somewhere.

Really, the only *right* thing to do is to raise an exception
ASAP after the NaN comes up.

On a more practical note, *is* there a isNaN() function? Seems
like it ought to be in the math module.   Looks like you have
to do it through "fpectl" as things stand.

Is anyone else bothered that "math" and "cmath" are in the
"Miscellaneous Services" section of the LR? Seems like we
ought to get Numeric and/or Numarray and group all of
these in a separate "Math & Science" section.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: Considering moving from Delphi to Python [Some questions]

2005-07-05 Thread Benji York
Dark Cowherd wrote:
> I want some feedback on folllwing:
> anybody who has experience in writing [...] data
> entry heavy web applications.
> Any suggestions?

You might be interested in Zope 3's ability to generate data entry/edit 
forms via schemas.
--
Benji York
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Folding in vim

2005-07-05 Thread Terry Hancock
On Monday 04 July 2005 12:41 am, Ron Adam wrote:
> > Actually, I think this one is doing what I want now. It seems
> > to be that it isn't robust against files with lots of mixed tabs
> > and spaces.  I also got "space_hi.vim" which highlights tabs
> > and trailing spaces, which made it a lot easier to fix the 
> > problem.
> 
> I edited my syntax coloring file to do the same thing.  Not to mention 
> adding a few key words that were missing.  :-)

This script:
http://www.vim.org/scripts/script.php?script_id=790
"python.vim" (but in ~/.vim/syntax) by Dmitry Vasiliev

adds a few dozen Python-specific syntax keywords, I used these
and edited my usual color scheme to give them more refined
syntax coloring, which is nice.  It is quite useful to have Unicode
strings and Raw strings display differently, for example, since
it's easy to forget which you're using (unless you're right next
to the mark).

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: Folding in vim

2005-07-05 Thread Terry Hancock
On Monday 04 July 2005 01:12 am, Andrea Griffini wrote:
> - never ever use tabs; tabs were nice when they had
> - stick to 4-space indent

Nice ideals to which I ascribe.  But if your editor isn't 
configured to support you on this, spacing over to, say
column 24 gets pretty dull.  Mine wasn't configured to
do anything special, so I was leaving tabs in the file
and etc.

So I wasn't really living up to my ideals. ;-)

Bad habits, I agree.  I now have things working so that
"tab" actually uses spaces in the file.  The problems
arose because I was still working with my old "tainted"
files.

All better now. :-)

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: What are the other options against Zope?

2005-07-05 Thread Terry Hancock
On Monday 04 July 2005 10:21 am, phil wrote:
> A data base with properties and methods. Cool.

I am so sure I already said this.  Well, I guess I typed
too much else.

Cheers,
Terry

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Good starterbook for learning Python?

2005-07-05 Thread Lennart
Hi everybody,

Can someone advice me with the following issue: i want to learn python in
my summer vacation (i try to ...:-) So, a good start is buying a good book.
But wich? There are many ...

I'm living in the Netherlands and I prefer a book from bol.com (see link)
because i've to order more books by them. I'm familiar with html & php and
basic (in the good old days). It has to be a newbie book, but not a book
what i don't need anymore when i've got some skills. I.e. the learning
curve of the book should be linear. A kind of book wich i could use as a
novice.

Search here for python (sorry, there's no short link)
http://www.nl.bol.com/is-bin/INTERSHOP.enfinity/eCS/Store/nl/-/EUR/BOL_BrowseCatalog-View;sid=nyuhO3sz8k2hODn5OfqfDJvrcywRiGQwhPU=?Section=BOOK_EN&CategoryContent=NJqR5Kpb0soAAADqmW%2eZypJb&OpenCategory=HwqR5Kpb8AUAAADqVW6ZypJb&CategoryLeftpanel=BOOK_EN%2eCATEGORY&Secondary=YES&Template=BOL_subcat_BOOK_EN_1476
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: More On - deepcopy, Tkinter

2005-07-05 Thread Duncan Booth
phil wrote:

>  
>> The deepcopy protocol does allow you to specify how complicated
>> objects should be copied. Try defining __deepcopy__() in your objects
>> to just copy the reference to the Canvas object instead of the object
>> itself. 
>  
> I can't figure out from the docs what __deepcopy__ is or how it
> 
> works.
> I have about 25 classes of drawn objects. for instance
> class linefromslope  creates an instance of class line.
> One of my "ugly solutions" involves a  class prop: within each class,
> put properties like slope and midpoint within the self.prop instance
> and making a copy of that.
> Would __deepcopy__ facilitate this?
> Or am I assuming too much: is __deepcopy__ just a method
> I invent to do what I want?
> 

The docs say:

> In order for a class to define its own copy implementation, it can
> define special methods __copy__() and __deepcopy__(). The former is
> called to implement the shallow copy operation; no additional
> arguments are passed. The latter is called to implement the deep copy
> operation; it is passed one argument, the memo dictionary. If the
> __deepcopy__() implementation needs to make a deep copy of a
> component, it should call the deepcopy() function with the component
> as first argument and the memo dictionary as second argument. 

__deepcopy__ is a method which overrides the default way to make a deepcopy 
of an object.

So, if you have a class with attributes a, b, and c, and you want to ensure 
that deepcopy copies a and b, but doesn't copy c, I guess you could do 
something like:

>>> class MyClass:
   _dontcopy = ('c',) # Tuple of attributes which must not be copied

   def __deepcopy__(self, memo):
  clone = copy.copy(self) # Make a shallow copy
  for name, value in vars(self).iteritems():
  if name not in self._dontcopy:
  setattr(clone, name, copy.deepcopy(value, memo))
  return clone

>>> class Copyable(object):
def __new__(cls, *args):
print "created new copyable"
return object.__new__(cls, *args)


>>> m = MyClass()
>>> m.a = Copyable()
created new copyable
>>> m.b = Copyable()
created new copyable
>>> m.c = Copyable()
created new copyable
>>> clone = copy.deepcopy(m)
created new copyable
created new copyable
>>> m.a is clone.a
False
>>> m.c is clone.c
True
>>> 

As you can see, the deepcopy only creates deep copies of 2 of the 3 
attributes, 'c' is simply copied across as a shallow copy.

and if you subclass MyClass you can modify the _dontcopy value to add 
additional attributes which must not be copied.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: threads and sleep?

2005-07-05 Thread Jonathan Ellis
Jeffrey Maitland wrote:
> The problem I have is I had an application
> (wrote/co-wrote) that has a long run time dependant on some variables
> passed to it (mainly accuracy variables, the more accurate the longer
> the run time - makes sense). However in the hopes to speed it up I
> decided to write a threaded version  of the program to try and speed
> it up.  How ever what I am noticing is that the threaded version is
> taking as long possibly longer to run.  The thing is the threaded
> version is running on an 8 ia-64 proccessor system and it seems to
> only be using 2 or 3 porcessors at about 30% (fluxiates).  My guess is
> that 6 threads are running they are using 30% sprox each of a 2 given
> CPUS.

In many ways, Python is an incredibly bad choice for deeply
multithreaded applications.  One big problem is the global interpreter
lock; no matter how many CPUs you have, only one will run python code
at a time.  (Many people who don't run on multiple CPUs anyway try to
wave this off as a non-problem, or at least worth the tradeoff in terms
of a simpler C API, but with multicore processors coming from every
direction I think the "let's pretend we don't have a problem" approach
may not work much longer.)

If the GIL isn't an issue (and in your case it clearly is), you'll
quickly find that there's little support for debugging multithreaded
applications, and even less for profiling.

Sometimes running multiple processes is an acceptable workaround; if
not, good luck with the rewrite in Java or something else with real
thread support.  (IIRC Jython doesn't have a GIL; that might be an
option too.)

Python is a great tool but if you really need good threading support
you will have to look elsewhere.

-Jonathan

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


Re: Good starterbook for learning Python?

2005-07-05 Thread TechBookReport
Lennart wrote:
> Hi everybody,
> 
> Can someone advice me with the following issue: i want to learn python in
> my summer vacation (i try to ...:-) So, a good start is buying a good book.
> But wich? There are many ...
> 
> I'm living in the Netherlands and I prefer a book from bol.com (see link)
> because i've to order more books by them. I'm familiar with html & php and
> basic (in the good old days). It has to be a newbie book, but not a book
> what i don't need anymore when i've got some skills. I.e. the learning
> curve of the book should be linear. A kind of book wich i could use as a
> novice.
> 
> Search here for python (sorry, there's no short link)
> http://www.nl.bol.com/is-bin/INTERSHOP.enfinity/eCS/Store/nl/-/EUR/BOL_BrowseCatalog-View;sid=nyuhO3sz8k2hODn5OfqfDJvrcywRiGQwhPU=?Section=BOOK_EN&CategoryContent=NJqR5Kpb0soAAADqmW%2eZypJb&OpenCategory=HwqR5Kpb8AUAAADqVW6ZypJb&CategoryLeftpanel=BOOK_EN%2eCATEGORY&Secondary=YES&Template=BOL_subcat_BOOK_EN_1476

Two excellent books match your criteria:

Dive Into Python (review: http://www.techbookreport.com/tbr0103.html) - 
also available as a free download.

Learning Python (review: http://www.techbookreport.com/tbr0064.html)

Both are recommended for beginners but have a reasonable level of depth. 
They're clear, enthusiastic and well-written.

HTH

-- 
TechBookReport - Programming   http://www.techbookreport.com/ProgIndex.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Good starterbook for learning Python?

2005-07-05 Thread Patrick Rutkowski
On Tuesday 05 July 2005 11:32, Lennart wrote:
> Hi everybody,
>
> Can someone advice me with the following issue: i want to learn python in
> my summer vacation (i try to ...:-) So, a good start is buying a good book.
> But wich? There are many ...
>
> I'm living in the Netherlands and I prefer a book from bol.com (see link)
> because i've to order more books by them. I'm familiar with html & php and
> basic (in the good old days). It has to be a newbie book, but not a book
> what i don't need anymore when i've got some skills. I.e. the learning
> curve of the book should be linear. A kind of book wich i could use as a
> novice.
>
> Search here for python (sorry, there's no short link)
> http://www.nl.bol.com/is-bin/INTERSHOP.enfinity/eCS/Store/nl/-/EUR/BOL_Brow
>seCatalog-View;sid=nyuhO3sz8k2hODn5OfqfDJvrcywRiGQwhPU=?Section=BOOK_EN&Cate
>goryContent=NJqR5Kpb0soAAADqmW%2eZypJb&OpenCategory=HwqR5Kpb8AUAAADqVW6ZypJb
>&CategoryLeftpanel=BOOK_EN%2eCATEGORY&Secondary=YES&Template=BOL_sub
>cat_BOOK_EN_1476

I've taken up learning python over the summer as well. 
http://safari.oreilly.com/ is a website which sells IT books for on-line 
viewing. They charge $20 per month and you get 10 "slots" on your books 
shelf. You can get anybook you want, some books take 2 slots, some 1 slot, 
and some are even half of a slot.

They have a 14 day free trial as well, its really worth giving it a whirl 
(free books!!). It's totally 100% over the internet (or in downloadable PDF 
format), its so great.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: f*cking re module

2005-07-05 Thread George Sakkis
"jwaixs" <[EMAIL PROTECTED]> wrote:

> To reply to the last part of the discussion and esspecially to Gustavo
> Niemeyer, I really apriciate the way in which I had been answered. And
> I won't have any questions about the re module that I had before I post
> this threat.
>
> I was frustration and should, probebly, not post this frustration. But
> it was never my purpous to ask something stupid or asking it arrogant.

I think most people who answered you calmly realized that it was
frustration rather than arrogance and trolling behavior. This happens
often if you're new to something and/or this something is inherently
complicated; I almost did the same mistake when I had to mess with the
loathsome autoconf/automake/autohell files and tools, but at least I
refrained from the expletives.

> The python re module is, in my opinion, a non beginner user friendly
> module. And it's not meant for beginning python programmers. I don't
> have any experience with perl or related script/programming languages
> like python. (I prefer to do things in c) So the re module is
> completely new for me.

It's not the python re module beginner unfriendly; it's the regular
expression concepts and syntax that the module implements. Read some
introductory material about regexps first (Wikipedia is a good place to
start: http://en.wikipedia.org/wiki/Regular_expression) and then get
familiar with the re module by trying the examples interactively in the
interpreter.

> If I upset someones clean mind posting a "stupid" and "arrogant"
> question, I'm sorry and won't post my frustrasion on this usenet group
> anymore.

It's always a good idea to wait for a few hours before posting anything
you may regret later, but this doesn't mean you should leave this
group; as you saw already, it's far more tolerant and civilized than
other groups in this respect.

> But thank you for all your help about the re module,
> 
> Noud Aldenhoven

Cheers,
George

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


Re: importing pyc from memory?

2005-07-05 Thread Bengt Richter
On Mon, 4 Jul 2005 13:01:06 -0500, Jeff Epler <[EMAIL PROTECTED]> wrote:

>
>--s2ZSL+KKDSLx8OML
>Content-Type: text/plain; charset=us-ascii
>Content-Disposition: inline
>
>This stupid code works for modules, but not for packages.  It probably has 
>bugs.
>
>
>import marshal, types
>
>class StringImporter:
>def __init__(self, old_import, modules):
>self._import = old_import
>self._modules = modules
>
>def __call__(self, name, *args):
>module = self._modules.get(name, None)
>if module is None:
>return self._import(name, *args)
>code = marshal.loads(module)
>mod = types.ModuleType(name)
>exec code in mod.__dict__
>return mod
>
>def test():
>import __builtin__
>__builtin__.__import__ = StringImporter(__builtin__.__import__,
>{ 'test_importer': open("/usr/lib/python2.3/os.pyc").read()[8:] })
>
>import test_importer
>print test_importer.path.join("a", "b")
>print test_importer.__doc__
>
>if __name__ == '__main__': test()

I have a feeling that the OP might be looking for a way to convert
source -> source, e.g., (sketch only, not even remotely tested ;-)

# main.py
import some_module
import another

into

# main.py
# prelim
import marshal, sys#  builtin
ModuleType = type(__builtins__) # avoid import types
def unscramble_proprietary_format(proprietary_string):
# ... whatever
def extract_code(proprietary_string):
return marshal.loads(unscramble_proprietary_format(proprietary_string))

# replacing each import with
try: some_module = sys.modules['some_module']  # don't re-"import"
except KeyError:
some_module = ModuleType('some_module')
exec extract_code(
 "< ... string literal for proprietarily scrambled marshalled 
module body code"
 " generated by source -> source rewrite utility ... >"
 ) in some_module.__dict__
sys.modules['some_module'] = some_module

try: another = sys.modules['another']
except NameError:
another = ModuleType('another')
exec extract_code('')
sys.modules['another'] = another

# etc

so that his some_module and another scripts can be pre-compiled by the rewrite 
utility and embedded in
a single source (e.g. main.py) so that he doesn't have to have external .pyc 
file accesses.

His startup will then still cost the execs, but not the compiles, and if he 
doesn't "import" stuff
he doesn't need, until he needs it, it should spread the import time load, if 
so desired.

All the proprietary string literal sources should become efficiently 
represented as part of the
single main.pyc IWT, assuming at least that one is used. Chasing various forms 
of import of
non-builtins recursively to eliminate imports in imported modules before they 
are converted to
marshalled form etc., all to avoid real imports, and statically determining 
that some imports
don't need to be converted to marshalled string import form because a prior 
import can be proved,
should be an interesting exercise, which I can't pursue at this point... ;-)

But I may be reading too much between the lines ;-)

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


Re: threads and sleep?

2005-07-05 Thread Grant Edwards
On 2005-07-05, Jeffrey Maitland <[EMAIL PROTECTED]> wrote:

> Ok here goes. The problem I have is I had an application
> (wrote/co-wrote) that has a long run time dependant on some variables
> passed to it (mainly accuracy variables, the more accurate the longer
> the run time - makes sense). However in the hopes to speed it up I
> decided to write a threaded version  of the program to try and speed
> it up.  How ever what I am noticing is that the threaded version is
> taking as long possibly longer to run.  The thing is the threaded
> version is running on an 8 ia-64 proccessor system and it seems to
> only be using 2 or 3 porcessors at about 30% (fluxiates).  My guess is
> that 6 threads are running they are using 30% sprox each of a 2 given
> CPUS.

Because of the global interpreter lock, a multi-threaded python
program does not take advantage of multiple processors.  No
matter how many CPUs you have, only one thread is allowed to
run at any point in time.

Multi-threading in Python is useful for simplifying the
architecture of a program that has to do multiple independent
tasks, but it isn't useful for actually running multiple
threads in parallel.

-- 
Grant Edwards   grante Yow!  Inside, I'm already
  at   SOBBING!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: precision problems in base conversion of rational numbers

2005-07-05 Thread Terry Hancock
On Monday 04 July 2005 06:11 am, Brian van den Broek wrote:
> As a self-directed learning exercise I've been working on a script to 
> convert numbers to arbitrary bases. It aims to take any of whole 
> numbers (python ints, longs, or Decimals), rational numbers (n / m n, 
> m whole) and floating points (the best I can do for reals), and 
> convert them to any base between 2 and 36, to desired precision.

Interesting, I'd like to see that.

> I'm pretty close but I know I am not handling the precision quite 
> right. Nothing other than understanding hangs on it, but, that's 
> enough :-)

Okay.  You do understand that many numbers that can be exactly
represented in one base cannot be in another?

E.g. in base 3, one-third is 0.1, but in base 10, it's a repeating
decimal: 0.333  And of course, there are infinitely many
other examples.

So what you're really doing is trying to make sure that you don't
*lose* precision in the conversion, *except* due to this point. I.e.
you want to do the best you can do.

I would say that if you have a number of places past the decimal
point, that can be interpreted as the error of the representation:

1/3   ~=  0.3 base10 +- 0.05

Needless to say, the conventional floating point numbers in Python
are actually stored as *binary*, which is why there is a "decimal"
module (which is new).

If you're going to be converting between bases anyway, it probably
makes little difference whether you are using the decimal module
or not, of course.  You'll have the same problems the conventional
float numbers do.

Getting back to your precision problem: I bet if you simply
evaluate the error term as I have above, and then convert *that* into
your base of choice, you will be able to tell how many places are
correct in the conversion.

That is to, say, stop think about "number of places" and instead
think about "representation error".  That number is a real property
of the data which can be represented in any base.  Then you can
convert it to number of places in the representation process.

e.g. 0.05 has 6 places behind the zero in decimal, how many
does base3(0.05)? --- that's the accuracy of the statement

0.3 base10 ~= 0.1 base3 +- base3(0.05 base10)

Roughly, we know that 0.05 = 10^-5 / 2.  The same term
in base 3 will be 3^-x/2 = 10^5/2 places, which can be solved
using logarithms, but I'll "leave that as an excercise for the reader",
because I'm too lazy to go look it up, and I've forgotten the
details. ;-)

I hope this is helpful, though,
Terry

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: threads and sleep?

2005-07-05 Thread Mike Meyer
Jeffrey Maitland <[EMAIL PROTECTED]> writes:
> What I would like to do is have say 1 thread use as much of a given
> CPU as possible and if a new thread is started (added) that if a CPU
> is available use it instead of using the same cpu. That way it should
> speed the application up.  The standalone (non-threaded) app uses 90+
> % of a single cpu when in this part of the algorithm, that is why I
> split and threaded that part of the algorithm there to try and speed
> it up because this part is repeated several times.   I can post
> generic code of what I am doing but can't post the actuall code
> because of the confidentially of it.  Thanks again in advance for any
> and all comments (even any spitefull ones)

This kind of fine control over CPU allocation is very
plaform-specific. Some don't allow it at all. If your platform does,
the details on how you go about doing it will vary depending on the
platform.

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: threads and sleep?

2005-07-05 Thread Jeffrey Maitland
Thanks.

I was hoping that python would allow for the cpu threading such in
Java etc.. but I guess not. (from the answers,and other findings) I
guess I will have to write this part of the code in something such as
java or c or something that allows for it then I can either wrap it in
python or avoid python for this part of the app.

Thanks for all the help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: threads and sleep?

2005-07-05 Thread Grant Edwards
On 2005-07-05, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:

> Don't think you can do that with Python... The Python runtime
> interpreter itself is running on a single processor.

I don't see how that can be.  Under Linux at least, the Python
threading module uses "real" OS threads, so there are multiple
instances of the interpreter, right?  Generally all but one of
them will be blocked on the GIL, but there are still multiple
interpreter threads (which can be on multiple different CPUs).

Or is the Python interpreter actually doing the context
switches itself?

> The second thing is the infamous "global interpreter lock"
> (pull up the Python documentation and do a search for that
> phrase).

The GIL is the issue.

> Basically, even if the threads could be assigned to
> processors,

Can somebody explani why they can't?

> this lock means only one thread can be performing Python
> operations at a time -- a C-language number crunching module
> /could/ release the lock, then do its number crunching in
> parallel, reacquiring the lock when it finishes so it can
> return its result(s) as Python objects.

True.  Python can execute C code in parallel, but not Python
code.

> Tou might get the results you want by not using threads,
> instead spawning off completely new Python invocations
> assigned to other processors.

That should work, but managing the inter-process communication
and syncronization is a pain.

-- 
Grant Edwards   grante Yow!  If Robert Di Niro
  at   assassinates Walter Slezak,
   visi.comwill Jodie Foster marry
   Bonzo??
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pexpect question....

2005-07-05 Thread [EMAIL PROTECTED]

Hi,

While I continue to look at the problem, I thought I would post more
details. In a sense, this is more of a UNIX issue.

I have a python script that uses pexpect to spawn a child process (p1).
The python script then goes ahead and does a "tail --pid=p1". Assuming
that I do close(wait=0), P1 completes and gets stuck in zombie status.
The python script is also stuck because "tail" will not return until
zombie P1 goes away. So each is waiting for the other to go away
resulting in a deadlock.

Apparently, when close(wait=0) is done, all that pexpect does is that
it wouldn't call wait() on the spawned process anymore. I was looking
for a solution where pexpect also should be able to tell kernel that it
doesn't care about child process's exit status. Note that this is
different from not doing "wait". I think this can be achieved by
ignoring SIGCLD on SVR4 systems but I am not sure what is the
(expected) behaviour on posix/linux. Unfortunately, only parent process
can control this behaviour. So my questions are two fold.

1) What is the best way (preferably a generic UNIX way) for a parent
process to inform kernel that it is not interested in child process's
exit status?

2) How can this be achieved in pexpect module since it is spawning the
child process in my case.

As I said, this is more of a UNIX question rather than python one.

Thanks,
Raghu.

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


Re: threads and sleep?

2005-07-05 Thread Grant Edwards
On 2005-07-05, Grant Edwards <[EMAIL PROTECTED]> wrote:

>> Don't think you can do that with Python... The Python runtime
>> interpreter itself is running on a single processor.
>
> I don't see how that can be.  Under Linux at least, the Python
> threading module uses "real" OS threads, so there are multiple
> instances of the interpreter, right?  Generally all but one of
> them will be blocked on the GIL, but there are still multiple
> interpreter threads (which can be on multiple different CPUs).
>
> Or is the Python interpreter actually doing the context
> switches itself?

Upon further thought, that just can't be the case.  There has
to be multiple instances of the intepreter because the
interpreter can make C system calls that block (thus blocking
that instance of the interpreter). Other Python threads within
the program continue to run, so there must be multiple Python
intepreters.

-- 
Grant Edwards   grante Yow!  I'm wearing PAMPERS!!
  at   
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: More On - deepcopy, Tkinter

2005-07-05 Thread Michael Hoffman
phil wrote:
> I posted the following yesterday and got no response

When you don't get as much of a response as you expected, you might 
consider the advice here:

http://www.catb.org/~esr/faqs/smart-questions.html

Pointing you here is only meant to be helpful. If you don't feel the 
advice applies to you, feel free to ignore it, but you clearly haven't 
been getting the results from this forum that you expected.
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what is __init__.py used for?

2005-07-05 Thread Terry Hancock
On Tuesday 05 July 2005 06:39 am, John Roth wrote:
> The real kicker here is that when I say that the
> first module will be completely empty, it's not
> quite true. First, it will have some standard
> identifiers that all modules have, and second
> it will have anything you put into the __init__.py
> module file.

It's not at all uncommon, for example, for __init__.py
to contain a set of imports:

from SubMod1 import *
import SubMod2 as sub

etc,

this is one way to create the "interface" that the package
will present to you when you import it.

> This last is an advanced feature, and
> you're well advised to stay away from it until
> you've got a lot more experiance.

Not until you are writing Python packages, anyway.
But it's probably a good idea to know what it does
so that you can read what it's doing in packages you
use and/or study (and studying existing packages
is one of the best ways to learn once you've gotten
beyond the basic hurdle of writing simple programs).

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Python Regular Expressions: re.sub(regex, replacement, subject)

2005-07-05 Thread Vibha Tripathi
Hi Folks,

I put a Regular Expression question on this list a
couple days ago. I would like to rephrase my question
as below:

In the Python re.sub(regex, replacement, subject)
method/function, I need the second argument
'replacement' to be another regular expression ( not a
string) . So when I find a 'certain kind of string' in
the subject, I can replace it with 'another kind of
string' ( not a predefined string ). Note that the
'replacement' may depend on what exact string is found
as a result of match with the first argument 'regex'.

Please let me know if the question is not clear.

Peace.
Vibha

===
"Things are only impossible until they are not."

__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: More On - deepcopy, Tkinter

2005-07-05 Thread phil
>  but you clearly haven't 
> been getting the results from this forum that you expected.
> 
Yes I have, this is a wonderful forum.

I was just providing more info due to more testing.




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


Re: Python Regular Expressions: re.sub(regex, replacement, subject)

2005-07-05 Thread Steven Bethard
Vibha Tripathi wrote:
> In the Python re.sub(regex, replacement, subject)
> method/function, I need the second argument
> 'replacement' to be another regular expression ( not a
> string) . So when I find a 'certain kind of string' in
> the subject, I can replace it with 'another kind of
> string' ( not a predefined string ). Note that the
> 'replacement' may depend on what exact string is found
> as a result of match with the first argument 'regex'.
> 
> Please let me know if the question is not clear.

It's still not very clear, but my guess is you want to supply a 
replacement function instead of a replacement string, e.g.:

py> help(re.sub)
Help on function sub in module sre:

sub(pattern, repl, string, count=0)
 Return the string obtained by replacing the leftmost
 non-overlapping occurrences of the pattern in string by the
 replacement repl.  repl can be either a string or a callable;
 if a callable, it's passed the match object and must return
 a replacement string to be used.

py> def repl(match):
... print match.group()
... return '46'
...
py> re.sub(r'x.*?x', repl, 'yxyyyxxyyxyy')
xyyyx
xyyx
'y4646yy'

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


Re: f*cking re module

2005-07-05 Thread Don
jwaixs wrote:

> To reply to the last part of the discussion and esspecially to Gustavo
> Niemeyer, I really apriciate the way in which I had been answered. And
> I won't have any questions about the re module that I had before I post
> this threat.
> 
> I was frustration and should, probebly, not post this frustration. But
> it was never my purpous to ask something stupid or asking it arrogant.
> 
> The python re module is, in my opinion, a non beginner user friendly
> module. And it's not meant for beginning python programmers. I don't
> have any experience with perl or related script/programming languages
> like python. (I prefer to do things in c) So the re module is
> completely new for me.
> 
> If I upset someones clean mind posting a "stupid" and "arrogant"
> question, I'm sorry and won't post my frustrasion on this usenet group
> anymore.
> 
> But thank you for all your help about the re module,
> 
> Noud Aldenhoven


I would recommend that you give Kodos a try:

http://kodos.sourceforge.net/

Doesn't make the re syntax any easier, but I find that it allows you to more
quickly develop workable code.

-Don

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


resume upload

2005-07-05 Thread Jxzzy78

How can i resume a partial upload using ftplib ? 


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


Re: Python Regular Expressions: re.sub(regex, replacement, subject)

2005-07-05 Thread Benjamin Niemann
Vibha Tripathi wrote:

> Hi Folks,
> 
> I put a Regular Expression question on this list a
> couple days ago. I would like to rephrase my question
> as below:
> 
> In the Python re.sub(regex, replacement, subject)
> method/function, I need the second argument
> 'replacement' to be another regular expression ( not a
> string) . So when I find a 'certain kind of string' in
> the subject, I can replace it with 'another kind of
> string' ( not a predefined string ). Note that the
> 'replacement' may depend on what exact string is found
> as a result of match with the first argument 'regex'.

Do mean 'backreferences'?

>>> re.sub(r"this(\d+)that", r"that\1this", "this12that foo13bar")
'that12this foo13bar'

Note that the replacement string r"that\1this" is not a regular expression,
it has completely different semantics as described in the docs. (Just
guessing: are you coming from perl? r"xxx" is not a regular expression in
Python, like /xxx/ in perl. It's is just an ordinary string where
backslashes are not interpreted by the parser, e.g. r"\x" == "\\x". Using
r"" when working with the re module is not required but pretty useful,
because re has it's own rules for backslash handling).

For more details see the docs for re.sub():
http://docs.python.org/lib/node114.html

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://www.odahoda.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Folding in vim

2005-07-05 Thread Sybren Stuvel
Andrea Griffini enlightened us with:
> - never ever use tabs

I always use one tab for indents, and set my editor to display it as
four spaces. I like being able to unindent a line by deleting a single
character. I don't see a reason why _not_ to use tabs, really. As long
as the use is consistent - I hate those files with an 8-space tab and
4-space indent, where they replace two indents with a single tab. For
me, one indent = one tab. No matter the tab setting, it'll look good.

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


Re: f*cking re module

2005-07-05 Thread Gustavo Niemeyer
> To reply to the last part of the discussion and esspecially to Gustavo
> Niemeyer, I really apriciate the way in which I had been answered. And
> I won't have any questions about the re module that I had before I
> post this threat.

Great! As I said, that's a nice news group.

> I was frustration and should, probebly, not post this frustration. But
> it was never my purpous to ask something stupid or asking it arrogant.

You can post frustration for sure. But saying "f*cking re module"
and than showing that your problem is not understanding the very
basics of regular expressions is not a nice way to ask for help.

> The python re module is, in my opinion, a non beginner user friendly
> module. And it's not meant for beginning python programmers. I don't
> have any experience with perl or related script/programming languages
> like python. (I prefer to do things in c) So the re module is
> completely new for me.

  >>> re.match("(.*)", "foobar").group(1)
  'foobar'

That's very similar to your problem and looks quite clear and
simple, but you must understand what regular expressions are
about, of course.

> If I upset someones clean mind posting a "stupid" and "arrogant"
> question, I'm sorry and won't post my frustrasion on this usenet group
> anymore.

Not upset at all. You just asked it the wrong way, and I was impressed
that even then there were lots of people to help you. That's not
usual in most places.

> But thank you for all your help about the re module,

In my opinion you would benefit from looking at some documentation
talking about regular expressions in general. After you understand
them, the re module will look f*cking simple. ;-)

-- 
Gustavo Niemeyer
http://niemeyer.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: f*cking re module

2005-07-05 Thread Paul McGuire
Your elaboration on what problem you are actually trying to solve gave
me some additional insights into your question.  It looks like you are
writing a Python-HTML templating system, by embedding Python within
HTML using ... tags.

As many may have already guessed, I worked up a pyparsing treatment of
your problem.  As part of the implementation, I reinterpreted your
transformations slightly.  You said:

>>>I want to replace the  with " ",  
>>>with "\n" and every thing that's not between the two
>>>python tags must begin with "\nprint \"\"\"" and
>>>end with "\"\"\"\n"

If this were an HTML page with  tags, it might look like:



x = 1



The corresponding CGI python code would then read:
print """\n"""
x = 1
print """\n"""

So we can reinterpret your transformation as:
1. From start of file to first  tag,
   enclose in print """\n"""
2. From  tag to  tag to next  tag,
   enclose in print """\n"""
4. From last  tag to end of file,
   enclose in print """\n"""

Or more formally:
  -> 'print r"""'
 -> '"""\n'
<\python> -> 'print r"""'
 -> '"""\n'

Now that we have this defined, we can consider adding some standard
imports to the  transformation, such as "import
sys", etc.

Here is a working implementation.  The grammar itself is only about 10
lines of code, mostly in defining the replacement transforms.  The last
18 lines are the test case itself, printing the transformed string, and
then eval'ing the transformed string.


# Take HTML that has   tags interspersed, with python
code
# between the  tags.  Convert to running python cgi program.

# replace  with r'"""\n' and  with r'\nprint """'
# also put 'print """\ \n' at the beginning and '"""\n' at the end

from pyparsing import *

class OnlyOnce(object):
def __init__(self, methodCall):
self.callable = methodCall
self.called = False
def __call__(self,s,l,t):
if not self.called:
self.called = True
return self.callable(s,l,t)
raise ParseException(s,l,"")

stringStartText = """import sys
print "Content-Type: text/html\\n"
print r\"\"\
stringEndText = '"""\n'
startPythonText = '"""\n'
endPythonText = '\nprint r"""\n'

# define grammar
pythonStart = CaselessLiteral("")
pythonEnd = CaselessLiteral("")
sStart = StringStart()
sEnd = StringEnd()

sStart.setParseAction( OnlyOnce( replaceWith(stringStartText) ) )
sEnd.setParseAction( replaceWith(stringEndText) )
pythonStart.setParseAction( replaceWith(startPythonText) )
pythonEnd.setParseAction( replaceWith(endPythonText) )

xform = sStart | sEnd | pythonStart | pythonEnd

# run test case
htmlWithPython = r"""

Sample Page Created from Python


Sample Page Created from Python

for i in range(10):
print "This is line %d" % i



"""

generatedPythonCode = xform.transformString( htmlWithPython )
print generatedPythonCode
print
exec(generatedPythonCode)

Here is the output:
import sys
print "Content-Type: text/html\n"
print r"""

Sample Page Created from Python


Sample Page Created from Python
"""

for i in range(10):
print "This is line %d" % i

print r"""



"""


Content-Type: text/html



Sample Page Created from Python


Sample Page Created from Python

This is line 0
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9






This exercise was interesting to me in that it uncovered some
unexpected behavior in pyparsing when matching on positional tokens (in
this case StringStart and StringEnd).  I learned that:
1. Since StringStart does not advance the parsing position in the
string, it is necessary to ensure that the parse action get run only
once, and then raise a ParseException on subsequent calls.  The little
class OnlyOnce takes care of this (I will probably fold OnlyOnce into
the next point release of pyparsing).
2. StringEnd is not well matched during scanString or transformString
if there is no trailing whitespace at the end of the input.  Even a
trailing \n is sufficient.  My first example of testdata ended with the
closing  tag, with no carriage return, and
scanString/transformString failed to match.  If I added a newline to
close the  tag, then scanString could find the StringEnd.  This
is not a terrible workaround, but it's another loose end to tie up in
the next release.

Enjoy!
-- Paul

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


Re: math.nroot [was Re: A brief question.]

2005-07-05 Thread Michael Hudson
Tim Peters <[EMAIL PROTECTED]> writes:

> [Tim Peters]
> >> All Python behavior in the presence of infinities, NaNs, and signed
> >> zeroes is a platform-dependent accident, mostly inherited from that
> >> all C89 behavior in the presence of infinities, NaNs, and signed
> >> zeroes is a platform-dependent crapshoot.
>  
> [Michael Hudson]
> > As you may have noticed by now, I'd kind of like to stop you saying
> > this :) -- at least on platforms where doubles are good old-fashioned
> > 754 8-byte values.
> 
> Nope, I hadn't noticed!  I'll stop saying it when it stops being true,
> though .  Note that since there's not even an alpha out for 2.5
> yet, none of the good stuff you did in CVS counts for users yet.

Well, obviously.  OTOH, there's nothing I CAN do that will be useful
for users until 2.5 actually comes out.

> > But first, I'm going to whinge a bit, and lay out some stuff that Tim
> > at least already knows (and maybe get some stuff wrong, we'll see).
> >
> > Floating point standards lay out a number of "conditions": Overflow
> > (number too large in magnitude to represent), Underflow (non-zero
> > number to small in magnitude to represent), Subnormal (non-zero number
> > to small in magnitude to represent in a normalized way), ...
> 
> The 754 standard has five of them:  underflow, overflow, invalid
> operation, inexact, and "divide by 0" (which should be understood more
> generally as a singularity; e.g., divide-by-0 is also appropriate for
> log(0)).

OK, the decimal standard has more, which confused me for a bit
(presumably it has more because it doesn't normalize after each
operation).

> > For each condition, it should (at some level) is possible to trap each
> > condition, or continue in some standard-mandated way (e.g. return 0
> > for Underflow).
> 
> 754 requires that, yes.
> 
> > While ignoring the issue of allowing the user to control this, I do
> > wish sometimes that Python would make up it's mind about what it does
> > for each condition.
> 
> Guido and I agreed long ago that Python "should", by default, raise an
> exception on overflow, invalid operation, and divide by 0, and "should
> not", by default, raise an exception on underflow or inexact.

OK.

> Such defaults favor non-expert use.  Experts may or may not be happy
> with them, so Python "should" also allow changing the set.

Later :)

(In the mean time can we just kill fpectl, please?)

> > There are a bunch of conditions which we shouldn't and don't trap by
> > default -- Underflow for example.  For the conditions that probably should
> > result in an exception, there are inconsistencies galore:
> 
> > >>> inf = 1e300 * 1e300 # <- Overflow, no exception
> > >>> nan = inf/inf # <- InvalidOperation, no exception
> 
> Meaning you're running on a 754 platform whose C runtime arranged to
> disable the overflow and invalid operation traps.

Isn't that the standard-mandated start up environment?

> You're seeing native HW fp behavior then.

But anyway, shouldn't we try to raise exceptions in these cases?  I
don't think it's a particularly good idea to try to utilize the fp
hardware's ability to do this at this stage, btw, but to add some kind
of check after each operation.

> > >>> pow(1e100, 100) <- Overflow, exception
> > Traceback (most recent call last):
> >  File "", line 1, in ?
> > OverflowError: (34, 'Numerical result out of range')
> > >>> math.sqrt(-1) # <- InvalidOperation, exception
> > Traceback (most recent call last):
> >  File "", line 1, in ?
> > ValueError: math domain error
> 
> Unlike the first two examples, these call libm functions.

And the user cares about this why?

> Then it's a x-platform crapshoot whether and when the libm functions
> set errno to ERANGE or EDOM, and somewhat of a mystery whether it's
> better to reproduce what the native libm considers to be "an error",
> or try to give the same results across platforms.  Python makes a
> weak attempt at the latter.

Well, you can at least be pretty sure that an infinite result is the
result of an overflow condition, I guess.

> > At least we're fairly consistent on DivisionByZero...
> 
> When it's a division by 0, yes.  It's cheap and easy to test for that.
>  However, many expert uses strongly favor getting back an infinity
> then instead, so it's not good that Python doesn't support a choice
> about x/0.

Indeed.  But I'd rather work on non-settable predictability first.

> > If we're going to trap Overflow consistently, we really need a way of
> > getting the special values reliably -- which is what pep 754 is about,
> > and its implementation may actually work more reliably in 2.5 since my
> > recent work...
> 
> I don't know what you have in mind.  

Well, the reason I headbutted into this stuff again recently was
writing (grotty) string to float parsing code for PyPy.  If you write
(where 'e' is the exponent parsed from, say '1e309'):

while e > 0:
result *= 10
e -= 1

you get an infinite result in the large e case.  If instead you wri

Re: Folding in vim

2005-07-05 Thread Mike Meyer
Sybren Stuvel <[EMAIL PROTECTED]> writes:

> Andrea Griffini enlightened us with:
>> - never ever use tabs
>
> I always use one tab for indents, and set my editor to display it as
> four spaces. I like being able to unindent a line by deleting a single
> character. I don't see a reason why _not_ to use tabs, really. As long
> as the use is consistent - I hate those files with an 8-space tab and
> 4-space indent, where they replace two indents with a single tab. For
> me, one indent = one tab. No matter the tab setting, it'll look good.

And so if you're working with someone who uses a different tab stop -
say the traditional 8-space tabs - they'll get code that may well be
unreadable.

If you're the only one dealing with your code, you can keep the use
consistent. As soon as theirs more than one person editing the code,
that pretty much goes out the window. You either mandate a standard -
which is hard for a large group - or you mandate that you don't use
tabs.

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Folding in vim

2005-07-05 Thread Benji York
Sybren Stuvel wrote:
> I always use one tab for indents, and set my editor to display it as
> four spaces. I like being able to unindent a line by deleting a single
> character.

Your editor probably supports a "backspace unindents" option.  If using 
Vim it would be something like "set softtabstop=4".
--
Benji York
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: precision problems in base conversion of rational numbers

2005-07-05 Thread [EMAIL PROTECTED]


Brian van den Broek wrote:
> Hi all,
>
> I guess it is more of a maths question than a programming one, but it
> involves use of the decimal module, so here goes:
>
> As a self-directed learning exercise I've been working on a script to
> convert numbers to arbitrary bases. It aims to take any of whole
> numbers (python ints, longs, or Decimals), rational numbers (n / m n,
> m whole) and floating points (the best I can do for reals), and
> convert them to any base between 2 and 36, to desired precision.
>
> I'm pretty close but I know I am not handling the precision quite
> right. Nothing other than understanding hangs on it, but, that's
> enough :-)
>
> To do all this I'm using the decimal module (for the first time) and
> I've been setting the precision with
>
> decimal.getcontext().prec = max(getcontext().prec,
>  x * self.precision )
>
> This is in my class's __init__ method before I convert every number to
> Decimal type and self.precision is at this point an int passed.
>
> The first term is to be sure not to reduce precision anywhere else. In
> the last term I'd started off with x = 1, and that works well enough
> for "small" cases (i.e. cases where I demanded a relatively low degree
> of precision in the output).
>
> I've no idea how to work out what x should be in general. (I realize
> the answer may be a function of my choice of algorithm. If it is
> needed, I'm happy to extract the relevant chunks of code in a
> follow-up -- this is long already.)
>
> For getcontext.prec = 80 (i.e x = 1) when I work out 345 / 756 in base
> 17 to 80 places (i.e. self.precision = 80) I get:
>
>  >>> print Rational_in_base_n(345, 756, 17, 80)
> 0.7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0D5C1G603999179EB
>
> (Rational_in_base_n(numerator, denominator, base, precision) is the
> rational specific subclass. When I convert the result back to decimal
> notation by hand it agrees with the correct answer to as many places
> as I cared to check.)
>
> I've discovered empirically that I have to set getcontext.prec = 99 or
> greater (i.e. x >= 1.2375) to get

The value you want for x is log(17)/log(10) =
1.2304489213782739285401698943283

Multiplied by 80 gives you 98.435913710261914283213591546267, but you
can't
have a fraction of a digit, so round up to 99 (giving x=1.235).

> 0.7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7C
>
> (I do feel safe in assuming that is the right answer. :-)

It's not. The last digit should be "D".

This is how the GMPY module handles it:

>>> from gmpy import *

>>> # Create an unlimited precision rational.
>>> r = mpq(345,756)

>>> # Convert rational to floating point with 300 bits precision.
>>> # GMPY default precision is based on the nature of the rational
>>> # but can be specified. Note that prcision is in bits, not digits.
>>> f = mpf(r,300)
>>> print f
0.45634920634920634920634920634920634920634920634920634920634920634920634920634920634920634920634921

>>> # Convert the floating point to base 17.
>>> # Note that it has been correctly rounded up, so last digit is 'd'.
>>> print fdigits(f,17)
[EMAIL PROTECTED]


>
> How would I go about working out what degree of precision for the
> decimal module's context is needed to get n 'digits' of precision in
> an expression of base m in general? (I've no formal training in Comp
> Sci, nor in the relevant branches of mathematics.)
> 
> Thanks and best,
> 
> Brian vdB

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


Dr. Dobb's Python-URL! - weekly Python news and links (Jul 5)

2005-07-05 Thread Simon Brunning
QOTW: "That's what I love in that news group. Someone comes with a stupid
and arrogant question, and someone else answers in a calm and reasonable
way." - Gustavo Niemeyer

"After 25 years doing this, I've become something of a Luddite as far as
fancy IDEs and non-standard features go... and a huge believer in strict
decoupling between my tools, to the point of ignoring things that bundle
them together in ways that are, in my opinion, too tight." - Peter Hansen


Ralf Grosse-Kunstleve floats a proposal to reduce the amount of code
requires to set instance fields from arguments in __init__ methods:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/7346ad00a14e821a

The Python Software Foundation Summer of Code projects have been selected:
http://www.amk.ca/diary/archives/003975.html

A discussion about the long-term plan to remove map, filter, reduce
and lambda starts out bad-tempered then ... improves little:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/ceef909ebd10b65a

There's a new wxPython tutorial at Dev Shed:
http://www.devshed.com/c/a/Python/A-Look-at-wxPython/

Peter Hansen wants to determine the wall-clock elapsed time taken by
a process on a managed host in a reliable, cross-platform way:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/cd1222d713730b67

Par Nicolas Lehuen uses Python to compare Microsoft Word documents
stored in a Subversion repository (!):

http://www.lehuen.com/nicolas/index.php/2005/06/30/60-comparing-microsoft-word-documents-stored-in-a-subversion-repository

Terry Hancock explains what ZOPE actually is:

http://groups-beta.google.com/group/comp.lang.python/msg/174d4101e0e419e8



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily  
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html 
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

For far, FAR more Python reading than any one mind should
absorb, much of it quite interesting, several pages index
much of the universe of Pybloggers.
http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog
http://www.planetpython.org/
http://mechanicalcat.net/pyblagg.html

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous
tradition early borne by Andrew Kuchling, Michael Hudson and Brett
Cannon of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/   

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance. 
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donate.html

Kurt B. Kaiser publishes a weekly report on faults and patches.
http://www.google.com/groups?as_usubject=weekly%20python%20patch
   
Cetus collects Python hyperlinks.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http://python.faqts.com/

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://aspn.activestate.com/ASPN/Cookbook/Python

Among several Python-oriented RSS/RDF feeds available are
http://www.python.org/channews.rdf
http://bootleg-rss.g-blog.net/pytho

Re: resume upload

2005-07-05 Thread Jeff Epler
probably by using REST.  This stupid program puts a 200 line file by
sending 100 lines, then using REST to set a resume position and sending
the next 100 lines.

import getpass, StringIO, ftplib

lines = ["Line %d\n" % i for i in range(200)]
part1 = "".join(lines[:100])
part2 = "".join(lines[:100])

f = ftplib.FTP('server', 'username', 'password')
f.debugging = True
f.sendcmd('CWD /tmp')
f.storbinary("STOR example", StringIO.StringIO(part1))
f.putcmd('REST %d' % len(part1))
resp = f.getresp();
if resp[0] != '3': raise ftplib.error_reply, resp
f.storbinary("STOR example", StringIO.StringIO(part2))
f.quit()


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

Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-05 Thread Christopher Subich
[EMAIL PROTECTED] wrote:
> concept quickly familiar. But "lambda" has a very clear meaning... it's
> a letter of the greek alphabet. The connection between that letter and
> anonymous functions is tenuous at best, and fails the test of making
> Python read like "executable pseudocode".

But 'lambda' does have a very clear meaning in the realm of functional 
programming, and it means precisely (mostly) what it means in Python: an 
anonymous function.

It might not be the -best- possible name, but anyone who's had a 
computer science education should have had a class that introduced basic 
functional programming topics (even if only for academic interest), and 
so they should be familiar with the keyword name.

If not, then it's just a magic word.  Kind of like 'def'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Good starterbook for learning Python?

2005-07-05 Thread Lennart
With  Dive Into Python in an other language i can learn python & the
russian language :-) Thanks anyway

Now i can learn python Op Tue, 05 Jul 2005 16:43:03 +0100 schreef
TechBookReport:

> Lennart wrote:
>> Hi everybody,
>> 
>> Can someone advice me with the following issue: i want to learn python in
>> my summer vacation (i try to ...:-) So, a good start is buying a good book.
>> But wich? There are many ...
>> 
>> I'm living in the Netherlands and I prefer a book from bol.com (see link)
>> because i've to order more books by them. I'm familiar with html & php and
>> basic (in the good old days). It has to be a newbie book, but not a book
>> what i don't need anymore when i've got some skills. I.e. the learning
>> curve of the book should be linear. A kind of book wich i could use as a
>> novice.
>> 
>> Search here for python (sorry, there's no short link)
>> http://www.nl.bol.com/is-bin/INTERSHOP.enfinity/eCS/Store/nl/-/EUR/BOL_BrowseCatalog-View;sid=nyuhO3sz8k2hODn5OfqfDJvrcywRiGQwhPU=?Section=BOOK_EN&CategoryContent=NJqR5Kpb0soAAADqmW%2eZypJb&OpenCategory=HwqR5Kpb8AUAAADqVW6ZypJb&CategoryLeftpanel=BOOK_EN%2eCATEGORY&Secondary=YES&Template=BOL_subcat_BOOK_EN_1476
> 
> Two excellent books match your criteria:
> 
> Dive Into Python (review: http://www.techbookreport.com/tbr0103.html) - 
> also available as a free download.
> 
> Learning Python (review: http://www.techbookreport.com/tbr0064.html)
> 
> Both are recommended for beginners but have a reasonable level of depth. 
> They're clear, enthusiastic and well-written.
> 
> HTH
-- 
http://mail.python.org/mailman/listinfo/python-list


best options for oracle/python?

2005-07-05 Thread Mark Harrison
Any recommendations for Oracle bindings for the
DB-API 2.0 specification?  This is for Oracle 10g
if that makes any difference.

Also, any other Oracle related goodies that might
be useful?

Many TIA!
Mark

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


Re: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code

2005-07-05 Thread mcherm
Ralf W. Grosse-Kunstleve wrote:
> I often find myself writing::
>
> class grouping:
>
> def __init__(self, x, y, z):
> self.x = x
> self.y = y
> self.z = z
> # real code, finally
>
> This becomes a serious nuisance in complex applications with long
> argument lists

Yes... indeed it does. This is so common that there is a standard
idiom for handling it:

def __init__(self, x, y, z):
self.__dict__.update(locals())

sometimes with modifications to avoid setting self.self.

> Therefore I propose that Python includes
> built-in support for reducing the ``self.x=x`` clutter.

If all you were proposing was a built-in function to make this
particular
idiom clearer and more reliable, then I think I'd back such a feature
because the need is SO common. However, the suggestion you actually
make:

> def __init__(self, .x, .y, .z):
> # real code right here

is far too broad and introduces new syntax unnecessarily.

You yourself are using a helper function (although I belive it could
be done more easily than you did it):

> I am actually using a simple trick::
>
> adopt_init_args(self, locals())

To which you raise the following objections:

>   - The solution doesn't come with Python -> everybody has to reinvent.

Good point. Particularly since people won't think of all the
special cases (eg: classes with __slots__ defined).

>   - People are reluctant to use the trick since scripts become
> dependent on a non-standard feature.
>   - It is difficult to remember which ``import`` to use for
> ``adopt_init_args`` (since everybody has a local version/variety).


If the implementation is only 3-4 lines long (and a simpler
implementation
can be), then is can simply be included inline with every script that
needs
to use it.

>   - The ``adopt_init_args(self, locals())`` incantation is hard to
> remember and difficult to explain to new-comers.

A better name would help with this. The need for locals() is
unavoidable.
But for REAL beginners, I wouldn't even bother... writing out "self.x =
x"
is useful for beginners since it helps make it very clear and concrete
to
them just what is happening.

>   - Inside the ``__init__()`` method, the same object has two names,
> e.g. ``x`` and ``self.x``. This lead to subtle bugs a few times
> when I accidentally assigned to ``x`` instead of ``self.x`` or vice
> versa in the wrong place (the bugs are typically introduced while
> refactoring).

Hmm... I've never had that problem, myself.

>   - In some cases the ``adopt_init_args()`` overhead was found to
> introduce a significant performance penalty (in particular the
> enhanced version discussed below).

Again... a different code will help here. And if execution speed is
REALLY a concern, then you can just write it out the long way!

>   - Remember where Python comes from: it goes back to a teaching
> language, enabling mere mortals to embrace programming.
> ``adopt_init_args(self, locals())`` definitely doesn't live up
> to this heritage.

No, but "self.x = x" does. It's only when you have lots of variables
or very long names that this approach becomes unwieldy.

> My minimal proposal is to add an enhanced version of ``adopt_init_args()``
> as a standard Python built-in function (actual name secondary!)::

I'd alter the name and the implementation, but the basic idea seems
sound to me.

> However, there is another problem not mentioned before:
> It is cumbersome to disable adoption of selected variables.

The VERY simple, VERY straightforward, VERY common behavior of
"store all the arguments as like-named attributes of self" is
worth having a standard idiom (and *perhaps* a built-in). But
odd special cases like skipping some arguments... that calls
for writing the whole thing out. I'm firmly -1 on any proposal
to support skipping arguments.

> When ``__slots__`` are used (cool feature!) the boilerplate problem
> becomes even worse::
>
>   class grouping:
>
>   __slots__ = ["keep_this", "and_this", "but_this_again"]
>
>   def __init__(self, keep_this, and_this, but_not_this, but_this_again):
>   self.keep_this = keep_this
>   self.and_this = and_this
>   self.but_this_again = but_this_again
>   # real code, finally
>
> Each variable name appears four times!

** NO! **

__slots__ is *NOT* to be used except for those times when you NEED
the performance advantages (mostly memory use). The simple rule is
that you should *NEVER* use __slots__ (if you are in a situation
where you *do* need it, then you'll know enough to understand why
this advice doesn't apply to you). There should NOT be any support
for auto-setting __slots__ *anywhere* in the standard library,
because it would make it FAR too tempting for people to mis-use
__slots__.

Besides, a metaclass would be a better solution, and it can be done
today with no modifications to Python.

. . .

All in all, I th

Re: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code

2005-07-05 Thread Thomas Heller
[EMAIL PROTECTED] writes:

> Ralf W. Grosse-Kunstleve wrote:
>> I often find myself writing::
>>
>> class grouping:
>>
>> def __init__(self, x, y, z):
>> self.x = x
>> self.y = y
>> self.z = z
>> # real code, finally
>>
>> This becomes a serious nuisance in complex applications with long
>> argument lists
>
> Yes... indeed it does. This is so common that there is a standard
> idiom for handling it:
>
> def __init__(self, x, y, z):
> self.__dict__.update(locals())
>
> sometimes with modifications to avoid setting self.self.

>> I am actually using a simple trick::
>>
>> adopt_init_args(self, locals())
>
> If the implementation is only 3-4 lines long (and a simpler
> implementation can be), then is can simply be included inline with
> every script that needs to use it.
>
>>   - The ``adopt_init_args(self, locals())`` incantation is hard to
>> remember and difficult to explain to new-comers.
>
> A better name would help with this. The need for locals() is
> unavoidable.

Ahem - sys._getframe()

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


Re: Using Numeric 24.0b2 with Scientific.IO.NetCDF

2005-07-05 Thread bandw
Robert,

Thanks for your reply.  However, I am still having problems.  Sometimes
I get a scalar return
and sometimes I get an array.  For example, using the netCDF file:

netcdf simple {
   dimensions:
   num = 3 ;
   variables:
   float temp0(num) ;
   int   temp1(num) ;
   data:

temp0 = 1., 2., 3. ;
temp1 = 1,  2,  3 ;
}

and running:

#
import Numeric
print Numeric.__version__
from Scientific.IO.NetCDF import NetCDFFile

cdf_file1 = NetCDFFile("simple.nc","r")

var1 = cdf_file1.variables["temp0"][:]
var2 = cdf_file1.variables["temp1"][:]
min1 = reduce(Numeric.minimum,var1)
min2 = reduce(Numeric.minimum,var2)

print "Types of var1, min(var1), min1:",type(var1), type(min(var1)),
type(min1)
print "Types of var2, min(var2), min2:",type(var2), type(min(var2)),
type(min2)

I get:

24.0b2
Types of var1, min(var1), min1:   
Types of var2, min(var2), min2:   

Even something like:


>>> import Numeric
>>> a = Numeric.array([1.,2.])
>>> print type(a),type(min(a))
 

does not produce an array.

Any comments woud be appreciated.

Fred Clare

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-05 Thread mcherm
Up until a few years ago, I ran the computer science department at a
high-school. I provided support for the English teachers who taught
*all* students -- but they taught things like the use of a word
processor or the internet, and never covered the meaning of "lambda". I
taught a computer applications course which was taken by only small
fraction of the students (<10%) but there I taught things like the use
of photo-editing software, creating web sites, and the use of simple
databases; I never covered the meaning of "lambda". I also taught the
programming class (taken by only a dozen or so students per graduating
class) -- students learned basic concepts like variables, looping, up
through fancier bits like a couple different sorting algorithms. But I
didn't cover the meaning of "lambda". And I also taught the "AP"
computer course (taken by an average of just 4 students per year!), in
which I explained things like object oriented programming and recursion
and managed to get the students to the level where they could work
together as a group to write a moderately complex program, like a
simple video game. And I didn't teach the meaning of "lambda", nor was
it covered by the "AP" exam, which is supposed to be equivalent to a
single college-level course in computer programming.

So I'd say that it's a pretty obscure name that most people wouldn't
know.

And besides, "def" isn't a "magic" word... it's an abreviation for
"define"... I hope that any student who didn't understand a word as
common as "define" wouldn't have graduated from our school.

-- Michael Chermside

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


Re: How do you program in Python?

2005-07-05 Thread Peter Hansen
Tom Anderson wrote:
> +1 insight of the century. This is the heart of the unix way - lots of 
> simple little programs that do exactly one thing well, and can be 
> composed through simple, clean interfaces. For actually getting things 
> done, a toolkit beats a swiss army knife.

Perhaps, but I'm puzzled how that explanation would apply to emacs and 
those who use it as a swiss army knife, doing everything from editing to 
email to laundry in the same editor...

(Note: this isn't a flame about emacs, nor vi for that matter, just a 
discussion about the apparent conflict in the two philosophies embodied 
by the "simple little programs" and the "emacs" approaches.)

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


Re: threads and sleep?

2005-07-05 Thread Peter Hansen
Jeffrey Maitland wrote:
> I was hoping that python would allow for the cpu threading such in
> Java etc.. but I guess not. (from the answers,and other findings) I
> guess I will have to write this part of the code in something such as
> java or c or something that allows for it then I can either wrap it in
> python or avoid python for this part of the app.

Or investigate the use of Irmen's Pyro package and how it could let you 
almost transparently move your code to a *multi-process* architecture 
which would then let you take advantage of all the CPUs you have 
available (even if they _aren't_ on the same machine!).

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


PyUnicodeUCS4_AsUnicode error

2005-07-05 Thread fjs205
When I try to import gtk, or even start some programs that use Python I
get the error:

"ImportError: /usr/lib/python2.4/site-packages/gtk-2.0/gobject.so:
undefined symbol: PyUnicodeUCS4_AsUnicode"

Can anyone shed some light on this?

FWIW, I have reinstalled python, tried v2.3.4 instead of 2.4,
reinstalled GTK, searched for a unicode library problem (I reinstalled
libunicode too).

Thanks for any assistance.

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


Re: (Win32 API) callback to Python, threading hiccups

2005-07-05 Thread Christopher Subich
Francois De Serres wrote:
> - so, on callback, I create a new thread, after checking that the 
> previous one has returned already (WaitOnSingleObject(mythread)) so we 
> only have one thread involved.

Uh... to me, this looks like a frighteningly inefficient way of doing 
things.  How about using a synchronous queue to post the data to a 
processing thread?  That way, you don't have to create an entierly new 
thread each time you receive data in the callback.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do you program in Python?

2005-07-05 Thread Grant Edwards
On 2005-07-05, Peter Hansen <[EMAIL PROTECTED]> wrote:
> Tom Anderson wrote:
>> +1 insight of the century. This is the heart of the unix way - lots of 
>> simple little programs that do exactly one thing well, and can be 
>> composed through simple, clean interfaces. For actually getting things 
>> done, a toolkit beats a swiss army knife.
>
> Perhaps, but I'm puzzled how that explanation would apply to emacs and
> those who use it as a swiss army knife, doing everything from editing to 
> email to laundry in the same editor...

It doesn't.  Emacs doesn't follow the Unix way.

> (Note: this isn't a flame about emacs, nor vi for that matter,
> just a discussion about the apparent conflict in the two
> philosophies embodied by the "simple little programs" and the
> "emacs" approaches.)

Who said there wasn't a conflict?

-- 
Grant Edwards   grante Yow!  Xerox your lunch
  at   and file it under "sex
   visi.comoffenders"!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-05 Thread Peter Hansen
[EMAIL PROTECTED] wrote:
[snip description of experience teaching high school students]
> So I'd say that it's a pretty obscure name that most people wouldn't
> know.

It would be hard to argue against that statement; certainly "lambda" in 
this context (or probably any) is not a word "most people" would know.

On the other hand, the name itself is probably not very important.  I 
still remember my first encounter with "lambda" in Python very clearly.

I saw the word, thought "huh? what the heck is that?", then read a 
sentence about it that included some comment about its background in 
other fields.

"Oh," I said, "pre-existing usage.  Whatever."  I proceeded to read 
about what it did and how to use it.

The name was irrelevant.  If the text had said "anonymous functions are 
created using the keyword 'tribble' (named for a similar feature in a 
fictional Klingon programming language)", I wouldn't have felt any 
differently about it.  So it makes some sense to a few trekkers... big 
furry deal.

What bothered me was the syntax.  Arguments without parentheses?  What 
possessed anyone to put something so inconsistent in the language?  No 
statements?  Dang, that will limit my interest in using them.  Oh well, 
what's page four of the tutorial got for me next?  It shouldn't take 
anyone more than ten seconds to integrate "lambda" into their brain and 
carry on with useful work.

Really, the name is such a trivial, unimportant part of this whole thing 
that it's hardly worth discussing.  The syntax is more important, and 
the limitations are of definite interest.  Not the name.

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-05 Thread Grant Edwards
On 2005-07-05, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> Up until a few years ago, I ran the computer science department at a
> high-school. I provided support for the English teachers who taught
> *all* students -- but they taught things like the use of a word
> processor or the internet,

That's not computer science.

> and never covered the meaning of "lambda". I taught a computer
> applications course which was taken by only small fraction of
> the students (<10%) but there I taught things like the use of
> photo-editing software, creating web sites, and the use of
> simple databases;

That's not computer science.

> I never covered the meaning of "lambda". I also taught the
> programming class (taken by only a dozen or so students per
> graduating class) -- students learned basic concepts like
> variables, looping, up through fancier bits like a couple
> different sorting algorithms.

Now you're getting a little closer to computer science.

It sounds like you ran a computer user training department.  I
don't think it could be called computer science.

> But I didn't cover the meaning of "lambda". And I also taught
> the "AP" computer course (taken by an average of just 4
> students per year!), in which I explained things like object
> oriented programming and recursion and managed to get the
> students to the level where they could work together as a
> group to write a moderately complex program, like a simple
> video game. And I didn't teach the meaning of "lambda", nor
> was it covered by the "AP" exam, which is supposed to be
> equivalent to a single college-level course in computer
> programming.

Computer programming isn't the same thing as computer science.
It's just one of the tools used to do computer science.

> So I'd say that it's a pretty obscure name that most people
> wouldn't know.

I can't believe that anybody with any computer science
background doesn't know it.

> And besides, "def" isn't a "magic" word... it's an abreviation
> for "define"... I hope that any student who didn't understand
> a word as common as "define" wouldn't have graduated from our
> school.

Lamda isn't a magic word either.  It comes from lambda
calculus.

-- 
Grant Edwards   grante Yow!  Is this where people
  at   are HOT and NICE and they
   visi.comgive you TOAST for FREE??
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Folding in vim

2005-07-05 Thread Sybren Stuvel
Benji York enlightened us with:
> Your editor probably supports a "backspace unindents" option.

Yes, it does. I'm using vim.

> If using Vim it would be something like "set softtabstop=4".

This gives you a mixture of tabs and spaces, which I don't like. I'd
rather use real tabs for indenting. If you then use another tab width,
you only see a wider indent, but the rest of the code is okay.

When using a tab/space mixture, with eight spaces being one tab, and
an indent of four spaces, things go wrong when the tab size is
anything but eight spaces.

My solution works for all tab sizes, the other solution only works for
tabs of eight spaces. This is why in my opinion it's better to just
use tabs.

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


Re: Good starterbook for learning Python?

2005-07-05 Thread Sybren Stuvel
Lennart enlightened us with:
> Can someone advice me with the following issue: i want to learn
> python in my summer vacation (i try to ...:-) So, a good start is
> buying a good book.  But wich? There are many ...

http://www.diveintopython.org/ - I read it during the weekend, and
it's a very good book. Clearly written, good examples and a healthy
dose of humor.

> I'm living in the Netherlands and I prefer a book from bol.com (see link)
> because i've to order more books by them.

Dive Into Python can be freely downloaded.

> Search here for python (sorry, there's no short link)

Yes there is. Check http://tinyurl.com/

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


Re: Python Regular Expressions: re.sub(regex, replacement, subject)

2005-07-05 Thread George Sakkis
"Vibha Tripathi" <[EMAIL PROTECTED]> wrote:

> Hi Folks,
>
> I put a Regular Expression question on this list a
> couple days ago. I would like to rephrase my question
> as below:
>
> In the Python re.sub(regex, replacement, subject)
> method/function, I need the second argument
> 'replacement' to be another regular expression ( not a
> string) . So when I find a 'certain kind of string' in
> the subject, I can replace it with 'another kind of
> string' ( not a predefined string ). Note that the
> 'replacement' may depend on what exact string is found
> as a result of match with the first argument 'regex'.

In re.sub, 'replacement' can be either a string, or a callable that
takes a single match argument and should return the replacement string.
So although replacement cannot be a regular expression, it can be
something even more powerful, a function. Here's a toy example of what
you can do that wouldn't be possible with regular expressions alone:

>>> import re
>>> from datetime import datetime
>>> this_year = datetime.now().year
>>> rx = re.compile(r'(born|gratuated|hired) in (\d{4})')
>>> def replace_year(match):
>>> return "%s %d years ago" % (match.group(1), this_year - 
>>> int(match.group(2)))
>>> rx.sub(replace_year, 'I was born in 1979 and gratuated in 1996.')
'I was born 26 years ago and gratuated 9 years ago'

In cases where you don't have to transform the matched string (such as
calling int() and evaluating an expression as in the example) but only
append or prepend another string, there is a simpler solution that
doesn't require writing a replacement function: backreferences.
Replacement can be a string where \1 denotes the first group of the
match, \2 the second and so on. Continuing the example, you could hide
the dates by:

>>> rx.sub(r'\1 in ', 'I was hired in 2001 in a company of 2001 employees.')
'I was hired in  in a company of 2001 employees.'

By the way, run the last example without the 'r' in front of the
replacement string and you'll see why it is there for.

HTH,

George

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


Re: precision problems in base conversion of rational numbers

2005-07-05 Thread Brian van den Broek
Terry Hancock said unto the world upon 05/07/2005 11:49:
> On Monday 04 July 2005 06:11 am, Brian van den Broek wrote:
> 
>>As a self-directed learning exercise I've been working on a script to 
>>convert numbers to arbitrary bases. It aims to take any of whole 
>>numbers (python ints, longs, or Decimals), rational numbers (n / m n, 
>>m whole) and floating points (the best I can do for reals), and 
>>convert them to any base between 2 and 36, to desired precision.

Thanks to Terry and mensanator for the replies.

To consolidate, I respond to Terry in-line and then add some response 
to mensanator at the end.


> Interesting, I'd like to see that.

I'd like it to be seen :-)  I will soon send my current version in a 
private email.


>>I'm pretty close but I know I am not handling the precision quite 
>>right. Nothing other than understanding hangs on it, but, that's 
>>enough :-)
> 
> 
> Okay.  You do understand that many numbers that can be exactly
> represented in one base cannot be in another?

Indeed. The original impetus for writing this was to substantiate my 
claim in an off-list conversation that whether a given rational had a 
repeating or terminating expansion was a function of the base of 
representation. In particular, that 1 / n in base n is 0.1


> E.g. in base 3, one-third is 0.1, but in base 10, it's a repeating
> decimal: 0.333  And of course, there are infinitely many
> other examples.

The exact example I used in my off-list exchange :-)
(No "great minds" claim, sadly, as it is the natural example.)





> Needless to say, the conventional floating point numbers in Python
> are actually stored as *binary*, which is why there is a "decimal"
> module (which is new).
> 
> If you're going to be converting between bases anyway, it probably
> makes little difference whether you are using the decimal module
> or not, of course.  You'll have the same problems the conventional
> float numbers do.

It may be a function of the algorithm I picked, but I am almost 
certain that I switched to employing Decimals after finding a 
substantial inaccuracy with a purely float logic. I will likely get 
around to switching back to floats late tonight to confirm my 
recollection.


> Getting back to your precision problem: I bet if you simply
> evaluate the error term as I have above, and then convert *that* into
> your base of choice, you will be able to tell how many places are
> correct in the conversion.
> 
> That is to, say, stop think about "number of places" and instead
> think about "representation error".  That number is a real property
> of the data which can be represented in any base.  Then you can
> convert it to number of places in the representation process.

A useful "cognitive correction", thanks :-)


> e.g. 0.05 has 6 places behind the zero in decimal, how many
> does base3(0.05)? --- that's the accuracy of the statement
> 
> 0.3 base10 ~= 0.1 base3 +- base3(0.05 base10)
> 
> Roughly, we know that 0.05 = 10^-5 / 2.  The same term
> in base 3 will be 3^-x/2 = 10^5/2 places, which can be solved
> using logarithms, but I'll "leave that as an excercise for the reader",
> because I'm too lazy to go look it up, and I've forgotten the
> details. ;-)

Thanks. mensanator provided the actual formula for my case. I had a 
"magic number" in my code by which I multiplied my desired level of 
"number of places in the representation" to obtain the value for 
decimal.getcontext.prec.

mensanator wrote:

> The value you want for x is log(17)/log(10) =
> 1.2304489213782739285401698943283

where x was my "magic number". I've not had a chance to think it 
through yet, but I feel confident that given the formula, I'll be able 
to work out *why* that is the formula I need.

So, thanks for that, too.

mensanator also pointed out an inaccuracy in my posted example. I had 
345 / 756 represented in base 17 to 80 digits, and came up with a 
repeating expansion. It was pointed out that I should have rounded up 
the last 'digit' ['17-it' ? :-) ]. Indeed. I'd been concentrating on 
getting the conversion logic right before adding logic to deal with 
rounding and should have mentioned my result was not a rounded one, 
but merely a truncation of the infinite expansion. Thanks for the 
correction / reminder to add the logic.

> I hope this is helpful, though,
> Terry

Indeed, both your's and mensanator's. Thanks to both. Best to all,

Brian vdB


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


Re: distutils is able to handle...

2005-07-05 Thread Robert Kern
George Sakkis wrote:
> "mg" <[EMAIL PROTECTED]> wrote:
> 
> 
>>Hello
>>
>>I work on an finite element framework and Python bindings have been
>>developped.
>>Actually, we use Boost.Build as build system but we would like to change
>>it.
>>
>>We have two kinds of problems. First, the framework is used for generate
>>pure C++ applications with static libraries ; second, the framework have
>>some dependencies to fortran projects.
>>Then, in order to know if Distutils can be use in our case, I would like
>>to know if :
>>- Can distutil compile static C/C++ libraries ?
>>- Can distutil compile C/C++ applications ?
>>- Can distutil manage fortran compiler and compile fortran libraries and
>>applications ?
>>
>>Thank for your answers
> 
> I don't think distutils can handle all these, especially the last one,
> so I doubt it's the right tool in your case. I would suggest SCons
> (http://www.scons.org/), a modern make/automake/autoconf replacement
> that uses python for its configuration files instead of yet another
> cryptic half-baked mini-language or XML.

It does handle FORTRAN when using the scipy_distutils extensions.

-- 
Robert Kern
[EMAIL PROTECTED]

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

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-05 Thread Devan L
def flatten(iterable):
if not hasattr(iterable, '__iter__'):
return [iterable]
return sum([flatten(element) for element in iterable],[])
Recursion makes things so much shorter.

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


  1   2   >