Re: list unpack trick?

2005-01-23 Thread Bengt Richter
On Sun, 23 Jan 2005 15:43:43 +1000, Nick Coghlan <[EMAIL PROTECTED]> wrote:

>aurora wrote:
>> I am think more in the line of string.ljust(). So if we have a  
>> list.ljust(length, filler), we can do something like
>> 
>>   name, value = s.split('=',1).ljust(2,'')
>
>Eh?
>
>Py> s.split('=',1).ljust(2,'')
>Traceback (most recent call last):
>   File "", line 1, in ?
>AttributeError: 'list' object has no attribute 'ljust'
>

 Python 2.4b1 (#56, Nov  3 2004, 01:47:27)
 [GCC 3.2.3 (mingw special 20030504-1)] on win32
 Type "help", "copyright", "credits" or "license" for more information.
 >>> help(''.ljust)
 Help on built-in function ljust:

 ljust(...)
 S.ljust(width[, fillchar]) -> string

 Return S left justified in a string of length width. Padding is
 done using the specified fill character (default is a space).

I should upgrade too ;-)

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


Re: Comments in configuration files

2005-01-23 Thread alex23
> I would like it to be editable, through a web browser or a GUI
> application. With ConfigParser I can read the configuration file and
> edit the options, but when I write the result all the comments are
lost

Hey Pierre,

I came across a good review of a number of possible solutions for this
at http://www.python.org/moin/ConfigParserShootout
Hope it helps.

- alex23

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


Re: [OT] XML design intent ... further musings

2005-01-23 Thread Stephen Waterbury
Paul Rubin wrote:
Stephen Waterbury <[EMAIL PROTECTED]> writes:
I should note that I have to deal with XML a lot, but always
kicking and screaming (though much less now because of Fredrik's
Elementtree package ;).  Thanks, Fredrik and Peter, for the
references.  ;)
I love this old rant about XML:
http://groups-beta.google.com/group/comp.lang.lisp/msg/9a30c508201627ee
Yep, Erik Naggum is one of my heroes for that!  :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: list unpack trick?

2005-01-23 Thread Bengt Richter
On Sun, 23 Jan 2005 08:22:36 GMT, [EMAIL PROTECTED] (Bengt Richter) wrote:

>On Sun, 23 Jan 2005 15:43:43 +1000, Nick Coghlan <[EMAIL PROTECTED]> wrote:
>
>>aurora wrote:
>>> I am think more in the line of string.ljust(). So if we have a  
>>> list.ljust(length, filler), we can do something like
>>> 
>>>   name, value = s.split('=',1).ljust(2,'')
>>
>>Eh?
>>
>>Py> s.split('=',1).ljust(2,'')
>>Traceback (most recent call last):
>>   File "", line 1, in ?
>>AttributeError: 'list' object has no attribute 'ljust'
>>
>
> Python 2.4b1 (#56, Nov  3 2004, 01:47:27)
> [GCC 3.2.3 (mingw special 20030504-1)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> help(''.ljust)
> Help on built-in function ljust:
>
> ljust(...)
> S.ljust(width[, fillchar]) -> string
>
> Return S left justified in a string of length width. Padding is
> done using the specified fill character (default is a space).
>
>I should upgrade too ;-)
>
And learn to read instead of jumping to conclusions ;-/
No ljust for *LIST* objects, D'oh.

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


Re: getting file size

2005-01-23 Thread John Machin

Tim Roberts wrote:
> Bob Smith <[EMAIL PROTECTED]> wrote:
>
> >Are these the same:
> >
> >1. f_size = os.path.getsize(file_name)
> >
> >2. fp1 = file(file_name, 'r')
> >data = fp1.readlines()
> >last_byte = fp1.tell()
> >
> >I always get the same value when doing 1. or 2. Is there a reason I
> >should do both? When reading to the end of a file, won't tell() be
just
> >as accurate as os.path.getsize()?
>
> On Windows, those two are not equivalent.  Besides the newline
conversion
> done by reading text files,

Doesn't appear to me to go wrong due to newline conversion:

Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on
win32
>>> import os.path
>>> txt = 'qwertyuiop\nasdfghjkl\nzxcvbnm\n'
>>> file('bob', 'w').write(txt)
>>> len(txt)
29
>>> os.path.getsize('bob')
32L # as expected
>>> f = file('bob', 'r')
>>> lines = f.readlines()
>>> lines
['qwertyuiop\n', 'asdfghjkl\n', 'zxcvbnm\n']
>>> f.tell()
32L # as expected

> the solution in 2. will stop as soon as it sees
> a ctrl-Z.

... and the value returned by f.tell() is not the position of the
ctrl-Z but more likely the position of the end of the current block --
which could be thousands/millions of bytes before the physical end of
the file.

Good ol' CP/M.

>
> If you used 'rb', you'd be much closer.

And be much less hassled when that ctrl-Z wasn't meant to mean EOF, it
just happened to appear in an unvalidated data field part way down a
critical file :-(

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


Re: how to write a tutorial

2005-01-23 Thread Xah Lee
adding to my previosu comment...
In the Python tutorial:
http://python.org/doc/2.3.4/tut/node11.html

the beginning two paragraphs should be deleted. Nobody gives a shit
except a few smug academicians where the author wrote it for pleasing
himself. For 99% of readers, it is incomprehensible and irrelevant.

the first paragraph of 9.1 "A Word About Terminology" is epitome of
masturbation. The entire 9.1 is not necessary.

Large part of 9.2 "Python Scopes and Name Spaces" is again
masturbatory.

--

Most texts in computing are written by authors to defend and showcase
their existence against their peers. In a tutorial, nobody cares how
the language compared to x y and z, or what technicality is it all
about, or some humorous snippet of history only funny to the author
himself.

Particularly for texts in a tutorial context, you want to write it as
simple as possible covering the most useful basic functionalities and
concepts, and self-contained. Not showcasing your knowledge of history
of languages or your linguistic lineage byways.

For example this chapter 9 on Objects, it is not difficult to write it
without making a show of lingoes. One simply write what is of Python,
without thinking about relation to xyz languages or the "computer
science" establishment and their ways of thinkings of namespaces and
scopes and dynamic and statics and inheritances ... fucking bags of
shit.

Also, in the computing industry, documentations and tutorials often
lacks examples. Especially important in tutorials. Be fewer in words,
more in examples. (for example, unix man pages are full of arcane
abstract syntax specifications and inner-working technicalities while
most don't contain a single example of usage that is much needed.)

also, this does not mean beginning to write for dummies as the highly
successful series of "xyz for Dummies" books. These are successful
because the corpus of textbook writers are all inclined and habituated
to chalk up to jargons and intellectualization on the accounts of their
own esteem and careers. Dummy books are moronic because they assumed
the general readers are morons.

PS Another illustrative case is the official Java Tutorial. Python
tutorial is to the point on the whole. The Java Tutorial is completely
asinine. Chalking up to rocket sciences every chance with unhelpful and
misleading drivel.
Xah
 [EMAIL PROTECTED]
 http://xahlee.org/PageTwo_dir/more.html

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


Re: getting file size

2005-01-23 Thread John Machin

Tim Roberts wrote:
> Bob Smith <[EMAIL PROTECTED]> wrote:
>
> >Are these the same:
> >
> >1. f_size = os.path.getsize(file_name)
> >
> >2. fp1 = file(file_name, 'r')
> >data = fp1.readlines()
> >last_byte = fp1.tell()
> >
> >I always get the same value when doing 1. or 2. Is there a reason I
> >should do both? When reading to the end of a file, won't tell() be
just
> >as accurate as os.path.getsize()?
>
> On Windows, those two are not equivalent. Besides the newline
conversion
> done by reading text files,

Doesn't appear to me to go wrong due to newline conversion:

Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on
win32
>>> import os.path
>>> txt = 'qwertyuiop\nasdfghjkl\nzxcvbnm\n'
>>> file('bob', 'w').write(txt)
>>> len(txt)
29
>>> os.path.getsize('bob')
32L # as expected
>>> f = file('bob', 'r')
>>> lines = f.readlines()
>>> lines
['qwertyuiop\n', 'asdfghjkl\n', 'zxcvbnm\n']
>>> f.tell()
32L # as expected

> the solution in 2. will stop as soon as it sees
> a ctrl-Z.

... and the value returned by f.tell() is not the position of the
ctrl-Z but more likely the position of the end of the current block --
which could be thousands/millions of bytes before the physical end of
the file.

Good ol' CP/M.

>
> If you used 'rb', you'd be much closer.

And be much less hassled when that ctrl-Z wasn't meant to mean EOF, it
just happened to appear in an unvalidated data field part way down a
critical file :-(

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


Re: how to write a tutorial

2005-01-23 Thread CBFalconer
Xah Lee wrote:
> 
... snip ...
> 
> the first paragraph of 9.1 "A Word About Terminology" is epitome
> of masturbation. The entire 9.1 is not necessary.
> 
> Large part of 9.2 "Python Scopes and Name Spaces" is again
> masturbatory.

PLONK for excessive OT crossposting and trolling.

-- 
"If you want to post a followup via groups.google.com, don't use
 the broken "Reply" link at the bottom of the article.  Click on 
 "show options" at the top of the article, then click on the 
 "Reply" at the bottom of the article headers." - Keith Thompson


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


Re: Insanity

2005-01-23 Thread Tim Daneliuk
Fredrik Lundh wrote:
Tim Daneliuk wrote:

Given an arbitrary string, I want to find each individual instance of
text in the form:  "[PROMPT:optional text]"
I tried this:
   y=re.compile(r'\[PROMPT:.*\]')
Which works fine when the text is exactly "[PROMPT:whatever]"

didn't you leave something out here?  "compile" only compiles that pattern;
it doesn't match it against your string...
Sorry - I thought this was obvious - I was interested more in the conceptual
part of the contruction of the re itself.

but does not match on:
  "something [PROMPT:foo] something [PROMPT:bar] something ..."
The overall goal is to identify the beginning and end of each [PROMPT...]
string in the line.

if the pattern can occur anywhere in the string, you need to use "search",
not "match".  if you want multiple matches, you can use "findall" or, better
in this case, "finditer":
import re
s = "something [PROMPT:foo] something [PROMPT:bar] something"
for m in re.finditer(r'\[PROMPT:[^]]*\]', s):
print m.span(0)
prints
(10, 22)
(33, 45)
which looks reasonably correct.
(note the "[^x]*x" form, which is an efficient way to spell "non-greedy match"
for cases like this)
Thanks - very helpful.  One followup - your re works as advertised.  But
if I use: r'\[PROMPT:[^]].*\]'  it seems not to.  the '.*' instead of just '*'
it matches the entire string ... which seems counterintutive to me.
Thanks,
--

Tim Daneliuk [EMAIL PROTECTED]
PGP Key: http://www.tundraware.com/PGP/
--
http://mail.python.org/mailman/listinfo/python-list


Re: debugging xmlrpc servers

2005-01-23 Thread Diez B. Roggisch
I have difficulties understanding your probelem - is your own method giving
you trouble (and the 'exceptions.ValueError:too many values to unpack')
error or is it the remote debugger? Or do you simply not understand the
error message itself.

The error itself is raised in cases like this:

a,b,c = (1,2,3,4)

Now to see where that sort of statement fails, it would help if you'd give
us the actual code for your result-method.


-- 
Regards,

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


Re: re Insanity

2005-01-23 Thread Orlando Vazquez
Tim Daneliuk wrote:
For some reason, I am having the hardest time doing something that should
be obvious.  (Note time of posting ;)
Given an arbitrary string, I want to find each individual instance of
text in the form:  "[PROMPT:optional text]"
I tried this:
y=re.compile(r'\[PROMPT:.*\]')
Which works fine when the text is exactly "[PROMPT:whatever]" but
does not match on:
   "something [PROMPT:foo] something [PROMPT:bar] something ..."
The overall goal is to identify the beginning and end of each [PROMPT...]
string in the line.
Ideas anyone?
If I understand correctly, this is what you are trying to achieve:
>>> import re
>>> temp = "something [PROMPT:foo] something [PROMPT:bar] something ..."
>>> prompt_re = re.compile(r"\[PROMPT:.*?\]")
>>> prompt_re.findall(temp)
['[PROMPT:foo]', '[PROMPT:bar]']
>>>
HTH,
--
Orlando
--
http://mail.python.org/mailman/listinfo/python-list


Textual markup languages (was Re: What YAML engine do you use?)

2005-01-23 Thread Alan Kennedy
[Effbot]
ReST and YAML share the same deep flaw: both formats are marketed
as simple, readable formats, and at a first glance, they look simple and read-
able -- but in reality, they're messy as hell, and chances are that the thing
you're looking at doesn't really mean what you think it means (unless you're
the official ReST/YAML parser implementation).  experienced designers
know how to avoid that; the ReST/YAML designers don't even understand
why they should.
I'm looking for a good textual markup language at the moment, for 
capturing web and similar textual content.

I don't want to use XML for this particular usage, because this content 
will be entered through a web interface, and I don't want to force users 
through multiple rounds of 
submit/check-syntax/generate-error-report/re-submit in order to enter 
their content.

I have no strong feelings about YAML: If I want to structured data, e.g. 
lists, dictionaries, etc, I just use python.

However, I'm torn on whether to use ReST for textual content. On the one 
hand, it's looks pretty comprehensive and solidly implemented. But OTOH, 
I'm concerned about complexity: I don't want to commit to ReST if it's 
going to become a lot of hard work or highly-inefficient when I really 
need to use it "in anger".

From what I've seen, pretty much every textual markup targetted for web 
content, e.g. wiki markup, seems to have grown/evolved organically, 
meaning that it is either underpowered or overpowered, full of special 
cases, doesn't have a meaningful object model, etc.

So, I'm hoping that the learned folks here might be able to give me some 
pointers to a markup language that has the following characteristics

1. Is straightforward for non-technical users to use, i.e. can be 
(mostly) explained in a two to three page document which is 
comprehensible to anyone who has ever used a simple word-processor or 
text-editor.

2. Allows a wide variety of content semantics to be represented, e.g. 
headings, footnotes, sub/superscript, links, etc, etc.

3. Has a complete (but preferably lightweight) object model into which 
documents can be loaded, for transformation to other languages.

4. Is speed and memory efficient.
5. Obviously, has a solid python implementation.
Most useful would be a pointer to a good comparison/review page which 
compares multiple markup languages, in terms of the above requirements.

If I can't find such a markup language, then I might instead end up 
using a WYSIWYG editing component that gives the user a GUI and 
generates (x)html.

htmlArea: http://www.htmlarea.com/
Editlet:  http://www.editlet.com/
But I'd prefer a markup solution.
TIA for any pointers.
regards,
--
alan kennedy
--
email alan:  http://xhaus.com/contact/alan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Insanity

2005-01-23 Thread Fredrik Lundh
Tim Daneliuk wrote:

> Thanks - very helpful.  One followup - your re works as advertised.  But
> if I use: r'\[PROMPT:[^]].*\]'  it seems not to.  the '.*' instead of just '*'
> it matches the entire string ...

it's not "just '*'", it's "[^]]*".  it's the "^]" set (anything but ]) that's 
repeated.

"[^]].*\]" means match a single non-] character, and then match as many
characters as you possibly can, as long as the next character is a ].

"[^]]*\]" means match as many non-] characters as possible, plus a single ].

> which seems counterintutive to me.

then you need to study RE:s a bit more.

(hint: an RE isn't a template, it's a language description, and the RE engine
is designed to answer the question "does this string belong to this language"
(for match) or "is there any substring in this string that belongs to this
language" (for search) as quickly as possible.  things like match locations
etc are side effects).

 



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


Re: finding name of instances created

2005-01-23 Thread André

Nick Coghlan wrote:
> André wrote:
> > So, students will be able to write:
> > pete = CreateRobot(2, 3)
> > pete.move()
> >
> > learning about objects and methods.
> >
> > As for things like
> > for robot in robots:
> > do stuff
> >
> > that will be for my use only: drawing robots on the screen,
updating
> > the 'world' when robots pick stuff up, etc.  My intention is that
the
> > students will use the EXACT python syntax, so that they don't know
that
> > *I* have given a *name* to their robot(s) behind the scene.
> > I have to cut this short; I hope it clarifies my intentions.
>
> My (and, if I understand him correctly, Jeremy's) concern would be
that error
> messages like "Robot 'pete' has hit a wall!" would give students the
impression
> that the robots automatically know their name as a result of the
assignment. In
> standard Python, that simply isn't true.
>

It was not my intention to reveal that I had assigned a 'name' to the
robot; it was only for internal purpose.(However, see below)

> If, instead, CreateRobot looked something like:
>
> def CreateRobot(street, avenue, name=None):
>if name is None:
>  name = "Robot" + Robot.getNextNumber()
>return Robot(street, avenue, name)
>
>
> Then, using a simple assignment:
>
> pete = CreateRobot(2, 3)
> pete.move()
>
> Would give an error like:
>
> "Robot1 has hit a wall"

That might be an excellent way to solve my problem.

>
> This could then be used to point out that objects named using
assignment don't
> know about the names they have been given, and need to be told:
>
> pete = CreateRobot(2, 3, "Pete")
> pete.move()
>
> "Pete has hit a wall"
>
> Instead of misleading the students ("objects know what names they
have been
> given"), you have taught them a powerful truth - objects and the
names you give
> them via assignment are entirely independent.

Good point.

>
> It also directly addresses the question of aliasing. Think about how
Steven's
> modified dictionary would react to this code:
>
> pete = CreateRobot(2, 3)
> dad = pete
> dad.move()
> pete.move()
>
> Internally, idioms like "for robot in robots" should be entirely
unaffected -
> the registration of the robot instance with the global list of robots
can be
> handled by the robot initialisation method.
>

You make some excellent points.  What I implemented (last night) was
the "code pre-processing" suggestion.  Instead of simply "exec"uting
the code, I changed it first so that statements like

pete = CreateRobot(2, 3)
john = CreateRobot()
albert = CreateRobot(colour="blue")

get translated to

pete = CreateRobot(2, 3, name="pete")
john = CreateRobot(name="john")
albert = CreateRobot(colour="blue", name="albert")

I just checked with:

pete = CreateRobot()
dad = pete
dad.move()
pete.move()

and I got (I haven't implemented the gui part of dealing with multiple
robots)
==
robot pete move()
robot pete move()
==
which worked the same way as your method would (except with "pete" as a
common name instead of "Robot1").

[As an aside, it was an *interesting* experience to learn enough about
regular expressions to do this.]

Now, after reading your post, I realise that I would have to deal with
the problem of figuring out how to handle cases where the users has
already given a name to the robot.  Your solution takes care of this in
a very simple way.

Furthermore, I could probably base a lesson around it, about how
instances have no name.
Thank you very much for your suggestions.

André

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


Re: Textual markup languages (was Re: What YAML engine do you use?)

2005-01-23 Thread Paul Rubin
Alan Kennedy <[EMAIL PROTECTED]> writes:
> However, I'm torn on whether to use ReST for textual content. On the
> one hand, it's looks pretty comprehensive and solidly implemented.

It seemed both unnecessary and horrendously overcomplicated when I
looked at it.  I'd stay away.

> So, I'm hoping that the learned folks here might be able to give me
> some pointers to a markup language that has the following
> characteristics

I'm a bit biased but I've been using Texinfo for a long time and have
been happy with it.  It's reasonably lightweight to implement, fairly
intuitive to use, and doesn't get in the way too much when you're
writing.  There are several implementations, none in Python at the
moment but that would be simple enough.  It does all the content
semantics you're asking (footnotes etc).  It doesn't have an explicit
object model, but is straightforward to convert into a number of
formats including high-quality printed docs (TeX); the original Info
hypertext browser that predates the web; and these days HTML.

> If I can't find such a markup language, then I might instead end up
> using a WYSIWYG editing component that gives the user a GUI and
> generates (x)html  But I'd prefer a markup solution.

Yes, for heavy-duty users, markup is far superior to yet another
editor.  Everyone has their favorite editor and doesn't want to have
to switch to another one, hence the Emacs vs. Vi wars etc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Textual markup languages (was Re: What YAML engine do you use?)

2005-01-23 Thread Fredrik Lundh
Alan Kennedy wrote:

> From what I've seen, pretty much every textual markup targetted for web 
> content, e.g. wiki markup, 
> seems to have grown/evolved organically, meaning that it is either 
> underpowered or overpowered, 
> full of special cases, doesn't have a meaningful object model, etc.

I spent the eighties designing one textual markup language after another,
for a wide variety of projects (mainly for technical writing).  I've since come
to the conclusion that they all suck (for exactly the reasons you mention above,
plus the usual "the implementation is the only complete spec we have" issue).

these days, I usually use HTML+custom classes for authoring (and run them
through a HTML->XHTML converter for processing).

the only markup language I've seen lately that isn't a complete mess is John
Gruber's markdown:

http://daringfireball.net/projects/markdown/

which has an underlying object model (HTML/XHTML) and doesn't have too
many warts.  not sure if anyone has done a Python implementation yet, though
(for html->markdown, see http://www.aaronsw.com/2002/html2text/ ), and I
don't think it supports footnotes (HTML doesn't).

> If I can't find such a markup language, then I might instead end up using a 
> WYSIWYG editing 
> component that gives the user a GUI and generates (x)html.
>
> htmlArea: http://www.htmlarea.com/
> Editlet:  http://www.editlet.com/
>
> But I'd prefer a markup solution.

some of these are amazingly usable.  have you asked your users what they
prefer?  (or maybe you are your user? ;-)

 



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


Re: finding name of instances created

2005-01-23 Thread André

Scott David Daniels wrote:
> André Roberge wrote:
> > Craig Ringer wrote:
> >
> >> On Fri, 2005-01-21 at 16:13 -0800, André wrote:
> >>
> >>> Short version of what I am looking for:
> >>>
> >>> Given a class "public_class" which is instantiated a few times
e.g.
> >>>
> >>> a = public_class()
> >>> b = public_class()
> >>> c = public_class()
> >>>
> >>> I would like to find out the name of the instances so that I
could
> >>> create a list of them e.g.
> >>> ['a', 'b', 'c']
> >
> > ...
> > Behind the scene, I have something like:
> > robot_dict = { 'robot' = CreateRobot( ..., name = 'robot') }
> > and have mapped move() to correspond to robot_dict['robot'].move()
> > (which does lots of stuff behind the scene.)
> > ...[good explanation]...
>  > Does this clarify what I am trying to do and why?
>
> Yup.  Would something like this help?
>
>  parts = globals().copy()
>  parts.update(locals())
>  names = [name for name, value in parts.iteritems()
>   if isinstance(value, Robot)] # actual class name here
>
> Note, however, that
>
>  a = b = CreateRobot()
>
> will give two different names to the same robot.
>
> And even:
>
>  Karl = CreateRobot()
>  Freidrich = CreateRobot()
>  for robot in (Karl, Freidrich):
>  robot.move()
>
> Will have two names for "Freidrich" -- Freidrich and robot
>
> --Scott David Daniels

Thanks for your suggestion.
It might have been interesting to try, but I am going to
try and implement a suggestion given by Nick Coghlan instead.
André

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


Re: What YAML engine do you use?

2005-01-23 Thread Daniel Bickett
Doug Holton wrote:
> You might like programming in XML then: http://www.meta-language.net/
> :)

http://www.meta-language.net/sample.html#class-metal

I'm not so sure ;-)

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


compile python to binary

2005-01-23 Thread sam
Hi,
I have seen some software written in python and delivered as binary form.
How does these binary code get generated by python compiler?
Thanks
Sam.
--
http://mail.python.org/mailman/listinfo/python-list


Re: compile python to binary

2005-01-23 Thread Fredrik Lundh
"sam" <[EMAIL PROTECTED]> wrote:

> I have seen some software written in python and delivered as binary form.
>
> How does these binary code get generated by python compiler?

see section 6.1.2 in the tutorial:

http://docs.python.org/tut/node8.html

 



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


Alternative Ways to install Python 2.4?

2005-01-23 Thread Michael Goettsche
Hello guys,

I convinced my CS teacher to use Python in school. We currently have 2.2 
installed on a Windows 2000 Terminal server. I asked the system administrator 
to upgrade to Python 2.4, but he didn't succeed in doing it. He used the 
microsoft installer package, which according to him crashed when starting. 
So my question is if there's an alternative way to install it(must be easy). 
Would it be an option to remove 2.2 first and then try to install 2.4 again?

Sorry for asking, but he doesn't have so much time and I've to install it 
tomorrow.

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


Re: Reload Tricks

2005-01-23 Thread Kamilche
Well, I look forward to seeing the new version. I have the old version
of the Python cookbook, it was very useful!

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


is there better 32 clock() timing?

2005-01-23 Thread Ray Schumacher
I have a need for a time.clock() with >0.16 second (16us) accuracy.
The sleep() (on Python 2.3, Win32, at least) has a .001s limit.

Are they lower/better on other's platforms? 

Test code, 2.4GHz P4
Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32

import time
t0 = time.clock()
t1 = time.clock()
t2 = time.clock()
t3 = time.clock()
t4 = time.clock()
t5 = time.clock()
print (-t0+t5)/5.
print t1-t0
print t2-t1
print t3-t2
print t4-t3
print t5-t4

>>> 
ave 0.000342754564927
0.000321028401686
0.00030348379596
0.000297101358228
0.000295895991258

I had also considered forking a thread that would spin a loop checking 
time.clock() and firing the TTL pulse after the appropriate interval, but the 
real, ultimate resolution of time.clock() appears to be ~.00035s. If I increase 
process priority to real-time, it is ~.00028s
The alternative appears to be more C code...

Ray
BCI/Congitive Vision

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


Re: Reload Tricks

2005-01-23 Thread Alex Martelli
Kamilche <[EMAIL PROTECTED]> wrote:

> Well, I look forward to seeing the new version. I have the old version
> of the Python cookbook, it was very useful!

I hope the new one is even better -- many more recipes, all updated to
Python 2.3 and 2.4.  The old one will remain useful for all those who
need to keep using older versions of Python, though; to fit more recipes
in, the historical discussions of how you did things with Python 1.5.2,
1.6, 2.0 etc have been ruthlessly snipped...


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


Re: is there better 32 clock() timing?

2005-01-23 Thread Michael Hoffman
Ray Schumacher wrote:
I have a need for a time.clock() with >0.16 second (16us) accuracy.
The sleep() (on Python 2.3, Win32, at least) has a .001s limit.
Are they lower/better on other's platforms? 
The meaning of time.clock() is entirely different on other platforms. 
See the documentation. You could probably get a slight speedup by using 
"from time import clock" and then just clock().
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: is there better 32 clock() timing?

2005-01-23 Thread [EMAIL PROTECTED]
alternatively you could use the now() method of the datetime module, it
has a resolution of 1 microsecond

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


Re: how to write a tutorial

2005-01-23 Thread Dan Perl

"Xah Lee" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> the beginning two paragraphs should be deleted. Nobody gives a shit
> except a few smug academicians where the author wrote it for pleasing
> himself. For 99% of readers, it is incomprehensible and irrelevant.
>
> the first paragraph of 9.1 "A Word About Terminology" is epitome of
> masturbation. The entire 9.1 is not necessary.
>
> Large part of 9.2 "Python Scopes and Name Spaces" is again
> masturbatory.

This is a perfect description for your own postings.  Why don't you follow 
your own advice? 


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


ANN: eric3 3.6.0 released

2005-01-23 Thread Detlev Offenbach
Hi,

this is to let you know about a new release of eric3, the Python IDE. It
has a bunch of new functions. The most prominent ones are listed below.

- added some dialog wrappers that make eric3 use KDE dialogs, if KDE and
PyKDE are installed
- added a previewer for UI files
- added a previewer for translation files

- added a "Continue to cursor" command to the debugger
- added view profiles and a correspondig configuration dialog
- added capability to show the coverage annotations in the editor
- added capability to select the protocol of the VCS server at login time
- added support for alternative keyboard shortcuts
- changed variables viewer to keep the state of the tree while debugging
- added multiple selection capabilities to the browsers
- added capability to enter variables filter patterns to the variables
viewer windows
- added an icon previewer to the configuration dialog icons page

and some more little things.

It is available via http://www.die-offenbachs.de/detlev/eric3.html

I hope you enjoy it.

What is eric3
-
eric3 is Python IDE written using the PyQt wrappers. If the PyKDE
wrappers are installed as well, it will work as a KDE application and
use KDE dialogs. It has a built in debugger, profiler, help viewer,
unlimited number of editors with syntax highlighting, autocompletion and
many more. Eric3 interfaces to CVS and subversion and has a built in
documentation generation facility. For all the other details and
snapshots please see the above URL.

Regards,
Detlev
-- 
Detlev Offenbach
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


PSE : Python Servlet Engine configuration

2005-01-23 Thread salvatore
Hello,
Is there someone who use PSE ?
I have a strange problem, i don't see how pse.conf
is managed.
Indeed althoug I make modifications on it nothind is take
in account.
I have also erases it !!! and PSE doesn't claim anything !!!
Can someone help me ?
Regards
Salvatore
--
http://mail.python.org/mailman/listinfo/python-list


Re: is there better 32 clock() timing?

2005-01-23 Thread Paul Rubin
Ray Schumacher <[EMAIL PROTECTED]> writes:
> I have a need for a time.clock() with >0.16 second (16us) accuracy.
> The sleep() (on Python 2.3, Win32, at least) has a .001s limit.
> 
> Are they lower/better on other's platforms? 
> 
> The alternative appears to be more C code...

C code is your best bet.  The highest resolution timer on x86's these
days is the Pentium RTDSC instruction which counts the number of cpu
cycles since power-on.  There's various C routines floating around
that let you access that instruction.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to write a tutorial

2005-01-23 Thread Daniel Bickett
> Most texts in computing are written by authors to defend and showcase
> their existence against their peers.

When you aren't busy `showcasing' your ignorance, this is *all* i see
in everything you write.

> In a tutorial, nobody cares how
> the language compared to x y and z, or what technicality is it all
> about, or some humorous snippet of history only funny to the author
> himself.

You couldn't be farther from the truth. To preface a document by
illustrating it's similarities to other languages is to better prepare
a reader who may have experience in those languages. As for the
snippet of history, few people desire to live life as cynical as you
do, and one would hope even fewer take their own opinion and assume it
applies to their peers, as you have just done.

> Particularly for texts in a tutorial context, you want to write it as
> simple as possible covering the most useful basic functionalities and
> concepts, and self-contained. Not showcasing your knowledge of history
> of languages or your linguistic lineage byways.

You of all people are the least qualified to say this, as you are the
most guilty of such a crime.

> For example this chapter 9 on Objects, it is not difficult to write it
> without making a show of lingoes. One simply write what is of Python,
> without thinking about relation to xyz languages or the "computer
> science" establishment and their ways of thinkings of namespaces and
> scopes and dynamic and statics and inheritances ... fucking bags of
> shit.

Then please be so kind as to give us all a pleasant surprise, and take
the place of the productive reformer rather than the angsty
criticizer. Your vision as to the errors in the tutorial is *clearly*
less clouded than ours, so only *you* are in the position to write the
proper replacement.

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


ANN: cElementTree 0.9.8 (january 23, 2005)

2005-01-23 Thread Fredrik Lundh
effbot.org proudly presents release 0.9.8 of the cElementTree library,
a fast and very efficient implementation of the ElementTree API, for
Python 2.1 and later.  On typical documents, it's 15-20 times faster
than the Python version of ElementTree, and uses 2-5 times less
memory.

Here are some benchmark figures, using a number of popular XML tool-
kits to parse a 3405k document-style XML file from disk:

library memory  time

amara   20300k  6.4s
minidom (python 2.4)53000k  1.4s
ElementTree 1.2.4   14500k  1.1s
cDomlette   20500k  0.54s
pyRXPU  10850k  0.175s
libxml2 16000k  0.098s
cElementTree 0.9 4900k  0.047s

readlines (read as utf-8)8850k  0.093s
readlines (read as ascii)5050k  0.032s


This release also includes a new "iterparse" mechanism, which can be
used to process the tree as it is being built.  While not quite as
fast as a full parse, it's over 4 times faster than Python's standard
SAX interface, and even a bit faster than sgmlop.

The library is available as C source code, and as Windows installers
for all recent Python versions.  Get your copy here:

http://effbot.org/downloads#celementtree

The cElementTree module uses some support functions from the standard
ElementTree library, and will not work properly without it.  If you
haven't installed it already, you can get it from:

http://effbot.org/downloads#elementtree

enjoy /F

"effbot.org -- not knowing how Python is used since 1995" 



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


Re: compile python to binary

2005-01-23 Thread Daniel Bickett
Fredrik Lundh wrote:
> see section 6.1.2 in the tutorial:
> [snip]

I believe Sam was talking about "frozen" python scripts using tools
such as py2exe:

http://starship.python.net/crew/theller/py2exe/

As to how the actual process works, I'm not qualified to answer
(having only read an article in the linux magazine,) but I hope this
helps.

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


best way to do a series of regexp checks with groups

2005-01-23 Thread Mark Fanty
In perl, I might do (made up example just to illustrate the point):

if(/add (\d+) (\d+)/) {
  do_add($1, $2);
} elsif (/mult (\d+) (\d+)/) {
  do_mult($1,$2);
} elsif(/help (\w+)/) {
  show_help($1);
}

or even

do_add($1,$2) if /add (\d+) (\d+)/;
do_mult($1,$2) if /mult (\d+) (\d+)/;
show_help($1) if /help (\w+)/;

How can I best do this in pyhon?  Attempt 1:

m = re.search(r'add (\d+) (\d+)', $line)
if m:
do_add(m.group(1), m.group(2))
else:
m = re.search(r'mult (\d+) (\d+)', $line)
if m:
do_mult(m.group(1), m.group(2))
else:
m = re.search(r'help (\w+)', $line)
show_help(m.group(1))

The increasing nesting is a problem.  I could put them in a while loop just 
so I can use break

while 1:
m = re.search(r'add (\d+) (\d+)', $line)
if m:
do_add(m.group(1), m.group(2))
break
m = re.search(r'mult (\d+) (\d+)', $line)
if m:
do_mult(m.group(1), m.group(2))
break
m = re.search(r'help (\w+)', $line)
if m:
show_help(m.group(1))
break

No nesting, but the while is misleading since I'm not looping and this is a 
bit awkward.  I don't mind a few more key strokes, but I'd like clarity.  I 
wish I could do

if m =  re.search(r'add (\d+) (\d+)', $line):
do_add(m.group(1), m.group(2))
elif m = re.search(r'mult (\d+) (\d+)', $line):
do_mult(m.group(1), m.group(2))
else m = re.search(r'help (\w+)', $line):
show_help(m.group(1))

Now that's what I'm looking for, but I can't put the assignment in an 
expression.  Any recommendations?  Less "tricky" is better.  Not having to 
import some personal module with a def to help would be better (e.g. for 
sharing)..

Thanks


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


Re: compile python to binary

2005-01-23 Thread Daniel Bickett
Fredrik Lundh wrote:
> oh, you mean that "python compiler" didn't mean "the python compiler".
> [snip]

I simply inferred that he was using the wrong terminology, being that
he said "binary" twice ;-)

sam wrote:
> I have seen some software written in python and delivered as binary form.
>
> How does these binary code get generated by python compiler?

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


Re: File objects? - under the hood question

2005-01-23 Thread EP
 
> My brain-teaser:  What I'd like to do is read the last ~2K of a large 
> number of large files on arbitrary servers across the net, without 
> having to read each file from the beginning (which would be slow and 
> resource inefficient)...
> 

Proper googling would have revealed that HTTP 1.1 includes a Range Request.  My 
bad.

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

Before I reinvent the wheel (and make it a little squarer than it has to be) 
has anyone seen a "cookbook" recipe for adding the HTTP 1.1 range request to a 
urllib urlopener (or something similar)?

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


Have you heard the GOOD NEWS?

2005-01-23 Thread google_groups_usa
http://www3.boxke.net << click link for the good news

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


Re: File objects? - under the hood question

2005-01-23 Thread Jeremy Bowers
On Sun, 23 Jan 2005 08:27:49 -0800, EP wrote:

> 
>> My brain-teaser:  What I'd like to do is read the last ~2K of a large
>> number of large files on arbitrary servers across the net, without
>> having to read each file from the beginning (which would be slow and
>> resource inefficient)...
>> 
>> 
> Proper googling would have revealed that HTTP 1.1 includes a Range
> Request.  My bad.
> 
> http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
> 
> Before I reinvent the wheel (and make it a little squarer than it has to
> be) has anyone seen a "cookbook" recipe for adding the HTTP 1.1 range
> request to a urllib urlopener (or something similar)?

I posted a followup already to your previous message, I just changed the
subject since it no longer applied, and it is the type of thing one would
google for. (Those need proper subjects.) See: "Retrieving the last bit
Re: File objects? - under the hood question".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: debugging xmlrpc servers

2005-01-23 Thread alan dot ezust at gmail dot com
Understandable - i had difficulties understanding my problem too!

I don't really understand why I got that error message before - I
believe it was due to the fact that some other exception was being
raised inside results().

Anyway, the solution was to call rpdb.set_trace() inside the actual
method which was being called by xmlrpc, and setting the breakpoint to
be the statement following that line (rather than the function itself).
cheers --alan

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


Re: What YAML engine do you use?

2005-01-23 Thread rm
rm wrote:
Paul Rubin wrote:
Reinhold Birkenfeld <[EMAIL PROTECTED]> writes:
For those of you who don't know what YAML is: visit http://yaml.org/!
You will be amazed, and never think of XML again. Well, almost.

Oh please no, not another one of these.  We really really don't need it.

well, I did look at it, and as a text format is more readable than XML 
is. Furthermore, XML's verbosity is incredible. This format is not.
People are abusing the genericity of XML to put everything into it.

Parsing and working with XML are highly optimized, so there's not really 
a problem in that sector. But to transfer the same data in a YAML 
format, rather than a XML format is much more economic. But networks are 
getting faster, right?

Nowadays, people are trying to create binary XML, XML databases, 
graphics in XML (btw, I'm quite impressed by SVG), you have XSLT, you 
have XSL-FO, ... .

And I think, YAML is a nice initiative.
bye,
rm
http://www.theinquirer.net/?article=20868 :-)
rm
--
http://mail.python.org/mailman/listinfo/python-list


Re: list unpack trick?

2005-01-23 Thread aurora
On Sat, 22 Jan 2005 10:03:27 -0800, aurora <[EMAIL PROTECTED]> wrote:
I am think more in the line of string.ljust(). So if we have a  
list.ljust(length, filler), we can do something like

   name, value = s.split('=',1).ljust(2,'')
I can always break it down into multiple lines. The good thing about  
list unpacking is its a really compact and obvious syntax.
Just to clarify the ljust() is a feature wish, probably should be named  
something like pad().

Also there is another thread a few hours before this asking about  
essentially the same thing.

"default value in a list"
http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/f3affefdb4272270
--
http://mail.python.org/mailman/listinfo/python-list


Dr. Dobb's Python-URL! - weekly Python news and links (Jan 23)

2005-01-23 Thread Josiah Carlson
QOTW:  "XML with elementtree is what makes me never have [to] think about
XML again." -- Istvan Albert

"'Plays well with others' was a strong motivator for Python's design, and
that often means playing by others' rules." -- Tim Peters


Type mutability, and why some types are immutable.  This has been
discussed before, and should be a FAQ topic (if it isn't already):

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/f05c9cbb7e58db9b
http://www.python.org/tim_one/000195.html

Caching instances of classes for reuse:

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

Storing data in a persistant fashion.  One link discussing concurrency,
the other discussing data storage mechanisms.  A link to PyTables as a
way of storing and indexing large amounts of data, and the announcement
for Dejavu 1.3, which also stores persistant data:

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

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/7f2849d3099abfdc
http://pytables.sourceforge.net/html/WelcomePage.html

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

So, you want to use SFTP in Python?  Paramiko is the answer (or so I read):

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/e95e8482c023fe25
http://www.lag.net/paramiko/

Circular iteration, or any strange iteration tasks?  Try itertools!

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

What do PyChecker and Pylint have to do with each other?
Are they configurable?  And do *you* know a half-dozen 
distinct formats for printing a multi-line text?

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

Jeremy Bowers and Dan Stromberg know that some applications
should do the right thing, whether they happen to have a
bit-mapped user interface at run time or not:

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

The Bangalore Python Meetup first convened on 22 January 2005:
http://python.meetup.com/158/events/?eventId=3974233&action=pastdetail

Why generator expressions sometimes don't beat list comprehensions, and
fitting Python to requirements.  Let not the anti-functional fashion
obscure that filter() still sometimes makes for better coding than the
comparable list comprehension:

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

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

Security is hard.  Even the narrow aspect of cryptography is
hard, if only for the complication state politics makes of the
mathematics and engineering involved.  Paul Rubin, Nick Craig-
Wood, and others present a few details:

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

No, really--Python does *that*, too.  Although many people
regard hardware interfacing, and its associated bit-twiddling,
as outside Python's purview, they're ... wrong.  See for 
yourself how Python makes for *clearer* codings than C or
Java or Assembler or ...:

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


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

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

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

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

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

Brett Cannon continues the marvelous tradition established by 
Andrew Kuchling and Michael Hudson of intelligently summarizing
action on the python-dev mailing list once every other week.
http://www.python.org/dev/summary/

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

The somewhat older Vaults of Parnassus ambitiously collects refe

Re: best way to do a series of regexp checks with groups

2005-01-23 Thread [EMAIL PROTECTED]
what about something like this?
>>> import re
>>> m = re.match(r"""(?Padd|mult) (?P\d+)
(?P\d+)""", 'add 3 5')
>>> from operator import add, mul
>>> op = {'add': add, 'mult: mul}
>>> op[m.groupdict()['operator']](int(m.groupdict()['int_1']),
int(m.groupdict()['int_2']))
8

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


Re: compile python to binary

2005-01-23 Thread Fredrik Lundh
Daniel Bickett wrote:

> I believe Sam was talking about "frozen" python scripts using tools
> such as py2exe:

oh, you mean that "python compiler" didn't mean "the python compiler".

here are links to some more tools, btw:

http://effbot.org/zone/python-compile.htm

 



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


Re: how to write a tutorial

2005-01-23 Thread Hans Nowak
Xah Lee wrote:
the first paragraph of 9.1 "A Word About Terminology" is epitome of
masturbation. The entire 9.1 is not necessary.
Large part of 9.2 "Python Scopes and Name Spaces" is again
masturbatory.
So I can just take a copy of the tutorial to the bathroom next time. 
Thanks for the tip, man!

--
Hans Nowak
http://zephyrfalcon.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: compile python to binary

2005-01-23 Thread Doug Holton
Fredrik Lundh wrote:
Daniel Bickett wrote:

I believe Sam was talking about "frozen" python scripts using tools
such as py2exe:

oh, you mean that "python compiler" didn't mean "the python compiler".
I wouldn't assume a novice uses terms the same way you would.  It was 
quite clear from his message that py2exe and the like were what he was 
referring to, if you had read his first sentence:

"I have seen some software written in python and delivered as binary form."
--
http://mail.python.org/mailman/listinfo/python-list


What is print? A function?

2005-01-23 Thread Frans Englich

Nah, I don't think it's a function, but rather a builtin "statement". But it's 
possible to invoke it as an function; print( "test" ) works fine.

So I wonder, what _is_ exactly the print statement? The untraditional way of 
invoking it(without paranteses) makes me wonder.

The reason I thinks about this is I need to implement a debug print for my 
program; very simple, a function/print statement that conditionally prints 
its message whether a bool is true. Not overly complex.

I tried this by overshadowing the print keyword, but that obviously didn't 
work.. Is defining a two-liner function the right way to go, or is there 
better ways to approach it?


Cheers,

Frans








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


Re: What is print? A function?

2005-01-23 Thread Fredrik Lundh
Frans Englich wrote:

> Nah, I don't think it's a function, but rather a builtin "statement". But it's
> possible to invoke it as an function; print( "test" ) works fine.
>
> So I wonder, what _is_ exactly the print statement? The untraditional way of
> invoking it(without paranteses) makes me wonder.

it's a statement.  (expr) is an expression (in parenthesis), so when you
type

print("test")

python sees:

print ("test")

(see the language reference for details)

> The reason I thinks about this is I need to implement a debug print for my
> program; very simple, a function/print statement that conditionally prints
> its message whether a bool is true. Not overly complex.
>
> I tried this by overshadowing the print keyword, but that obviously didn't
> work.. Is defining a two-liner function the right way to go

yup.  something like this might be useful:

def printif(cond, fmt, *args):
if cond: print fmt % args

 



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


Re: What is print? A function?

2005-01-23 Thread Michael Hoffman
Frans Englich wrote:
Nah, I don't think it's a function, but rather a builtin "statement". But it's 
possible to invoke it as an function; print( "test" ) works fine.
That is not invoking it as a function. The parentheses are only for 
ordering the expression on the right

You can do this too:
>>> print("abc"),("def"),("ghi")
abc def ghi
So I wonder, what _is_ exactly the print statement?
Uh, a statement.
The reason I thinks about this is I need to implement a debug print for my 
program; very simple, a function/print statement that conditionally prints 
its message whether a bool is true. Not overly complex.

I tried this by overshadowing the print keyword, but that obviously didn't 
work.. Is defining a two-liner function the right way to go, or is there 
better ways to approach it?
In the long run, you might want to look into the logging module. In the 
short run:

def _debug_true(text):
print >>sys.stderr, text
def _debug_false(text):
pass
if command_line_debug_option:
debug = _debug_true
else
debug = _debug_false
That way you only have to check whether the option is true once in the 
entire run of your program, not every time you call the debug() function 
(which is presumably many times).
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is print? A function?

2005-01-23 Thread Fredrik Lundh
>> The reason I thinks about this is I need to implement a debug print for my
>> program; very simple, a function/print statement that conditionally prints
>> its message whether a bool is true. Not overly complex.
>>
>> I tried this by overshadowing the print keyword, but that obviously didn't
>> work.. Is defining a two-liner function the right way to go
>
> yup.  something like this might be useful:
>
>def printif(cond, fmt, *args):
>if cond: print fmt % args

or, perhaps more useful in your case:

if my_debug_flag:
def debug(fmt, *args):
print fmt % args
else:
def debug(*args): pass

debug("hello!")
debug("the value is %d", value)

 



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


Re: What is print? A function?

2005-01-23 Thread Frans Englich
On Sunday 23 January 2005 18:04, Michael Hoffman wrote:
> Frans Englich wrote:
[...]
> if command_line_debug_option:
>  debug = _debug_true
> else
>  debug = _debug_false

I find this a nice solution. The most practical would be if it was possible to 
do this with print, of course. But print won't budge.

Is it possible to create own statements, such that it would be possible to do:

printDebug "test"

?


Cheers,

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


on the way to find pi!

2005-01-23 Thread Ali Polatel

dear friends ,
I found a code which calculates pi with an interesting algorithm the programme code is below:
from sys import stdout
def f((q,r,t,k)):    n = (3*q+r) / t    if (4*q+r) / t == n:    return (10*q,10*(r-n*t),t,k,n)    else:    return (q*k, q*(4*k+2)+r*(2*k+1),t*(2*k+1),k+1)
# Call pi(20) for first 20 digits, or pi() for all digitsdef pi(n=-1):    printed_decimal = False    r = f((1,0,1,1))    while n != 0:    if len(r) == 5:    stdout.write(str(r[4]))    if not printed_decimal:    stdout.write('.')    printed_decimal = True    n -= 1    r = f(r[:4])    #stdout.write('\n')
if __name__ == '__main__':    from sys import argv    try:    digit_count = long(argv[1])    except:    digit_count=int(raw_input('How many digits? :'))    pi(digit_count)    
This code gives the number in an unusual format like "3.1415'None'" it has a number part and a string part . I want to seperate these from easc other but I couldn't manage. I mean when I try to turn it into string format then try to use things like [:4] or like that they don't work.Any idea how to seperate this 'None' from the number and make it a real normal number on which I can do operations like +1 -1 or like that :)
Regards__Do You Yahoo!?Tired of spam?  Yahoo! Mail has the best spam protection around http://mail.yahoo.com -- 
http://mail.python.org/mailman/listinfo/python-list

Re: What is print? A function?

2005-01-23 Thread Fredrik Lundh
Frans Englich wrote:

> I find this a nice solution. The most practical would be if it was possible to
> do this with print, of course. But print won't budge.

you can disable print, though:

class dev_null:
def write(self, text):
pass
sys.stdout = dev_null()

or pipe all print requests to a debug stream:

if my_debug_flag:
debug = sys.stdout
else:
debug = dev_null()

print >>debug, "hello"
print >>debug, "the value is", value

> Is it possible to create own statements, such that it would be possible to do:
>
> printDebug "test"

no.

 



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


Re: on the way to find pi!

2005-01-23 Thread Daniel Bickett
Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.pi
3.1415926535897931

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


Re: on the way to find pi!

2005-01-23 Thread Fredrik Lundh
Ali Polatel wrote:

> I found a code which calculates pi with an interesting algorithm the 
> programme code is below:

> [code snipped]

> This code gives the number in an unusual format like "3.1415'None'" it has
> a number part and a string part.

are you sure?

$ python pi.py
How many digits? :5
3.1415
$ python pi.py
How many digits? :10
3.141592653
$ python pi.py
How many digits? :20
3.1415926535897932384

> Any idea how to seperate this 'None' from the number and make it a real
> normal number on which I can do operations like +1 -1 or like that :)

what's the point of that?  the math module already contains pi with as many
decimals as you can put in a Python float:

$ python
>>> pi = 3.1415926535897932384
>>> pi
3.1415926535897931
>>> import math
>>> math.pi
3.1415926535897931
>>> pi = math.pi
True

 



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


Re: on the way to find pi!

2005-01-23 Thread Ali Polatel
that's just little near to pi... pi is so far away ;)__Do You Yahoo!?Tired of spam?  Yahoo! Mail has the best spam protection around http://mail.yahoo.com -- 
http://mail.python.org/mailman/listinfo/python-list

Re: on the way to find pi!

2005-01-23 Thread Ali Polatel
write the code type str(pi(5)) and see what I mean__Do You Yahoo!?Tired of spam?  Yahoo! Mail has the best spam protection around http://mail.yahoo.com -- 
http://mail.python.org/mailman/listinfo/python-list

OT: problems mirroring python-list to c.l.py?

2005-01-23 Thread Daniel Bickett
I'm not sure if it's just me (or, indeed, just google groups), but my
"python-list" folder (label, that is) in my gmail account looks less
and less similar to Google Groups' comp.lang.python with each day.

Not only that, c.l.py has been acting rather strange. Example that
happened just now: Ali Polatel mailed[1] (I'm assuming) the
python-list asking about pi. I responded, showing an interactive shell
snippet[2], however on Google Groups' c.l.py it created the thread[3]
as beginning with my post (undoubtedly causing confusion because mine
was an answer not a question).

Is there a reason that Google Groups isn't mirroring python-list
exactly like it used to, or is it simply a conspiracy I'm not in on?

perfectly-capable-of-conspiring-ly y'rs,
Daniel Bickett

NOTES:
[1] http://mail.python.org/pipermail/python-list/2005-January/261966.html
[2] http://mail.python.org/pipermail/python-list/2005-January/261968.html
[3] http://tinyurl.com/6tsec
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Textual markup languages (was Re: What YAML engine do you use?)

2005-01-23 Thread Alan Kennedy
[Alan Kennedy]
>> From what I've seen, pretty much every textual markup targetted
>> for web content, e.g. wiki markup, seems to have grown/evolved
>> organically, meaning that it is either underpowered or overpowered,
>> full of special cases, doesn't have a meaningful object model, etc.
[Fredrik Lundh]
> I spent the eighties designing one textual markup language after
> another, for a wide variety of projects (mainly for technical
> writing).  I've since come to the conclusion that they all suck
> (for exactly the reasons you mention above, plus the usual
> "the implementation is the only complete spec we have" issue).
Thanks Fredrik, I thought you might have a fair amount of experience in 
this area :-)

[Fredrik Lundh]
> the only markup language I've seen lately that isn't a complete mess
> is John Gruber's markdown:
>
> http://daringfireball.net/projects/markdown/
>
> which has an underlying object model (HTML/XHTML) and doesn't have
> too many warts.  not sure if anyone has done a Python implementation
> yet, though (for html->markdown, see
> http://www.aaronsw.com/2002/html2text/ ), and I don't think it
> supports footnotes (HTML doesn't).
Thanks for the pointer. I took a look at Markdown, and it does look 
nice. But I don't like the dual syntax, e.g. switching into HTML for 
tables, etc: I'm concerned that the syntax switch might be too much for 
non-techies.

[Alan Kennedy]
>> If I can't find such a markup language, then I might instead end up
>> using a WYSIWYG editing component that gives the user a GUI and
>> generates (x)html.
>>
>> htmlArea: http://www.htmlarea.com/
>> Editlet:  http://www.editlet.com/
>>
>> But I'd prefer a markup solution.
[Fredrik Lundh]
> some of these are amazingly usable.  have you asked your users what
> they prefer?  (or maybe you are your user? ;-)
Actually, I'm looking for a solution for both myself and for end-users 
(who will take what they're given ;-).

For myself, I think I'll end up picking Markdown, ReST, or something 
comparable from the wiki-wiki-world.

For the end-users, I'm starting to think that GUI is the only way to go. 
The last time I looked at this area, a few years ago, the components 
were fairly immature and pretty buggy. But the number of such components 
and their quality seems to have greatly increased in recent times.

Particularly, many of them seem to address an important requirement that 
I neglected to mention in my original list: unicode support. I'll be 
processing all kinds of funny characters, e.g. math/scientific symbols, 
european, asian and middle-eastern names, etc.

thanks-and-regards-ly-y'rs,
--
alan kennedy
--
email alan:  http://xhaus.com/contact/alan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Textual markup languages (was Re: What YAML engine do you use?)

2005-01-23 Thread Alan Kennedy
[Alan Kennedy]
>>So, I'm hoping that the learned folks here might be able to give me
>>some pointers to a markup language that has the following
>>characteristics
[Paul Rubin]
> I'm a bit biased but I've been using Texinfo for a long time and have
> been happy with it.  It's reasonably lightweight to implement, fairly
> intuitive to use, and doesn't get in the way too much when you're
> writing.  There are several implementations, none in Python at the
> moment but that would be simple enough.  It does all the content
> semantics you're asking (footnotes etc).  It doesn't have an explicit
> object model, but is straightforward to convert into a number of
> formats including high-quality printed docs (TeX); the original Info
> hypertext browser that predates the web; and these days HTML.
Thanks Paul,
I took a look at texinfo, and it looks powerful and good ... for 
programmers.

Looks like a very steep learning curve for non-programmers though. It 
seems to require just a few hundred kilobytes too much documentation ..

regards,
--
alan kennedy
--
email alan:  http://xhaus.com/contact/alan
--
http://mail.python.org/mailman/listinfo/python-list


Re: on the way to find pi!

2005-01-23 Thread Fredrik Lundh
Ali Polatel wrote:

> write the code type str(pi(5)) and see what I mean

it helps if you post the code you want help with in your first post,
so people don't have to guess.

the pi function doesn't return anything, it prints the value to stdout
(that's what the stdout.write things are doing).

if a function doesn't return anything, Python automagically inserts
a "return None", which explains the "None" you're seeing (well, it
prints 3.1415None after your modification, so you probably did
something else to get "3.1415'None'").

if you want the digits, you have to change the stdout.write calls to
something else.  say:

def pi(n=-1):
output = ""
printed_decimal = False
r = f((1,0,1,1))
while n != 0:
if len(r) == 5:
output += str(r[4])
if not printed_decimal:
output += '.'
printed_decimal = True
n -= 1
r = f(r[:4])
return output

(this returns a string.  to convert it to a Python float, use float(pi(x)).  if 
x is
large enough, that gives you the same thing as math.pi).

 



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


Re: OT: problems mirroring python-list to c.l.py?

2005-01-23 Thread Steve Holden
Daniel Bickett wrote:
John Lenton wrote:
On Sun, Jan 23, 2005 at 01:53:52PM -0500, Daniel Bickett wrote:
Is there a reason that Google Groups isn't mirroring python-list
exactly like it used to, or is it simply a conspiracy I'm not in on?
You should not ask this kind of question in a public forum,
and *you* should know better than to go around flapping your mouth
like that.

Now I'm further confused, because I don't know what you quoted, but it
isn't on the mailing list and it isn't on c.l.py :) Maybe I should
give up trying to figure these things out.
You didn't include a name at the beginning of your citation... Who had
the audacity to take my joke seriously? ;-)
Daniel Bickett
It is well known tha the PSU ha
--
http://mail.python.org/mailman/listinfo/python-list


Re: specifying constants for a function (WAS: generator expressions: performance anomaly?)

2005-01-23 Thread Steven Bethard
Nick Coghlan wrote:
Steven Bethard wrote:
I wrote:
 > If you really want locals that don't contribute to arguments, I'd be
 > much happier with something like a decorator, e.g.[1]:
 >
 > @with_consts(i=1, deftime=time.ctime())
 > def foo(x, y=123, *args, **kw):
 >return x*y, kw.get('which_time')=='now' and time.ctime() or deftime
 >
 > Then you don't have to mix parameter declarations with locals
 > definitions.
 >
 > Steve
 >
 > [1] I have no idea how implementable such a decorator would be.  I'd
 > just like to see function constants declared separate from arguments
 > since they mean such different things.
I played around with this, and I think it's basically implementable:

Raymond's constant binding decorator is probably a good model for how to 
do it:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940
Yeah, I thought about this recipe, but opcodes always scare me too much. ;)
Steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: OT: problems mirroring python-list to c.l.py?

2005-01-23 Thread John Lenton
> On Sun, Jan 23, 2005 at 01:53:52PM -0500, Daniel Bickett wrote:
> > 
> > Is there a reason that Google Groups isn't mirroring python-list
> > exactly like it used to, or is it simply a conspiracy I'm not in on?
> 
> You should not ask this kind of question in a public forum,

and *you* should know better than to go around flapping your mouth
like that.

-- 
John Lenton ([EMAIL PROTECTED]) -- Random fortune:
Comer se ha de hacer en silencio, como los frailes en sus conventos. 


signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Help on project, anyone?

2005-01-23 Thread Georg Brandl
Hello,

to train my Python skills I am looking for some project I can contribute
to. I learned Python about one year ago, and had already some
programming background behind (I contributed to SharpDevelop for
instance), so I'm not the complete newbie.

About myself: I'm a 20 year old German with strong interests in
programming and, of course, especially in Python (I love it...).

Does anyone run, or participate in, a project looking for fellow
programmers? I don't have a special area of interest, well, perhaps web
programming...

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


Re: specifying constants for a function (WAS: generator expressions: performance anomaly?)

2005-01-23 Thread Steven Bethard
Bengt Richter wrote:
On Sat, 22 Jan 2005 16:22:33 +1000, Nick Coghlan <[EMAIL PROTECTED]> wrote:

Steven Bethard wrote:
I wrote:
> If you really want locals that don't contribute to arguments, I'd be
> much happier with something like a decorator, e.g.[1]:
>
> @with_consts(i=1, deftime=time.ctime())
> def foo(x, y=123, *args, **kw):
>return x*y, kw.get('which_time')=='now' and time.ctime() or deftime
>
> Then you don't have to mix parameter declarations with locals
> definitions.
>
> Steve
>
> [1] I have no idea how implementable such a decorator would be.  I'd
> just like to see function constants declared separate from arguments
> since they mean such different things.
I played around with this, and I think it's basically implementable:
Raymond's constant binding decorator is probably a good model for how to do 
it:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940

I thought so too. I modified it to accept **presets as a keyword argument
and generate constants and assignments from its values matching assignment names
when the rhs was __frompresets__, e.g.,
 >>> from makeconstpre import make_constants as pre
 >>> import time
 >>> @pre(verbose=True, deftime=time.ctime(), a=1, b=2, c=3, 
pi=__import__('math').pi)
 ... def foo():
 ... deftime = __frompresets__
 ... b, a = __frompresets__
 ... c = __frompresets__
 ... pi = __frompresets__
 ... return locals()
 ...
 __frompresets__ : deftime --> Sat Jan 22 20:18:09 2005
 __frompresets__ : ('b', 'a') --> (2, 1)
 __frompresets__ : c --> 3
 __frompresets__ : pi --> 3.14159265359
 locals --> 
Hmm... Having to state
deftime = __frompresets__
when you've already stated
deftime=time.ctime()
seems a little redundant to me...
Steve
--
http://mail.python.org/mailman/listinfo/python-list


Weekly Python Patch/Bug Summary

2005-01-23 Thread Kurt B. Kaiser
Patch / Bug Summary
___

Patches :  273 open ( +1) /  2746 closed ( +9) /  3019 total (+10)
Bugs:  797 open ( +4) /  4789 closed (+12) /  5586 total (+16)
RFE :  166 open ( +1) /   141 closed ( +0) /   307 total ( +1)

New / Reopened Patches
__

fix distutils.install.dump_dirs() with negated options  (2005-01-17)
CLOSED http://python.org/sf/1103844  opened by  Wummel

Add O_SHLOCK/O_EXLOCK to posix  (2005-01-17)
   http://python.org/sf/1103951  opened by  Skip Montanaro

setup.py --help and --help-commands altered.  (2005-01-17)
   http://python.org/sf/1104111  opened by  Titus Brown

new-style exceptions  (2005-01-18)
   http://python.org/sf/1104669  opened by  Michael Hudson

misc doc typos  (2005-01-18)
CLOSED http://python.org/sf/1104868  opened by  DSM

chr, ord, unichr documentation updates  (2004-10-31)
   http://python.org/sf/1057588  reopened by  mike_j_brown

Faster commonprefix in macpath, ntpath, etc.  (2005-01-19)
   http://python.org/sf/1105730  opened by  Jimmy Retzlaff

get rid of unbound methods (mostly)  (2005-01-17)
CLOSED http://python.org/sf/1103689  opened by  Guido van Rossum

Updated "Working on Cygwin" section  (2005-01-22)
   http://python.org/sf/1107221  opened by  Alan Green

Add Thread.isActive()  (2005-01-23)
   http://python.org/sf/1107656  opened by  Alan Green

Speed up function calls/can add more introspection info  (2005-01-23)
   http://python.org/sf/1107887  opened by  Neal Norwitz

Patches Closed
__

fix distutils.install.dump_dirs() with negated options  (2005-01-17)
   http://python.org/sf/1103844  closed by  theller

ast-branch: fix for coredump from new import grammar  (2005-01-11)
   http://python.org/sf/1100563  closed by  kbk

Shadow Password Support Module  (2002-07-10)
   http://python.org/sf/579435  closed by  loewis

misc doc typos  (2005-01-18)
   http://python.org/sf/1104868  closed by  fdrake

extending readline functionality  (2003-02-11)
   http://python.org/sf/684500  closed by  fdrake

self.button.pack() in tkinter.tex example  (2005-01-03)
   http://python.org/sf/1094815  closed by  fdrake

Clean up discussion of new C thread idiom  (2004-09-20)
   http://python.org/sf/1031233  closed by  fdrake

Description of args to IMAP4.store() in imaplib  (2004-12-12)
   http://python.org/sf/1084092  closed by  fdrake

get rid of unbound methods (mostly)  (2005-01-17)
   http://python.org/sf/1103689  closed by  gvanrossum

New / Reopened Bugs
___

email.base64MIME.header_encode vs RFC 1522  (2005-01-17)
   http://python.org/sf/1103926  opened by  Ucho

wishlist: os.feed_urandom(input)  (2005-01-17)
   http://python.org/sf/1104021  opened by  Zooko O'Whielacronx

configure doesn't set up CFLAGS properly  (2005-01-17)
   http://python.org/sf/1104249  opened by  Bryan O'Sullivan

Bugs in _csv module - lineterminator  (2004-11-24)
   http://python.org/sf/1072404  reopened by  fresh

Wrong expression with \w+?  (2005-01-18)
CLOSED http://python.org/sf/1104608  opened by  rengel

Bug in String rstrip method  (2005-01-18)
CLOSED http://python.org/sf/1104923  opened by  Rick Coupland

Undocumented implicit strip() in split(None) string method  (2005-01-19)
   http://python.org/sf/1105286  opened by  YoHell

Warnings in Python.h with gcc 4.0.0  (2005-01-19)
   http://python.org/sf/1105699  opened by  Bob Ippolito

incorrect constant names in curses window objects page  (2005-01-19)
   http://python.org/sf/1105706  opened by  dcrosta

null source chars handled oddly  (2005-01-19)
   http://python.org/sf/1105770  opened by  Reginald B. Charney

bug with idle's stdout when executing load_source  (2005-01-20)
   http://python.org/sf/1105950  opened by  imperialfists

os.stat int/float oddity  (2005-01-20)
CLOSED http://python.org/sf/1105998  opened by  George Yoshida

README of 2.4 source download says 2.4a3  (2005-01-20)
   http://python.org/sf/1106057  opened by  Roger Erens

semaphore errors from Python 2.3.x on AIX 5.2  (2005-01-20)
   http://python.org/sf/1106262  opened by  The Written Word

slightly easier way to debug from the exception handler  (2005-01-20)
   http://python.org/sf/1106316  opened by  Leonardo Rochael Almeida

os.makedirs() ignores mode parameter  (2005-01-21)
   http://python.org/sf/1106572  opened by  Andreas Jung

split() takes no keyword arguments  (2005-01-21)
   http://python.org/sf/1106694  opened by  Vinz

os.pathsep is wrong on Mac OS X  (2005-01-22)
CLOSED http://python.org/sf/1107258  opened by  Mac-arena the Bored Zo

Bugs Closed
___

--without-cxx flag of configure isn't documented.  (2003-03-12)
   http://python.org/sf/702147  closed by  bcannon

presentation typo in lib: 6.21.4.2 How callbacks are called  (2004-12-22)
   http://python.org/sf/1090139  closed by  gward

rfc822 Deprecated since release 2.3?  (2005-01-15)
   h

Re: re Insanity

2005-01-23 Thread Tim Daneliuk
Orlando Vazquez wrote:
Tim Daneliuk wrote:
For some reason, I am having the hardest time doing something that should
be obvious.  (Note time of posting ;)
Given an arbitrary string, I want to find each individual instance of
text in the form:  "[PROMPT:optional text]"
I tried this:
y=re.compile(r'\[PROMPT:.*\]')
Which works fine when the text is exactly "[PROMPT:whatever]" but
does not match on:
   "something [PROMPT:foo] something [PROMPT:bar] something ..."
The overall goal is to identify the beginning and end of each [PROMPT...]
string in the line.
Ideas anyone?

If I understand correctly, this is what you are trying to achieve:
 >>> import re
 >>> temp = "something [PROMPT:foo] something [PROMPT:bar] something ..."
 >>> prompt_re = re.compile(r"\[PROMPT:.*?\]")
 >>> prompt_re.findall(temp)
['[PROMPT:foo]', '[PROMPT:bar]']
 >>>
HTH,
--
Orlando
Yes - that seems to be the simplest solution to the problem.  I'd forgotten
entirely about non-greedy matching when I asked the question.  Thanks.
--

Tim Daneliuk [EMAIL PROTECTED]
PGP Key: http://www.tundraware.com/PGP/
--
http://mail.python.org/mailman/listinfo/python-list


bdb

2005-01-23 Thread jimbo
Hi,
I am trying to sort how to best programmatically run the debugger on a 
program, and another way that I am trying to explore is by using the 
bdb module. There isn't any documentation for this and I have tried 
reading through the source, which includes an example/test at the end 
of bdb.py on Python 2.3/OS X.

What I can't figure out is how this might work if you wanted to have 
the function 'step' through each line. I see various functions that 
suggest that they might be for this but I can not get anything to work. 
Has anyone any suggestions or point me in the direction of any other 
docs?

Thank you!
jms.
From the bdb.py:
def test():
t = Tdb()
t.run('import bdb; bdb.foo(10)')
where Tbd subclasses Bdp and overrides the user_ methods (see around 
line 533 of bdb.py. But what about set_step()? Or am I way off here?

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


Re: [python-win32] on the way to find pi!

2005-01-23 Thread Michel Claveau
Hi ! 


Very more simplistic, but easy for to code : 

def pi(nb):
cpi=0
for i in xrange(1,nb,4):
cpi=cpi+4./i-4./(i+2.)
return(cpi)

print pi(99)



@-salutations
-- 
Michel Claveau


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


Re: make install with python

2005-01-23 Thread Christopher De Vries
On Sat, Jan 22, 2005 at 01:54:17AM +0100, Uwe Mayer wrote:
> Any suggestions how I handle uninstallation? This was provided by automake
> rather mechanically. I didn't find a section on that in the distutils
> documentation... :(

I've been using distutils for a couple of projects I've written for
work. Overall I love it as I rarely have to consult documentation (I always
need to look at documentation to use autoconf, though I must admit I have only
used autoconf/automake on two projects). On the distutils2.0 Wiki page
(http://www.python.org/moin/DistUtils20) I found the quote:

"Uninstallation is solved as soon as we have an installation database, which
is part of what we're trying to do here." -- BobIppolito

So it looks like they are working on it.

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


python-dev Summary for 2004-12-01 through 2004-12-15

2005-01-23 Thread Brett C.
This is a summary of traffic on the `python-dev mailing list`_ from December 
01, 2004 through December 15, 2004.  It is intended to inform the wider Python 
community of on-going developments on the list.  To comment on anything 
mentioned here, just post to `comp.lang.python`_ (or email 
[email protected] which is a gateway to the newsgroup) with a subject line 
mentioning what you are discussing. All python-dev members are interested in 
seeing ideas discussed by the community, so don't hesitate to take a stance on 
something.  And if all of this really interests you then get involved and join 
`python-dev`_!

This is the fifty-fourth summary written by Brett Cannon (amazed no one has
complained about the lateness of these summaries!).
To contact me, please send email to brett at python.org ; I do not have the 
time to keep up on comp.lang.python and thus do not always catch follow-ups 
posted there.

All summaries are archived at http://www.python.org/dev/summary/ .
Please note that this summary is written using reStructuredText_ which can be 
found at http://docutils.sf.net/rst.html .  Any unfamiliar punctuation is 
probably markup for reST_ (otherwise it is probably regular expression syntax 
or a typo =); you can safely ignore it, although I suggest learning reST; it's 
simple and is accepted for `PEP markup`_ and gives some perks for the HTML 
output.  Also, because of the wonders of programs that like to reformat text, I 
cannot guarantee you will be able to run the text version of this summary 
through Docutils_ as-is unless it is from the `original text file`_.

.. _PEP Markup: http://www.python.org/peps/pep-0012.html
The in-development version of the documentation for Python can be found at
http://www.python.org/dev/doc/devel/ and should be used when looking up any
documentation on new code; otherwise use the current documentation as found at
http://docs.python.org/ .  PEPs (Python Enhancement Proposals) are located at 
http://www.python.org/peps/ .  To view files in the Python CVS online, go to 
http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ .  Reported bugs and 
suggested patches can be found at the SourceForge_ project page.

The `Python Software Foundation`_ is the non-profit organization that holds the 
intellectual property for Python.  It also tries to forward the development and 
use of Python.  But the PSF_ cannot do this without donations.  You can make a 
donation at http://python.org/psf/donations.html .  Every penny helps so even a 
small donation (you can donate through PayPal or by check) helps.

.. _python-dev: http://www.python.org/dev/
.. _SourceForge: http://sourceforge.net/tracker/?group_id=5470
.. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev
.. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python
.. _Docutils: http://docutils.sf.net/
.. _reST:
.. _reStructuredText: http://docutils.sf.net/rst.html
.. _PSF:
.. _Python Software Foundation: http://python.org/psf/
.. contents::
.. _last summary: http://www.python.org/dev/summary/2004-11-16_2004-11-30.html
.. _original text file: 
http://www.python.org/dev/summary/2004-12-01_2004-12-15.ht

=
Summary Announcements
=
PyCon_ 2005 planning is well underway.  The schedule has been posted at 
http://www.python.org/pycon/2005/schedule.html and looks great with a quite the 
varied topics.  And there is still time for the early-bird registration price 
of $175 ($125 students) before it expires on January 28th.

Some day I will be all caught up with the Summaries...
.. _PyCon: http://www.pycon.org
=
Summaries
=
--
PEPS: those existing and gestating
--
[for emails on PEP updates, subscribe to python-checkins_ and choose the 'PEP' 
topic]

A proto-PEP covering the __source__ proposal from the `last summary`_ has been 
posted to python-dev.

`PEP 338`_ proposes how to modify the '-m' modifier so as to be able to execute 
modules contained within packages.

.. _python-checkins: http://mail.python.org/mailman/listinfo/python-checkins
.. _PEP 338: http://www.python.org/peps/pep-0338.html
Contributing threads:
  - `PEP: __source__ proposal 
`__
  - `PEP 338: Executing modules inside packages with '-m' 
`__

---
Deprecating modules
---
The xmllib module was deprecated but not listed in `PEP 4`_.  What does one do? 
 Well, this led to a long discussion on how to handle module deprecation.

With the 'warning' module now in existence, PEP 4 seemed to be less important. 
 It was generally agreed that listing modules in PEP 4 was no longer needed. 
It was also agreed that deleting deprecated modules was not needed; it breaks 
code and disk space is cheap.

It seems that no longer listing documentation a

Re: finding name of instances created

2005-01-23 Thread Steven Bethard
Michael Tobis wrote:
I have a similar problem. Here's what I do:
.def new_robot_named(name,indict=globals()):
.   execstr = name + " = robot('" + name + "')"
.   exec(execstr,indict)
.class robot(object):
.   def __init__(self,name):
.  self.name = name
.   def sayhi(self):
.  print "Hi!  I'm %s!" % self.name
.if __name__=="__main__":
.   new_robot_named('Bert')
.   new_robot_named('Ernie')
.   Ernie.sayhi()
.   Bert.sayhi()
If you're changing the syntax from
alex = CreateRobot()
to
new_robot_named('Alex')
I don't see what you gain from using exec...
py> class robot(object):
...def __init__(self,name):
...   self.name = name
...def sayhi(self):
...   print "Hi!  I'm %s!" % self.name
...
py> def new_robot_named(name, indict=globals()):
... indict[name] = robot(name)
...
py> new_robot_named('Bert')
py> new_robot_named('Ernie')
py> Ernie.sayhi()
Hi!  I'm Ernie!
py> Bert.sayhi()
Hi!  I'm Bert!
py> import new
py> temp = new.module('temp')
py> new_robot_named('Alex', temp.__dict__)
py> temp.Alex.sayhi()
Hi!  I'm Alex!
That said, I do think a 'new_robot_named' function is probably a better 
approach than trying to change the meaning of Python's assignment 
statement...

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


Re: finding name of instances created

2005-01-23 Thread Georg Brandl
Michael Tobis wrote:
> I have a similar problem. Here's what I do:
> 
> .def new_robot_named(name,indict=globals()):
> .   execstr = name + " = robot('" + name + "')"
> .   exec(execstr,indict)
> 
> .class robot(object):
> .   def __init__(self,name):
> .  self.name = name
> 
> .   def sayhi(self):
> .  print "Hi!  I'm %s!" % self.name
> 
> .if __name__=="__main__":
> .   new_robot_named('Bert')
> .   new_robot_named('Ernie')
> .   Ernie.sayhi()
> .   Bert.sayhi()

Uh. Try explaining this to newbies... ;)

On a second thought, the idea is quite usable considering some differences:

class Robot(object):
# as above

class Robots(dict):
def new(self, name):
new_robot = Robot(name)
self[name] = new_robot
return new_robot
def __getattr__(self, name):
if name in self:
return self[name]
raise AttributeError

robots = Robots()
robots.new('Bert')
robots.new('Ernie')
robots.Bert.sayhi()
robots["Bert"].sayhi()

for robot in robots:
robot.sayhi()

... etc ...

This doesn't include ugly globals() and exec "tricks".

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


Re: What is print? A function?

2005-01-23 Thread Roy Smith
Frans Englich <[EMAIL PROTECTED]> wrote:

> Nah, I don't think it's a function, but rather a builtin "statement". But 
> it's possible to invoke it as an function; print( "test" ) works fine.

That's not calling it as a function. The parens in this case are simply 
evaluated as grouping operators around the string literal.
 
> So I wonder, what _is_ exactly the print statement? The untraditional way of 
> invoking it(without paranteses) makes me wonder.

It's a statement, just like "write" in Fortran.  When C came around, the 
idea of a language having no built-in print statement and having to call 
a function to generate output was "untraditional".  The function was 
named "printf" (with an "f" at the end) to emphasize that it was a 
function call, not a built-in language keyword.  Java, and many other 
quasi-C-based languages also use print functions, and this has become so 
common that people have come to expect it.  It's even a function in 
Perl, although that language's devil-may-care attitude about punctuation 
makes it difficult to tell for sure :-)
 
> The reason I thinks about this is I need to implement a debug print for my 
> program; very simple, a function/print statement that conditionally prints 
> its message whether a bool is true. Not overly complex.

You can certainly define a function which conditionally calls print, you 
just can't call it "print", because that's a reserved word.  But, before 
you get too far down that path, you might want to explore the logging 
module.  It suffers from a bit of kitchen-sink syndrome, so it may be 
more complicated than you want to deal with, but it's worth taking a 
look at.  You may discover that what you want to do is already done for 
you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Fuzzy matching of postal addresses [1/1]

2005-01-23 Thread Andrew McLean
In case anyone is interested, here is the latest.
I implemented an edit distance technique based on tokens. This 
incorporated a number of the ideas discussed in the thread.

It works pretty well on my data. I'm getting about 95% matching now, 
compared with 90% for the simple technique I originally tried. So I have 
matched half the outstanding cases.

I have spotted very few false positives, and very few cases where I 
could make a match manually. Although I suspect the code could still be 
improved.

It took a bit of head scratching to work out how to incorporate 
concatenation of tokens into the dynamic programming method, but I think 
I got there! At least my test cases seem to work!

#
# First attempt at a fuzzy compare of two addresses using a form of Edit 
Distance algorithm on tokens
# v0.5
# Andrew McLean, 23 January 2005
#
# The main routine editDistance takes two lists of tokens and returns a 
distance measure
# Allowed edits are replace, insert, delete and concatenate a pair of tokens.
# The cost of these operations depends on the value of the tokens and their 
position within the sequence.
#
# The tokens consist of a tuple containing a string representation and it's 
soundex encoding
# The program assumes that some normalisation has already been carried out, for 
instance converting all 
# text to lowercase. 
#
# The routine has undergone limited testing, but it appeared to work quite well 
for my application,
# with a reasonablly low level of false positives
#
# I'm not convinced that I have got the logic quite right in the dynamic 
programming, dealing correctly with
# token pair concatenation is non-trivial.
#
# It would be neater to have an out of band flag for impossible/infinite cost. 
Could abstract this into a
# Cost class. But I am a bit concerned about efficiency. Could use a negative 
number for infinite cost
# and use a modified min function to reflect this. The approach I am using with 
a very big number for INFINITY
# will be fine for any sensible tokens relating to addresses.
#
# The code could probably do with more test caases.
#
# Also, if I was going to refactor the code I would either
# 1. Make this a bit more object oriented by introducing a Token class.
# 2. Not precompute the soundex encodings. It is probably sufficient to use a 
memoized soundex routine.
#

# Standard library module imports
import re, sys, os

# Kludge!
sys.path.append(os.path.abspath('../ZODB'))

# Paul Moore's Memoize class from Python cookbook
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52201
from memoize import Memoize

# Public domain soundex implementation, by Skip Montanaro, 21 December 2000
# http://manatee.mojam.com/~skip/python/soundex.py
import soundex

# Memoize soundex for speed
get_soundex = Memoize(soundex.get_soundex)

# List of numbers spelt out
numbers_spelt = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 
'eight', 'nine', 'ten', 'eleven',
 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 
'seventeen', 'eighteen', 'nineteen',
 'twenty']
digitsToTextMap = dict([(str(i+1), numbers_spelt[i]) for i in 
range(len(numbers_spelt))])

# Set up a dictonary mapping abbreviations to the full text version
# Each abbreviation can map to a single string expansion or a list of possible 
expansions
abbrev = {'cott': 'cottage', 'rd':'road', 'fm':'farm', 'st':['street', 'saint']}
# ... include number to text mapping
abbrev.update(digitsToTextMap)

# Regular expression to find tokens containing a number
contains_number = re.compile('\d')
# ... could include numbers spelt in words, but it causes more problems than it 
solves
# ... as lots of words include character sequences like "one"
##contains_number = re.compile('\d|'+'|'.join(numbers_spelt))

# List of minor tokens
minorTokenList = ['the', 'at']

# Various weights
POSITION_WEIGHT = 1.2
REPLACEMENT_COST = 50
SOUNDEX_MATCH_COST = 0.95
PLURAL_COST = 0.25
ABBREV_COST = 0.25
INSERT_TOKEN_WITH_NUMBER = 5
INSERT_TOKEN_AFTER_NUMBER = 10
INSERT_TOKEN = 2
INSERT_MINOR_TOKEN = 0.5
CONCAT_COST = 0.2
INFINITY = 1000

def containsNumber(token):
"""Does the token contain any digits"""
return contains_number.match(token[0])
# Memoize it
containsNumber = Memoize(containsNumber)

def replaceCost(token1, token2, pos, allowSoundex=True):
"""Cost of replacing token1 with token2 (or vice versa)
at a specific normalised position within the sequence"""

# Make sure token1 is shortest
m, n = len(token1[0]), len(token2[0])
if m > n:
token1, token2 = token2, token1
m, n = n, m

# Look for exact matches
if token1[0] == token2[0]:
return 0

# Look for plurals
if (n - m == 1) and (token2[0] == token1[0] + 's'):
return PLURAL_COST

# Look for abbreviations
try:
expansion = abbrev[token1[0]]
except KeyError:
pass
else:
if type(expansion) == list and token2[0] in expansion:
return AB

Re: What is print? A function?

2005-01-23 Thread Georg Brandl
Roy Smith wrote:

>> So I wonder, what _is_ exactly the print statement? The untraditional way of 
>> invoking it(without paranteses) makes me wonder.
> 
> It's a statement, just like "write" in Fortran.  When C came around, the 
> idea of a language having no built-in print statement and having to call 
> a function to generate output was "untraditional".  The function was 
> named "printf" (with an "f" at the end) to emphasize that it was a 
> function call, not a built-in language keyword.

I beg to differ. Doesn't 'printf' stand for 'PRINT Formatted string'?

> Java, and many other 
> quasi-C-based languages also use print functions, and this has become so 
> common that people have come to expect it.  It's even a function in 
> Perl, although that language's devil-may-care attitude about punctuation 
> makes it difficult to tell for sure :-)

And it should have been and perhaps will be a function in Python, see
"Python Regrets" by GvR.

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


Keyboard problems with Python shell over SSH

2005-01-23 Thread Nils Emil P.Larsen
Hello

I'm not sure this is Python-related but it might be since Bash and vim
works perfectly.

I connect to my server using SSH and then run 'python' to enter the
shell.  I can't use the arrow buttons (up, down, left and right).
Instead I get this ^[[A , ^[[B,  ^[[C or  ^[[D.

How do I get my arrow buttons to work?

Sorry if this is offtopic.

Nils Emil P. Larsen

--
My reply-address is valid.   www.bios-flash.dk
Min svar-adresse er gyldig.  Redning af døde BIOS'er
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Keyboard problems with Python shell over SSH

2005-01-23 Thread Stian Soiland
På 23. jan 2005 kl. 21:55 skrev Nils Emil P.Larsen:
I connect to my server using SSH and then run 'python' to enter the
shell.  I can't use the arrow buttons (up, down, left and right).
Instead I get this ^[[A , ^[[B,  ^[[C or  ^[[D.
Your Python installation is probably compiled without readline support. 
It is the readline library that enables arrow keys and Ctrl-R and stuff 
to work.

Try "import readline" - you will probably get an error.
I won't go into detail on how to install readline on your OS. In 
Linuxes, it might be apt-get install readline-dev. In other OSes, 
different licensing and packaging issues might have prevented 
readline's precense.

-- -- 
Stian Søiland   You can't say civilization don't
Trondheim, Norway   advance, however, for in every war
http://www.soiland.no/  they kill you in a new way. [Rogers]
 =/\=

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


Re: What is print? A function?

2005-01-23 Thread Nelson Minar
Frans Englich <[EMAIL PROTECTED]> writes:
> The reason I thinks about this is I need to implement a debug print for my 
> program; very simple, a function/print statement that conditionally prints 
> its message whether a bool is true. Not overly complex.

As several folks have said, print is a statement, and Python doesn't
really let you add statements to the language.

You said you wanted to build a simple debugging function, so maybe
this doesn't fit the bill, but for bigger pieces of code Python has a
nice logging library. It's something like log4j or java.util.logging.
  http://www.python.org/doc/2.4/lib/module-logging.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: finding name of instances created

2005-01-23 Thread Steven Bethard
Nick Coghlan wrote:
It also directly addresses the question of aliasing. Think about how 
Steven's modified dictionary would react to this code:

pete = CreateRobot(2, 3)
dad = pete
dad.move()
pete.move()
If you'd like to handle these cases, but you don't want to have to 
explain aliasing right off the bat, you could try something like:

py> class Robot(object):
... def __init__(self):
... self.names = set()
... def move(self):
... if len(self.names) == 1:
... name, = self.names
... print "robot with name %r moved" % name
... else:
... print "robot with names %r moved" % sorted(self.names)
...
py> class RobotDict(dict):
... def __setitem__(self, name, value):
... if isinstance(value, Robot):
... value.names.add(name)
... super(RobotDict, self).__setitem__(name, value)
...
py> user_code = """\
... nick = Robot()
... pete = Robot()
... dad = pete
... nick.move()
... dad.move()
... pete.move()"""
py> exec user_code in RobotDict(Robot=Robot)
robot with name 'nick' moved
robot with names ['dad', 'pete'] moved
robot with names ['dad', 'pete'] moved
That is, you can just keep track of all the names of a Robot in the 
Robot object.  In the simple case, where there's only one name, you can 
display it as such.  In the more complicated case, where there's some 
aliasing, you can display the multiple aliases.  This means you don't 
have to teach about aliasing right off the bat, but if a student 
accidentally discovers it on their own, the machinery's there to explain 
it...

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


Microsoft to Provide PyCon Opening Keynote

2005-01-23 Thread Steve Holden

Dear Python Colleague:

The PyCon Program Committee is happy to announce that
the opening keynote speech, at 9:30 am on Wednesday
March 23 will be:

Python on the .NET Platform, by
Jim Hugunin, Microsoft Corporation

Jim Hugunin is well-known in the Python world for his
pioneering work on JPython (now Jython), and more
recently for the IronPython .NET implementation of
Python.

Jim joined Microsoft's Common Language Runtime team
in August last year to continue his work on Iron Python
and further improve the CLR's support for dynamic
languages like Python.

I look forward to hearing what Jim has to say, and
hope that you will join me and the rest of the Python
community at PyCon DC 2005, at George Washington
University from March 23-25, with a four-day sprint
starting on Saturday March 19.

Early bird registration rates are still available for
a few more days. Go to

http://www.python.org/moin/PyConDC2005/Schedule

for the current schedule, and register at

http://www.python.org/pycon/2005/


regards
Steve Holden
Chairman, PyCON DC 2005
-- 
PyCon DC 2005: The third Python Community Conference
http://www.pycon.org/   http://www.python.org/pycon/
The scoop on Python implementations and applications
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: JPype and classpath (Was Re: embedding jython in CPython... )

2005-01-23 Thread johng2001
Thanks for the response. However, I continue to have problems. Allow me
to give some more detail.

For simplicity of testing, I hard coded the classpath and JVM path
(BTW getDefaultJVMPath() returns None on my system)

import os, os.path
from jpype import *

startJVM("C:/jdk1.5.0/jre/bin/client/jvm.dll",
"-Djava.class.path=D:/Temp/classes")
...
shutdownJVM()


I have setup a classes folder in the script folder (D:/Temp) and have
placed test.class in it.
I run the script from the script folder (working directory is the same
as script's root path in this case)

Now how do I load the class test? I am afraid I cannot make that out
from the docs.

The simple test class is
public class test
{
public int i = 100;
}


What do I have to do before I can write
test().i
?

Thank you for your time.

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


Classical FP problem in python : Hamming problem

2005-01-23 Thread Francis Girard
Hi,

First,

My deepest thanks to Craig Ringer, Alex Martelli, Nick Coghlan and Terry Reedy 
for having generously answered on the "Need help on need help on generator" 
thread. I'm compiling the answers to sketch myself a global pictures about 
iterators, generators, iterator-generators and laziness in python.

In the meantime, I couldn't resist to test the new Python features about 
laziness on a classical FP problem, i.e. the "Hamming" problem.

The name of the game is to produce the sequence of integers satisfying the 
following rules :

(i) The list is in ascending order, without duplicates
(ii) The list begins with the number 1
(iii) If the list contains the number x, then it also contains the numbers 
2*x, 3*x, and 5*x
(iv) The list contains no other numbers.

The algorithm in FP is quite elegant. Simply suppose that the infinite 
sequence is produced, then simply merge the three sequences (2*x,3*x,5*x) for 
each x in the infinite sequence we supposed as already produced ; this is 
O(n) complexity for n numbers.

I simply love those algorithms that run after their tails.

In haskell, the algorithm is translated as such :

-- BEGIN SNAP
-- hamming.hs

-- Merges two infinite lists
merge :: (Ord a) => [a] -> [a] -> [a]
merge (x:xs)(y:ys)
  | x == y= x : merge xs ys
  | x <  y= x : merge xs (y:ys)
  | otherwise = y : merge (x:xs) ys

-- Lazily produce the hamming sequence
hamming :: [Integer]
hamming 
  = 1 : merge (map (2*) hamming) (merge (map (3*) hamming) (map (5*) hamming))
-- END SNAP


In Python, I figured out this implementation :

-- BEGIN SNAP
import sys
from itertools import imap

## Merges two infinite lists
def imerge(xs, ys):
  x = xs.next()
  y = ys.next()
  while True:
if x == y:
  yield x
  x = xs.next()
  y = ys.next()
elif x < y:
  yield x
  x = xs.next()
else: # if y < x:
  yield y
  y = ys.next()

## Lazily produce the hamming sequence 
def hamming():
  yield 1 ## Initialize the machine
  for n in imerge(imap(lambda h: 2*h, hamming()),
  imerge(imap(lambda h: 3*h, hamming()),
 imap(lambda h: 5*h, hamming(:
yield n
  print "Falling out -- We should never get here !!"

for n in hamming():
  sys.stderr.write("%s " % str(n)) ## stderr for unbuffered output
-- END SNAP


My goal is not to compare Haskell with Python on a classical FP problem, which 
would be genuine stupidity.

Nevertheless, while the Haskell version prints Hamming sequence for as long as 
I can stand it, and with very little memory consumation, the Python version 
only prints :

>> hamming.py
1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 25 27 30 32 36 40 45 48 50 54 60 64 72 75 
80 81 90 96 100 108 120 125 128 135 144 150 160 162 180 192 200 216 225 240 
243 250 256 270 288 300 320 324 360 375 384 400 405 432 450 480 486 500 512 
540 576 600 625 640 648 675 720 729 750 768 800 810 864 900 960 972 1000 1024 
1080 1125 1152 1200 1215 1250 1280 1296 1350 1440 1458 1500 1536 1600 1620 
1728 1800 1875 1920 1944 2000 2025 2048 2160 2187 2250 2304 2400 2430 2500 
2560 2592 2700 2880 2916 3000 3072 3125 3200 3240 3375 3456 3600 3645 3750 
3840 3888 4000 4050 4096 4320 4374 4500 4608 4800 4860 5000 5120 5184 5400 
5625 5760 5832 6000 6075 6144 6250 6400 6480 6561 6750 6912 7200 7290 7500 
7680 7776 8000 8100 8192 8640 8748 9000 9216 9375 9600 9720 1 10125 10240 
10368 10800 10935 11250 11520 11664 12000 12150 12288 12500 12800 12960 13122 
13500 13824 14400 14580 15000 15360 15552 15625 16000 16200 16384 16875 17280 
17496 18000 18225 18432 18750 19200 19440 19683 2 20250 20480 20736 21600 
21870 22500 23040 23328 24000 24300 24576 25000 25600 25920 26244 27000 27648 
28125 28800 29160 3 30375 30720 31104 31250 32000 32400 32768 32805 33750 
34560 34992 36000 36450 36864 37500 38400 38880 39366 4 40500 40960 41472 
43200 43740 45000 46080 46656 46875 48000 48600 49152 5 50625 51200 51840 
52488 54000 54675 55296 56250 57600
Processus arrÃtÃ

After 57600, my machine begins swapping like crazy and I do have to kill the 
python processus. 

I think I should not have this kind of behaviour, even using recursion, since 
I'm only using lazy constructs all the time. At least, I would expect the 
program to produce much more results before surrending.

What's going on ?

Thank you

Francis Girard
FRANCE

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


Re: What is print? A function?

2005-01-23 Thread Steven Bethard
Frans Englich wrote:
The reason I thinks about this is I need to implement a debug print for my 
program; very simple, a function/print statement that conditionally prints 
its message whether a bool is true. Not overly complex.
Sounds like you want to override sys.stdout:
py> class ConditionalWriter(object):
... def __init__(self, outfile, cond=True):
... self.outfile = outfile
... self.cond = cond
... def write(self, text):
... if self.cond:
... self.outfile.write(text)
...
...
py> import sys
py> writer = ConditionalWriter(sys.stdout)
py> sys.stdout = writer
py> print "hi!"
hi!
py> writer.cond = False
py> print "hi!"
py> writer.cond = True
py> print "hi!"
hi!
You probably want to restore sys.stdout when you're done too:
py> sys.stdout = writer.outfile
py> writer.cond = False
py> print "hi!"
hi!
That said, you probably _really_ want the logging module:
http://docs.python.org/lib/module-logging.html
Steve
--
http://mail.python.org/mailman/listinfo/python-list


Set parity of a string

2005-01-23 Thread snacktime
Is there a module that sets the parity of a string?  I have an
application that needs to communicate with a host using even parity 
So what I need is before sending the message, convert it from space to
even parity.  And when I get the response I need to convert that from
even to space parity.

The perl module String::Parity is what I have used to do this under perl.  

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


Re: Insanity

2005-01-23 Thread Tim Daneliuk
Fredrik Lundh wrote:
Tim Daneliuk wrote:

Thanks - very helpful.  One followup - your re works as advertised.  But
if I use: r'\[PROMPT:[^]].*\]'  it seems not to.  the '.*' instead of just '*'
it matches the entire string ...

it's not "just '*'", it's "[^]]*".  it's the "^]" set (anything but ]) that's 
repeated.
"[^]].*\]" means match a single non-] character, and then match as many
characters as you possibly can, as long as the next character is a ].
"[^]]*\]" means match as many non-] characters as possible, plus a single ].
Got it - 'Makes perfect sense too

which seems counterintutive to me.

then you need to study RE:s a bit more.
(hint: an RE isn't a template, it's a language description, and the RE engine
is designed to answer the question "does this string belong to this language"
(for match) or "is there any substring in this string that belongs to this
language" (for search) as quickly as possible.  things like match locations
etc are side effects).
Yes, I understand this.  But your clarification is most helpful.  Thanks!

Tim Daneliuk [EMAIL PROTECTED]
PGP Key: http://www.tundraware.com/PGP/
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to write a tutorial

2005-01-23 Thread Lucas Raab
Daniel Bickett wrote:
Most texts in computing are written by authors to defend and showcase
their existence against their peers.

When you aren't busy `showcasing' your ignorance, this is *all* i see
in everything you write.

Um, maybe that was his point...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Solutions for data storage?

2005-01-23 Thread Shalabh Chaturvedi
Leif K-Brooks wrote:
I'm writing a relatively simple multi-user public Web application with 
Python. It's a rewrite of a similar application which used PHP+MySQL 
(not particularly clean code, either). My opinions on various Web 
frameworks tends to vary with the phase of the moon, but currently, I'm 
planning to use Quixote.
Good choice, IMO! And while you're using Quixote, you might want to look 
at QLime [1] for all your data storage needs :)

I've looked at SQLObject, and it's very nice, but it doesn't provide 
certain features I really want, like the ability to store lists of 
strings or integers directly in the database (using commas in a varchar 
column or something).
In any mapper that lets you set attributes for storing columns (such as 
QLime), this should be fairly simple using properties.

My ideal solution would be an object database (or object-relational 
mapper, I guess) which provided total transparency in all but a few 
places, built-in indexing, built-in features for handling schema 
changes, the ability to create attributes which are required to be 
unique among other instances, and built-in querying with pretty syntax.
Briefly, QLime uses RDBMS indexing, automatically handles schema changes 
(in fact you don't define the schema in Python at all, you just create 
the table). For uniqueness you'd have to set the constraint on the 
table. To look at the query syntax avaialable, (and OR mapping features) 
see http://www.qlime.org/0.5.1/qlime_or_mapping.html.

Cheers,
Shalabh
[1] http://www.qlime.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Classical FP problem in python : Hamming problem

2005-01-23 Thread Jeff Epler
Your formulation in Python is recursive (hamming calls hamming()) and I
think that's why your program gives up fairly early.

Instead, use itertools.tee() [new in Python 2.4, or search the internet
for an implementation that works in 2.3] to give a copy of the output
sequence to each "multiply by N" function as well as one to be the
return value.

Here's my implementation, which matched your list early on but
effortlessly reached larger values.  One large value it printed was
6412351813189632 (a Python long) which indeed has only the distinct
prime factors 2 and 3. (2**43 * 3**6)

Jeff

from itertools import tee
import sys

def imerge(xs, ys):
x = xs.next()
y = ys.next()
while True:
if x == y:
yield x
x = xs.next()
y = ys.next()
elif x < y:
yield x
x = xs.next()
else:
yield y
y = ys.next()

def hamming():
def _hamming(j, k):
yield 1
hamming = generators[j]
for i in hamming:
yield i * k
generators = []
generator = imerge(imerge(_hamming(0, 2), _hamming(1, 3)), _hamming(2, 5))
generators[:] = tee(generator, 4)
return generators[3]

for i in hamming():
print i,
sys.stdout.flush()


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

Re: finding name of instances created

2005-01-23 Thread Michael Tobis
I have a similar problem. Here's what I do:

.def new_robot_named(name,indict=globals()):
.   execstr = name + " = robot('" + name + "')"
.   exec(execstr,indict)

.class robot(object):
.   def __init__(self,name):
.  self.name = name

.   def sayhi(self):
.  print "Hi!  I'm %s!" % self.name

.if __name__=="__main__":
.   new_robot_named('Bert')
.   new_robot_named('Ernie')
.   Ernie.sayhi()
.   Bert.sayhi()

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


Weakref.ref callbacks and eliminating __del__ methods

2005-01-23 Thread Mike C. Fletcher
I'm looking at rewriting parts of Twisted and TwistedSNMP to eliminate 
__del__ methods (and the memory leaks they create).  Looking at the docs 
for 2.3's weakref.ref, there's no mention of whether the callbacks are 
held with a strong reference.  My experiments suggest they are not...  
i.e. I'm trying to use this pattern:

class Closer( object ):
   """Close the OIDStore (without a __del__)"""
   def __init__( self, btree ):
   """Initialise the closer object"""
   self.btree = btree
   def __call__( self, oldObject=None ):
   """Regular call via self.close or weakref deref"""
   if self.btree:
   self.btree.close()
   self.btree = None
class BSDOIDStore(oidstore.OIDStore):
   def __init__( self, filename, OIDs = None ):
   """Initialise the storage with appropriate OIDs"""
   self.btree = self.open( filename )
   self.update( OIDs )
   self.close = Closer( self.btree )
   weakref.ref( self, self.close )
but the self.close reference in the instance is going away *before* the 
object is called.

So, this approach doesn't *seem* to work (the Closer doesn't get 
called), so I can gather that the callbacks don't get incref'd (or they 
get decref'd during object deletion).

I can work around it in this particular case by defining a __del__ on 
the Closer, but that just fixes this particular instance (and leaves 
just as many __del__'s hanging around).  I'm wondering if there's a 
ready recipe that can *always* replace a __del__'s operation? 

I know I heard a rumour somewhere about Uncle Timmy wanting to eliminate 
__del__ in 2.5 or thereabouts, so I gather there must be *some* way of 
handling the problem generally.  The thing is, weakref callbacks trigger 
*after* the object is deconstructed, while __del__ triggers before... 
must be something clever I'm missing.

Throw an old doggie a bone?
Mike

 Mike C. Fletcher
 Designer, VR Plumber, Coder
 http://www.vrplumber.com
 http://blog.vrplumber.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Set parity of a string

2005-01-23 Thread Fredrik Lundh
"snacktime" wrote:

> Is there a module that sets the parity of a string?  I have an
> application that needs to communicate with a host using even parity
> So what I need is before sending the message, convert it from space to
> even parity.  And when I get the response I need to convert that from
> even to space parity.

umm.  shouldn't the communication library do this for you?

 



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


Re: OT: problems mirroring python-list to c.l.py?

2005-01-23 Thread Daniel Bickett
John Lenton wrote:
> > On Sun, Jan 23, 2005 at 01:53:52PM -0500, Daniel Bickett wrote:
> > >
> > > Is there a reason that Google Groups isn't mirroring python-list
> > > exactly like it used to, or is it simply a conspiracy I'm not in on?
> > 
> > You should not ask this kind of question in a public forum,
> 
> and *you* should know better than to go around flapping your mouth
> like that.

Now I'm further confused, because I don't know what you quoted, but it
isn't on the mailing list and it isn't on c.l.py :) Maybe I should
give up trying to figure these things out.

You didn't include a name at the beginning of your citation... Who had
the audacity to take my joke seriously? ;-)

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


Re: Fuzzy matching of postal addresses [1/1]

2005-01-23 Thread John Machin
Andrew McLean wrote:
> In case anyone is interested, here is the latest.

> def insCost(tokenList, indx, pos):
> """The cost of inserting a specific token at a specific
normalised position along the sequence."""
> if containsNumber(tokenList[indx]):
> return INSERT_TOKEN_WITH_NUMBER + POSITION_WEIGHT * (1 - pos)
> elif indx > 0 and containsNumber(tokenList[indx-1]):
> return INSERT_TOKEN_AFTER_NUMBER + POSITION_WEIGHT * (1 -
pos)
> elif tokenList[indx][0] in minorTokenList:
> return INSERT_MINOR_TOKEN
> else:
> return INSERT_TOKEN + POSITION_WEIGHT * (1 - pos)
>
> def delCost(tokenList, indx, pos):
> """The cost of deleting a specific token at a specific normalised
position along the sequence.
> This is exactly the same cost as inserting a token."""
> return insCost(tokenList, indx, pos)

Functions are first-class citizens of Pythonia -- so just do this:

delCost = insCost

Re speed generally: (1) How many addresses in each list and how long is
it taking? On what sort of configuration? (2) Have you considered using
pysco -- if not running on x86 architecture, consider exporting your
files to a grunty PC and doing the match there. (3) Have you considered
some relatively fast filter to pre-qualify pairs of addresses before
you pass the pair to your relatively slow routine?

Soundex?? To put it bluntly, the _only_ problem to which soundex is the
preferred solution is genealogy searching in the US census records, and
even then one needs to know what varieties of the algorithm were in use
at what times. I thought you said your addresses came from
authoritative sources. You have phonetic errors? Can you give some
examples of pairs of tokens that illustrate the problem you are trying
to overcome with soundex?

Back to speed again: When you look carefully at the dynamic programming
algorithm for edit distance, you will note that it is _not_ necessary
to instantiate the whole NxM matrix -- it only ever refers to the
current row and the previous row. What does space saving have to do
with speed, you ask? Well, Python is not FORTRAN; it takes considerable
effort to evaluate d[i][j]. A relatively simple trick is to keep 2 rows
and swap (the pointers to) them each time around the outer loop. At the
expense of a little more complexity, one can reduce this to one row and
3 variables (north, northwest, and west) corresponding to d[i-1][j],
d[i-1][j-1], and d[i][j-1] -- but I'd suggest the simple way first.
Hope some of this helps,

John

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


Re: Weakref.ref callbacks and eliminating __del__ methods

2005-01-23 Thread Alex Martelli
Mike C. Fletcher <[EMAIL PROTECTED]> wrote:

> weakref.ref( self, self.close )
> 
> but the self.close reference in the instance is going away *before* the
> object is called.

Uh -- what's holding on to this weakref.ref instance?  I guess the
weakreference _itself_ is going away right after being created...


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


Re: rotor replacement

2005-01-23 Thread "Martin v. Löwis"
Paul Rubin wrote:
There's tons of such examples, but python-dev apparently reached
consensus that the Python maintainers were less willing than the
maintainers of those other packages to deal with those issues.
As Andrew says, it is not apparent that there was consensus.
Martin, do you know more about this?
I'm pretty certain that we (the PSF) sent a message to BXA, reporting
the rotor module. While I can't find out exactly when this happened
right now, the board meeting on 2002-04-09 decided that this should
happen, see
http://python.org/psf/records/board/minutes-2002-04-09.html
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: Alternative Ways to install Python 2.4?

2005-01-23 Thread "Martin v. Löwis"
Michael Goettsche wrote:
I convinced my CS teacher to use Python in school. We currently have 2.2 
installed on a Windows 2000 Terminal server. I asked the system administrator 
to upgrade to Python 2.4, but he didn't succeed in doing it. He used the 
microsoft installer package, which according to him crashed when starting. 
So my question is if there's an alternative way to install it(must be easy). 
Would it be an option to remove 2.2 first and then try to install 2.4 again?
That would be an option, but I doubt it helps. Please have a look at
http://www.python.org/2.4/bugs.html
Most likely, you need to upgrade Visual Basic on that machine.
Of course, without a precise error description, it is hard to tell.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: Set parity of a string

2005-01-23 Thread snacktime
On Sun, 23 Jan 2005 23:52:29 +0100, Fredrik Lundh
<[EMAIL PROTECTED]> wrote:
> "snacktime" wrote:
> 
> > Is there a module that sets the parity of a string?  I have an
> > application that needs to communicate with a host using even parity
> > So what I need is before sending the message, convert it from space to
> > even parity.  And when I get the response I need to convert that from
> > even to space parity.
> 
> umm.  shouldn't the communication library do this for you?
> 
The communication is an https post, but the host needs the data in
even parity before sending it into their internal systems (this is a
large bank network) and it's up to the client to do the
transformation.

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


Re: [perl-python] 20050121 file reading & writing

2005-01-23 Thread Fredrik Lundh
Erik Max Francis wrote:

>> To do this efficiently on a large file (dozens or hundreds of megs), you 
>> should use the 
>> 'sizehint' parameter so as not to use too much memory:
>>
>> sizehint = 0
>> mylist = f.readlines(sizehint)
>
> It doesn't make any difference.  .readlines reads the entire file into memory 
> at once.

except when it doesn't:

readlines([sizehint])

Read until EOF using readline() and return a list containing the
lines thus read. If the optional sizehint argument is present, instead
of reading up to EOF, whole lines totalling approximately sizehint
bytes (possibly after rounding up to an internal buffer size) are read.
Objects implementing a file-like interface may choose to ignore
sizehint if it cannot be implemented, or cannot be implemented
efficiently.

>>> f = open("ot.xml")
>>> s = f.readlines(1000)
>>> len(s)
157

>>> f = open("ot.xml")
>>> s = f.readlines()
>>> len(s)
48560

 



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


  1   2   >