Re: Self function

2009-05-05 Thread Carl Banks
On May 4, 8:26 pm, Steven D'Aprano
 wrote:
> On Mon, 04 May 2009 16:33:13 -0700, Carl Banks wrote:
> > On May 4, 4:06 pm, [email protected] wrote:
> >> Carl Banks:
>
> >> >1. Singly-linked lists can and should be handled with iteration.<
>
> >> I was talking about a binary tree with list-like topology, of course.
>
> > "(every node has 1 child, and they are chained)"
>
> > That's a singly-linked list, not a tree.  It's a degenerate tree at
> > best.
>
> A singly-linked list is a degenerate tree. Not "at best", but "is".

No, many implemenations of singly-linked lists aren't trees by any
definition.  You are probably thinking of the bastardized list-tree
spawn they use in Lisp.  But many implementations don't even bother
with a cons cell and just have the object itself refer to the next
object.  That is not a tree.

But even singly-linked lists implemented with cons cells can be
handled, and are better handled, with interation.


> >> >All recursion does it make what you're doing a lot less readable for
> >> >almost all programmers.<
>
> >> I can't agree.
>
> > If every child has one node you don't need recursion.
>
> And if one single node in the entire tree has two children, you do.

Then it't not a singly-linked list.  It's a tree.


> What
> are you suggesting, that Bearophile should write his tree-processing code
> to only deal with the degenerate case?

I'm suggesting that Bearophile should write recursive code for his
trees and iterative code for his lists.


> >> If the data structure is recursive (like a tree, or even sometimes
> >> graphs, etc) a recursive algorithm is shorter, more readable and more
> >> natural.
>
> > Because that's a tree, not a linked-list.
>
> And a linked list is a degenerate tree. If you have a non-self-balancing
> tree, sometimes it will be degenerate, and your code needs to deal with
> it.

If you have a tree, then you use recursive code.  If you have a list
you use iterative code.


> > Which is germane because Python's recursion limit is the thing you're
> > complaining about here, and you don't normally hit that limit with real
> > trees because they rarely go 1000 deep.
>
> And if just ONE branch of the tree goes 1000 deep, even if the rest of
> the tree is shallow, then you hit the default recursion limit.

Yeah, well, see that's just the point here.  Bearophile was asked if
any of his trees go 1000 deep, he said yes, his singly-linked lists
do.  Well, I'm sorry, that's not going to convince me, because
bearophile should be using iteration for the singly-linked lists.

Bearophile might very well have real trees that are 1000 deep, but
that's not going to convince me either, because IMO real trees rarely
do that, and Python's recursion limit can be increased in the rare
cases they do.

Bearophile and you are welcome to try to convince me that there are
lots of real trees out there that can't be handled with iteration and
that do go 1000 deep, and that this is a common enough problem that
Python should drastically improve support for recursion.  Until then I
will opine that it is adequate now for almost all purposes.


> > Singly-linked lists don't count because you don't need recursion for
> > them.
>
> If each node has two (or more) child fields, even if only one of those
> children is non-empty, then your data structure is a degenerate tree and
> does count.

If one of the fields is always empty, you don't need recursion to deal
with it.


> > [snip strawman example]
>
> It's not a strawman just because you don't like it.

No, it's a strawman because I said singly-linked lists don't need
recursion, and his counterexample was showing that recursion was
useful a tree.  Which was true, but it wasn't answering my argument.


> Dealing with
> degenerate trees is a genuine issue, and avoiding degenerate trees is the
> reason why people have developed more complicated structures like red-
> black trees.

I'm not talking about degenerate trees.  I'm talking about singly-
linked lists, which you DO NOT NEED, and SHOULD NOT USE, recursion to
deal with.


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


Re: Self function

2009-05-05 Thread Arnaud Delobelle
On 5 May, 07:08, Steven D'Aprano
 wrote:
> On Mon, 04 May 2009 17:54:50 -0400, Terry Reedy wrote:
> > [email protected] wrote:
>
> >> Another possible syntax:
>
> >> def fact(n):
> >>     return 1 if n <= 1 else n * return(n - 1)
>
> >> But I guess most people don't see this problem as important&common
> >> enough to justify changing the language.
>
> > Actually, I would like a way to refer to the current function from
> > inside a function.  but I would like support in the language, so that
> > the compiler patched the code after the function object is created to
> > directly refer to the function object (or can the code object call the
> > code object?) without any name lookup at all.
>
> I don't know about avoiding name lookup, that smacks of deepest black
> magic, and Python doesn't usually do that. It does however do parlour
> tricks like `__name__` and `self`, suggests a solution.
>
> I propose a small piece of sugar. When a function is entered, Python
> creates an ordinary local name in the function's local namespace, and
> binds the function itself to that name. Two possibilities for the name
> are `this` or `__this__`, analogous to `self` in methods and `__name__`
> in modules.
>
> If there is any support for this, I propose to send the following (long)
> post to python-ideas. Feedback, corrections and suggestions welcome.
>
> * * *
>
> Summary:
>
> Most objects in Python don't need to know what name, or names (if any)
> they are bound to. Functions are a conspicuous exception to that rule:
> there are good reasons for a function to refer to itself, and the only
> straightforward way to do so is by name. I propose that on calling a
> function, Python should create a local name which refers to the function
> itself, giving the programmer the ability to have a function refer to
> itself without using its name.
>
> There are (at least) four reasons for a function to refer to itself. In
> no particular order:
>
> (1) User-friendly messages (for logging, errors or other):
>
> def parrot():
>     print "Error feeding cracker to function %r" % parrot
>
> (2) Recursion:
>
> def spam(n):
>     if n < 0: return spam(-n).upper()
>     return "spam "*n
>
> (3) Introspection:
>
> def spanish_inquisition():
>     print inspect.getmembers(spanish_inquisition)
>
> (4) Storing data between function calls:
>
> def cheeseshop():
>     if hasattr(cheeseshop, 'cheeses'):
>         print "We have many fine cheeses"
>     else:
>         print "I'm sorry, I have been wasting your time"
>
> I call these self-reflective functions.
>
> In some cases there are alternatives e.g. cheeseshop could be written as
> a functor object, or some recursive functions can be re-written as
> iteration. Nevertheless such self-reflective functions are acceptable to
> many people, and consequently in moderately common use. How to have a
> function refer to itself is a common question, e.g. for newbies:
>
> http://www.mail-archive.com/tutor%40python.org/msg35114.html
>
> and even more experienced programmers:
>
> http://article.gmane.org/gmane.comp.python.general/622020
>
> (An earlier draft of this proposal was sent to that thread.)
>
> However, none of these functions are robust in the face of the function
> being renamed, either at runtime or in the source code. In general, this
> will fail for any of the above functions:
>
> func = spam
> del spam
> func()
>
> Self-reflective functions like these are (almost?) unique in Python in
> that they require a known name to work correctly. You can rename a class,
> instance or module and expect it to continue to work, but not so for such
> functions. When editing source code, it is very easy to forget to change
> all the references to the function name within the body of itself
> function, even for small functions, and refactoring tools are overkill.
>
> My proposal is for Python to automatically generate a local variable
> named either `this` or `__this__` when entering a function. This will
> allow any of the above functions to be re-written using the special name,
> and become robust against name changes.
>
> def spanish_inquisition():
>     print inspect.getmembers(__this__)
>
> fang = spanish_inquisition
> del spanish_inquisition
> fang()
>
> It will also allow lambda to use recursion:
>
> lambda n: 0 if n <= 1 else __this__(n-1)
>
> (This may count as a point against it, for those who dislike lambda.)
>
> It is often useful to create two similar functions, or a variant of a
> function, without duplicating the source code. E.g. you might want a
> function that uses a cache, while still keeping around the version
> without a cache:
>
> cached_function = memoize(function)
>
> Currently, this does not give the expected results for recursive
> functions, nor does it give an error. It simply fails to behave as
> expected. Re-writing function() to use __this__ for the recursive call
> will solve that problem.
>
> Q: Will `__this__` or `this` clash with existing variables?
>
> I prefer `this

Re: Self function

2009-05-05 Thread CTO
On May 5, 2:08 am, Steven D'Aprano
 wrote:
> On Mon, 04 May 2009 17:54:50 -0400, Terry Reedy wrote:
> > [email protected] wrote:
>
> >> Another possible syntax:
>
> >> def fact(n):
> >>     return 1 if n <= 1 else n * return(n - 1)
>
> >> But I guess most people don't see this problem as important&common
> >> enough to justify changing the language.
>
> > Actually, I would like a way to refer to the current function from
> > inside a function.  but I would like support in the language, so that
> > the compiler patched the code after the function object is created to
> > directly refer to the function object (or can the code object call the
> > code object?) without any name lookup at all.
>
> I don't know about avoiding name lookup, that smacks of deepest black
> magic, and Python doesn't usually do that. It does however do parlour
> tricks like `__name__` and `self`, suggests a solution.
>
> I propose a small piece of sugar. When a function is entered, Python
> creates an ordinary local name in the function's local namespace, and
> binds the function itself to that name. Two possibilities for the name
> are `this` or `__this__`, analogous to `self` in methods and `__name__`
> in modules.
>
> If there is any support for this, I propose to send the following (long)
> post to python-ideas. Feedback, corrections and suggestions welcome.

[snip proposal]

I'm not all that in favor of this, but I think I've got another use
case
for you at http://code.activestate.com/recipes/576731/. The functions
written to use it would be a lot more standard looking at least.

Geremy Condra

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


Re: Self function

2009-05-05 Thread Paul Rubin
[email protected] writes:
> This happens to me more than one time every year.
> So I have written this:
> ...
> self_name = getframeinfo(currentframe()).function

ZOMG, you've got to be kidding.  I'd expect Pylint to catch that sort
of error statically.  If not, the best approach is probably to extend
Pylint to handle those cases.  The frame crawling stuff just comes
across as madness to me.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Which one is best Python or Java for developing GUI applications?

2009-05-05 Thread Paul Rubin
srinivasan srinivas  writes:
> Could you tell me does Python have any advantages over Java for the 
> development of GUI applications?

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


Re: Code works fine except...

2009-05-05 Thread John Yeung
On May 5, 1:12 am, John Yeung  wrote:

> [...] the problem may require bigger guns (either much better
> math or much more sophisticated programming).

Yes, I'm responding to myself.

Well, I went ahead with the approach I mentioned earlier, generating
all possible matches and then selecting among them as needed to fill
up the courts, trying to keep the number of matches played by each
player as fair as possible.  (I should mention that this, or something
similar, was suggested earlier by someone else in a different thread,
in response to the same question by the same OP.)

I did use "bigger guns" (mainly a class for player objects, with
custom __cmp__ method), but still didn't do anything with doubles.

I haven't tested it much, but I'll post it if anyone's interested.
(That way people can pick on me instead of the OP. ;)

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


Re: Personal recommendations for Python and Django on-boarding materials

2009-05-05 Thread Bruno Desthuilliers

Arnaud Delobelle a écrit :

Grant Rettke  writes:


Hi folks,

From one developer to another, I am looking for some personal
recommendations on what are the best materials for fast tracking an on-
boarding to Python and Django.

I know how to program, get web apps and OO; this is the audience.

I have found some good recommendations and stuff on Amazon and various
websites, but if I could get some humans vouching for things directly
that would be worth a lot more.

Best wishes,

Grant


I've learnt both Python and Django using the tutorials, the docs and
lots of experimentation.





 Django now have a book [1] which might be
useful to read.

[1] http://djangobook.com/




You may also want to join the django-users group, browse 
django-snippets, and read James Bennet's blog.


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


Re: Which one is best Python or Java for developing GUI applications?

2009-05-05 Thread Bruno Desthuilliers

Paul Rubin a écrit :

srinivasan srinivas  writes:

Could you tell me does Python have any advantages over Java for the development 
of GUI applications?


Yes.


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


Re: Tkinter, Trouble with Message,Label widget

2009-05-05 Thread Hendrik van Rooyen
"norseman"  wrote:

> Hendrik van Rooyen  mentioned the textvar too.  Thanks Hendrik

Yeah - and also omitted to mention the set method.
With friends like that, who needs enemies?

- Hendrik

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


Re: Which one is best Python or Java for developing GUI applications?

2009-05-05 Thread Leon
I think there are two advantages over java for GUI application

First, python is more productive and has very rich third modules
support,
you can check the demo of wxPython.

Second, you can develop native-looking GUI

BTW: I'm developing GUI application using python and wxPython.



Second,
On May 4, 11:41 pm, srinivasan srinivas 
wrote:
> Could you tell me does Python have any advantages over Java for the 
> development of GUI applications?
>
> Thanks,
> Srini
>
>       Now surf faster and smarter ! Check out the new Firefox 3 - Yahoo! 
> Editionhttp://downloads.yahoo.com/in/firefox/?fr=om_email_firefox

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


Re: Self function

2009-05-05 Thread Steven D'Aprano
On Mon, 04 May 2009 23:09:25 -0700, Carl Banks wrote:

> On May 4, 8:22 pm, Steven D'Aprano
>  wrote:
>> On Mon, 04 May 2009 15:51:15 -0700, Carl Banks wrote:
>> > All
>> > recursion does it make what you're doing a lot less readable for
>> > almost all programmers.
>>
>> What nonsense.
> 
> It's not nonsense for a singly-linked list.

def ivisit(node):
print node
while node and node.link is not None:
node = node.link
print node

def rvisit(node):
print node
if node and node.link is not None:
rvisit(node.link)


If there are programmers who find rvisit "a lot less readable" than 
ivisit, then in my arrogant opinion they should consider a change of 
profession.



> I don't need to be taught
> the benefit of recursion, but whenever interation is suitable for an
> algorithm/data structure, as it is with singly-linked lists, then it is
> the more readable and more preferrable choice, especially in Python.

Most (all?) recursive algorithms can be re-written as iteration. For many 
recursive algorithms (but not all) the cost for doing so is to simulate 
recursion yourself by managing your own stack. By making such an 
absolutist claim, you're claiming that it is "more readable" and "more 
preferable" to manage your own stack than to let the compiler do so. 
That's clearly nonsense.

Whenever iteration gives a simpler and more readable algorithm than 
recursion, then it should be preferred on account of being simpler and 
more readable. That's not just a no-brainer, it's a tautology. "Whenever 
iteration is simpler, it's simpler." But that's a far cry from what you 
said: that recursion, as a general technique, is "a lot less readable" 
for "almost all" programmers.


 
> In Python the One Obvious Way is iteration when possible, recursion when
> necessary.

There's nothing "obvious" about solving the 8 Queens problem using 
iteration. Or walking a binary tree. Or generating all the permutations 
of a list.

But don't just tell me that recursion isn't Pythonic. Tell Guido:

http://www.python.org/doc/essays/graphs.html

I quote:

"These [recursive] functions are about as simple as they get. Yet, they 
are nearly optimal (for code written in Python)."



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


Re: Which one is best Python or Java for developing GUI applications?

2009-05-05 Thread Paul Rudin
Paul Rubin  writes:

> srinivasan srinivas  writes:
>> Could you tell me does Python have any advantages over Java for the
>> development of GUI applications?
>
> Yes.

Clearly c.l.p needs to adopt the SNB 
convention :) 
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-05 Thread Steven D'Aprano
On Tue, 05 May 2009 00:09:27 -0700, Arnaud Delobelle wrote:

> Are you aware of PEP 3130? http://www.python.org/dev/peps/pep-3130/

I am now. Very disappointing.

> (BTW, it seems to me that your implementation breaks as soon as two
> functions are decorated - not tested!)

Of course it does! That's why I warned that I was "abusing a global 
variable", and that it should not be read as meaning that I wanted 
__this__ to be global. I want it to be local to the function.


If somebody can tell me how to inject a new local name into a function, 
that would be far preferable to using global in the decorator.



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


Re: Self function

2009-05-05 Thread Carl Banks
On May 5, 12:51 am, Steven D'Aprano
 wrote:
> On Mon, 04 May 2009 23:09:25 -0700, Carl Banks wrote:
> > In Python the One Obvious Way is iteration when possible, recursion when
> > necessary.
>
> There's nothing "obvious" about solving the 8 Queens problem using
> iteration. Or walking a binary tree. Or generating all the permutations
> of a list.

*Sigh*  Well, I'm out of this debate.  Apparently it's not possible to
argue that recursivie algorithms should be avoided *sometimes* without
everyone citing cases that obviously aren't from those times (as if I
had been arguing that recursion should be avoided all the time).

Here's a parting thought for you to cite "counterexamples" of:

Iteration should be used instead of recursion anywhere a tail-
recursive algorithm is possible.  Recursion should be used only when
tail-recursion is not possible.


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


Re: Self function

2009-05-05 Thread wolfram . hinderer
On 5 Mai, 08:08, Steven D'Aprano
 wrote:

> Self-reflective functions like these are (almost?) unique in Python in
> that they require a known name to work correctly. You can rename a class,
> instance or module and expect it to continue to work, but not so for such
> functions. When editing source code, it is very easy to forget to change
> all the references to the function name within the body of itself
> function, even for small functions, and refactoring tools are overkill.

It is easy to change all references of the function name, except for
those in the function body itself? That needs some explantation.

> It is often useful to create two similar functions, or a variant of a
> function, without duplicating the source code. E.g. you might want a
> function that uses a cache, while still keeping around the version
> without a cache:
>
> cached_function = memoize(function)
>
> Currently, this does not give the expected results for recursive
> functions, nor does it give an error. It simply fails to behave as
> expected. Re-writing function() to use __this__ for the recursive call
> will solve that problem.

Won't __this__ (inside function) still refer to function, not
cached_function?

> Here is a proof-of-concept pure Python implementation, using a decorator,
> and abusing a global variable. This is NOT to imply that `__this__`
> should be a global if this proposal goes ahead.
>
> from functools import wraps
> def make_this(func):
>     global __this__
>     __this__ = func
>     @wraps(func)
>     def f(*args, **kwargs):
>         return func(*args, **kwargs)
>     return f

This still has the memoizing problem.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-05 Thread Steven D'Aprano
On Mon, 04 May 2009 23:55:41 -0700, Carl Banks wrote:

> On May 4, 8:26 pm, Steven D'Aprano
>  wrote:
>> On Mon, 04 May 2009 16:33:13 -0700, Carl Banks wrote:
>> > On May 4, 4:06 pm, [email protected] wrote:
>> >> Carl Banks:
>>
>> >> >1. Singly-linked lists can and should be handled with iteration.<
>>
>> >> I was talking about a binary tree with list-like topology, of
>> >> course.
>>
>> > "(every node has 1 child, and they are chained)"
>>
>> > That's a singly-linked list, not a tree.  It's a degenerate tree at
>> > best.
>>
>> A singly-linked list is a degenerate tree. Not "at best", but "is".
> 
> No, many implemenations of singly-linked lists aren't trees by any
> definition.

I would say not. Nodes with a single link field can't form a tree, 
because you can't give it a left and right child. However trees can 
degenerate into a singly-linked list, where each node has at least one 
unused child. That is what both Bearophile and I are trying to tell you. 
It's not that anyone sane thinks "I know, I'll use a binary tree to 
implement a linked list" -- that would be stupid, and shame on you for 
thinking that Bearophile is that stupid. But if you insert data into a 
non-self-balancing tree, sometimes the tree will degenerate into a linked 
list with extra, unused child links.


[...]
> But even singly-linked lists implemented with cons cells can be handled,
> and are better handled, with interation.

Can be, certainly.

Better? Maybe.


>> >> >All recursion does it make what you're doing a lot less readable
>> >> >for almost all programmers.<
>>
>> >> I can't agree.
>>
>> > If every child has one node you don't need recursion.
>>
>> And if one single node in the entire tree has two children, you do.
> 
> Then it't not a singly-linked list.  It's a tree.

It was already a tree. It's just that the entire tree happened to form 
one long chain.



>> What
>> are you suggesting, that Bearophile should write his tree-processing
>> code to only deal with the degenerate case?
> 
> I'm suggesting that Bearophile should write recursive code for his trees
> and iterative code for his lists.

But his tree-handling recursive code MUST and WILL operate on degenerate 
trees that form chains (linked lists), unless he writes more complicated 
code to avoid it (e.g. red-black trees). For simple trees, you don't have 
the luxury of saying "Oh, my trees will never be degenerate, they'll 
always be optimal, with the minimum depth possible." You get the trees 
you're given, and sometimes they'll be one long branch with no, or very 
fewer, off-shoots, and you'll have O(N) performance instead of O(log N).

And the clever thing?

Just write the recursive code, as normal, and it will magically handle 
the degenerate case too.



>> >> If the data structure is recursive (like a tree, or even sometimes
>> >> graphs, etc) a recursive algorithm is shorter, more readable and
>> >> more natural.
>>
>> > Because that's a tree, not a linked-list.
>>
>> And a linked list is a degenerate tree. If you have a
>> non-self-balancing tree, sometimes it will be degenerate, and your code
>> needs to deal with it.
> 
> If you have a tree, then you use recursive code.  If you have a list you
> use iterative code.

I wish to retract my poorly worded comment "And a linked list is a 
degenerate tree". That is incorrect. What I should have said is that a 
degenerate tree behaves equivalently to a linked list, rather than "is".



>> > Which is germane because Python's recursion limit is the thing you're
>> > complaining about here, and you don't normally hit that limit with
>> > real trees because they rarely go 1000 deep.
>>
>> And if just ONE branch of the tree goes 1000 deep, even if the rest of
>> the tree is shallow, then you hit the default recursion limit.
> 
> Yeah, well, see that's just the point here.  Bearophile was asked if any
> of his trees go 1000 deep, he said yes, his singly-linked lists do. 

He certainly did not say anything of the sort.


> Well, I'm sorry, that's not going to convince me, because bearophile
> should be using iteration for the singly-linked lists.

What Bearophile actually wrote was:

"You are thinking just about complete binary trees. But consider that a 
topology LIKE a single linked list (every node has 1 child, and they are 
chained) is a true binary tree still." [Emphasis added.]

It should be obvious what he means. But if, by some chance, you 
misunderstood what he said, he replied to your earlier post and explained 
further:

"I was talking about a binary tree with list-like topology, of course."

If you don't understand what a binary-tree with a list-like topology is, 
then I respectfully suggest that you are unqualified to have an opinion 
in this discussion and you should come back when you've learned what a 
binary-tree with a list-like topology actually is, and why your 
suggestion that he use iteration on linked lists is, to quote Wolfgang 
Pauli, Not Even Wrong.


> Bearophile might very well h

Re: Self function

2009-05-05 Thread Steven D'Aprano
On Tue, 05 May 2009 01:25:49 -0700, Carl Banks wrote:

> *Sigh*  Well, I'm out of this debate.  Apparently it's not possible to
> argue that recursivie algorithms should be avoided *sometimes* without
> everyone citing cases that obviously aren't from those times (as if I
> had been arguing that recursion should be avoided all the time).

You overstated your position, and then instead of gracefully admitting 
that you overstated it, you're trying to weasel out of it by acting the 
victim. If all you had said was that "sometimes" recursion should be 
avoided, then who could argue against that? Scheme purists? Pah, this is 
Python, we don't need no stinkin' mathematical purity!

Practicality beats purity is *precisely* why sometimes you need recursion 
instead of forcing a complicated iterative solution onto a simple 
recursive problem.


> Here's a parting thought for you to cite "counterexamples" of:
> 
> Iteration should be used instead of recursion anywhere a tail- recursive
> algorithm is possible. Recursion should be used only when
> tail-recursion is not possible.

Or when the recursive algorithm is simpler than the iterative algorithm, 
and you don't care about squeezing out every last tiny micro-optimization 
into the code.



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


Re: Which one is best Python or Java for developing GUI applications?

2009-05-05 Thread srinivasan srinivas

Could you list down those advantages??



- Original Message 
From: Bruno Desthuilliers 
To: [email protected]
Sent: Tuesday, 5 May, 2009 1:07:41 PM
Subject: Re: Which one is best Python or Java for developing GUI applications?

Paul Rubin a écrit :
> srinivasan srinivas  writes:
>> Could you tell me does Python have any advantages over Java for the 
>> development of GUI applications?
> 
> Yes.

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



  Cricket on your mind? Visit the ultimate cricket website. Enter 
http://beta.cricket.yahoo.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: change some lines from a read file

2009-05-05 Thread utab
On May 4, 10:06 pm, Anthra Norell  wrote:
> utab wrote:
> > Dear all,
>
> > I have to change some lines from a template file, which is rather long
> > to paste here, but I would like to make some parts of some lines
> > optional with my command line arguments but I could not see this
> > directly, I can count the line numbers and decide on this basis to
> > decide the lines to be configured to my will.
>
> > More specifically, say, I have a that file includes
>
> > this is an example python file to play around
> > .
> > .
> > .
> > some lines
> > .
> > .
> > .
> > . -> an option line for example.
> > .
> > .
> > .
> > -> another option line so on.
>
> > and execute the script
> > ./myScript option1 option2
>
> > so that the options at correct locations will be written.
>
> > Any other options for this simple job that i can improve my Python a
> > bit as well.
>
> > Best,
> > Umut
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> Your description is not explicit enough to convey your intention. If
> your template file is too long to post, post a short representative
> section, an input data sample and a hand-edited sample of the output
> data you want to generate. You will get more and better advice. .
>
> Frederic

Thanks here is a  sample Session file from a commercial finite element
pre-post processor PATRAN, the file longer but the ideas are the same
so that let me give an example, say I would like to make write line 10
composed of some command line arguments: path+database_name, Also
there are some lines similar to this in the below sections of the
file. I am doing it with a if-elif-else clause checking the line
numbers with which I thought of there should be a better way and ended
up asking...

 1 $# Session file patran.ses.02 started recording at 05-May-09
11:12:25
 2 $# Build: 15.0.038 Mon Aug 20 21:31:45 PDT 2007
 3 $# Recorded by: Patran 2007 r1b
 4 $# FLEXlm initialization complete.  Acquiring license(s)...
 5 $# License File: /opt/patran-2007r1b/license.dat
 6 $# Patran 2007 r1b has obtained 1 concurrent license(s) from
FLEXlm per a
 7 $# request to execute on Linux node hpc06(001e4f20c494) (Linux
 8 $# 2.6.23.15-80.fc7) at 05-May-09 11:12:25.
 9 uil_file_new.go( "/opt/patran-2007r1b/template.db",  @
10 "/home/utabak/PATRAN/cavityModels/fromGmsh.db" )
11 $# Question from application FILE
12 $# Database /home/utabak/PATRAN/cavityModels/fromGmsh.db
already exists.
13 $# Do you wish to delete the existing database and create a new
one ?
14 $? YES 3602
15 $# Copying /opt/patran-2007r1b/template.db to
16 $# /home/utabak/PATRAN/cavityModels/fromGmsh.db
17 $# Template copy complete.
18 $# Database version 3.8 created by Patran 2007 r1b successfully
opened.
19 ga_viewport_size_set( "default_viewport", 14.571214, 7.509466,
1 )
20 ga_viewport_location_set( "default_viewport", 0.00,
1.088771, 1 )
21 $# Creating journal file /home/utabak/PATRAN/cavityModels/
fromGmsh.db.jou at
22 $# 05-May-09 11:12:43
23 nastran_input_import( "/home/utabak/PATRAN/cavityModels/
toPatran.bdf",  @
24 "default_group", 10, [TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, FALSE,  @
25 TRUE], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0,
0, 0], [ @
26 -20, -20, -20, -20,
-20, -20,  @
27 -20, -20, 0, 0] )
28 $# Reading of MSC.Nastran input file completed.
29 ui_exec_function( "mesh_seed_display_mgr", "init" )

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


Re: Which one is best Python or Java for developing GUI applications?

2009-05-05 Thread Chris Rebert
On Tue, May 5, 2009 at 12:26 AM, Paul Rudin  wrote:
> Paul Rubin  writes:
>
>> srinivasan srinivas  writes:
>>> Could you tell me does Python have any advantages over Java for the
>>> development of GUI applications?
>>
>> Yes.
>
> Clearly c.l.p needs to adopt the SNB 
> convention :)

Surely you have forgotten the comedy style of the language's namesake,
which makes that rule completely inadmissible! ;P

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


Re: Any idea to emulate tail -f

2009-05-05 Thread Lawrence D'Oliveiro
In message , Joel 
Juvenal Rivera Rivera wrote:

> I want to make something very similar to  the command tail -f (follow a
> file) ...



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


what's the best way to call a method of object without a guarantee of its existence

2009-05-05 Thread Leon
One way,  define the object before it is used,
like this:
object = None
.
.

if object is not None:
   object.method()

The other way, using try ... catch
try:
 object.method()
catch NameError:
 pass

for  big programs, which is better, or any other way?

Miles


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


Re: find sublist inside list

2009-05-05 Thread Gerard Flanagan

Matthias Gallé wrote:

Hi.

My problem is to replace all occurrences of a sublist with a new element.

Example:
Given ['a','c','a','c','c','g','a','c'] I want to replace all 
occurrences of ['a','c'] by 6 (result [6,6,'c','g',6]).




For novelty value:

from itertools import izip

def replace2(data, pattern):
assert len(pattern) == 2
pattern = tuple(pattern)
icopy = iter(data)
icopy.next()
gen = izip(data, icopy)
while True:
item = gen.next()
if item == pattern:
yield '6'
gen.next()
else:
yield item[0]

# works if list ends with ['a', 'c']
data = ['g', 'a', 'c', 'a', 'c', 'a', 'a', 'a', 'g', 'a', 'c']
want = 'g66aaag6'
assert ''.join(replace2(data, ['a', 'c'])) == want

# otherwise you lose the last element of the tail
data = ['g', 'a', 'c', 'a', 'c', 'a', 'a', 'a', 'g', 'a', 'c', 'c', 'g']
want = 'g66aaag6cg'
get = 'g66aaag6c'
assert not ''.join(replace2(data, ['a', 'c'])) == want
assert ''.join(replace2(data, ['a', 'c'])) == get

# fix by adding the pattern to the end of the data as a sentinel

def replace2(data, pattern):
assert len(pattern) == 2
def _replace2(data, pattern):
pattern = tuple(pattern)
icopy = iter(data)
icopy.next()
gen = izip(data, icopy)
while True:
item = gen.next()
if item == pattern:
yield '6'
gen.next()
else:
yield item[0]
data = data + pattern
return list(_replace2(data, pattern))[:-1]

data = ['g', 'a', 'c', 'a', 'c', 'a', 'a', 'a', 'g', 'a', 'c']
want = 'g66aaag6'
assert ''.join(replace2(data, ['a', 'c'])) == want

data = ['g', 'a', 'c', 'a', 'c', 'a', 'a', 'a', 'g', 'a', 'c', 'c', 'g']
want = 'g66aaag6cg'
assert ''.join(replace2(data, ['a', 'c'])) == want

print 'done'

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


Re: Any idea to emulate tail -f

2009-05-05 Thread Iain King
On May 5, 7:00 am, Joel Juvenal Rivera Rivera 
wrote:
> I want to make something very similar to  the command tail -f (follow a
> file), i have been trying  with some while True and some microsleeps
> (about .1 s); did someone has already done something like this?
>
> And about the file is the apache acceslog  of a site with a lot of
> traffic.
>
> Regards    
>
> joe / Joel Rivera

This is very interesting, about using Generator Expressions:
http://209.85.229.132/search?q=cache:ZHrV4E0eTI8J:www.dabeaz.com/generators/Generators.pdf

Relevant stuff about 'tail -f' is on page 39, but I'd read the whole
thing if you can.

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


Re: what's the best way to call a method of object without a guarantee of its existence

2009-05-05 Thread Marco Mariani

Leon wrote:


One way,  define the object before it is used,
like this:
object = None


This is a good practice anyway. Conditional existance of objects is 
quite evil. Resorting to if defined('foo') is double-plus-ugly.




The other way, using try ... catch
try:
 object.method()
catch NameError:
 pass


Except you should trap AttributeError because you defined the thing as 
None before. NameErrors should be fixed as bugs, not trapped (IMHO -- 
but in python there is always a use case for everything).


Keep in mind that AttributeError might come from inside the method(), 
which could be confusing


By using the

if stuff:
   stuff.run()

idiom, you avoid the last issue and keep it simple enough.



for  big programs, which is better, or any other way?


Define "big", as in scope, LOCs, or number of committers?

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


Re: find sublist inside list

2009-05-05 Thread mzdude
On May 4, 4:54 pm, "Gabriel Genellina"  wrote:
> En Mon, 04 May 2009 15:12:41 -0300, mzdude  escribió:
>
> > substring isn't limited to 0..255
>  substring = "\0x%d\0x%d" % (257,257)
>  'acaccgac'.replace("ac", substring)
> > '\x00x257\x00x257\x00x257\x00x257cg\x00x257\x00x257'
>
> This isn't what you think it is. Look carefully:
>
> py> substring = "\0x%d\0x%d" % (257,257)
> py> len(substring)
> 10
> py> list(substring)
> ['\x00', 'x', '2', '5', '7', '\x00', 'x', '2', '5', '7']
>
> --
> Gabriel Genellina

OOPS. My bad. But I'm not going to give up.

l = ['a','b','c','a','c']
us = unicode("".join(l))
substr = unichr(257) + unichr(257)
us = us.replace(u'ac',substr)
print len(us)
print list(us)


output is
>>>
5
[u'a', u'b', u'c', u'\u0101', u'\u0101']
--
http://mail.python.org/mailman/listinfo/python-list


Re: stuck with PyOBEX

2009-05-05 Thread alejandro
Ejla! I have sent you a mail (in case you check it often like me :-))

"David Boddie"  wrote in message 
news:[email protected]...
> On Sunday 03 May 2009 10:33, alejandro wrote:
>
>> Yes!
>>
>>> I'll send you an updated version to try if you would like to test it.
>
> My mails to you keep getting returned, so I've put it here:
>
> http://www.boddie.org.uk/david/Projects/Python/PyOBEX/Software/PyOBEX-0.21.zip
>
> Please let me know if it works on Windows, and feel free to get in touch 
> if
> you have any problems.
>
> David 


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


Re: exit a program gracefully

2009-05-05 Thread Lawrence D'Oliveiro
In message , Gabriel 
Genellina wrote:

> I prefer to put the code inside a function, and just `return` earlier.

It would be nice if Python offered a straightforward equivalent to

... initialization goes here ...
do /*once*/
  {
... do stuff ...
if (check1_failed)
break;
... do more stuff ...
if (check2_failed)
break;
... do even more stuff ...
  }
while (false);
... cleanup goes here ...


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


Re: exit a program gracefully

2009-05-05 Thread Cameron Simpson
On 05May2009 23:28, Lawrence D'Oliveiro  
wrote:
| In message , Gabriel 
| Genellina wrote:
| 
| > I prefer to put the code inside a function, and just `return` earlier.
| 
| It would be nice if Python offered a straightforward equivalent to
| 
| ... initialization goes here ...
| do /*once*/
|   {
| ... do stuff ...
| if (check1_failed)
| break;
| ... do more stuff ...
| if (check2_failed)
| break;
| ... do even more stuff ...
|   }
| while (false);
| ... cleanup goes here ...

  while True:
... do stuff ...
if check1_failed:
  break;
... do more stuff ...
if check2_failed:
  break;
... do even more stuff ...
break
  ... cleanup goes here ...

Seems more straightforward to me!

And there's always try/except and context managers.

Cheers,
-- 
Cameron Simpson  DoD#743
http://www.cskk.ezoshosting.com/cs/

So why can't we celebrate November 5th the way Guy Fawkes would've wanted?
- Mike Holmes 
--
http://mail.python.org/mailman/listinfo/python-list


help required with pylons

2009-05-05 Thread M Kumar
Hi,

I am having an application server in pylons, which was giving error
sometimes and sometimes it gives the result. I will copy paste the error
below. I am new to pylons and not getting any clue of this kind of behavior.
Please help me what should I do to avoid this kind of errors.


Exception happened during processing of request from ('127.0.0.1', 33021)
Traceback (most recent call last):
  File
"/usr/lib/python2.5/site-packages/Paste-1.4.2-py2.5.egg/paste/httpserver.py",
line 1046, in process_request_in_thread
self.finish_request(request, client_address)
  File "/usr/lib/python2.5/SocketServer.py", line 254, in finish_request
self.RequestHandlerClass(request, client_address, self)
  File "/usr/lib/python2.5/SocketServer.py", line 522, in __init__
self.handle()
  File
"/usr/lib/python2.5/site-packages/Paste-1.4.2-py2.5.egg/paste/httpserver.py",
line 425, in handle
BaseHTTPRequestHandler.handle(self)
  File "/usr/lib/python2.5/BaseHTTPServer.py", line 316, in handle
self.handle_one_request()
  File
"/usr/lib/python2.5/site-packages/Paste-1.4.2-py2.5.egg/paste/httpserver.py",
line 420, in handle_one_request
self.wsgi_execute()
  File
"/usr/lib/python2.5/site-packages/Paste-1.4.2-py2.5.egg/paste/httpserver.py",
line 287, in wsgi_execute
self.wsgi_start_response)
  File
"/usr/lib/python2.5/site-packages/Paste-1.4.2-py2.5.egg/paste/cascade.py",
line 92, in __call__
return self.apps[-1](environ, start_response)
  File
"/usr/lib/python2.5/site-packages/Paste-1.4.2-py2.5.egg/paste/registry.py",
line 340, in __call__
app_iter = self.application(environ, start_response)
  File
"/usr/lib/python2.5/site-packages/AuthKit-0.4.0-py2.5.egg/authkit/authenticate/__init__.py",
line 290, in __call__
return self.app(environ, start_response)
  File
"/usr/lib/python2.5/site-packages/AuthKit-0.4.0-py2.5.egg/authkit/authenticate/cookie.py",
line 354, in __call__
return self.app(environ, cookie_setting_start_response)
  File
"/usr/lib/python2.5/site-packages/AuthKit-0.4.0-py2.5.egg/authkit/authenticate/multi.py",
line 64, in __call__
raise Exception('WSGI start_response was not called before a result'
Exception: WSGI start_response was not called before a result was returned

thanks in advance
Maneesh KB
--
http://mail.python.org/mailman/listinfo/python-list


problem in using sendmail in multi thread

2009-05-05 Thread gganesh
hi,
I'm a beginner in using Python script
I'm trying to send mails using multi-thread
I wrote



FROM = '[email protected]'
# for more mail add';' the another mail id
listTo = ['[email protected]', '[email protected]',
'[email protected]']
SUBJECT = 'This is the subject'
MSGBODY = 'This the body of the message '
MAILSERVER = 'mail..com'
port = 25
username = 'x'
password = 'x'

# trim the strings of any leading or trailing spaces
FROM = FROM.strip()
SUBJECT = SUBJECT.strip()
MSGBODY = MSGBODY.strip()
MAILSERVER = MAILSERVER.strip()
username = username.strip()
password = password.strip()



#Connect to server
print 'Connecting to mail server ', MAILSERVER
try:
s = smtplib.SMTP(MAILSERVER,port)
print 'connected'
#s.set_debuglevel(1)
except:
 print 'ERROR: Unable to connect to mail server', sys.exc_info  ()[0]
 sys.exit(1)

#login to server
if password <> '':
print 'Logging into mail server'
try:
s.login(username,password)
except:
print 'ERROR: Unable to login to mail server', MAILSERVER
print 'Please recheck your password'
sys.exit(1)

#--
print "Starting Multi Thread Method"


class MyThread(Thread):

def __init__(self, site, s, FROM, MSGBODY):
Thread.__init__(self)
self.site = site
self.s=s
self.FROM=FROM
self.MSGBODY=MSGBODY

def run(self):
print "running for %s " %self.site
s.sendmail(self.FROM, self.site, self.MSGBODY)
print "Emailed for  site %s" %self.site



a= time.time()
threads = []

for site in listTo:
T = MyThread(site,s,FROM,MSGBODY)
threads.append(T)
T.start()


for i in threads:
i.join()
s.quit()
s.close()
print "Took %s seconds" %str(time.time()-a)

#-

Error:
There is no problem with mail ids
I'm using python2.5 ,Ubuntu
I got an error like



Traceback (most recent call last):
  File "/usr/lib/python2.5/threading.py", line 486, in
__bootstrap_inner
self.run()
  File "threadmailmul.py", line 85, in run
s.sendmail(self.FROM, self.site, self.MSGBODY)
  File "/usr/lib/python2.5/smtplib.py", line 703, in sendmail
raise SMTPRecipientsRefused(senderrs)
SMTPRecipientsRefused: {'[email protected]': (503, '5.5.1 Error: nested
MAIL command')}

Exception in thread Thread-2:
Traceback (most recent call last):
  File "/usr/lib/python2.5/threading.py", line 486, in
__bootstrap_inner
self.run()
  File "threadmailmul.py", line 85, in run
s.sendmail(self.FROM, self.site, self.MSGBODY)
  File "/usr/lib/python2.5/smtplib.py", line 704, in sendmail
(code,resp) = self.data(msg)
  File "/usr/lib/python2.5/smtplib.py", line 487, in data
raise SMTPDataError(code,repl)
SMTPDataError: (503, '5.5.1 Error: need MAIL command')

Exception in thread Thread-3:
Traceback (most recent call last):
  File "/usr/lib/python2.5/threading.py", line 486, in
__bootstrap_inner
self.run()
  File "threadmailmul.py", line 85, in run
s.sendmail(self.FROM, self.site, self.MSGBODY)
  File "/usr/lib/python2.5/smtplib.py", line 692, in sendmail
raise SMTPSenderRefused(code, resp, from_addr)
SMTPSenderRefused: (503, '5.5.1 Error: need RCPT command',
'[email protected]')

Exception in thread Thread-4:
Traceback (most recent call last):
  File "/usr/lib/python2.5/threading.py", line 486, in
__bootstrap_inner
self.run()
  File "threadmailmul.py", line 85, in run
s.sendmail(self.FROM, self.site, self.MSGBODY)
  File "/usr/lib/python2.5/smtplib.py", line 702, in sendmail
self.rset()
  File "/usr/lib/python2.5/smtplib.py", line 453, in rset
return self.docmd("rset")
  File "/usr/lib/python2.5/smtplib.py", line 378, in docmd
return self.getreply()
  File "/usr/lib/python2.5/smtplib.py", line 355, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
SMTPServerDisconnected: Connection unexpectedly closed

Traceback (most recent call last):
  File "threadmailmul.py", line 102, in 
i.join()
  File "/usr/lib/python2.5/threading.py", line 594, in join
self.__block.wait()
  File "/usr/lib/python2.5/threading.py", line 216, in wait
waiter.acquire()


If someone could point out the (probably silly)
mistake I'm making , I would be very grateful.
Thanks in advance
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-05 Thread Luis Zarrabeitia
On Tuesday 05 May 2009 02:46:58 am Chris Rebert wrote:
> 
> Adding syntax is EVIL(tm) for it angers the Gods of Backwards
> Compatibility, and this proposal is completely unnecessary because you
> could instead just write:
[...]
> And there would be much clashing with existing variable names,
> for keywords are the Devil's work!
> 

Heh. I liked the proposal (though I'm not 100% sold on the name __this__), and 
one of the reasons I liked it was... it preempted the name-clashing argument. 
Not a new keyword, just a variable that is injected on the local namespace, 
so it would only clash with code that uses __this__ as a global (or that 
expects to use an unbound __this__).

Btw, is there any way to inject a name into a function's namespace? Following 
the python tradition, maybe we should try to create a more general solution!

K.

(P.S: there is one advantage on having it as a keyword, though: it would make 
static analisis easier)

-- 
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-05 Thread Luis Zarrabeitia
On Tuesday 05 May 2009 03:51:19 am Steven D'Aprano wrote:
> def ivisit(node):
>     print node
>     while node and node.link is not None:
>         node = node.link
>         print node
>
> def rvisit(node):
>     print node
>     if node and node.link is not None:
>         rvisit(node.link)
>
>
> If there are programmers who find rvisit "a lot less readable" than
> ivisit, then in my arrogant opinion they should consider a change of
> profession.

/me smiles.

What if I happen to find rvisit _more_ readable than ivisit?

/me ducks.

[I'm not a lisp user, but I tend to think recursively anyway...]

-- 
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-05 Thread Luis Zarrabeitia
On Tuesday 05 May 2009 04:25:49 am Carl Banks wrote:
> Iteration should be used instead of recursion anywhere a tail-
> recursive algorithm is possible.  Recursion should be used only when
> tail-recursion is not possible.

Why?
Is it because most languages suck at recursion (specially python, as this 
thread shows)? If that's the reason, I think you have it backwards... Turning 
a tail-recursion into an iteration should be the compiler's job, not mine.

An algorithm, any algorithm, should be written in the way that is easier to 
read, unless the language wont allow that easier implementation to be 
efficient enough.

Programming languages suck, but that shouldn't mean that we can't hope to 
improve them.

-- 
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
--
http://mail.python.org/mailman/listinfo/python-list


How to build Python 2.6.2 on HP-UX Itanium with thread support?

2009-05-05 Thread henning . vonbargen
Our program that makes use of cx_Oracle and multi-threading (and works
fine on Windows, Linux and other platforms, including HP-UX PA-RISC),
fails to run on HP-UX Itanium.
When trying to start the first daemon thread, the program raises an
exception:
...
  File "/usr/local/lib/python2.6/threading.py", line 471, in start
_start_new_thread(self.__bootstrap, ())
error: can't start new thread

I guess there's something wrong with the way we built Python, but I
have absolutely no clue what (I'm not too familiar with HP-UX).
>From what I found in the internet, it's probably something about the
threading libraries at the C level.

So the question is:
Which steps are necessary to build Python 2.6.2 (32bit or 64bit) on HP-
UX Itanium 11.31 with working multi-threading support?

Note:
For whatever reasons, in order to get cx_Oracle 5.0.1 to work on HP-
UX, I have to build it as a built-in module. That's why I have to
build Python myself (and unfortunately there's no Python 2.6.2 binary
distribution for HP-UX itanium available). Everything works fine
except multi-threading.

Before running configure and make, I set up the environment like this:
export PATH=$PATH:/usr/local/bin
export CPPFLAGS=-I/opt/openssl/0.9.8/include
export LDFLAGS="-L/usr/lib/hpux32 -L/usr/local/lib/hpux32 -L/opt/
openssl/0.9.8/lib"

I have the files generated by configure and make available, but it's
too much to post it all, as as I don't know what is relevant and what
not.
So, here's just the first few lines of the config.log output:

This file contains any messages produced by compilers while
running configure, to aid debugging if configure makes a mistake.

It was created by python configure 2.6, which was
generated by GNU Autoconf 2.61.  Invocation command line was

  $ ./configure --with-zlib --with-openssl

## - ##
## Platform. ##
## - ##

hostname = polref4
uname -m = ia64
uname -r = B.11.31
uname -s = HP-UX
uname -v = U
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-05 Thread Arnaud Delobelle
On 5 May, 13:33, Luis Zarrabeitia  wrote:
> On Tuesday 05 May 2009 02:46:58 am Chris Rebert wrote:
>
> > 
> > Adding syntax is EVIL(tm) for it angers the Gods of Backwards
> > Compatibility, and this proposal is completely unnecessary because you
> > could instead just write:
> [...]
> > And there would be much clashing with existing variable names,
> > for keywords are the Devil's work!
> > 
>
> Heh. I liked the proposal (though I'm not 100% sold on the name __this__), and
> one of the reasons I liked it was... it preempted the name-clashing argument.
> Not a new keyword, just a variable that is injected on the local namespace,
> so it would only clash with code that uses __this__ as a global (or that
> expects to use an unbound __this__).

One issue with automatically binding a local variable to the current
function is with nested functions:

def foo()
def bar():
   # How do I call foo() from here?

One solution would be

def foo()
def bar(foo=__this__):
foo()

I don't know, it does not convince me ATM.

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


New Module Proposal

2009-05-05 Thread Riccardo Fadiga
Greetings,

I'm a basic python coder, and I wrote for myself a module wich has many
function regarding encryption/decryption with Caesar, Vigenere, RSA and many
more ciphers. People told me that it would be useful that it would be
included in stardard Python distribution. I'll send you a copy of the file,
just in case you decide to really do that.

Thanks for reading. Please write back.

 

Riccardo

 


 
 
 --
 Caselle da 1GB, trasmetti allegati fino a 3GB e in piu' IMAP, POP3 e SMTP 
autenticato? GRATIS solo con Email.it http://www.email.it/f
 
 Sponsor:
 Posta Elettronica Certificata con valore legale e notifica via SMS: scopri 
legal.email.it
 Clicca qui: http://adv.email.it/cgi-bin/foclick.cgi?mid=8977&d=3-5
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiprocessing.Queue - I want to end.

2009-05-05 Thread Luis Alberto Zarrabeitia Gomez

Quoting Cameron Simpson :

> | And as it happens I have an IterableQueue class right here which does
> | _exact_ what was just described. You're welcome to it if you like.
> | Added bonus is that, as the name suggests, you can use the class as
> | an iterator:
> |   for item in iterq:
> | ...
> | The producer calls iterq.close() when it's done.
> 
> Someone asked, so code appended below.
> [...]

Thank you!. I tested it, and it seems to work... and having the queue be an
iterable is a plus. Thank you, Cameron & MRAB!

-- 
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie

-- 
Participe en Universidad 2010, del 8 al 12 de febrero de 2010
La Habana, Cuba 
http://www.universidad2010.cu

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


Is there is any way to send messages to chunk of emails ID's concurrently using smptlib

2009-05-05 Thread gganesh
Hi friends,
I suppose sendmail() can send mails one by one ,how to send mails
concurrently ,
It would be very grateful,if someone could point out a solution.
Thanks
Ganesh
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can someone please explain to me this code?

2009-05-05 Thread CTO
> root.change_attributes(event_mask = X.KeyPressMask)

This asks X to send this application keypress events

> root.grab_key(keycode, X.AnyModifier, 1,X.GrabModeAsync, X.GrabModeAsync)

This tells X to grab the keyboard if the given keycode is generated
and
any modifier is pressed, not to stop processing keyboard events, and
not
to stop processing pointer events. That's pretty safe, although I'm
not
sure if you'd need the modifier for your application.

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


Re: Problem with case insensitive volumes

2009-05-05 Thread spillz
> os;walk will tell you the correct case for each node.   So if it gives
> you a different case than the stored form, you have your answer.

Thanks, although I was hoping that wouldn't be the answer (I have to
compare a LOT of files).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Profiling gives very different predictions of best algorithm

2009-05-05 Thread Rick
On May 2, 9:10 am, Rick  wrote:

> I was posting to the list mostly because I would like to know whether
> I can do something different when I profile my code so that it give
> results that correspond more closely to those that the nonprofiling
> results give.

A good comment that was emailed to me rather than being posted to the
list was to use cProfile rather than profile. Doing this gave much
more realistic results.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question of UTF16BE encoding / decoding

2009-05-05 Thread Napalmski
In article , 
[email protected] says...
> 
> 
> import binascii
> s = '004e006100700061006c006d'
> h = binascii.unhexlify(s)
> print h.decode('utf-16-be')
> 
> -Mark

And: 
name2 = name2.encode("utf-16-be")
print binascii.b2a_hex(name2)

to re-encode,
Thank you, much appreciated!
--
http://mail.python.org/mailman/listinfo/python-list


Re: find sublist inside list

2009-05-05 Thread bearophileHUGS
John O'Hagan:
> li=['a', 'c', 'a', 'c', 'c', 'g', 'a', 'c']
> for i  in range(len(li)):
>     if li[i:i + 2] == ['a', 'c']:
>         li[i:i + 2] = ['6']

Oh well, I have done a mistake, it seems.
Another solution then:

>>> 'acaccgac'.replace("ac", chr(6))
'\x06\x06cg\x06'

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Any idea to emulate tail -f

2009-05-05 Thread Paul Scott
On Mon, 2009-05-04 at 23:50 -0700, CTO wrote:
> You might want to try http://pyinotify.sourceforge.net/. Works well on
> Linux systems. Otherwise, I'd watch the mtime on the file and fork to
> handle the change.
> 

pyinotify works really well. If you need to watch a file, simply use the
IN_MODIFY watch to fire off a notification when the file changes. Then
you can use that event in anything you may need.

I put up some basic pyinotify usage here:
http://www.paulscott.za.net/index.php?module=jabberblog&postid=ps123_2560_1240747637&action=viewsingle
 but if you need some more help with it, read the docs and then ask me also

-- Paul
http://www.paulscott.za.net
http://twitter.com/paulscott56
http://avoir.uwc.ac.za
-- 

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


Re: exit a program gracefully

2009-05-05 Thread Scott David Daniels

Lawrence D'Oliveiro wrote:

It would be nice if Python offered a straightforward equivalent to
...
do /*once*/
  {
... do stuff ...
if (check1_failed)
break;
... do even more stuff ...
  }
while (false);
... cleanup goes here ...


What's wrong with:

for _ in (None,):
... do stuff ...
if (check1_failed)
break;
... do even more stuff ...
... cleanup ...

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


Re: change some lines from a read file

2009-05-05 Thread Anthra Norell

utab wrote:

On May 4, 10:06 pm, Anthra Norell  wrote:
  

utab wrote:


Dear all,
  
I have to change some lines from a template file, which is rather long

to paste here, but I would like to make some parts of some lines
optional with my command line arguments but I could not see this
directly, I can count the line numbers and decide on this basis to
decide the lines to be configured to my will.
  
More specifically, say, I have a that file includes
  
this is an example python file to play around

.
.
.
some lines
.
.
.
. -> an option line for example.
.
.
.
-> another option line so on.
  
and execute the script

./myScript option1 option2
  
so that the options at correct locations will be written.
  
Any other options for this simple job that i can improve my Python a

bit as well.
  
Best,

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

Your description is not explicit enough to convey your intention. If
your template file is too long to post, post a short representative
section, an input data sample and a hand-edited sample of the output
data you want to generate. You will get more and better advice. .

Frederic



Thanks here is a  sample Session file from a commercial finite element
pre-post processor PATRAN, the file longer but the ideas are the same
so that let me give an example, say I would like to make write line 10
composed of some command line arguments: path+database_name, Also
there are some lines similar to this in the below sections of the
file. I am doing it with a if-elif-else clause checking the line
numbers with which I thought of there should be a better way and ended
up asking...

 1 $# Session file patran.ses.02 started recording at 05-May-09
11:12:25
 2 $# Build: 15.0.038 Mon Aug 20 21:31:45 PDT 2007
 3 $# Recorded by: Patran 2007 r1b
 4 $# FLEXlm initialization complete.  Acquiring license(s)...
 5 $# License File: /opt/patran-2007r1b/license.dat
 6 $# Patran 2007 r1b has obtained 1 concurrent license(s) from
FLEXlm per a
 7 $# request to execute on Linux node hpc06(001e4f20c494) (Linux
 8 $# 2.6.23.15-80.fc7) at 05-May-09 11:12:25.
 9 uil_file_new.go( "/opt/patran-2007r1b/template.db",  @
10 "/home/utabak/PATRAN/cavityModels/fromGmsh.db" )
  

Okay! Please clarify:
Question 1: Is it always line 10 or is it always a path-file-name, which 
could be on another line?
Question 2: Are there other lines you want to translate? If yes, how do 
you identify them? By line number or by content?
Question 3: If you identify your target by content, what ist the 
distinctive feature which it doesn't share with non-target lines? (e.g. 
Path-file name format and nothing else)
Question 4: Do you want to substitute the path name with another path 
name and the file name with another file name, both of which you supply 
on the command line?
Question 5: If your input has a number of different names, do you want 
to translate them all to the same name, in which case you'd only have to 
supply a single pair of names on the command line?
Question 6: If your input has a number of different names and your 
translation also consists of a number of path-file-name pairs, how do 
the targets and substitutes correlate? Sequentially? By pattern?
Question 7: Can you estimate how many different path-file-names your 
complete session file contains? And how many different substitutes you 
may have in extreme cases?

11 $# Question from application FILE
12 $# Database /home/utabak/PATRAN/cavityModels/fromGmsh.db
already exists.
13 $# Do you wish to delete the existing database and create a new
one ?
14 $? YES 3602
15 $# Copying /opt/patran-2007r1b/template.db to
  

Question 8: Here you have a file name. What do you do with it?

16 $# /home/utabak/PATRAN/cavityModels/fromGmsh.db
  

Question 9: Here line 10 repeats. What do you do with it?

17 $# Template copy complete.
18 $# Database version 3.8 created by Patran 2007 r1b successfully
opened.
19 ga_viewport_size_set( "default_viewport", 14.571214, 7.509466,
1 )
20 ga_viewport_location_set( "default_viewport", 0.00,
1.088771, 1 )
21 $# Creating journal file /home/utabak/PATRAN/cavityModels/
fromGmsh.db.jou at
  

Question 10: Here the file name of line 10 repeats. What do you do?

22 $# 05-May-09 11:12:43
23 nastran_input_import( "/home/utabak/PATRAN/cavityModels/
toPatran.bdf",  @
  

Question 11: Here the file name of line 10 repeats. What do you do?


24 "default_group", 10, [TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, FALSE,  @
25 TRUE], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0,
0, 0], [ @
26 -20, -20, -20, -20,
-20, -20,  @
27 -20, -20, 0, 0] )
28 $# Reading of MSC.Nastran input file completed.
29 ui_exec_function( "mesh_seed_display_mgr", "init" )

Best,
--
http://mail.python.org/mailman/listi

Re: Open a dialog from MainWindow - pyQT4 - Beginner :-)

2009-05-05 Thread nickgaens
On May 4, 7:31 pm, Florian Wollenschein  wrote:
> Dear folks,
>
> I'm just working on a pyQT4 version of my txt to html converter thc (see
> listick.org for details).
>
> I created the MainWindow with QT Designer and then converted it to .py
> with pyuic4. It works well so far. Then I created a new UI for my
> abtDialog (about dialog for my application). I did the same as with the
> MainWindow, so I have two UIs and two *_ui.py files now. How can I open
> the dialog from my main application class?
>
> Here's part of the code I'm using:
>
> ...
> self.connect(self.actionAbout,
>                  QtCore.SIGNAL("triggered()"), self.OpenAbout)
> ...
>   def OpenAbout(self):
>          pass
> ...
>
> The OpenAbout function should open the dialog. I've already tried a
> abtDialog.show() after creating it via abtDialog = ThcAboutDialog()
> (ThcAboutDialog is the class for this dlg).
>
> Any ideas?
>
> Thanks,
> Listick Lorchhttp://www.listick.org
>
> PS: Keep in mind that I'm quite a beginner in the field of python and qt...

def OpenAbout(self):
# don't forget to connect the "Ok"-button of this about-dialog to
QDialog::accept() ;-)
abtDialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
abtDialog.exec_()

R3

ps: you could take a look at a QMessageBox::information or so to make
this more "simple"
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with case insensitive volumes

2009-05-05 Thread Scott David Daniels

spillz wrote:

os;walk will tell you the correct case for each node.   So if it gives
you a different case than the stored form, you have your answer.


Thanks, although I was hoping that wouldn't be the answer (I have to
compare a LOT of files).

What is so tough about something like:

base, dirs, files = next(os.walk(dirn))  # older: os.walk(dirn).next()
current = dict((name.upper() for name in dirs + files)
...
changed = some_name == current[some_name.upper()]
...

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


Re: object query assigned variable name?

2009-05-05 Thread Sion Arrowsmith
John O'Hagan   wrote:
>I can see that it's tantalizing, though, because _somebody_ must know about 
>the assignment; after all, we just executed it!

Except we haven't, if we're talking about reporting from the
object's __init__:

>>> class Brian:
... def __init__(self):
... print "I'm Brian!"
...
>>> l = []
>>> l[1] = Brian()
I'm Brian!
Traceback (most recent call last):
  File "", line 1, in 
IndexError: list assignment index out of range

(Yeah, I know that's a setitem call not an assignment. Point stands.
It also demonstrates why the whole idea of "what name is a newly-
created object assigned to" is broken.)

-- 
\S

   under construction

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


Re: Code works fine except...

2009-05-05 Thread Ross
On May 5, 12:32 am, John Yeung  wrote:
> On May 5, 1:12 am, John Yeung  wrote:
>
> > [...] the problem may require bigger guns (either much better
> > math or much more sophisticated programming).
>
> Yes, I'm responding to myself.
>
> Well, I went ahead with the approach I mentioned earlier, generating
> all possible matches and then selecting among them as needed to fill
> up the courts, trying to keep the number of matches played by each
> player as fair as possible.  (I should mention that this, or something
> similar, was suggested earlier by someone else in a different thread,
> in response to the same question by the same OP.)
>
> I did use "bigger guns" (mainly a class for player objects, with
> custom __cmp__ method), but still didn't do anything with doubles.
>
> I haven't tested it much, but I'll post it if anyone's interested.
> (That way people can pick on me instead of the OP. ;)
>
> John

I'm interested to see what you did. From your description, it sounds
like I've tried what you've done, but when I implemented my version,
it took minutes to evaluate for bigger numbers. If that isn't the case
with yours, I'd be interested in seeing your implementation.
--
http://mail.python.org/mailman/listinfo/python-list


Python-URL! - weekly Python news and links (May 5)

2009-05-05 Thread Gabriel Genellina
QOTW:  "... [S]omebody's gotta put up some resistance to cute shortcuts, or
we'll find ourselves back with Perl." - Peter Pearson
http://groups.google.com/group/comp.lang.python/msg/2ce1b43e4d40528f


How much memory occupies an object?
http://groups.google.com/group/comp.lang.python/t/e0581c6c80e813aa/

Get the item actually contained in a set:
http://groups.google.com/group/comp.lang.python/t/a2ab7d3ffc28e1b1/

Manipulating individual bits in a long bit string
http://groups.google.com/group/comp.lang.python/t/471162166df52100/

A "float" version of range() -like range(-10.5,10.5,0.1)- isn't trivial
to implement:
http://groups.google.com/group/comp.lang.python/t/70bdf77282b63944/

How can a function refer to itself?
http://groups.google.com/group/comp.lang.python/t/d265da85d4b70eaf/

Why do all objects have an implicit boolean value?
http://groups.google.com/group/comp.lang.python/t/1167f4f275a9a64c/

multiprocessing: How to notify other processes that there is no more
work to do:
http://groups.google.com/group/comp.lang.python/t/8c57b2796cae95ff/

bearophile kindly shares some of his itertools enhancements:
http://groups.google.com/group/comp.lang.python/t/642e3d4dc3e04a46/

A package/module/class confusion -- also: how to organize a package
containing hundreds of classes
http://groups.google.com/group/comp.lang.python/t/c216908a72d4fb8c/

Python lists aren't linked lists, as Lisp programmers are used to:
http://groups.google.com/group/comp.lang.python/t/a0ce55f3d1fbe25/

And the Lisp mentality is very different :)
http://groups.google.com/group/comp.lang.python/t/68bf9c5bae807545/

Passing a method as an argument from within the same class:
http://groups.google.com/group/comp.lang.python/t/dabfc9f5443b7892/

Handling large arrays that barely fit in the address space:
http://groups.google.com/group/comp.lang.python/t/7f065dac609436ea/



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

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

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily

Just beginning with Python?  This page is a great place to start:
http://wiki.python.org/moin/BeginnersGuide/Programmers

The Python Papers aims to publish "the efforts of Python enthusiats":
http://pythonpapers.org/
The Python Magazine is a technical monthly devoted to Python:
http://pythonmagazine.com

Readers have recommended the "Planet" sites:
http://planetpython.org
http://planet.python.org

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.
http://groups.google.com/group/comp.lang.python.announce/topics

Python411 indexes "podcasts ... to help people learn Python ..."
Updates appear more-than-weekly:
http://www.awaretek.com/python/index.html

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

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

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

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

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

The Summary of Python Tracker Issues is an automatically generated
report summarizing new bugs, closed ones, and patch submissions. 

http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date

Although unmaintained since 2002, the Cetus collection of Python
hyperlinks retains a few gems.
http://www.cetus-links.org/oo_python.html

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

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://code.activestate.com/recipes/langs/python/

Many Python conferences around the world are in preparation.
Watch this space for links to them.

Among several Pyt

Re: for with decimal values?

2009-05-05 Thread Sion Arrowsmith
Gabriel Genellina  wrote:
>En Sun, 03 May 2009 17:41:49 -0300, Zentrader   
>escribió:
>> There is no need for a function or a generator.  A for() loop is a
>> unique case of a while loop
>> ## for i in range(-10.5, 10.5, 0.1):
>> ctr = -10.5
>> while ctr < 10.5:
>>print ctr
>>ctr += 0.1
>
>Isn't so easy. You have representation errors and rounding errors here,  
>and they accumulate. [ ... ]

And remarkably quickly at that:

>>> ctr = -10.5
>>> for i in range(-105, 106):
... i *= 0.1
... if i != ctr: print repr(i), repr(ctr)
... ctr += 0.1
...
-10.0 -10.002
etc.

-- 
\S

   under construction

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


Re: Open a dialog from MainWindow - pyQT4 - Beginner :-)

2009-05-05 Thread Florian Wollenschein

[email protected] wrote:

On May 4, 7:31 pm, Florian Wollenschein  wrote:

Dear folks,

I'm just working on a pyQT4 version of my txt to html converter thc (see
listick.org for details).

I created the MainWindow with QT Designer and then converted it to .py
with pyuic4. It works well so far. Then I created a new UI for my
abtDialog (about dialog for my application). I did the same as with the
MainWindow, so I have two UIs and two *_ui.py files now. How can I open
the dialog from my main application class?

Here's part of the code I'm using:

...
self.connect(self.actionAbout,
 QtCore.SIGNAL("triggered()"), self.OpenAbout)
...
  def OpenAbout(self):
 pass
...

The OpenAbout function should open the dialog. I've already tried a
abtDialog.show() after creating it via abtDialog = ThcAboutDialog()
(ThcAboutDialog is the class for this dlg).

Any ideas?

Thanks,
Listick Lorchhttp://www.listick.org

PS: Keep in mind that I'm quite a beginner in the field of python and qt...


def OpenAbout(self):
# don't forget to connect the "Ok"-button of this about-dialog to
QDialog::accept() ;-)
abtDialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
abtDialog.exec_()

R3

ps: you could take a look at a QMessageBox::information or so to make
this more "simple"


Wow, thanks for your help. Now it's working :-)

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


call function of class instance with no assigned name?

2009-05-05 Thread George Oliver
hi, I'm a Python beginner with a basic question. I'm writing a game
where I have keyboard input handling defined in one class, and command
execution defined in another class. The keyboard handler class
contains a dictionary that maps a key to a command string (like 'h':
'left') and the command handler class contains functions that do the
commands (like def do_right(self):),

I create instances of these classes in a list attached to a third,
'brain' class. What I'd like to have happen is when the player presses
a key, the command string is passed to the command handler, which runs
the function. However I can't figure out a good way to make this
happen.

I've tried a dictionary mapping command strings to functions in the
command handler class, but those dictionary values are evaluated just
once when the class is instantiated. I can create a dictionary in a
separate function in the command handler (like a do_command function)
but creating what could be a big dictionary for each input seems kind
of silly (unless I'm misunderstanding something there).

What would be a good way to make this happen, or is there a different
kind of architecture I should be thinking of?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with case insensitive volumes

2009-05-05 Thread spillz
On May 5, 10:02 am, Scott David Daniels  wrote:
> What is so tough about something like:
>
> base, dirs, files = next(os.walk(dirn))  # older: os.walk(dirn).next()
> current = dict((name.upper() for name in dirs + files)
> ...
> changed = some_name == current[some_name.upper()]
> ...

not so fast. :) Consider:

/my/path/to/usbkey/and/file

everything up to "/my/path/to/usbkey" is case sensitive. only the "and/
file" is case insensitive. but my list of stored paths might include
all images under "/my". thus

/my/path/to/usbkey/and/file1==/my/path/to/usbkey/and/FILE1
/my/path/to/usbkey/and/file1==/my/path/to/usbkey/AND/FILE1
but
/my/path/to/usbkey/and/file1!=/my/path/TO/usbkey/AND/FILE1

so to do this right I'd need to establish which parts of the path are
case insensitive. being able to retrieve the actual path from an
equivalent representation would be so much simpler.
--
http://mail.python.org/mailman/listinfo/python-list


Re: call function of class instance with no assigned name?

2009-05-05 Thread Chris Rebert
On Tue, May 5, 2009 at 8:52 AM, George Oliver  wrote:
> hi, I'm a Python beginner with a basic question. I'm writing a game
> where I have keyboard input handling defined in one class, and command
> execution defined in another class. The keyboard handler class
> contains a dictionary that maps a key to a command string (like 'h':
> 'left') and the command handler class contains functions that do the
> commands (like def do_right(self):),
>
> I create instances of these classes in a list attached to a third,
> 'brain' class. What I'd like to have happen is when the player presses
> a key, the command string is passed to the command handler, which runs
> the function. However I can't figure out a good way to make this
> happen.
>
> I've tried a dictionary mapping command strings to functions in the
> command handler class, but those dictionary values are evaluated just
> once when the class is instantiated. I can create a dictionary in a
> separate function in the command handler (like a do_command function)
> but creating what could be a big dictionary for each input seems kind
> of silly (unless I'm misunderstanding something there).
>
> What would be a good way to make this happen, or is there a different
> kind of architecture I should be thinking of?

You could exploit Python's dynamism by using the getattr() function:

key2cmd = {'h':'left'}
cmd_name = key2cmd[keystroke]
getattr("do_"+cmd_name, cmd_handler)() #same as cmd_handler.do_left()


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


Re: problem in using sendmail in multi thread

2009-05-05 Thread Aahz
In article <[email protected]>,
gganesh   wrote:
>
>I'm a beginner in using Python script
>I'm trying to send mails using multi-thread

You need a separate SMTP connection for each thread.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
--
http://mail.python.org/mailman/listinfo/python-list


SQL and CSV

2009-05-05 Thread Nick
I have a requirement to read a CSV file. Normally, no problem, just
import CSV and slurp the file up.

However, in this case I want to filter out lines that have fields set
to particular values.

It would be neat to be able to do something like this.

select * from test.csv where status <> "Canceled"

Using adodb I can do this, so long as I don't have the where clause. :-
(

Is there a reasonable lightweight way of doing this in Python?

I could write some python code that is used to filter rows, and inport
that from config, but it's not quite as elegant as an SQL route.

Thanks

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


Re: SQL and CSV

2009-05-05 Thread Tim Golden

Nick wrote:

I have a requirement to read a CSV file. Normally, no problem, just
import CSV and slurp the file up.

However, in this case I want to filter out lines that have fields set
to particular values.

It would be neat to be able to do something like this.

select * from test.csv where status <> "Canceled"

Using adodb I can do this, so long as I don't have the where clause. :-
(

Is there a reasonable lightweight way of doing this in Python?

I could write some python code that is used to filter rows, and inport
that from config, but it's not quite as elegant as an SQL route.



Not entirely clear what you are and aren't prepared to try here, but...
the most obvious Python-based way to do this is treating the csv reader
as an iterator and filtering there. Your last line suggests that's not
what you want but just in case I've misunderstood:


id,code,status
1,"ONE","Active"
2,"TWO","Cancelled"
3,"THREE","Active"



import csv

for row in csv.DictReader (open ("c:/temp/test.csv", "rb")):
 if row['status'] != 'Cancelled':
   print row



Doesn't seem too onerous, and could obviously be wrapped in
some useful class/module.

But if you really want to go the SQL route, I believe there are
ODBC adapters for CSV which, combined with PyODBC or CeODBC,
would probably take you where you want to go.

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


Re: list comprehension question

2009-05-05 Thread J Kenneth King
Emile van Sebille  writes:

> On 5/1/2009 7:31 AM J Kenneth King said...
>> Chris Rebert  writes:
>>> b = []
>>> for pair in a:
>>> for item in pair:
>>> b.append(item)
>>
>> This is much more clear than a nested comprehension.
>>
>> I love comprehensions, but abusing them can lead to really dense and
>> difficult to read code.
>
> I disagree on dense and difficult, although I'll leave open the
> question of abuse.

Dense and difficult may be subjective to people like you or I, but you
left out the "to read" part of that sentence. I was referring to the
negative effect nested or complex list comprehensions can have on
readability.

> b = [ item for pair in a for item in pair ]

It's a clever statement, but use it once and its gone. Why not use the
expanded form in a function definition and get an even shorter, but
clearer statement?

>>> b = flatten(a)

Boom, done.

> This is exactly the code above expressed in comprehension form.
>
> It's worth knowing that a list comprehension is structured identically
> to the equivalent for loop.  So it really is neither more dense nor
> more difficult to read.  Further, you can tell immediately from the
> start of the list comprehension what you've got -- in this case a list
> of item(s).
>
> Here with some slight changes...
>
 a = [(1, 2), (3, 4, 7), (5, 6)]
 [ item for j in a if len(j)==2 for item in j if item % 2 ]
> [1, 5]
>
> ...opposed to...
>
 for j in a:
> ... if len(j)==2:
> ... for item in j:
> ... if item % 2:
> ... b.append(item)
> ...
 b
> [1, 5]


Thanks for the lesson in list comprehensions, but I'm well aware of
how they work.

List comprehensions can make a reader of your code apprehensive
because it can read like a run-on sentence and thus be difficult to
parse. The Python documentation discourages their use and I believe
for good reason. It's much easier to explain complex processes with a
function rather than a single nested statement.

>
> YMMV,
>
> Emile

It will apparently vary greatly. Depending on how much coffee I've
had.

;)

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


Re: call function of class instance with no assigned name?

2009-05-05 Thread Arnaud Delobelle
Chris Rebert  writes:

> On Tue, May 5, 2009 at 8:52 AM, George Oliver  
> wrote:
>> hi, I'm a Python beginner with a basic question. I'm writing a game
>> where I have keyboard input handling defined in one class, and
>> command execution defined in another class. The keyboard handler
>> class contains a dictionary that maps a key to a command string (like
>> 'h': 'left') and the command handler class contains functions that do
>> the commands (like def do_right(self):),
>>
>> I create instances of these classes in a list attached to a third,
>> 'brain' class. What I'd like to have happen is when the player
>> presses a key, the command string is passed to the command handler,
>> which runs the function. However I can't figure out a good way to
>> make this happen.
>>
>> I've tried a dictionary mapping command strings to functions in the
>> command handler class, but those dictionary values are evaluated just
>> once when the class is instantiated. I can create a dictionary in a
>> separate function in the command handler (like a do_command function)
>> but creating what could be a big dictionary for each input seems kind
>> of silly (unless I'm misunderstanding something there).
>>
>> What would be a good way to make this happen, or is there a different
>> kind of architecture I should be thinking of?
>
> You could exploit Python's dynamism by using the getattr() function:
>
> key2cmd = {'h':'left'}
> cmd_name = key2cmd[keystroke]
> getattr("do_"+cmd_name, cmd_handler)() #same as cmd_handler.do_left()

getattr(cmd_handler, "do_" + cmd_name)() will work even better!

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


Re: Any idea to emulate tail -f

2009-05-05 Thread J Kenneth King
Iain King  writes:

> On May 5, 7:00 am, Joel Juvenal Rivera Rivera 
> wrote:
>> I want to make something very similar to  the command tail -f (follow a
>> file), i have been trying  with some while True and some microsleeps
>> (about .1 s); did someone has already done something like this?
>>
>> And about the file is the apache acceslog  of a site with a lot of
>> traffic.
>>
>> Regards    
>>
>> joe / Joel Rivera
>
> This is very interesting, about using Generator Expressions:
> http://209.85.229.132/search?q=cache:ZHrV4E0eTI8J:www.dabeaz.com/generators/Generators.pdf
>
> Relevant stuff about 'tail -f' is on page 39, but I'd read the whole
> thing if you can.
>
> Iain

+1

I second this suggestion. I've used this method in many scripts of
late and it is quite handy.

He even takes it a little further and shows you some neat things you
can do with it later on.
--
http://mail.python.org/mailman/listinfo/python-list


Re: SQL and CSV

2009-05-05 Thread Nick
On May 5, 5:19 pm, Tim Golden  wrote:
> Nick wrote:
> > I have a requirement to read a CSV file. Normally, no problem, just
> > import CSV and slurp the file up.
>
> > However, in this case I want to filter out lines that have fields set
> > to particular values.
>
> > It would be neat to be able to do something like this.
>
> > select * from test.csv where status <> "Canceled"
>
> > Using adodb I can do this, so long as I don't have the where clause. :-
> > (
>
> > Is there a reasonable lightweight way of doing this in Python?
>
> > I could write some python code that is used to filter rows, and inport
> > that from config, but it's not quite as elegant as an SQL route.
>
> Not entirely clear what you are and aren't prepared to try here, but...
> the most obvious Python-based way to do this is treating the csv reader
> as an iterator and filtering there. Your last line suggests that's not
> what you want but just in case I've misunderstood:
>
> 
> id,code,status
> 1,"ONE","Active"
> 2,"TWO","Cancelled"
> 3,"THREE","Active"
> 
>
> 
> import csv
>
> for row in csv.DictReader (open ("c:/temp/test.csv", "rb")):
>   if row['status'] != 'Cancelled':
>     print row
>
> 
>
> Doesn't seem too onerous, and could obviously be wrapped in
> some useful class/module.
>
> But if you really want to go the SQL route, I believe there are
> ODBC adapters for CSV which, combined with PyODBC or CeODBC,
> would probably take you where you want to go.
>
> TJG

Part of the problem is that the 'selection' needs to be in a config
file. I can put the if row['status'] != 'Cancelled': return True into
a config, read it and eval it, but its not quite as clean as an sql
route.

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


Re: problem in using sendmail in multi thread

2009-05-05 Thread Piet van Oostrum
> gganesh  (g) wrote:

>g> hi,
>g> I'm a beginner in using Python script
>g> I'm trying to send mails using multi-thread
>g> I wrote



>g> FROM = '[email protected]'
>g> # for more mail add';' the another mail id
>g> listTo = ['[email protected]', '[email protected]',
>g> '[email protected]']
>g> SUBJECT = 'This is the subject'
>g> MSGBODY = 'This the body of the message '
>g> MAILSERVER = 'mail..com'
>g> port = 25
>g> username = 'x'
>g> password = 'x'

>g> # trim the strings of any leading or trailing spaces
>g> FROM = FROM.strip()
>g> SUBJECT = SUBJECT.strip()
>g> MSGBODY = MSGBODY.strip()
>g> MAILSERVER = MAILSERVER.strip()
>g> username = username.strip()
>g> password = password.strip()



>g> #Connect to server
>g> print 'Connecting to mail server ', MAILSERVER
>g> try:
>g> s = smtplib.SMTP(MAILSERVER,port)

You can't have a single SMTP connection that's used in multiple threads.
That is what causes the error. Each thread should have its own SMTP
connection. So move this code (above and below) into the run() method.

>g> print 'connected'
>g> #s.set_debuglevel(1)
>g> except:
>g>  print 'ERROR: Unable to connect to mail server', sys.exc_info  ()[0]
>g>  sys.exit(1)

>g> #login to server
>g> if password <> '':
>g> print 'Logging into mail server'

I think this try except block should be inside the if statement, i.e.
indented 4 spaces.

>g> try:
>g> s.login(username,password)
>g> except:
>g> print 'ERROR: Unable to login to mail server', MAILSERVER
>g> print 'Please recheck your password'
>g> sys.exit(1)

>g> #--
>g> print "Starting Multi Thread Method"


>g> class MyThread(Thread):

>g> def __init__(self, site, s, FROM, MSGBODY):
>g> Thread.__init__(self)
>g> self.site = site
>g> self.s=s
>g> self.FROM=FROM
>g> self.MSGBODY=MSGBODY

You give the s (connection) here as a parameter, store it in self.s and
never use that attribute.

>g> def run(self):
>g> print "running for %s " %self.site
>g> s.sendmail(self.FROM, self.site, self.MSGBODY)

Here you use the global s, not self.s

As I said above you should do the SMTP connection setup, including the
login, here, and store the connection either in self.s or in a local
variable s in the method. As you don't use the s in another method, I
think a local variable is better.

>g> print "Emailed for  site %s" %self.site

>g> a= time.time()
>g> threads = []

>g> for site in listTo:
>g> T = MyThread(site,s,FROM,MSGBODY)
>g> threads.append(T)
>g> T.start()

>g> for i in threads:
>g> i.join()

Of course the next 2 lines should also be moved to run().

>g> s.quit()
>g> s.close()
>g> print "Took %s seconds" %str(time.time()-a)

>g> #-

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: [email protected]
--
http://mail.python.org/mailman/listinfo/python-list


Error in running python -v on Mac ox 10.5.

2009-05-05 Thread silverburgh

Hi,

I run 'python -v' on Macos 10.5 but I get this error :
# can't create /System/Library/Frameworks/Python.framework/Versions/
2.5/lib/python2.5/encodings/utf_8.pyc

Can you please tell me how to fix it?

And why I am seeing a lot of 'install' message' when i run 'python -
v'? I don't think I see that many
install message on linux.

Here is the full message.  Thanks for any help.

$ python -v
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# /System/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/site.pyc matches /System/Library/Frameworks/Python.framework/
Versions/2.5/lib/python2.5/site.py
import site # precompiled from /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/site.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/os.pyc matches /System/Library/Frameworks/Python.framework/
Versions/2.5/lib/python2.5/os.py
import os # precompiled from /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/os.pyc
import posix # builtin
# /System/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/posixpath.pyc matches /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/posixpath.py
import posixpath # precompiled from /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/posixpath.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/stat.pyc matches /System/Library/Frameworks/Python.framework/
Versions/2.5/lib/python2.5/stat.py
import stat # precompiled from /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/stat.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/UserDict.pyc matches /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/UserDict.py
import UserDict # precompiled from /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/UserDict.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/copy_reg.pyc matches /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/copy_reg.py
import copy_reg # precompiled from /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/copy_reg.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/types.pyc matches /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/types.py
import types # precompiled from /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/types.pyc
import _types # builtin
# /System/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/warnings.pyc matches /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/warnings.py
import warnings # precompiled from /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/warnings.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/linecache.pyc matches /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/linecache.py
import linecache # precompiled from /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/linecache.pyc
import encodings # directory /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/encodings
# /System/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/encodings/__init__.pyc matches /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/encodings/__init__.py
import encodings # precompiled from /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/encodings/__init__.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/codecs.pyc matches /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/codecs.py
import codecs # precompiled from /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/codecs.pyc
import _codecs # builtin
# /System/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/encodings/aliases.pyc matches /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/encodings/aliases.py
import encodings.aliases # precompiled from /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/encodings/aliases.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/encodings/utf_8.pyc has bad mtime
import encodings.utf_8 # from /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/encodings/utf_8.py
# can't create /System/Library/Frameworks/Python.framework/Versions/
2.5/lib/python2.5/encodings/utf_8.pyc
Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
dlopen("/System/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/lib-dynload/readline.so", 2);
import readline # dynamically loaded from /System/Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/lib-dynload/readline.s

thc v0.3 - txt to html converter - better code?

2009-05-05 Thread Florian Wollenschein

Hi all,

here's some code of thc, my txt to html converter programmed with Python 
and pyQT4:

---
if self.rdioBtnTransitional.isChecked():
if self.cmboBoxLang.currentText() == "English":
file_open.write('HTML 4.0 Transitional//EN">' + '\n')

elif self.cmboBoxLang.currentText() == "German":
file_open.write('HTML 4.0 Transitional//DE">' + '\n')

else:
file_open.write('4.0 Strict//EN">' + '\n')

if self.cmboBoxLang.currentText() == "English":
file_open.write('HTML 4.0 Strict//EN">' + '\n')

elif self.cmboBoxLang.currentText() == "German":
file_open.write('HTML 4.0 Strict/DE">' + '\n')



Do you have any ideas for a better code than that? Could this be done 
smarter, shorter, whatever!?


Thanks in advance,
Listick
http://www.listick.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: desperately looking for a howto on running my wxPython app on Vista

2009-05-05 Thread Paul Sijben
Mike Driscoll wrote:
> On Apr 29, 4:17 am, Paul Sijben  wrote:

>> Is there any way to check which is the offending pyd/dll?  (normally
>> Vista does not give out much data on what went wrong)
>>
>> Paul
> 
> You might be able to find it using the Dependency Walker utility:
> 
> http://www.dependencywalker.com/

Mike, thanks! That spotted indeed some issues with one specific file:
SHLWAPI.DLL, now let's see what is the issue. The report from Dependency
 Walker:"Warning: At least one module has an unresolved import due to a
missing export function in a delay-load dependent module." is not
telling me much at this moment. The FAQ from Dependency Walker sais this
  is not a major issue, but apparently on Vista it is ?!?

Does anyone have a clue what I am to do about this?

Interestingly On WinXP it flags DWMAPI.DLL as missing. I did not spot
that on the Vista box.

Paul

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


Re: list comprehension question

2009-05-05 Thread Emile van Sebille

On 5/5/2009 9:15 AM J Kenneth King said...


List comprehensions can make a reader of your code apprehensive
because it can read like a run-on sentence and thus be difficult to
parse. The Python documentation discourages their use and I believe
for good reason.


Can you provide a link for this?  I'd like to see specifically what's 
being discouraged, as I'd be surprised to find routine usage frowned upon.


Emile

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


Re: for with decimal values?

2009-05-05 Thread J. Cliff Dyer
On Sun, 2009-05-03 at 19:48 -0700, alex23 wrote:
> On May 4, 11:41 am, Esmail  wrote:
> > All this discussion makes me wonder if it would be a good idea
> > for Python to have this feature (batteries included and all) - it
> > would have its uses, no?
> 
> Well, sometimes more discussion == less consensus :)
> 
> But it's really easy to roll your own:
> 
> from decimal import Decimal
> 
> def args2dec(fn):
> '''*args to Decimal decorator'''
> float2dec = lambda f: Decimal(str(f))
> def _args2dec(*args):
> args = map(float2dec, args)
> return fn(*args)
> return _args2dec
> 
> @args2dec
> def drange(start, stop, step):
> while start < stop:
> yield start
> start += step

I'd prefer not to force my users into using the Decimal type.  Maybe
float fits their needs better.  So here's a generalized xrange
replacement, which fixes an error in the drange implementation above
(try it with a negative step).  It's also highly *not* optimized.
Calculating i * step every time slows it down.  Speeding it back up is
an exercise for the reader.

def general_xrange(start, stop, step=1):
target = stop * step
if start * step > target:
raise ValueError
i = start
while i * step < target:
yield i
i += step

Cheers,
Cliff


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


Re: call function of class instance with no assigned name?

2009-05-05 Thread George Oliver
On May 5, 9:01 am, Chris Rebert  wrote:
> On Tue, May 5, 2009 at 8:52 AM, George Oliver  
> wrote:

> > I create instances of these classes in a list attached to a third,
> > 'brain' class.
>
> You could exploit Python's dynamism by using the getattr() function:


Thanks for the responses -- I should have mentioned that I looked at
the getattr() function, but as I instantiate the key handler and
command handler classes in a list (like handlers = [command_handler(),
keyboard_handler()], I'm unsure how to reference that class instance
in the getattr in a straightforward way (short of keeping track of
each instance's position in the handlers list). Is there a typical way
of doing that?

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


Re: Code works fine except...

2009-05-05 Thread MRAB

Ross wrote:

On May 5, 12:32 am, John Yeung  wrote:

On May 5, 1:12 am, John Yeung  wrote:


[...] the problem may require bigger guns (either much better
math or much more sophisticated programming).

Yes, I'm responding to myself.

Well, I went ahead with the approach I mentioned earlier, generating
all possible matches and then selecting among them as needed to fill
up the courts, trying to keep the number of matches played by each
player as fair as possible.  (I should mention that this, or something
similar, was suggested earlier by someone else in a different thread,
in response to the same question by the same OP.)

I did use "bigger guns" (mainly a class for player objects, with
custom __cmp__ method), but still didn't do anything with doubles.

I haven't tested it much, but I'll post it if anyone's interested.
(That way people can pick on me instead of the OP. ;)

John


I'm interested to see what you did. From your description, it sounds
like I've tried what you've done, but when I implemented my version,
it took minutes to evaluate for bigger numbers. If that isn't the case
with yours, I'd be interested in seeing your implementation.


Here's my approach (incomplete):

def get_pair(player_list, played):
for first in range(len(player_list)):
player_1 = player_list[first]
for second in range(first + 1, len(player_list)):
player_2 = player_list[second]
pair = player_1, player_2
sorted_pair = tuple(sorted(pair))
if sorted_pair not in played:
played.add(sorted_pair)
del player_list[second]
del player_list[first]
return pair
return None

def round_robin(player_list, courts, played):
playing = []
for c in range(courts):
pair = get_pair(player_list, played)
if pair is None:
break
playing.append(pair)
byes = player_list[:]
player_list[:] = byes + [player for pair in playing for player in pair]
yield playing, byes

def test_round_robin(players, rounds, courts, doubles=False):
player_list = range(players)
played = set()
for r in range(rounds):
for playing, byes in round_robin(player_list, courts, played):
print playing, byes

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


Re: Is there is any way to send messages to chunk of emails ID's concurrently using smptlib

2009-05-05 Thread Minesh Patel
On Mon, May 4, 2009 at 2:01 PM, Piet van Oostrum  wrote:
>> gganesh  (g) wrote:
>
>>g> Hi friends,
>>g> I suppose sendmail() can send mails one by one ,how to send mails
>>g> concurrently ,
>>g> It would be very grateful,if someone could point out a solution.
>

You can always use twisted which has an smtp library which is used for
concurrency. Not a complete working example but an understanding of
deferreds is required.

Ex:

from twisted.mail import smtp
from twisted.internet import reactor, defer

  def sendEmail(to, message, subject="Testing",
 _from='[email protected]'):
  """Used to send emails asyncronously to multiple recipients"""
  msg = MIMEText(message)
  msg['Subject'] = subject
  msg['From'] = _from
  msg['To'] = ", ".join(to)

  sending = smtp.sendmail('localhost', _from, to, msg)
  sending.addCallback(sendComplete, to).addErrback(sendFailed)

   def sendFailed(error):
  print "Email failed: %r" % (error.getTraceback(),)

   def sendComplete(result, recipients):
  numDelivered, addrInfo = result
  print addrInfo
  if (numDelivered != len(recipients)):
 log.msg(SmtpError, "Not all recipients received email %r" % addrInfo)

buf = 'TESTING'
sendEmail(to=['[email protected]'], message=buf)


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


Re: Re: list comprehension question

2009-05-05 Thread J. Cliff Dyer
On Fri, 2009-05-01 at 13:00 -0400, John Posner wrote:
> Shane Geiger wrote:
> >if type(el) == list or type(el) is tuple:
> A tiny improvement:
> 
> if type(el) in (list, tuple):
> 

Another alternative, which might be useful in some cases:

  if hasattr(el, '__iter__'):

This covers all iterables, not just lists and tuples.  

So:

>>> flatten([1,2, xrange(3,15), 15, 16])
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

The downside, of course, is that some iterables might be infinite (such
as count), which would cause hidden breakage.  But if you have one of
those in your data structure, why are you trying to flatten it anyway?


Cheers,
Cliff


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


help for documentation and license

2009-05-05 Thread Murali kumar
hi all..

I finished my application using python 2.6 and wxpython 2.8.9

>> I want to generate documentation for my application..
  please suggest me and provide links to generate documents in easy
way..

>> I want to host my product as open source.. I'dont know about licensing..
  help me for this also..


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


Re: list comprehension question

2009-05-05 Thread J. Cliff Dyer
On Tue, 2009-05-05 at 12:15 -0400, J Kenneth King wrote:
> Emile van Sebille  writes:
> 
> > On 5/1/2009 7:31 AM J Kenneth King said...
> >> Chris Rebert  writes:
> >>> b = []
> >>> for pair in a:
> >>> for item in pair:
> >>> b.append(item)
> >>
> >> This is much more clear than a nested comprehension.
> >>
> >> I love comprehensions, but abusing them can lead to really dense and
> >> difficult to read code.
> >
> > I disagree on dense and difficult, although I'll leave open the
> > question of abuse.
> 
> Dense and difficult may be subjective to people like you or I, but you
> left out the "to read" part of that sentence. I was referring to the
> negative effect nested or complex list comprehensions can have on
> readability.
> 
> > b = [ item for pair in a for item in pair ]
> 
> It's a clever statement, but use it once and its gone. Why not use the
> expanded form in a function definition and get an even shorter, but
> clearer statement?
> 

It's also not obvious what it means.  I would have thought the proper
incantation would be:

[item for item in pair for pair in a]

but that returns [5,5,5,6,6,6].  I still haven't figured out why.  The
way you have to bounce your eyes back and forth in the comprehension
makes it hard to read the logic.  With the loop, on the other hand it is
blatantly obvious which way the nesting occurs.



>
> >>> b = flatten(a)
> 
> Boom, done.
> 
> > This is exactly the code above expressed in comprehension form.
> >
> > It's worth knowing that a list comprehension is structured identically
> > to the equivalent for loop.  So it really is neither more dense nor
> > more difficult to read.  Further, you can tell immediately from the
> > start of the list comprehension what you've got -- in this case a list
> > of item(s).

Empirically, I'd have to disagree with you.  The structure is changed by
the fact that "item" gets put at the beginning of the comprehension.
With the loop, each variable gets introduced in a for statement, and
then used.  With the list comprehension, "item" gets used at the
beginning, and then assigned to in the for expression at the end.
Meanwhile, pair gets introduced as the loop variable in the first for
expression, and iterated over in the second for expression.  So do you
read it left to right or right to left?  Neither.  You have to hold the
whole expression in your mind at once.  Good for short and simple
comprehensions, bad as they get more complicated.

 
> >
> > Here with some slight changes...
> >
>  a = [(1, 2), (3, 4, 7), (5, 6)]
>  [ item for j in a if len(j)==2 for item in j if item % 2 ]
> > [1, 5]
> >

This, to me, looks like line noise, approaching perl in its
unreadability.


> > ...opposed to...
> >
>  for j in a:
> > ... if len(j)==2:
> > ... for item in j:
> > ... if item % 2:
> > ... b.append(item)
> > ...
>  b
> > [1, 5]
> 
> 

Much nicer.  Thank you.

> Thanks for the lesson in list comprehensions, but I'm well aware of
> how they work.
> 
> List comprehensions can make a reader of your code apprehensive
> because it can read like a run-on sentence and thus be difficult to
> parse. The Python documentation discourages their use and I believe
> for good reason. It's much easier to explain complex processes with a
> function rather than a single nested statement.
> 
> >
> > YMMV,
> >
> > Emile
> 
> It will apparently vary greatly. Depending on how much coffee I've
> had.
> 
> ;)
> 
> J
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

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


Re: SQL and CSV

2009-05-05 Thread Matimus
On May 5, 9:25 am, Nick  wrote:
> On May 5, 5:19 pm, Tim Golden  wrote:
>
>
>
> > Nick wrote:
> > > I have a requirement to read a CSV file. Normally, no problem, just
> > > import CSV and slurp the file up.
>
> > > However, in this case I want to filter out lines that have fields set
> > > to particular values.
>
> > > It would be neat to be able to do something like this.
>
> > > select * from test.csv where status <> "Canceled"
>
> > > Using adodb I can do this, so long as I don't have the where clause. :-
> > > (
>
> > > Is there a reasonable lightweight way of doing this in Python?
>
> > > I could write some python code that is used to filter rows, and inport
> > > that from config, but it's not quite as elegant as an SQL route.
>
> > Not entirely clear what you are and aren't prepared to try here, but...
> > the most obvious Python-based way to do this is treating the csv reader
> > as an iterator and filtering there. Your last line suggests that's not
> > what you want but just in case I've misunderstood:
>
> > 
> > id,code,status
> > 1,"ONE","Active"
> > 2,"TWO","Cancelled"
> > 3,"THREE","Active"
> > 
>
> > 
> > import csv
>
> > for row in csv.DictReader (open ("c:/temp/test.csv", "rb")):
> >   if row['status'] != 'Cancelled':
> >     print row
>
> > 
>
> > Doesn't seem too onerous, and could obviously be wrapped in
> > some useful class/module.
>
> > But if you really want to go the SQL route, I believe there are
> > ODBC adapters for CSV which, combined with PyODBC or CeODBC,
> > would probably take you where you want to go.
>
> > TJG
>
> Part of the problem is that the 'selection' needs to be in a config
> file. I can put the if row['status'] != 'Cancelled': return True into
> a config, read it and eval it, but its not quite as clean as an sql
> route.
>
> Nick

Well, if you are using 2.5.x you could always stuff it into a sqlite
in-memory database, and then execute a SQL query. Heck, you don't even
_need_ 2.5, but in 2.5 sqlite is part of the distribution.

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


Re: help for documentation and license

2009-05-05 Thread Gökhan SEVER
Hi,

Even though I don't know what your project does, you will need to use
"Sphinx" to create semi-automatic documentation out of your project.

I would recommend you to take a look a quality "free" Python module:
Matplotlib (http://matplotlib.sourceforge.net/index.html)
Go ahead, and check out the main svn trunk. There you will see all
what you need about documentation creation with Sphinx.

Good luck...

Gökhan



On Tue, May 5, 2009 at 12:43 PM, Murali kumar  wrote:
> hi all..
>
> I finished my application using python 2.6 and wxpython 2.8.9
>
>>> I want to generate documentation for my application..
>   please suggest me and provide links to generate documents in easy
> way..
>
>>> I want to host my product as open source.. I'dont know about licensing..
>   help me for this also..
>
>
> Advanced Thanks ..
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: help for documentation and license

2009-05-05 Thread CTO
On May 5, 2:30 pm, Gökhan SEVER  wrote:
> Hi,
>
> Even though I don't know what your project does, you will need to use
> "Sphinx" to create semi-automatic documentation out of your project.
>
> I would recommend you to take a look a quality "free" Python module:
> Matplotlib (http://matplotlib.sourceforge.net/index.html)
> Go ahead, and check out the main svn trunk. There you will see all
> what you need about documentation creation with Sphinx.
>
> Good luck...
>
> Gökhan
>
> On Tue, May 5, 2009 at 12:43 PM, Murali kumar  wrote:
> > hi all..
>
> > I finished my application using python 2.6 and wxpython 2.8.9
>
> >>> I want to generate documentation for my application..
> >   please suggest me and provide links to generate documents in easy
> > way..
>
> >>> I want to host my product as open source.. I'dont know about licensing..
> >   help me for this also..

You can autogenerate API docs using pydoc (builtin, usually ugly) or
epydoc
(external, not so ugly), or you can use a project like sphinx for hand
written docs.

As far as hosting goes, sourceforge is usually the way to go, although
I'm
a huge fan of gitorious (in fact, wrote a recipe to autogenerate API
docs
for markdown http://code.activestate.com/recipes/576733/>) but
you
have to be using git for it to work. Github is another choice. If
that's
the case.

As far as licensing goes, you have a *LOT* of options, so you may want
to
check out http://en.wikipedia.org/wiki/Comparison_of_free_software_licenses>

Geremy Condra

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


Re: thc v0.3 - txt to html converter - better code?

2009-05-05 Thread Stefan Behnel
Florian Wollenschein wrote:
> here's some code of thc, my txt to html converter programmed with Python
> and pyQT4:
> ---
> 
> if self.rdioBtnTransitional.isChecked():
> if self.cmboBoxLang.currentText() == "English":
> file_open.write(' 4.0 Transitional//EN">' + '\n')
> elif self.cmboBoxLang.currentText() == "German":
> file_open.write(' 4.0 Transitional//DE">' + '\n')
> else:
> file_open.write(' Strict//EN">' + '\n')
> if self.cmboBoxLang.currentText() == "English":
> file_open.write(' 4.0 Strict//EN">' + '\n')
> elif self.cmboBoxLang.currentText() == "German":
> file_open.write(' 4.0 Strict/DE">' + '\n')
> 
> 
> 
> Do you have any ideas for a better code than that? Could this be done
> smarter, shorter, whatever!?

I assume you are referring to the code duplication above. You can build the
string incrementally instead, e.g.

language_map = {'English': 'EN', 'Deutsch': 'DE'}
strict_or_transitional = {True: 'Transitional', False: 'Strict'}

# this will raise a KeyError for unknown languages
language = language_map[ self.cmboBoxLang.currentText() ]

# this assumes that isChecked() returns True or False
spec = strict_or_transitional[self.rdioBtnTransitional.isChecked()]

doctype = '\n' % (
spec, language)

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


Re: call function of class instance with no assigned name?

2009-05-05 Thread Dave Angel

George Oliver wrote:

hi, I'm a Python beginner with a basic question. I'm writing a game
where I have keyboard input handling defined in one class, and command
execution defined in another class. The keyboard handler class
contains a dictionary that maps a key to a command string (like 'h':
'left') and the command handler class contains functions that do the
commands (like def do_right(self):),

I create instances of these classes in a list attached to a third,
'brain' class. What I'd like to have happen is when the player presses
a key, the command string is passed to the command handler, which runs
the function. However I can't figure out a good way to make this
happen.

I've tried a dictionary mapping command strings to functions in the
command handler class, but those dictionary values are evaluated just
once when the class is instantiated. I can create a dictionary in a
separate function in the command handler (like a do_command function)
but creating what could be a big dictionary for each input seems kind
of silly (unless I'm misunderstanding something there).

What would be a good way to make this happen, or is there a different
kind of architecture I should be thinking of?

  
You have lots of words, but no code, and no explanation of why you're 
choosing this "architecture."  So it's unclear just what to propose to 
you, without sticking to generalities.


1) forget about getattr() unless you have hundreds of methods in your 
map.  The real question is why you need two maps. What good is the 
"command string" doing you?   Why not just map the keyvalues directly 
into function objects?


2) Look at the following simple example, where I'm assuming that a 
"keycode" is simply an ASCII character.


class Command(object):
   def __init__(self):
   pass
   def doEnter(self):
   print "Enter is done"
   def doA(self):
   print "A is done"

cmd = Command()



table = {
   13: cmd.doEnter,
   65: cmd.doA
}

print "trying 13"
key = 13
table[key]()
print "trying 65"
key = 65
table[key]()

3) As for rebuilding the dictionary, that just depends on where you 
build it, and what it's lifetime is.  If it's got enough lifetime, and 
appropriate scope, you wouldn't have to rebuild anything.


4) Code up a first try, and when you get stuck, ask a specific question.

You said you're a beginner.  So keep it as simple as possible.l

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


Re: desperately looking for a howto on running my wxPython app on Vista

2009-05-05 Thread Mike Driscoll
On May 5, 11:43 am, Paul Sijben  wrote:
> Mike Driscoll wrote:
> > On Apr 29, 4:17 am, Paul Sijben  wrote:
> >> Is there any way to check which is the offending pyd/dll?  (normally
> >> Vista does not give out much data on what went wrong)
>
> >> Paul
>
> > You might be able to find it using the Dependency Walker utility:
>
> >http://www.dependencywalker.com/
>
> Mike, thanks! That spotted indeed some issues with one specific file:
> SHLWAPI.DLL, now let's see what is the issue. The report from Dependency
>  Walker:"Warning: At least one module has an unresolved import due to a
> missing export function in a delay-load dependent module." is not
> telling me much at this moment. The FAQ from Dependency Walker sais this
>   is not a major issue, but apparently on Vista it is ?!?
>
> Does anyone have a clue what I am to do about this?
>
> Interestingly On WinXP it flags DWMAPI.DLL as missing. I did not spot
> that on the Vista box.
>
> Paul
>
>
>
> > - Mike

Hmmm...I'm not familiar with that DLL, but a little googling seems to
indicate that you may be able to get it off your installation CD:

http://www.techimo.com/forum/applications-operating-systems/76550-winxp-msgina-dll-shlwapi-dll-problem.html

The link above gives the steps for XP, but Vista will probably be
similar. I don't know for sure, but you may have to register the dll
once you've got it copied back onto your machine.

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


Re: Self function

2009-05-05 Thread Paul Rubin
Steven D'Aprano  writes:
> def rvisit(node):
> print node
> if node and node.link is not None:
> rvisit(node.link)

Less redundant (remember the extra "recursion" doesn't cost anything
if the compiler is sane enough to turn it into a jump):

 def rvisit(node):
 print node
 if node:
 rvisit(node.link)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Which one is best Python or Java for developing GUI applications?

2009-05-05 Thread Pascal Chambon

Chris Rebert a écrit :

On Tue, May 5, 2009 at 12:26 AM, Paul Rudin  wrote:
  

Paul Rubin  writes:



srinivasan srinivas  writes:
  

Could you tell me does Python have any advantages over Java for the
development of GUI applications?


Yes.
  

Clearly c.l.p needs to adopt the SNB 
convention :)



Surely you have forgotten the comedy style of the language's namesake,
which makes that rule completely inadmissible! ;P

Cheers,
Chris
  


The fact that Python is a dynamic language offers, in my opinion, a huge 
advantage to quickly setup a GUI, without caring about the infinite 
details of the variable types and function signatures.
Its good handling of "function as first-class objects" is also precious 
when comes the time of setting callbacks (I can't bear anymore the way 
Swing does it, with interfaces etc.)


But much depends on the framework used, too. I've used wxPython for a 
multimedia project, and actually it lacked a lot of necessary features 
(transparency, event loop tuning, multithreading support...), but that 
was 1 year ago, maybe things have changed.
Anyway, I'd advocate the use of PyQt, which really offers tremendous 
possibilities - if your application isn't a simple office application, 
its' really worth turning towards pyqt.


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


Numpy on python 2.7a

2009-05-05 Thread A. Cavallo
Hi,

I'm trying to compile numpy using my own pet project based on the python svn 
code (that's the reason for the 2.7a tag).

It is essentially a /opt python installation and it tailored for linux: its 
main goal is to be installed in parallel so it won't collide with a system 
installed python (this won't impact the sys admin work).

The rpms built so far can be found under:

http://download.opensuse.org/repositories/home:/cavallo71:/python-opt/

It includes several patches both stolen from other sources, some made by 
myself (at some point I plan to do the same for debian based distributions 
when I'll have some spare time) and it contains a smoke test to verify the 
build is ok.

The user willing to activate the "opt-python" has to just source the 
file /opt/opt-python-2.7a0/opt-python-env.sh and he/she will have a fully 
working python (in this way there could be several different python version 
at the same time).

So far so good, I've been able to compile the python imaging library, but it 
fails to compile numpy.

The message I'm receiving is:



/opt/opt-python-2.7a0/include/python2.7/pyconfig.h:127:1: warning: this is the 
location of the previous definition
ar: adding 1 object files to build/temp.linux-i686-2.7/libnpymath.a
ar: illegal option -- /
Usage: ar [emulation options] [-]{dmpqrstx}[abcfilNoPsSuvV] [member-name] 
[count] archive-file file...
   ar -M [  - read options from 
 emulation options:
  No emulation specific options
ar: supported targets: elf32-i386 a.out-i386-linux efi-app-ia32 efi-bsdrv-ia32 
efi-rtdrv-ia32 elf32-little elf32-big elf64-alpha ecoff-litt
lealpha elf64-little elf64-big elf32-littlearm elf32-bigarm elf32-hppa-linux 
elf32-hppa elf64-hppa-linux elf64-hppa elf64-x86-64 elf64-ia64
-little elf64-ia64-big efi-app-ia64 efi-bsdrv-ia64 efi-rtdrv-ia64 elf32-m68k 
a.out-m68k-linux elf32-tradbigmips elf32-tradlittlemips ecoff-
bigmips ecoff-littlemips elf32-ntradbigmips elf64-tradbigmips 
elf32-ntradlittlemips elf64-tradlittlemips elf32-powerpc aixcoff-rs6000 elf32
-powerpcle ppcboot elf64-powerpc elf64-powerpcle aixcoff64-rs6000 elf32-s390 
elf64-s390 elf32-sh-linux elf32-shbig-linux elf32-sparc a.out-
sparc-linux elf64-sparc a.out-sunos-big efi-app-x86_64 efi-bsdrv-x86_64 
efi-rtdrv-x86_64 mach-o-le mach-o-be mach-o-fat pef pef-xlib sym sr
ec symbolsrec tekhex binary ihex trad-core
ar: illegal option -- /
Usage: ar [emulation options] [-]{dmpqrstx}[abcfilNoPsSuvV] [member-name] 
[count] archive-file file...




Is there any way I can increase the output to discover what went wrong?

Best regards,
Antonio Cavallo
--
http://mail.python.org/mailman/listinfo/python-list


Re: call function of class instance with no assigned name?

2009-05-05 Thread George Oliver
On May 5, 11:59 am, Dave Angel  wrote:

> 1) forget about getattr() unless you have hundreds of methods in your
> map.  The real question is why you need two maps. What good is the
> "command string" doing you?   Why not just map the keyvalues directly
> into function objects?


Thanks for the reply Dave. I understand your example and it's what I
originally used. Here is more detail on what I'm doing now, I hope
this will explain my question better.

In the game I'm writing the player, monsters, items and so on are
instances of class Thing, like:

class Thing(object):
def __init__(self, x, y, name):
self.x, self.y = x, y
self.name = name
self.brain = None

Some Things have an instance of class Brain attached. The Brain
instance has a list of handlers, like:

class Brain(object):
def __init__(self):
self.handlers = []

A handler class defines some functionality for the Brain. Each Brain
has an update method like this:

def update(self, arguments):
for handler in self.handlers:
handler.update(arguments)

So on each pass through the main game loop, it calls the update method
of all the brains in the game, which run their handler update methods
to change the state of the game.

A handler would be something like a key input handler. The key input
handler is defined separately from the command handler in the case I
want to use a different method of input, for example a mouse or
joystick.

In the dictionary of key inputs I could map each input directly to a
function. However there is no instance name I can call the function
on, as I create a thing, add a brain, and add handlers to the brain
like this:

player = Thing(26, 16, 'player')
player.brain = Brain()
player.brain.add_handlers(
commandHandler(player.brain, player),
keyboardHandler(player.brain),
fovHandler(player.brain))


So what I'm wondering is how to reference the instance in each brain's
list of handlers when I want to map something like a key input to a
command, or what a better way might be to structure the code.






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


Re: SQL and CSV

2009-05-05 Thread Tim Golden

Nick wrote:

Part of the problem is that the 'selection' needs to be in a config
file. I can put the if row['status'] != 'Cancelled': return True into
a config, read it and eval it, but its not quite as clean as an sql
route.



Still not clear what the restriction is. If you were writing
SQL you'd have to read *something* from your config file,
unless you're suggesting that the "config file" is in fact
a SQL file. Which is one way of doing it, but then you might
just as well have your config file as a Python file and
import it.

Have I missed the point somewhere here? Can you give an
example -- even a fictional one -- of what you couldn't
do using, say, the example I gave earlier?

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


Re: Way to use proxies & login to site?

2009-05-05 Thread Kushal Kumaran
On Wed, Apr 29, 2009 at 8:21 AM, inVINCable  wrote:
> On Apr 27, 7:40 pm, inVINCable  wrote:
>> Hello,
>>
>> I have been using ClientForm to log in to sites & ClientCookie so I
>> can automatically log into my site to do some penetration testing,
>> although, I cannot figure out a solution to use proxies with this
>> logging in automatically. Does anyone have any solutions?
>>
>> Thanks :)
>>
>> Vince
>
> Any ideas?

If, like the example at http://wwwsearch.sourceforge.net/ClientForm/,
you are using urllib2, you can read the documentation for that module.
 It also has examples for working with proxies.

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


Re: Self function

2009-05-05 Thread Steve Howell
On May 4, 11:08 pm, Steven D'Aprano
 wrote:
>
> I propose a small piece of sugar. When a function is entered, Python
> creates an ordinary local name in the function's local namespace, and
> binds the function itself to that name. Two possibilities for the name
> are `this` or `__this__`, analogous to `self` in methods and `__name__`
> in modules.
>
> If there is any support for this, I propose to send the following (long)
> post to python-ideas. Feedback, corrections and suggestions welcome.
>

I totally support this proposal.   I've definitely wasted time in the
past trying to invent my own workarounds for the use cases you
describe.

Obviously, there will be some bikeshed debates on __this__ vs.
__name__ vs. __func__, etc.  I don't have an opinion there, just want
*something* handy for introspection, DRYness, etc.

A more interesting question is whether __this__ would just always be
there (that's my vote), or if you should have to apply a special
decorator to get it (which I oppose, but I can see some merits).

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


Re: Self function

2009-05-05 Thread Aaron Brady
On May 5, 2:50 pm, Steve Howell  wrote:
> On May 4, 11:08 pm, Steven D'Aprano
>
>  wrote:
>
> > I propose a small piece of sugar. When a function is entered, Python
> > creates an ordinary local name in the function's local namespace, and
> > binds the function itself to that name. Two possibilities for the name
> > are `this` or `__this__`, analogous to `self` in methods and `__name__`
> > in modules.
>
> > If there is any support for this, I propose to send the following (long)
> > post to python-ideas. Feedback, corrections and suggestions welcome.
>
> I totally support this proposal.   I've definitely wasted time in the
> past trying to invent my own workarounds for the use cases you
> describe.
>
> Obviously, there will be some bikeshed debates on __this__ vs.
> __name__ vs. __func__, etc.  I don't have an opinion there, just want
> *something* handy for introspection, DRYness, etc.
>
> A more interesting question is whether __this__ would just always be
> there (that's my vote), or if you should have to apply a special
> decorator to get it (which I oppose, but I can see some merits).

Here is how to get the function into the function as an argument, and
still permit recursive calls onto it.

>>> def auto( f ):
... def _inner( *ar, **kw ):
... return f( g, *ar, **kw )
... g= _inner
... return g
...
>>> @auto
... def f( self, n ):
... print( self, n )
... return 1 if n== 1 else n* self( n- 1 )
...
>>> f(7)
 7
 6
 5
 4
 3
 2
 1
5040

The function that is passed into the function is the decorated
function, not the original.  The decorator function is also returned
from the decorator calls, so both the external caller and the internal
caller are calling the same function, '_inner' in the sample, which
then back-calls the original.

Please stay tuned for the post-graduate lecture.  There will be time
for questions at the cookies-and-creme seminar afterward.
--
http://mail.python.org/mailman/listinfo/python-list


Re: call function of class instance with no assigned name?

2009-05-05 Thread Aaron Brady
On May 5, 2:17 pm, George Oliver  wrote:
> On May 5, 11:59 am, Dave Angel  wrote:
>
> > 1) forget about getattr() unless you have hundreds of methods in your
> > map.  The real question is why you need two maps. What good is the
> > "command string" doing you?   Why not just map the keyvalues directly
> > into function objects?
>
> Thanks for the reply Dave. I understand your example and it's what I
> originally used. Here is more detail on what I'm doing now, I hope
> this will explain my question better.
>
> In the game I'm writing the player, monsters, items and so on are
> instances of class Thing, like:
>
> class Thing(object):
>     def __init__(self, x, y, name):
>         self.x, self.y = x, y
>         self.name = name
>         self.brain = None
>
> Some Things have an instance of class Brain attached. The Brain
> instance has a list of handlers, like:
>
> class Brain(object):
>     def __init__(self):
>         self.handlers = []
>
> A handler class defines some functionality for the Brain. Each Brain
> has an update method like this:
>
> def update(self, arguments):
>     for handler in self.handlers:
>         handler.update(arguments)
>
> So on each pass through the main game loop, it calls the update method
> of all the brains in the game, which run their handler update methods
> to change the state of the game.
>
> A handler would be something like a key input handler. The key input
> handler is defined separately from the command handler in the case I
> want to use a different method of input, for example a mouse or
> joystick.
>
> In the dictionary of key inputs I could map each input directly to a
> function. However there is no instance name I can call the function
> on, as I create a thing, add a brain, and add handlers to the brain
> like this:
>
> player = Thing(26, 16, 'player')
> player.brain = Brain()
> player.brain.add_handlers(
>                             commandHandler(player.brain, player),
>                             keyboardHandler(player.brain),
>                             fovHandler(player.brain))
>
> So what I'm wondering is how to reference the instance in each brain's
> list of handlers when I want to map something like a key input to a
> command, or what a better way might be to structure the code.

I'm not entirely sure I follow, but you may want to try keeping a set
(or list) of handlers that you pass in to the 'add_handlers' function,
and trying the 'getattr( handlerX, keyY )' on each of them, possible
only until you have a success.  You could also cache these results to
avoid performing the same search subsequently.

Otherwise, query each of the passed-in handlers when they are passed
in for a list of events they can handle; this may be by a brute
'getattr( x ) for x in ALL_EVENTS', or by maintaining a list of
handlers on a per-object basis, and merely combining the dictionaries;
then pick one or all of the handlers you've accumulated for an event
when the event occurs.



If you're really trying to be clever, you might use a metaclass or
class decorator to accumulate what events are handled in a class; or
just try the '__dict__' member of the /class/.

Will any of your handlers be handling overlapping or duplicate
events?  Do they all get a crack at it, or do you follow a pre-
deterimend order of precedence, or follow the order in which they were
passed in?

I'd probably try to discourage you from circularly linking the object
and handlers, not only for practical reasons.

There is also the possibility you could use dynamic mix-ins to create
a specialized once-in-a-lifetime brain class:

def create_brain( handlers ):
class new_brain( Brain ):
pass
for x in handlers:
setattr( new_brain, x.__name__, x )
return new_brain

brain= create_brain( handlers )( creation_args )

Forgive, just Thing-king aloud.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-05 Thread Duncan Booth
Aaron Brady  wrote:

> Here is how to get the function into the function as an argument, and
> still permit recursive calls onto it.
> 
 def auto( f ):
> ... def _inner( *ar, **kw ):
> ... return f( g, *ar, **kw )
> ... g= _inner
> ... return g
> ...
 @auto
> ... def f( self, n ):
> ... print( self, n )
> ... return 1 if n== 1 else n* self( n- 1 )
> ...
 f(7)
> 7
> 6
> 5
> 4
> 3
> 2
> 1
> 5040
> 

It might be better to use some convention other than 'self' for the first 
argument otherwise it will cause confusion when writing recursive methods:

>>> class C(object):
@auto
def meth(this, self, n):
print this, self, n
return 1 if n==1 else n*this(self, n-1)

>>> inst = C()
>>> inst.meth(5)
 <__main__.C object at 
0x0366C4E0> 5
 <__main__.C object at 
0x0366C4E0> 4
 <__main__.C object at 
0x0366C4E0> 3
 <__main__.C object at 
0x0366C4E0> 2
 <__main__.C object at 
0x0366C4E0> 1
120
--
http://mail.python.org/mailman/listinfo/python-list


Re: Code works fine except...

2009-05-05 Thread Ross
On May 5, 1:33 pm, MRAB  wrote:
> Ross wrote:
> > On May 5, 12:32 am, John Yeung  wrote:
> >> On May 5, 1:12 am, John Yeung  wrote:
>
> >>> [...] the problem may require bigger guns (either much better
> >>> math or much more sophisticated programming).
> >> Yes, I'm responding to myself.
>
> >> Well, I went ahead with the approach I mentioned earlier, generating
> >> all possible matches and then selecting among them as needed to fill
> >> up the courts, trying to keep the number of matches played by each
> >> player as fair as possible.  (I should mention that this, or something
> >> similar, was suggested earlier by someone else in a different thread,
> >> in response to the same question by the same OP.)
>
> >> I did use "bigger guns" (mainly a class for player objects, with
> >> custom __cmp__ method), but still didn't do anything with doubles.
>
> >> I haven't tested it much, but I'll post it if anyone's interested.
> >> (That way people can pick on me instead of the OP. ;)
>
> >> John
>
> > I'm interested to see what you did. From your description, it sounds
> > like I've tried what you've done, but when I implemented my version,
> > it took minutes to evaluate for bigger numbers. If that isn't the case
> > with yours, I'd be interested in seeing your implementation.
>
> Here's my approach (incomplete):
>
> def get_pair(player_list, played):
>      for first in range(len(player_list)):
>          player_1 = player_list[first]
>          for second in range(first + 1, len(player_list)):
>              player_2 = player_list[second]
>              pair = player_1, player_2
>              sorted_pair = tuple(sorted(pair))
>              if sorted_pair not in played:
>                  played.add(sorted_pair)
>                  del player_list[second]
>                  del player_list[first]
>                  return pair
>      return None
>
> def round_robin(player_list, courts, played):
>      playing = []
>      for c in range(courts):
>          pair = get_pair(player_list, played)
>          if pair is None:
>              break
>          playing.append(pair)
>      byes = player_list[:]
>      player_list[:] = byes + [player for pair in playing for player in pair]
>      yield playing, byes
>
> def test_round_robin(players, rounds, courts, doubles=False):
>      player_list = range(players)
>      played = set()
>      for r in range(rounds):
>          for playing, byes in round_robin(player_list, courts, played):
>              print playing, byes- Hide quoted text -
>
> - Show quoted text -

Looks like somewhat of an improvement, although the bye distribution
is still slightly lopsided. For example, in a singles league with 12
players, 12 rounds, and 4 courts, The first player had at least 2 less
byes than every other player and 3 less byes than the players with the
most number of byes. Thanks for your input though...I'll look into how
I can improve upon it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: AutoComplete in C++ Editor for Python

2009-05-05 Thread justme
I the rope project http://rope.sourceforge.net/ has an autocomplete
lib.
(I have not used it  just remember reading about it)
--
http://mail.python.org/mailman/listinfo/python-list


Re: python docs for beginner programmer?

2009-05-05 Thread Deep_Feelings
that is good ,thank you

anyone did that ? learning from python docs straight away ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-05 Thread bearophileHUGS
wolfram.hinde...:
> It is easy to change all references of the function name, except for
> those in the function body itself? That needs some explantation.

I can answer this. If I have a recursive function, I may want to
create a similar function, so I copy and paste it, to later modify the
copied version. Then to change its name I usually don't use a search &
rename of its name into its block of code because it's usually
useless. In non-recursive functions the name of the function is stated
only once, at the top.

Recursive functions violate the DRY principle, that's the root of the
problem.

The auto(f) decorator shown later by Aaron Brady seems the best
solution found so far, it's so nice that it even seems practically
usable.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-05 Thread bearophileHUGS
Aaron Brady:
> >>> def auto( f ):
>
> ...     def _inner( *ar, **kw ):
> ...             return f( g, *ar, **kw )
> ...     g= _inner
> ...     return g

Looks nice, I'll try to the following variant to see if it's usable:

def thisfunc(fun):
"""Decorator to inject a default name of a
function inside a function"""
def _inner(*args, **kwds):
return fun(g, *args, **kwds)
g = _inner
g.__name__ = fun.__name__
g.__dict__.update(fun.__dict__)
g.__doc__ = fun.__doc__
g.__module__ = fun.__module__
return g

@thisfunc
def SOMEVERYUGLYNAME(this, n):
return 1 if n <= 1 else n * this(n - 1)

assert SOMEVERYUGLYNAME(6) == 2*3*4*5*6

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Error in running python -v on Mac ox 10.5.

2009-05-05 Thread Piet van Oostrum
> silverburgh  (s) wrote:

>s> Hi,

>s> I run 'python -v' on Macos 10.5 but I get this error :
>s> # can't create /System/Library/Frameworks/Python.framework/Versions/
>s> 2.5/lib/python2.5/encodings/utf_8.pyc

>s> Can you please tell me how to fix it?

This looks like the utf_8.py file has not been compiled in the
installation. Looks like a (not serious) bug to me.

Probably sudo python -v would solve it (even without -v, but it will
tell you that it wrote the .pyc file).

>s> And why I am seeing a lot of 'install' message' when i run 'python -
>s> v'? I don't think I see that many
>s> install message on linux.

I don't see 'install' messages in the included text.
>s> Here is the full message.  Thanks for any help.
[deleted]
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: [email protected]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-05 Thread Aaron Brady
On May 5, 3:54 pm, [email protected] wrote:
> Aaron Brady:
>
> > >>> def auto( f ):
>
> > ...     def _inner( *ar, **kw ):
> > ...             return f( g, *ar, **kw )
> > ...     g= _inner
> > ...     return g
>
> Looks nice, I'll try to the following variant to see if it's usable:
>
> def thisfunc(fun):
>     """Decorator to inject a default name of a
>     function inside a function"""
>     def _inner(*args, **kwds):
>         return fun(g, *args, **kwds)
>     g = _inner
>     g.__name__ = fun.__name__
>     g.__dict__.update(fun.__dict__)
>     g.__doc__ = fun.__doc__
>     g.__module__ = fun.__module__
>     return g
>
> @thisfunc
> def SOMEVERYUGLYNAME(this, n):
>     return 1 if n <= 1 else n * this(n - 1)
>
> assert SOMEVERYUGLYNAME(6) == 2*3*4*5*6
>
> Bye,
> bearophile

/Actually/, the 'g' variable was spurious.  FWIW.

def auto( f ):
def _inner( *ar, **kw ):
return f( _inner, *ar, **kw )
return _inner

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


Re: Numpy on python 2.7a

2009-05-05 Thread Robert Kern

On 2009-05-05 15:06, A. Cavallo wrote:

Hi,

I'm trying to compile numpy using my own pet project based on the python svn
code (that's the reason for the 2.7a tag).


Ask on the numpy-discussion mailing list:

  http://www.scipy.org/Mailing_Lists

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


  1   2   >