Re: Any idea to emulate tail -f

2009-05-04 Thread CTO
On May 5, 2: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

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.

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


Re: Self function

2009-05-04 Thread Chris Rebert
On Mon, May 4, 2009 at 11:08 PM, Steven D'Aprano
 wrote:
> On Mon, 04 May 2009 17:54:50 -0400, Terry Reedy wrote:
>
>> bearophileh...@lycos.com 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.



While I'm +0 on the proto-PEP, it doesn't currently address (or at
least rebut hard enough) the inevitable obvious naysayer argument
which will go along the lines of:


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:

def recursive(func):
"""We caved enough to allow this into functools."""
def wrapper(*args, **kwds):
return func(func, *args, **kwds)
return wrapper
#
from functools import recursive
@recursive
def spam(this, number_of_thy_counting):
print " ".join([this.__name__.capitalize() + "!"]*number_of_thy_counting)

Which is not significantly more complex/longer/painful than learning
about __this__'s existence or typing the extra underscores and it
doesn't require any new syntax.

And the performance penalty for the proposed feature would actually be horrible!
And there would be much clashing with existing variable names, for
keywords are the Devil's work!
And your mother wears combat boots!
(etc...)


You touch on this in "Is this really necessary?", but I think you're
going to prove more persuasively how drastically sweeter this syntax
sugar would be.

Cheers,
Chris
-- 
The Devil's Advocate-General
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-05-04 Thread srinivasan srinivas

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! 
Edition http://downloads.yahoo.com/in/firefox/?fr=om_email_firefox
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-04 Thread Carl Banks
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.  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.

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


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


Re: Self function

2009-05-04 Thread Steven D'Aprano
On Mon, 04 May 2009 17:54:50 -0400, Terry Reedy wrote:

> bearophileh...@lycos.com 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` over `__this__`, for analogy with `self` inside methods. 
However it is more likely that existing code already uses the name 
`this`, since double-leading-and-trailing-underscore names are reserved 
for us

Any idea to emulate tail -f

2009-05-04 Thread Joel Juvenal Rivera Rivera
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

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


Re: subprocess & shared environments

2009-05-04 Thread Gabriel Genellina
En Mon, 04 May 2009 23:25:42 -0300, Robert Dailey   
escribió:



Thanks for your help guys. Unfortunately both ideas will not work. I
guess I should have mentioned that the batch file in question is
vsvars32.bat, from the Visual Studio installation directory. I should
not modify this file, nor can I create a "wrapper" batch file as you
suggested, since I call several other batch files at different times.
There's about 6 other nmake calls I make that each is preceeded with a
call to vsvars32.bat. For now I'm using the && DOS operator, this
seems to work, however it is not ideal.


There is nothing special about vsvars32.bat. If you execute it before your  
first program (maybe inside a .cmd that calls vsvars32 and then your  
program) then all the spawned programs will already see those settings. No  
need to invoke it over and over.
Also, if you enter the same settings in the registry (so they become  
persistent) you don't have to worry again.


--
Gabriel Genellina

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


Re: Question of UTF16BE encoding / decoding

2009-05-04 Thread Mark Tolonen


"Napalmski"  wrote in message 
news:mpg.2469d7edf8bbcd0a989...@eu.news.astraweb.com...

Hello,

I have an encoded string in the form "004e006100700061006c006d", if you
split on every 4 characters it decodes to a single character.
I have come up with this:

name = '004e006100700061006c006d'
name2 = ""
for x in range(0, len(name), 4):
   name2 = name2 + chr(int(name[x:x+4], 16))

Is there a better way to do this using name.decode() that would then
also work with .encode()?

I have tried .decode("utf-16-be"), which I beleive is the format here,
but I am getting the error:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-
11: ordinal not in range(128)

And my debugger seems to show a load of unicode when it breaks.


import binascii
s = '004e006100700061006c006d'
h = binascii.unhexlify(s)
print h.decode('utf-16-be')

-Mark


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


Re: Code works fine except...

2009-05-04 Thread John Yeung
On May 4, 11:01 pm, Ross  wrote:
> Anyways, I'm new to
> programming and this has been a good learning experience.

I'm glad that you've been trying, and seem to be sticking it out
despite sometimes getting negative feedback here.

> Next time around, I'll be sure to thoroughly comment
> my code before I ask for help on it.

The best documentation, especially for a language like Python, is
simply logical variable names and sensible conventions.  I bring this
up because I'm wary of the word "thoroughly".  When you're dealing
with experts, it's actually best to use inline comments sparingly;
they can figure out what code does.  The overall problem description
at the top is important, as well as explanation of "magic numbers" and
such.

> I really appreciate all the help that you've offered so far.

You're welcome.  I'm not sure how much I've helped, especially as I'm
frankly not one of the stronger programmers here.

> Right now, I'm debating whether I should try to reinvent
> the round_robin generator part of the code or whether
> there still might be a way to shuffle the results of the
> generated output so that I can slice it effectively.

If you are going to typically have roughly enough courts for your
players (as implied by your test data), then maybe there's still a
chance for using extended slicing.  Just make sure you don't always
pick the first element.  If the number of players and the number of
courts can vary wildly, and won't always match up at least sort of
nicely, then the problem may require bigger guns (either much better
math or much more sophisticated programming).

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


Question of UTF16BE encoding / decoding

2009-05-04 Thread Napalmski
Hello,

I have an encoded string in the form "004e006100700061006c006d", if you 
split on every 4 characters it decodes to a single character.
I have come up with this:

name = '004e006100700061006c006d'
name2 = ""
for x in range(0, len(name), 4):
name2 = name2 + chr(int(name[x:x+4], 16))

Is there a better way to do this using name.decode() that would then 
also work with .encode()?

I have tried .decode("utf-16-be"), which I beleive is the format here, 
but I am getting the error:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-
11: ordinal not in range(128)

And my debugger seems to show a load of unicode when it breaks.

Thank you!
--
http://mail.python.org/mailman/listinfo/python-list


Re: local module-docs server on Linux?

2009-05-04 Thread CTO
On May 4, 10:30 pm, Soumen banerjee  wrote:
> Hello,
> I had used python on windows and one of the features i liked best was
> that you could start a module-docs server and then use firefox to
> access it.

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


Re: Problem with case insensitive volumes

2009-05-04 Thread Dave Angel

dmoore wrote:

Does anyone know of a way to get the unique pathname for files stored
on FAT32 or other case insensitive drives?

For example:

os.path.samefile('/media/usbkey/file1.jpg','/media/usbkey/FILE1.jpg')

returns True

but, is there a simple way to determine whether '/media/usbkey/
file1.jpg' or '/media/usbkey/FILE1.jpg' is the actual representation
on the device.

it matters because operations like this have meaning:

os.rename('/media/usbkey/file1.jpg','/media/usbkey/tmp')
os.rename('/media/usbkey/tmp','/media/usbkey/FILE1.jpg')

If I have a program that scans a directory for files and compares
against a stored list of pathnames, I want to be able to determine not
only that the file still exists but whether or not it has changed case
(i.e. '/media/usbkey/file1.jpg' has become '/media/usbkey/FILE1.jpg').

Any takers?

  
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.



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


Re: Threaded alternatives to smtplib?

2009-05-04 Thread Alex Jurkiewicz

Piet van Oostrum wrote:

AJ> if __name__ == '__main__':
AJ>THREADS = []
AJ>for i in range(CONCURRENCY):
AJ>THREADS.append(threading.Thread(target=threadProcessRecipient))
AJ>for thread in THREADS:
AJ>thread.run()



You should use thread.start(), not thread.run(). When you use run(), it
will be sequential execution, as you experience. With start() you get
concurrency
  


Thanks! Changing this method call fixes the original problem we saw. In 
the process I've run into another though, seemingly a race condition / 
deadlock.


Our email script DKIM signs all messages with pydkim. Because this is so 
CPU intensive we run the signing in an external process, using 
dkimsign.py (which basically accepts the message on stdin, calls 
dkim.sign() on it and passes the result back on stdout). We call the 
DKIM signing while preparing each message in each thread like this:

cmd = subprocess.Popen(
   ['/usr/bin/nice', PYTHONBIN, 'dkimsign.py',
   DKIMSELECTOR,
   DKIMDOMAIN,
   DKIMPRIVATEKEYFILE],
   stdin = subprocess.PIPE,
   stdout = subprocess.PIPE)
message = cmd.communicate(message)[0]

The majority of the time (80%) our mail merge works fine -- messages are 
sent out in a multi-threaded manner. The rest of the time, some of the 
threads deadlock when calling dkimsign.py. Specifically, they stop 
during the communicate() call above. dkimsign.py never receives any 
input (hangs on message=sys.stdin.read()), and sits there waiting 
forever, which stops the thread from doing anything.


Is this a bug with subprocess? Is there some way to set a timeout on the 
communicate() call so I can detect these locks?


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


Re: Self function

2009-05-04 Thread Steven D'Aprano
On Mon, 04 May 2009 16:33:13 -0700, Carl Banks wrote:

> On May 4, 4:06 pm, bearophileh...@lycos.com 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".


>> >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. What 
are you suggesting, that Bearophile should write his tree-processing code 
to only deal with the degenerate case?



>> 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.


> 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.


> 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.



> [snip strawman example]

It's not a strawman just because you don't like it. 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.



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


Problem with case insensitive volumes

2009-05-04 Thread dmoore
Does anyone know of a way to get the unique pathname for files stored
on FAT32 or other case insensitive drives?

For example:

os.path.samefile('/media/usbkey/file1.jpg','/media/usbkey/FILE1.jpg')

returns True

but, is there a simple way to determine whether '/media/usbkey/
file1.jpg' or '/media/usbkey/FILE1.jpg' is the actual representation
on the device.

it matters because operations like this have meaning:

os.rename('/media/usbkey/file1.jpg','/media/usbkey/tmp')
os.rename('/media/usbkey/tmp','/media/usbkey/FILE1.jpg')

If I have a program that scans a directory for files and compares
against a stored list of pathnames, I want to be able to determine not
only that the file still exists but whether or not it has changed case
(i.e. '/media/usbkey/file1.jpg' has become '/media/usbkey/FILE1.jpg').

Any takers?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-04 Thread Steven D'Aprano
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. There are many algorithms that are more understandable 
written recursively than iteratively -- consult any good text book for 
examples. There are algorithms that are naturally iterative, and 
algorithms which are naturally recursive (and a few which are equally 
simple either way), and forcing either one into the other form leads to 
complicated and confusing code. This especially holds for mutually-
recursive functions, where re-writing them to be iterative is usually 
very difficult.

Sometimes it's worth rewriting a recursive algorithm to be iterative for 
the performance optimization, but that comes at the price of reduced 
readability.



-- 
Steven

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


Re: Code works fine except...

2009-05-04 Thread Ross
On May 4, 7:33 pm, John Yeung  wrote:
> On May 4, 8:56 pm, Ross  wrote:
>
> > Anyways, you're right that seq[0] is always evaluated.
> > That's why my algorithm works fine when there are odd
> > numbers of players in a league.
>
> It doesn't work fine for all odd numbers of players.  For example, 15
> players on 3 courts should result in 5 byes.  But what actually
> happens with your code is that you get 4 byes or 8 byes, depending on
> whether you've got floating-point division enabled.
>
> So the way you are selecting byes does not even guarantee that you'll
> allocate the correct number of active matches for the number of
> courts, and this is due to the fact that the extended slice is too
> "coarse" a tool for the task.  Now, it may be that for you, the number
> of players and courts is always within a confined range such that
> extended slicing and your magic constants will work.  That's fine for
> you, but we weren't given that information.
>
> I haven't even begun to look at what happens for doubles.
>
> John

You're right... I only tested cases when number of people playing
outnumbered the number of byes that week. Anyways, I'm new to
programming and this has been a good learning experience. Next time
around, I'll be sure to thoroughly comment my code before I ask for
help on it. I really appreciate all the help that you've offered so
far. Right now, I'm debating whether I should try to reinvent the
round_robin generator part of the code or whether there still might be
a way to shuffle the results of the generated output so that I can
slice it effectively.
--
http://mail.python.org/mailman/listinfo/python-list


Re: local module-docs server on Linux?

2009-05-04 Thread David Lyon
Hi Soumen,

You could try running the Python Package Manager that we are developing
on sourceforge.

There isn't a release yet but we have implemented two buttons inside
the program for 'Examples' and 'Documentation'.

What they do is go off and find any documentation files or example
directories for third party modules that are installed on the system.

Then, if found, they will open a web browser on any documentation
or examples directories.

In the spirit of open source you could give it a try

svn co https://pythonpkgmgr.svn.sourceforge.net/svnroot/pythonpkgmgr
pythonpkgmgr

Any feedback is welcome..

David

On Tue, 5 May 2009 08:00:13 +0530, Soumen banerjee 
wrote:
> Hello,
> I had used python on windows and one of the features i liked best was
> that you could start a module-docs server and then use firefox to
> access it. This would show module-docs for all modules you had
> installed(including any 3rd party installs) . How do i do this on
> linux?
> regards
> Soumen
> --
> http://mail.python.org/mailman/listinfo/python-list

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


Re: Code works fine except...

2009-05-04 Thread John Yeung
On May 4, 8:56 pm, Ross  wrote:

> Anyways, you're right that seq[0] is always evaluated.
> That's why my algorithm works fine when there are odd
> numbers of players in a league.

It doesn't work fine for all odd numbers of players.  For example, 15
players on 3 courts should result in 5 byes.  But what actually
happens with your code is that you get 4 byes or 8 byes, depending on
whether you've got floating-point division enabled.

So the way you are selecting byes does not even guarantee that you'll
allocate the correct number of active matches for the number of
courts, and this is due to the fact that the extended slice is too
"coarse" a tool for the task.  Now, it may be that for you, the number
of players and courts is always within a confined range such that
extended slicing and your magic constants will work.  That's fine for
you, but we weren't given that information.

I haven't even begun to look at what happens for doubles.

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


local module-docs server on Linux?

2009-05-04 Thread Soumen banerjee
Hello,
I had used python on windows and one of the features i liked best was
that you could start a module-docs server and then use firefox to
access it. This would show module-docs for all modules you had
installed(including any 3rd party installs) . How do i do this on
linux?
regards
Soumen
--
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess & shared environments

2009-05-04 Thread Robert Dailey
On May 1, 4:18 pm, Aaron Brady  wrote:
> On May 1, 12:09 am, Robert Dailey  wrote:
>
> > I'm currently calling subprocess.call() on a batch file (in Windows)
> > that sets a few environment variables that are needed by further
> > processes started via subprocess.call(). How can I persist the
> > environment modifications by the first call() function? I've done my
> > own searching on this and I came up with nothing.
>
> > Help is appreciated.
>
> I don't know if this will work, but you can try spawning a batch file
> that calls the first program to set the variables, then executes the
> second program.  You might need to create that batch file by hand, as
> well as the command line for the second process.
>
> You can also try setting the env. variables in the parent process, and
> restoring them after.

Thanks for your help guys. Unfortunately both ideas will not work. I
guess I should have mentioned that the batch file in question is
vsvars32.bat, from the Visual Studio installation directory. I should
not modify this file, nor can I create a "wrapper" batch file as you
suggested, since I call several other batch files at different times.
There's about 6 other nmake calls I make that each is preceeded with a
call to vsvars32.bat. For now I'm using the && DOS operator, this
seems to work, however it is not ideal.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Code works fine except...

2009-05-04 Thread Ross
On May 4, 7:59 pm, John Yeung  wrote:
> On May 4, 10:01 am, Ross  wrote:
>
> > The "magic numbers" that everyone is wondering about are
> > indeed used for spreading out the bye selection and I got
> > them by simply calculating a line of best fit when plotting
> > several courts: byes ratios.
>
> But that doesn't really help you.  When you do seq[::step], step is
> evaluated once and used for the whole extended slice.  So in almost
> all cases that you are likely to encounter, step is 2, so you'll get
> seq[0], seq[2], seq[4], etc.  Even if step is some other positive
> number, seq[0] will always be chosen.
>
> > The "byes = #whatever" in my code calculate the number of
> > tuples that need to be placed in the bye_list.
>
> Fine, but that's not the number of byes that you put into bye_list.
>
> > At first glance, the suggestion of adding a simple shift
> > at the end of round_robin doesn't seem to work since
> > round_robin already shifts everything except for the first
> > position already. Please correct me if I'm wrong because
> > you might have been suggesting something different.
>
> If you read my post carefully, you would see that you HAVE to do
> something about the first player always being stuck in the first
> spot.  Either move him around, or select your byes differently.
>
> That said, I've played around with the shuffling a bit, and it does
> seem to be pretty tricky to get it to work for the general case where
> there is no prior knowledge of how many players and courts you will
> have.
>
> I can't shake the feeling that someone good at math will be able to
> figure out something elegant; but if left to my own devices, I am
> starting to lean toward just generating all the possible matches and
> somehow picking from them as needed to fill the courts, trying to keep
> the number of matches played by each player as close to equal as
> possible, and trying to keep the waiting times approximately equal as
> well.
>
> John

"But that doesn't really help you.  When you do seq[::step], step is
evaluated once and used for the whole extended slice.  So in almost
all cases that you are likely to encounter, step is 2, so you'll get
seq[0], seq[2], seq[4], etc.  Even if step is some other positive
number, seq[0] will always be chosen."

It's not true that in almost all cases the step is 2. How that is
evaluated directly depends on the number of available courts. Anyways,
you're right that seq[0] is always evaluated. That's why my algorithm
works fine when there are odd numbers of players in a league. But if
you will notice, my original question was how I could ADD TO or AMMEND
my current code to account for even number of players. I have used an
algorithm that comes up with all possible pairings and then randomly
puts people together each week and places players in a bye list
according to how many times they've previously been in the bye list
but since I was dealing with random permutations, the algorithm took
minutes to evaluate when there were more than 10 players in the
league.
--
http://mail.python.org/mailman/listinfo/python-list


RE: sorting items in a table problematic because of scientific notation

2009-05-04 Thread Davis, Amelie Y
Thank you  _ that solved it. 

 
Amélie
 
 Please consider the environment before printing this e-mail or any of its 
attachments (if applicable)
 


-Original Message-
From: python-list-bounces+aydavis=purdue@python.org 
[mailto:python-list-bounces+aydavis=purdue@python.org] On Behalf Of Raymond 
Hettinger
Sent: Wednesday, April 29, 2009 10:31 AM
To: python-list@python.org
Subject: Re: sorting items in a table problematic because of scientific notation

[John Machin]
> > 'NEAR_DIST'], [('N', 9, 0), ('N', 9, 0), ('F', 19, 11)], [53, 55, '
>
> The data type code for the offending column is "F" which is not in the
> bog-standard dBase III set of C, N, D, and L. The code that you have used 
> merely
> returns unchanged the character string that finds in the data base.
>
>
>
> > 1.05646365517e+005'], [53, 6, ' 9.32599134016e+004'], [53, 0, '
> > 8.97477154418e+004'], [53, 2, ' 8.96449127749e+004'], [53, 1, '
> > 7.88170078501e+004'], [53, 5, ' 8.29281503631e+004'], [53, 4, '

FWIW, I just updated the recipe to handle an F typecode
by casting it to a float.  Hope this helps.


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


Re: Tkinter, Trouble with Message,Label widget

2009-05-04 Thread norseman

Ioannis Lalopoulos wrote:

I assume that you create the two windows through two different calls
to Tkinter.Tk() but you cannot enter two mainloops (at least not in a
normal way).

If you want a second window use the Toplevel widget.

Try the following, it does what you want:

import Tkinter

root = Tkinter.Tk()

my_text = Tkinter.StringVar(root)

another_window = Tkinter.Toplevel()

entry = Tkinter.Entry(root, textvar=my_text)
entry.pack()

label = Tkinter.Label(another_window, textvar=my_text)
label.pack()

root.mainloop()

In the above example, whatever you type in the entry widget in the
root window gets reflected in the label widget which is inside the
second window, the one that was created with Tkinter.Toplevel().

Hope it helps,

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



Hendrik van Rooyen  mentioned the textvar too.  Thanks Hendrik

John (Ioannis);
It took me awhile to get your template to work for me.
People reading this!  THE ABOVE CODE WORKS JUST FINE - AS IS!!!

My needs are slightly different and it took me a bit to get python and I 
on the same track.  I still have reflexes that demand dictionary 
compliance.  Global is supposed to be Global, really, not just sort of.


Once I get past the children I seem to do OK in python.

like:
mVar= '1234'according to docs, this is a global
p='%6s\n' % mVarsame
...some code to do something
mVar= '4321'updates a supposed global

  these two don't think so
print p prints from both of these show the 1234,
print '%s' % p[:]   they do not reflect the updated 'global'


>>>
>>> mVar= '1234'
>>> mVar
'1234'
>>> p= '%s\n' % mVar
>>> p
'1234\n'
>>>
>>> mVar= '4321'
>>> mVar
'4321'
>>> print p
1234
>>> print '%s' % p[:]
1234
>>>


The definitive on Toplevel was the biggest help. All I have read have 
never clearly stated its purpose. (A non-root root)


per Tkinter help:
"class Toplevel(BaseWidget, Wm)
 Toplevel widget, e.g. for dialogs.
 ...
"
Since I'm not doing dialogs, I quite reading and move on.




John: Thank you again.

Today: 20090504
copy/paste from Python 2.5.2 on Linux Slackware 10.2

Steve
norse...@hughes.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Code works fine except...

2009-05-04 Thread John Yeung
On May 4, 10:01 am, Ross  wrote:
> The "magic numbers" that everyone is wondering about are
> indeed used for spreading out the bye selection and I got
> them by simply calculating a line of best fit when plotting
> several courts: byes ratios.

But that doesn't really help you.  When you do seq[::step], step is
evaluated once and used for the whole extended slice.  So in almost
all cases that you are likely to encounter, step is 2, so you'll get
seq[0], seq[2], seq[4], etc.  Even if step is some other positive
number, seq[0] will always be chosen.

> The "byes = #whatever" in my code calculate the number of
> tuples that need to be placed in the bye_list.

Fine, but that's not the number of byes that you put into bye_list.

> At first glance, the suggestion of adding a simple shift
> at the end of round_robin doesn't seem to work since
> round_robin already shifts everything except for the first
> position already. Please correct me if I'm wrong because
> you might have been suggesting something different.

If you read my post carefully, you would see that you HAVE to do
something about the first player always being stuck in the first
spot.  Either move him around, or select your byes differently.

That said, I've played around with the shuffling a bit, and it does
seem to be pretty tricky to get it to work for the general case where
there is no prior knowledge of how many players and courts you will
have.

I can't shake the feeling that someone good at math will be able to
figure out something elegant; but if left to my own devices, I am
starting to lean toward just generating all the possible matches and
somehow picking from them as needed to fill the courts, trying to keep
the number of matches played by each player as close to equal as
possible, and trying to keep the waiting times approximately equal as
well.

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


Re: Database help needed

2009-05-04 Thread CTO
On May 4, 7:51 pm, Emile van Sebille  wrote:
> On 5/4/2009 4:30 PM Amber said...
>
>
>
>
>
> > My PHB is insane.
>
> > Today he drops 50,000 databases in MS Access format on my desk, and
> > tells me that by Friday I need to:
> > * Remove all of the "junk content" in the record fields;
> > * Remove all records with blank fields in them;
> > * Correct all fields in which the markup is "wrong";
> > * Correct all fields in which the data is "wrong";
> > * Ensure that all database include some specific tables;
> > ** Add appropriate content to the records in the "new" tables;
>
> > And finally, said databases are to be in:
>
> > * MS Access 97 format;
> > * MS Access 2000 format;
> > * MS Access 2003 format;
> > ** Is there any documentation anywhere on what the differences between
> > those is?   Won't a database created for Access 97 be openable in MS
> > Access 2003?
> > * SQLite format;
> > * MySQL format;
> > * PDB format, for use on his PalmPilot;
> > * Commas separated values;
> > * dBase 3;
> > * Excell spreadsheets;
> > * ODF spreadsheets;
>
> It wouldn't surprise me that you couldn't do all this with open office
> using command line options which is where I'd start.  There's also
> python modules available, but I haven't yet gotten into them.  I found
> most of what I needed on groups.google.com though, so not having
> internet access could be trouble -- some of the conversion structures
> and requirements weren't quite so obvious nor documentation easily
> available.
>
> Emile

I was just about to recommend OO. PyUNO is pretty easy to use, IMHO,
and while I obviously have no idea what your boss wants in specific,
it shouldn't be too bad.

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


Re: Database help needed

2009-05-04 Thread Emile van Sebille

On 5/4/2009 4:30 PM Amber said...


My PHB is insane.

Today he drops 50,000 databases in MS Access format on my desk, and 
tells me that by Friday I need to:

* Remove all of the "junk content" in the record fields;
* Remove all records with blank fields in them;
* Correct all fields in which the markup is "wrong";
* Correct all fields in which the data is "wrong";
* Ensure that all database include some specific tables;
** Add appropriate content to the records in the "new" tables;

And finally, said databases are to be in:

* MS Access 97 format;
* MS Access 2000 format;
* MS Access 2003 format;
** Is there any documentation anywhere on what the differences between 
those is?   Won't a database created for Access 97 be openable in MS 
Access 2003?

* SQLite format;
* MySQL format;
* PDB format, for use on his PalmPilot;
* Commas separated values;
* dBase 3;
* Excell spreadsheets;
* ODF spreadsheets;



It wouldn't surprise me that you couldn't do all this with open office 
using command line options which is where I'd start.  There's also 
python modules available, but I haven't yet gotten into them.  I found 
most of what I needed on groups.google.com though, so not having 
internet access could be trouble -- some of the conversion structures 
and requirements weren't quite so obvious nor documentation easily 
available.


Emile

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


Re: Self function

2009-05-04 Thread Carl Banks
On May 4, 4:06 pm, bearophileh...@lycos.com 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.


> >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.


> 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.

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.

Singly-linked lists don't count because you don't need recursion for
them.


[snip strawman example]
> > 2. You should be using a Python list anyway.
>
> I should use D when I have to use such algorithms, I know.

That's another idea.


Carl Banks

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


Database help needed

2009-05-04 Thread Amber
My PHB is insane.

Today he drops 50,000 databases in MS Access format on my desk, and tells me
that by Friday I need to:
* Remove all of the "junk content" in the record fields;
* Remove all records with blank fields in them;
* Correct all fields in which the markup is "wrong";
* Correct all fields in which the data is "wrong";
* Ensure that all database include some specific tables;
** Add appropriate content to the records in the "new" tables;

And finally, said databases are to be in:

* MS Access 97 format;
* MS Access 2000 format;
* MS Access 2003 format;
** Is there any documentation anywhere on what the differences between those
is?   Won't a database created for Access 97 be openable in MS Access 2003?
* SQLite format;
* MySQL format;
* PDB format, for use on his PalmPilot;
* Commas separated values;
* dBase 3;
* Excell spreadsheets;
* ODF spreadsheets;

I'm a programming novice, but I think that I can write a script that reads
the MSAccess databases, and cleans up the content in the individual fields
of the database.
What I need is:
* A pointer to good. current, downloadable documentation on creating, and
editing databases using Python;
** Good current books on python and databases will also be useful;
* Pointers to material that describe how to create MS Access databases using
Python, on Linux;
* Pointers to material that describe how to create, and edit SQL CE 2.0
databases in Python, on Linux.  I'm assuming that this is possible, but
since that database engine is available for Windows Mobile only --- at least
according to the Google search I did --- I have some doubts;

I need stuff I can download.   I'll be burning it to a DVD, and taking that
to work.   No internet access at work.  The PHB considers that to be a time
waster, and an expensive luxury that can not be justified in the current
economic climate.

Amber
-- 
Wind under Thy Wings
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-04 Thread bearophileHUGS
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.


>All recursion does it make what you're doing a lot less readable for almost 
>all programmers.<

I can't agree. If the data structure is recursive (like a tree, or
even sometimes graphs, etc) a recursive algorithm is shorter, more
readable and more natural.

An example, a postorder recursive visit:

def postorder_scan(root):
if root is not None:
if root.left is not None:
for n in postorder_scan(root.left):
yield n
if root.right is not None:
for n in postorder_scan(root.right):
yield n
yield root

Try to write that in an iterative way, not adding any new field to the
nodes, and you will see.
And even if you add a "visited" new boolean field to nodes, the
resulting code isn't as nice as the recursive one yet.


> 2. You should be using a Python list anyway.

I should use D when I have to use such algorithms, I know.

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


Re: IDE for python 2.6 (auto complete)

2009-05-04 Thread Ben Finney
Soumen banerjee  writes:

> Is there any IDE with support for autocomplete in python 2.6 with all
> the newer functions included?

Emacs, with the right library, is an excellent Python IDE with
auto-completion and many other features
http://tellarite.net/2008/05/09/emacs-as-a-powerful-python-ide/>.

-- 
 \   “People are very open-minded about new things, as long as |
  `\ they're exactly like the old ones.” —Charles F. Kettering |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-04 Thread Carl Banks
On May 4, 1:25 pm, bearophileh...@lycos.com wrote:
> Aahz:
>
> > When have you ever had a binary tree a thousand levels deep?
>
> Yesterday.
>
> >Consider how big 2**1000 is...<
>
> 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.

1. Singly-linked lists can and should be handled with iteration.  All
recursion does it make what you're doing a lot less readable for
almost all programmers.

2. You should be using a Python list anyway.


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


Re: if statement, with function inside it: if (t = Test()) == True:

2009-05-04 Thread Scott David Daniels

MRAB wrote:

If you're not limited to ASCII then there's '←' (U+2190, 'LEFTWARDS
ARROW'). It's a little too late now, though.

Well, if you are old enough, that was the ASCII graphic for the
character now printed as '_' (ASCII), and SAIL used it for assignment
statements, causing much consternation when our source code displayed
funny on new-fangled terminals.  So, just an unfortunate setting on
the time machine is the basic flaw.

--Scott David Daniels
@Acm.Org
--
http://mail.python.org/mailman/listinfo/python-list


Re: if statement, with function inside it: if (t = Test()) == True:

2009-05-04 Thread Terry Reedy

Antoon Pardon wrote:

On 2009-04-24, Steven D'Aprano  wrote:

On Fri, 24 Apr 2009 03:00:26 -0700, GC-Martijn wrote:


Hello,

I'm trying to do a if statement with a function inside it. I want to use
that variable inside that if loop , without defining it.

def Test():
return 'Vla'

I searching something like this:

if (t = Test()) == 'Vla':
print t # Vla

or

if (t = Test()):
print t # Vla
Fortunately, there is no way of doing that with Python. 


There is a way to do something close.

def x(v):
x.val = v
return v

if x(3)==3:
print('x.val is ', x.val)
# prints
x.val is  3

In OP's case, condition is "x(Test()) == 'Vla'"


This is one  source of hard-to-debug bugs that Python doesn't have.


I think this is an unfortunate consequence of choosing '=' for the
assignment.


Actually, is is a consequence of making assignment a statement rather 
than an expression.  And that is because if assignment were an 
expression, the new name would have to be quoted.  Or there would have 
to be a special exception to the normal expression evaulation rule.  In 
other words, the problems one sees in a pure expression language.  Note 
that C, for instance, which has such a special exception, does not, last 
I knew, allow a,b = 1,2.


The solution for this use case is to encapsulate the binding within a 
function.  The above is one possible example.  One could use a pocket 
class instead of a pocket function.  Or


def set_echo(name, val):
  globals()[name] = val
  return val

if set_echo('t', Test()) == 'Vla': print t ...

Terry Jan Reedy


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


Re: exit a program gracefully

2009-05-04 Thread Gabriel Genellina

En Mon, 04 May 2009 19:14:53 -0300, Chris Rebert escribió:

On Mon, May 4, 2009 at 3:02 PM,   wrote:



In a python program I ask if the user wants to continue.  If they answer
'no', what options do I have to halt execution?  I can put the rest of  
the
code inside an "if bContinue:" block, but that seems awkward.  I have  
looked
at raising an exception, and perhaps this is the preferred method, but  
it

seems daunting to my non-OOP eyes.  Thanks -- Rob


There's the C-like:
from sys import exit
exit(return_code)

Or if you prefer exceptions, the standard way is:
raise SystemExit


I prefer to put the code inside a function, and just `return` earlier.
Having a sys.exit() in the middle of a function means that it's not  
reusable; I usually have a single exit() at the end.



def do_work():
  do some work
  ask the user
  if not continue:
return 0
  do more work
  return 0

if __name__=='__main__':
  try: sts = do_work()
  except: sts = 1, log exception
  sys.exit(sts)

--
Gabriel Genellina

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


Re: Self function

2009-05-04 Thread Scott David Daniels

Arnaud Delobelle wrote:

In that case the following would not grow the stack, given tail-call
optimization:

def visit(node):
print 'visiting', node
if node.right is None:
return visit(node.left)
if node.left is not None:
visit(node.left)
return visit(node.right)


Or (without TCO):
def visit(node):
while node is not None:
print 'visiting', node
if node.right is None:
node = node.left
else:
if node.left is not None:
visit(node.left)
node = node.right

Not so hard, really.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] regobj - Pythonic object-based access to the Windows Registry

2009-05-04 Thread Ryan Kelly

> >   I've just released the results of a nice Sunday's coding, inspired by
> > one too many turns at futzing around with the _winreg module.  The
> > "regobj" module brings a convenient and clean object-based API for
> > accessing the Windows Registry.
>
> Sounds very interesting, Ryan.  Just a couple questions about the 
> dictionary interface.

Thanks for you interest and suggestions, a couple of quick points below.

> I could see how you could map  numbers to DWORD, 2.x str/3.x bytes to 
> binary, and 2.x unicode/3.x str to REG_SZ.  But you don't document such 
> a translation, so it is unclear exactly what you actually do.  This 
> would be somewhat weird in 2.x, though, where str commonly would want to 
> map to String rather than Binary.
> 
> It seems almost necessary to add an explanation of whatever mapping is 
> presently done, to have complete documentation.

I guess I just ran out of steam on the documentation front :-)

Currently it maps integers to DWORD and anything else to REG_SZ.  The
idea of having a distinct Value class is to allow a more nuanced mapping
to be developed, but I haven't got down to the details of that yet - my
current application only requires REG_SZ.

> Thinking more, I wonder if it is possible to create objects of type 
> Value to put in the dictionary to allow specification of multistring and 
> expandablestring Registry types, but then the dictionary name would have 
> to be redundant with the name attribute in the Value object.  Maybe a 
> nameless value type could be invented, with just type and data attributes?

It certainly is, using syntax like:

  HKCU.foo.bar["key"] = Value("%SYSTEMROOT%/mydir",type=REG_EXPAND_SZ)}

Putting a nameless Value() instance in the initialisation dictionary
should also work (but as you note, there's no documentation or tests for
this yet...)


  Cheers,

 Ryan



-- 
Ryan Kelly
http://www.rfk.id.au  |  This message is digitally signed. Please visit
r...@rfk.id.au|  http://www.rfk.id.au/ramblings/gpg/ for details



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


Re: Most Basic Question Ever - please help

2009-05-04 Thread seanm . py
On May 3, 12:22 am, CM  wrote:
> On May 2, 4:36 pm, seanm...@gmail.com wrote:
>
>
>
> > I am going to try posting here again with more detail to see if I can
> > finally get my first program to work.
>
> > I am working on a MacBook Pro with OS X 10.4.11. I opened a new window
> > in IDLE to create a file. The file had only one line of code and was
> > saved as module1.py. I saved it to Macintosh HD. The one line of code
> > in the file is copied below:
>
> > print 'Hello module world!'
>
> > I closed the file and tried to run it in IDLE and Terminal, but I have
> > had no success. I'll paste my commands and the error messages below
> > (for IDLE, then Terminal). Any help would be very much appreciated. I
> > feel like the marathon just started and I've fallen flat on my face.
> > Thanks.
>
> > IDLE 2.6.2>>> python module1.py
>
> > SyntaxError: invalid syntax
>
> > sean-m-computer:~ seanm$ python
> > Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39)
> > [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
> > Type "help", "copyright", "credits" or "license" for more information.>>> 
> > python module1.py
>
> >   File "", line 1
> >     python module1.py
> >                  ^
> > SyntaxError: invalid syntax
>
> Sean, also, keep in mind you can use IDLE to run
> your scripts.  After you have saved a script/program,
> there is an option for Run in the menu, and then under
> that, Run Module.  The output of the script will be
> sent to IDLE window indicated as the Python shell.
> You can also just test code directly from within
> that shell, though for multi-line programs, it is
> easier within the composing window.
>
> I suggest you sign up for the Python tutor 
> list:http://mail.python.org/mailman/listinfo/tutor
>
> And you can search through their big archive of
> questions and answers here:http://www.nabble.com/Python---tutor-f2981.html
>
> The tutors there are great and super-helpful, and
> will field any level of question but are particularly
> good for absolute beginners.
>
> Here is a tutorial on using 
> IDLE:http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html
>
> And here is a very good general programming tutorial online
> book, focusing on Python:http://www.freenetpages.co.uk/hp/alan.gauld/
>
> Good luck!
> Che

Thanks Che! The explaination and links are much appreciated. -Sean
--
http://mail.python.org/mailman/listinfo/python-list


Re: exit a program gracefully

2009-05-04 Thread MRAB

robert.t.ly...@seagate.com wrote:


In a python program I ask if the user wants to continue.  If they answer 
'no', what options do I have to halt execution?  I can put the rest of 
the code inside an "if bContinue:" block, but that seems awkward.  I 
have looked at raising an exception, and perhaps this is the preferred 
method, but it seems daunting to my non-OOP eyes.  Thanks -- Rob



What is the overall structure of the program? What happens if the user
wants to continue? If you're in a loop then you can just use 'break' to
leave the loop.
--
http://mail.python.org/mailman/listinfo/python-list


Re: AutoComplete in C++ Editor for Python

2009-05-04 Thread Scott David Daniels

flam...@gmail.com wrote:

... Using this code, I can get information like the name of the symbol
(x), but I can't figure out how to get the type. If I knew how to get
this it would solve 99% of my problems :)


If Python were statically typed, you might be correct.
A _value_ in python has a type, not a variable.  so, you can do:
   some_list = []
   for a in None, True, 1, 1.0, 3.1j, 'text', u'text':
   some_list.append(a)
   print some_list
and you will see something like:
[None, True, 1, 1.0, 3.1001j, 'text', u'text']
That is, a has the type of its current value.
any kind of object can be stored in any variable.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: if statement, with function inside it: if (t = Test()) == True:

2009-05-04 Thread MRAB

Rhodri James wrote:
On Mon, 04 May 2009 15:25:44 +0100, Antoon Pardon 
 wrote:


On 2009-04-24, Steven D'Aprano  
wrote:

On Fri, 24 Apr 2009 03:00:26 -0700, GC-Martijn wrote:


Hello,

I'm trying to do a if statement with a function inside it. I want to 
use

that variable inside that if loop , without defining it.

def Test():
return 'Vla'

I searching something like this:

if (t = Test()) == 'Vla':
print t # Vla

or

if (t = Test()):
print t # Vla


Fortunately, there is no way of doing that with Python. This is one
source of hard-to-debug bugs that Python doesn't have.


I think this is an unfortunate consequence of choosing '=' for the
assignment. They could have chosen an other token to indicate an
assignment one that would have made the difference between an
assignment and a comparison more visually different and thus
bugs by using one while needing the other less hard to track
down.


What token could be used and still be meaningful, though?  Algol
used ":=", which has most of the same problems as "=" (more, in my
opinion, since it fools the eye more easily if you're scanning
printed code quickly).  Easily constructed arrows like "<=" or
"<-" collide with different comparators.  About all that's left
that even vaguely implies assignment is "~", and it's no better.


If you're not limited to ASCII then there's '←' (U+2190, 'LEFTWARDS
ARROW'). It's a little too late now, though.
--
http://mail.python.org/mailman/listinfo/python-list


Re: exit a program gracefully

2009-05-04 Thread Chris Rebert
On Mon, May 4, 2009 at 3:02 PM,   wrote:
>
> In a python program I ask if the user wants to continue.  If they answer
> 'no', what options do I have to halt execution?  I can put the rest of the
> code inside an "if bContinue:" block, but that seems awkward.  I have looked
> at raising an exception, and perhaps this is the preferred method, but it
> seems daunting to my non-OOP eyes.  Thanks -- Rob

There's the C-like:
from sys import exit
exit(return_code)

Or if you prefer exceptions, the standard way is:
raise SystemExit

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


exit a program gracefully

2009-05-04 Thread Robert . T . Lynch
In a python program I ask if the user wants to continue.  If they answer 
'no', what options do I have to halt execution?  I can put the rest of the 
code inside an "if bContinue:" block, but that seems awkward.  I have 
looked at raising an exception, and perhaps this is the preferred method, 
but it seems daunting to my non-OOP eyes.  Thanks -- Rob--
http://mail.python.org/mailman/listinfo/python-list


Re: find sublist inside list

2009-05-04 Thread Terry Reedy

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]).


If I do this with string ('acaccgac') I have the advantage of all the 
'find' functions, but perfomance is bad and some extra care must be 
taken if one element consist of more then one character (case of 11 for 
example)


So I really would like to work with lists straightforward, but I could 
not found anything to search a sublist inside a list.

Any propositions for a simple solution?


For a mutable homogenous array, consider the array module.
Any algorithm that applies to a sequence of chars can be adjusted to 
other sequences.  For the above case, remember than you can easily 
filter None out of a sequence.  IE, replace 'a','c' with 6, None and 
then filter when done.


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


Re: Self function

2009-05-04 Thread Terry Reedy

bearophileh...@lycos.com 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. [An possible objection to 
doing this is that the code might no longer be valid if used to make 
another function object, but I think this is so rare at to hardly worry 
about.] Your initial post seemed to be about a hackish work around that 
looked to me to make as much trouble as it saves.  So I did not respond.


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


Re: find sublist inside list

2009-05-04 Thread Gabriel Genellina

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

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


Re: if statement, with function inside it: if (t = Test()) == True:

2009-05-04 Thread Rhodri James
On Mon, 04 May 2009 15:25:44 +0100, Antoon Pardon  
 wrote:


On 2009-04-24, Steven D'Aprano   
wrote:

On Fri, 24 Apr 2009 03:00:26 -0700, GC-Martijn wrote:


Hello,

I'm trying to do a if statement with a function inside it. I want to  
use

that variable inside that if loop , without defining it.

def Test():
return 'Vla'

I searching something like this:

if (t = Test()) == 'Vla':
print t # Vla

or

if (t = Test()):
print t # Vla


Fortunately, there is no way of doing that with Python. This is one
source of hard-to-debug bugs that Python doesn't have.


I think this is an unfortunate consequence of choosing '=' for the
assignment. They could have chosen an other token to indicate an
assignment one that would have made the difference between an
assignment and a comparison more visually different and thus
bugs by using one while needing the other less hard to track
down.


What token could be used and still be meaningful, though?  Algol
used ":=", which has most of the same problems as "=" (more, in my
opinion, since it fools the eye more easily if you're scanning
printed code quickly).  Easily constructed arrows like "<=" or
"<-" collide with different comparators.  About all that's left
that even vaguely implies assignment is "~", and it's no better.

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-04 Thread Arnaud Delobelle
bearophileh...@lycos.com writes:

> Aahz:
>> When have you ever had a binary tree a thousand levels deep?
>
> Yesterday.
>
>
>>Consider how big 2**1000 is...<
>
> 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.

In that case the following would not grow the stack, given tail-call
optimization:

def visit(node):
print 'visiting', node
if node.right is None:
return visit(node.left)
if node.left is not None:
visit(node.left)
return visit(node.right)

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


Re: SYSTEM and USER environment (was Your confirmation is required to join the Python-list mailing list)

2009-05-04 Thread Dave Angel

Allan Yuan wrote:

Hi,
I just wanna know how to set SYSTEM variables and USER variables of windows,
but got no way.

Firstly I thought "os.environ + os.system" may work well, but found no way
to let "os.environ" run to retrive USER variables.

Then I tried win32api, finding the GetEnvironmentVariables() mixing SYSTEM
and USER variables up, and SetEnvironmentVariables() failing to add
variables.

Could you help me, please?
Thanks a lot.

  
First, you need to put a meaningful subject line on a query to the 
list.  Hopefully you also did the confirmation, so that you'll actually 
be getting the list emails.


Next, your problem.  SYSTEM and USER variables are a uniquely Windows 
concept, and as far as I know, have no direct counterpart in Python.  
These are really just names used in the Control Panel applet to refer to 
two sections of the registry which are used to define which environment 
variables a task will start with, if the task is started directly from 
Explorer.  Tasks that are started by other tasks (eg. the command line) 
get environment variables as defined by the parent.


So, there are at least three obvious ways a process gets started.  One 
is by explorer, in which case it gets the environment described above.  
Two is by a DOS box, in which case it gets the environment variables 
according to the rules of the CMD shell.  And third is from an arbitrary 
3rd party process, in which case it's up to that developer.


So, which are you trying to change?  I'm suspecting you're interested in 
the Explorer version, for example that launches a program from a 
shortcut on the desktop, or via an association with a particular file 
extension.  i don't know which registry variables are involved, but 
there are two registry keys,
Try:hklm/SYSTEm/CurrentControlSet/Control/Session 
Manager/Environmentfor the SYSTEM environment variables

  and hkcu/Environment for the USER environment variables

Experiment first with REGEDIT, then when you get the behavior you want,  
look up module _winreg  (or winreg in Python 3.0) to do it 
programmatically.  Notice that existing DOS boxes won't see these new 
variables, only things launched by Explorer or the equivalent.


It's also possible you just want to set environment variables for a 
particular DOS box session.  In that case, use a .BAT or .CMD file, in 
which a SET statement tells the shell what values to use next time it 
launches.



--
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-04 Thread Piet van Oostrum
> 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.

There is a discussion about this in the thread `Threaded alternatives to
smtplib?' 
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-04 Thread Chris Rebert
On Mon, May 4, 2009 at 1:25 PM,   wrote:
> Aahz:
>> When have you ever had a binary tree a thousand levels deep?
>
> Yesterday.
>
>
>>Consider how big 2**1000 is...<
>
> 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.

And who in their right mind would not use a *self-balancing* binary
tree in that situation?

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


Re: change some lines from a read file

2009-05-04 Thread norseman

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

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



===

Assuming the total number of changes is not large,

put OPTION1 where you want it to go in the text
put OPTION2  (same)

import sys

if len(sys.argv) >1:
  OPTION1 = sys.argv[1]
else:
  OPTION1 = "some default stuff"

similar for OPTION2
if len(sys.argv) >2:
  like above
and any others

print section1+OPTION1+section2+OPTION2

   or
  just using the line count  (in place of "print sect..")
line_number= 0
for i in template:
  if line_number matches line number to place Opt1
print OPTION1
  elif line_number matches v2
print OPTION2
and so forth
  else:
print i   (line from template NOT being changed)
  line_number += Line_number

you can group line number and replacement on command line
runprogram (43,"use this instead") (56,
and parse inside program before opening template

one thing to watch out for:
   for i in file...  often returns just one character at a time, 
meaning you will have to track EOL's yourself  OR
import the readline and use it to stand a better chance of getting what 
you expect from a read file function.



Today: 20090504
Logic outline, No particular version

HTH

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


Re: change some lines from a read file

2009-05-04 Thread norseman

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

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



===

Assuming the total number of changes is not large,

put OPTION1 where you want it to go in the text
put OPTION2  (same)

import sys

if len(sys.argv) >1:
  OPTION1 = sys.argv[1]
else:
  OPTION1 = "some default stuff"

similar for OPTION2
if len(sys.argv) >2:
  like above
and any others

print section1+OPTION1+section2+OPTION2

   or
  just using the line count  (in place of "print sect..")
line_number= 0
for i in template:
  if line_number matches line number to place Opt1
print OPTION1
  elif line_number matches v2
print OPTION2
and so forth
  else:
print i   (line from template NOT being changed)
  line_number += Line_number

you can group line number and replacement on command line
runprogram (43,"use this instead") (56,
and parse inside program before opening template

one thing to watch out for:
   for i in file...  often returns just one character at a time, 
meaning you will have to track EOL's yourself  OR
import the readline and use it to stand a better chance of getting what 
you expect from a read file function.



Today: 20090504
Logic outline, No particular version

HTH

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


Re: Threaded alternatives to smtplib?

2009-05-04 Thread Piet van Oostrum
> Alex Jurkiewicz  (AJ) wrote:

>AJ> def threadProcessRecipient():
[snip]
>AJ> if __name__ == '__main__':
>AJ>THREADS = []
>AJ>for i in range(CONCURRENCY):
>AJ>THREADS.append(threading.Thread(target=threadProcessRecipient))
>AJ>for thread in THREADS:
>AJ>thread.run()

You should use thread.start(), not thread.run(). When you use run(), it
will be sequential execution, as you experience. With start() you get
concurrency
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to walk up parent directories?

2009-05-04 Thread Dave Angel



Matthew Wilson wrote:

On Sun 03 May 2009 09:24:59 PM EDT, Ben Finney wrote:
  

Not every simple function belongs in the standard library :-)



Thanks for the help with this!  Maybe I'm overestimating how often
people need this walkup function.

Matt

  

Look at os.path.normpath(os.path.join( name, ".."))


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


Re: IDE for python 2.6 (auto complete)

2009-05-04 Thread Dave Angel

Soumen banerjee wrote:

Hello,
I have just installed and run python 2.6.2 from the sources available
on the website. I notice that SPE (the editor which i used with python
2.5) is not displaying some of the functions new in 2.6 as
autocomplete options. Is there any IDE with support for autocomplete
in python 2.6 with all the newer functions included?

  

No idea if it's "all", but Komodo 5.1.1 has been updated for 2.6.


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


Re: AutoComplete in C++ Editor for Python

2009-05-04 Thread Dave Angel

flam...@gmail.com wrote:

On May 3, 3:14 pm, Dave Angel  wrote:
  

flam...@gmail.com wrote:


Hello,
I am embedding python support in my C++ application and was looking at
adding "Intellisense" or "AutoComplete" support.
  
I found a way to do it using the "dir" function, but this creates a

problem. Here's why. Let's say I have the following code in my editor:
  
import sys

x =ys
  
Now, I would like to get all attributes of the object called 'x'. I

can "instrument" the code and add "print dir(x)" at the end,
temporarily redirect the python output to a string and execute the
code.
  
But this is not safe: I do NOT want to execute the code while the user

is typing!
  
Is there a way to "compile" the python code and get access to the

symbol table from that compiled block?
  
Did anybody ever implement AutoComplete in a editor for Python?
  
cheers.
  

Several editors for Python support auto-complete, to one extent or
another.  The only one I have experience with is Komodo.  Komodo runs in
a separate process, so it doesn't suffer from the problems of having two
gui event-loops in the same process, and other similar problems.   It
also won't be executing code that might have side effects in the child
process.

The downside is that in order to do auto-complete, it has to figure it
out from other clues.  From the docs, and from reading, and from
experiementing, I believe that it uses two approaches.  One approach is
a set of language files which try to describe all the symbols in the
standard language and library.  They have one for each release (2.4,
2.5, ...)  Theoretically, you could add your own for other libraries.  
Second approach is to parse the code that's visible to it.  That parsing

is well done, and surprisingly quick, but there are lots of tricks a
developer might use that can fool it.  For example, wxPython lets you
import just one symbol, and lots more appear magically.  It's no big
deal, they have code structured one way, but the interface is very
different.  Catch is that code completion frequently gets fooled by these.

I'd point out that if you do walk the dictionaries at run time, you'll
get different results when you do it with nothing running than if you do
a strictly static analysis.  So some things might only show up if you've
stepped into the function with the magic going on.

Simplest example I can come up with of something a static analysis won't
spot:   An instance objectobj   may have some number of attributes
assigned the the __init__() method.  But it could also have new fields
added by anyone with a referent into it.

There is a Python parser in module ast.  Perhaps that'd be some help.  
I've not used it, so can't give you any specifics.


DaveA




I think it might be possible for me to figure out how to do
AutoCompletion using the symtable object. But I am having difficulty
making sense of it.

In my tests, I was use the following Python code:

[code]
import sys
x=s
[/code]

The idea is to get the type of the variable x

To attempt this, I use the following C code (my editor is written in
C)

symtable* st =y_SymtableString ( "import sys
\nx=s,"",Py_single_input);

PyObject *name, *value;
Py_ssize_t pos =;
while (PyDict_Next(st->st_symbols, &pos, &name, &value))
{
...
}



Using this code, I can get information like the name of the symbol
(x), but I can't figure out how to get the type. If I knew how to get
this it would solve 99% of my problems :)

Any ideas?

  
There's a type() function as a builtin.  It returns a string showing the 
type of any object you pass it.


I have my doubts about the 99%;   I'd say more like 1%.  Objects have to 
be instantiated to have a type, there's no declarations.  And a function 
has a type, but in order to see the result type through introspection, 
you'd have to run it.  And before you could do that, you'd have to guess 
its parameter types.  And hope it didn't have any serious side effects.


I can't help with the C++ code, since I've never written any that use 
the Python runtime, but perhaps you can experiment with a Python 
version, till you see what is and is-not possible.  Look at the 
following in Python:

import sys

dict = sys.__dict__
for sym in dict:
   print "**", sym, type(dict[sym]), str(dict[sym])


Now, for many of these sym values, sym.__dict__  could similarly be 
analyzed.  So you might write a recursive generator that gave you a list 
of symbols.



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


Re: Code works fine except...

2009-05-04 Thread Ross
On May 4, 12:15 pm, a...@pythoncraft.com (Aahz) wrote:
> In article <8d4ec1df-dddb-469a-99a1-695152db7...@n4g2000vba.googlegroups.com>,
>
> Ross   wrote:
>
> >def test_round_robin(players, rounds, courts, doubles = False):
> >    players = range(players)
> >    for week in round_robin(players,rounds,courts):
> >        if doubles == True:
> >                doubles_week = len(week)/2.0
> >                byes = doubles_week - courts
>
> Side note: thou shalt indent four spaces, no more, no fewer
>
> For more info, see PEP 8.
> --
> Aahz (a...@pythoncraft.com)           <*>        http://www.pythoncraft.com/
>
> "It is easier to optimize correct code than to correct optimized code."
> --Bill Harlan

Yes... I know this. Unfortunately, copy/pasting my code from the IDE
into the google group messes with indentations.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-04 Thread bearophileHUGS
Aahz:
> When have you ever had a binary tree a thousand levels deep?

Yesterday.


>Consider how big 2**1000 is...<

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.

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


Re: Self function

2009-05-04 Thread Tim Wintle
On Mon, 2009-05-04 at 19:51 +0100, Arnaud Delobelle wrote:
> 
> Bearophile, there is a thread on python-ideas about tail-call
> optimization at the moment.

Oooh - haven't noticed that (and don't have time to follow it), but has
anyone seen the results I got a week or so ago from briefly playing with
a couple of simple optimisations:



I was amazed how much you could improve performance by not jumping all
over the stack




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


Re: yet another list comprehension question

2009-05-04 Thread namekuseijin
On May 4, 9:15 am, David Robinow  wrote:
> On Mon, May 4, 2009 at 2:33 AM, namekuseijin
>
>  wrote:
>  ls = [(1,2), (3,4), (5, None), (6,7), (8, None)]
>  [(x,y) for (x,y) in ls if y]
> > [(1, 2), (3, 4), (6, 7)]
>
> Nope. That filters out 0 as well as None. Not what the OP asked for.

True.  I'm still a C programmer at heart I guess.  ah, the flexibility
of 0... ;)
--
http://mail.python.org/mailman/listinfo/python-list


Re: change some lines from a read file

2009-05-04 Thread Anthra Norell

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

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


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

2009-05-04 Thread Arnaud Delobelle
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/

-- 
Arnaud

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


Re: Self function

2009-05-04 Thread Aahz
In article ,
  wrote:
>Arnaud Delobelle:
>> 
>> Bearophile, there is a thread on python-ideas about tail-call
>> optimization at the moment.
>
>Someday I'll have to start following those mailing lists...
>But I am not interested in such optimization. It's not going to help
>me significantly. Most times I use recursion, I think it can't be
>optimized away by simple means (think about a visit to a binary tree).

When have you ever had a binary tree a thousand levels deep?  Consider
how big 2**1000 is...
-- 
Aahz (a...@pythoncraft.com)   <*> 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


Re: Self function

2009-05-04 Thread bearophileHUGS
Arnaud Delobelle:
> def fac(n):
>     def rec(n, acc):
>         if n <= 1:
>             return acc
>         else:
>             return rec(n - 1, n*acc)
>     return rec(n, 1)

Right, that's another way to partially solve the problem I was talking
about. (Unfortunately the performance in Python is significantly
lower. I can use that in D).


> Bearophile, there is a thread on python-ideas about tail-call
> optimization at the moment.

Someday I'll have to start following those mailing lists...
But I am not interested in such optimization. It's not going to help
me significantly. Most times I use recursion, I think it can't be
optimized away by simple means (think about a visit to a binary tree).

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


Re: change some lines from a read file

2009-05-04 Thread MRAB

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.


You could put special markers around the optional parts in the template
file. Your script would remove the markers from around the optional
parts it wants to keep and then remove any remaining unwanted optional
parts and their markers.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-04 Thread Arnaud Delobelle
bearophileh...@lycos.com writes:

> Steve Howell:
>>two methods with almost identical names, where one function is the
>>public interface and then another method that does most of the
>>recursion.<
>
> Thanks Guido & Walter both Python and D support nested functions, so
> in such situations I put the recursive function inside the "public
> interface" function/method.

Yes, this is a common idiom for me:

def public_function(a, b):
def rec():
...
return rec()

E.g, to continue with the factorial toy example (of course for this
particular example and in this particular language, a loop would be more
appropriate):

def fac(n):
def rec(n, acc):
if n <= 1:
return acc
else:
return rec(n - 1, n*acc)
return rec(n, 1)

This is tail recursive, but Python does not optimise tail-calls so there
is not much point.

> Recursion is a high-level way to represent certain kinds of algorithms
> in a short and readable way (when data structures are nested, the most
> natural algorithms that work on them are recursive). But in Python
> function calls are slow, the maximum level of nested calls is limited
> (and it can't grow too much), so this has sometimes forced me to
> manually convert recursive functions into iterative ones with a stack.
> This is silly for a supposed high-level language. The bad support for
> recursivity is one of the few faults of Python.

Bearophile, there is a thread on python-ideas about tail-call
optimization at the moment.

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


Re: improved search algorithm

2009-05-04 Thread MRAB

grahamdic...@gmail.com wrote:

Hi

I have an excel file that is read into python (8000 rows)

from csvimport reader, writer
incsv = reader(open(MY_FILE), dialect='excel')
keys = incsv.next()

There are mixed datatypes.

the last column contains a cumulative frequency running in order
0. to 1. for the 8000 rows

for a loop of 100,000 times I want to take a new random number each
time and find the row with the next biggest cumulative frequency value

Here's my current (pseudo)code:

for 1 to 10

myRand = random.random()
for line in incsv:
if float(line[-1]) > myRand:
resline = []
for item in line:
try:
i = int(item)
except ValueError:
try:
i = float(item)
except ValueError:
i = item
resline.append(i)
#Here we construct a dict of pair values:
#{'ID':18,...
res = dict(zip(keys,resline))
break
else:
continue

  #do some stuff with res




I'm scanning over each line of the csv and deciding which row to
select (100k times) this is just not very efficient

How can i improve this code.
for line in incsv:
if float(line[-1]) > random.random():

I can use numpy etc. whatever


Here's a suggestion:

Construct the dicts for all the rows, stored in a list.

Construct a list of just the cumulative frequencies.

For each random value, use the bisect module to search for the value in
the cumulative frequencies list. This will return an index which you can
then use on your list of dicts.
--
http://mail.python.org/mailman/listinfo/python-list


change some lines from a read file

2009-05-04 Thread utab
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


pychecker vs pychecker2

2009-05-04 Thread qhfgva
For my edification I was looking through the source code of
pychecker.  I noticed that there was also a pychecker2 directory
(ubuntu).  The pychecker command line tool points to pychecker (w/out
the 2).  Does anyone know off the top of their head what this second
directory is about?

thanks

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


Re: Self function

2009-05-04 Thread bearophileHUGS
Steve Howell:
>two methods with almost identical names, where one function is the public 
>interface and then another method that does most of the recursion.<

Thanks Guido & Walter both Python and D support nested functions, so
in such situations I put the recursive function inside the "public
interface" function/method.

Recursion is a high-level way to represent certain kinds of algorithms
in a short and readable way (when data structures are nested, the most
natural algorithms that work on them are recursive). But in Python
function calls are slow, the maximum level of nested calls is limited
(and it can't grow too much), so this has sometimes forced me to
manually convert recursive functions into iterative ones with a stack.
This is silly for a supposed high-level language. The bad support for
recursivity is one of the few faults of Python.

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


improved search algorithm

2009-05-04 Thread grahamdick77
Hi

I have an excel file that is read into python (8000 rows)

from csvimport reader, writer
incsv = reader(open(MY_FILE), dialect='excel')
keys = incsv.next()

There are mixed datatypes.

the last column contains a cumulative frequency running in order
0. to 1. for the 8000 rows

for a loop of 100,000 times I want to take a new random number each
time and find the row with the next biggest cumulative frequency value

Here's my current (pseudo)code:

for 1 to 10

myRand = random.random()
for line in incsv:
if float(line[-1]) > myRand:
resline = []
for item in line:
try:
i = int(item)
except ValueError:
try:
i = float(item)
except ValueError:
i = item
resline.append(i)
#Here we construct a dict of pair values:
#{'ID':18,...
res = dict(zip(keys,resline))
break
else:
continue

  #do some stuff with res




I'm scanning over each line of the csv and deciding which row to
select (100k times) this is just not very efficient

How can i improve this code.
for line in incsv:
if float(line[-1]) > random.random():

I can use numpy etc. whatever
--
http://mail.python.org/mailman/listinfo/python-list


Re: find sublist inside list

2009-05-04 Thread mzdude
On May 4, 9:01 am, Matthias Gallé  wrote:
> bearophileh...@lycos.com wrote:
> > 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
>
> Thanks bearophile and John for your quick answers.
> Unfortunately, the int that can replace a sublist can be > 255, but
> John's answer looks simple and good enough for me. I will use it as a
> starting point.
>

substring isn't limited to 0..255
>>> substring = "\0x%d\0x%d" % (257,257)
>>> 'acaccgac'.replace("ac", substring)
'\x00x257\x00x257\x00x257\x00x257cg\x00x257\x00x257'
--
http://mail.python.org/mailman/listinfo/python-list


Personal recommendations for Python and Django on-boarding materials

2009-05-04 Thread Grant Rettke
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
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-05-04 Thread Florian Wollenschein

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 Lorch
http://www.listick.org

PS: Keep in mind that I'm quite a beginner in the field of python and qt...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is it better to use threads or fork in the following case

2009-05-04 Thread CTO
> Which brings us backs to the "20 questions"-part of my earlier post. It
> could be, but it could also be that processing takes seconds. Or it takes
> so long that even concurrency won't help. Who knows?

Probably the OP ;)

Geremy Condra

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


Re: find sublist inside list

2009-05-04 Thread John O'Hagan
On Mon, 4 May 2009, Francesco Guerrieri wrote:
> On Mon, May 4, 2009 at 3:01 PM, John O'Hagan  wrote:
> > On Mon, 4 May 2009, 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]).
> >
> > 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']
> >
> > HTH,
> >
> > John
>
> Beware that you are mutating the list you are iterating over. That could
> lead to some strange bugs (for instance if you replaced the deleted items
> with a longer sequence, the range(len(li)) would still go up to the
> original lenght).
> It is better to modify a new list instead. Eg you could append to a new
> list.
[...]

Quite right, while it happens to work in this particular example, as you and 
MRAB point out, it's generally dangerous (and in fact this one silently and 
uselessly iterates over the last couple of indexes which no longer exist); a 
new list could be created like this:

index=0
newli=[]
while indexhttp://mail.python.org/mailman/listinfo/python-list


Re: IDE for python 2.6 (auto complete)

2009-05-04 Thread Detlev Offenbach
Mike Driscoll wrote:

> On May 4, 10:13 am, Soumen banerjee  wrote:
>> Hello,
>> I have just installed and run python 2.6.2 from the sources available
>> on the website. I notice that SPE (the editor which i used with python
>> 2.5) is not displaying some of the functions new in 2.6 as
>> autocomplete options. Is there any IDE with support for autocomplete
>> in python 2.6 with all the newer functions included?
> 
> Wingware probably does. You should just submit a bug report to Stani
> though. He can probably fix SPE for you.

And eric4 does this as well.

Detlev
-- 
Detlev Offenbach
det...@die-offenbachs.de
--
http://mail.python.org/mailman/listinfo/python-list


Re: replacing numbers in LARGE MATRIX with criterium in 2 columns (a--> b)

2009-05-04 Thread Aahz
In article <68d22002-fc0a-4590-9395-c78b6ee41...@r34g2000vba.googlegroups.com>,
Alexzive   wrote:
>
>I have this matrix [20*4 - but it could be n*4 , with n~100,000] in
>file "EL_list" like this:

Take a look at NumPy
-- 
Aahz (a...@pythoncraft.com)   <*> 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


Re: [ANN] regobj - Pythonic object-based access to the Windows Registry

2009-05-04 Thread Glenn Linderman
On approximately 5/3/2009 7:35 AM, came the following characters from 
the keyboard of Ryan Kelly:

Hi All,

  I've just released the results of a nice Sunday's coding, inspired by
one too many turns at futzing around with the _winreg module.  The
"regobj" module brings a convenient and clean object-based API for
accessing the Windows Registry.



Sounds very interesting, Ryan.  Just a couple questions about the 
dictionary interface.




If a subkey is assigned a dictionary, the structure of that dictionary
is copied into the subkey.  Scalar values become key values, while
nested  dictionaries create subkeys:

  >>> HKCU.Software.MyTests = {"val1":7, "stuff":{"a":1,"c":2,"e":3}}
  >>> [v.name for v in HKCU.Software.MyTests.values()]
  ['val1']
  >>> [k.name for k in HKCU.Software.MyTests.subkeys()]
  ['stuff']
  >>> len(HKCU.Software.MyTests.stuff)
  3

Any other value assigned to a subkey will become the default value for
that key (i.e. the value with name ""):

  >>> HKCU.Software.MyTests = "dead parrot"
  >>> HKCU.Software.MyTests[""].data
  u'dead parrot'



I could see how you could map  numbers to DWORD, 2.x str/3.x bytes to 
binary, and 2.x unicode/3.x str to REG_SZ.  But you don't document such 
a translation, so it is unclear exactly what you actually do.  This 
would be somewhat weird in 2.x, though, where str commonly would want to 
map to String rather than Binary.


It seems almost necessary to add an explanation of whatever mapping is 
presently done, to have complete documentation.




Thinking more, I wonder if it is possible to create objects of type 
Value to put in the dictionary to allow specification of multistring and 
expandablestring Registry types, but then the dictionary name would have 
to be redundant with the name attribute in the Value object.  Maybe a 
nameless value type could be invented, with just type and data attributes?


Then the dictionary could be populated with numbers (mapped to DWORD) 
str or unicode items (mapped to String), [3.x only] bytes (mapped to 
Binary), or nameless value objects (which map to their internal types).




This would allow a bidirectional conversion between dictionaries and 
registry keys... when asking for the value of a key, one could return a 
dictionary of nameless value types... and allow iterations over that.


Subkeys could be a tuple with the type of key, and the value of a key 
object.



Well, these are just thoughts.  I don't know if they would increase or 
decrease the Pythonicity of your design, which certainly sounds better 
than using _winreg, to me.



--
Glenn -- http://nevcal.com/
===
A protocol is complete when there is nothing left to remove.
-- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking
--
http://mail.python.org/mailman/listinfo/python-list


How is the start of my server monitoring code?

2009-05-04 Thread Echo
I just started a project to monitor servers(load, memory, processes,
etc) via ssh(using paramiko). And I was hoping to get some input on
the design of my project, how pythonic it is, etc. It is quite basic
right now. But it is currently able to get load and memory stats from
any number of servers. I haven't started the logging to a DB or the
GUI for it yet. I also haven't touched on error handling at all
either.

My reasons for making my own server monitoring project:
-It's fun
-Low requirements (only python, paramiko, and pycrypto 1.9+ is required)
-Nothing to install on the servers
-Easy to customize

You can view the code at:
http://github.com/brandonsinger/pywatchlmn/blob/43afb593a891a3d25f3cd9910c5829867bbe229d/monitor.py
The project page is at: http://github.com/brandonsinger/pywatchlmn/tree/master

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


Re: find sublist inside list

2009-05-04 Thread Aahz
In article ,
=?ISO-8859-1?Q?Matthias_Gall=E9?=   wrote:
>
>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]).

What's your goal?  After you do this once, you cannot repeat the
operation with a different sublist because you are not tracking the
source of the numbers.  You might look into standard compression
algorithms for information about how to accomplish this.
-- 
Aahz (a...@pythoncraft.com)   <*> 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


Re: Code works fine except...

2009-05-04 Thread Aahz
In article <8d4ec1df-dddb-469a-99a1-695152db7...@n4g2000vba.googlegroups.com>,
Ross   wrote:
>
>def test_round_robin(players, rounds, courts, doubles = False):
>players = range(players)
>for week in round_robin(players,rounds,courts):
>   if doubles == True:
>   doubles_week = len(week)/2.0
>   byes = doubles_week - courts

Side note: thou shalt indent four spaces, no more, no fewer

For more info, see PEP 8.
-- 
Aahz (a...@pythoncraft.com)   <*> 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


Re: Your confirmation is required to join the Python-list mailing list

2009-05-04 Thread Allan Yuan
Hi,
I just wanna know how to set SYSTEM variables and USER variables of windows,
but got no way.

Firstly I thought "os.environ + os.system" may work well, but found no way
to let "os.environ" run to retrive USER variables.

Then I tried win32api, finding the GetEnvironmentVariables() mixing SYSTEM
and USER variables up, and SetEnvironmentVariables() failing to add
variables.

Could you help me, please?
Thanks a lot.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to walk up parent directories?

2009-05-04 Thread Matthew Wilson
On Sun 03 May 2009 09:24:59 PM EDT, Ben Finney wrote:
> Not every simple function belongs in the standard library :-)

Thanks for the help with this!  Maybe I'm overestimating how often
people need this walkup function.

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


Re: Code works fine except...

2009-05-04 Thread Ross
On May 3, 8:29 pm, John Machin  wrote:
> On May 4, 12:36 pm, Ross  wrote:
>
>
>
> > For the past couple weeks, I've been working on an algorithm to
> > schedule tennis leagues given court constraints and league
> > considerations (i.e. whether it's a singles or a doubles league). Here
> > were my requirements when I was designing this algorithm:
>
> > -Each player plays against a unique opponent each week.
> > -Similarly, in a doubles league, each player plays with a unique
> > partner each week.
> > -Each player gets a fair number of bye weeks (i.e. the player with the
> > most bye weeks will have no more than one bye week than the player
> > with the least number of bye weeks)
>
> > I'm very close to arriving at my desired solution, but I have one
> > glaring flaw. When I have an even number of players sign up for my
> > league and there are court constraints, my current algorithm gives the
> > first player in my league a bye week every single week. I'll post my
> > code below and see how you guys think I should add to/ amend my code.
>
> > def round_robin(players, rounds):
> >     if len(players)%2:
> >         players.insert(0, None)
> >     mid = len(players)//2
> >     for i in range(rounds):
> >         yield zip(players[:mid], players[mid:])
> >         players = players[0:1] + players[mid:mid+1] + players[1:mid-1] +
> > players[mid+1:] + players[mid-1:mid]
>
> > def test_round_robin(players, rounds, courts, doubles = False):
> >     players = range(players)
>
> DON'T change the type/contents/meaning of a variable name like that.
> E.g. use "nthings" for a number of things and "things" for a
> collection of things.
>
> >     for week in round_robin(players,rounds,courts):
>
> The round_robin() function has only TWO arguments. This code won't
> even run.
>
> When you document neither your data structures nor what your functions
> are intended to do, the last hope for somebody trying to make sense of
> your code is to give meaningful names to your variables. "week" and
> "doubles_week" are NOT meaningful.
>
> >             if doubles == True:
>
> Bletch. s/ == True//
>
> >                     doubles_week = len(week)/2.0
>
> I doubt very much that using floating point is a good idea here.
>
> >                     byes = doubles_week - courts
> >                     if byes == 0:
> >                             bye_list = []
> >                     else:
> >                             bye_list = 
> > week[::int(round(1.072*(courts/byes)+1.08))]
>
> The derivation of the constants 1.072 and 1.08 is  what?
>
> >                     playing = [u for u in week if u not in bye_list]
> >                     midd = len(playing)//2
> >                     doub_sched = zip(playing[:midd], playing[midd:])
> >                     print doub_sched, bye_list
> >             else:
> >                     byes = len(week)- courts
> >                     if byes == 0:
> >                             bye_list = []
> >                     else:
> >                             bye_list = 
> > week[::int(round(1.072*(courts/byes)+1.08))]
> >                     playing = [u for u in week if u not in bye_list]
> >                     print playing, bye_list

For everybody's enlightenment, I have gone through and commented my
code so you can better understand what I'm doing. Here it is:

def round_robin(players, rounds):
# if number of players odd, insert None at first position
if len(players)%2:
players.insert(0, None)
mid = len(players)//2
for i in range(rounds):
yield zip(players[:mid], players[mid:])
players = players[0:1] + players[mid:mid+1] + players[1:mid-1] +
players[mid+1:] + players[mid-1:mid]
""" rotates players like this: 1 2  ->  3 -> 4

 /|

   5 <- 6 <-7 <- 8 """

def test_round_robin(players, rounds, courts, doubles = False):
players = range(players)
for week in round_robin(players,rounds):
if doubles == True: #for doubles pairings
doubles_week = len(week)/2.0
byes = doubles_week - courts #number of tuples to be put 
into
bye_list
if byes == 0:
bye_list = []
else: """ following formula equally spaces out tuples 
selected
for bye_list and selects appropriate number according to length of the
league"""
bye_list = 
week[::int(round(1.072*(courts/byes)+1.08))]
playing = [u for u in week if u not in bye_list]
midd = len(playing)//2
doub_sched = zip(playing[:midd], playing[midd:])#matches the
remaining tuples into doubles matches
print doub_sched, bye_list
else:
byes = len(week)- courts
if byes == 0:
bye_list = []
else:
bye

Re: fcntl and siginfo_t in python

2009-05-04 Thread ma
Ok! So, I decided to write a C-extension instead of using ctypes. So
far, I create a module called dnotifier and the handler callback
receives two arguments, the signal number and the respective file
descriptor that was modified.

This works beautifully. Now, I want to release this to the public, so
I'm thinking of making a bit of code cleanup. Should I just pack the
entire siginfo_t struct, right now I just use the fd, into a
dictionary and pass it to the python callback handler function? Maybe
there might be some more suggestions to what data structures to use,
so I'm open right now to any of them.

The siginfo_t structure is defined as follows in C:

union sigval {
int sival_int;
void *sival_ptr;
};

typedef struct {
int si_signo;
int si_code;
union sigval si_value;
int si_errno;
pid_t si_pid;
uid_t si_uid;
void *si_addr;
int si_status;
int si_band;
} siginfo_t;

Thanks,
Mahmoud



On Fri, May 1, 2009 at 3:08 PM, ma  wrote:
>
> According to man signal,
> "The default action for an unhandled real-time signal is to terminate
> the receiving process."
>
> This means that my registered callback and sigaction does not work. I
> think the only solution would be to try this with a C-extension. Has
> anyone had any experience with this before?
>
> I attached my latest copy. Any insight is appreciated.
>
> On Thu, Apr 30, 2009 at 7:37 PM, ma  wrote:
> > I attached a clean copy of the .py file in case others couldn't read
> > it in their emails.
> > I'll try that and let you know how SIGRTMIN+1 goes!
> > What about this part?
> >
> > #sigemptyset(&act.sa_mask);
> > #python2.6 has byref(act, offset),how can i port this over?
> > #maybe addressof(act)+sizeof(sigaction.sa_mask)*(position_in_sigaction)
> > rc = __clib.sigemptyset(byref(act))
> >
> > Thanks!
> > Mahmoud
> >
> >
> >
> > On Thu, Apr 30, 2009 at 7:33 PM, Philip  wrote:
> >>
> >> ma  gmail.com> writes:
> >>
> >> >
> >> >
> >> >
> >> >
> >> > Here's something that I came up with so far, I'm having some issues with
> >> segfaulting, if I want to pass a struct member by ref in ctypes(see 
> >> below), if
> >> not, I just get a
> >> > "Real-time signal 0" sent back to me.
> >> >
> >> >
> >> > Any ideas?
> >>
> >> Try "SIGRTMIN+1", per http://souptonuts.sourceforge.net/code/dnotify.c.html
> >>
> >> Philip
> >>
> >>
> >>
> >> --
> >> http://mail.python.org/mailman/listinfo/python-list
> >
--
http://mail.python.org/mailman/listinfo/python-list


Re: IDE for python 2.6 (auto complete)

2009-05-04 Thread Mike Driscoll
On May 4, 10:13 am, Soumen banerjee  wrote:
> Hello,
> I have just installed and run python 2.6.2 from the sources available
> on the website. I notice that SPE (the editor which i used with python
> 2.5) is not displaying some of the functions new in 2.6 as
> autocomplete options. Is there any IDE with support for autocomplete
> in python 2.6 with all the newer functions included?

Wingware probably does. You should just submit a bug report to Stani
though. He can probably fix SPE for you.

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


Re: Self function

2009-05-04 Thread Steve Howell
On May 3, 3:39 pm, bearophileh...@lycos.com wrote:
> Sometimes I rename recursive functions, or I duplicate&modify them,
> and they stop working because inside them there's one or more copy of
> their old name.
> This happens to me more than one time every year.
> So I have written this:
>
> from inspect import getframeinfo, currentframe
>
> def SOMEVERYUGLYNAME(n):
>     if n <= 1:
>         return 1
>     else:
>         self_name = getframeinfo(currentframe()).function
>         #self_name = getframeinfo(currentframe())[2] # older python
>
>         # only if it's a global function
>         #return n * globals()[self_name](n - 1)
>         return n * eval(self_name + "(%d)" % (n - 1))
> assert SOMEVERYUGLYNAME(6) == 2*3*4*5*6
>
> Are there nicer ways to do that? I don't know.
> If there aren't, then a way may be added.
> An idea-syntax:
>
> def fact(n):
>     return 1 if n <= 1 else n * inspect.self(n - 1)
>
> Or even a lambda, because you don't need the name anymore to call the
> function:
>
> fact = lambda n: 1 if n <= 1 else n * self(n - 1)
>
> (If you have two or more recursive functions that call each other this
> idea can't be used, but I think such situations are uncommon enough to
> not deserve help from the language).
>

One very simple thing that you can do is assign the current function
name to a local var at the very top to make it a little more obvious.

I agree that there are lots of recursive patterns where python itself
does not provide much sugar.  A pattern that comes up for me
occasionally is two methods with almost identical names, where one
function is the public interface and then another method that does
most of the recursion.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Default padding for Tkinter grid

2009-05-04 Thread Amr
On May 4, 3:57 pm, "Gabriel Genellina"  wrote:
> En Mon, 04 May 2009 10:27:49 -0300, Amr  escribió:
>
> > I've been spending the last few days experimenting with Tkinter. The
> > grid manager is nice and easy to use, but I have found that I am often
> > having to specify padx and pady options to every widget I add to my
> > grid. The way I am doing it is to create a dictionary:
>
> > paddding = {'padx': '1m', 'pady': '1m'}
>
> > and then apply it to the grid method using **padding.
>
> > However, I was wondering if there was a way of setting default padx
> > and pady controls for the grid, so that I can just call grid without
> > having to specify any extra parameters.
>
> You have to call grid() once on every widget, so adding **padding at the  
> end doesn't appear too bad to me:
>
>    label = Label(master, text="Hello world!")
>    widget.grid(row=3, col=1, **padding)
>
> What about a function:
>
> def grid_with_padding(widget, padx='1m', pady='1m', **kw):
>    widget.grid(padx=padx, pady=pady, **kw)
>
> If you want an uniform padding:
>
> def add_padding(container, padx='1m', pady='1m'):
>    nc, nr = container.grid_size()
>    for i in range(nc):
>      container.grid_columnconfigure(i, pad=padx)
>    for i in range(nr):
>      container.grid_rowconfigure(i, pad=pady)
>
> --
> Gabriel Genellina

Hi Gabriel,

Thanks for your reply - I like the method you mention at the end,
using grid_columnconfigure and grid_rowconfigure as I can use that to
apply setting to the whole grid at the end. I'll have a mess around
with it.

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


IDE for python 2.6 (auto complete)

2009-05-04 Thread Soumen banerjee
Hello,
I have just installed and run python 2.6.2 from the sources available
on the website. I notice that SPE (the editor which i used with python
2.5) is not displaying some of the functions new in 2.6 as
autocomplete options. Is there any IDE with support for autocomplete
in python 2.6 with all the newer functions included?
--
http://mail.python.org/mailman/listinfo/python-list


Re: find sublist inside list

2009-05-04 Thread MRAB

Matthias Gallé wrote:

bearophileh...@lycos.com wrote:

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


Thanks bearophile and John for your quick answers.
Unfortunately, the int that can replace a sublist can be > 255, but 
John's answer looks simple and good enough for me. I will use it as a 
starting point.



John's solution changes the length of the list over which it's
iterating.

I'd suggest something more like:

li = ['a', 'c', 'a', 'c', 'c', 'g', 'a', 'c']
pos = 0
try:
while True:
pos = li.index('a', pos)
if li[pos : pos + 2] == ['a', 'c']:
li[pos : pos + 2] = [6]
pos += 1
except ValueError:
pass
--
http://mail.python.org/mailman/listinfo/python-list


Re: Default padding for Tkinter grid

2009-05-04 Thread Gabriel Genellina

En Mon, 04 May 2009 10:27:49 -0300, Amr  escribió:


I've been spending the last few days experimenting with Tkinter. The
grid manager is nice and easy to use, but I have found that I am often
having to specify padx and pady options to every widget I add to my
grid. The way I am doing it is to create a dictionary:

paddding = {'padx': '1m', 'pady': '1m'}

and then apply it to the grid method using **padding.

However, I was wondering if there was a way of setting default padx
and pady controls for the grid, so that I can just call grid without
having to specify any extra parameters.


You have to call grid() once on every widget, so adding **padding at the  
end doesn't appear too bad to me:


  label = Label(master, text="Hello world!")
  widget.grid(row=3, col=1, **padding)

What about a function:

def grid_with_padding(widget, padx='1m', pady='1m', **kw):
  widget.grid(padx=padx, pady=pady, **kw)

If you want an uniform padding:

def add_padding(container, padx='1m', pady='1m'):
  nc, nr = container.grid_size()
  for i in range(nc):
container.grid_columnconfigure(i, pad=padx)
  for i in range(nr):
container.grid_rowconfigure(i, pad=pady)

--
Gabriel Genellina

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


Re: find sublist inside list

2009-05-04 Thread bearophileHUGS
Matthias Gallé:
>the int that can replace a sublist can be > 255,<

You didn't specify your integer ranges.
Probably there are many other solutions for your problem, but you have
to give more information. Like the typical array size, typical range
of the numbers, how much important is total memory used, how much
important is running speed, what kind of processing (or serialization/
output) you later have to do with such arrays, and so on.
Other solutions include using an array('H', []), and using 0-255 to
represent ASCII and numbers >255 <2^16 to represent the other numbers,
etc.
If speed is critical you can even think about creating a little
function with PyInline or D+Pyd, etc.

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


Re: find sublist inside list

2009-05-04 Thread Matthias Gallé

bearophileh...@lycos.com wrote:

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


Thanks bearophile and John for your quick answers.
Unfortunately, the int that can replace a sublist can be > 255, but 
John's answer looks simple and good enough for me. I will use it as a 
starting point.


Thank's again.

--
Matthias Gallé
Project Symbiose
Centre de Recherche INRIA Rennes - Bretagne Atlantique,
Campus de Beaulieu, 35042 Rennes cedex, France
tel: (33|0) 2 9984 7523
http://www.irisa.fr/symbiose/matthias_galle
--
http://mail.python.org/mailman/listinfo/python-list


Re: if statement, with function inside it: if (t = Test()) == True:

2009-05-04 Thread Antoon Pardon
On 2009-04-24, Steven D'Aprano  wrote:
> On Fri, 24 Apr 2009 03:00:26 -0700, GC-Martijn wrote:
>
>> Hello,
>> 
>> I'm trying to do a if statement with a function inside it. I want to use
>> that variable inside that if loop , without defining it.
>> 
>> def Test():
>> return 'Vla'
>> 
>> I searching something like this:
>> 
>> if (t = Test()) == 'Vla':
>> print t # Vla
>> 
>> or
>> 
>> if (t = Test()):
>> print t # Vla
>
> Fortunately, there is no way of doing that with Python. This is one 
> source of hard-to-debug bugs that Python doesn't have.

I think this is an unfortunate consequence of choosing '=' for the
assignment. They could have chosen an other token to indicate an
assignment one that would have made the difference between an
assignment and a comparison more visually different and thus
bugs by using one while needing the other less hard to track
down.

So when a certain kind of bug is hard to track down because of
the similarity of the tokens and not because of the specific
functionality I find it unfortunate they dropped the functionality
instead of making the tokens less similar.

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


Re: Code works fine except...

2009-05-04 Thread Ross
On May 3, 10:16 pm, John Yeung  wrote:
> On May 3, 11:29 pm, Chris Rebert  wrote:
>
> > Probably not the cause of the problem, but where
> > did the magic numbers 1.072 and 1.08 come from?
>
> It is perhaps not the most direct cause of the problem, in the sense
> that the magic numbers could take various values and the problem would
> still be there.  But the magic numbers appear to be used for
> "spreading out" bye selection, and that's broken.
>
> The extended slice as written will always pick the first element,
> since the step is guaranteed to be positive.  Since the first player
> (or None, when there are an odd number of players) stays put in the
> first position during the round_robin shuffle, that player will always
> be selected for a bye.
>
> Further, as written, the calculated number of byes has no bearing on
> the actual number of byes selected.
>
> I think what I would do is adjust the shuffling algorithm in such a
> way that everyone moves through the various positions in the list
> (would it be as simple as adding a shift at the end of
> round_robin???).  Then I could simply select the byes from one end of
> the list (with a regular slice instead of an extended slice).
>
> John

The "magic numbers" that everyone is wondering about are indeed used
for spreading out the bye selection and I got them by simply
calculating a line of best fit when plotting several courts: byes
ratios.

The "byes = #whatever" in my code calculate the number of tuples that
need to be placed in the bye_list.

At first glance, the suggestion of adding a simple shift at the end of
round_robin doesn't seem to work since round_robin already shifts
everything except for the first position already. Please correct me if
I'm wrong because you might have been suggesting something different.
--
http://mail.python.org/mailman/listinfo/python-list


Re: AutoComplete in C++ Editor for Python

2009-05-04 Thread flamz3d
On May 3, 3:14 pm, Dave Angel  wrote:
> flam...@gmail.com wrote:
> > Hello,
> > I am embedding python support in my C++ application and was looking at
> > adding "Intellisense" or "AutoComplete" support.
>
> > I found a way to do it using the "dir" function, but this creates a
> > problem. Here's why. Let's say I have the following code in my editor:
>
> > import sys
> > x = sys
>
> > Now, I would like to get all attributes of the object called 'x'. I
> > can "instrument" the code and add "print dir(x)" at the end,
> > temporarily redirect the python output to a string and execute the
> > code.
>
> > But this is not safe: I do NOT want to execute the code while the user
> > is typing!
>
> > Is there a way to "compile" the python code and get access to the
> > symbol table from that compiled block?
>
> > Did anybody ever implement AutoComplete in a editor for Python?
>
> > cheers.
>
> Several editors for Python support auto-complete, to one extent or
> another.  The only one I have experience with is Komodo.  Komodo runs in
> a separate process, so it doesn't suffer from the problems of having two
> gui event-loops in the same process, and other similar problems.   It
> also won't be executing code that might have side effects in the child
> process.
>
> The downside is that in order to do auto-complete, it has to figure it
> out from other clues.  From the docs, and from reading, and from
> experiementing, I believe that it uses two approaches.  One approach is
> a set of language files which try to describe all the symbols in the
> standard language and library.  They have one for each release (2.4,
> 2.5, ...)  Theoretically, you could add your own for other libraries.  
> Second approach is to parse the code that's visible to it.  That parsing
> is well done, and surprisingly quick, but there are lots of tricks a
> developer might use that can fool it.  For example, wxPython lets you
> import just one symbol, and lots more appear magically.  It's no big
> deal, they have code structured one way, but the interface is very
> different.  Catch is that code completion frequently gets fooled by these.
>
> I'd point out that if you do walk the dictionaries at run time, you'll
> get different results when you do it with nothing running than if you do
> a strictly static analysis.  So some things might only show up if you've
> stepped into the function with the magic going on.
>
> Simplest example I can come up with of something a static analysis won't
> spot:   An instance object    obj   may have some number of attributes
> assigned the the __init__() method.  But it could also have new fields
> added by anyone with a referent into it.
>
> There is a Python parser in module ast.  Perhaps that'd be some help.  
> I've not used it, so can't give you any specifics.
>
> DaveA


I think it might be possible for me to figure out how to do
AutoCompletion using the symtable object. But I am having difficulty
making sense of it.

In my tests, I was use the following Python code:

[code]
import sys
x=sys
[/code]

The idea is to get the type of the variable x

To attempt this, I use the following C code (my editor is written in
C)

symtable* st = Py_SymtableString ( "import sys
\nx=sys,"",Py_single_input);

PyObject *name, *value;
Py_ssize_t pos = 0;
while (PyDict_Next(st->st_symbols, &pos, &name, &value))
{
...
}



Using this code, I can get information like the name of the symbol
(x), but I can't figure out how to get the type. If I knew how to get
this it would solve 99% of my problems :)

Any ideas?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Code works fine except...

2009-05-04 Thread Ross
On May 4, 7:01 am, Ross  wrote:
> On May 3, 10:16 pm, John Yeung  wrote:
>
>
>
> > On May 3, 11:29 pm, Chris Rebert  wrote:
>
> > > Probably not the cause of the problem, but where
> > > did the magic numbers 1.072 and 1.08 come from?
>
> > It is perhaps not the most direct cause of the problem, in the sense
> > that the magic numbers could take various values and the problem would
> > still be there.  But the magic numbers appear to be used for
> > "spreading out" bye selection, and that's broken.
>
> > The extended slice as written will always pick the first element,
> > since the step is guaranteed to be positive.  Since the first player
> > (or None, when there are an odd number of players) stays put in the
> > first position during the round_robin shuffle, that player will always
> > be selected for a bye.
>
> > Further, as written, the calculated number of byes has no bearing on
> > the actual number of byes selected.
>
> > I think what I would do is adjust the shuffling algorithm in such a
> > way that everyone moves through the various positions in the list
> > (would it be as simple as adding a shift at the end of
> > round_robin???).  Then I could simply select the byes from one end of
> > the list (with a regular slice instead of an extended slice).
>
> > John
>
> The "magic numbers" that everyone is wondering about are indeed used
> for spreading out the bye selection and I got them by simply
> calculating a line of best fit when plotting several courts: byes
> ratios.
>
> The "byes = #whatever" in my code calculate the number of tuples that
> need to be placed in the bye_list.
>
> At first glance, the suggestion of adding a simple shift at the end of
> round_robin doesn't seem to work since round_robin already shifts
> everything except for the first position already. Please correct me if
> I'm wrong because you might have been suggesting something different.

And also, as you all have pointed out, my inclusion of

> def test_round_robin(players, rounds, courts, doubles = False):
> players = range(players)
> for week in round_robin(players,rounds,courts):

should have been

> def test_round_robin(players, rounds, courts, doubles = False):
> players = range(players)
> for week in round_robin(players,rounds):

I forgot to erase that extra parameter when I was playing around with
my code.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to walk up parent directories?

2009-05-04 Thread David Smith
Matthew Wilson wrote:
> Is there already a tool in the standard library to let me walk up from a
> subdirectory to the top of my file system?
> 
> In other words, I'm looking for something like:
> 
> >>> for x in walkup('/home/matt/projects'):
> ... print(x)
> /home/matt/projects
> /home/matt
> /home
> /
> 
> I know I could build something like this with various os.path
> components, but I'm hoping I don't have to.
> 
> TIA
> 
> 
> Matt

You should take a look at the os.path module.  Seems like you might find
something in that toolbox for this.

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


  1   2   >