Re: Eclipse/PyDev - BOM Lexical Error

2010-10-13 Thread Steven D'Aprano
On Thu, 14 Oct 2010 16:41:13 +1300, Lawrence D'Oliveiro wrote:

> In message , Ethan
> Furman wrote:
> 
>> Lawrence D'Oliveiro wrote:
>>
>>> In message ,
>>> Ethan Furman wrote:
>>> 
Lawrence D'Oliveiro wrote:

>In message ,
>Ethan Furman wrote:
>
MS treats those first three bytes as a flag -- if they equal the BOM,
MS treats it as UTF-8, if they equal anything else, MS does not treat
it as UTF-8.
>>> 
>>> So what does it treat it as? You previously gave examples of flag
>>> values for dBase III. What are the flag values for Windows-1252,
>>> versus, say, ISO-8859-15?
>> 
>> I am not aware of any other flag values for text files besides the BOM
>> for UTF-8.
> 
> Then how can you say “MS treats those first three bytes as a flag”,
> then?

Because Microsoft tools treat those first three bytes as a flag. An 
*optional* flag, but still a flag. If the first three bytes of a text 
file equal the UTF-8 BOM, most MS tools treat them as a BOM. If they 
equal any other value, then they are not treated as a BOM, but merely 
part of the file's contents.

http://blogs.msdn.com/b/oldnewthing/archive/2004/03/24/95235.aspx
http://blogs.msdn.com/b/oldnewthing/archive/2007/04/17/2158334.aspx

It's not just Notepad either:

http://support.microsoft.com/kb/301623
http://msdn.microsoft.com/en-us/library/cc295463.aspx


The Python interpreter does the same thing too:

http://docs.python.org/reference/lexical_analysis.html#encoding-declarations



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


Question regarding python2.5 migration from windows xp to windows 7

2010-10-13 Thread python_tsp
Hi,

We have a Python based test framework which is being used in various
projects.

Our current environment is
Python (ver 2.5.1)
wxPython (wxPython2.8-win32-ansi-2.8.6.0-py25)
pywin32-210.win32-py2.5
vcredist_x86.exe
pyserial-2.2

Our Framework is being currently used in Windows XP.

The issue is:
Soon our environment will be migrated from Windows XP to Windows 7.
In this regard, I would be in need of suggestions/ideas/information
regarding migration of our existing framework into windows 7
environment.

Do i need to migrate our framework from Python 2.5 to either Python
2.6 or directly to Python 3.0 ? What happens to all supporting
packages..etc

Which is the best way ?

We tried out of some option of using our framework under virtual xp
context of windows 7.Thou it works for timebeing,i am not interested
to having the same as kind of way of working for future.

Please help

Many thanks in advance

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


Re: what happens to Popen()'s parent-side file descriptors?

2010-10-13 Thread Chris Torek
In article 
Roger Davis   wrote:
>My understanding is that this functionality is best coded via
>subprocess.Popen().

"Best" is always a big question mark. :-)

>I need to read output from these spawned children
>via a pipe from their stdout, hence something like
>
> p= subprocess.Popen(args, stdout=subprocess.PIPE)
>
>This means that somewhere a pipe file descriptor is opened on the
>parent side to read from the child's stdout. When, if ever, is that
>descriptor closed?

(I am going to tell this tale in a slightly different order than
your question asked, as I think it works out better that way.)

subprocess.Popen() creates the instance variable and any pipes
needed, forks (on a Unix system) the target process, but has not
yet done any I/O with it (except to read a success/fail indicator
for whether the exec worked and/or any exception that occurred
before then, e.g., during the preexec_fn).  It then makes the stdin,
stdout, and/or stderr attributes (p.stdout, for the example above)
using os.fdopen().  Streams not requested in the call are set to
None (so p.stderr, for instance, will be None in this case).

At this point, then, the underlying open pipe is still around.
But your next step is (normally) to use p.communicate(); this is
where most of the magic happens.  The Unix implementation loops,
using select() to read and write from/to whichever pipe(s) are open
to the child process, until *all* data are sent and received.  As
each data stream is finished, it is closed (in this case, via
self.stdout.close()).  Lastly, p.communicate() invokes p.wait() (via
self.wait()), to wait for the child process to exit.

By the time p.communicate() returns, the pipe is closed and the
command has finished.  The entire output text, however large it
is, is returned as the first element of the return-value 2-tuple
(remember that p.communicate() returns both the stdout and the
stderr -- stderr will be the empty string in this case, as stderr
was not redirected in the subprocess.Popen() call).

>Per-process FDs are limited and I am looping
>infinitely so I need to be very careful about not running out of them.
>Are there any other FDs related to this operation that also need to be
>closed?

Only if you (or code you call) have opened them and not set
FD_CLOEXEC.  In this case, you can set close_fds = True in your
call to subprocess.Popen().  That will make the child of fork()
loop over higher-number fd's, calling os.close() on each one.

>Testing with the interpreter (2.6, MacOSX) it appears that p.stdout is
>being closed somehow by someone other than me:
>
>import subprocess
>args= ["echo", "This is a mystery!"]
>i= 0
>while True:
>p= subprocess.Popen(args, stdout=subprocess.PIPE)
>for line in p.stdout:
>print "[%5d] %s" % (i, line.strip())
>i+= 1
>
>The above code closes nothing but appears to run indefinitely without
>running the parent out of FDs. WTF is going on here?

The above reads from p.stdout -- the os.fdopen() result on the
underlying pipe -- directly.  In the general case (multiple input
and output pipes), this is not safe as you can deadlock with
constipated pipes (hence the existence of p.communicate()).  In
this specific case, there is just one pipe so the deadlock issue
goes away.  Instead, the file descriptor remains open while the
inner loop runs (i.e., while "line in p.stdout" is able to fetch
lines via the file's iterator).  When the loop stops the pipe is
still open in the parent, but the child has finished and is now
exiting (or has exited or will exit soon).  You then reach the
"i+=1" line and resume the loop, calling subprocess.Popen()
anew.

Now we get to the even deeper magic. :-)

What happens to the *old* value in p?  Answer: because p is
reassigned, the (C implementation, interpreted Python bytecode
runtime) reference count drops [%].  Since p was the only live
reference, the count drops from 1 to 0.  This makes the old instance
variable go away, invoking old_p.__del__() as it were.  The deletion
handler cleans up a few things itself, including a a call to
os.waitpid() if needed, and then simply lets the reference to
old_p.stdout go away.  That in turn decrements old_p.stdout's
reference count.  Since that, too, reaches zero, its __del__ is
run ... and *that* closes the underlying file descriptor.

[% This is all simplified -- the Python documentation mentions that
reference counting for local variables is somewhat tricked-out by
the compiler to avoid unnecessary increments and decrements.  The
principles apply, though.]

Running the above code fragment in a different implementation, in
which garbage collection is deferred, would *not* close the file
descriptor, and the system would potentially run out (depending on
when a gc occurred, and/or whether the system would attempt gc on
running out of file descriptors, in the hope that the gc would free
some up).

The subprocess module does go through a bunch of extra work to make
sure that any as-yet-uncollected fork()ed proc

Question regarding python migration

2010-10-13 Thread Pramod Thirthachar Sridhar
Hi,



We have a Python based test framework which is being used in various projects.



Our current environment is

Python (ver 2.5.1)

wxPython (wxPython2.8-win32-ansi-2.8.6.0-py25)

pywin32-210.win32-py2.5

vcredist_x86.exe

pyserial-2.2



Our Framework is being currently used in Windows XP.



The issue is:

Soon our environment will be migrated from Windows XP to Windows 7.

In this regard, I would be in need of suggestions/ideas/information regarding 
migration of our existing framework into windows 7 environment.



Do i need to migrate our framework from Python 2.5 to either Python 2.6 or 
directly to Python 3.0 ? What happens to all supporting packages..etc



Which is the best way ?



We tried out of some option of using our framework under virtual xp context of 
windows 7.Thou it works for timebeing,i am not interested to having the same as 
kind of way of working for future.



Please help



Many thanks in advance



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


Question regarding python migration

2010-10-13 Thread Pramod Thirthachar Sridhar
Hi,



We have a Python based test framework which is being used in various projects.



Our current environment is

Python (ver 2.5.1)

wxPython (wxPython2.8-win32-ansi-2.8.6.0-py25)

pywin32-210.win32-py2.5

vcredist_x86.exe

pyserial-2.2



Our Framework is being currently used in Windows XP.



The issue is:

Soon our environment will be migrated from Windows XP to Windows 7.

In this regard, I would be in need of suggestions/ideas/information regarding 
migration of our existing framework into windows 7 environment.



Do i need to migrate our framework from Python 2.5 to either Python 2.6 or 
directly to Python 3.0 ? What happens to all supporting packages..etc



Which is the best way ?



We tried out of some option of using our framework under virtual xp context of 
windows 7.Thou it works for timebeing,i am not interested to having the same as 
kind of way of working for future.



Please help



Many thanks in advance



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


Python, Windows, and file sockets

2010-10-13 Thread culix
Hey list,

I have a question about unix-style file sockets and/or named pipes
with python. I have a linux server program that uses a file socket to
listen for connections. It has been ported to Windows with cygwin (I'm
running WinXP SP3). On linux I have a python script that acts as a
client - it connects to the socket with code like

sock = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
sock.connect("/some/file/socket")

It then communicates with a bunch of sock.send() and sock.recv() calls
as normal.

Since the server runs on Windows I would like to make the client run
on Windows. However, this seems to be difficult because the AF_UNIX
socket type has not been defined in Windows python. I have tried using
'multiprocessing' Pipes and Clients, as well as the 'socket' module,
but in both cases I get an error that says "'module' object has no
attribute 'AF_UNIX'". As well the socket documentation says "If the
AF_UNIX constant is not defined then this protocol is unsupported" (
http://docs.python.org/library/socket.html#socket.AF_UNIX ). I also
tried using select(). For select.select() the docs say "On Windows,
the underlying select() function is provided by the WinSock library,
and does not handle file descriptors that don’t originate from
WinSock". Indeed, if I try this (after opening the socket with
subprocess.Popen()), I get "'C:\some\file\socket' is not recognized as
an internal or external command, operable program or batch file" on
the command line, and " (10038, 'An operation
was attempted on something that is not a socket')" from python.


I have successfully written C code that will talk to the file socket
on Windows, so I believe this is possible on the OS. But I would
rather port the existing python client than create a new one in a
different language.

So: is it possible to talk to a file socket via python on Windows?
Does it require implementing enough functionality to get AF_UNIX
sockets defined? Is there some other obvious method that I'm
overlooking?


Thanks for listening,
culix
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Whining about "struct"

2010-10-13 Thread Ned Deily
In article ,
 Tim Roberts  wrote:
> I have a bad memory.  I admit it.  Because of that, the Python "help"
> system is invaluable to me.  Up through Python 2.5, I could get a quick
> reference to the format specifiers for the struct module via
>   import struct; help(struct)
> 
> I used that a LOT.
> 
> But in Python 2.6, the struct module moved from Python code to C code, and
> that helpful help string was removed.
> 
> Is that still gone in Python 3.1?  What are the chances of reinstating that
> helpful chart?

Hmm, for me, help(struct) produces pretty similar results on all pythons 
from 2.5 through 3.2.  (This is on Mac OS X with the Pythons from 
various sources.)  Here's a snippet from the 3.1.2 help:

[...]
DESCRIPTION
Functions to convert between Python values and C structs.
Python bytes objects are used to hold the data representing the C 
struct
and also as format strings (explained below) to describe the layout 
of data
in the C struct.

The optional first format char indicates byte order, size and 
alignment:
  @: native order, size & alignment (default)
  =: native order, std. size & alignment
  <: little-endian, std. size & alignment
  >: big-endian, std. size & alignment
  !: same as >

The remaining chars indicate types of args and must match exactly;
[...]

Is that what you meant?   Ah, I see.  It looks like the doc string was 
missing-in-action in the initial 2.6 releases but subsequently fixed (as 
of 2.6.5 or so).

-- 
 Ned Deily,
 n...@acm.org

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


Re: what happens to Popen()'s parent-side file descriptors?

2010-10-13 Thread Nobody
On Wed, 13 Oct 2010 14:58:57 -0700, Roger Davis wrote:

> My understanding is that this functionality is best coded via
> subprocess.Popen(). I need to read output from these spawned children
> via a pipe from their stdout, hence something like
> 
>  p= subprocess.Popen(args, stdout=subprocess.PIPE)
> 
> This means that somewhere a pipe file descriptor is opened on the
> parent side to read from the child's stdout. When, if ever, is that
> descriptor closed? Per-process FDs are limited and I am looping
> infinitely so I need to be very careful about not running out of them.
> Are there any other FDs related to this operation that also need to be
> closed?
> 
> Testing with the interpreter (2.6, MacOSX) it appears that p.stdout is
> being closed somehow by someone other than me:
> 
> import subprocess
> args= ["echo", "This is a mystery!"]
> i= 0
> while True:
> p= subprocess.Popen(args, stdout=subprocess.PIPE)
> for line in p.stdout:
> print "[%5d] %s" % (i, line.strip())
> i+= 1
> 
> The above code closes nothing but appears to run indefinitely without
> running the parent out of FDs. WTF is going on here?

Garbage collection is going on here.

On the second and subsequent invocations of:

p= subprocess.Popen(args, stdout=subprocess.PIPE)

the assignment to p causes its previous value to become unreferenced.

This will eventually result in a call to the __del__ method of the
now-unreferenced Popen object, which will poll to see if the child is
still running.

If it has terminated, the child process will be reaped and the Popen
object can be discarded. Otherwise, it will be put onto a list
(subprocess._active) of processes to be polled by subprocess._cleanup(),
which is called whenever a new Popen object is created.

IOW, Popen objects are garbage-collected in a "sane" manner; the
associated child processes are allowed to continue running and will
be reaped semi-automatically once they terminate (at least, they won't
accumulate without bound).

> Also, does Popen.returncode contain only the child's exit code or is
> does it also contain signal info like the return of os.wait()?

If the child terminated normally, .returncode will be non-negative, and
contains the "exit status", i.e. the value returned from main() or passed
to exit() etc.

If the child terminated on a signal, .returncode will be negative, and
contains the negation of the signal number.

If the child is still running (or is a zombie), .returncode will be None.

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


Re: what happens to Popen()'s parent-side file descriptors?

2010-10-13 Thread Seebs
On 2010-10-13, Roger Davis  wrote:
> Hi, I am new to this group, please forgive me if this is a repeat
> question. I am a new Python programmer but experienced in C/Unix. I am
> converting a shell script to Python which essentially loops
> infinitely, each pass through the loop running commands like
>
>   set output = `cat this | grep that | whatever ...`
>
> My understanding is that this functionality is best coded via
> subprocess.Popen().

Actually...

It's probably BEST coded, when possible, by doing the work internally.

So:
thisfile = open('this')
lines = []
for line in thisfile:
if re.match('that', line):
lines.append(line)
whatever(lines)

... or something like that.

(Which you can write as a oneliner list comprehension, but I don't know
that it's got clarity)

Basically, don't use popen() unless the thing you'd be calling is something
hard enough to do that you really, really, want to run an external program
for it.  This is not a shell script; it is not just there to be glue
around other programs.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Whining about "struct"

2010-10-13 Thread Terry Reedy

On 10/14/2010 12:30 AM, Tim Roberts wrote:

I have a bad memory.  I admit it.  Because of that, the Python "help"
system is invaluable to me.  Up through Python 2.5, I could get a quick
reference to the format specifiers for the struct module via
   import struct; help(struct)

I used that a LOT.

But in Python 2.6, the struct module moved from Python code to C code, and
that helpful help string was removed.

Is that still gone in Python 3.1?  What are the chances of reinstating that
helpful chart?


With 3.1, help(struct) includes the following:

The optional first format char indicates byte order, size and 
alignment:

  @: native order, size & alignment (default)
  =: native order, std. size & alignment
  <: little-endian, std. size & alignment
  >: big-endian, std. size & alignment
  !: same as >

The remaining chars indicate types of args and must match exactly;
these can be preceded by a decimal repeat count:
  x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;
  ?: _Bool (requires C99; if not available, char is used instead)
  h:short; H:unsigned short; i:int; I:unsigned int;
  l:long; L:unsigned long; f:float; d:double.
Special cases (preceding decimal count indicates length):
  s:string (array of char); p: pascal string (with count byte).
Special case (only available in native format):
  P:an integer type that is wide enough to hold a pointer.
Special case (not in native mode unless 'long long' in platform C):
  q:long long; Q:unsigned long long
Whitespace between formats is ignored.

If this does not cover what you were referring to, open an issue with 
*specific* suggestion for addition.


--
Terry Jan Reedy

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


Whining about "struct"

2010-10-13 Thread Tim Roberts
I have a bad memory.  I admit it.  Because of that, the Python "help"
system is invaluable to me.  Up through Python 2.5, I could get a quick
reference to the format specifiers for the struct module via
  import struct; help(struct)

I used that a LOT.

But in Python 2.6, the struct module moved from Python code to C code, and
that helpful help string was removed.

Is that still gone in Python 3.1?  What are the chances of reinstating that
helpful chart?
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing" [OT]

2010-10-13 Thread Paul Rubin
Steve Howell  writes:
> And yet nobody can recite this equally interesting ratio to thousands
> of digits:
>
>  0.2141693770623265...

That is 1/F1 where F1 is the first Feigenbaum constant a/k/a delta.
The mathworld article is pretty good:

  http://mathworld.wolfram.com/FeigenbaumConstant.html

It mentions that both constants were calculated to about 1000 digits in
1999.  I don't know how that was done, but presumably they could be
calculated to more digits these days if someone felt like it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to add patch

2010-10-13 Thread Steve Howell
On Oct 13, 12:36 pm, jimgardener  wrote:
> hi
> I have some demo python  code hosted on a public host that uses
> subversion..and I want to modify one of the files using a patch file
> handed to me by another person..How do I do this?Generally I checkout
> the code and make the change and then commit again..I have never done
> through patch..Can somebody tell me how to do this?
> thanks

Obviously "man patch" is where you should start, but like many Unix
man pages, the man page for "patch" is surprisingly obtuse for such an
elegant and useful program.

(BTW we are slightly off-topic for Python, but I am sympathetic to
your basic problem.)

The "patch" program is pretty smart about doing the correct thing once
you grok its options, but if you are concerned about doing the wrong
thing, I recommend you simply play around with it with some toy
examples.

Hopefully the example below demonstrates the basic premise behind
"patch," which I think you already understand.  The bells and whistles
are mostly about "patch" being able to recognize that a diff applies
to a specific file.  Again, I would take a few minutes to experiment
with a couple small files and diffs that you generate yourself before
applying other people's patches.

I haven't used "patch" a ton myself, so I'm no expert, but it's
definitely a cool program, so it's worth learning.


  $ echo foo > foo
  $ cp foo foobetter
  $ echo better >> foobetter
  $ cat foo
  foo
  $ cat foobetter
  foo
  better
  $ diff foo foobetter
  1a2
  > better
  $ diff foo foobetter > make_foo_better
  $ patch foo make_foo_better
  patching file foo
  $ cat foo
  foo
  better
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Eclipse/PyDev - BOM Lexical Error

2010-10-13 Thread Lawrence D'Oliveiro
In message , Ethan 
Furman wrote:

> Lawrence D'Oliveiro wrote:
>
>> In message , Ethan
>> Furman wrote:
>> 
>>>Lawrence D'Oliveiro wrote:
>>>
In message , Ethan
Furman wrote:

>>>MS treats those first three bytes as a flag -- if they equal the BOM, MS
>>>treats it as UTF-8, if they equal anything else, MS does not treat it as
>>>UTF-8.
>> 
>> So what does it treat it as? You previously gave examples of flag values
>> for dBase III. What are the flag values for Windows-1252, versus, say,
>> ISO-8859-15?
> 
> I am not aware of any other flag values for text files besides the BOM
> for UTF-8.

Then how can you say “MS treats those first three bytes as a flag”, then?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing" [OT]

2010-10-13 Thread Steve Howell
On Oct 13, 12:31 pm, Steven D'Aprano  wrote:
0.2141693770623265
>
> Perhaps this will help illustrate what I'm talking about... the
> mathematician Mitchell Feigenbaum discovered in 1975 that, for a large
> class of chaotic systems, the ratio of each bifurcation interval to the
> next approached a constant:
>
> δ = 4.66920160910299067185320382...
>

And yet nobody can recite this equally interesting ratio to thousands
of digits:

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


Re: Help needed - To get path of a directory

2010-10-13 Thread Lawrence D'Oliveiro
In message , Kingsley 
Turner wrote:

> I don't know how to enumerate all your windows device letters.

There are only 26 of them, so you can try them all, right?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 249 (database api) -- executemany() with iterable?

2010-10-13 Thread Lawrence D'Oliveiro
In message <4cb5e659$0$1650$742ec...@news.sonic.net>, John Nagle wrote:

>  Also note that there are some issues with doing a huge volume of
> updates in one MySQL InnoDB transaction.  The system has to keep the
> data needed to undo the updates, and there's a limit on the amount of
> pending transaction history that can be stored.

How does “load data” avoid this? Is that not a transaction too?

>  It's common to load data into a new, empty table, then, once
> the reload has succeeded, do a RENAME like CURRENT->OLD, NEW->CURRENT.
> Rename of multiple databases is atomic and interlocked with other
> operations, so you can replace an entire table on a live server.

Is that to avoid impacting searches on the existing data while loading the 
new records?

Seems to me this isn’t going to help, since both old and new tables are on 
the same disk, after all. And it’s the disk access that’s the bottleneck.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 249 (database api) -- executemany() with iterable?

2010-10-13 Thread Lawrence D'Oliveiro
In message
, Steve 
Howell wrote:

> Bulk-load strategies usually solve one or more of these problems:
> 
>  network latency

That’s not an issue. This is a bulk operation, after all.

>  index maintenance during the upload

There are usually options to temporarily turn this off.

>  parsing of the SQL

Not usually a problem, as far as I can tell.

>  reallocating storage

You mean for thr SQL? Again, not usually a problem, as far as I can tell.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to add patch

2010-10-13 Thread Lawrence D'Oliveiro
In message , Diez B. Roggisch wrote:

> My first attempt would be
> 
>   cd my_project
>   patch -p0 < the.patch
> 
> But it might not work, depending on how the patch was created.

If the OP can post some initial part of the patch (probably the first dozen 
lines should be ample), we can get a better idea of how to proceed.

Most patches follow the format of output from diff -u or diff -c; I think 
the former is slightly more common.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing" [OT]

2010-10-13 Thread Steven D'Aprano
On Wed, 13 Oct 2010 21:52:54 +0100, Arnaud Delobelle wrote:

> Steven D'Aprano  writes:
> 
>> On Wed, 13 Oct 2010 16:17:19 +0200, Antoon Pardon wrote:
>>
>>> On Wed, Oct 13, 2010 at 01:20:30PM +, Steven D'Aprano wrote:
 On Tue, 12 Oct 2010 22:13:26 -0700, RG wrote:
 
 >> The formula: circumference = 2 x pi x radius is taught in primary
 >> schools, yet it's actually a very difficult formula to prove!
 > 
 > What's to prove?  That's the definition of pi.
 
 Incorrect -- it's not necessarily so that the ratio of the
 circumference to the radius of a circle is always the same number. It
 could have turned out that different circles had different ratios.
>>> 
>>> If that is your concern, you should have reacted to the previous
>>> poster since in that case his equation couldn't be proven either.
>>
>> "Very difficult to prove" != "cannot be proven".
> 
> But in another section of your previous post you argued that it cannot
> be proven as it doesn't hold in projective or hyperbolic geometry.

But in Euclidean geometry it *can* be proven. What I was pointing out 
that it can't be taken for granted. Under non-Euclidean geometries, it 
can't be proven because it isn't necessarily true; under Euclidean 
geometry, there was a time when people didn't know whether or not the 
ratio of circumference to radius was or wasn't a constant, and proving 
that it is a constant is non-trivial.


> But you were claiming that the proposition "C = 2πr is the definition of
> π" was false.

Well, what is the definition of pi? Is it:

the ratio of the circumference of a circle to twice its radius;
the ratio of the area of a circle to the square of its radius;
4*arctan(1);
the complex logarithm of -1 divided by the negative of the complex square 
root of -1; 
any one of many, many other formulae.


None of these formulae are intuitively correct; the formula C = 2πr isn't 
a definition in the same sense that 1+1=2 defines 2. The point that I was 
trying to get across is that, until somebody proved the formula, it 
wasn't clear that the ratio was constant.


> Also, it is very intuitive to think that the ratio of the circumference
> of a circle to it radius is constant:
> 
> Given two circles with radii r1 and r2, circumferences C1 and C2, one is
> obviously the scaled-up version of the other, therefore the ratio of
> their circumferences is equal to the ratio of their radii:

That's exactly the sort of thing Peter Nilsson was talking about when he 
said "Most attempts by students collapse because they assume the formula 
in advance". It might be "obvious" to you that the two circles are merely 
scaled up versions of each other, but that is equivalent to assuming that 
the ratio of the circumference to radius is a constant. Well, yes, it is 
(at least under Euclidean geometry), but assuming it is a constant 
doesn't allow you to prove it is a constant -- that's circular reasoning, 
if you excuse the pun.



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


Re: Scheme as a virtual machine?

2010-10-13 Thread Ertugrul Söylemez
namekuseijin  wrote:

> On 13 out, 21:01, Ertugrul Söylemez  wrote:
> > What exactly is "friggin' huge" and "complex" about Haskell, and
> > what's this stuff about a "very own monolithic gcc"?  Haskell isn't
> > a lot more complex than Scheme.  In fact, Python is much more
> > complex.  Reduced to bare metal (i.e. leaving out syntactic sugar)
> > Haskell is one of the simplest languages.
>
> yeah, like scheme, it's essentially evaluation of lambda expressions.
> Unlike scheme, it's got a huge plethora of syntatic sugar as big and
> complex as a full numeric tower.  Such is the fear to avoid
> parentheses at all costs that they allowed lots of perlisms into the
> language ($ . `` >>= etc) plus python's significant whitespace.  So,
> in practice, even though at the core it's as simple as scheme's core,
> at practice it's so mindnumbing complex that only one implementation
> is worth of note.

That's nonsense.  There is only little syntactic sugar in Haskell.  And
all of them make your life considerably easier.  You get multiple
function clauses instead of an explicit 'case', which makes your
functions much more readable.  You get 'do'-notation for monads, which
makes (many) monadic computations much easier to read.  And you get
support for infix functions with a very clean syntax.  That's about all
the syntactic features you use in general.

BTW, you mentioned symbols ('$', '.' and '>>='), which are not syntactic
sugar at all.  They are just normal functions, for which it makes sense
to be infix.  The fact that you sold them as syntactic sugar or
"perlisms" proves that you have no idea about the language, so stop
crying.  Also Python-style significant whitespace is strictly optional.
It's nice though.  After all most Haskell programmers prefer it.

Further Scheme lacks these:
* A powerful type system,
* lazy evaluation,
* non-strict semantics,
* easy, straightforward to use concurrency,
* easy, straightforward to use parallelism and
* much more.

I'm not saying Scheme is a bad language (I recommend it to beginners),
but it doesn't beat Haskell in any way, at least for me, and in contrast
to you I /can/ make a comparison, because I have used both productively.


> And one as complex and scary beast as gcc... that's the cost of a very
> irregular syntax...

What also proves that you have no idea is the fact that there is no
Haskell compiler called 'gcc'.  That's the GNU C compiler.  There is the
Glasgow Haskell Compiler, GHC, and it's by far not the only one.  It's
just the one most people use, and there is such a compiler for all
languages.  Many Schemers use Racket, for example.

You never used Haskell seriously, so stop complaining.


Greets,
Ertugrul


-- 
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://ertes.de/

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


Re: Help with sets

2010-10-13 Thread Steve Howell
On Oct 13, 7:25 pm, Lawrence D'Oliveiro  wrote:
> In message
> , Steve
>
> Howell wrote:
> > I guess a lot depends on how you define "symmetry."  Is your
> > definition of "symmetry" equivalent to your definition of
> > "orthogonality"?
>
> No idea. It’s just that the example being discussed in this thread seemed to
> come under the old term “orthogonality”, so I wondered why a different term
> was being used.
>
> So far no-one has come up with a good excuse for using a different term.

Ask the authors of PEP 234 why they use the term symmetry:

http://www.python.org/dev/peps/pep-0234/

That was the original context of my comment.  The term "symmetry" gets
used a couple times in that PEP, and I think we're in violent
agreement that the concept of "symmetry" is wishy-washy at best.

Here is just one example from the PEP:

  The symmetry between "if x in y" and "for x in y"
  suggests that it should iterate over keys.  This symmetry has
been
  observed by many independently and has even been used to
"explain"
  one using the other.

I think I'm just making the same observation as you coming from a
different angle.  Why talk about "symmetry" when it's such a tricky
balance?



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


Re: Help needed - To get path of a directory

2010-10-13 Thread Kingsley Turner

 On 13/10/10 15:26, Bishwarup Banerjee wrote:

I want to get the absolute path of the Directory I pass explicitly. Like
functionName("\abcd").
I should pass the name of the directory and the function should search for 
it in the Hard drives and return me the full path of location on the 
drive. I tried using os.path, but didn't succeed.


One way to achieve this is to fetch a recursive directory list for all 
drives, and then search for your directory_name.endswith("abcd") in each 
list.  But what would you do with multiple occurrences ?


Here's a function to fetch a recursive directory list:

import os.path

def getRecursiveDirList(path):
dir_list = []
if (os.path.isdir(path)):
try:
files = os.listdir(path)
files.sort()
except:
files = []
for x in files:
full_path = os.path.join(path, x)
if (os.path.isdir(full_path)):
dir_list.append(os.path.join(full_path,''))
for full_path in getRecursiveDirList(full_path):
dir_list.append(full_path)
return dir_list

I've only tested this function under Linux.
It's also probably sub-optimal.

I don't know how to enumerate all your windows device letters.

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


Re: Help with sets

2010-10-13 Thread Lawrence D'Oliveiro
In message
, Steve 
Howell wrote:

> I guess a lot depends on how you define "symmetry."  Is your
> definition of "symmetry" equivalent to your definition of
> "orthogonality"?

No idea. It’s just that the example being discussed in this thread seemed to 
come under the old term “orthogonality”, so I wondered why a different term 
was being used.

So far no-one has come up with a good excuse for using a different term.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Scheme as a virtual machine?

2010-10-13 Thread namekuseijin
On 13 out, 19:41, p...@informatimago.com (Pascal J. Bourguignon)
wrote:
> namekuseijin  writes:
> > On 11 out, 08:49, Oleg  Parashchenko  wrote:
> >> Hello,
>
> >> I'd like to try the idea that Scheme can be considered as a new
> >> portable assembler. We could code something in Scheme and then compile
> >> it to PHP or Python or Java or whatever.
>
> >> Any suggestions and pointers to existing and related work are welcome.
> >> Thanks!
>
> >> My current approach is to take an existing Scheme implementation and
> >> hijack into its backend. At this moment Scheme code is converted to
> >> some representation with a minimal set of bytecodes, and it should be
> >> quite easy to compile this representation to a target language. After
> >> some research, the main candidates are Gambit, Chicken and CPSCM:
>
> >>http://uucode.com/blog/2010/09/28/r5rs-scheme-as-a-virtual-machine-i/...
>
> >> If there is an interest in this work, I could publish progress
> >> reports.
>
> >> --
> >> Oleg Parashchenko  o...@http://uucode.com/http://uucode.com/blog/ XML, 
> >> TeX, Python, Mac, Chess
>
> > it may be assembler, too bad scheme libs are scattered around written
> > in far too many different flavors of assembler...
>
> > It warms my heart though to realize that Scheme's usual small size and
> > footprint has allowed for many quality implementations targetting many
> > different backends, be it x86 assembly, C, javascript or .NET.  Take
> > python and you have a slow c bytecode interpreter and a slow
> > bytecode .NET compiler.  Take haskell and its so friggin' huge and
> > complex that its got its very own scary monolithic gcc.  When you
> > think of it, Scheme is the one true high-level language with many
> > quality perfomant backends -- CL has a few scary compilers for native
> > code, but not one to java,
>
> Yep, it only has two for java.

I hope those are not Clojure and Qi... :p
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Scheme as a virtual machine?

2010-10-13 Thread namekuseijin
On 13 out, 21:01, Ertugrul Söylemez  wrote:
> What exactly is "friggin' huge" and "complex" about Haskell, and what's
> this stuff about a "very own monolithic gcc"?  Haskell isn't a lot more
> complex than Scheme.  In fact, Python is much more complex.  Reduced to
> bare metal (i.e. leaving out syntactic sugar) Haskell is one of the
> simplest languages.

yeah, like scheme, it's essentially evaluation of lambda expressions.
Unlike scheme, it's got a huge plethora of syntatic sugar as big and
complex as a full numeric tower.  Such is the fear to avoid
parentheses at all costs that they allowed lots of perlisms into the
language ($ . `` >>= etc) plus python's significant whitespace.  So,
in practice, even though at the core it's as simple as scheme's core,
at practice it's so mindnumbing complex that only one implementation
is worth of note.  And one as complex and scary beast as gcc... that's
the cost of a very irregular syntax...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with sets

2010-10-13 Thread Steve Howell
On Oct 13, 4:27 pm, Lawrence D'Oliveiro  wrote:
> In message
> <57a322df-8e42-4da5-af96-0c21c5733...@b14g2000pro.googlegroups.com>, Steve
>
> Howell wrote:
> > Lawrence, I was actually talking about symmetry, not orthogonality.
>
> So what’s the difference?

I don't think there's a big difference between the two--you snipped
away my comment about them often going hand in hand, so I will repeat
it here that they do often go hand in hand.

I guess a lot depends on how you define "symmetry."  Is your
definition of "symmetry" equivalent to your definition of
"orthogonality"?

I don't have a precise definition of "symmetry" myself, I will admit.
Perhaps for lack of a better word, I throw around the term "symmetry"
for situations where analogous constructs get used in slightly
different contexts.  The example in this discussion is the "in"
keyword.  You can use "in" for strings, sets, lists, and dictionaries,
which in and of itself is an example of "symmetry" in my mind.
Another example is the relationship of the "+" operator to the "*"
operator.  With numbers "*" connotes repeated use of "+", as it does
with strings, even though the underlying operations for "+" are not
exactly equivalent.  String star-ification is repeated concatenation,
whereas integer star-ification is repeated addition, but since
concatenation and addition are both represented by "+", it creates
some sort of symmetry to have "*" as the string-concatenation-
repetition operator, even if it is not something folks commonly
encounter outside of programming languages.



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


Re: Using csv.DictReader with \r\n in the middle of fields

2010-10-13 Thread Tim Chase

On 10/13/10 11:33, Dennis Lee Bieber wrote:

While I've not tested it, my understanding of the documentation
indicates that the reader /can/ handle multi-line fields IF QUOTED...
(you may still have to strip the terminator out of the description data
after it has been loaded).

That is:

Some Title~Subtitle~Episode~"A description with
an embedded new line terminator"~Date

should be properly parsed.


I believe this was fixed in 2.5  The following worked in 2.5 but 
2.4 rejected it:


  # saved as testr.py
  from cStringIO import StringIO
  from csv import DictReader

  data = StringIO(
'one,"two two",three\n'
'"1a\r1b","2a\n2b","3a\r\n3b"\n'
'"1x\r1y","2x\n2y","3x\r\n3y"\n'
)

  data.reset()
  dr = DictReader(data)
  for row in dr:
for k,v in row.iteritems():
  print '%r ==> %r' % (k,v)


t...@rubbish:~/tmp$ python2.5 testr.py
'two two' ==> '2a\n2b'
'three' ==> '3a\r\n3b'
'one' ==> '1a\r1b'
'two two' ==> '2x\n2y'
'three' ==> '3x\r\n3y'
'one' ==> '1x\r1y'
t...@rubbish:~/tmp$ python2.4 testr.py
Traceback (most recent call last):
  File "testr.py", line 12, in ?
for row in dr:
  File "/usr/lib/python2.4/csv.py", line 109, in next
row = self.reader.next()
_csv.Error: newline inside string



-tkc



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


Re: My first Python program

2010-10-13 Thread Ben Finney
Christian Heimes  writes:
> msg = ("WARNING: "
>"Pants on fire")

Ick. When the name changes to something with a different length, you'll
need to change every continuation line. A name change is easily
predicted and quite likely to happen often in one's code, so why invite
more work when it happens?

-- 
 \   “Let others praise ancient times; I am glad I was born in |
  `\  these.” —Ovid (43 BCE–18 CE) |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Ben Finney
"Jonas H."  writes:

> On 10/13/2010 11:26 PM, Seebs wrote:
> >>  stderr.write(
> >>  "WARNING:"
> >>  " Pants on fire\n")
> >
> > Hmm.  So I just indent stuff inside the ()s or whatever?  I can work with
> > that.
>
> I think common is
>
> stderr.write("WARNING: ",
>  "Pants on fire")

Which makes it unwieldy if the first line changes length. Why bother
keeping lots of lines aligned every time the first line changes length?
Just use a single level of indentation for continuation lines, and the
first line can change length as much as it needs to without requiring
editing every continuation line.

> or
>
> stderr.write(
> "WARNING: "
> "Pants on fire"
> )

Better, and it allows more lines to be added between the parens without
messing around with any other lines.

In cases where the lines aren't conceptually a fungible list, though,
I'd just put the closing paren on the end of the last useful line. As a
Python programmer, we're committed to reading changes in indentation as
terminating a group of lines.

> If you haven't got braces around an expression and you want it to be
> multi-line, you need a '\' at the end of each line, just like C
> macros:
>
> msg = "WARNING: " \
>   "Pants on fire"
>
> Though that is not commonly used afaik.

I'd go so far as to call it an anti-idiom. Better to add parens for
grouping lines as needed.

long_identifier_to_demonstrate_my_point_again = (
"WARNING:"
" Pants on fire\n"
)

-- 
 \ “Men never do evil so completely and cheerfully as when they do |
  `\it from religious conviction.” —Blaise Pascal (1623–1662), |
_o__)   Pensées, #894. |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Ben Finney
Seebs  writes:

> On 2010-10-13, Ben Finney  wrote:
> > Python borrows from C in that consecutive literal strings are
> > concatenated in the bytecode::
> >
> > stderr.write(
> > "WARNING:"
> > " Pants on fire\n")
>
> Hmm. So I just indent stuff inside the ()s or whatever? I can work
> with that.

Yes. More generally, within any “parenthesising” operators, like parens,
brackets, or braces. Anything which allows Python's parser to read the
next line as a continuation.

You'll often find code written in a different style:

long_line_to_demonstrate_my_point.write("WARNING:"
" Pants on fire\n")

but I find that silly and unwieldy, especially when the early parts of
the first line change length.

-- 
 \“Of course, everybody says they're for peace. Hitler was for |
  `\  peace. Everybody is for peace. The question is: what kind of |
_o__)peace?” —Noam Chomsky, 1984-05-14 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Scheme as a virtual machine?

2010-10-13 Thread Ertugrul Söylemez
namekuseijin  wrote:

> Take haskell and its so friggin' huge and complex that its got its
> very own scary monolithic gcc.  When you think of it, Scheme is the
> one true high-level language with many quality perfomant backends --
> CL has a few scary compilers for native code, but not one to java,
> .NET or javascript that I know of...

What exactly is "friggin' huge" and "complex" about Haskell, and what's
this stuff about a "very own monolithic gcc"?  Haskell isn't a lot more
complex than Scheme.  In fact, Python is much more complex.  Reduced to
bare metal (i.e. leaving out syntactic sugar) Haskell is one of the
simplest languages.  Since recent versions of GHC produced code is also
very small.

The only downside of Haskell is that the popular VMs like JVM and .NET
are not supported.  But that's also because their type systems are very
incompatible.  Haskell can express types, which they can't express.  The
only thing I could imagine to bring the worlds together is another
foreign function interface, a JFFI and a VESFFI.

In my opinion Scheme is not the "one true high-level language".  For me
personally Haskell gets much closer to this.  For others it's probably
Common Lisp or something else.


Greets,
Ertugrul


-- 
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://ertes.de/

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


Re: Compiling as 32bit on MacOSX

2010-10-13 Thread Ned Deily
In article <8hmpchfsh...@mid.individual.net>,
 Gregory Ewing  wrote:
> Ned Deily wrote: 
> > You'll also need to specify the appropriate SDK using Apple's gcc 
> > -sysroot option.
> Are you sure? I'm not asking for ppc + i386, I'm
> asking for i386 + x86_64. I can get either of these
> individually without switching SDKs.

Well, you'd need it if you want backward compatibility (with an older 
ABI) but, no, you wouldn't need -sysroot just to produce i386 and x86_64 
on a 64-bit capable machine running 10.6.

Getting back to your previous post: "But I can't seem to get it to work 
-- it just uses the last architecture specified."   Perhaps you're 
calling ld(1) directly?  To link multiple-arch executables (etc), the 
Apple gcc driver does the dirty work of calling ld multiple times and 
lipo-ing the results.  See the Apple ld(1) man page.

-- 
 Ned Deily,
 n...@acm.org

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


Re: Searching in str backwards

2010-10-13 Thread Chris Kaynor
Look up the string's rfind method.

Chris


On Wed, Oct 13, 2010 at 4:28 PM, Pratik Khemka wrote:

>  I  want to search for a symbol in a string backwards..
> For eg:
>
> *line = "my/cat/dog/baby"*
> **
> *line.find('/')* *# but from the back...*
>
> The reason I want to do this is because I want to print the last part of
> the string after the '/' . And I do not know how long the string might be or
> how many '/' it might have . I just want to print whatever is there after
> the last '/'.
>
> Thanks,
> Pratik
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Searching in str backwards

2010-10-13 Thread Emile van Sebille

On 10/13/2010 4:28 PM Pratik Khemka said...

line = "my/cat/dog/baby"


Introspection is your friend

>>> line = "my/cat/dog/baby"
>>> dir(line)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', 
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem_
_', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', 
'__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__
', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', 
'__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclass
hook__', '_formatter_field_name_split', '_formatter_parser', 
'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expan
dtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 
'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lo
wer', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 
'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'starts

with', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> help(line.rfind)
Help on built-in function rfind:

rfind(...)
S.rfind(sub [,start [,end]]) -> int

Return the highest index in S where substring sub is found,
such that sub is contained within s[start:end].  Optional
arguments start and end are interpreted as in slice notation.

Return -1 on failure.

>>>


Emile












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


Re: Help with sets

2010-10-13 Thread Lawrence D'Oliveiro
In message
<57a322df-8e42-4da5-af96-0c21c5733...@b14g2000pro.googlegroups.com>, Steve 
Howell wrote:

> Lawrence, I was actually talking about symmetry, not orthogonality.

So what’s the difference?
-- 
http://mail.python.org/mailman/listinfo/python-list


Searching in str backwards

2010-10-13 Thread Pratik Khemka

I  want to search for a symbol in a string backwards..
For eg:
 
line = "my/cat/dog/baby"
 
line.find('/') # but from the back...
 
The reason I want to do this is because I want to print the last part of the 
string after the '/' . And I do not know how long the string might be or how 
many '/' it might have . I just want to print whatever is there after the last 
'/'.
 
Thanks,
Pratik-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to add patch

2010-10-13 Thread Diez B. Roggisch
jimgardener  writes:

> hi
> I have some demo python  code hosted on a public host that uses
> subversion..and I want to modify one of the files using a patch file
> handed to me by another person..How do I do this?Generally I checkout
> the code and make the change and then commit again..I have never done
> through patch..Can somebody tell me how to do this?

This is not really python specific. Which is not to say that you are
wrong here asking, but there are a bazillion of sources out there to
help you. Google. Read man-pages. Try it out.

My first attempt would be

  cd my_project
  patch -p0 < the.patch

But it might not work, depending on how the patch was created.

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


Re: Difficulty in easy_install

2010-10-13 Thread Diez B. Roggisch
John Nagle  writes:

> On 10/11/2010 1:45 AM, sankalp srivastava wrote:
>>
>>   I am having difficulty in easy_installing
>> I use a proxy server and strange errors , like it can't fetch the
>> package is showing up .
>> the package is pyspeech ...please help me :(
>>
>> I don't know if the proxy server is causing the problems , in linux i
>> would have import http-proxy in .bashrc
>> but am not a windows expert
>> can anyone help me plz
>
> That's about typical.  "easy_install" isn't "easy".  It has some
> built-in assumptions about where various files are stored, and if
> the installation doesn't match them, installs fail with obscure
> error messages.
>

I've been using easy_install and eggs for years, and at least since the
advent ogf virtualenve they haven't given me any troubles whatsoever. 

So I guess it's an OSI layer 8 issue.

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


Re: what happens to Popen()'s parent-side file descriptors?

2010-10-13 Thread Mike Kent
You might want to check out the Python 2.7 'pipes' standard library
module: http://docs.python.org/library/pipes.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Scheme as a virtual machine?

2010-10-13 Thread Pascal J. Bourguignon
namekuseijin  writes:

> On 11 out, 08:49, Oleg  Parashchenko  wrote:
>> Hello,
>>
>> I'd like to try the idea that Scheme can be considered as a new
>> portable assembler. We could code something in Scheme and then compile
>> it to PHP or Python or Java or whatever.
>>
>> Any suggestions and pointers to existing and related work are welcome.
>> Thanks!
>>
>> My current approach is to take an existing Scheme implementation and
>> hijack into its backend. At this moment Scheme code is converted to
>> some representation with a minimal set of bytecodes, and it should be
>> quite easy to compile this representation to a target language. After
>> some research, the main candidates are Gambit, Chicken and CPSCM:
>>
>> http://uucode.com/blog/2010/09/28/r5rs-scheme-as-a-virtual-machine-i/http://uucode.com/blog/2010/09/28/r5rs-scheme-as-a-virtual-machine-ii/
>>
>> If there is an interest in this work, I could publish progress
>> reports.
>>
>> --
>> Oleg Parashchenko  o...@http://uucode.com/http://uucode.com/blog/ XML, TeX, 
>> Python, Mac, Chess
>
> it may be assembler, too bad scheme libs are scattered around written
> in far too many different flavors of assembler...
>
> It warms my heart though to realize that Scheme's usual small size and
> footprint has allowed for many quality implementations targetting many
> different backends, be it x86 assembly, C, javascript or .NET.  Take
> python and you have a slow c bytecode interpreter and a slow
> bytecode .NET compiler.  Take haskell and its so friggin' huge and
> complex that its got its very own scary monolithic gcc.  When you
> think of it, Scheme is the one true high-level language with many
> quality perfomant backends -- CL has a few scary compilers for native
> code, but not one to java,

Yep, it only has two for java.


>  .NET or javascript that I know of...

-- 
__Pascal Bourguignon__ http://www.informatimago.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Christian Heimes
Am 14.10.2010 00:00, schrieb Jonas H.:
> If you haven't got braces around an expression and you want it to be 
> multi-line, you need a '\' at the end of each line, just like C macros:
> 
>  msg = "WARNING: " \
>"Pants on fire"

or

msg = ("WARNING: "
   "Pants on fire")

Christian

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


Re: Compiling as 32bit on MacOSX

2010-10-13 Thread Gregory Ewing

Ned Deily wrote:

You'll also need to specify the appropriate SDK using Apple's gcc 
-sysroot option.


Are you sure? I'm not asking for ppc + i386, I'm
asking for i386 + x86_64. I can get either of these
individually without switching SDKs.

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


Re: Hyperlink to a file using python

2010-10-13 Thread Chris Rebert
>> To: python-list@python.org
>> From: em...@fenx.com
>> Subject: Re: Hyperlink to a file using python
>> Date: Wed, 13 Oct 2010 14:19:36 -0700
>>
>> On 10/13/2010 1:57 PM Pratik Khemka said...
>> >
>> > I want to create a hyperlink in my excel sheet using python such that
>> > when you click on that link (which is a file name (html file)), the file
>> > automatically opens. This file is present in the same folder in which the
>> > python code file is present.
>> >
>> > I am using xlwt module
>> >
>> > link= 'abcd.html'
>> > sheet.write(x, y, link, format_style)
>>
>> Hmmm... my excel does that automagically when I
>> type "http://xx.yy.zz/word.html into a cell.
>>
>> What happens when you use "http://a.b.c/abcd.html";?

On Wed, Oct 13, 2010 at 3:13 PM, Pratik Khemka  wrote:
> This file is present on my hardrive..This file is present in the same folder
> in which the python code file is present...so http: wont work..

Have you tried a file:/// URI?
http://en.wikipedia.org/wiki/File_URI_scheme

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


RE: Hyperlink to a file using python

2010-10-13 Thread Pratik Khemka

This file is present on my hardrive..This file is present in the same folder in 
which the python code file is present...so http: wont work..

 
> To: python-list@python.org
> From: em...@fenx.com
> Subject: Re: Hyperlink to a file using python
> Date: Wed, 13 Oct 2010 14:19:36 -0700
> 
> On 10/13/2010 1:57 PM Pratik Khemka said...
> >
> > I want to create a hyperlink in my excel sheet using python such that when 
> > you click on that link (which is a file name (html file)), the file 
> > automatically opens. This file is present in the same folder in which the 
> > python code file is present.
> >
> > I am using xlwt module
> >
> >
> >
> >
> >
> > link= 'abcd.html'
> > sheet.write(x, y, link, format_style)
> 
> 
> Hmmm... my excel does that automagically when I
> type "http://xx.yy.zz/word.html into a cell.
> 
> What happens when you use "http://a.b.c/abcd.html";?
> 
> Emile
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
  -- 
http://mail.python.org/mailman/listinfo/python-list


what happens to Popen()'s parent-side file descriptors?

2010-10-13 Thread Roger Davis
Hi, I am new to this group, please forgive me if this is a repeat
question. I am a new Python programmer but experienced in C/Unix. I am
converting a shell script to Python which essentially loops
infinitely, each pass through the loop running commands like

  set output = `cat this | grep that | whatever ...`

My understanding is that this functionality is best coded via
subprocess.Popen(). I need to read output from these spawned children
via a pipe from their stdout, hence something like

 p= subprocess.Popen(args, stdout=subprocess.PIPE)

This means that somewhere a pipe file descriptor is opened on the
parent side to read from the child's stdout. When, if ever, is that
descriptor closed? Per-process FDs are limited and I am looping
infinitely so I need to be very careful about not running out of them.
Are there any other FDs related to this operation that also need to be
closed?

Testing with the interpreter (2.6, MacOSX) it appears that p.stdout is
being closed somehow by someone other than me:

import subprocess
args= ["echo", "This is a mystery!"]
i= 0
while True:
p= subprocess.Popen(args, stdout=subprocess.PIPE)
for line in p.stdout:
print "[%5d] %s" % (i, line.strip())
i+= 1

The above code closes nothing but appears to run indefinitely without
running the parent out of FDs. WTF is going on here?

Popen.communicate() similarly appears to be closing the parent's pipe
FDs, although that seems more understandable as it appears to be
designed to encapsulate a lot of cleanup activity. In either case
(code snippet above or communicate() an attempt to manually close
p,stdout goes as follows:

>>> print p.stdout.close()
None

Attempts to close anything else fail spectacularly as one might
expect:

>>> print p.stdin.close()
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'NoneType' object has no attribute 'close'

Can anyone explain the treatment of the pipe FDs opened in the parent
by Popen() to me or point me to some documentation? The python.org
docs say absolutely nothing about this as far as I can tell, a glaring
deficiency IMO (hint to all you underworked volunteer developers ;-
> ).

Also, does Popen.returncode contain only the child's exit code or is
does it also contain signal info like the return of os.wait()?
Documentation on this is also unclear to me.

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


Re: My first Python program

2010-10-13 Thread Jonas H.

On 10/13/2010 11:26 PM, Seebs wrote:

 stderr.write(
 "WARNING:"
 " Pants on fire\n")


Hmm.  So I just indent stuff inside the ()s or whatever?  I can work with
that.


I think common is

stderr.write("WARNING: ",
 "Pants on fire")

or

stderr.write(
"WARNING: "
"Pants on fire"
)

If you haven't got braces around an expression and you want it to be 
multi-line, you need a '\' at the end of each line, just like C macros:


msg = "WARNING: " \
  "Pants on fire"

Though that is not commonly used afaik.
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-13 Thread Pascal J. Bourguignon
Steven D'Aprano  writes:

> On Wed, 13 Oct 2010 17:28:42 +0200, Pascal J. Bourguignon wrote:
>
 But what exactly *is* this number? Is it 0.25, 1.57 or 90?
>>>
>>> That's the wrong question. It's like asking, what exactly "is" the
>>> number twenty-one -- is it "one and twenty", or 21, or 0x15, or 0o25,
>>> or 21.0, or 20.999... recurring, or 63/3, or XXI, or 0b10101, or "vinet
>>> et un", or any one of many other representations.
>> 
>> This is not the wrong question.  These are two different things.
>
> Which is why I said it was LIKE asking the second.
>
>
>> In the case of 0.25, 1.57 or 90, you have elements of the same set of
>> real numbers ℝ, which are used to represent the same entity, which IS
>> NOT a number, but an angle.  Angles are not in the ℝ set, but in ℝ/2π,
>> which is an entirely different set with entirely different properties.
>
> It's quite standard to discuss (say) sin(theta) where theta is an element 
> of ℝ. The fact that angles can extent to infinity in both directions is 
> kind of fundamental to the idea of saying that the trig functions are 
> periodic.

You're falling in a trap.  It's costumary in mathematics to ellide the
trivial isomorphims.  But they're still there.

When you're writing:  2+3.4 you have to use the trivial isomorphims
between ℕ and the subset of ℝ called 1.0ℕ, let's call it t, so that when
you write:  2+3.4
you actually mean t(2)+3.4
with t(2) ∈ 1.0ℕ ⊂ ℝ
 3.4  ∈ ℝ
and + being the additive operator on ℝ with 0.0 as neutral element.


Similarly, when you write sin(θ) with θ ∈ ℝ
what you actually mean is sin( angle-equivalence-class-of(θ) )
with angle-equivalence-class-of(θ) ∈ ℝ/2π.


As a programmer, it should be obvious to you.

(defstruct angle
  (representant 0.0 :type real))

(defun sinus (angle)
   ...)


(sinus 0.2) --> error

(sinus (make-angle :representant 0.2)) --> 0.19866933079506122


It just happen that 

   (defun cl:sin (representant)
 (sinus (make-angle :representant representant)))


But this should not confuse you, nor the type checking.



>> So you have different pairs of sets and different representationnal
>> mapping.  There's very little in common between an angle of 90 degree,
>> and the number 21.
>
> Would it have been easier to understand if I had made the analogy between 
> angles and (say) time? A time of 1 minute and a time of 60 seconds are 
> the same time, regardless of what representation you use for it.

Yes, but time has a dimension (time), so you don't confuse it with
random numbers.


>>> Likewise, it doesn't matter whether you write 45° or π/4 radians, the
>>> angle you are describing -- the number -- is the same.
>> 
>> No.  The numbers ARE different.  One number is 45, the other is π/4.
>> What is the same, is the angle that is represented.
>
> Fair enough. I worded that badly.

-- 
__Pascal Bourguignon__ http://www.informatimago.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Seebs
On 2010-10-13, Ben Finney  wrote:
> Python borrows from C in that consecutive literal strings are
> concatenated in the bytecode::
>
> stderr.write(
> "WARNING:"
> " Pants on fire\n")

Hmm.  So I just indent stuff inside the ()s or whatever?  I can work with
that.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


PyCharm

2010-10-13 Thread Robert H
Since the new IDE from Jetbrains is out I was wondering if "you" are
using it and what "you" think about it.

I have to start learning Python for a project at work and I am looking
around for options.

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


Re: My first Python program

2010-10-13 Thread Hallvard B Furuseth
Ethan Furman writes:
>Seebs wrote:
>>On 2010-10-12, Hallvard B Furuseth  wrote:
 self.type, self.name = None, None
>>
>>> Actually you can write self.type = self.name = None,
>>> though assignment statements are more limited than in C.
>>> (And I think they're assigned left-to-right.)
>
> Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>
> --> a = 2
> --> b = 7
> --> c = 13
> --> a = b = c = 'right to left'
> --> a, b, c
> ('right to left', 'right to left', 'right to left')

Eek.  I just meant to remark it's quite different from C where it means
a=(b=(c='...')), the assignments even happen in left-to-right _order_.
In this Python version anyway.  Not that you'd be setting a string to a
variable:-)

   >>> class Foo(str):
   ...   def __setattr__(*args): print "%s.%s = %s" % args
   ... 
   >>> f, g = Foo("f"), Foo("g")
   >>> f.x = g.y = 3
   f.x = 3
   g.y = 3

  match = re.match('(.*)\(\*([a-zA-Z0-9_]*)\)\((.*)\)', text)
>>
>>> Make a habit of using r'' for strings with lots of backslashes,
>>> like regexps.
>>
>> Hmm.  There's an interesting question -- does this work as-is? I'm
>> assuming it must or it would have blown up on me pretty badly, so
>> presumably those backslashes are getting passed through untouched
>> already.  But if that's just coincidence (they happen not to be valid
>> \-sequences), I should definitely fix that.
>
> Unknown backslash sequences are passed through as-is.

Personally I don't want to need to remember, I'm already confusing the
backslash rules of different languges.  Often you can just ask Python
what it thinks of such things, as I did with open("nonesuch"), and
then either imitate the answer or use it to help you zoom in on it in
the doc now that you know the rough answer to look for.  So,

$ python
>>> '(.*)\(\*([a-zA-Z0-9_]*)\)\((.*)\)'
'(.*)\\(\\*([a-zA-Z0-9_]*)\\)\\((.*)\\)'

Thus I'd personally spell it that way or with r'':

r'(.*)\(\*([a-zA-Z0-9_]*)\)\((.*)\)'

Note that [a-zA-Z0-9_] is equivalent to \w or [\w] in Python 2 unless
you give a LOCALE or UNICODE flag, and in Python 3 if you give the
ASCII flag.

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


Re: Hyperlink to a file using python

2010-10-13 Thread Emile van Sebille

On 10/13/2010 1:57 PM Pratik Khemka said...


I want to create a hyperlink in my excel sheet using python such that when you 
click on that link (which is a file name (html file)), the file automatically 
opens. This file is present in the same folder in which the python code file is 
present.

I am using xlwt module





link=  'abcd.html'
sheet.write(x, y, link, format_style)



Hmmm... my excel does that automagically when I
type "http://xx.yy.zz/word.html into a cell.

What happens when you use "http://a.b.c/abcd.html";?

Emile

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


Re: "Strong typing vs. strong testing"

2010-10-13 Thread Gregory Ewing

RG wrote:
I just couldn't wrap my brain around 
what it meant to square a second.


That's nothing. Magnetic permeability is measured in
newtons per square amp...

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


Re: Hyperlink to a file using python

2010-10-13 Thread Chris Rebert
On Wed, Oct 13, 2010 at 1:57 PM, Pratik Khemka  wrote:
> I want to create a hyperlink in my excel sheet using python such that when
> you click on that link (which is a file name (html file)), the file
> automatically opens. This file is present in the same folder in which the
> python code file is present.
> I am using xlwt module

You might consider asking on their newsgroup then:
http://groups.google.com/group/python-excel

Cheers,
Chris
--
"Python Problem solver"; Quite a complementary moniker for the list there.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Scheme as a virtual machine?

2010-10-13 Thread namekuseijin
On 11 out, 08:49, Oleg  Parashchenko  wrote:
> Hello,
>
> I'd like to try the idea that Scheme can be considered as a new
> portable assembler. We could code something in Scheme and then compile
> it to PHP or Python or Java or whatever.
>
> Any suggestions and pointers to existing and related work are welcome.
> Thanks!
>
> My current approach is to take an existing Scheme implementation and
> hijack into its backend. At this moment Scheme code is converted to
> some representation with a minimal set of bytecodes, and it should be
> quite easy to compile this representation to a target language. After
> some research, the main candidates are Gambit, Chicken and CPSCM:
>
> http://uucode.com/blog/2010/09/28/r5rs-scheme-as-a-virtual-machine-i/http://uucode.com/blog/2010/09/28/r5rs-scheme-as-a-virtual-machine-ii/
>
> If there is an interest in this work, I could publish progress
> reports.
>
> --
> Oleg Parashchenko  o...@http://uucode.com/http://uucode.com/blog/ XML, TeX, 
> Python, Mac, Chess

it may be assembler, too bad scheme libs are scattered around written
in far too many different flavors of assembler...

It warms my heart though to realize that Scheme's usual small size and
footprint has allowed for many quality implementations targetting many
different backends, be it x86 assembly, C, javascript or .NET.  Take
python and you have a slow c bytecode interpreter and a slow
bytecode .NET compiler.  Take haskell and its so friggin' huge and
complex that its got its very own scary monolithic gcc.  When you
think of it, Scheme is the one true high-level language with many
quality perfomant backends -- CL has a few scary compilers for native
code, but not one to java, .NET or javascript that I know of...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exceptions are not just for errors (was: My first Python program)

2010-10-13 Thread Emmanuel Surleau
> Seebs  writes:
> > On 2010-10-13, Chris Rebert  wrote:
> > > For future reference, the significant majority of things in Python
> > > raise exceptions upon encountering errors rather than returning
> > > error values of some sort.
> > 
> > Yes.  I'm getting used to that -- it's a bit of a shift, because I'm
> > used to exceptions being *exceptional* -- as in, not a failure mode
> > you would expect to see happening.
> 
> From that expectation, it's an even more fundamental shift. Python
> encourages (and tends toward) raising exceptions in any exceptional
> circumstance — that is, in any circumstance that isn't the usual
> behaviour for the function.
> 
> So, for example, an exception (StopIteration) is how iterables signal
> that they've finished iterating; but that's not an error, only an
> exception. Likewise for the ‘str.index’ example given earlier.

I'd say more succintly that Python uses (at times) exception for flow control. 
Whether that's elegant or not is debatable.

Cheers,

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


Hyperlink to a file using python

2010-10-13 Thread Pratik Khemka

I want to create a hyperlink in my excel sheet using python such that when you 
click on that link (which is a file name (html file)), the file automatically 
opens. This file is present in the same folder in which the python code file is 
present.

I am using xlwt module

 

 

link=  'abcd.html'
sheet.write(x, y, link, format_style) 

 

x: row y :col 

 

Thanks,

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


Re: "Strong typing vs. strong testing" [OT]

2010-10-13 Thread Arnaud Delobelle
Steven D'Aprano  writes:

> On Wed, 13 Oct 2010 16:17:19 +0200, Antoon Pardon wrote:
>
>> On Wed, Oct 13, 2010 at 01:20:30PM +, Steven D'Aprano wrote:
>>> On Tue, 12 Oct 2010 22:13:26 -0700, RG wrote:
>>> 
>>> >> The formula: circumference = 2 x pi x radius is taught in primary
>>> >> schools, yet it's actually a very difficult formula to prove!
>>> > 
>>> > What's to prove?  That's the definition of pi.
>>> 
>>> Incorrect -- it's not necessarily so that the ratio of the
>>> circumference to the radius of a circle is always the same number. It
>>> could have turned out that different circles had different ratios.
>> 
>> If that is your concern, you should have reacted to the previous poster
>> since in that case his equation couldn't be proven either.
>
> "Very difficult to prove" != "cannot be proven".

But in another section of your previous post you argued that it cannot
be proven as it doesn't hold in projective or hyperbolic geometry.

>
>> Since by not reacting to the previous poster, you implicitely accepted
>> the equation and thus the context in which it is true: euclidean
>> geometry. So I don't think that concerns that fall outside this context
>> have any relevance.
>
> You've missed the point that, 4000 years later it is easy to take pi for 
> granted, but how did anyone know that it was special? After all, there is 
> a very similar number 3.1516... but we haven't got a name for it and 
> there's no formulae using it. Nor do we have a name for the ratio of the 
> radius of a circle to the proportion of the plane that is uncovered when 
> you tile it with circles of that radius, because that ratio isn't (as far 
> as I know) constant.
>
> Perhaps this will help illustrate what I'm talking about... the 
> mathematician Mitchell Feigenbaum discovered in 1975 that, for a large 
> class of chaotic systems, the ratio of each bifurcation interval to the 
> next approached a constant:
>
> δ = 4.66920160910299067185320382...
>
> Every chaotic system (of a certain kind) will bifurcate at the same rate. 
> This constant has been described as being as fundamental to mathematics 
> as pi or e. Feigenbaum didn't just *define* this constant, he discovered 
> it by *proving* that the ratio of bifurcation intervals was constant. 
> Nobody had any idea that this was the case until he did so.

But you were claiming that the proposition "C = 2πr is the definition of
π" was false.  Are you claiming that "δ is defined as the ratio of
bifurcation intervals" is false as well?  If you are not, how does this
tie in with the current discussion?

Also, it is very intuitive to think that the ratio of the circumference
of a circle to it radius is constant:

Given two circles with radii r1 and r2, circumferences C1 and C2, one is
obviously the scaled-up version of the other, therefore the ratio of
their circumferences is equal to the ratio of their radii:

C1/C2 = r1/r2

Therefore:

C1/r1 = C2/r2

This constant ratio can be called 2π.  There, it wasn't that hard.  You
can pick nits with this "proof" but it is very simple and is a convincing
enough argument.

This to show that AFAIK (and I'm no historian of Mathematics) there
probably has never been much of a debate about whether the ratio of
circumference to diameter is constant.  OTOH, there were centuries of
intense mathematical labour to find out the value of π.

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


Re: My first Python program

2010-10-13 Thread Ben Finney
Seebs  writes:

> 1. If I have a message that I wish to print, it is quite possible that
> message + indentation exceeds 80 lines. What's the idiomatic way to
> solve this? Do I just break the string up into parts, or do I just
> accept that some lines are over 80 characters, or what?

Python borrows from C in that consecutive literal strings are
concatenated in the bytecode::

stderr.write(
"WARNING:"
" Pants on fire\n")

> 2. It warns about **kw, both because the name is short and because of
> the "** magic". I was previously advised that the name "kw" is
> canonical for that usage, in which case, why am I getting linted at?

More conventional is the name ‘kwargs’; of a pair with ‘*args, **kwargs’.

-- 
 \“We have to go forth and crush every world view that doesn't |
  `\believe in tolerance and free speech.” —David Brin |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Exceptions are not just for errors (was: My first Python program)

2010-10-13 Thread Ben Finney
Seebs  writes:

> On 2010-10-13, Chris Rebert  wrote:
> > For future reference, the significant majority of things in Python
> > raise exceptions upon encountering errors rather than returning
> > error values of some sort.
>
> Yes.  I'm getting used to that -- it's a bit of a shift, because I'm
> used to exceptions being *exceptional* -- as in, not a failure mode
> you would expect to see happening.

From that expectation, it's an even more fundamental shift. Python
encourages (and tends toward) raising exceptions in any exceptional
circumstance — that is, in any circumstance that isn't the usual
behaviour for the function.

So, for example, an exception (StopIteration) is how iterables signal
that they've finished iterating; but that's not an error, only an
exception. Likewise for the ‘str.index’ example given earlier.

> So for instance, I wouldn't expect to get an exception for EOF,
> because that's not exceptional, that's virtually guaranteed to happen
> whenever you interact with files. I am gonna have to retrain a bit.

EOF is exceptional in that it's not the normal behaviour for “read some
bytes from a file and return them”. EOF is expected – hence it has a
code path for handling that circumstance – but it's not normal.

Another way of thinking about it is that there's no sensible sequence of
bytes to return at EOF, so the Pythonic thing to do is to raise an
exception for this exceptional circumstance.

So your expectations on this point, while not unusual, do need
retraining as you say :-)

-- 
 \   “In the long run nothing can withstand reason and experience, |
  `\and the contradiction which religion offers to both is all too |
_o__)palpable.” —Sigmund Freud |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to add patch

2010-10-13 Thread Jason Swails
On Wed, Oct 13, 2010 at 3:36 PM, jimgardener  wrote:

> hi
> I have some demo python  code hosted on a public host that uses
> subversion..and I want to modify one of the files using a patch file
> handed to me by another person..How do I do this?Generally I checkout
> the code and make the change and then commit again..I have never done
> through patch..Can somebody tell me how to do this?
>

Using patch.  Give the patch file to "patch" via stdin, with some occasional
arguments.

patch -p0 -N < patch_file

If the path to the file is properly specified in the patch file itself, then
this will be automatic.  Otherwise, you'll need to specify the file you want
to patch.  You can see the man page for more details and options.

Good luck!
Jason


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



-- 
Jason M. Swails
Quantum Theory Project,
University of Florida
Ph.D. Graduate Student
352-392-4032
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-13 Thread Aleksej Saushev
"BartC"  writes:

> "Thomas A. Russ"  wrote in message
> news:ymi1v7vgyp8@blackcat.isi.edu...
>> torb...@diku.dk (Torben ZÆgidius Mogensen) writes:
>>
>>> Trigonometric functions do take arguments of particular units: radians
>>> or (less often) degrees, with conversion needed if you use the "wrong"
>>> unit.
>>
>> But radians are dimensionless.
>
> But they are still units

1 is a unit. Thanks, Captain.


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


Re: "Strong typing vs. strong testing"

2010-10-13 Thread Steven D'Aprano
On Wed, 13 Oct 2010 17:28:42 +0200, Pascal J. Bourguignon wrote:

>>> But what exactly *is* this number? Is it 0.25, 1.57 or 90?
>>
>> That's the wrong question. It's like asking, what exactly "is" the
>> number twenty-one -- is it "one and twenty", or 21, or 0x15, or 0o25,
>> or 21.0, or 20.999... recurring, or 63/3, or XXI, or 0b10101, or "vinet
>> et un", or any one of many other representations.
> 
> This is not the wrong question.  These are two different things.

Which is why I said it was LIKE asking the second.


> In the case of 0.25, 1.57 or 90, you have elements of the same set of
> real numbers ℝ, which are used to represent the same entity, which IS
> NOT a number, but an angle.  Angles are not in the ℝ set, but in ℝ/2π,
> which is an entirely different set with entirely different properties.

It's quite standard to discuss (say) sin(theta) where theta is an element 
of ℝ. The fact that angles can extent to infinity in both directions is 
kind of fundamental to the idea of saying that the trig functions are 
periodic.

> So you have different pairs of sets and different representationnal
> mapping.  There's very little in common between an angle of 90 degree,
> and the number 21.

Would it have been easier to understand if I had made the analogy between 
angles and (say) time? A time of 1 minute and a time of 60 seconds are 
the same time, regardless of what representation you use for it.


>> Likewise, it doesn't matter whether you write 45° or π/4 radians, the
>> angle you are describing -- the number -- is the same.
> 
> No.  The numbers ARE different.  One number is 45, the other is π/4.
> What is the same, is the angle that is represented.

Fair enough. I worded that badly.




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


how to add patch

2010-10-13 Thread jimgardener
hi
I have some demo python  code hosted on a public host that uses
subversion..and I want to modify one of the files using a patch file
handed to me by another person..How do I do this?Generally I checkout
the code and make the change and then commit again..I have never done
through patch..Can somebody tell me how to do this?
thanks
jim
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing" [OT]

2010-10-13 Thread Steven D'Aprano
On Wed, 13 Oct 2010 16:17:19 +0200, Antoon Pardon wrote:

> On Wed, Oct 13, 2010 at 01:20:30PM +, Steven D'Aprano wrote:
>> On Tue, 12 Oct 2010 22:13:26 -0700, RG wrote:
>> 
>> >> The formula: circumference = 2 x pi x radius is taught in primary
>> >> schools, yet it's actually a very difficult formula to prove!
>> > 
>> > What's to prove?  That's the definition of pi.
>> 
>> Incorrect -- it's not necessarily so that the ratio of the
>> circumference to the radius of a circle is always the same number. It
>> could have turned out that different circles had different ratios.
> 
> If that is your concern, you should have reacted to the previous poster
> since in that case his equation couldn't be proven either.

"Very difficult to prove" != "cannot be proven".


> Since by not reacting to the previous poster, you implicitely accepted
> the equation and thus the context in which it is true: euclidean
> geometry. So I don't think that concerns that fall outside this context
> have any relevance.

You've missed the point that, 4000 years later it is easy to take pi for 
granted, but how did anyone know that it was special? After all, there is 
a very similar number 3.1516... but we haven't got a name for it and 
there's no formulae using it. Nor do we have a name for the ratio of the 
radius of a circle to the proportion of the plane that is uncovered when 
you tile it with circles of that radius, because that ratio isn't (as far 
as I know) constant.

Perhaps this will help illustrate what I'm talking about... the 
mathematician Mitchell Feigenbaum discovered in 1975 that, for a large 
class of chaotic systems, the ratio of each bifurcation interval to the 
next approached a constant:

δ = 4.66920160910299067185320382...

Every chaotic system (of a certain kind) will bifurcate at the same rate. 
This constant has been described as being as fundamental to mathematics 
as pi or e. Feigenbaum didn't just *define* this constant, he discovered 
it by *proving* that the ratio of bifurcation intervals was constant. 
Nobody had any idea that this was the case until he did so.


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


Re: My first Python program

2010-10-13 Thread MRAB

On 13/10/2010 20:03, Seebs wrote:

On 2010-10-13, Chris Rebert  wrote:

For future reference, the significant majority of things in Python
raise exceptions upon encountering errors rather than returning error
values of some sort.


Yes.  I'm getting used to that -- it's a bit of a shift, because I'm
used to exceptions being *exceptional* -- as in, not a failure mode
you would expect to see happening.  So for instance, I wouldn't expect
to get an exception for EOF, because that's not exceptional, that's
virtually guaranteed to happen whenever you interact with files.  I am
gonna have to retrain a bit.


Aside from APIs which explicitly provide a parameter to be returned as
a default value in case of error (e.g. getattr(obj, name, default)),
the only common exception* I can come up with off the top of my head
is str.find()**, and even that has an exception-throwing cousin,
str.index().


Interesting!  That may take me some getting used to.


Basically, Python tries to avoid returning 'magic' values which you
need to check, but could equally just ignore.

If it can't open a file, it doesn't return None, it complains.

If it can't parse an int from a string, it doesn't return 0 (which it
could return if it's successful) or None or whatever, it complains.

There are times when, say, C# complains but Python doesn't, like trying
to get a substring starting at a position which is off the end of the
source string.

In practice I find that the Python way just works better.
--
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Chris Kaynor
On Wed, Oct 13, 2010 at 12:12 PM, Seebs  wrote:

> On 2010-10-13, Jonas H.  wrote:
> > Not really. Files will be closed when the garbage collector collects the
> > file object, but you can't be sure the GC will run within the next N
> > seconds/instructions or something like that. So you should *always* make
> > sure to close files after using them. That's what context managers were
> > introduced for.
>
> >  with open('foobar') as fileobject:
> >  do_something_with(fileobject)
>
> That makes sense.  I don't think it'd quite work in this case, because I
> want to open several files all at once, do a ton of work that populates
> them with files, and then close them all.
>
> This is a nice idiom, though.  In C, I've been sort of missing that idiom,
> which I first encountered in Ruby.  (I mean, spelled differently, but the
> same basic thing.)
>

For opening multiple files, you can either nest the with statements:
with open('foobar1') as foobar1:
   dosomethingwithfoobar1()
   with open('foobar2') as foobar2:
  dosomethingwithfoobar2()
  dosomethingelsewithfoobar1()

or you can use the contextlib module to nest them in one line:
import contextlib
with contextlib.nested(open('foobar1'), open('foobar2')) as (foobar1,
foobar2):
dosomethingwithfoobar1and2()


> -s
> --
> Copyright 2010, all wrongs reversed.  Peter Seebach /
> usenet-nos...@seebs.net
> http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
> http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
> I am not speaking for my employer, although they do rent some of my
> opinions.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Chris Kaynor
On Wed, Oct 13, 2010 at 12:13 PM, Seebs  wrote:

> On 2010-10-13, Chris Torek  wrote:
> > Unfortunately "with" is newish and this code currently has to
> > support python 2.3 (if not even older versions).
>
> I think it might be 2.4 and later.  I'm not sure.  Of course, this being
> the real world, the chances that I'll be able to stick with "Python 2" and
> not have to simultaneously also support Python 1 and Python 3 are probably
> about 20%.
>

I'm fairly sure the with statement was first added in 2.5. In 2.5, you need
to use "from __future__ import with_statement" to enable it - in 2.6 it is
always enabled (the future import is still allowed for backwards
compatibility, but it does nothing).


>
> -s
> --
> Copyright 2010, all wrongs reversed.  Peter Seebach /
> usenet-nos...@seebs.net
> http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
> http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
> I am not speaking for my employer, although they do rent some of my
> opinions.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Chris Kaynor
On Wed, Oct 13, 2010 at 12:10 PM, Seebs  wrote:

> On 2010-10-13, Jean-Michel Pichavant  wrote:
> > If you wonder about some defects reported by such linters, you can then
> > ask in this list why something is not that good, because it may not be
> > always obvious.
>
> > 'pylint' is one them, pretty effective.
>
> Okay, several questions about stuff pylint found.
>
> 1.  If I have a message that I wish to print, it is quite possible
> that message + indentation exceeds 80 lines.  What's the idiomatic way
> to solve this?  Do I just break the string up into parts, or do I just
> accept that some lines are over 80 characters, or what?
> 2.  It warns about **kw, both because the name is short and because of
> the "** magic".  I was previously advised that the name "kw" is canonical
> for that usage, in which case, why am I getting linted at?
> 3.  More generally, the usage of **kw is probably not really right, but I'm
> not sure what to do.
>
> The issue here is as follows:
>
> In C, some functions have an optional argument with the curious trait that,
> if present, it is always of the same type.  e.g., open(2).  In my wrappers,
> I indicate this by declaring it as something like "...{mode_t mode}".  The
> intent is that in a declaration, this will turn into:
>foo(blah blah blah, ... /* mode_t mode */)
> so there's an indication of why there's a "..." there.
> But C comments don't nest.  And there's a couple of points where I want to
> put the declaration in a comment.  So in those cases, I need to do
> something
> other than /*...*/:
>/* foo(blah blah blah, ... mode_t mode) */
>
> The problem:  The determination of whether I wish to do this is at the
> level
> of the "represent this function in the following way" (Function.comment()),
> but the implementation is two layers down.  So right now, I am passing
> down 'comment = True' from the top level through, and I'm doing it using
> a **kw keyword argument.
>
> The rationale is that I could just use
>def decl(comment = False):
>...
> but then the invocation:
>func.decl(True)
> would be utterly opaque.  I want to name the thing I'm passing or otherwise
> indicate what it is.
>
> It could be that I am Doing This Wrong.  Is there a good idiom for labeling
> optional arguments, and passing them on (if they exist)?
>

You can always name the arguments (the following work in 2.5 and 2.6,
barring typos - the code is untested):

def func1(arg1, arg2):
print arg1, arg2

> func1(arg2=1, arg1=2)
2 1
> func1(2, arg2=1)
2 1

def func2(arg1, arg2, optionalArg=3):
print arg1, arg2, optionalArg

> func2(1, 2)
1 2 3
> func2(1, 2, optionalArg=4)
1 2 4
> func2(1, 2, 4)
1 2 4
> func2(arg2=1, arg1=2, optionalArg=4)
2 1 4

You can also mix and match:

def func1(arg1, arg2, arg3):
print arg1, arg2, arg3

> func1(1, arg3=2, arg2=3)
1 3 2



> -s
> --
> Copyright 2010, all wrongs reversed.  Peter Seebach /
> usenet-nos...@seebs.net
> http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
> http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
> I am not speaking for my employer, although they do rent some of my
> opinions.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Seebs
On 2010-10-13, Chris Torek  wrote:
> Unfortunately "with" is newish and this code currently has to
> support python 2.3 (if not even older versions).

I think it might be 2.4 and later.  I'm not sure.  Of course, this being
the real world, the chances that I'll be able to stick with "Python 2" and
not have to simultaneously also support Python 1 and Python 3 are probably
about 20%.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Seebs
On 2010-10-13, Jonas H.  wrote:
> Not really. Files will be closed when the garbage collector collects the 
> file object, but you can't be sure the GC will run within the next N 
> seconds/instructions or something like that. So you should *always* make 
> sure to close files after using them. That's what context managers were 
> introduced for.

>  with open('foobar') as fileobject:
>  do_something_with(fileobject)

That makes sense.  I don't think it'd quite work in this case, because I
want to open several files all at once, do a ton of work that populates
them with files, and then close them all.

This is a nice idiom, though.  In C, I've been sort of missing that idiom,
which I first encountered in Ruby.  (I mean, spelled differently, but the
same basic thing.)

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Seebs
On 2010-10-13, Jean-Michel Pichavant  wrote:
> If you wonder about some defects reported by such linters, you can then 
> ask in this list why something is not that good, because it may not be 
> always obvious.

> 'pylint' is one them, pretty effective.

Okay, several questions about stuff pylint found.

1.  If I have a message that I wish to print, it is quite possible
that message + indentation exceeds 80 lines.  What's the idiomatic way
to solve this?  Do I just break the string up into parts, or do I just
accept that some lines are over 80 characters, or what?
2.  It warns about **kw, both because the name is short and because of
the "** magic".  I was previously advised that the name "kw" is canonical
for that usage, in which case, why am I getting linted at?
3.  More generally, the usage of **kw is probably not really right, but I'm
not sure what to do.

The issue here is as follows:

In C, some functions have an optional argument with the curious trait that,
if present, it is always of the same type.  e.g., open(2).  In my wrappers,
I indicate this by declaring it as something like "...{mode_t mode}".  The
intent is that in a declaration, this will turn into:
foo(blah blah blah, ... /* mode_t mode */)
so there's an indication of why there's a "..." there.
But C comments don't nest.  And there's a couple of points where I want to
put the declaration in a comment.  So in those cases, I need to do something
other than /*...*/:
/* foo(blah blah blah, ... mode_t mode) */

The problem:  The determination of whether I wish to do this is at the level
of the "represent this function in the following way" (Function.comment()),
but the implementation is two layers down.  So right now, I am passing
down 'comment = True' from the top level through, and I'm doing it using
a **kw keyword argument.

The rationale is that I could just use
def decl(comment = False):
...
but then the invocation:
func.decl(True)
would be utterly opaque.  I want to name the thing I'm passing or otherwise
indicate what it is.

It could be that I am Doing This Wrong.  Is there a good idiom for labeling
optional arguments, and passing them on (if they exist)?

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing" [OT]

2010-10-13 Thread Steven D'Aprano
On Wed, 13 Oct 2010 15:07:07 +0100, Tim Bradshaw wrote:

> On 2010-10-13 14:20:30 +0100, Steven D'Aprano said:
> 
>> ncorrect -- it's not necessarily so that the ratio of the circumference
>> to the radius of a circle is always the same number. It could have
>> turned out that different circles had different ratios.
> 
> But pi is much more basic than that, I think.

Well yes it is, but how did anyone *know* that it was? How did anyone 
even know that there was a constant pi = 3.1415... ? It's not like it was 
inscribed on the side of some mountain in letters of fire 100 ft high, 
and even if it were, why should we believe it?

The context of my comment was the statement that there is no need to 
prove that C = 2πr because that's the definition of pi. That may be how 
pi was first defined, but the Greeks didn't just *decide* that the ratio 
C/r was a constant, they discovered it. They constructed a pair of 
regular polygons with n sides, the circle inscribing one polygon and in 
turn being inscribed by the second, and observed that as n approached 
infinity two things happened: the inner and outer polygons both became 
infinitesimally close to the circle, and the ratio of the perimeter of 
either polygon to twice the radius approached the same constant.

By modern standards it wasn't *quite* vigorous -- the Greeks hadn't 
invented calculus and limits, and so had to do things the hard way -- but 
nevertheless it was an inspired proof. I call it a proof rather than a 
definition because, prior to this, nobody knew that there was such a 
number as pi, let alone what it's value was. 


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


Re: My first Python program

2010-10-13 Thread Seebs
On 2010-10-13, Chris Rebert  wrote:
> For future reference, the significant majority of things in Python
> raise exceptions upon encountering errors rather than returning error
> values of some sort.

Yes.  I'm getting used to that -- it's a bit of a shift, because I'm
used to exceptions being *exceptional* -- as in, not a failure mode
you would expect to see happening.  So for instance, I wouldn't expect
to get an exception for EOF, because that's not exceptional, that's
virtually guaranteed to happen whenever you interact with files.  I am
gonna have to retrain a bit.

> Aside from APIs which explicitly provide a parameter to be returned as
> a default value in case of error (e.g. getattr(obj, name, default)),
> the only common exception* I can come up with off the top of my head
> is str.find()**, and even that has an exception-throwing cousin,
> str.index().

Interesting!  That may take me some getting used to.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Chris Torek
In article 
Jonas H.  wrote:
>On 10/13/2010 06:48 PM, Seebs wrote:
>> Is it safe for me to assume that all my files will have been flushed and
>> closed?  I'd normally assume this, but I seem to recall that not every
>> language makes those guarantees.
>
>Not really. Files will be closed when the garbage collector collects the 
>file object, but you can't be sure the GC will run within the next N 
>seconds/instructions or something like that. So you should *always* make 
>sure to close files after using them. That's what context managers were 
>introduced for.
>
> with open('foobar') as fileobject:
> do_something_with(fileobject)
>
>basically is equivalent to (simplified!)
>
> fileobject = open('foobar')
> try:
> do_something_with(fileobject)
> finally:
> fileobject.close()
>
>So you can sure `fileobject.close()` is called in *any* case.

Unfortunately "with" is newish and this code currently has to
support python 2.3 (if not even older versions).
-- 
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)  http://web.torek.net/torek/index.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Chris Torek
In article 
Seebs   wrote:
>> * raising `Exception` rather than a subclass of it is uncommon.
>
>Okay.  I did that as a quick fix when, finally having hit one of them,
>I found out that 'raise "Error message"' didn't work.  :)  I'm a bit unsure
>as to how to pick the right subclass, though.

For exceptions, you have two choices:

  - pick some existing exception that seems to make sense, or
  - define your own.

The obvious cases for the former are things like ValueError or
IndexError.  Indeed, in many cases, you just let a work-step
raise these naturally:

def frobulate(self, x):
...
self.table[x] += ...   # raises IndexError when x out of range
...

For the latter, make a class that inherits from Exception.  In
a whole lot of cases a trivial/empty class suffices:

class SoLongAndThanksForAllTheFish(Exception):
pass

def ...:
...
if somecondition:
raise SoLongAndThanksForAllTheFish()

Since Exception provides a base __init__() function, you can
include a string:

raise SoLongAndThanksForAllTheFish('RIP DNA')

which becomes the .message field:

>>> x = SoLongAndThanksForAllTheFish('RIP DNA')
>>> x.message
'RIP DNA'
-- 
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)  http://web.torek.net/torek/index.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Ian Kelly
On Wed, Oct 13, 2010 at 11:28 AM, Ethan Furman  wrote:

> Seebs wrote:
>
>> On 2010-10-12, Hallvard B Furuseth  wrote:
>>
> >
>
>>  self.type, self.name = None, None

>>>
>>  Actually you can write self.type = self.name = None,
>>> though assignment statements are more limited than in C.
>>> (And I think they're assigned left-to-right.)
>>>
>>
> Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
> --> a = 2
> --> b = 7
> --> c = 13
> --> a = b = c = 'right to left'
> --> a, b, c
> ('right to left', 'right to left', 'right to left')
>

I'm not sure how that demonstrates anything, but here is an example where
the order of assignment actually matters:

>>> d['a'] = d = {}
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'd' is not defined
>>> d = d['a'] = {}
>>> d
{'a': {...}}

As you can see, they're assigned left-to-right.

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


Re: how do I search python mailing list archives?

2010-10-13 Thread Ned Deily
In article 
,
 Daniel Fetchinson  wrote:
> > What are the various ways to search the python mailing list archives?
> 
> If you are searching for 'foo' and 'bar' you can try this in google:
> 
> foo bar site:mail.python.org inurl:python-list

The mailing list is also mirrored at gmane.org under the group name 
gmane.comp.python.general.  You can use gmane's Xapian-powered search 
engine here: http://search.gmane.org/

-- 
 Ned Deily,
 n...@acm.org

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


Re: My first Python program

2010-10-13 Thread Jonas H.

On 10/13/2010 06:48 PM, Seebs wrote:

Is it safe for me to assume that all my files will have been flushed and
closed?  I'd normally assume this, but I seem to recall that not every
language makes those guarantees.


Not really. Files will be closed when the garbage collector collects the 
file object, but you can't be sure the GC will run within the next N 
seconds/instructions or something like that. So you should *always* make 
sure to close files after using them. That's what context managers were 
introduced for.


with open('foobar') as fileobject:
do_something_with(fileobject)

basically is equivalent to (simplified!)

fileobject = open('foobar')
try:
do_something_with(fileobject)
finally:
fileobject.close()

So you can sure `fileobject.close()` is called in *any* case.


* you might want to pre-compile regular expressions (`re.compile`)


Thought about it, but decided that it was probably more complexity than I
need -- this is not a performance-critical thing.  And even if it were, well,
I'm pretty sure it's I/O bound.  (And on my netbook, the time to run this
is under .2 seconds in Python, compared to 15 seconds in shell, so...)


Forget about my suggestion. As someone pointed out in a another post, 
regular expressions are cached anyway.



I'm a bit unsure as to how to pick the right subclass, though.


There are a few pointers in the Python documentation on exceptions.

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


Re: My first Python program

2010-10-13 Thread MRAB

On 13/10/2010 18:17, Chris Rebert wrote:

On Wed, Oct 13, 2010 at 9:56 AM, Seebs  wrote:

On 2010-10-12, MRAB  wrote:



Line 51



The __init__ method should always return None. There's no need to be
explicit about it, just use a plain "return".


The real issue here is that I was assuming that open('nonexistent') returned
None rather than raising an exception.


For future reference, the significant majority of things in Python
raise exceptions upon encountering errors rather than returning error
values of some sort.
Aside from APIs which explicitly provide a parameter to be returned as
a default value in case of error (e.g. getattr(obj, name, default)),
the only common exception* I can come up with off the top of my head
is str.find()**, and even that has an exception-throwing cousin,
str.index().

Cheers,
Chris
--
*No pun intended; I just didn't want to have to break out a thesaurus.
**Returns -1 rather than raising ValueError


The re.search and so forth return Match objects or None.
--
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Jean-Michel Pichavant

Seebs wrote:

So, I'm new to Python, though I've got a bit of experience in a few other
languages.  My overall impressions are pretty mixed, but overall positive;
it's a reasonably expressive language which has a good mix between staying
out of my way and taking care of stuff I don't want to waste attention on.

My first project was to replace a shell script with a Python script.  The
context is a project ("pseudo") which does some really hairy stuff in C.
Part of what it does involves creating hundreds of stub functions.  The
existing shell script did this successfully, but wasn't particularly
fast, and was basically unmaintainable.  So I've redone it in Python.

The input is a list of C function declarations, such as:
int foo(char *s);
and the output is several files, which include lists of these functions,
declarations for wrappers for them, and so on.  So that would produce
something to the effect of:
int foo(char *s) {
   /* various magic */
   int rc = -1;
   /* stuff happens */
   rc = wrap_foo(s);
   /* more magic */
   return rc;
}

Where it gets complicated is that there are, of course, special cases;
for instance, the wrapper for 'int open(char *path, int mode, int flags)' has
to know that the flags argument is conditional, and not always provided, so
it declares open as "int open(char *path, int mode, ...)", then extracts
flags using a va_list.  Weird stuff ensues.  It's a pretty weird hunk of
code.

The source in its current form:

http://github.com/wrpseudo/pseudo/blob/master/makewrappers

The underlying task is fairly ugly, and it's my first Python project,
so the result isn't particularly pretty, but I'd be interested in
feedback on it.  However, I'm not at all sure whether it's appropriate for
this group to post 467 lines of code with no question beyond "how am
I screwing this up?"

At this point, it does everything I want it to do, so the question isn't
"how can I do this?", but "how should I have done this more idiomatically?"

There's a few quirks; one is that I have to run on whatever Python happens
to be installed on a variety of systems, from RHEL4 to Fedora 13 or so.
(It is, at least for now, completely unimportant whether I run on non-Linux
systems.)  I can't rely on packages or extensions which aren't going to
be in the base Python install.

Apart from that... I'm interested in feedback.  I'm not expecting that
this is good or idiomatic Python, but I'd like to learn to write Python
correctly and expressively, and there's nothing like criticism to improve
code.  And if people would prefer that I post the code here, I could,
I just figured that it was a bit large.

-s
  
If you plan to code in python, then you may consider using a linter. 
These a formidable tools to help you set your coding rules, and most of 
these tools can detect most of the basics errors, or coding wrong habits.


If you wonder about some defects reported by such linters, you can then 
ask in this list why something is not that good, because it may not be 
always obvious.


'pylint' is one them, pretty effective.

JM


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


Re: if the else short form

2010-10-13 Thread John Nagle

On 10/10/2010 6:46 PM, Lawrence D'Oliveiro wrote:


Languages that insisted on being able to do proper compiler-level cross
checks between separately-compiled modules (e.g. Modula-2, Ada) never really
became that popular. This saddened me.


   It's an sad consequence of a UNIX mindset that "you can't change
the linker".  This stems from the early days of UNIX, where the
linker was in assembler, very limited, and had very few
comments.  That's why C++ had "name mangling", instead of
a type-aware linker.  Really.

   There are interesting things to do at link time, and the Gnu
toolchain finally added some of them.  Weak links, for example -
ones which are resolved if the target is present, but won't
pull it in. This allows bringing in C++ classes without
hauling in every unreferenced member function of the class.

   Modula did more at link time.  In Modula, modules had
initialization sections.  Initialization sections could call
functions in other modules.   The rule was that you couldn't call
into a module until the module's initialization section had run.
Conveniently, the Modula "binder" computed the dependency graph
of what called what, and ordered the initialization sections so
that all modules were initialized before being called.  The
binder could detect dependency loops, and reported them at
link time.  So if the program would build, it would initialize
in proper order.

   This is a nice check, because it's a global property of
the program, not a local bug.  It's the sort of thing that
appears on large projects where different people are doing
different modules.  Computers are better than
people at finding that class of problem.

   C++ got this wrong, leading to the "static initialization
order fiasco".  Python is vulnerable to this problem in
import loops, although the consequences aren't as severe as
in C++.

John Nagle

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


Re: My first Python program

2010-10-13 Thread Ethan Furman

Seebs wrote:

On 2010-10-12, Hallvard B Furuseth  wrote:

>

self.type, self.name = None, None



Actually you can write self.type = self.name = None,
though assignment statements are more limited than in C.
(And I think they're assigned left-to-right.)


Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit 
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
--> a = 2
--> b = 7
--> c = 13
--> a = b = c = 'right to left'
--> a, b, c
('right to left', 'right to left', 'right to left')


 match = re.match('(.*)\(\*([a-zA-Z0-9_]*)\)\((.*)\)', text)



Make a habit of using r'' for strings with lots of backslashes,
like regexps.


Hmm.  There's an interesting question -- does this work as-is?  I'm
assuming it must or it would have blown up on me pretty badly, so
presumably those backslashes are getting passed through untouched
already.  But if that's just coincidence (they happen not to be valid
\-sequences), I should definitely fix that.


Unknown backslash sequences are passed through as-is.

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


Re: how do I search python mailing list archives?

2010-10-13 Thread Daniel Fetchinson
> What are the various ways to search the python mailing list archives?

If you are searching for 'foo' and 'bar' you can try this in google:

foo bar site:mail.python.org inurl:python-list

Cheers,
Daniel


-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Chris Rebert
On Wed, Oct 13, 2010 at 9:56 AM, Seebs  wrote:
> On 2010-10-12, MRAB  wrote:

>> Line 51
>
>> The __init__ method should always return None. There's no need to be
>> explicit about it, just use a plain "return".
>
> The real issue here is that I was assuming that open('nonexistent') returned
> None rather than raising an exception.

For future reference, the significant majority of things in Python
raise exceptions upon encountering errors rather than returning error
values of some sort.
Aside from APIs which explicitly provide a parameter to be returned as
a default value in case of error (e.g. getattr(obj, name, default)),
the only common exception* I can come up with off the top of my head
is str.find()**, and even that has an exception-throwing cousin,
str.index().

Cheers,
Chris
--
*No pun intended; I just didn't want to have to break out a thesaurus.
**Returns -1 rather than raising ValueError
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Difficulty in easy_install

2010-10-13 Thread John Nagle

On 10/11/2010 1:45 AM, sankalp srivastava wrote:


  I am having difficulty in easy_installing
I use a proxy server and strange errors , like it can't fetch the
package is showing up .
the package is pyspeech ...please help me :(

I don't know if the proxy server is causing the problems , in linux i
would have import http-proxy in .bashrc
but am not a windows expert
can anyone help me plz


That's about typical.  "easy_install" isn't "easy".  It has some
built-in assumptions about where various files are stored, and if
the installation doesn't match them, installs fail with obscure
error messages.

"egg" files are really just "zip" files.  It's sometimes
necessary to unpack them, and run "python setup.py".

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


Re: PEP 249 (database api) -- executemany() with iterable?

2010-10-13 Thread John Nagle

On 10/12/2010 6:01 PM, Lawrence D'Oliveiro wrote:

In message<4cb4ba4e$0$1641$742ec...@news.sonic.net>, John Nagle wrote:


In general, if you find yourself making millions of
SQL database requests in a loop, you're doing it wrong.


I’ve done this. Not millions, but certainly on the order of tens of
thousands.


   It's a scaling issue.  Millions of INSERT or UPDATE requests can
take hours.  That's when you need the speedup of bulk loading.


  Big database loads are usually done by creating a text file
with the desired data, then using a LOAD DATA INFILE command.


May not always be flexible enough.


   True; you can't do anything with LOAD DATA INFILE but load data.
If you need selects or joins within inserts, you may have to do it
the long way.


This (in MySQL) is tens to hundreds of times faster than doing individual
INSERT or UPDATE commands.


Why should that be? The database cannot read a text file any faster than I
can.


Because the indices are updated in one big update, rather than
after each change to the database.

Also note that there are some issues with doing a huge volume of
updates in one MySQL InnoDB transaction.  The system has to keep the
data needed to undo the updates, and there's a limit on the amount of
pending transaction history that can be stored.

It's common to load data into a new, empty table, then, once
the reload has succeeded, do a RENAME like CURRENT->OLD, NEW->CURRENT.
Rename of multiple databases is atomic and interlocked with other
operations, so you can replace an entire table on a live server.

I have some bulk databases which are updated from external
sources.  The PhishTank database is updated with UPDATE statements
every three hours. But the Open Directory database is updated by
downloading a big gzipped file of XML, creating a new database
table, then renaming.  That load takes hours, once a week.

(All this applies to MySQL, and to some extent, Postgres.
If you're using SQLite, it's different.  But a million records
is big for SQLite, which is, after all, a "lite" database.
At 10,000 records, you don't have to worry about any of this
stuff.  At 1,000,000 records, you do.)

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


Re: My first Python program

2010-10-13 Thread Seebs
On 2010-10-12, Hallvard B Furuseth  wrote:
>> list = map(lambda x: x.call(), self.args)
>> return ', '.join(list)
>
>   return ', '.join([x.call() for x in self.args])

I think I wrote that before I found out about list comprehensions.  How
new are list comprehensions?

I do like that, it's clearer.

>> self.type, self.name = None, None

> Actually you can write self.type = self.name = None,
> though assignment statements are more limited than in C.
> (And I think they're assigned left-to-right.)

Okay.

>>  match = re.match('(.*)\(\*([a-zA-Z0-9_]*)\)\((.*)\)', text)

> Make a habit of using r'' for strings with lots of backslashes,
> like regexps.

Hmm.  There's an interesting question -- does this work as-is?  I'm
assuming it must or it would have blown up on me pretty badly, so
presumably those backslashes are getting passed through untouched
already.  But if that's just coincidence (they happen not to be valid
\-sequences), I should definitely fix that.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Seebs
On 2010-10-12, MRAB  wrote:
> The code does require Python 2 and the use of except ... as ... requires 
> at least version 2.6.

Whoops.

> Line 51

> The __init__ method should always return None. There's no need to be 
> explicit about it, just use a plain "return".

The real issue here is that I was assuming that open('nonexistent') returned
None rather than raising an exception.

> The error message says:

>  "Couldn't open %s to read a template."

> but it's opening the file for writing.

Ahh, my famed attention to detail strikes again. :)

> You can't really rely on the destructor __del__ being called.

Interesting.  Do I just rely on files getting closed?

> Line 333

> Shouldn't you be checking that the name of the attribute you're setting 
> doesn't clash with one of the existing attributes? Are you sure that a 
> dict wouldn't be a better idea?

Actually, not sure at all.  There's a sort of gradual evolution going on
here, in that I was trying to avoid having a separate dict that I had to
populate with a bunch of stuff -- thus the switch to a hand-written
__getitem__.  What I probably ought to do/have done is use a dict first,
and set things in the dict from here, then check the dict first, then
regular getattr, and so on.

> Line 447
>
> The form:
>
>  except ... as ...
>
> is in Python versions >= 2.6, but not earlier.

Oops.  Is there a way to interact with the caught exception in earlier
Python?

> This use of del just deletes the name from the namespace and won't 
> necessarily call the __del__ method of the 'source' object. It's better 
> to rely on something more explicit like a 'close' method. (If you can't 
> be sure which version of Python it'll use then context managers are 
> probably out anyway!)

Okay, good to know.  I'll fix that.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Seebs
On 2010-10-12, Chris Rebert  wrote:
> 2.
> self.f = file(path, 'r')
> if not self.f:
> return None
>
> The "if" here is pointless; I'm reasonably sure files are always
> considered boolean true.

I actually seem to have done this wrong anyway -- I was thinking in
terms of the C-like idiom of returning NULL when a constructor-like thing
fails.  This ought to have been a raise of some sort to prevent the caller
from getting an object that didn't work out.

> Python's grammar has "not in" as an "operator" for just such occasions ==>

Ahh!

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Seebs
On 2010-10-12, Jonas H.  wrote:
> Just a few pointers, looks quite good to me for a newbie :)

Thanks!

> * Less action in __init__.

I'm a bit curious about this.  The __init__ functions in this are, at
least for now, pretty much doing only what's needed to create the objects
from their inputs.

> * Use `open` instead of `file` to open a file

Done.

> * Have a look at context managers for file handling (avoids doing 
> error-prune stuff like __del__)

Okay.  I wasn't at all sure the __del__ was needed.

> * Your `del` in line 464 is useless. A reference will be removed from 
> the object bound to the local variable 'source' anyway because of the 
> re-assignment.

Oh.  D'oh.  You can see the C programmer instinct there; that was the
sort of thing that would, in C, be:
for (i = 0; i < n; ++i)
free(array[i]);

But of course, that doesn't work.  I guess that leads to a general question:
Is it safe for me to assume that all my files will have been flushed and
closed?  I'd normally assume this, but I seem to recall that not every
language makes those guarantees.

> * according to common Python style guides you should not use underscores 
> in class names.

Makes sense.  I was finding "CArgument" hard to read, and couldn't think
of a better name.

> * no need for 'r' in `open` calls ('r' is the default mode)

'k.

> * `line == ''` can be written more pythonic as `not line`

'k.

> * `str.{r,l,}strip` removes '\n\t\r ' by default, no need for an 
> argument here (line 440 for example)

Ahh, good to know.

> * you might want to pre-compile regular expressions (`re.compile`)

Thought about it, but decided that it was probably more complexity than I
need -- this is not a performance-critical thing.  And even if it were, well,
I'm pretty sure it's I/O bound.  (And on my netbook, the time to run this
is under .2 seconds in Python, compared to 15 seconds in shell, so...)

> * raising `Exception` rather than a subclass of it is uncommon.

Okay.  I did that as a quick fix when, finally having hit one of them,
I found out that 'raise "Error message"' didn't work.  :)  I'm a bit unsure
as to how to pick the right subclass, though.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


how do I search python mailing list archives?

2010-10-13 Thread Sean Choi
What are the various ways to search the python mailing list archives?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-13 Thread Pascal J. Bourguignon
Steven D'Aprano  writes:

> Hmmm, my ISP's news software really doesn't like it when I cross-post to
> more than three newsgroups. So, trying again without comp.lang.c.
>
> On Wed, 13 Oct 2010 02:00:46 +0100, BartC wrote:
>
>> "RG"  wrote in message
>> news:rnospamon-20651e.17410012102...@news.albasani.net...
>>> In article , "BartC"
>>>  wrote:
>>>
 "Thomas A. Russ"  wrote in message
>>
 > But radians are dimensionless.

 But they are still units
>>>
>>> No, they aren't.
>>>
 so that you can choose to use radians, degrees or gradians
>>>
>>> Those aren't units either, any more than a percentage is a unit.  They
>>> are just different ways of writing numbers.
>>>
>>> All of the following are the same number written in different
>>> notations:
>>>
>>> 0.5
>>> 1/2
>>> 50%
>>>
>>> Likewise, all of the following are the same number written in different
>>> notations:
>>>
>>> pi/2
>>> pi/2 radians
>>> 90 degrees
>>> 100 gradians
>>> 1/4 circle
>>> 0.25 circle
>>> 25% of a circle
>>> 25% of 2pi
>>>
>>> See?
>>
>> But what exactly *is* this number? Is it 0.25, 1.57 or 90?
>
> That's the wrong question. It's like asking, what exactly "is" the number
> twenty-one -- is it "one and twenty", or 21, or 0x15, or 0o25, or 21.0, or
> 20.999... recurring, or 63/3, or XXI, or 0b10101, or "vinet et un", or any
> one of many other representations.

This is not the wrong question.  These are two different things.

In the case of 0.25, 1.57 or 90, you have elements of the same set of
real numbers ℝ, which are used to represent the same entity, which IS NOT
a number, but an angle.  Angles are not in the ℝ set, but in ℝ/2π, which
is an entirely different set with entirely different properties.



In the other case, we have strings "21", "0x15", "0o25", "21.0",
"20.999...", "63/3", "XXI", "0b10101", "vingt et un", that represent the
same number in ℝ.




So you have different pairs of sets and different representationnal
mapping.  There's very little in common between an angle of 90 degree,
and the number 21.




> Likewise, it doesn't matter whether you write 45° or π/4 radians, the
> angle you are describing -- the number -- is the same.

No.  The numbers ARE different.  One number is 45, the other is π/4.
What is the same, is the angle that is represented.

I cannot fathom how you can arrive at such a misunderstanding.  It's
rather easy to picture out:

ℝ   .ℝ/2π..
   :  : ::
  ::degree : full turn:
  :45 --\ :
  : :  : \:
  : :  :   angle of an eighth of a turn   :
  : :radian: /:
  :π/4 -/ :
  : :  :quarter turn  :
   :   :::
...  


--
__Pascal Bourguignon__ http://www.informatimago.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-13 Thread Keith Thompson
RG  writes:
> In article <8hl2ucfdv...@mid.individual.net>,
>  Gregory Ewing  wrote:
>> Tim Bradshaw wrote:
>> > In general any function 
>> > which raises its argument to more than one power ...  doesn't make
>> > much sense if its argument has units.
>> 
>> That's not true. Consider the distance travelled by a
>> falling object: y(t) = y0 + v0*t + 0.5*a*t**2. Here t has
>> dimensions of time, and it's being raised to different
>> powers in different terms. It works because the
>> coefficents have dimensions too, and all the terms end up
>> having the same dimensions.
>
> This reminds me of back when I was a kid and my dad was trying to teach 
> me basic physics.  He kept saying that the acceleration of gravity was 
> 9.8 meters per second squared and I just couldn't wrap my brain around 
> what it meant to square a second.
>
> Now that I think about it, I still can't.  :-)

Fuel economy can be measured in reciprocal acres (or reciprocal
hectares if you prefer).

miles/gallon or km/liter is distance / distance**3 --> distance**-2.

-- 
Keith Thompson (The_Other_Keith) ks...@mib.org  
Nokia
"We must do something.  This is something.  Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Compiling as 32bit on MacOSX

2010-10-13 Thread Philip Semanchuk

On Oct 13, 2010, at 3:54 AM, Gregory Ewing wrote:

> Philip Semanchuk wrote:
> 
>> Hi Greg,
>> Are you talking about compiling Python itself or extensions?
> 
> I've managed to get Python itself compiled as 32 bit,
> and that also seems to take care of extensions built
> using 'python setup.py ...'.
> 
> I'm mainly concerned about non-Python libraries that
> get wrapped by the extensions, of which I've built up
> quite a collection over the years. Currently I'm having
> to keep a careful eye out when building them to make
> sure they don't get compiled with the wrong architecture,
> since gcc's natural inclination is to default to 64 bit
> whenever it's available.
> 
> So I was wondering if there was some way of globally
> changing that default that doesn't rely on compiler
> options getting passed correctly through the many and
> varied layers of build technology that one comes across.
> But from what I've seen so far, it seems not.

If CFLAGS isn't doing the trick for you, then I don't know what to suggest. 
Maybe some libs also need LDFLAGS='-arch i386 -arch x86_64'?

FYI, the `file` command will give you information about whether or not a binary 
is 32-bit, 64-bit or both.

$ file shlib/libreadline.6.1.dylib 
shlib/libreadline.6.1.dylib: Mach-O universal binary with 2 architectures
shlib/libreadline.6.1.dylib (for architecture i386):Mach-O dynamically 
linked shared library i386
shlib/libreadline.6.1.dylib (for architecture x86_64):  Mach-O 64-bit 
dynamically linked shared library x86_64


Good luck
Philip
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using csv.DictReader with \r\n in the middle of fields

2010-10-13 Thread Neil Cerutti
On 2010-10-13, pstatham  wrote:
> Hopefully this will interest some, I have a csv file (can be
> downloaded from http://www.paulstathamphotography.co.uk/45.txt) which
> has five fields separated by ~ delimiters. To read this I've been
> using a csv.DictReader which works in 99% of the cases. Occasionally
> however the description field has errant \r\n characters in the middle
> of the record. This causes the reader to assume it's a new record and
> try to read it.

Here's an alternative idea. Working with csv module for this job
is too difficult for me. ;)

import re

record_re = 
"(?P.*?)~(?P.*?)~(?P.*?)~(?P.*?)~(?P.*?)\n(.*)"

def parse_file(fname):
with open(fname) as f:
data = f.read()
m = re.match(record_re, data, flags=re.M | re.S)
while m:
yield m.groupdict()
m = re.match(record_re, m.group(6), flags=re.M | re.S)

for record in parse_file('45.txt'):
print(record)

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


Re: Tkinter: Exception RuntimeError: 'maximum recursion depth exceeded'

2010-10-13 Thread Jeff Hobbs
On Oct 13, 2:18 am, o...@dtrx.de (Olaf Dietrich) wrote:
> Jeff  Hobbs :
>
>
>
>
>
> > On Oct 12, 9:43 am, o...@dtrx.de (Olaf Dietrich) wrote:
>
> >> After some somewhat heavy mouse action inside the
> >> canvas (with the left button pressed), the application throws:
>
> >> | Exception RuntimeError: 'maximum recursion depth exceeded' in  >> method PhotoImage.__del__ of > 
> >> ignored
> >> | Exception in Tkinter callback
> [...]
> >> (and similiar ones)
>
> >> This error can be provoked faster by setting the recursion limit
> >> to lower values (e.g. 400 as in the comment above).
>
> >> Is there anything I can do (apart from increasing the recursion
> >> limit) to avoid this exception? Can I improve anything in the
> >> script above to make the whole thing more robust?
>
> > It seems very heavy-handed to create 1-pixel images for drawing onto
> > the canvas.  Any reason not to use something lighter weight?
>
> The example was _heavily_ simplified; originally, there was
> a background (e.g. gray-scale) image and I was drawing lines or
> other shapes onto that background that should appear in color
> and semi-transparent on top of the background. Additionally,
> both background and foreground can be zoomed and scrolled, and
> there should be a pixel-by-pixel correspondence between the
> (zoomed) background pixels and the semi-transparent shapes
> in the foreground (as opposed to overlayed vector graphics).
> I could not find a more light-weight solution for these
> requirements.

Interesting.  The canvas would support many of your primitives,
although the semi-transparent is only directly supported by images in
the core.  I'm not sure I entirely understand your app needs, but this
sounds like something the tkpath Tk extension solves (sort of canvas+
+), though that doesn't have a Tkinter wrapper that I'm aware of.

> > I suspect the "self.root.update()" is the problem.  Try
> > update_idletasks() instead, or to even avoid it if possible.  You
> > don't want to call update in the event loop, because you are likely
> > reprocessing from the same call, causing the recursion.
>
> Indeed, Tk/Toplevel/Canvas.update() seems to be at the
> center of the problem.
>
> If I replace update() by update_idletasks(), the problem
> disappears, but unfortunately, considerably fewer events
> are recorded on the canvas (when connecting the pixels with
> lines, the lines become much longer with update_idletasks()
> than with update()). If I remove both update() and
> update_idletasks(), things work similarly as with
> update_idletasks() (the display is only marginally slower
> than with update_idletasks()).
>
> I wonder if there is any compromise between update()
> and update_idletasks():
>
> * update(): smooth lines but recursion exception
> * update_idletasks(): non-smooth lines without exceptions

In general it isn't necessary to use update to keep up in pure Tcl/
Tk.  You can see an example drawing app at http://wiki.tcl.tk/15386
that has no trouble keeping up with the fastest mouse, without
update.  Without digging deeper into the Tkinter wrapper, maybe just
extending the recursionlimit is the easiest work-around?

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


Re: "Strong typing vs. strong testing"

2010-10-13 Thread Steve Schafer
On Wed, 13 Oct 2010 06:05:27 -0500, r...@rpw3.org (Rob Warnock) wrote:

>Why should it?!? If you look way under the covers, I suspect that even
>the "c^2" in "E = mc^2" is a "collected" term in the above sense [that is,
>if I recall my classes in introductory special relativity correctly].

In special relativistic terms, -c^2 is basically a unit-of-measurement
conversion factor between two values that represent the same underlying
"thing," analogous to the way that 25.4 is a conversion factor between
inches and millimetres. Whether you consider this equivalence to be an
intrinsic characteristic of the physical universe or merely a
consequence of the mathematics we use to describe the universe is a
philosophical question. But the fact that such an equivalence exists at
all suggests that the notion of "squaring time" as an analog of squaring
distance isn't really all that farfetched. (However, like the previous
poster, I've never been able to make any sense of it.)

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


Re: send command to parent shell

2010-10-13 Thread Nobody
On Wed, 13 Oct 2010 06:30:15 -0700, Martin Landa wrote:

> is there a way how to send command from python script to the shell
> (known id) from which the python script has been called?

For Unix, this should work, but in general it's the wrong thing to do:

import os
import signal
os.kill(os.getppid(), signal.SIGKILL)

This is a rather unfriendly way to kill the shell (it won't be able to
save its history, etc), and if the program was started from something
other than a shell, you might kill something you don't want to.

Using SIGHUP is more friendly and will probably work, but it could be
caught and/or ignored (for bash, SIGTERM, SIGQUIT and SIGINT /will/ be
ignored). If the shell can catch the signal in order to save its history,
it can catch it and ignore it.

There isn't a nice way to do it. There isn't supposed to be a nice way to
do it. Processes may control their children, but a child isn't supposed to
control its parent.

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


Re: "Strong typing vs. strong testing" [OT]

2010-10-13 Thread Antoon Pardon
On Wed, Oct 13, 2010 at 01:20:30PM +, Steven D'Aprano wrote:
> On Tue, 12 Oct 2010 22:13:26 -0700, RG wrote:
> 
> >> The formula: circumference = 2 x pi x radius is taught in primary
> >> schools, yet it's actually a very difficult formula to prove!
> > 
> > What's to prove?  That's the definition of pi.
> 
> Incorrect -- it's not necessarily so that the ratio of the circumference 
> to the radius of a circle is always the same number. It could have turned 
> out that different circles had different ratios. 

If that is your concern, you should have reacted to the previous poster
since in that case his equation couldn't be proven either.

Since by not reacting to the previous poster, you implicitely accepted
the equation and thus the context in which it is true: euclidean geometry.
So I don't think that concerns that fall outside this context have any
relevance.

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


  1   2   >