Re: Python's "only one way to do it" philosophy isn't good?

2007-06-15 Thread Alex Martelli
Neil Cerutti <[EMAIL PROTECTED]> wrote:

> On 2007-06-12, Antoon Pardon <[EMAIL PROTECTED]> wrote:
> > On 2007-06-11, Terry Reedy <[EMAIL PROTECTED]> wrote:
> >> More so than supporters of most other languages, in particular
> >> Scheme?
> >
> > Well to my knowledge (which could be vastly improved), scheme
> > doesn't have some Zen-rules that include something like this.
> >
> > I tried to google for similar remarks in relation to scheme but
> > I got no results. Maybe your google skills are better.
> 
> It's in _The Revised^%d Report on Scheme_, Introduction:
> 
>   Programming languages should be designed not by piling feature
>   on top of feature, but by removing the weaknesses and
>   restrictions that make additional features appear necessary.
> 
> Of course, that was written well before Scheme had most of its
> current features.

The "Spirit of C" section in the preface of the ISO Standard for C
phrases this principle as "Provide only one way to do an operation".

Despite the phrasing variations, this commonality goes well with my
perception that, at their roots, Scheme, C and Python share one
philosophical underpinning (one that's extremely rare among programming
languages as a whole) -- an appreciation of SIMPLICITY AND UNIFORMITY as
language characteristics.


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


How to localize PyKaraoke ?

2007-06-15 Thread Eiwot

Hi all,
   Can I use PyKaraoke in another language such as German ? How to make a song 
lyrics that match with the song , any word break or phrase break algorithm 
required ?
 
Thanks
Eiwot
http://pyarticles.blogspot.com/
http://pythonforge.blogspot.com
_
Play free games, earn tickets, get cool prizes! Join Live Search Club. 
http://club.live.com/home.aspx?icid=CLUB_wlmailtextlink-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python's "only one way to do it" philosophy isn't good?

2007-06-15 Thread Paul Rubin
Dennis Lee Bieber <[EMAIL PROTECTED]> writes:
>   Adding generator expressions, which look identical except that one
> typically has () (or the () of an enclosing function call) while the
> other must have [] just seems to add confusion to the world. I'll
> abstain on "with"... Decorators I've not managed to figure out, and that
> refugee from Dr Moreau -- the inside out conditional expression -- is a
> prime candidate for termination...

Python has really changed its flavour over the past few releases, if
you develop a style that uses the above features (well maybe not the
if-expression) extensively.  The learning curve is steeper but you end
up writing cleaner code that's free of corner cases.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Want to learn Python

2007-06-15 Thread Alex Martelli
7stud <[EMAIL PROTECTED]> wrote:
   ...
> The reference book "Python in a Nutshell" is excellent, however its
> index is so bad I hesitate to recommend it.  A reference book should
> have a thorough index--you shouldn't have to hunt through the chapters
> trying to find the particular topic you are interested in.

Try  -- it will easily
generate for you queries on books.google.com such as, e.g.:
generator inauthor:"alex martelli"
to find 3 mentions of "generator" in the Nutshell and Cookbook.  Not
quite a replacement for a good index, of course (you're welcome to write
O'Reilly spewing hate on how much you loathe that index - maybe that
will help convince them to put more time and effort into indexing on
their future projects, or offer some way for book authors to add
indexing indications as they write their books), but it still seems
potentially helpful.


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


Re: Python's "only one way to do it" philosophy isn't good?

2007-06-15 Thread Douglas Alan
"Terry Reedy" <[EMAIL PROTECTED]> writes:

> > You are ignoring the fact that

> This prefactory clause is false and as such it turns what was a true 
> statement into one that is not.  Better to leave off such ad hominisms and 
> stick with the bare true statement.

You went on about how Gerry Sussman's opinion is a crock and how he
should look in the mirror, and then you get bent out of shape over the
phrase, "you are ignoring"???  For the record, "you are ignoring" is
not an ad hominem; "anyone who doesn't know how to spell 'ad hominem'
has the intelligence of a mealworm" is an ad hominem.

> > Scheme has a powerful syntax extension mechanism

> I did not and do not see this as relevant to the main points of my
> summary above.  Python has powerful extension mechanisms too, but
> comparing the two languages on this basis is a whole other topic.

How do you know that Prof. Sussman doesn't consider the macro issue to
be essential?  Certainly other Lisp aficionados do, as does, I believe
Guy Steele, the other inventor of Scheme.

It appears to me that you are missing the point that having a
minimalist disposition towards programming language design does not
preclude believing that such languages should have features that are
missing from Python.

|>oug
-- 
http://mail.python.org/mailman/listinfo/python-list


Open Source Developers' Conference 2007 - Brisbane - Call for Papers

2007-06-15 Thread Richard Jones
Call for Papers
Open Source Developers' Conference 2007 - Brisbane Australia
"Success in Development & Business"

OSDC is an Australian grass-roots conference providing Open Source  
developers with an opportunity to meet, share, learn, and of course  
show-off. OSDC focuses on Open Source developers building solutions  
directly for customers and other end users, anything goes as long as  
the code or the development platform is Open Source. Last year's  
conference attracted over 180 people, 60 talks, and 6 tutorials.  
Entry for delegates is kept easy by maintaining a low registration  
fee (approx $300), which always includes the conference dinner.

This year OSDC will be held in Brisbane (Australia) from the 26th to  
the 29th of November, with an extra dedicated stream for  
presentations on Open Source business development, case studies,  
software process, and project management. The theme for this year's  
conference is "Success in Development & Business". If you are an Open  
Source maintainer, developer or user we would encourage you to submit  
a talk proposal on the open-source tools, solutions, technologies, or  
languages you are working with.

Previous years have included numerous talks on topics such as:

  - FOSS Software Development Tools, Software Process and
Project Management
  - Languages/Platforms: C/C++, Java, C#/Mono/OSS.Net
  - Scripting: Perl, PHP, Python, Ruby
  - Databases
  - Education
  - Web Technologies
  - Emerging Technologies and Innovation

For more details and to submit your proposal(s), see
http://osdc.com.au/papers/cfp.html

If you have any questions or require assistance with your submission,  
please don't hesitate to ask!

We recognise the increasing importance of Open Source in providing a  
medium for collaboration between individuals, researchers, business  
and government.  In recognition of this, we offer optional peer- 
review for those members of our community who desire it.  We are  
still finalising our review board, in addition to which those  
requesting peer-review will be asked to contribute reviews for up to  
three papers.


OSDC 2007 Brisbane (Australia) - Key Program Dates:

30 Jun - Initial proposals (short abstract) due
31 Jul - Proposal acceptance
31 Aug - Submission deadline
15 Sep - Peer-review response (optional)
30 Sep - Final version for proceedings

26 Nov- OSDC 2007 Tutorials
27-29 Nov - OSDC 2007 Main Conference!

For all information, contacts and updates, see the OSDC conference  
web site at http://osdc.com.au/


We gratefully acknowledge the following companies for their early  
commitment in sponsoring OSDC 2007:
  - Apress (http://apress.com/)
  - Common Ground (http://commongroundgroup.com/)
  - Google (http://google.com.au/)
  - OpenGear (http://opengear.com.au/)

Interested in sponsoring also?
See http://www.osdc.com.au/sponsors/opportunities.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's "only one way to do it" philosophy isn't good?

2007-06-15 Thread Douglas Alan
Steven D'Aprano <[EMAIL PROTECTED]> writes:

> On Fri, 15 Jun 2007 17:05:27 -0400, Douglas Alan wrote:

>> You are ignoring the fact that Scheme has a powerful syntax extension
>> mechanism (i.e., hygenic macros), which means that anyone in the world
>> can basically extend Scheme to include practically any language
>> feature they might like it to have.

> You say that like it is a good thing.

A chaque son gout.

|>oug
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for a wxPython GUI builder

2007-06-15 Thread Jens Thiede
On Jun 16, 3:18 am, Dick Moores <[EMAIL PROTECTED]> wrote:
> How about SPE?
>
> Any others?
>
> And which ones do people
> actually use? Commercial or Freeware.
>
> Thanks,
>
> Dick Moores

There's Boa Constructor... (http://boa-constructor.sourceforge.net/
Screenshots). I haven't actually used it though.

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


Custom wxPython Widget

2007-06-15 Thread Jens Thiede
What is the best source code to read? Any tips; suggestions?

Thanks in advance
Jens Thiede

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


Re: Python's "only one way to do it" philosophy isn't good?

2007-06-15 Thread Terry Reedy

"Douglas Alan" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| "Terry Reedy" <[EMAIL PROTECTED]> writes:
|
| > Here's the situation.  Python is making inroads at MIT, Scheme home 
turf.
| > The co-developer of Scheme, while writing about some other subject, 
tosses
| > in an off-the-wall slam against Python.  Someone asks what we here 
think.
| > I think that the comment is a crock and the slam better directed, for
| > instance, at Scheme itself.  Hence 'he should look in a mirror'.
|
| You are ignoring the fact that

This prefactory clause is false and as such it turns what was a true 
statement into one that is not.  Better to leave off such ad hominisms and 
stick with the bare true statement.

| Scheme has a powerful syntax extension mechanism

I did not and do not see this as relevant to the main points of my summary 
above.  Python has powerful extension mechanisms too, but comparing the two 
languages on this basis is a whole other topic.

tjr



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


Re: Multiline lamba implementation in python.

2007-06-15 Thread Josh Gilbert
On Wednesday 13 June 2007 4:04 am, Duncan Booth wrote:
> "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> > But you already have "multiline" lambdas right now in that sense, no
> > need  to add anything. I think you were talking about lambdas *with*
> > statements  inside.
> >
> > bin = lambda x:((x&8 and '*' or '_') +
> >  (x&4 and '*' or '_') +
> >  (x&2 and '*' or '_') +
> >  (x&1 and '*' or '_'))
>
> Or in more recent versions of Python:
>
> bin = lambda x:(('*' if x&8 else '_') +
> ('*' if x&4 else '_') +
> ('*' if x&2 else '_') +
> ('*' if x&1 else '_'))
>
> but seriously, any example of lambda which simply assigns the function to a
> variable is flawed.
>
> I can sort of understand the people who object to a named function taking
> the logic 'out of line', but any expression which actually requires a
> multi-statement function to be embedded in the middle of it is already in
> danger of causing my brain to implode.

You're correct, my lambda function handles statements as well as multiple 
expressions. That code, however, is bloody hideous. If that's what I had to 
do to do multiline callbacks I'd always use def. Ew.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Should: "for k,v in **dictionary_instance" work?

2007-06-15 Thread Steven D'Aprano
On Fri, 15 Jun 2007 19:17:25 +, keithgabryelski wrote:

> Does it make sense to provide this syntax for iterating key/value
> pairs from a dictionary?
> 
> for k,v in **dict():
>print k,v
>
> why is this not the same as:
> 
> for k,v in dict().items():
>   print k,v

Because *t and **d already have well-defined meanings, and that's not
what **d would mean.

In a function definition, *t collects positional arguments into a tuple
and **d collects keyword arguments into a dictionary. In a function call,
they expand them again. For example:

function(1, 2, 3, a=4, b=5, c=6) 
==> t = (1, 2, 3); d = {'a':4, 'b':5, 'c':6}

function(*t, **d) 
==> function(1, 2, 3, a=4, b=5, c=6) 


Currently, *t and **d are syntax errors outside of function calls and
definitions. (Any other places?) But if they were allowed, what would they
mean? For consistency, we would expect the following:

t = tuple(1, 2, 3)
for item in *t:
# same as "for item in 1, 2, 3:"
print item


Even if it were allowed, it would be pointless: it would just expand the
tuple only to collect it again.

What would **d mean?

d = dict(a=1, b=2, c=3)
for key, value in **d:
# same as "for key, value in 'a': 1, 'b': 2, 'c': 3:"
print key, value


For starters, that would mean changing the syntax of Python to allow
key:value assignments outside of a dict constructor. I can't think of a
reason to do so, but even if there is, we have the same problem as for the
tuple expansion: it would pointlessly expand the dict, only to collect it
again.

Maybe you don't care about consistency and you just want the compiler to
accept "for k,v in **d" as syntactic sugar for "for k,v in d.items()". Or
perhaps d.iteritems() would be a better choice.

In that case, Python isn't very big on syntactic sugar merely for saving a
few characters of typing, so you're unlikely to convince those who would
need convincing.


> for that matter, why the heck doesn't a dictionary default to
> returning a tuple
> k,v pair from its iterator?

When dictionaries were first made iterable, in Python 2.2 if I recall
correctly, there was debate about whether "for thing in dict:" should be
equivalent to iterating over the keys, the values or both. In particular,
people pointed out that there were just as many, or slightly more,
examples of "for k,v in dict.items()" as "for k in dict.keys()" in the
standard library. So there is a good case for making iterating over a
dictionary equivalent to iterating over the keys and values.

But the deciding point was the correspondence between "for x in dict" and
"if x in dict". In fact, Python then, and now, included a fall-back
iterator protocol: if __getitem__ is defined, iteration over an object is
equivalent to repeatedly calling __getitem__.

You can read the PEP that covers some of these issues here:

http://svn.python.org/projects/peps/trunk/pep-0234.txt



-- 
Steven.

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


Re: Want to learn Python

2007-06-15 Thread BartlebyScrivener
On Jun 15, 6:41 am, Amol <[EMAIL PROTECTED]> wrote:
> Hi, I want to learn Python in less than a month which resources should
> I use. I prefer to read books . Please give me a list of *recognized*
> resources. Thank You all

Python Essential Reference, David Beazley, 3rd edition Feb 2006
great, esp. if you already know some other programming language

http://www.amazon.com/Python-Essential-Reference-Developers-Library/dp/0672328623/inscape-20

rd

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


Re: Want to learn Python

2007-06-15 Thread Jack Crane
Amol <[EMAIL PROTECTED]> wrote in news:1181907696.878873.214760
@i13g2000prf.googlegroups.com:

> Hi, I want to learn Python in less than a month which resources should
> I use. I prefer to read books . Please give me a list of *recognized*
> resources. Thank You all
> 

http://www.pythonware.com/daily/4368043588838810608/

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


Re: Html parser

2007-06-15 Thread Nikita the Spider
In article <[EMAIL PROTECTED]>,
 Stephen R Laniel <[EMAIL PROTECTED]> wrote:

> On Fri, Jun 15, 2007 at 07:11:56AM -0700, HMS Surprise wrote:
> > Could you recommend  an html parser that works with python (jython
> > 2.2)?
> 
> I'm new here, but I believe BeautifulSoup is the canonical
> answer:
> http://www.crummy.com/software/BeautifulSoup/

It is, but personally I'm a fan of Connelly Barnes' htmldata module:
http://oregonstate.edu/~barnesc/htmldata/

Much easier to use than BeautifulSoup IMO.

-- 
Philip
http://NikitaTheSpider.com/
Whole-site HTML validation, link checking and more
-- 
http://mail.python.org/mailman/listinfo/python-list


Looking for a wxPython GUI builder

2007-06-15 Thread Dick Moores
How about SPE?

Any others?

And which ones do people
actually use? Commercial or Freeware.

Thanks,

Dick Moores

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


Re: Python's "only one way to do it" philosophy isn't good?

2007-06-15 Thread Steven D'Aprano
On Fri, 15 Jun 2007 17:05:27 -0400, Douglas Alan wrote:

> You are ignoring the fact that Scheme has a powerful syntax extension
> mechanism (i.e., hygenic macros), which means that anyone in the world
> can basically extend Scheme to include practically any language
> feature they might like it to have.


You say that like it is a good thing.


-- 
Steven.

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


Re: Want to learn Python

2007-06-15 Thread 7stud
On Jun 15, 11:59 am, "Evan Klitzke" <[EMAIL PROTECTED]> wrote:
> On 6/15/07, Amol <[EMAIL PROTECTED]> wrote:
>
> > Hi, I want to learn Python in less than a month which resources should
> > I use. I prefer to read books . Please give me a list of *recognized*
> > resources. Thank You all
>
> The Apress "Beginning Python" book is the one that I recommend to
> people who want to learn the language. I started off with the O'Reilly
> book, and that book went too slow and didn't cover as many topic as
> the Apress book. If you are an experienced programmer and use the
> Apress book, you'll get a pretty good grasp of the language within a
> week or so.
>
> --
> Evan Klitzke <[EMAIL PROTECTED]>

I am of the opposite opinion: I recommend that people get any book but
"Beginning Python: Novice to Professional".  In my opinion, that book
is horribly written, the examples are terrible, some subjects are only
covered in passing so the info is too parse to be of any use, and
there are no problems at the end of the chapters to work on.  I think
a beginner might be fooled into thinking Beginning Python is a good
book because they won't know how many holes their knowledge of python
is riddled with, and since there are no problems to work on, they may
not even realize how little they learned.  I think an experienced
programmer would spot all the blunders in the book straight away.

As a result, I often use "Learning Python" as a reference to fill in
all the missing material in Beginning Python, and I wish I had
purchased it initially.  It also has problems to work on at the end of
each section.  One problem with Learning Python is that it needs a new
edition to catch up with the changes that have occurred in the
language, but it still seems like a much, much better book than
Beginning Python.

The reference book "Python in a Nutshell" is excellent, however its
index is so bad I hesitate to recommend it.  A reference book should
have a thorough index--you shouldn't have to hunt through the chapters
trying to find the particular topic you are interested in.

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


Re: Python's "only one way to do it" philosophy isn't good?

2007-06-15 Thread Kay Schluehr
On 15 Jun., 22:58, Douglas Alan <[EMAIL PROTECTED]> wrote:

> For instance, I believe that Python is now too big, and that much of
> what is in the language itself should be replaced with more general
> Scheme-like features.
> Then a good macro mechanism should be
> implemented so that all the conveniences features of the language can
> be implemented via macro definitions in the standard library.

And why sould anyone reimplement the whole standard library using
macro reductions? Because this is the "one obvious way to do it" for
people who are addicted to Scheme?

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


Re: Should: "for k,v in **dictionary_instance" work?

2007-06-15 Thread Dustan
On Jun 15, 2:17 pm, [EMAIL PROTECTED] wrote:
> Does it make sense to provide this syntax for iterating key/value
> pairs from a dictionary?
>
> for k,v in **dict():
>print k,v
>
> why is this not the same as:
>
> for k,v in dict().items():
>   print k,v
>
> for that matter, why the heck doesn't a dictionary default to
> returning a tuple
> k,v pair from its iterator?
>
> Pax, Keith
>
> Ps, I'm sure someone has thought of these things before, probably been
> answered before, but I'm sure I didn't find reference to them when i
> searched.

The answer is simply for history and for clarity.

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


Re: Python's "only one way to do it" philosophy isn't good?

2007-06-15 Thread Douglas Alan
Kay Schluehr <[EMAIL PROTECTED]> writes:

> On 15 Jun., 22:58, Douglas Alan <[EMAIL PROTECTED]> wrote:

>> For instance, I believe that Python is now too big, and that much
>> of what is in the language itself should be replaced with more
>> general Scheme-like features.  Then a good macro mechanism should
>> be implemented so that all the conveniences features of the
>> language can be implemented via macro definitions in the standard
>> library.

> And why sould anyone reimplement the whole standard library using
> macro reductions? Because this is the "one obvious way to do it" for
> people who are addicted to Scheme?

(1) By, "should be replaced", I meant in an ideal world.  I'm not
proposing that this be done in the real world anytime soon.

(2) I didn't suggest that a single line of the standard library be
changed.  What would need to be changed is the core Python language,
not the standard library.  If this idea were implemented, the core
language could be made smaller, and the features that were thereby
removed from the language core could be moved into the standard
library instead.

(3) My reasons for wanting this have nothing to do with being
"addicted to Scheme", which I almost never use.  It has to do more
with my language design and implementation aesthetics, and my desire
for a syntax extension mechanism so that I can add my own language
features to Python without having to hack on the CPython source code.

|>oug
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Should: "for k,v in **dictionary_instance" work?

2007-06-15 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, keithgabryelski
wrote:

> Does it make sense to provide this syntax for iterating key/value
> pairs from a dictionary?
> 
> for k,v in **dict():
>print k,v
> 
> why is this not the same as:
> 
> for k,v in dict().items():
>   print k,v

Why should it be?  Why adding something that unreadable and magic instead
of the perfect readable ``for k, v in some_dict.iteritems():``?

And I don't see why it should be ``**``!?

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


Re: Get the current date, python 2.2

2007-06-15 Thread Rob Williscroft
On Fri, 15 Jun 2007 14:46:20 -0700, nano wrote:

> In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED]
> says...
>> On Fri, 15 Jun 2007 14:30:36 -0700, nano wrote:
>> 
>> > Using python 2.2 what is the simplest way to get the current date
>> > value? I have looked in so many places. The question is often asked
>> > and the usual response indicates how to get the current date and time
>> > like
>> > 
>> > now = time.localtime()
>> > 
>> > I want just the date, like 2007-06-15. The value will go into a
>> > postgresql Date type column.
>> 
>>  >>> import datetime
>>  >>> d = datetime.date.today()
>>  >>> d.isoformat()
>>  '2007-06-15'
>>  >>> 
>>  >>> 
>> Rob.
>> 
> Thanks, I'd read that today() was only good for 2.3?

Right I missed that, though its actually the datetime module that
is new in 2.3.

This should do though:

 >>> import time
 >>> time.strftime( "%Y-%m-%d" )
 '2007-06-15'
 >>> 

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


Re: Priority Queue with Mutable Elements

2007-06-15 Thread Josiah Carlson
Chris Lasher wrote:
> I am working with large graphs (~150,000 to 500,000 nodes) which I
> need decompose node-by-node, in order of a node's value. A node's
> value is determined by the sum of its edge weights. When a node is
> removed from the graph, its neighbors' values must be updated to take
> into account the removed edges.
> 
> I was told to look for a priority queue in Python. I had a look at the
> heapq module. It looks like it supports ordering on insertion, but I'm
> unsure how to update the queue once a node's value changes.
> Additionally, I need the queue to be sorted on a particular attribute
> of the node objects, and don't see a way to do that other than
> override the __cmp__ method. Should I just use a list and use .sort()
> or sorted()? That seems like it could be horribly inefficient.
> 
> I found Andrew Snare's PQueue extension module [1] , which supports
> updating values in the priority queue by reassignment. It appeared to
> be broken in Python2.5 [2] but I found the offending line (a call to
> PyMem_DEL) and changed it (to PyObject_FREE) and it appears to be
> working fine. I would prefer to limit external depedencies for my
> modules, however.

See this implementation of a "pair heap":
   http://mail.python.org/pipermail/python-dev/2006-November/069845.html
...which offers the ability to update the 'priority' of an entry in the 
heap.  It requires that the 'value' in (priority, value) pairs be unique 
(to the heap) and hashable.

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


Re: Get the current date, python 2.2

2007-06-15 Thread nano
In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] 
says...
> On Fri, 15 Jun 2007 14:30:36 -0700, nano wrote:
> 
> > Using python 2.2 what is the simplest way to get the current date value?
> > I have looked in so many places. The question is often asked and the
> > usual response indicates how to get the current date and time like
> > 
> > now = time.localtime()
> > 
> > I want just the date, like 2007-06-15. The value will go into a
> > postgresql Date type column.
> 
>  >>> import datetime
>  >>> d = datetime.date.today()
>  >>> d.isoformat()
>  '2007-06-15'
>  >>> 
>  
> Rob.
> 
Thanks, I'd read that today() was only good for 2.3? 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get the current date, python 2.2

2007-06-15 Thread Yongjian Xu

time.strftime('%Y-%m-%d', time.localtime()) gives you just the date format.

Jim

On 6/15/07, nano <[EMAIL PROTECTED]> wrote:


Using python 2.2 what is the simplest way to get the current date value?
I have looked in so many places. The question is often asked and the
usual response indicates how to get the current date and time like

now = time.localtime()

I want just the date, like 2007-06-15. The value will go into a
postgresql Date type column.

Also, if postgres field of this type is set to time.localtime(), is the
time portion of the date discarded, or stored 'invisibly', of will there
be an error of some type? Just thought someone here might know.
--
http://mail.python.org/mailman/listinfo/python-list





--
Yongjian (Jim) Xu
===
Sysops
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Get the current date, python 2.2

2007-06-15 Thread Rob Williscroft
On Fri, 15 Jun 2007 14:30:36 -0700, nano wrote:

> Using python 2.2 what is the simplest way to get the current date value?
> I have looked in so many places. The question is often asked and the
> usual response indicates how to get the current date and time like
> 
> now = time.localtime()
> 
> I want just the date, like 2007-06-15. The value will go into a
> postgresql Date type column.

 >>> import datetime
 >>> d = datetime.date.today()
 >>> d.isoformat()
 '2007-06-15'
 >>> 
 
Rob.
-- 
http://mail.python.org/mailman/listinfo/python-list


Get the current date, python 2.2

2007-06-15 Thread nano
Using python 2.2 what is the simplest way to get the current date value? 
I have looked in so many places. The question is often asked and the 
usual response indicates how to get the current date and time like 

now = time.localtime()

I want just the date, like 2007-06-15. The value will go into a 
postgresql Date type column. 

Also, if postgres field of this type is set to time.localtime(), is the 
time portion of the date discarded, or stored 'invisibly', of will there 
be an error of some type? Just thought someone here might know.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a_list.count(a_callable) ?

2007-06-15 Thread Dustan
On Jun 15, 12:52 pm, Ping <[EMAIL PROTECTED]> wrote:
> On 6 15 ,   11 17 , Dustan <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Jun 15, 9:15 am, Ping <[EMAIL PROTECTED]> wrote:
>
> > > > sum(1 for i in a_list if a_callable(i))
>
> > > > --
> > > > Carsten Haesehttp://informixdb.sourceforge.net
>
> > > This works nicely but not very intuitive or readable to me.
>
> > > First of all, the generator expression makes sense only to
> > > trained eyes.  Secondly, using sum(1 ...) to mean count()
> > > isn't very intuitive either.
>
> > Then wrap it in a function:
> > def count(a_list, a_function):
> >return sum(1 for i in a_list if a_function(i))
>
> > And call the function. You can also give it a different name (although
> > I can't think of a concise name that would express it any better).
>
> Hmm... This sounds like the best idea so far.  It is efficient both
> in memory and time while exposes an easy-to-understand name.
> I would name the function count_items though.
>
> n = count_items(a_list, lambda x: x > 3) # very readable  :)

Although that particular example would be more efficient inlined,
because of the additional time spent creating the lambda function in
your count_items call.

sum(1 for i in a_list if i > 3)

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


Re: Python's "only one way to do it" philosophy isn't good?

2007-06-15 Thread Douglas Alan
"Terry Reedy" <[EMAIL PROTECTED]> writes:

> Here's the situation.  Python is making inroads at MIT, Scheme home turf. 
> The co-developer of Scheme, while writing about some other subject, tosses 
> in an off-the-wall slam against Python.  Someone asks what we here think. 
> I think that the comment is a crock and the slam better directed, for 
> instance, at Scheme itself.  Hence 'he should look in a mirror'.

You are ignoring the fact that Scheme has a powerful syntax extension
mechanism (i.e., hygenic macros), which means that anyone in the world
can basically extend Scheme to include practically any language
feature they might like it to have.

|>oug
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's "only one way to do it" philosophy isn't good?

2007-06-15 Thread Douglas Alan
"Terry Reedy" <[EMAIL PROTECTED]> writes:

> My only point was that Sussman is an odd person to be criticizing
> (somewhat mistakingly) Python for being minimalist.

I think that being a language minimalist is very different from
believing that there should be exactly one obvious way to do
everything.

For instance, I believe that Python is now too big, and that much of
what is in the language itself should be replaced with more general
Scheme-like features.  Then a good macro mechanism should be
implemented so that all the conveniences features of the language can
be implemented via macro definitions in the standard library.

Macros, however, are typically claimed in these parts to violate the
"only one way" manifesto.

|>oug
-- 
http://mail.python.org/mailman/listinfo/python-list


Priority Queue with Mutable Elements

2007-06-15 Thread Chris Lasher
Hello,

I am working with large graphs (~150,000 to 500,000 nodes) which I
need decompose node-by-node, in order of a node's value. A node's
value is determined by the sum of its edge weights. When a node is
removed from the graph, its neighbors' values must be updated to take
into account the removed edges.

I was told to look for a priority queue in Python. I had a look at the
heapq module. It looks like it supports ordering on insertion, but I'm
unsure how to update the queue once a node's value changes.
Additionally, I need the queue to be sorted on a particular attribute
of the node objects, and don't see a way to do that other than
override the __cmp__ method. Should I just use a list and use .sort()
or sorted()? That seems like it could be horribly inefficient.

I found Andrew Snare's PQueue extension module [1] , which supports
updating values in the priority queue by reassignment. It appeared to
be broken in Python2.5 [2] but I found the offending line (a call to
PyMem_DEL) and changed it (to PyObject_FREE) and it appears to be
working fine. I would prefer to limit external depedencies for my
modules, however.

Many thanks for your insight and advice,
Chris

[1] http://py.vaults.ca/apyllo.py/514463245.769244789.44776582
[2] http://tinyurl.com/363dg9 or 

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


Re: Html parser

2007-06-15 Thread Lee Hinde
On Jun 15, 7:11 am, HMS Surprise <[EMAIL PROTECTED]> wrote:
> Could you recommend  an html parser that works with python (jython
> 2.2)?   HTMLParser does not seem to be in this library. To test some
> of our browser based (mailnly php) code I seek for field names and
> values associated with them.
>
> Thanks,
>
> jh

Twill:
http://twill.idyll.org/
Don't know about the jython part

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


Should: "for k,v in **dictionary_instance" work?

2007-06-15 Thread keithgabryelski
Does it make sense to provide this syntax for iterating key/value
pairs from a dictionary?

for k,v in **dict():
   print k,v

why is this not the same as:

for k,v in dict().items():
  print k,v

for that matter, why the heck doesn't a dictionary default to
returning a tuple
k,v pair from its iterator?

Pax, Keith

Ps, I'm sure someone has thought of these things before, probably been
answered before, but I'm sure I didn't find reference to them when i
searched.

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


Re: Python's "only one way to do it" philosophy isn't good?

2007-06-15 Thread Douglas Alan
"Terry Reedy" <[EMAIL PROTECTED]> writes:

> Try suggesting on a Lisp or Scheme group that having only one type
> of syntax (prefix expressions) lacks something and that they should
> add variety in the form of statement syntax ;-) Hint: some Lispers
> have bragged here about the simplicity of 'one way to do it' and put
> Python down for its mixed syntax.  (Of course, this does not mean
> that some dialects have not sneaked in lists of statements thru a
> back door ;-).

Almost all Lisp dialects have an extremely powerful macro mechanism
that lets users and communities extend the syntax of the language in
very general ways.  Consequently, dialects such a Scheme try to keep
the core language as simple as possible.  Additional ways of doing
things can be loaded in as a library module.

So, a language such as Scheme may have no *obvious* way of something,
and yet may provide excellent means to extend the language so that
many obvious ways might be provided.

|>oug
-- 
http://mail.python.org/mailman/listinfo/python-list


PIL cutting off letters

2007-06-15 Thread Matt Haggard
I'm using PIL (Python Imaging Library) to generate button images.
They consist of a left end image, a middle, repeating image and a
right side image anyway, that's not important

I'm using a TTF font for the text of the button (Verdana.TTF) and it
keeps cutting the bottom part of the the g's q's and y's off.

Here's the important parts of my code (options contains command-line
params):

im = Image.new("RGB",(1,1))
font = ImageFont.truetype(options.font,options.fontsize)
draw = ImageDraw.Draw(im)
textsize = draw.textsize(options.text, font=font)
im = im.resize( (totalwidth, maxheight) )
draw = ImageDraw.Draw(im)
thecolor = "rgb(0,0,0)"
x = (totalwidth - textsize[0]) / 2
y = (maxheight - textsize[1]) / 2 + options.offsetY
draw.text((x, y), options.text, font=font, fill=thecolor )
im.save(savefile, quality=100)

If I increase the font-size to larger than about 16, the tails
appear... any clue as to why this happens or what I can do to fix it?

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


Re: a_list.count(a_callable) ?

2007-06-15 Thread Carsten Haese
On Fri, 2007-06-15 at 14:39 -0400, Carsten Haese wrote:
> class WhereTrue(object):
> def __init__(self, func):
> self.func = func
> def __eq__(self, other):
> return self.func(other)
> 
> list1.count(WhereTrue(callable1))
> list2.count(WhereTrue(callable2))

P.S: Note, however, that this will only work if the list elements don't
define __eq__ methods themselves. If they do, their __eq__ methods get
called instead of WhereTrue's __eq__ method, leading to incorrect
results.

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: Want to learn Python

2007-06-15 Thread Christof Winter
Amol wrote:
> Hi, I want to learn Python in less than a month which resources should
> I use. I prefer to read books . Please give me a list of *recognized*
> resources. Thank You all

This is an excellent resource:
http://rgruet.free.fr/PQR24/PQR2.4.html

Although it's quite different from a book, I must admit.

Cheers,
Christof

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


Re: a_list.count(a_callable) ?

2007-06-15 Thread Carsten Haese
On Fri, 2007-06-15 at 17:55 +, Ping wrote:
> On 6 16 ,   12 33 , Carsten Haese <[EMAIL PROTECTED]> wrote:
> > Did you see my alternative example on this thread? It allows you to use
> > list.count in almost exactly that way, except that instead of passing
> > the callable directly, you pass an object that defers to your callable
> > in its __eq__ method.
> >
> > HTH,
> >
> > --
> > Carsten Haesehttp://informixdb.sourceforge.net
> 
> Yes, I read it.  This works, but it may make lots of dummy classes
> with the special __eq__ method if I have many criteria to use for
> counting.

No, it won't. You only need one class that is given the criterion at
instantiation time. Something like this:

class WhereTrue(object):
def __init__(self, func):
self.func = func
def __eq__(self, other):
return self.func(other)

list1.count(WhereTrue(callable1))
list2.count(WhereTrue(callable2))

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: a_list.count(a_callable) ?

2007-06-15 Thread BJörn Lindqvist
On 6/15/07, Ping <[EMAIL PROTECTED]> wrote:
> >
> > sum(1 for i in a_list if a_callable(i))
> >
> > --
> > Carsten Haesehttp://informixdb.sourceforge.net
>
> This works nicely but not very intuitive or readable to me.
>
> First of all, the generator expression makes sense only to
> trained eyes.  Secondly, using sum(1 ...) to mean count()
> isn't very intuitive either.
>
> I would still prefer an expression like a_list.count(a_callable),
> which is short, clean, and easy to understand.   :)   However,
> it does produce ambiguities if a_list is a list of callables.
> Should the count() method match values or check return values
> of a_callable?  There are several possible designs but I'm not
> sure which is better.

Maybe you could extend count() analogous to how sort() works:

# L is a list of Person objects, each Person has a name attribute
L.sort(key = attrgetter("name"))

# How many olle are there?
print L.count("olle", key = attrgetter("name"))

# And index could be extended in the same way!
# Whom has id 1234?
print L.index(1234, key = attrgetter("id")).name

All of these could be solved by giving Person an __eq__() method, but
it fails when you need to search, sort or count on a different key.

-- 
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Output of HTML parsing

2007-06-15 Thread Stefan Behnel
Jackie wrote:
> I want to get the information of the professors (name,title) from the
> following link:
> 
> "http://www.economics.utoronto.ca/index.php/index/person/faculty/";

That's even XHTML, no need to go through BeautifulSoup. Use lxml instead.

http://codespeak.net/lxml


> Ideally, I'd like to have a output file where each line is one Prof,
> including his name and title. In practice, I use the CSV module.
> 
> 
> import urllib,re,csv
> 
> url = "http://www.economics.utoronto.ca/index.php/index/person/
> faculty/"
> 
> sock = urllib.urlopen(url)
> htmlSource = sock.read()
> sock.close()

import lxml.etree as et
url = "http://www.economics.utoronto.ca/index.php/index/person/faculty/";
tree = et.parse(url)

> namePattern = re.compile(r'class="name">(.*)')
> titlePattern = re.compile(r', (.*)\s*')
> 
> name = namePattern.findall(htmlSource)
> title_temp = titlePattern.findall(htmlSource)
> title =[]
> for item in title_temp:
> item_new=" ".join(item.split())#Suppress the
> spaces between 'title' and 
> title.extend([item_new])
> 
> 
> output =[]
> for i in range(len(name)):
> output.insert(i,[name[i],title[i]])#Generate a list of
> [name, title]

# untested
get_name_text = et.XPath('normalize-space(td[a/@class="name"]')
name_list = []
for name_row in tree.xpath('//tr[td/a/@class = "name"]'):
  name_list.append(
tuple(get_name_text(name_row).split(",", 3) + ["","",""])[:3] )


> writer = csv.writer(open("professor.csv", "wb"))
> writer.writerows(output)   #output CSV file

writer = csv.writer(open("professor.csv", "wb"))
writer.writerows(name_list) #output CSV file
> -- End of Program
> --
> 
> 3.Should I close the opened csv file("professor.csv")? How to close
> it?

I guess it has a "close()" function?

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


Re: a_list.count(a_callable) ?

2007-06-15 Thread Ping
On 6 16 ,   12 33 , Carsten Haese <[EMAIL PROTECTED]> wrote:
> On Fri, 2007-06-15 at 14:15 +, Ping wrote:
> > using sum(1 ...) to mean count() isn't very intuitive
>
> I find it very intuitive, but then again, my years of studying Math may
> have skewed my intuition.
>
> > I would still prefer an expression like a_list.count(a_callable),
> > which is short, clean, and easy to understand.
>
> Did you see my alternative example on this thread? It allows you to use
> list.count in almost exactly that way, except that instead of passing
> the callable directly, you pass an object that defers to your callable
> in its __eq__ method.
>
> HTH,
>
> --
> Carsten Haesehttp://informixdb.sourceforge.net

Yes, I read it.  This works, but it may make lots of dummy classes
with the special __eq__ method if I have many criteria to use for
counting.  I find the function design mentioned by Dustan most
attractive.  :)

cheers,
Ping

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


Re: Want to learn Python

2007-06-15 Thread Evan Klitzke
On 6/15/07, Amol <[EMAIL PROTECTED]> wrote:
> Hi, I want to learn Python in less than a month which resources should
> I use. I prefer to read books . Please give me a list of *recognized*
> resources. Thank You all

The Apress "Beginning Python" book is the one that I recommend to
people who want to learn the language. I started off with the O'Reilly
book, and that book went too slow and didn't cover as many topic as
the Apress book. If you are an experienced programmer and use the
Apress book, you'll get a pretty good grasp of the language within a
week or so.

-- 
Evan Klitzke <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a_list.count(a_callable) ?

2007-06-15 Thread Ping
On 6 15 ,   11 17 , Dustan <[EMAIL PROTECTED]> wrote:
> On Jun 15, 9:15 am, Ping <[EMAIL PROTECTED]> wrote:
>
> > > sum(1 for i in a_list if a_callable(i))
>
> > > --
> > > Carsten Haesehttp://informixdb.sourceforge.net
>
> > This works nicely but not very intuitive or readable to me.
>
> > First of all, the generator expression makes sense only to
> > trained eyes.  Secondly, using sum(1 ...) to mean count()
> > isn't very intuitive either.
>
> Then wrap it in a function:
> def count(a_list, a_function):
>return sum(1 for i in a_list if a_function(i))
>
> And call the function. You can also give it a different name (although
> I can't think of a concise name that would express it any better).
>

Hmm... This sounds like the best idea so far.  It is efficient both
in memory and time while exposes an easy-to-understand name.
I would name the function count_items though.

n = count_items(a_list, lambda x: x > 3) # very readable  :)

cheers,
Ping

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


Re: Subprocess Not Working on Solaris

2007-06-15 Thread MrJean1
FWIIW, on my Solaris 10 (Opteron) machine, there are no import
subprocess errors, not with Python 2.4.3 nor with Python 2.5.

/Jean Brouwers

PS) Python 2.4.3 is the ActivePython Solaris build 11 from
ActivState.  Python 2.5 was built from source using SUN compilers, not
GNU.  There is an ActivePython Solaris build for 2.5.1 but I have not
tried that one yet.  See 



On Jun 15, 8:00 am, Lee <[EMAIL PROTECTED]> wrote:
> Has anyone ran into this problem? I've done extensive googling and
> research and I cannot seem to find the answer.
>
> I downloaded the source for 2.5.1 from python.org compiled and
> installed it on a Solaris box,
>
> uname -a returns
>
> SunOS unicom5 5.8 Generic_117350-26 sun4u sparc SUNW,Sun-Fire-V210
>
> When I launch the python interpreter, I try the following:
>
> "
> Python 2.5.1 (r251:54863, Jun 13 2007, 13:40:52)
> [GCC 3.2.3] on sunos5
> Type "help", "copyright", "credits" or "license" for more information.>>> 
> import subprocess
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/local/lib/python2.5/subprocess.py", line 401, in 
> import select
> ImportError: No module named select
> "
>
> The subprocess module works just fine on a BSD box I have and after
> doing a 'find' I notice there is a select.so module. This does not
> exist on the Solaris box, only subprocess exists. Within subprocess.py
> on the Solaris box, exists the following:
>
> "
> else:
> import select
> import errno
> import fcntl
> import pickle
> "
>
> Any ideas? I'd like to get the subprocess module working...
>
> -Lee

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


Re:

2007-06-15 Thread David Wahler
On 6/15/07, Wiley Thomas <[EMAIL PROTECTED]> wrote:
> I'm trying to write a script to open a file on our (windows) network.  The
> file is located on a machine that is not part of the domain and requires a
> separate user id and password to access.  I tried using urllib2 and the
> password_manager to authenticate but as some point urllib2 sees I'm trying
> to access a local file and passes it off to os.  The error message I get is:
>
> "WindowsError: [Error 1326] Logon failure: unknown user name or bad
> password: 
> Does anyone know of a better approach.

Urllib2 is used for making HTTP/FTP requests. When you open a file on
a network share, the networking is handled by Windows; as far as
Python is concerned, it's treated the same as a local file.

You could try something like this (untested):

os.system(r"NET USE \\computer\share password /USER:username")
# do something with file
os.system(r"NET USE \\computer\share /DELETE")

That should authenticate and de-authenticate you properly, but it
seems like a fragile way of doing it -- for one thing, I think it
would grant access to any other program running under your login
session. There may be a better way of doing this using the Windows
API. Alternatively, depending on your application, you might want to
consider using a simple web or FTP server.

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


Re: problem on waiting exit thread and write on file

2007-06-15 Thread Flyzone
Marc 'BlackJack' Rintsch ha scritto:
> for thread in threads:
> thread.join()
>
> Much shorter, isn't it!?  :-)

If i do like you tell, all thread will run together right? So i'll get
troubles!
I have a list of hostname, i run a network program and then i need to
write some of the output that give me this command to a file.
If i run the thread together, they can get problems writing on the
same file.
So I have splitted the list in 5 groups, the group 1 have filetmp 1,
group 2 have filetmp 2 and so on...
Then I start one thread for all groups, so 5 threads running together,
the other waiting the end of one of them.

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


Re: Re printing on same line.

2007-06-15 Thread Robert Bauck Hamar
Jerry Hill wrote:

> On 6/15/07, HMS Surprise <[EMAIL PROTECTED]> wrote:
>> I want to print a count down timer on the same line. I tried
>>
>> print '\r', timeLeft,
>>
>> which just appends to the same line.
> 
> Sounds to me like whatever you're printing to doesn't do what you
> expect when it encounters a carriage return (\r).  Is your program
> running in a terminal?  Both the windows cmd.exe shell and bash under
> linux seem to do the right thing when encountering a '\r'.

Actually, bash has nothing to do with how the terminal handles \r. The job
of the shell (bash, ksh, csh, sh ...) is to execute your script when you
type its name.

Outputting a \r might or might not move the cursor to the beginning of the
line. It's completely system specific, and even on the same OS, it depends
on the capabilities of the actual terminal the programs run on, and on some
terminal emulators it might depend on configuration settings.

If you need to explore the capabilities of the terminal, curses will be a
good place to start.

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


Re: global destructor not called?

2007-06-15 Thread Neal Becker
Bruno Desthuilliers wrote:

> Neal Becker a écrit :
>> To implement logging, I'm using a class:
> 
> If I may ask : any reason not to use the logging module in the stdlib ?

Don't exactly recall, but needed some specific behavior and it was just
easier this way.

> 
>> class logger (object):
>> def __init__ (self, name):
>> self.name = name
>> self.f = open (self.name, 'w')
>> def write (self, stuff):
>> self.f.write (stuff)
>> def close (self):
>> self.f.close()
>> def flush (self):
>> self.f.flush()
>> def reopen (self):
>> self.f.flush()
>> self.f.close()
>> os.rename (self.name, self.name + '.old')
>> self.f = open (self.name, 'w')
>> def __del__ (self):
>> try:
>> os.remove (self.name + '.old')
>> except:
>> pass
>> 
>> And setting:
>> sys.stderr = logger(...)
>> 
>> It seems my cleanup (__del__) is never called,
> 
> What makes you think so ?

Cleanup should remove file file '.old', and it wasn't removed.  Adding
atexit.register (self.__del__) to the logger constructor DID fix it.

> 
>> even though I believe my
>> program exits normally.  What's wrong?
> 
> Not enough data...


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

Do U have anything to share with this students

2007-06-15 Thread slvslv89

This is a network of students. Find the people of your kind there

http://tinyurl.com/33uvla

Click and register to access millions of students.

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


Re: dynamically generated runtime methods & reflection

2007-06-15 Thread Bruno Desthuilliers
Alex Martelli a écrit :
> Bruno Desthuilliers <[EMAIL PROTECTED]>
> wrote:
> 
>> Josiah Carlson a écrit :
>> (snip)
>>> Well, the particular operation is typically called 'currying a 
>>> function', 
>> 
>> it's not 'currying' but 'partial application'.
>>
>> Currying is somehow the reverse of partial : it's a way of building a
>> multiple-args function from single-args functions.
>> 
> 
> Wikipedia says 
 >
>"currying or Schönfinkelisation[1] "

cf below...

> "is the technique of
> transforming a function that takes multiple arguments into a function
> that takes a single argument"

The definition commonly agreed upon (in the FP world at least) is that 
currying is the process that "build" ("emulate", whatever...) 
multiple-args functions in a context that only supports single-arg 
functions (ie: ML, Haskell), so that (using Python syntax):

   f(x, y, z)

would really be in fact (and under the hood):

   f(x)(y)(z)

where f(x) returns a function closing over(x) and taking y, itself 
returning a function closing over x and y and taking z...

Talking about this:
"""
currying (...) reduces multiple-argument
functions to single-argument functions only (Schoenfinkel,
1924)
"""
http://srfi.schemers.org/srfi-26/mail-archive/msg00015.html


So while *very closely* related to partial application, it's not exactly 
the same thing.

FWIW, you can also have a look here: 
http://www.python.org/dev/peps/pep-0309/#motivation

> -- and FWIW I agree with Wikipedia in this
> case; 

I don't - and I'm not the only one:

http://lambda-the-ultimate.org/node/2266
"""
I had mistakenly learned that curry was a form of generalized partial 
application from the paper : Function Currying in Scheme by Jeffrey A. 
Meunier
and the Wikipedia entry (I should have known better), however I was 
mildly reprimanded for making this novice mistake in a recent paper 
submission to ICFP
"""

> the reverse (going from single-arg to multiple-args)

Note that I didn't say "going from", but "building". The context is a 
functional language where there's *no* such thing as "multiple args" 
functions.

Re-reading, I can agree that my choice of words may have been a bit 
poor, specially wrt/ the word "reverse". What I meant here was that 
partial application is used in the context of multiple-args function to 
'build' a function taking n-x arguments from a function taking n 
arguments, while currying is used in the context of single-arg functions 
to "emulate" multiple-args functions.

> would be
> "uncurrying", though I don't think I've ever used that term myself.
> 
> functools.partial's name may be more precise (because it can, e.g., go
> from a function taking 3 arguments to one taking 2 -- not just from N
> down to 1)
 >
> but your 'pedantic' remark seems pedantically wrong:-).

I certainly won't pretend knowing more about CS that you do, but given 
the definition of currying in pep-0309 - which exactly matches the 
definition I first learned when toying with Haskell -, I maintain my 
pedantic remark until proven wrong - which BTW should not be overly 
difficult if it happened to be the case !-)

As a last word, the original version of pep-0309 was named "curry", and 
has been corrected since:

"""
It isn't function currying, but partial application. Hence the name is 
now proposed to be partial().
"""
http://www.python.org/dev/peps/pep-0309/#feedback-from-comp-lang-python-and-python-dev

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


Re: Re printing on same line.

2007-06-15 Thread Jerry Hill
On 6/15/07, HMS Surprise <[EMAIL PROTECTED]> wrote:
> I want to print a count down timer on the same line. I tried
>
> print '\r', timeLeft,
>
> which just appends to the same line.

Sounds to me like whatever you're printing to doesn't do what you
expect when it encounters a carriage return (\r).  Is your program
running in a terminal?  Both the windows cmd.exe shell and bash under
linux seem to do the right thing when encountering a '\r'.

On the other hand, running the same code in IDLE doesn't work right,
presumably because the text window doesn't really know what to do with
a bare carriage return.

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


Re: Want to learn Python

2007-06-15 Thread Simon Brunning
On 6/15/07, Amol <[EMAIL PROTECTED]> wrote:
> Hi, I want to learn Python in less than a month which resources should
> I use. I prefer to read books . Please give me a list of *recognized*
> resources. Thank You all

One other invaluable resource: http://mail.python.org/mailman/listinfo/tutor

Cheers,
Simon B.
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a_list.count(a_callable) ?

2007-06-15 Thread Carsten Haese
On Fri, 2007-06-15 at 14:15 +, Ping wrote:
> using sum(1 ...) to mean count() isn't very intuitive

I find it very intuitive, but then again, my years of studying Math may
have skewed my intuition.

> I would still prefer an expression like a_list.count(a_callable),
> which is short, clean, and easy to understand.

Did you see my alternative example on this thread? It allows you to use
list.count in almost exactly that way, except that instead of passing
the callable directly, you pass an object that defers to your callable
in its __eq__ method.

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: Serialization across languages?

2007-06-15 Thread Simon Brunning
On 15 Jun 2007 09:02:34 -0700, Paul Rubin
<"http://phr.cx"@nospam.invalid> wrote:
> Any idea if a C implementation is available?  I mean Python-callable.

There's a fairly in-detail comparison of a number of JSON translators
here: http://tinyurl.com/39zgw4

Cheers,
Simon B.
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Serialization across languages?

2007-06-15 Thread Paul Rubin
Bruno Desthuilliers <[EMAIL PROTECTED]> writes:
> Then I'd second Simon's suggestion to use JSON.

Any idea if a C implementation is available?  I mean Python-callable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: global destructor not called?

2007-06-15 Thread Bruno Desthuilliers
Neal Becker a écrit :
> To implement logging, I'm using a class:

If I may ask : any reason not to use the logging module in the stdlib ?

> class logger (object):
> def __init__ (self, name):
> self.name = name
> self.f = open (self.name, 'w')
> def write (self, stuff):
> self.f.write (stuff)
> def close (self):
> self.f.close()
> def flush (self):
> self.f.flush()
> def reopen (self):
> self.f.flush()
> self.f.close()
> os.rename (self.name, self.name + '.old')
> self.f = open (self.name, 'w')
> def __del__ (self):
> try:
> os.remove (self.name + '.old')
> except:
> pass
> 
> And setting:
> sys.stderr = logger(...)
> 
> It seems my cleanup (__del__) is never called,

What makes you think so ?

> even though I believe my
> program exits normally.  What's wrong?

Not enough data...
-- 
http://mail.python.org/mailman/listinfo/python-list


[no subject]

2007-06-15 Thread Wiley Thomas
I'm trying to write a script to open a file on our (windows) network.
The file is located on a machine that is not part of the domain and
requires a separate user id and password to access.  I tried using
urllib2 and the password_manager to authenticate but as some point
urllib2 sees I'm trying to access a local file and passes it off to os.
The error message I get is:

"WindowsError: [Error 1326] Logon failure: unknown user name or bad
password: -- 
http://mail.python.org/mailman/listinfo/python-list

Re: MySQL - Jython2.2

2007-06-15 Thread HMS Surprise
Thanks, everyone.

I will give it a try. Don't know a lot about mySQL (or any flavor SQL)
but from some minute exposure to the ODBC connector I am guessing that
jdbc provides a connector.

Wish me luck

jh

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


Re: IndentationError: unexpected indent

2007-06-15 Thread Bjoern Schliessmann
"Wim Vogelaar"  wrote:

> You have possibly unvisible tab characters in your file.
> Just copy your lines to the simple MS notepad and try again.

How is he supposed to run MS notepad on X11? :)

Regards,


Björn

P.S.: YES, I know there is wine.

-- 
BOFH excuse #126:

it has Intel Inside

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


Re: poking around a running program

2007-06-15 Thread Bjoern Schliessmann
Paul Rubin wrote:

> Is this kind of thing common?  Has it been done before and are
> there some recipes?  

The Twisted framework offers an interactive Python shell inside the
application (Twisted manhole).

Regards,


Björn

-- 
BOFH excuse #249:

Unfortunately we have run out of bits/bytes/whatever. Don't worry,
the next supply will be coming next week.

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


Re: Re printing on same line.

2007-06-15 Thread HMS Surprise

>... ruining the
> output?
>

? None.

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


Re: Re printing on same line.

2007-06-15 Thread Gabriel Genellina
En Fri, 15 Jun 2007 12:21:01 -0300, HMS Surprise <[EMAIL PROTECTED]>  
escribió:

> I want to print a count down timer on the same line. I tried
>
> print '\r', timeLeft,
>
>
> which just appends to the same line.

It works OK for me. Don't you have any other print statement ruining the  
output?

-- 
Gabriel Genellina

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


Re: Subprocess Not Working on Solaris

2007-06-15 Thread Paul Boddie
On 15 Jun, 17:00, Lee <[EMAIL PROTECTED]> wrote:
> Has anyone ran into this problem? I've done extensive googling and
> research and I cannot seem to find the answer.
>
> I downloaded the source for 2.5.1 from python.org compiled and
> installed it on a Solaris box,

Aren't there additional linking flags for the networking libraries on
Solaris? Did the configure script and the related machinery work this
out, or was the select module disabled as a consequence of such things
not being discovered? It would surprise me somewhat that this still
needed manual adjustment given that this has always been the case with
Solaris.

[...]

> The subprocess module works just fine on a BSD box I have and after
> doing a 'find' I notice there is a select.so module. This does not
> exist on the Solaris box, only subprocess exists.

I imagine that something failed to work as anticipated in the
configuration process.

Paul

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


Re: Html parser

2007-06-15 Thread HMS Surprise
Thanks,

jh

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


Re printing on same line.

2007-06-15 Thread HMS Surprise
I want to print a count down timer on the same line. I tried

print '\r', timeLeft,


which just appends to the same line.


thanx,

jh

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


Re: a_list.count(a_callable) ?

2007-06-15 Thread Dustan
On Jun 15, 9:15 am, Ping <[EMAIL PROTECTED]> wrote:
> > sum(1 for i in a_list if a_callable(i))
>
> > --
> > Carsten Haesehttp://informixdb.sourceforge.net
>
> This works nicely but not very intuitive or readable to me.
>
> First of all, the generator expression makes sense only to
> trained eyes.  Secondly, using sum(1 ...) to mean count()
> isn't very intuitive either.

Then wrap it in a function:
def count(a_list, a_function):
   return sum(1 for i in a_list if a_function(i))

And call the function. You can also give it a different name (although
I can't think of a concise name that would express it any better).

> I would still prefer an expression like a_list.count(a_callable),
> which is short, clean, and easy to understand.   :)   However,
> it does produce ambiguities if a_list is a list of callables.
> Should the count() method match values or check return values
> of a_callable?  There are several possible designs but I'm not
> sure which is better.

Indeed, the ambiguity in that situation would be a reason *not* to
introduce such behavior, especially since it would break older
programs that don't recognize that behavior. Just stick with writing
the function, as shown above.

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


Re: FTP Date Format Function

2007-06-15 Thread samuraisam
On Jun 14, 10:53 pm, billiejoex <[EMAIL PROTECTED]> wrote:
> On 14 Giu, 19:25, samuraisam <[EMAIL PROTECTED]> wrote:
>
>
>
> > FTP LST/LIST/NLST date field formatting function for all those seekers
> > out there...
>
> > import time
> > import datetime
>
> > def ftpdateformat(value):
> > """Formats dates from most FTP servers"""
> > if ":" in value: # within 6 months
> > return datetime.datetime(
> > *time.strptime( # have to guess this calculation
> > "%s %s" % (value, datetime.datetime.now().year),
> > "%b %d %H:%M %Y"
> > )[0:5]
> > ).strftime("%B %d, %Y %H:%M")
> > else: # before six months
> > return datetime.datetime(
> > *time.strptime(value, "%b %d %Y")[0:5]
> > ).strftime("%B %d, %Y")
>
> > I'm not sure if there is a proper algorithm for deciding on a proper
> > year within the last 6 months as it isn't given by most FTP servers.
> > I'd love to amend the function with the correct solution. :)
>
> I didn't well understand your question, anyway...
>
> - FTP got no LST command. What's that?
> - NLST should return filenames only: returned output doesn't contain
> file sizes, last modification time values or whatever.
> - RFC959 gives no specifications about *how* LIST command output
> should be formatted. Depending on the type of server you're talking to
> you could find unix/"ls -l"-like format outputs, DOS-like ones or
> something completely different and your code does not cover all of
> them. Take a look at:http://effbot.org/downloads/#ftpparse

Ah, well if there isn't LST and if NLST doesn't return dates that's
OK, I wasn't sure at the time I authored the post. :)

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


Subprocess Not Working on Solaris

2007-06-15 Thread Lee
Has anyone ran into this problem? I've done extensive googling and
research and I cannot seem to find the answer.

I downloaded the source for 2.5.1 from python.org compiled and
installed it on a Solaris box,

uname -a returns

SunOS unicom5 5.8 Generic_117350-26 sun4u sparc SUNW,Sun-Fire-V210

When I launch the python interpreter, I try the following:

"
Python 2.5.1 (r251:54863, Jun 13 2007, 13:40:52)
[GCC 3.2.3] on sunos5
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python2.5/subprocess.py", line 401, in 
import select
ImportError: No module named select
"

The subprocess module works just fine on a BSD box I have and after
doing a 'find' I notice there is a select.so module. This does not
exist on the Solaris box, only subprocess exists. Within subprocess.py
on the Solaris box, exists the following:

"
else:
import select
import errno
import fcntl
import pickle
"

Any ideas? I'd like to get the subprocess module working...

-Lee

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


Re: MySQL - Jython2.2

2007-06-15 Thread Ant
On Jun 15, 3:31 pm, HMS Surprise <[EMAIL PROTECTED]> wrote:
> I thought I had a winner mySql-python but it require2 python 2.3-5 and
> the tool I am using (maxq) is based on jython 2.2. Is there another
> way that I could perform queries from python?

If you want to query via Jython, use the jdbc driver from www.mysql.com,
and you an then use JDBC from within Jython. You'll just need to add
the mysql jdbc jar to your classpath.

HTH.

--
Ant...

http://antroy.blogspot.com/




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


global destructor not called?

2007-06-15 Thread Neal Becker
To implement logging, I'm using a class:
class logger (object):
def __init__ (self, name):
self.name = name
self.f = open (self.name, 'w')
def write (self, stuff):
self.f.write (stuff)
def close (self):
self.f.close()
def flush (self):
self.f.flush()
def reopen (self):
self.f.flush()
self.f.close()
os.rename (self.name, self.name + '.old')
self.f = open (self.name, 'w')
def __del__ (self):
try:
os.remove (self.name + '.old')
except:
pass

And setting:
sys.stderr = logger(...)

It seems my cleanup (__del__) is never called, even though I believe my
program exits normally.  What's wrong?

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


Re: MySQL - Jython2.2

2007-06-15 Thread Paul Boddie
On 15 Jun, 16:31, HMS Surprise <[EMAIL PROTECTED]> wrote:
> I thought I had a winner mySql-python but it require2 python 2.3-5 and
> the tool I am using (maxq) is based on jython 2.2. Is there another
> way that I could perform queries from python?

For Jython you should use the JDBC driver for the database system in
question (MySQL Connector/J in this case, I believe [1]), either
writing code which uses the JDBC API directly, or using the zxJDBC
module for DB-API compatibility (such as that provided by most other
Python database modules). See here for details:

http://www.jython.org/docs/zxjdbc.html

Paul

[1] http://www.mysql.com/products/connector/j/

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


Re: huge dictionary -> bsddb/pickle question

2007-06-15 Thread Alex Martelli
lazy <[EMAIL PROTECTED]> wrote:
   ...
> key1=>{key11=>[1,2] , key12=>[6,7] ,   }
   ...
> Im processesing  HUGE(~100M inserts into the dictionary) data.

What will you need from the "saved" version later?  If you need lookups
by single keys or key pairs then a relational DB may be best; if you
need to recover the whole huge dictionary into memory (assuming it will
fit, e.g. you have a 64-bit machine with ample RAM) then it might be
more efficient to "dump" things into a custom-designed format.  If I was
uncertain about future uses of the saved data, I'd go for the maximal
flexibility afforded by a relational DB -- if you save to a relational
DB you can later easily use the data in every which way, including
ad-hoc ones (such flexibility is a key architectural feature of
relational databases).  E.g., a single table with 4 fields might be
enough: key, subkey, leftint, rightint -- each field of the appropriate
type (you do tell us that the two ints are smallish integers, but we
don't know directly about the types of the keys -- besides a hint that
the main keys are presumably strings of some kind since that's what
bsddb likes as its own keys, but still, choosing the right kind of
string may be important in order to save space and obtain good
performance).  The (key,subkey) pair would be the primary key on that
table, and unless and until you need peculiar "navigation" in the future
you may not require other indices, constraints, or whatever.

At the scale you're talking about (multi-gigabyte, it appears) it's
probably worth using a powerful DB (such as PostgreSQL, interfacing it
to Python via psycopg2) rather than a lightweight one (such as sqlite,
which comes with Python 2.5); however, depending on how critical
performance is, such issues are often best resolved by benchmarking
(similarly, you might benchmark the performance for inserting into the
properly constrained table from the start, vs originally making the
table constraints-less and using an ALTER TABLE later to add the primary
key constraint/index that will be useful for later lookups; "bulk
insertions" into DBs can often benefit from the latter idea).


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


Re: dynamically generated runtime methods & reflection

2007-06-15 Thread Alex Martelli
Bruno Desthuilliers <[EMAIL PROTECTED]>
wrote:

> Josiah Carlson a écrit :
> (snip)
> > Well, the particular operation is typically called 'currying a 
> > function', 
> 
> 
> it's not 'currying' but 'partial application'.
> 
> Currying is somehow the reverse of partial : it's a way of building a
> multiple-args function from single-args functions.
> 

Wikipedia says "currying or Schönfinkelisation[1] is the technique of
transforming a function that takes multiple arguments into a function
that takes a single argument" -- and FWIW I agree with Wikipedia in this
case; the reverse (going from single-arg to multiple-args) would be
"uncurrying", though I don't think I've ever used that term myself.

functools.partial's name may be more precise (because it can, e.g., go
from a function taking 3 arguments to one taking 2 -- not just from N
down to 1) but your 'pedantic' remark seems pedantically wrong:-).


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


Re: MySQL - Jython2.2

2007-06-15 Thread Carsten Haese
On Fri, 2007-06-15 at 07:31 -0700, HMS Surprise wrote:
> I thought I had a winner mySql-python but it require2 python 2.3-5 and
> the tool I am using (maxq) is based on jython 2.2. Is there another
> way that I could perform queries from python?

The low version number is not your main problem. The main problem is
that Jython is based on Java, and it can not use CPython modules such as
MySQL-python. You'll need JDBC:

http://dev.mysql.com/downloads/connector/j/5.0.html
http://www.jython.org/docs/zxjdbc.html

I have not tried this combination myself, so your mileage may vary, but
in theory this should work.

Good luck,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


MySQL - Jython2.2

2007-06-15 Thread HMS Surprise
I thought I had a winner mySql-python but it require2 python 2.3-5 and
the tool I am using (maxq) is based on jython 2.2. Is there another
way that I could perform queries from python?


thanx,

jh

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


Re: Html parser

2007-06-15 Thread Stephen R Laniel
On Fri, Jun 15, 2007 at 07:11:56AM -0700, HMS Surprise wrote:
> Could you recommend  an html parser that works with python (jython
> 2.2)?

I'm new here, but I believe BeautifulSoup is the canonical
answer:
http://www.crummy.com/software/BeautifulSoup/

-- 
Stephen R. Laniel
[EMAIL PROTECTED]
Cell: +(617) 308-5571
http://laniels.org/
PGP key: http://laniels.org/slaniel.key
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a_list.count(a_callable) ?

2007-06-15 Thread Ping
>
> sum(1 for i in a_list if a_callable(i))
>
> --
> Carsten Haesehttp://informixdb.sourceforge.net

This works nicely but not very intuitive or readable to me.

First of all, the generator expression makes sense only to
trained eyes.  Secondly, using sum(1 ...) to mean count()
isn't very intuitive either.

I would still prefer an expression like a_list.count(a_callable),
which is short, clean, and easy to understand.   :)   However,
it does produce ambiguities if a_list is a list of callables.
Should the count() method match values or check return values
of a_callable?  There are several possible designs but I'm not
sure which is better.

Ping

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


Re: Output of HTML parsing

2007-06-15 Thread Sebastian Wiesner
[ Jackie <[EMAIL PROTECTED]> ]
> 1.The code above assume that each Prof has a tilte. If any one of them
> does not, the name and title will be mismatched. How to program to
> allow that title can be empty?
>
> 2.Is there any easier way to get the data I want other than using
> list?

Use BeautifulSoup.

> 3.Should I close the opened csv file("professor.csv")? How to close
> it?

Assign the file object to a separate name (e.g. stream) and then invoke its 
close method after writing all csv data to it.

-- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)


signature.asc
Description: This is a digitally signed message part.
-- 
http://mail.python.org/mailman/listinfo/python-list

Html parser

2007-06-15 Thread HMS Surprise

Could you recommend  an html parser that works with python (jython
2.2)?   HTMLParser does not seem to be in this library. To test some
of our browser based (mailnly php) code I seek for field names and
values associated with them.

Thanks,

jh

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


RE: Questions about mathematical and statistical functionality in Python

2007-06-15 Thread Talbot Katz
Thank you to all who replied online or offline.  This has been quite 
helpful.

--  TMK  --
212-460-5430home
917-656-5351cell



>From: "John Krukoff" <[EMAIL PROTECTED]>
>To: "'Talbot Katz'" <[EMAIL PROTECTED]>
>CC: 
>Subject: RE: Questions about mathematical and statistical functionality in 
>Python
>Date: Thu, 14 Jun 2007 15:53:40 -0600
>
>On Jun 14, 4:02 pm, "Talbot Katz" <[EMAIL PROTECTED]> wrote:
> > Greetings Pythoners!
> >
> > I hope you'll indulge an ignorant outsider.  I work at a financial
> > software
> > firm, and the tool I currently use for my research is R, a software
> > environment for statistical computing and graphics.  R is designed with
> > matrix manipulation in mind, and it's very easy to do regression and 
>time
> > series modeling, and to plot the results and test hypotheses.  The kinds
> > of
> > functionality we rely on the most are standard and robust versions of
> > regression and principal component / factor analysis, bayesian methods
> > such
> > as Gibbs sampling and shrinkage, and optimization by linear, quadratic,
> > newtonian / nonlinear, and genetic programming; frequently used graphics
> > include QQ plots and histograms.  In R, these procedures are all 
>available
> > as functions (some of them are in auxiliary libraries that don't come 
>with
> > the standard distribution, but are easily downloaded from a central
> > repository).
> >
> > For a variety of reasons, the research group is considering adopting
> > Python.
> >   Naturally, I am curious about the mathematical, statistical, and
> > graphical
> > functionality available in Python.  Do any of you out there use Python 
>in
> > financial research, or other intense mathematical/statistical 
>computation?
> > Can you compare working in Python with working in a package like R or S-
> > Plus
> > or Matlab, etc.?  Which of the procedures I mentioned above are 
>available
> > in
> > Python?  I appreciate any insight you can provide.  Thanks!
> >
> > --  TMK  --
> > 212-460-5430home
> > 917-656-5351cell
> >
> >
> > --
> > http://mail.python.org/mailman/listinfo/python-list
>
>It is worth noting that there's a bridge available to allow python to
>integrate cleanly with R, the Rpy project:
>http://rpy.sourceforge.net/
>
>Which should allow you to use python for whatever it is you need without
>abandoning R for your mathematical/statistical work.
>
>-
>John Krukoff
>[EMAIL PROTECTED]
>


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


Output of HTML parsing

2007-06-15 Thread Jackie
Hi, all,

I want to get the information of the professors (name,title) from the
following link:

"http://www.economics.utoronto.ca/index.php/index/person/faculty/";

Ideally, I'd like to have a output file where each line is one Prof,
including his name and title. In practice, I use the CSV module.

The following is my program:


--- Program


import urllib,re,csv

url = "http://www.economics.utoronto.ca/index.php/index/person/
faculty/"

sock = urllib.urlopen(url)
htmlSource = sock.read()
sock.close()

namePattern = re.compile(r'class="name">(.*)')
titlePattern = re.compile(r', (.*)\s*')

name = namePattern.findall(htmlSource)
title_temp = titlePattern.findall(htmlSource)
title =[]
for item in title_temp:
item_new=" ".join(item.split())#Suppress the
spaces between 'title' and 
title.extend([item_new])


output =[]
for i in range(len(name)):
output.insert(i,[name[i],title[i]])#Generate a list of
[name, title]

writer = csv.writer(open("professor.csv", "wb"))
writer.writerows(output)   #output CSV file

-- End of Program
--

My questions are:

1.The code above assume that each Prof has a tilte. If any one of them
does not, the name and title will be mismatched. How to program to
allow that title can be empty?

2.Is there any easier way to get the data I want other than using
list?

3.Should I close the opened csv file("professor.csv")? How to close
it?

Thanks!

Jackie

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

Re: Want to learn Python

2007-06-15 Thread Joe Riopel
I am still learning and this is a great resource:
http://diveintopython.org/index.html

You can buy it or read it online for free.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unsupported operand type(s) for ^: 'float' and 'float'

2007-06-15 Thread benc
On Jun 15, 9:21 am, Florian Lindner <[EMAIL PROTECTED]> wrote:
> >>> 5.3^4.3
>
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: unsupported operand type(s) for ^: 'float' and 'float'

That operator... I do not think it means what you think it means.

>>> hex(0x1010^0x0110)
'0x1100'

^ is the bitwise XOR operator.  For exponentiation, use **.

>>> 5.3**4.3
1301.326396639844

Hope that helps,
--Ben

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


Re: Want to learn Python

2007-06-15 Thread Eric
On Jun 15, 7:41 am, Amol <[EMAIL PROTECTED]> wrote:
> Hi, I want to learn Python in less than a month which resources should
> I use. I prefer to read books . Please give me a list of *recognized*
> resources. Thank You all

I started here: http://docs.python.org/tut/tut.html

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


Re: Want to learn Python

2007-06-15 Thread Sergio Monteiro Basto
On Fri, 2007-06-15 at 11:41 +, Amol wrote:
> Hi, I want to learn Python in less than a month which resources should
> I use. I prefer to read books . Please give me a list of *recognized*
> resources. Thank You all
> 
Books : 
Learning Python 2nd Edition (ISBN 0-596-00281-5) or above
Python in a nutshell (I guess).
both O'Reilly (r) 
-- 
Sérgio M. B.


smime.p7s
Description: S/MIME cryptographic signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Want to learn Python

2007-06-15 Thread Bruno Desthuilliers
Amol a écrit :
> Hi, I want to learn Python in less than a month which resources should
> I use.

Your brain ?-)

(actually, a computer with Python installed on it may help too...)

> I prefer to read books .

Books are fine, but won't be of much help unless you actually *code* in 
Python.

> Please give me a list of *recognized*
> resources. 

http://wiki.python.org/moin/IntroductoryBooks
=> I'd recommand Mark Lutz's books and/or Mark Pilgrim's Dive Into Python

http://wiki.python.org/moin/AdvancedBooks
=> the Python CookBook


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


Re: dynamically generated runtime methods & reflection

2007-06-15 Thread Bruno Desthuilliers
Josiah Carlson a écrit :
(snip)
> Well, the particular operation is typically called 'currying a 
> function', 


it's not 'currying' but 'partial application'.

Currying is somehow the reverse of partial : it's a way of building a 
multiple-args function from single-args functions.

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


PythonWin crash - works only once after installation

2007-06-15 Thread Ze'ev
Hi,
  I've installed Python 2.5 and PythonWin (pywin32-210.win32-py2.5) on
my new XP machine. The first time I run PythonWin after installation
it runs normally but if I close it and try to run it again it crashes
("PyWin32 has encountered a problem and needs to close") every time.
If I re-install it then it will run once more but subsequent runs
fail.
I've installed and ran this before (on my old machine and at work) and
it runs ok.

Any clues?

Thanks,
Ze'ev

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


Re: using Mac OS X CoreGraphics via ctypes

2007-06-15 Thread Daniel
> > # the next line causes a segfault - what's the right way to do this?
> > #GCS_RGB = cglib.kCGColorSpaceGenericRGB()
>
> Usually, things in the OSX lib that start with k* are a constant - not a
> function. As is this.
>
> Diez

That's what I thought too. But when I try passing it directly as if it
were a constant:

GCS_RGB = cglib.kCGColorSpaceGenericRGB
cs = cglib.CGColorSpaceCreateWithName(GCS_RGB)

I get a segfault too. ctypes said kCGColorSpaceGenericRGB was a
function pointer, so I thought maybe I needed to call it to get the
value (not very good reasoning, I know).

~ Daniel

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


Re: Want to learn Python

2007-06-15 Thread jitudon
On Jun 15, 4:41 pm, Amol <[EMAIL PROTECTED]> wrote:
> Hi, I want to learn Python in less than a month which resources should
> I use. I prefer to read books . Please give me a list of *recognized*
> resources. Thank You all

http://python.org/doc/

JItendra Nair

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


Want to learn Python

2007-06-15 Thread Amol
Hi, I want to learn Python in less than a month which resources should
I use. I prefer to read books . Please give me a list of *recognized*
resources. Thank You all

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


Re: Serialization across languages?

2007-06-15 Thread Steve Howell

--- Bruno Desthuilliers
<[EMAIL PROTECTED]>
wrote:

> Tobiah a écrit :
> > I want to do SOAP like calls from a device who's
> libraries
> > don't include SOAP.  I'm thinking of using simple
> HTTP posts,
> > but I'm going to want to send arrays and hashes.
> 
> Then I'd second Simon's suggestion to use JSON.
> 

I'll third it.

Another thing to look at may be YAML:

http://www.yaml.org/start.html
http://www.yaml.org/
http://www.yaml.org/discuss.html

There are implementations in Python, Ruby, Perl, Java,
Javascript, etc.:

http://www.yaml.org/download.html

One thing that YAML has strived for, and largely got
for free through fortunate coincidence, was
compatibility with JSON.




   
Ready
 for the edge of your seat? 
Check out tonight's top picks on Yahoo! TV. 
http://tv.yahoo.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Serialization across languages?

2007-06-15 Thread Bruno Desthuilliers
Tobiah a écrit :
> I want to do SOAP like calls from a device who's libraries
> don't include SOAP.  I'm thinking of using simple HTTP posts,
> but I'm going to want to send arrays and hashes.

Then I'd second Simon's suggestion to use JSON.

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


Re: save class

2007-06-15 Thread Diez B. Roggisch
> of having to keep track of a separate dictionary file. I am new to
> this, but I thought that this would be a regular thing to do in
> python, because people must make classes in the interactive console
> and then export them somehow for later use.

No. That's not how things work. One does dabble with the interpreter a 
bit, sometimes even creating a tiny class.

But except from the occasional expression tested in the interpreter, 
it's not common to use that code and save it.

Write python-files from the start. Then either execute them

python myfile.py

or if you insist, do


python

 >>> import myfile
 >>> myfile.some_function()


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


Re: huge dictionary -> bsddb/pickle question

2007-06-15 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, lazy wrote:

> I have a dictionary something like this,
> 
> key1=>{key11=>[1,2] , key12=>[6,7] ,   }
> For lack of wording, I will call outer dictionary as dict1 and its
> value(inner dictionary) dict2 which is a dictionary of small fixed
> size lists(2 items)
> 
> The key of the dictionary is a string and value is another dictionary
> (lets say dict2)
> dict2 has a string key and a list of 2 integers.
> 
> Im processesing  HUGE(~100M inserts into the dictionary) data.
> I tried 2 options both seem to be slower and Im seeking suggestions to
> improve the speed. The code is sort of in bits and pieces, so Im just
> giving the idea.
> 
> […]
> 
> This is not getting to speed even with option 2. Before inserting, I
> do some processing on the line, so the bottleneck is not clear to me,
> (i.e in processing or inserting to db). But I guess its mainly because
> of pickling and unpickling.
> 
> Any suggestions will be appreciated :)

I guess your guess about the pickling as bottleneck is correct but
measuring/profiling will give more confidence.

Maybe another database than bsddb might be useful here.  An SQL one like
SQLite or maybe an object DB like zodb or Durus.

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

WebThumb

2007-06-15 Thread Johny
How can I get a website thumbnail?
I would like to allow visitors to add their URLs  to our pages with
the thumbnail of their website.
Can anyone suggest a solution for web thumbnails?
Thanks
L.

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


Re: Serialization across languages?

2007-06-15 Thread Simon Brunning
On 6/14/07, Tobiah <[EMAIL PROTECTED]> wrote:
> I want to do SOAP like calls from a device who's libraries
> don't include SOAP.  I'm thinking of using simple HTTP posts,
> but I'm going to want to send arrays and hashes.
>
> First, what do I need to be aware of when sending arbitrary
> data by a POST, and Second, is there a universally supported
> version of what python can do with pickle?  I mostly need
> python and PHP, but perl would be nice too.

JSON might be worth a look. There are libraries available for loads of
languages, and it's fairly human readable to boot.

-- 
Cheers,
Simon B.
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues
-- 
http://mail.python.org/mailman/listinfo/python-list


huge dictionary -> bsddb/pickle question

2007-06-15 Thread lazy
Hi,

I have a dictionary something like this,

key1=>{key11=>[1,2] , key12=>[6,7] ,   }
For lack of wording, I will call outer dictionary as dict1 and its
value(inner dictionary) dict2 which is a dictionary of small fixed
size lists(2 items)

The key of the dictionary is a string and value is another dictionary
(lets say dict2)
dict2 has a string key and a list of 2 integers.

Im processesing  HUGE(~100M inserts into the dictionary) data.
I tried 2 options both seem to be slower and Im seeking suggestions to
improve the speed. The code is sort of in bits and pieces, so Im just
giving the idea.

1) Use bsddb. when an insert is done, the db will have key1 as key and
the value(i.e db[key1] will be be pickleled value of dict2). after
1000 inserts , I close and open the db ,inorder to flush the contents
to disk. Also when I try to insert a key, if its already present, I
unpickle the value and change something in dict2 and then pickle it
back to the bsddb.

2)Instead of pickling the value(dict2) and storing in bsddb
immediately, I keep the dict1(outer dictionary in memory) and when it
reaches 1000 inserts, I store it to bsddb as before, pickling each
individual value. The advantage of this is, when one insert is done,
if its already present, I adjust the value and I dont need to unpickle
and pickle it back, if its the memory. If its not present in memory, I
will still need to lookup in bsddb

This is not getting to speed even with option 2. Before inserting, I
do some processing on the line, so the bottleneck is not clear to me,
(i.e in processing or inserting to db). But I guess its mainly because
of pickling and unpickling.

Any suggestions will be appreciated :)

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


Re: Help with PAM and ctypes

2007-06-15 Thread Lenard Lindstrom
Chris AtLee wrote:
> On Jun 11, 6:01 pm, Lenard Lindstrom <[EMAIL PROTECTED]> wrote:
> [snip snip snip]
>>> if __name__ == "__main__":
>>> import getpass, os, sys
>>> @conv_func
>>> def my_conv(nMessages, messages, pResponse, appData):
>>> # Create an array of nMessages response objects
>>> # Does r get GC'ed after we're all done?
>>> r = (pam_response * nMessages)()
>> The memory allocated to r is garbage collected immediately after my_conv
>> returns. You need to allocate it explicitly using C's calloc or such.
>> This assumes pam_start will free the memory for you.
>>
>> addr = calloc(sizeof(pam_response), nMessages)
>>
>> addr is the memory address as a Python integer.
>>
>>> pResponse.contents = cast(r, POINTER(pam_response))
>> pResponse.contents changes the actual value of pResponse, a value on the
>> stack. You want to change the value of the pointer pResponse points to:
>>
>> pResponse[0] = cast(addr, POINTER(pam_response))
>>
>> The cast creates a POINTER(pam_reponse) instance with value addr.
> 
> Ahhh, thank you!  I never understood how ctypes' pointer.contents
> related
> to C pointers.  So, the following are equivalent?
> 
> int  v = 42;v = 42
> int *p = 0; p = cast(0, POINTER(c_int))
> p = &v; p.contents = v
> *p = 123;   p[0] = 123

Actually

int v = 42; v = c_int(42)

for p.contents = v to work. 42 is a Python integer. c_int(42) refers to 
a mutable C integer in memory initialized to 42. Also, the preferred way 
to create a NULL pointer in ctypes is to call the pointer type without 
an argument:

int *p = 0; p = POINTER(c_int)()


> 
> Using "pResponse[0] = cast(...)" got me part of the way to fixing my
> problem.  PAM started either crashing or saying authentication had
> failed.
> The crash was in free(), and some digging around revealed that PAM
> tries to
> free the response sent by the application, which makes sense.
> 
> My initial attempt to fix this involved wrapping strdup to allocate a
> new
> copy of a string to send back to PAM.  Here's how I wrapped it:
> 
> strdup = libc.strdup
> strdup.argstypes = [c_char_p]
> strdup.restype = c_char_p
> 
> This still crashed in free().  I took a look at some of the ctypes
> regression tests and something made me try this:
> 
> strdup = libc.strdup
> strdup.argstypes = [c_char_p]
> strdup.restype = POINTER(c_char) # NOT c_char_p 
> 
> This works like a charm.  Not sure why though...Does ctypes do
> something
> special with c_char_p return types?  It seems as if Python was freeing
> the
> result of strdup() when the string was GC'ed, and then PAM would fail
> when
> trying to free the same memory.
> 

c_char_p implicitly converts to/from a Python string. So strdup with a 
c_char_p restype returns a copy of the returned C string as a Python 
string instead of a pointer to the memory allocated by strdup. And I 
don't know how a Python string is cast to a c_char_p.

--
Lenard Lindstrom
<[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >