Re: PythonCard - My app stuck when button clicked

2009-05-14 Thread daved170
On May 13, 7:42 pm, Dave Angel  wrote:
> daved170 wrote:
> > Hi there,
> > I'm newbie in pythonCard.
> > I have an application with 2 buttons : START , STOP
> > Start execute a while(1) loop that execute my calculations.
> > Stop suppose to raise a flag that will end that loop.
>
> > Whenever I pish the START button my GUI is stuck. the calculation
> > executes but I can't push the STOP button.
>
> > I added thread that START start a thread that execute my calculations.
> > I also added a Global variable that will hold the indication if the
> > loop should continue.
> > The problem now is that the thread ignore that variable and loop
> > forever.
>
> > Is there a simple way to make sure that the GUI won't stuck (without
> > threads)?
> > And if there isn't such way I would appriciet it very much if anyone
> > could post an example of how to make my thread read that variable
> > Thanks
> > Dave
>
> I don't know PythonCard, but most GUI's are similar enough that the
> concepts will work, even though the details differ.  I'll assume that
> PythonCard has a traditional event loop, from which all events are
> dispatched.
>
> If your loop is fairly small, then you should keep it to one thread.  
> Debugging it will usually be much easier.  The trick is to break the
> task into pieces (each piece might be once around what is now a loop),
> and invoke one piece each time the event loop empties.  I can't tell you
> how to do that without seeing your loop, but it's not usually very hard.
>
> Now, there is some way of POSTing an event to the event loop.  That puts
> the event *after* all the events that are already there, but returns
> control immediately.  So create a custom event, and POST it from the
> START button's button-pressed event.  That will fire off one "loop" of
> the special task, in other words, make one function call to your new
> function.  Then at the end of the function, POST it again, unless the
> STOP button has been pressed in the meantime.
>
> An optimization for this is to use coroutines, which are usually done
> with a generator.  It's much trickier to describe, but much easier to
> accomplish.  Roughly, you'd take your existing loop, and put a yield
> statement in it at appropriate place(s).  Then the custom event is
> simply a call to the .next() function of that generator.
>
> Now, threading isn't that tough either, depending on how much data is
> being shared between the thread and the main program.  You say that
> sharing a global flag isn't working, but it should.  So how about if you
> show us some code, and somebody'll spot the trouble.  For example, is
> the thread defined in the same module as the App?  Global only shares
> between a single module.  Another reason globals might seem to fail is
> if you tried to do mutual imports between two or more modules.  (A
> imports B, which imports A).  Sometimes that fails in mysterious ways.
>
> Make a simple (stripped) example of what you're trying, and we'll try to
> find the problem.  Without concrete code, we end up with ambiguities
> like the above usage of two different meanings for "the loop."- Hide quoted 
> text -
>
> - Show quoted text -

Thank's Dave,
Here my code, It's a very simple app. the Start button starts a TCP/IP
communication and the Stop should dtop it and kill the client.
I'll be thankful if you'll be able to spot my mistake.
Thanks again
Dave

#Global Variable
bStopLoop = False

#Global Function
def execute(sockObj):
   while(!bStopLoop):
  str = sockObj.recv(1024)
  tmpStr = "Hello " + str
  sockObj.send(tmpStr)

#Thread handle class
class myThread(threading.Thread):
   def __init__(self,sockObj):
  threading.Thread.__init__(self)
  bStopLoop = False
  self.sockObj = sockObj

   def run(self):
  execute(self.SockObj)

# GUI
class GUI(model.Background)

   def on_Start_mouseclick(self,event):
   try:
  event.target.enable = False
  event.target.redraw()
  self.components.Start.enable = False
  self.currThread = myThread(self.sockObj)
  self.currThread.Start()
  wx.SafeYield(self)
  self.components.Start.enable = True
   except:
  .

   def on_Stop_mouseclick(self,event):
  bStopLoop = True
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's the use of the else in try/except/else?

2009-05-14 Thread Andre Engels
On Thu, May 14, 2009 at 6:39 AM, ma  wrote:
> A really great use for try/except/else would be if an object is
> implementing its own __getitem__ method, so you would have something
> like this:
>
> class SomeObj(object):
>    def __getitem__(self, key):
>                try:
>                        #sometype of assertion here based on key type
>                except AssertionError, e:
>                        raise TypeError, e #invalid type
>                else:
>                        #continue processing, etc.. return some index, which 
> will auto throw
>                        #an index error if you have some type of indexable 
> datastructure

Again, this is a case where no else is needed. Whenever you raise
something in the except clause (as your only exit point), it would
work just as well (though it might be a bit uglier) to put the rest
after the try ... except without an else. It is when after the
exception execution continues normally, but skipping part of the code,
that you need an else.


-- 
André Engels, [email protected]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HTTP HEAD and docxmlrpcserver

2009-05-14 Thread Gabriel Genellina
En Mon, 11 May 2009 04:23:29 -0300, Christopher Mahan  
 escribió:


I have a docxmlrpcserver install (kissws.com) that's returning HTTP code  
501

when the client makes a HEAD request.

Any idea as to whether that's by design?


Yes. The XMLRPC spec defines only the POST request; DocXMLRPCServer  
extends the definition so a GET request is interpreted as a documentation  
query. Any other method remains undefined and generates a "501 Unsupported  
method (xxx)" response.


If you do need HEAD, extend DocXMLRPCRequestHandler to define a do_HEAD  
method (same as do_GET but without actually sending the response entity).


--
Gabriel Genellina

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


Re: HTTP HEAD and docxmlrpcserver

2009-05-14 Thread Christopher Mahan
On Thu, May 14, 2009 at 12:13 AM, Gabriel Genellina
wrote:

> En Mon, 11 May 2009 04:23:29 -0300, Christopher Mahan <
> [email protected]> escribió:
>
>  I have a docxmlrpcserver install (kissws.com) that's returning HTTP code
>> 501
>> when the client makes a HEAD request.
>>
>> Any idea as to whether that's by design?
>>
>
> Yes. The XMLRPC spec defines only the POST request; DocXMLRPCServer extends
> the definition so a GET request is interpreted as a documentation query. Any
> other method remains undefined and generates a "501 Unsupported method
> (xxx)" response.
>
> If you do need HEAD, extend DocXMLRPCRequestHandler to define a do_HEAD
> method (same as do_GET but without actually sending the response entity).
>
> --
> Gabriel Genellina
>


Thank you.

Chris Mahan
[email protected]
gv (818) 671-1709
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Distributed locking

2009-05-14 Thread Diez B. Roggisch

James schrieb:

Hey all, I'm looking for suggestions on how to tackle distributed
locking across several Python programs on several different machines.

- the objects to be locked are uniquely identified by an integer
- I need "one at a time" semantics for the lock: zero or one read-
writer at any point
- the operations to be performed on the objects are strictly limited
in duration (no more than 10 seconds)

As the operations have a maximum duration, my ideal solution would be
to lock the objects, and have them automatically unlock after some
time period even if the original lock-holder doesn't release them.

I'm currently playing with memcached as a locking mechanism as it's
simplicity and timeout fit my requirements well.

There is a check-and-set operation which atomically writes new data
iff the existing value hasn't been changed since we last looked.
However, their CAS operation doesn't handle the case of a non-existent
key..

Does anyone have suggestions on how I can do distributed locking to
take advantage of the time limit on operations?


I'd use a database. Maybe the time limit could be modeled with a 
transaction-timeout, but even if not, you should be able to model a 
solution with timestamps and distinct transactions to modify the locked row.


Also, for the case of the non-existing lock, go with something like this:


if not lock_exists(my_lock):
   lock_locks_table()
   if not lock_exists(my_lock):
  create_lock(my_lock)

with my_lock:
...


In the __enter__ and __exit__-methods of my_lock, you can perfom the 
necessary database-ops.



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


Re: please help with python program

2009-05-14 Thread Tim Golden

chedderslam wrote:

IOError: [Errno 13] Permission denied: u'D:/My Music/Ani DiFranco/
Canon/Disc 1\\folder.jpg'

I have removed the read-only attribute on the folder, and added
"Everyone" with full control for security.  Not sure what else to do.
I would really like to get this working so any help would be
appreciated.


FWIW, read-only on a folder has no appreciable effect. It's generally
used by the Windows shell to indicate that the folder is "special"
(eg My Documents, My Music etc). It doesn't stop you writing files
in that directory.

Not sure how much Windows-fu you have, so apols if any of
this is teaching my grandmother to suck eggs...

I'm not familiar with the app you mention but make sure that the
user it's running under (which may be your own) has permissions
to write the file you're trying to save in the location in
question. Ie, as that user, do this in Python:

 open (u'D:/My Music/Ani DiFranco/Canon/Disc 1\\folder.jpg', "w")

to see if you get the same result. If you do, access the [Security]
tab on the folder itself, select [Advanced] and then the 
[Effective Permissions] tab to make sure what the permissions
really are. As a rule, "My xxx" folders tend to have more 
restrictive permissions as they are tied to a specific user.

This only matters, obviously, if the app is not running as
your own user.

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


Re: Skipping unit tests

2009-05-14 Thread Gabriel Genellina
En Mon, 11 May 2009 10:33:03 -0300, Ulrich Eckhardt  
 escribió:


We have a few tests for some module here. These tests are under  
development
and applied to older versions (with less features) of the module, too.  
That

means that if I have module version 42, tests A and B can not possibly
work. I don't want to have test failures but I also don't want to fork  
the

test suite, so how do I get the tests to behave like Python's test suite,
which also skips some "expected failures".


The simplest way would be to check for some condition (code version,  
attribute existence) in the tests themselves, and just skip it when it's  
not apropiate.


Another way is to omit the test case from the suite. Things can be a lot  
fancier... Look at the Python test suite for some ideas.


--
Gabriel Genellina

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


Re: about Python doc reader

2009-05-14 Thread Tim Golden

[forwarding back to the list]
Please reply to the list: I'm not the only person
who can help, and I might not have the time even
if I can.

Shailja Gulati wrote:
I have installed win32com but still not able to run tht code as its giving 
error 


  File "readDocPython.py", line 1, in ?
import win32com.client
  File "C:\pywin32-212\com\win32com\__init__.py", line 5, in ?
import win32api, sys, os
ImportError: No module named win32api


>
> i have even installed win32api.dll in Sytsem folder but
>  still can't do t.Any further help??

I don't know how you've installed it, but I really don't expect
to see it in c:\pywin32-212 Download *and run* the
.exe installer, from here, choosing the one which corresponds
to your Python installation?

http://sourceforge.net/project/platformdownload.php?group_id=78018

Don't try to download the source -- the zip -- and add it to 
sys.path, which is the only thing I can imagine you've done there.



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


Question: Running Python programs in KDE

2009-05-14 Thread Grant Ito
Hello.

Silly question here. I'd like to find out how to create an icon in KDE to 
run my Python scripts. Specs are as follows:

KDE version 4.1.3 in OpenSuse 11.1.
Some scripts have output to Konsole window, others use Tkinter.

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


about Python doc reader

2009-05-14 Thread Shailja Gulati
[forwarding back to the list]
Please reply to the list: I'm not the only person
who can help, and I might not have the time even
if I can.

Shailja Gulati wrote:
> I have installed win32com but still not able to run tht code as its 
giving 
> error 
> 
>   File "readDocPython.py", line 1, in ?
> import win32com.client
>   File "C:\pywin32-212\com\win32com\__init__.py", line 5, in ?
> import win32api, sys, os
> ImportError: No module named win32api

 >
 > i have even installed win32api.dll in Sytsem folder but
 >  still can't do t.Any further help??

I don't know how you've installed it, but I really don't expect
to see it in c:\pywin32-212 Download *and run* the
.exe installer, from here, choosing the one which corresponds
to your Python installation?


Sorry about mailing u Tim.It just happened by mistake.

Reg win32api , i m still facing the same problem of Import error...Could 
anyone pls help?? m stuck

http://sourceforge.net/project/platformdownload.php?group_id=78018

Don't try to download the source -- the zip -- and add it to 
sys.path, which is the only thing I can imagine you've done there.


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

ForwardSourceID:NTEC7A 
=-=-=
Notice: The information contained in this e-mail
message and/or attachments to it may contain 
confidential or privileged information. If you are 
not the intended recipient, any dissemination, use, 
review, distribution, printing or copying of the 
information contained in this e-mail message 
and/or attachments to it are strictly prohibited. If 
you have received this communication in error, 
please notify us by reply e-mail or telephone and 
immediately and permanently delete the message 
and any attachments. Thank you


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


Re: urllib2 slow for multiple requests

2009-05-14 Thread Tomas Svarovsky
On May 13, 4:55 pm, cgoldberg  wrote:
> > Bascally it just grabs a page xy
> > times and tells me how long it took.
>
> you aren't doing a read(), so technically you are just connecting to
> the web server and sending the request but never reading the content
> back from the socket.  So your timing wouldn't be accurate.
>
> try this instead:
> response = urllib2.urlopen(req).read()
>
> But that is not the problem you are describing...

Thanks for this pointer, didn't come to my mind.

> > when I increase the number of repetitions, it is
> > slowing down considerably (1 is like 3 ms, 100 takes 6 seconds).
> > Maybe it is a known issue in urllib2
>
> I ran your code and can not reproduce that behavior.  No matter how
> many repetitions, I still get a similar response time per transaction.
>
> any more details or code samples you can provide?
>

I don;t know, I have tried the program on my local MacOs, where I have
several python runtimes installed and there is huge dfference between
result after running at 2.6 and 2.4. So this might be the problem.
When ran on the 2.6 result are comparable to php and better than ruby,
which is what I expect.

The problem is, that CentOS is running on the server and there is only
2.4 available. On wich version did you ran these tests?

Thanks

> -Corey Goldberg

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


Re: Question: Running Python programs in KDE

2009-05-14 Thread Diez B. Roggisch
Grant Ito wrote:

> Hello.
> 
> Silly question here. I'd like to find out how to create an icon in KDE to
> run my Python scripts. Specs are as follows:
> 
> KDE version 4.1.3 in OpenSuse 11.1.
> Some scripts have output to Konsole window, others use Tkinter.
> 
> Thanks in advance,
> Grant.

Try right mouseclick over the desktop. Follow the context-menu.

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


Re: about Python doc reader

2009-05-14 Thread Tim Golden

Shailja Gulati wrote:

Sorry about mailing u Tim.It just happened by mistake.

Reg win32api , i m still facing the same problem of Import error...Could 
anyone pls help?? m stuck


Shailja. Did you download and install the download .exe
from the link below?



http://sourceforge.net/project/platformdownload.php?group_id=78018



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


Fw: about Python doc reader

2009-05-14 Thread Shailja Gulati
Shailja Gulati wrote:
> Sorry about mailing u Tim.It just happened by mistake.
> 
> Reg win32api , i m still facing the same problem of Import error...Could 

> anyone pls help?? m stuck

Shailja. Did you download and install the download .exe
from the link below?


yeah..I have installed it from the same link earlier..bt getting the 
Import error ...

Anyways i have got an alternate solution as

1.first convert doc to .txt file with free doc to text converter.I have 
used "Antiword"  software for this.
2. Python can easily read this txt file and process tabular data also.

so hoping tht problem will be solved.

thanks for ur help.


> 
> http://sourceforge.net/project/platformdownload.php?group_id=78018


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

ForwardSourceID:NTEC9E 
=-=-=
Notice: The information contained in this e-mail
message and/or attachments to it may contain 
confidential or privileged information. If you are 
not the intended recipient, any dissemination, use, 
review, distribution, printing or copying of the 
information contained in this e-mail message 
and/or attachments to it are strictly prohibited. If 
you have received this communication in error, 
please notify us by reply e-mail or telephone and 
immediately and permanently delete the message 
and any attachments. Thank you


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


Re: urllib2 slow for multiple requests

2009-05-14 Thread Tomas Svarovsky
One more thing, since I am stuck with 2.4 (and if this is really 2.4
issue), is there some substitution for urllib2?

On May 14, 11:00 am, Tomas Svarovsky 
wrote:
> On May 13, 4:55 pm, cgoldberg  wrote:
>
> > > Bascally it just grabs a page xy
> > > times and tells me how long it took.
>
> > you aren't doing a read(), so technically you are just connecting to
> > the web server and sending the request but never reading the content
> > back from the socket.  So your timing wouldn't be accurate.
>
> > try this instead:
> > response = urllib2.urlopen(req).read()
>
> > But that is not the problem you are describing...
>
> Thanks for this pointer, didn't come to my mind.
>
> > > when I increase the number of repetitions, it is
> > > slowing down considerably (1 is like 3 ms, 100 takes 6 seconds).
> > > Maybe it is a known issue in urllib2
>
> > I ran your code and can not reproduce that behavior.  No matter how
> > many repetitions, I still get a similar response time per transaction.
>
> > any more details or code samples you can provide?
>
> I don;t know, I have tried the program on my local MacOs, where I have
> several python runtimes installed and there is huge dfference between
> result after running at 2.6 and 2.4. So this might be the problem.
> When ran on the 2.6 result are comparable to php and better than ruby,
> which is what I expect.
>
> The problem is, that CentOS is running on the server and there is only
> 2.4 available. On wich version did you ran these tests?
>
> Thanks
>
> > -Corey Goldberg

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


Re: urllib2 slow for multiple requests

2009-05-14 Thread Richard Brodie

"cgoldberg"  wrote in message 
news:[email protected]...

> you aren't doing a read(), so technically you are just connecting to
> the web server and sending the request but never reading the content
> back from the socket.
>
> But that is not the problem you are describing...

It might be, if the local server doesn't scale well enough to handle
100 concurrent requests. 


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


2nd Pyggy Awards Open

2009-05-14 Thread Greg Ewing

The Second Pyggy Awards is now open for entries.

  http://pyggy.pyweek.org/1008/

Judging will be held in the first two weeks of
August 2009.

Once again, the event is open to games from any
previous PyWeek competition.

You may also submit a game that you were intending
to enter in PyWeek 8 but didn't finish.

(It seems that some people decided not to enter their
unfinished games in PyWeek, hoping to make them Pyggy
entries instead. I'll allow that this time, but in
future it would be better to submit whatever you've
got at the end of PyWeek. You can still make a backup
PyWeek entry as well if you want.)

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


Re: urllib2 slow for multiple requests

2009-05-14 Thread Tomas Svarovsky
On May 14, 11:57 am, "Richard Brodie"  wrote:
> "cgoldberg"  wrote in message
>
> news:[email protected]...
>
> > you aren't doing a read(), so technically you are just connecting to
> > the web server and sending the request but never reading the content
> > back from the socket.
>
> > But that is not the problem you are describing...
>
> It might be, if the local server doesn't scale well enough to handle
> 100 concurrent requests.

This is a good point, but then it would manifest regardless of the
language used AFAIK. And this is not the case, ruby and php
implementations are working quite fine.

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


matplotlib - overlaying plots.

2009-05-14 Thread Ant
Hi All,

I am trying to get matplotlib to overlay a couple of graphs, but am
getting nowhere. I originally thought that the following may work:

>>> x = [1,2,3,4,5]
>>> y = [2,4,6,8,10]
>>> y2 = [1,4,9,16,25]

>>> plot(x, y)
>>> plot(x, y2)

Now this works as desired, however, the actual case I have is more
like this:

>>> x = [1,2,3,4,5]
>>> y = [2,4,6,8,10]
>>> y2 = [.0001, .0002, .0003, .0004, .0005]

Now the graph is useless, since the results are plotted on the same
axis. What I really want is two different sets of axes, each scaled
appropriately, but overlayed.

The data I actually have, is one set of axes plotting distance against
elevation, and a second plotting distance against speed. The former
has (y-coord) units in the range 0-2000 ft and the latter 0 - 0.01
miles/second. I want them on the same graph, so points can be easily
correlated, but overlayed so that each line has a different scale on
the y-axis. The closest I can get is to have two subplots, one above
the other.

Thanks in advance,

Ant.

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


Re: (Windows) Finding out which process has locked a file.

2009-05-14 Thread Lawrence D'Oliveiro
In message <787d6072-3381-40bd-
[email protected]>, CinnamonDonkey wrote:

> I have a script running which occa[s]ionally fails because it is trying
> to delete a file in use by another process. When this happens I want
> it to log which process has the lock.

Maybe there is no such process. Maybe it's just the Dimdows filesystem 
randomly returning a failure on its own. How would you know?

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


Re: Nimrod programming language

2009-05-14 Thread Dikkie Dik

> 3) Most text files have no header specifying the encoding anyway. How
> should the programm/programmer know? And often he does not need to
> know anyway.


What? Off COURSE texts have no header stating the encoding! And it is
the programmer's responsibility to know what a text's encoding is. So do
not ignore HTTP headers when downloading or other means of communicating
the encoding.

That is the whole problem with texts represented as strings. A string is
a free sequence of bytes, whereas a text is a free sequence of
characters WITH AN ENCODING. This may be a default encoding, but you
must still know which one that is. That is your JOB as a programmer.

Putting the encoding as some sort of header in the string itself is the
worst "solution" that has ever been proposed. Do you put the only key to
a safe inside the very same safe and lock it? Then why do you have to
hack a string (is is not a text as it is not accompanied by an encoding)
to see what encoding is hidden inside?

Ask yourself: would the following "headers" ever work (each given in the
stated encoding off course)?







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


introspection question: get return type

2009-05-14 Thread flamz3d
Hello,
I am wondering if it's possible to get the return value of a method
*without* calling it using introspection?

something like this, suppose I want to know the type of the return
value for the method "getsomething". Is it possible to get it without
actually calling 'getsomething'?

ex:
import mystuff
print dir (mystuff.getsomething)


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


Re: introspection question: get return type

2009-05-14 Thread Diez B. Roggisch
[email protected] wrote:

> Hello,
> I am wondering if it's possible to get the return value of a method
> *without* calling it using introspection?

Nope. All that's possible to see if there is a implicit or explicit return
through dis.disassemble - if you find "LOAD_CONST None" before any
return-statement, you know that you don't anything else.

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


Re: PythonCard - My app stuck when button clicked

2009-05-14 Thread Dave Angel

daved170 wrote:

On May 13, 7:42 pm, Dave Angel  wrote:
  

daved170 wrote:


Hi there,
I'm newbie in pythonCard.
I have an application with 2 buttons : START , STOP
Start execute a while(1) loop that execute my calculations.
Stop suppose to raise a flag that will end that loop.
  
Whenever I pish the START button my GUI is stuck. the calculation

executes but I can't push the STOP button.
  
I added thread that START start a thread that execute my calculations.

I also added a Global variable that will hold the indication if the
loop should continue.
The problem now is that the thread ignore that variable and loop
forever.
  
Is there a simple way to make sure that the GUI won't stuck (without

threads)?
And if there isn't such way I would appriciet it very much if anyone
could post an example of how to make my thread read that variable
Thanks
Dave
  

I don't know PythonCard, but most GUI's are similar enough that the
concepts will work, even though the details differ.  I'll assume that
PythonCard has a traditional event loop, from which all events are
dispatched.

If your loop is fairly small, then you should keep it to one thread.  
Debugging it will usually be much easier.  The trick is to break the

task into pieces (each piece might be once around what is now a loop),
and invoke one piece each time the event loop empties.  I can't tell you
how to do that without seeing your loop, but it's not usually very hard.

Now, there is some way of POSTing an event to the event loop.  That puts
the event *after* all the events that are already there, but returns
control immediately.  So create a custom event, and POST it from the
START button's button-pressed event.  That will fire off one "loop" of
the special task, in other words, make one function call to your new
function.  Then at the end of the function, POST it again, unless the
STOP button has been pressed in the meantime.

An optimization for this is to use coroutines, which are usually done
with a generator.  It's much trickier to describe, but much easier to
accomplish.  Roughly, you'd take your existing loop, and put a yield
statement in it at appropriate place(s).  Then the custom event is
simply a call to the .next() function of that generator.

Now, threading isn't that tough either, depending on how much data is
being shared between the thread and the main program.  You say that
sharing a global flag isn't working, but it should.  So how about if you
show us some code, and somebody'll spot the trouble.  For example, is
the thread defined in the same module as the App?  Global only shares
between a single module.  Another reason globals might seem to fail is
if you tried to do mutual imports between two or more modules.  (A
imports B, which imports A).  Sometimes that fails in mysterious ways.

Make a simple (stripped) example of what you're trying, and we'll try to
find the problem.  Without concrete code, we end up with ambiguities
like the above usage of two different meanings for "the loop."- Hide quoted 
text -

- Show quoted text -



Thank's Dave,
Here my code, It's a very simple app. the Start button starts a TCP/IP
communication and the Stop should dtop it and kill the client.
I'll be thankful if you'll be able to spot my mistake.
Thanks again
Dave

#Global Variable
bStopLoop =alse

#Global Function
def execute(sockObj):
   while(!bStopLoop):
  str =ockObj.recv(1024)
  tmpStr =Hello " + str
  sockObj.send(tmpStr)

#Thread handle class
class myThread(threading.Thread):
   def __init__(self,sockObj):
  threading.Thread.__init__(self)
  bStopLoop =alse
  self.sockObj =ockObj

   def run(self):
  execute(self.SockObj)

# GUI
class GUI(model.Background)

   def on_Start_mouseclick(self,event):
   try:
  event.target.enable =alse
  event.target.redraw()
  self.components.Start.enable =alse
  self.currThread =yThread(self.sockObj)
  self.currThread.Start()
  wx.SafeYield(self)
  self.components.Start.enable =rue
   except:
  .

   def on_Stop_mouseclick(self,event):
  bStopLoop =rue

  
In the two methods that try to change bStopLoop, you don't declare it 
global.  Add the line "global bStopLoop"  to beginning of both 


on_Start_mouseclick() and on_Stop_mouseclick(), and (my preference) to function 
execute()

The semantics of global versus local variables for non-nested functions/methods is roughly:   if a function or method assigns to a name, it's taken to be a local, unless it's explicitly declared as global. 



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


Re: introspection question: get return type

2009-05-14 Thread bearophileHUGS
[email protected]:
> I am wondering if it's possible to get the return value of a method
> *without* calling it using introspection?

Python is dynamically typed, so you can create a function like this:

>>> foo = lambda x: "x" if x else 1
>>> foo(1)
'x'
>>> foo(0)
1

The return type of foo() changes according to the input value.
In general there's not much hope to know the return type if you don't
actually run the function.

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


python copy method alters type

2009-05-14 Thread Zhenhai Zhang

Really weired; Here is my code:

   a = ["a", 1, 3, 4]
   print "a:", a
  
   c = copy(a)

   c[0] = "c"
   c[1] = 2
   print "c:", c
   print "a:",a

output as follows:

a: ['a', 1, 3, 4]
c: ['c' '2' '3' '4']
a: ['a', 1, 3, 4]

Btw, I'm using python 2.5. I'm very curious why the copied list changed 
data type.


Thanks,

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


Re: introspection question: get return type

2009-05-14 Thread Diez B. Roggisch
Diez B. Roggisch wrote:

> [email protected] wrote:
> 
>> Hello,
>> I am wondering if it's possible to get the return value of a method
>> *without* calling it using introspection?
> 
> Nope. All that's possible to see if there is a implicit or explicit return
> through dis.disassemble - if you find "LOAD_CONST None" before any
> return-statement, you know that you don't anything else.

Gosh, this is barely intelligible...

What I wanted to say is that you can check if a function only returns
constant values, which most of the time will be implicit "return None"
statements, as in this:

def foo():
a = 10

dis.disassemble(foo.func_code)
...
  2   0 LOAD_CONST   0 (None)
  3 RETURN_VALUE
Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python copy method alters type

2009-05-14 Thread Diez B. Roggisch
Zhenhai Zhang wrote:

> Really weired; Here is my code:
> 
> a = ["a", 1, 3, 4]
> print "a:", a
>
> c = copy(a)
> c[0] = "c"
> c[1] = 2
> print "c:", c
> print "a:",a
> 
> output as follows:
> 
> a: ['a', 1, 3, 4]
> c: ['c' '2' '3' '4']
> a: ['a', 1, 3, 4]
> 
> Btw, I'm using python 2.5. I'm very curious why the copied list changed
> data type.

It doesn't. This must be some effect of you toying around and forgetting
some steps.

>>> import copy
>>> print "a:", a
a: ['a', 1, 3, 4]
>>> c = copy.copy(a)
>>> c[0] = "c"
>>> c[1] = 2
>>> print "c:", c
c: ['c', 2, 3, 4]


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


Re: python copy method alters type

2009-05-14 Thread Wynand Winterbach
My only guess is that the code below is not using the copy function from
the copy module, but that some other function is aliasing the copy
function.

I've tried this code with both Python 2.5 and 2.6 and get the correct
behaviour.

Best
Wynand

Op donderdag 14-05-2009 om 09:05 uur [tijdzone -0400], schreef Zhenhai
Zhang:
> Really weired; Here is my code:
> 
> a = ["a", 1, 3, 4]
> print "a:", a
>
> c = copy(a)
> c[0] = "c"
> c[1] = 2
> print "c:", c
> print "a:",a
> 
> output as follows:
> 
> a: ['a', 1, 3, 4]
> c: ['c' '2' '3' '4']
> a: ['a', 1, 3, 4]
> 
> Btw, I'm using python 2.5. I'm very curious why the copied list changed 
> data type.
> 
> Thanks,
> 
> Zhenhai

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


Re: python copy method alters type

2009-05-14 Thread Bruno Desthuilliers

Zhenhai Zhang a écrit :

Really weired; Here is my code:

   a = ["a", 1, 3, 4]
   print "a:", a
 c = copy(a)
   c[0] = "c"
   c[1] = 2
   print "c:", c
   print "a:",a

output as follows:

a: ['a', 1, 3, 4]
c: ['c' '2' '3' '4']
a: ['a', 1, 3, 4]

Btw, I'm using python 2.5. I'm very curious why the copied list changed 
data type.


I think you're not using the stdlib's copy.copy function...

Python 2.5.2 (r252:60911, Oct  5 2008, 19:24:49)
GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.

from copy import copy
a = ["a", 1, 3, 4]
print a

['a', 1, 3, 4]

c = copy(a)
c

['a', 1, 3, 4]

c[0] = "c"
c[1] = 2
c

['c', 2, 3, 4]

a

['a', 1, 3, 4]




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


Re: introspection question: get return type

2009-05-14 Thread Bruno Desthuilliers

[email protected] a écrit :

Hello,
I am wondering if it's possible to get the return value of a method
*without* calling it


Getting the return *value* without calling the function ? heck, that 
would be really helpful - we'd save quiet a lot on function call 
overhead and function execution time !-)



using introspection?

something like this, suppose I want to know the type of the return
value for the method "getsomething". Is it possible to get it without
actually calling 'getsomething'?


Oh, you meant the "return type" ? Nope, no way. It just doesn't make 
sense given Python's dynamic typing.




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


itertools question

2009-05-14 Thread Neal Becker
Is there any canned iterator adaptor that will 

transform:
in = [1,2,3]

into:
out = [(1,2,3,4), (5,6,7,8),...]

That is, each time next() is called, a tuple of the next N items is 
returned.


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


Re: python copy method alters type

2009-05-14 Thread Tim Chase

Zhenhai Zhang wrote:

Really weired; Here is my code:

a = ["a", 1, 3, 4]
print "a:", a
   
c = copy(a)


Where do you get this copy() function?

  t...@rubbish:~$ python2.5
  Python 2.5.4 (r254:67916, Feb 17 2009, 20:16:45)
  >>> help(copy)
  Traceback (most recent call last):
File "", line 1, in 
  NameError: name 'copy' is not defined

There is no "copy" in the python default namespace.  So you must 
have gotten it somewhere.  However, if you got it from the stdlib:


  >>> from copy import copy

  >>> a = ["a", 1,2,3]
  >>> b = copy(a)
  >>> b[0] = "b"
  >>> b[1] = 42
  >>> print b
  ['b', 42, 2, 3]

it would work as evidenced here.  Thus your code shows this is 
some custom copy() function which you didn't include in your 
message.  Therein lies your problem.


For shallow-copying lists, you'll usually find it written as

  b = a[:]

The "copy" module is more useful for complex data-structures and 
deep-copies.


-tkc



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


Re: Nimrod programming language

2009-05-14 Thread bearophileHUGS
[email protected]:
> Eventually the "rope" data structure (that the compiler uses heavily)
> will become a proper part of the library:

Ropes are a complex data structure, that it has some downsides too.
Python tries to keep its implementation too simple, this avoids lot of
troubles (and is one of the not much visible design ideas that have
determined the success of Python).



I've seen that in Nimrod the following names are the same one:
justaname JustAName just_a_name just__aname Justaname

So like Pascal (and unlike Python/C) it doesn't tell apart names just
on the base of their case (this is positive for newbie programmers,
they usually use the convention of natural written language where
'Hello' and 'hello' are the same word, they need some time to learn
the case-sensitivity).

Nimrod also seems to ignore underscores inside names, seeing them as
blanks. Some languages ignore underscores inside number literals, but
I have never seen a language ignoring them into names too.

In a class if you have a method like:
change_table_color
Isn't much good to also have a method named:
changeTableColor
Good programming practice tells you to avoid names that can be
confused (as 'chop' and 'chomp' in the string functions of D Phobos
lib). To avoid that most languages adopt a convention, so for example
in Python the change_table_color is the only used name, Java uses
changeTableColor, etc. Such conventions solve most of such problems.

So I don't know how much I like this design detail of Nimrod.

In Python you often see code like:
node = Node()

Sometimes in a case-sensitive language I'd like to have a compilation
warning switch that tells me that in a namespace there are two or more
names that differ only on character case or underscore count. This may
help avoid some bugs. A language may even enforce this as a syntax
error, so you have to write things like:
n = Node()
Or:
anode = Node()

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


Re: introspection question: get return type

2009-05-14 Thread bearophileHUGS
On the other hand, generally good programming practice suggests you to
write functions that have a constant return type. And in most programs
most functions are like this. This is why ShedSkin can indeed infer
the return type of functions in "good behaved" programs. To do this
ShedSkin uses a quite refined (and slow if written in Python) type
inference algorithm.

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


Re: itertools question

2009-05-14 Thread Glauco

Neal Becker ha scritto:
Is there any canned iterator adaptor that will 


transform:
in = [1,2,3]

into:
out = [(1,2,3,4), (5,6,7,8),...]

That is, each time next() is called, a tuple of the next N items is 
returned.





http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python



Gla

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


Re: PythonCard - My app stuck when button clicked

2009-05-14 Thread MRAB

daved170 wrote:

On May 13, 7:42 pm, Dave Angel  wrote:

daved170 wrote:

Hi there,
I'm newbie in pythonCard.
I have an application with 2 buttons : START , STOP
Start execute a while(1) loop that execute my calculations.
Stop suppose to raise a flag that will end that loop.
Whenever I pish the START button my GUI is stuck. the calculation
executes but I can't push the STOP button.
I added thread that START start a thread that execute my calculations.
I also added a Global variable that will hold the indication if the
loop should continue.
The problem now is that the thread ignore that variable and loop
forever.
Is there a simple way to make sure that the GUI won't stuck (without
threads)?
And if there isn't such way I would appriciet it very much if anyone
could post an example of how to make my thread read that variable
Thanks
Dave

I don't know PythonCard, but most GUI's are similar enough that the
concepts will work, even though the details differ.  I'll assume that
PythonCard has a traditional event loop, from which all events are
dispatched.

If your loop is fairly small, then you should keep it to one thread.  
Debugging it will usually be much easier.  The trick is to break the

task into pieces (each piece might be once around what is now a loop),
and invoke one piece each time the event loop empties.  I can't tell you
how to do that without seeing your loop, but it's not usually very hard.

Now, there is some way of POSTing an event to the event loop.  That puts
the event *after* all the events that are already there, but returns
control immediately.  So create a custom event, and POST it from the
START button's button-pressed event.  That will fire off one "loop" of
the special task, in other words, make one function call to your new
function.  Then at the end of the function, POST it again, unless the
STOP button has been pressed in the meantime.

An optimization for this is to use coroutines, which are usually done
with a generator.  It's much trickier to describe, but much easier to
accomplish.  Roughly, you'd take your existing loop, and put a yield
statement in it at appropriate place(s).  Then the custom event is
simply a call to the .next() function of that generator.

Now, threading isn't that tough either, depending on how much data is
being shared between the thread and the main program.  You say that
sharing a global flag isn't working, but it should.  So how about if you
show us some code, and somebody'll spot the trouble.  For example, is
the thread defined in the same module as the App?  Global only shares
between a single module.  Another reason globals might seem to fail is
if you tried to do mutual imports between two or more modules.  (A
imports B, which imports A).  Sometimes that fails in mysterious ways.

Make a simple (stripped) example of what you're trying, and we'll try to
find the problem.  Without concrete code, we end up with ambiguities
like the above usage of two different meanings for "the loop."- Hide quoted 
text -

- Show quoted text -


Thank's Dave,
Here my code, It's a very simple app. the Start button starts a TCP/IP
communication and the Stop should dtop it and kill the client.
I'll be thankful if you'll be able to spot my mistake.
Thanks again
Dave

#Global Variable
bStopLoop = False

#Global Function
def execute(sockObj):
   while(!bStopLoop):


That should be:

   while not bStopLoop:


  str = sockObj.recv(1024)
  tmpStr = "Hello " + str
  sockObj.send(tmpStr)

#Thread handle class
class myThread(threading.Thread):
   def __init__(self,sockObj):
  threading.Thread.__init__(self)
  bStopLoop = False


'bStopLoop' is local to __init__. Add:

  global bStopLoop


  self.sockObj = sockObj

   def run(self):
  execute(self.SockObj)

# GUI
class GUI(model.Background)

   def on_Start_mouseclick(self,event):
   try:
  event.target.enable = False
  event.target.redraw()
  self.components.Start.enable = False
  self.currThread = myThread(self.sockObj)
  self.currThread.Start()
  wx.SafeYield(self)
  self.components.Start.enable = True
   except:
  .

   def on_Stop_mouseclick(self,event):
  bStopLoop = True


'bStopLoop' is local to on_Stop_mouseclick. Add:

  global bStopLoop

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


Re: urllib2 slow for multiple requests

2009-05-14 Thread cgoldberg
> The problem is, that CentOS is running on the server and there is only
> 2.4 available. On wich version did you ran these tests?

I tested with Windows XP and Python 2.5.4.  I don't have a 2.4 setup I
can easily test with.

you can try httplib rather than urllib2.  httplib is slightly lower
level and is actually used inside urllib2 for transport.

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


Re: urllib2 slow for multiple requests

2009-05-14 Thread cgoldberg
> It might be, if the local server doesn't scale well enough to handle
> 100 concurrent requests.

true.. I didn't think of that.  I was assuming the client machine
wasn't resource constrained.  That would definitely lead to inaccurate
timings if that was the case.




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


Re: itertools question

2009-05-14 Thread Nick Craig-Wood
Neal Becker  wrote:
>  Is there any canned iterator adaptor that will 
> 
>  transform:
>  in = [1,2,3]
> 
>  into:
>  out = [(1,2,3,4), (5,6,7,8),...]
> 
>  That is, each time next() is called, a tuple of the next N items is 
>  returned.

This is my best effort... not using itertools as my brain doesn't seem
to work that way!

class Grouper(object):
def __init__(self, n, i):
self.n = n
self.i = iter(i)
def __iter__(self):
while True:
out = tuple(self.i.next() for _ in xrange(self.n))
if not out:
break
yield out

g = Grouper(5, xrange(20))
print list(g)

g = Grouper(4, xrange(19))
print list(g)

Which produces

[(0, 1, 2, 3, 4), (5, 6, 7, 8, 9), (10, 11, 12, 13, 14), (15, 16, 17, 18, 19)]
[(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11), (12, 13, 14, 15), (16, 17, 18)]


-- 
Nick Craig-Wood  -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nimrod programming language

2009-05-14 Thread MRAB

[email protected] wrote:

[email protected]:

Eventually the "rope" data structure (that the compiler uses heavily)
will become a proper part of the library:


Ropes are a complex data structure, that it has some downsides too.
Python tries to keep its implementation too simple, this avoids lot of
troubles (and is one of the not much visible design ideas that have
determined the success of Python).



I've seen that in Nimrod the following names are the same one:
justaname JustAName just_a_name just__aname Justaname

So like Pascal (and unlike Python/C) it doesn't tell apart names just
on the base of their case (this is positive for newbie programmers,
they usually use the convention of natural written language where
'Hello' and 'hello' are the same word, they need some time to learn
the case-sensitivity).

Nimrod also seems to ignore underscores inside names, seeing them as
blanks. Some languages ignore underscores inside number literals, but
I have never seen a language ignoring them into names too.

In a class if you have a method like:
change_table_color
Isn't much good to also have a method named:
changeTableColor
Good programming practice tells you to avoid names that can be
confused (as 'chop' and 'chomp' in the string functions of D Phobos
lib). To avoid that most languages adopt a convention, so for example
in Python the change_table_color is the only used name, Java uses
changeTableColor, etc. Such conventions solve most of such problems.

So I don't know how much I like this design detail of Nimrod.

In Python you often see code like:
node = Node()

Sometimes in a case-sensitive language I'd like to have a compilation
warning switch that tells me that in a namespace there are two or more
names that differ only on character case or underscore count. This may
help avoid some bugs. A language may even enforce this as a syntax
error, so you have to write things like:
n = Node()
Or:
anode = Node()


Does Nimrod accept non-ASCII names? If so, is "I" the same character as
"i"? In most languages using the Latin alphabet they would be, but in 
Turkish they wouldn't.

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


Re: itertools question

2009-05-14 Thread Peter Otten
Neal Becker wrote:

> Is there any canned iterator adaptor that will
> 
> transform:
> in = [1,2,3]
> 
> into:
> out = [(1,2,3,4), (5,6,7,8),...]
> 
> That is, each time next() is called, a tuple of the next N items is
> returned.

Depending on what you want to do with items that don't make a complete N-
tuple:

>>> from itertools import *
>>> items = range(10)

>>> list(izip(*(iter(items),)*3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]

>>> list(izip_longest(*(iter(items),)*3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]

>>> list(takewhile(bool, imap(tuple, starmap(islice, repeat((iter(items), 
3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9,)]

Peter

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


Re: matplotlib - overlaying plots.

2009-05-14 Thread Hyuga
On May 14, 7:41 am, Ant  wrote:
> Hi All,
>
> I am trying to get matplotlib to overlay a couple of graphs, but am
> getting nowhere. I originally thought that the following may work:
>
> >>> x = [1,2,3,4,5]
> >>> y = [2,4,6,8,10]
> >>> y2 = [1,4,9,16,25]
> >>> plot(x, y)
> >>> plot(x, y2)
>
> Now this works as desired, however, the actual case I have is more
> like this:
>
> >>> x = [1,2,3,4,5]
> >>> y = [2,4,6,8,10]
> >>> y2 = [.0001, .0002, .0003, .0004, .0005]
>
> Now the graph is useless, since the results are plotted on the same
> axis. What I really want is two different sets of axes, each scaled
> appropriately, but overlayed.
>
> The data I actually have, is one set of axes plotting distance against
> elevation, and a second plotting distance against speed. The former
> has (y-coord) units in the range 0-2000 ft and the latter 0 - 0.01
> miles/second. I want them on the same graph, so points can be easily
> correlated, but overlayed so that each line has a different scale on
> the y-axis. The closest I can get is to have two subplots, one above
> the other.
>
> Thanks in advance,
>
> Ant.

Just scale up the y-axis values of your second graph 200,000 times,
and specify in label that the y-axis for the second graph is velocity
scaled up 20x for comparison purposes.  Nothing wrong with that--
it's done all the time.

On the other hand, I just took a peek at the matplotlib example
gallery, which is very diverse, and it has an example that I think is
exactly what you're looking for: 
http://matplotlib.sourceforge.net/examples/api/two_scales.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: about Python doc reader

2009-05-14 Thread Tim Golden

norseman wrote:

I did try these.

Doc at once:
outputs two x'0D' and the file.  Then it appends x'0D' x'0D' x'0A' x'0D' 
x'0A' to end of file even though source file itself has no EOL.

( EOL is EndOfLine  aka newline )

That's  cr cr There are two blank lines at begining.
cr cr lf cr lfThere is no EOL in source
  Any idea what those are about?
One crlf is probably from python's print text, but the other?

The lines=
appends   [u'\r', u'\r', u"  to begining of output
and   \r"]x'0D'x'0A'   to the end even though there is no EOL in source.

output is understood:u'\r'  is Apple EOL
the crlf is probably from print lines.


Not clear what you're doing to get there. This is the (wrapped) 
output from my interpreter, using Word 2003. As you can see, new

doc: one "\r", nothing more.


Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 
bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more 
information.

>>> import win32com.client
>>> word = win32com.client.gencache.EnsureDispatch 
("Word.Application")

>>> doc = word.Documents.Add ()
>>> print repr (doc.Range ().Text)
u'\r'
>>>



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


Re: (Windows) Finding out which process has locked a file.

2009-05-14 Thread David Lyon

> In message <787d6072-3381-40bd-
> [email protected]>, CinnamonDonkey wrote:
> 
>> I have a script running which occa[s]ionally fails because it is trying
>> to delete a file in use by another process. When this happens I want
>> it to log which process has the lock.

Maybe there is something on sysinternals.com that you can download
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PythonCard - My app stuck when button clicked

2009-05-14 Thread daved170
On May 14, 2:37 pm, Dave Angel  wrote:
> daved170 wrote:
> > On May 13, 7:42 pm, Dave Angel  wrote:
>
> >> daved170 wrote:
>
> >>> Hi there,
> >>> I'm newbie in pythonCard.
> >>> I have an application with 2 buttons : START , STOP
> >>> Start execute a while(1) loop that execute my calculations.
> >>> Stop suppose to raise a flag that will end that loop.
>
> >>> Whenever I pish the START button my GUI is stuck. the calculation
> >>> executes but I can't push the STOP button.
>
> >>> I added thread that START start a thread that execute my calculations.
> >>> I also added a Global variable that will hold the indication if the
> >>> loop should continue.
> >>> The problem now is that the thread ignore that variable and loop
> >>> forever.
>
> >>> Is there a simple way to make sure that the GUI won't stuck (without
> >>> threads)?
> >>> And if there isn't such way I would appriciet it very much if anyone
> >>> could post an example of how to make my thread read that variable
> >>> Thanks
> >>> Dave
>
> >> I don't know PythonCard, but most GUI's are similar enough that the
> >> concepts will work, even though the details differ.  I'll assume that
> >> PythonCard has a traditional event loop, from which all events are
> >> dispatched.
>
> >> If your loop is fairly small, then you should keep it to one thread.  
> >> Debugging it will usually be much easier.  The trick is to break the
> >> task into pieces (each piece might be once around what is now a loop),
> >> and invoke one piece each time the event loop empties.  I can't tell you
> >> how to do that without seeing your loop, but it's not usually very hard.
>
> >> Now, there is some way of POSTing an event to the event loop.  That puts
> >> the event *after* all the events that are already there, but returns
> >> control immediately.  So create a custom event, and POST it from the
> >> START button's button-pressed event.  That will fire off one "loop" of
> >> the special task, in other words, make one function call to your new
> >> function.  Then at the end of the function, POST it again, unless the
> >> STOP button has been pressed in the meantime.
>
> >> An optimization for this is to use coroutines, which are usually done
> >> with a generator.  It's much trickier to describe, but much easier to
> >> accomplish.  Roughly, you'd take your existing loop, and put a yield
> >> statement in it at appropriate place(s).  Then the custom event is
> >> simply a call to the .next() function of that generator.
>
> >> Now, threading isn't that tough either, depending on how much data is
> >> being shared between the thread and the main program.  You say that
> >> sharing a global flag isn't working, but it should.  So how about if you
> >> show us some code, and somebody'll spot the trouble.  For example, is
> >> the thread defined in the same module as the App?  Global only shares
> >> between a single module.  Another reason globals might seem to fail is
> >> if you tried to do mutual imports between two or more modules.  (A
> >> imports B, which imports A).  Sometimes that fails in mysterious ways.
>
> >> Make a simple (stripped) example of what you're trying, and we'll try to
> >> find the problem.  Without concrete code, we end up with ambiguities
> >> like the above usage of two different meanings for "the loop."- Hide 
> >> quoted text -
>
> >> - Show quoted text -
>
> > Thank's Dave,
> > Here my code, It's a very simple app. the Start button starts a TCP/IP
> > communication and the Stop should dtop it and kill the client.
> > I'll be thankful if you'll be able to spot my mistake.
> > Thanks again
> > Dave
>
> > #Global Variable
> > bStopLoop =alse
>
> > #Global Function
> > def execute(sockObj):
> >    while(!bStopLoop):
> >       str =ockObj.recv(1024)
> >       tmpStr =Hello " + str
> >       sockObj.send(tmpStr)
>
> > #Thread handle class
> > class myThread(threading.Thread):
> >    def __init__(self,sockObj):
> >       threading.Thread.__init__(self)
> >       bStopLoop =alse
> >       self.sockObj =ockObj
>
> >    def run(self):
> >       execute(self.SockObj)
>
> > # GUI
> > class GUI(model.Background)
>
> >    def on_Start_mouseclick(self,event):
> >    try:
> >       event.target.enable =alse
> >       event.target.redraw()
> >       self.components.Start.enable =alse
> >       self.currThread =yThread(self.sockObj)
> >       self.currThread.Start()
> >       wx.SafeYield(self)
> >       self.components.Start.enable =rue
> >    except:
> >       .
>
> >    def on_Stop_mouseclick(self,event):
> >       bStopLoop =rue
>
> In the two methods that try to change bStopLoop, you don't declare it
> global.  Add the line "global bStopLoop"  to beginning of both
>
> on_Start_mouseclick() and on_Stop_mouseclick(), and (my preference) to 
> function execute()
>
> The semantics of global versus local variables for non-nested 
> functions/methods is roughly:   if a function or method assigns to a name, 
> it's taken to be a local, unless it's explicitly dec

Re: itertools question

2009-05-14 Thread Lie Ryan

Neal Becker wrote:
Is there any canned iterator adaptor that will 


transform:
in = [1,2,3]

into:
out = [(1,2,3,4), (5,6,7,8),...]

That is, each time next() is called, a tuple of the next N items is 
returned.







An option, might be better since it handles infinite list correctly:

>>> lst = [1, 4, 2, 5, 7, 3, 2, 5, 7, 3, 2, 6, 3, 2, 6, 8, 4, 2]
>>> d = 4
>>> for x in itertools.groupby(enumerate(lst), lambda x: x[0] // d):
... print(list(x[1]))
...
[(0, 1), (1, 4), (2, 2), (3, 5)]
[(4, 7), (5, 3), (6, 2), (7, 5)]
[(8, 7), (9, 3), (10, 2), (11, 6)]
[(12, 3), (13, 2), (14, 6), (15, 8)]
[(16, 4), (17, 2)]
>>> [list(x[1]) for x in itertools.groupby(enumerate(lst), lambda x: 
x[0] // d)]
[[(0, 1), (1, 4), (2, 2), (3, 5)], [(4, 7), (5, 3), (6, 2), (7, 5)], 
[(8, 7), (9, 3), (10, 2), (11, 6)], [(12, 3), (13, 2), (14, 6), (15, 
8)], [(16, 4), (17, 2)]]


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


Re: matplotlib - overlaying plots.

2009-05-14 Thread Ant
On May 14, 3:52 pm, Hyuga  wrote:
...
> On the other hand, I just took a peek at the matplotlib example
> gallery, which is very diverse, and it has an example that I think is
> exactly what you're looking 
> for:http://matplotlib.sourceforge.net/examples/api/two_scales.html

Superb - spot on. Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Toronto PyCamp 2009

2009-05-14 Thread Chris Calloway
For beginners, this ultra-low-cost Python Boot Camp developed by the 
Triangle Zope and Python Users Group makes you productive so you can get 
your work done quickly. PyCamp emphasizes the features which make Python 
a simpler and more efficient language. Following along by example speeds 
your learning process in a modern high-tech classroom. Become a 
self-sufficient Python developer in just five days at PyCamp!


The University or Toronto Department of Physics brings PyCamp to 
Toronto, July 13-17, 2009.


Register today at http://trizpug.org/boot-camp/pycamp-toronto-2009/

--
Sincerely,

Chris Calloway
http://www.secoora.org
office: 332 Chapman Hall   phone: (919) 599-3530
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599



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


Assigning a list to a key of a dict

2009-05-14 Thread Wells
Why can't I do this?

teams = { "SEA": "Seattle Mariners" }
for team, name in teams.items():
teams[team]["roster"] = ["player1", "player2"]

I get an error:

Traceback (most recent call last):
  File "./gamelogs.py", line 53, in 
teams[team]["roster"] = ["player1", "player2"]
TypeError: 'str' object does not support item assignment

You can see that I am trying to make a key called "roster" for each
team item in the dictionary, which is a list of players.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: itertools question

2009-05-14 Thread Ned Deily
In article ,
 Neal Becker  wrote:
> Is there any canned iterator adaptor that will 
> 
> transform:
> in = [1,2,3]
> 
> into:
> out = [(1,2,3,4), (5,6,7,8),...]
> 
> That is, each time next() is called, a tuple of the next N items is 
> returned.

This topic was discussed here just a few days ago:



-- 
 Ned Deily,
 [email protected]

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


Re: How to get all named args in a dict?

2009-05-14 Thread kj
In  Terry Reedy 
 writes:

>kj wrote:
>> 
>> Suppose I have the following:
>> 
>> def foo(x=None, y=None, z=None):
>> d = {"x": x, "y": y, "z": z}
>> return bar(d)
>> 
>> I.e. foo takes a whole bunch of named arguments and ends up calling
>> a function bar that takes a single dictionary as argument, and this
>> dictionary has the same keys as in foo's signature, so to speak.
>> 
>> Is there some builtin variable that would be the same as the variable
>> d, and would thus obviate the need to explicitly bind d?

>Use the built-in function locals()
> >>> def f(a,b):
>   x=locals()
>   print(x)

> >>> f(1,2)
>{'a': 1, 'b': 2}

That's *exactly* what I was looking for.  Thanks!

kynn


-- 
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Assigning a list to a key of a dict

2009-05-14 Thread Diez B. Roggisch
Wells wrote:

> Why can't I do this?
> 
> teams = { "SEA": "Seattle Mariners" }
> for team, name in teams.items():
> teams[team]["roster"] = ["player1", "player2"]
> 
> I get an error:
> 
> Traceback (most recent call last):
>   File "./gamelogs.py", line 53, in 
> teams[team]["roster"] = ["player1", "player2"]
> TypeError: 'str' object does not support item assignment
> 
> You can see that I am trying to make a key called "roster" for each
> team item in the dictionary, which is a list of players.

This is not a list as key, it's a nested dictionary. There are several
approaches to this:

 - make your keys tuples, like this:

>>> teams[(team, "roster") = [...]

 - use setedfault:

>>> teams.setdefault(team, {})["roster"] = ['player1']

 - defaultdict

>>> from collections import *
>>> defaultdict

>>> teams = defaultdict(dict)
>>> teams["team"]["roster"] = ["player1"]
>>> teams
defaultdict(, {'team': {'roster': ['player1']}})
>>>   

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


Re: When *don't* I use 'self' in classes?

2009-05-14 Thread Adam Gaskins
Thanks a lot everyone! This really cleared it up for me! :)

"Adam Gaskins"  wrote in message 
news:[email protected]...
>I am a bit confused as too when, if ever, it is not appropriate to prepend 
>'self' to objects in a class. All of the examples of how to use 'self' that 
>I find seem to be short and very simple (as examples tent to be). I 
>appologize if I am asking an ignorant question here, but I want to get off 
>on the right foot. Here's an example of what I mean:
>
> import serial
> class foo:
>def __init(self, comport):
>self.comport = comport
>self.baudrate = 9600 #default
>self.ser = serial
>try:
>self.ser.Serial()
>self.ser.baudrate = self.baudrate
>self.ser.open()
>except:
>print 'Serial port could not be opened'
>
> === OR ===
> import serial
> class foo:
>def __init(self, comport):
>self.comport = comport
>self.baudrate = 9600 #default
>try:
>ser = serial.Serial()
>ser.baudrate = self.baudrate
>ser.open()
>except:
>print 'Serial port could not be opened'
>
> There may be a typo in here, this is just a random example similar to 
> something I'm working with, but which one of these are more 'proper'? If I 
> am importing a library do I still prepend it's object with self when I use 
> it in my class? I suppose my question is just basically... when do you NOT 
> prepent an object in a class with 'self'?
>
> I'm not even sure I'm using the term 'object' correctly here. Feel free to 
> set me straight, but I hope my example makes it clear what I am asking.
>
> Thanks a lot, this ng has already been super helpful as I take my 
> crash-course in to python! :P
> 


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


capture stdout and stderror from within a Windows Service?

2009-05-14 Thread Chris Curvey
I'm trying to get this invocation right, and it is escaping me.  How
can I capture the stdout and stderr if I launch a subprocess using
subprocess.check_call()?  The twist here is that the call is running
from within a Windows service.

I've tried:

check_call("mycmd.exe", stdout=subprocess.PIPE)  [raises an exception
"An integer is required"]

check_call("mycmd.exe", stdout=file("c:\\temp\\foobar.txt", "w"))
[raises an exception "An integer is required"]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: introspection question: get return type

2009-05-14 Thread Marco Mariani

Bruno Desthuilliers wrote:

Oh, you meant the "return type" ? Nope, no way. It just doesn't make 
sense given Python's dynamic typing.


I thought that the OP was writing a tool to document not-very-dynamic code.

Unless he's really trying to write in Nohtyp, the language where value 
types are more important than values ;)


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


Re: itertools question

2009-05-14 Thread Chris Rebert
On Thu, May 14, 2009 at 8:53 AM, Ned Deily  wrote:
> In article ,
>  Neal Becker  wrote:
>> Is there any canned iterator adaptor that will
>>
>> transform:
>> in = [1,2,3]
>>
>> into:
>> out = [(1,2,3,4), (5,6,7,8),...]
>>
>> That is, each time next() is called, a tuple of the next N items is
>> returned.
>
> This topic was discussed here just a few days ago:
>
> 

They really should just add grouper() to itertools rather than leaving
it as a recipe. People keep asking for it so often...

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


Re: Assigning a list to a key of a dict

2009-05-14 Thread Chris Rebert
On Thu, May 14, 2009 at 8:45 AM, Wells  wrote:
> Why can't I do this?
>
> teams = { "SEA": "Seattle Mariners" }
> for team, name in teams.items():
>        teams[team]["roster"] = ["player1", "player2"]
> I get an error:
>
> Traceback (most recent call last):
>  File "./gamelogs.py", line 53, in 
>    teams[team]["roster"] = ["player1", "player2"]
> TypeError: 'str' object does not support item assignment

teams - a dict of str to str
teams[team] - a string (specifically, "Seattle Mariners" in this case)
teams[team]["roster"] - um, you can't subscript a string by another
string; you can subscript it only by integer indices

> You can see that I am trying to make a key called "roster" for each
> team item in the dictionary, which is a list of players.

I'd say you need to restructure your data structure by introducing
another level of dictionaries:

teams = { "SEA": {"full_name":"Seattle Mariners"} }
for team, name in teams.items():
teams[team]["roster"] = ["player1", "player2"]
print teams
#output: {'SEA': {'full_name': 'Seattle Mariners', 'roster':
['player1', 'player2']}}

Of course, it would probably be nicer if you did this using objects
(e.g. define a Team class and have `teams` be a dict of str to Team.

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


Re: Assigning a list to a key of a dict

2009-05-14 Thread Gary Herron

Wells wrote:

Why can't I do this?

teams = { "SEA": "Seattle Mariners" }
for team, name in teams.items():
teams[team]["roster"] = ["player1", "player2"]
  


Because,
 team will be "SEA",
so 
 teams[team] will be  "Seattle Mariners"

and
 "Seattle Mariners"["roster"] makes no sense.



Gary Herron



I get an error:

Traceback (most recent call last):
  File "./gamelogs.py", line 53, in 
teams[team]["roster"] = ["player1", "player2"]
TypeError: 'str' object does not support item assignment

You can see that I am trying to make a key called "roster" for each
team item in the dictionary, which is a list of players.
  


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


Re: capture stdout and stderror from within a Windows Service?

2009-05-14 Thread Chris Rebert
On Thu, May 14, 2009 at 8:57 AM, Chris Curvey  wrote:
> I'm trying to get this invocation right, and it is escaping me.  How
> can I capture the stdout and stderr if I launch a subprocess using
> subprocess.check_call()?  The twist here is that the call is running
> from within a Windows service.
>
> I've tried:
>
> check_call("mycmd.exe", stdout=subprocess.PIPE)  [raises an exception
> "An integer is required"]
>
> check_call("mycmd.exe", stdout=file("c:\\temp\\foobar.txt", "w"))
> [raises an exception "An integer is required"]

Providing the full exception Tracebacks would be highly recommended.

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


Re: matplotlib - overlaying plots.

2009-05-14 Thread norseman

Ant wrote:

Hi All,

I am trying to get matplotlib to overlay a couple of graphs, but am
getting nowhere. I originally thought that the following may work:


x = [1,2,3,4,5]
y = [2,4,6,8,10]
y2 = [1,4,9,16,25]



plot(x, y)
plot(x, y2)


Now this works as desired, however, the actual case I have is more
like this:


x = [1,2,3,4,5]
y = [2,4,6,8,10]
y2 = [.0001, .0002, .0003, .0004, .0005]


Now the graph is useless, since the results are plotted on the same
axis. What I really want is two different sets of axes, each scaled
appropriately, but overlayed.

The data I actually have, is one set of axes plotting distance against
elevation, and a second plotting distance against speed. The former
has (y-coord) units in the range 0-2000 ft and the latter 0 - 0.01
miles/second. I want them on the same graph, so points can be easily
correlated, but overlayed so that each line has a different scale on
the y-axis. The closest I can get is to have two subplots, one above
the other.

Thanks in advance,

Ant.



==
Use scalers to 'sync' the axis (x or y or both on the page)
The 'scales' along the axis need to match or you get your problem.

You know - like trying to do 1:1 but one is meters and the other feet.
That case needs two different graphs (or CAD drawings) each with its own 
legend.  The scales are not the same.  ie... 100meters is not 100feet

By scalling to same units/distance on graph you get overlay ability.

my first thought on your 0-2000ft and miles/sec is to convert miles to 
feet and multiply time by enough to be integer values and see if you get 
a better visual


one graph means one set of units per axis
 or
plot each and scale one to the other
  (in CAD it's a case of meters/3.28083_ to reduce to feet units
  .3048 * meters if using International scaler
  meters/3.2808(infinitely repeating 3s) is US Standard.
  The difference cost us a mars rover.
  You don't seem to be metric vs US but you do have miss matched units.
  miles vs feet, time vs (feet)elevation
  or whatever the units distance/elevation may be.
  )
target_size / 2nd_graph unit => scaler for that axis (mostly)
  since the units are not completely the same type you may need
  to experiment.
same units would be  time time  hours days seconds
 linear linear  meter feet mile
 angular angularmils degrees rads
and so forth.

HTH


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


Re: capture stdout and stderror from within a Windows Service?

2009-05-14 Thread Grant Edwards
On 2009-05-14, Chris Curvey  wrote:
> I'm trying to get this invocation right, and it is escaping me.  How
> can I capture the stdout and stderr if I launch a subprocess using
> subprocess.check_call()?  The twist here is that the call is running
> from within a Windows service.
>
> I've tried:
>
> check_call("mycmd.exe", stdout=subprocess.PIPE)  [raises an exception
> "An integer is required"]
>
> check_call("mycmd.exe", stdout=file("c:\\temp\\foobar.txt", "w"))
> [raises an exception "An integer is required"]

An educated guess...

By default, subprocess will use the existing stdin, stdout, and
stderr filedescriptors for the child process. Since services
presumably don't have valid file descriptors for stdin, stdout,
and stderr, you probably have to tell subprocess to use pipes
for all three.  Otherwise, it will default to using the invalid
or nonexistant file descriptors of the parent.

[If you reply, I proably won't see it.  All posts from google
groups are plonked by my newsreader configuration.  It was
somewhat of a fluke that I came across your posting.]

-- 
Grant Edwards   grante Yow! On the road, ZIPPY
  at   is a pinhead without a
   visi.compurpose, but never without
   a POINT.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: about Python doc reader

2009-05-14 Thread norseman

Tim Golden wrote:

norseman wrote:

I did try these.

Doc at once:
outputs two x'0D' and the file.  Then it appends x'0D' x'0D' x'0A' 
x'0D' x'0A' to end of file even though source file itself has no EOL.

( EOL is EndOfLine  aka newline )

That's  cr cr There are two blank lines at begining.
cr cr lf cr lfThere is no EOL in source
  Any idea what those are about?
One crlf is probably from python's print text, but the other?

The lines=
appends   [u'\r', u'\r', u"  to begining of output
and   \r"]x'0D'x'0A'   to the end even though there is no EOL in source.

output is understood:u'\r'  is Apple EOL
the crlf is probably from print lines.


Not clear what you're doing to get there. This is the (wrapped) output 
from my interpreter, using Word 2003. As you can see, new

doc: one "\r", nothing more.


Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit 
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
 >>> import win32com.client
 >>> word = win32com.client.gencache.EnsureDispatch ("Word.Application")
 >>> doc = word.Documents.Add ()
 >>> print repr (doc.Range ().Text)
u'\r'
 >>>




==
The original "do it this way" snippets were:

import win32com.client

doc = win32com.client.GetObject ("c:/temp/temp.doc")
text = doc.Range ().Text



Note that this will give you a unicode object with \r line-delimiters.
You could read para by para if that were more useful:


import win32com.client

doc = win32com.client.GetObject ("c:/temp/temp.doc")
lines = [p.Range () for p in doc.Paragraphs]




and I added:

print textafter "text =" line above

print lines   after "lines =" line above

then ran file using   python test.py >letmesee
followed by viewing letmesee in hex



Steve



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


Re: urllib2 slow for multiple requests

2009-05-14 Thread Richard Brodie

"Tomas Svarovsky"  wrote in message 
news:[email protected]...

> This is a good point, but then it would manifest regardless of the
> language used AFAIK. And this is not the case, ruby and php
> implementations are working quite fine.

What I meant was: not reading the data and leaving the connection
open is going to force the server to handle all 100 requests concurrently.
I'm guessing that's not what your other implementations do.
What happens to the timing if you call response.read(), response.close() ? 


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


Re: Odd list behavior

2009-05-14 Thread norseman

Rhodri James wrote:

On Wed, 13 May 2009 23:08:26 +0100, norseman  wrote:


Evan Kroske wrote:
I'm working on a simple file processing utility, and I encountered a 
weird error. If I try to get the first element of a list I'm 
splitting from a string, I get an error:

 key = string.split()[0]
Error!
 However, I can slice the list like normal, but that gives me a 
one-element-long list:

 key = string.split()[:1]
Success!
 Finally, the operation works perfectly if I initialize the list 
beforehand:

 list = string.split()
key = list[0]
Success!
 Why does this happen?




==
Take a look at the  split() command.

I think you will find you need one var on the left side for each piece 
on the right.


Given that he's immediately indexing the split results, that's irrelevant.
There's no point in even guessing with out the traceback.



"...the first element of a list..."
"key = string.split()[0]"
if the list is a list of tuples the error message is correct.
same for a list of key:value pairs
he will need one var on left for each piece of [0]
 k,v=  list.split(key:value)??!!


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


Re: capture stdout and stderror from within a Windows Service?

2009-05-14 Thread norseman

Chris Curvey wrote:

I'm trying to get this invocation right, and it is escaping me.  How
can I capture the stdout and stderr if I launch a subprocess using
subprocess.check_call()?  The twist here is that the call is running
from within a Windows service.

I've tried:

check_call("mycmd.exe", stdout=subprocess.PIPE)  [raises an exception
"An integer is required"]


mycmd.exe isn't open (running). the mycmd.exe is supposed to be a fn.
How did you start it?



check_call("mycmd.exe", stdout=file("c:\\temp\\foobar.txt", "w"))
[raises an exception "An integer is required"]

==
I think you need to run the .exe from your .py using the subprocess 
module's commands and hook in at that time to stdin, stdout, 

get the fn and use check_call() to see if .exe has something to say.

Check subprocess's help/man and so forth.

I know that if you start a program via os.Popen2's popen3 things work as 
expected.  How you would redirect I/O in an arbitrary already running 
program in Windows is a good question.



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


Re: DOM implementation

2009-05-14 Thread Emanuele D'Arrigo
Thank you Paul for your reply!

I'm looking into pxdom right now and it looks very good and useful!

Thank you again!

Manu

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


Re: itertools question

2009-05-14 Thread Lie Ryan

Chris Rebert wrote:

They really should just add grouper() to itertools rather than leaving
it as a recipe. People keep asking for it so often...


I've just added it to the issue tracker: http://bugs.python.org/issue6021
--
http://mail.python.org/mailman/listinfo/python-list


C API: how to replace python number object in place?

2009-05-14 Thread Stephen Vavasis
If x is a C variable of type PyObject*, and I happen to know already that 
the object is of a numeric type, say int, is there a way to change the 
value of x in place to a different number?  In the C/API documentation I 
found routines to increment or decrement it in place, but I didn't find a 
routine to simply replace its value by a different value.  (I suppose I 
could change it to the new value via an increment or decrement, but this 
is ugly as well as being susceptible to overflow problems and roundoff 
errors in the case of floats.)

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


Re: putting date strings in order

2009-05-14 Thread noydb
On May 12, 12:26 pm, John Machin  wrote:
> On May 13, 1:58 am, Jaime Fernandez del Rio 
> wrote:
>
>
>
>
>
> > On Tue, May 12, 2009 at 5:02 PM, MRAB  wrote:
> > > John Machin wrote:
>
> > >> MRAB  mrabarnett.plus.com> writes:
>
> > >>> Sort the list, passing a function as the 'key' argument. The function
> > >>> should return an integer for the month, eg 0 for 'jan', 1 for 'feb'. If
> > >>> you want to have a different start month then add
>
> > >> and if you don't like what that produces, try subtract :-)
>
> > > Oops!
>
> > >>> the appropriate
> > >>> integer for that month (eg 0 for 'jan', 1 for 'feb') and then modulo 12
> > >>> to make it wrap around (there are only 12 months in a year), returning
> > >>> the result.
>
> > > Actually, subtract the start month, add 12, and then modulo 12.
>
> > Both on my Linux and my Windows pythons, modulos of negative numbers
> > are properly taken, returning always the correct positive number
> > between 0 and 11. I seem to recall, from my distant past, that Perl
> > took pride on this being a language feature. Anyone knows if that is
> > not the case with python, and so not adding 12 before taking the
> > modulo could result in wrong results in some implementations?
>
> If that happens, it's a 
> bug.http://docs.python.org/reference/expressions.html#binary-arithmetic-o...
>
> If you look at function i_divmod() in the 2.x branch's Objects/
> intobject.c, you'll be reassured to see that it doesn't just take
> whatever C serves up :-)- Hide quoted text -
>
> - Show quoted text -

Thanks to those who provided suggestions.  I ended up using code
similar to what Jaime provided above first -- truly eloquent and
simple, especially compared to my original thoughts of several messy
loops.  I knew it could be done way better.  Thanks very much Jaime!!
That was a good learning experience for me.

fairly finished portion of code:

ordered_raster_list = []

pRasters = gp.ListRasters("precip_*", "All") # an enumeration object,
arcgis method
pRast = pRasters.next()
while pRast:
##month = pRast[-3:]
##print month
print pRast
ordered_raster_list.append(pRast)
pRast = pRasters.next()


print ordered_raster_list #unordered at this point

# create a dictionary dictating the order of the the precip_
rasters
monthsD = {"precip_jan" : 1, "precip_feb" : 2, "precip_mar" : 3,
"precip_apr" : 4, "precip_may" : 5, "precip_jun" : 6,
   "precip_jul" : 7, "precip_aug" : 8, "precip_sep" : 9,
"precip_oct" : 10, "precip_nov" : 11, "precip_dec" : 12}

# sort the list based on the dictionary
ordered_raster_list.sort(None, lambda x : monthsD[x])

print ordered_raster_list #ordered

start = 2 #user to define, starting month

ordered_raster_list = ordered_raster_list[start - 1:] +
ordered_raster_list[:start - 1]

print ordered_raster_list #ordered but starting in the middle, feb in
this case, ending with jan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: putting date strings in order

2009-05-14 Thread Peter Otten
noydb wrote:

> On May 12, 12:26 pm, John Machin  wrote:
>> On May 13, 1:58 am, Jaime Fernandez del Rio 
>> wrote:
>>
>>
>>
>>
>>
>> > On Tue, May 12, 2009 at 5:02 PM, MRAB 
>> > wrote:
>> > > John Machin wrote:
>>
>> > >> MRAB  mrabarnett.plus.com> writes:
>>
>> > >>> Sort the list, passing a function as the 'key' argument. The
>> > >>> function should return an integer for the month, eg 0 for 'jan', 1
>> > >>> for 'feb'. If you want to have a different start month then add
>>
>> > >> and if you don't like what that produces, try subtract :-)
>>
>> > > Oops!
>>
>> > >>> the appropriate
>> > >>> integer for that month (eg 0 for 'jan', 1 for 'feb') and then
>> > >>> modulo 12 to make it wrap around (there are only 12 months in a
>> > >>> year), returning the result.
>>
>> > > Actually, subtract the start month, add 12, and then modulo 12.
>>
>> > Both on my Linux and my Windows pythons, modulos of negative numbers
>> > are properly taken, returning always the correct positive number
>> > between 0 and 11. I seem to recall, from my distant past, that Perl
>> > took pride on this being a language feature. Anyone knows if that is
>> > not the case with python, and so not adding 12 before taking the
>> > modulo could result in wrong results in some implementations?
>>
>> If that happens, it's a
>> bug.http://docs.python.org/reference/expressions.html#binary-arithmetic-
o...
>>
>> If you look at function i_divmod() in the 2.x branch's Objects/
>> intobject.c, you'll be reassured to see that it doesn't just take
>> whatever C serves up :-)- Hide quoted text -
>>
>> - Show quoted text -
> 
> Thanks to those who provided suggestions.  I ended up using code
> similar to what Jaime provided above first -- truly eloquent and
> simple, especially compared to my original thoughts of several messy
> loops.  I knew it could be done way better.  Thanks very much Jaime!!
> That was a good learning experience for me.
> 
> fairly finished portion of code:
> 
> ordered_raster_list = []
> 
> pRasters = gp.ListRasters("precip_*", "All") # an enumeration object,
> arcgis method
> pRast = pRasters.next()
> while pRast:
> ##month = pRast[-3:]
> ##print month
> print pRast
> ordered_raster_list.append(pRast)
> pRast = pRasters.next()
> 
> 
> print ordered_raster_list #unordered at this point
> 
> # create a dictionary dictating the order of the the precip_
> rasters
> monthsD = {"precip_jan" : 1, "precip_feb" : 2, "precip_mar" : 3,
> "precip_apr" : 4, "precip_may" : 5, "precip_jun" : 6,
>"precip_jul" : 7, "precip_aug" : 8, "precip_sep" : 9,
> "precip_oct" : 10, "precip_nov" : 11, "precip_dec" : 12}
> 
> # sort the list based on the dictionary
> ordered_raster_list.sort(None, lambda x : monthsD[x])
> 
> print ordered_raster_list #ordered
> 
> start = 2 #user to define, starting month
> 
> ordered_raster_list = ordered_raster_list[start - 1:] +
> ordered_raster_list[:start - 1]
> 
> print ordered_raster_list #ordered but starting in the middle, feb in
> this case, ending with jan

Hm, if ordered_raster_list is guaranteed to contain one string item for 
every month the above can be simplified to

months = [
'precip_jan', 'precip_feb', 'precip_mar', 'precip_apr', 
'precip_may', 'precip_jun', 'precip_jul', 'precip_aug', 
'precip_sep', 'precip_oct', 'precip_nov', 'precip_dec']

start = 2
ordered_raster_list = months[start-1:] + months[:start-1]

print ordered_raster_list

What am I missing?

Peter

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


Re: how to consume .NET webservice

2009-05-14 Thread Дамјан Георгиевски
>> OpenOfficeXML document format AKA ODF? ;)
> 
> No...Office Open XML, which is used in Microsoft Office 2007 and which
> Microsoft rammed through the ISO:
> http://en.wikipedia.org/wiki/Office_Open_XML

Even worse, Microsoft Office 2007 doesn't even implement the ISO 
standard for Open XML.

-- 
дамјан ( http://softver.org.mk/damjan/ )

Our national drug is alcohol,
we tend to regard the use any other drug with special horror.
-- William S. Burroughs


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


Re: C API: how to replace python number object in place?

2009-05-14 Thread Benjamin Peterson
Stephen Vavasis  cpu111.math.uwaterloo.ca> writes:

> 
> If x is a C variable of type PyObject*, and I happen to know already that 
> the object is of a numeric type, say int, is there a way to change the 
> value of x in place to a different number?  In the C/API documentation I 
> found routines to increment or decrement it in place, but I didn't find a 
> routine to simply replace its value by a different value.  (I suppose I 
> could change it to the new value via an increment or decrement, but this 
> is ugly as well as being susceptible to overflow problems and roundoff 
> errors in the case of floats.)

Even in the C-API, Python ints and longs are immutable. You can convert it to a
C int and work with it, otherwise you have to use the APIs which create new
objects: PyNumber_Add etc...



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


Re: How to get all named args in a dict?

2009-05-14 Thread Dave Angel



kj wrote:

In  Terry Reedy 
 writes:

  

kj wrote:


Suppose I have the following:

def foo(x=None, y=None, z=None):
d = {"x": x, "y": y, "z": z}
return bar(d)

I.e. foo takes a whole bunch of named arguments and ends up calling
a function bar that takes a single dictionary as argument, and this
dictionary has the same keys as in foo's signature, so to speak.

Is there some builtin variable that would be the same as the variable
d, and would thus obviate the need to explicitly bind d?
  


  

Use the built-in function locals()


def f(a,b):
  

x=locals()
print(x)



  

f(1,2)
  

{'a': 1, 'b': 2}



That's *exactly* what I was looking for.  Thanks!

kynn


  

You already had a better answer from Chris Rebert:

def foo(**kwargs):
   return bar(kwargs)

kwargs at this point is exactly a dictionary of the named arguments to foo.

Because if you try to do anything in this function, you'll probably be 
adding more local variables. And then they'd be passed to bar as well.



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


OS independent file associate ?

2009-05-14 Thread Stef Mientki

hello,

I would like to make my programs available under the "standard" OS's, 
like Windows, Linux  (,Mac)
One of the problems I encounter, is launching of files through their 
file associates (probably a windows only terminology ;-)
Now I can detect the OS, but only the main OS and not e.g. Ubuntu / 
Gnome or whatever I've to detect.
Through trial and error I found a working mechanism under Ubuntu, but as 
I have to specify "gnome", I doubt this will work under other Linux systems.


any good solutions available ?

thanks,
Stef Mientki

   import subprocess
   CHM = '../numpy.chm'

   # works under Ubuntu
   subprocess.Popen( "gnome-open " + CHM , shell = True )

   # doesn't work under Ubuntu
   # (the list should be converted to a number of arguments,
   #but that doesn't seem to work under Ubuntu.
   subprocess.Popen( [ "gnome-open" , CHM] ,shell = True )

   # works under Windows
   subprocess.Popen( CHM , shell = True )

   # works better under windows
   win32help.HtmlHelp ( Win32_Viewer,
str(CHM),
win32help.HH_DISPLAY_INDEX,
str ( keyword ) )

  
--

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


Re: introspection question: get return type

2009-05-14 Thread Bruno Desthuilliers

Marco Mariani a écrit :

Bruno Desthuilliers wrote:

Oh, you meant the "return type" ? Nope, no way. It just doesn't make 
sense given Python's dynamic typing.


I thought that the OP was writing a tool to document not-very-dynamic code.




Unless he's really trying to write in Nohtyp,


You meant "Notype" ?-)

the language where value 
types are more important than values ;)


Hence it's name !-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: When *don't* I use 'self' in classes?

2009-05-14 Thread Bruno Desthuilliers

Tim Chase a écrit :
(snip)



 try:
   self.ser = Serial()
   self.ser.baudrate = DEFAULT_BAUD
   self.ser.open()
 except SomeSpecificException:
   print "Fail!"



Please make it:


  try:
self.ser = Serial()
self.ser.baudrate = DEFAULT_BAUD
self.ser.open()
  except SomeSpecificException, e:
print "Fail! reason : %s" % e
--
http://mail.python.org/mailman/listinfo/python-list


How to get the formal args of a function object?

2009-05-14 Thread kj


Suppose that f is an object whose type is 'function'.

Is there a way to find out f's list of formal arguments?

The reason for this is that I'm trying to write a decorator and
I'd like the wrapper to be able to check the number of arguments
passed.  Specifically, I'd like the wrapper to look as shown below:

def _wrap(f):
def wrapper(self, *params):
n_expected = len(f.FORMAL_ARGS)
n_received = len(params)
if n_received is not n_expected:
raise RuntimeError("Wrong number of arguments passed "
   "to %s" % f.__name__)
return self.send_jsonrpc_request(f.__name__, params)
return wrapper

...but I'm missing something like the hypothetical attribute
FORMAL_ARGS above.

TIA!

Kynn

-- 
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: introspection question: get return type

2009-05-14 Thread Aahz
In article <[email protected]>,
Bruno Desthuilliers   wrote:
>Marco Mariani a écrit :
>> Bruno Desthuilliers wrote:
>>> 
>>> Oh, you meant the "return type" ? Nope, no way. It just doesn't make 
>>> sense given Python's dynamic typing.
>>
>> Unless he's really trying to write in Nohtyp,
>
>You meant "Notype" ?-)

Marco's spelling is correct.  Try "Nohtyp".reverse()
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

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


Re: putting date strings in order

2009-05-14 Thread Scott David Daniels

Peter Otten wrote:
Hm, if ordered_raster_list is guaranteed to contain one string item for 
every month the above can be simplified to


months = [
'precip_jan', 'precip_feb', 'precip_mar', 'precip_apr', 
'precip_may', 'precip_jun', 'precip_jul', 'precip_aug', 
'precip_sep', 'precip_oct', 'precip_nov', 'precip_dec']


start = 2
ordered_raster_list = months[start-1:] + months[:start-1]


Or even:
>
multi_months = [
'precip_jan', 'precip_feb', 'precip_mar', 'precip_apr',
'precip_may', 'precip_jun', 'precip_jul', 'precip_aug',
'precip_sep', 'precip_oct', 'precip_nov', 'precip_dec'] * 2
start = 2
ordered_raster_list = multi_months[start - 1: start + 11]

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


Re: How to get all named args in a dict?

2009-05-14 Thread kj
In  Dave Angel 
 writes:



>kj wrote:
>> In  Terry Reedy 
>>  writes:
>>
>>   
>>> kj wrote:
>>> 
 Suppose I have the following:

 def foo(x=None, y=None, z=None):
 d = {"x": x, "y": y, "z": z}
 return bar(d)

 I.e. foo takes a whole bunch of named arguments and ends up calling
 a function bar that takes a single dictionary as argument, and this
 dictionary has the same keys as in foo's signature, so to speak.

 Is there some builtin variable that would be the same as the variable
 d, and would thus obviate the need to explicitly bind d?
   
>>
>>   
>>> Use the built-in function locals()
>>> 
>> def f(a,b):
>>   
>>> x=locals()
>>> print(x)
>>> 
>>
>>   
>> f(1,2)
>>   
>>> {'a': 1, 'b': 2}
>>> 
>>
>> That's *exactly* what I was looking for.  Thanks!
>>
>> kynn
>>
>>
>>   
>You already had a better answer from Chris Rebert:

>def foo(**kwargs):
>return bar(kwargs)

>kwargs at this point is exactly a dictionary of the named arguments to foo.

I disagree.  If I defined foo as you show above, then there is no
error checking on the named parameters passed to foo; anything
goes.

>Because if you try to do anything in this function, you'll probably be 
>adding more local variables. And then they'd be passed to bar as well.

That problem is easily solved: just make "x = locals()" the first
statement in the definition of foo.

kynn
-- 
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C API: how to replace python number object in place?

2009-05-14 Thread Scott David Daniels

Stephen Vavasis wrote:
If x is a C variable of type PyObject*, and I happen to know already that 
the object is of a numeric type, say int, is there a way to change the 
value of x in place to a different number?  In the C/API documentation I 
found routines to increment or decrement it in place, but I didn't find a 
routine to simply replace its value by a different value.  (I suppose I 
could change it to the new value via an increment or decrement, but this 
is ugly as well as being susceptible to overflow problems and roundoff 
errors in the case of floats.)


Thanks,
Steve Vavasis

If you do figurte out how to do what you want, you will put us in the
old FORTRAN trap:  People can write code that changes the value of a
constant.
The code:
month = 12 # make it december
inches_per_foot = 12
make_previous(month)
print ('Month is now: %s, inches_per_foot = %s' % (
   month, inches_per_foot))
might print:
Month is now: 11, inches_per_foot = 11

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


Need advice on distributing small module

2009-05-14 Thread kj



I've written a tiny module that I'd like to make available online
from my website.  This module is not "production-grade" code; it
is meant only as an illustration, but still I'd like to make its
download and installation as painless as possible.

I could simply bundle everything into a .tgz file, but I'd like
the distribution to conform to the expectations of Python users,
as far as the installation sequence is concerned.  I'm fairly new
to Python, and would appreciate your advice on this last point.

The module has only one non-standard dependency, described by the
following code:

if sys.version_info[:2] >= (2, 6):
import json
else:
import simplejson as json

If possible, I'd like to make distribution procedure such that if
necessary it also installs json or simplejson (as the case may be).

The actual package would contain the module file and a README file.

Is there a standard tool I can use to create this distribution?

TIA!

kynn
-- 
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get all named args in a dict?

2009-05-14 Thread Jason Tackaberry
On Thu, 2009-05-14 at 20:15 +, kj wrote:
> That problem is easily solved: just make "x = locals()" the first
> statement in the definition of foo.

That doesn't solve the problem.  You'd need locals().copy()

Cheers,
Jason.

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


Re: How to get the formal args of a function object?

2009-05-14 Thread Jeff McNeil
You can pull it out of f.func_code.co_varnames, but I don't believe
that's a very good approach. I tend to veer away from code objects
myself.

If you know how many arguments are passed into the wrapped function
when it's defined, you can write a function that returns your
decorator. As an example...

def validate_params(c):
def the_decorator(f):
def wrapper(*args):
if len(args) != c:
raise Exception("Bad things, Man.")
return f(*args)
return wrapper
return the_decorator

@validate_params(2)
def add(a,b):
return a+b

add(1,2)
add(1,2,3)

$ ./test.py
Traceback (most recent call last):
  File "test.py", line 16, in 
add(1,2,3)
  File "test.py", line 5, in wrapper
raise Exception("Bad things, Man.")
Exception: Bad things, Man.

Jeff



On May 14, 3:31 pm, kj  wrote:
> Suppose that f is an object whose type is 'function'.
>
> Is there a way to find out f's list of formal arguments?
>
> The reason for this is that I'm trying to write a decorator and
> I'd like the wrapper to be able to check the number of arguments
> passed.  Specifically, I'd like the wrapper to look as shown below:
>
> def _wrap(f):
>     def wrapper(self, *params):
>         n_expected = len(f.FORMAL_ARGS)
>         n_received = len(params)
>         if n_received is not n_expected:
>             raise RuntimeError("Wrong number of arguments passed "
>                                "to %s" % f.__name__)
>         return self.send_jsonrpc_request(f.__name__, params)
>     return wrapper
>
> ...but I'm missing something like the hypothetical attribute
> FORMAL_ARGS above.
>
> TIA!
>
> Kynn
>
> --
> NOTE: In my address everything before the first period is backwards;
> and the last period, and everything after it, should be discarded.

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


Re: OS independent file associate ?

2009-05-14 Thread norseman

Stef Mientki wrote:

hello,

I would like to make my programs available under the "standard" OS's, 
like Windows, Linux  (,Mac)
One of the problems I encounter, is launching of files through their 
file associates (probably a windows only terminology ;-)
Now I can detect the OS, but only the main OS and not e.g. Ubuntu / 
Gnome or whatever I've to detect.
Through trial and error I found a working mechanism under Ubuntu, but as 
I have to specify "gnome", I doubt this will work under other Linux 
systems.


any good solutions available ?

thanks,
Stef Mientki

   import subprocess
   CHM = '../numpy.chm'

   # works under Ubuntu
   subprocess.Popen( "gnome-open " + CHM , shell = True )

   # doesn't work under Ubuntu
   # (the list should be converted to a number of arguments,
   #but that doesn't seem to work under Ubuntu.
   subprocess.Popen( [ "gnome-open" , CHM] ,shell = True )

   # works under Windows
   subprocess.Popen( CHM , shell = True )

   # works better under windows
   win32help.HtmlHelp ( Win32_Viewer,
str(CHM),
win32help.HH_DISPLAY_INDEX,
str ( keyword ) )

 



General algorithm  which I have used for years.
Convert to specific syntax of compiler/interpreter/whatever...


Get OS from an OS call   Python has  platform   for that
Get the version  Python has  uname  for that
Get the version  Linux has   uname -a   for that

Pick your OS you use most and put that test first
  if it fails, try 2nd
  it it fails, try 3rd
  .
  .
each try uses the files suited to OS attempted


FYI
import platform
help(platform)
  (read)

os_is= platform.system()
  test for os_is == which



platform.dist()   check the doc - not sure this one does anything useful

platform.uname()  check the doc - Test it on Ubuntu, may be useful



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


Re: How to get the formal args of a function object?

2009-05-14 Thread Scott David Daniels

kj wrote:

Suppose that f is an object whose type is 'function'.

Is there a way to find out f's list of formal arguments?

The reason for this is that I'm trying to write a decorator and
I'd like the wrapper to be able to check the number of arguments
passedbut I'm missing something like the hypothetical attribute
FORMAL_ARGS above.


I can write a wrapper now:

def tracer(function):
def internal(*args, **kwargs):
print('calling %s(%s)' % (function.__name__,
', '.join([repr(arg) for arg in args] +
  ['%s=%r' % ka for ka in sorted(kwargs)])))
result = function(*args, **kwargs)
print('=> %r' % result)
return internal

and call like so:
tracer(math.sin)(3.1415 / 6)

calling sin(0.52358334)
=> 0.49998662654663256

What would your missing something be for tracer(math.sin)?

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


Re: How to get the formal args of a function object?

2009-05-14 Thread Chris Rebert
On Thu, May 14, 2009 at 12:31 PM, kj  wrote:
>
>
> Suppose that f is an object whose type is 'function'.
>
> Is there a way to find out f's list of formal arguments?
>
> The reason for this is that I'm trying to write a decorator and
> I'd like the wrapper to be able to check the number of arguments
> passed.  Specifically, I'd like the wrapper to look as shown below:
>
> def _wrap(f):
>    def wrapper(self, *params):
>        n_expected = len(f.FORMAL_ARGS)
>        n_received = len(params)
>        if n_received is not n_expected:
>            raise RuntimeError("Wrong number of arguments passed "
>                               "to %s" % f.__name__)
>        return self.send_jsonrpc_request(f.__name__, params)
>    return wrapper
>
> ...but I'm missing something like the hypothetical attribute
> FORMAL_ARGS above.

Take a look at inspect.getargspec(func):
http://docs.python.org/library/inspect.html#inspect.getargspec

Cheers,
Chris
-- 
http://blog.rebertia.com

> --
> NOTE: In my address everything before the first period is backwards;
> and the last period, and everything after it, should be discarded.

P.S. Have you considered making your address obfuscation just slightly
less of a pain in the ass? It's particularly annoying compared to
others'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C API: how to replace python number object in place?

2009-05-14 Thread Hrvoje Niksic
[email protected] (Stephen Vavasis) writes:

> If x is a C variable of type PyObject*, and I happen to know already
> that the object is of a numeric type, say int, is there a way to
> change the value of x in place to a different number?  In the C/API
> documentation I found routines to increment or decrement it in
> place, but I didn't find a routine to simply replace its value by a
> different value.

The only thing you can do is change x to point to a different object,
with the new desired value.  That is how the "in place" number
modification functions work.

Which routines to increment or decrement the number are you referring
to, exactly?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nimrod programming language

2009-05-14 Thread Piet van Oostrum
> [email protected] (b) wrote:

>b> Nimrod also seems to ignore underscores inside names, seeing them as
>b> blanks. Some languages ignore underscores inside number literals, but
>b> I have never seen a language ignoring them into names too.

You may not have seen it, but Fortran and Algol 60 belong to that
category. 
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: [email protected]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get the formal args of a function object?

2009-05-14 Thread norseman

kj wrote:


Suppose that f is an object whose type is 'function'.

Is there a way to find out f's list of formal arguments?

The reason for this is that I'm trying to write a decorator and
I'd like the wrapper to be able to check the number of arguments
passed.  Specifically, I'd like the wrapper to look as shown below:

def _wrap(f):
def wrapper(self, *params):
n_expected = len(f.FORMAL_ARGS)
n_received = len(params)
if n_received is not n_expected:
raise RuntimeError("Wrong number of arguments passed "
   "to %s" % f.__name__)
return self.send_jsonrpc_request(f.__name__, params)
return wrapper

...but I'm missing something like the hypothetical attribute
FORMAL_ARGS above.

TIA!

Kynn



I've never tried that approach.  But the attempt brings back memories.

Mind you I was using a compiler, not an interpreter.

Language was assembly

it outlines like this:

1st time called:

compile actual code   # boo-koo bytes
if token count test OK
  compile the call to the code# just the call (1 or 2 words)
else
  print current program address
  compile in a string denoting error"ERROR-ERROR"
   to force a quit (crash)


2nd time and on

do not compile actual code   # Zero bytes
if token count test OK
  compile the call to the code   # just the call (1 or 2 words)
else
  print current program address
  compile in a string denoting error"ERROR-ERROR"
   to force a quit (crash)

Helps to print the assembly 'prn' file and look for your error flag 
BEFORE trying to run program. :)


compiler token stack (storage) delta before/after packet loaded is
tested with size expected and compiler directives adjusted accordingly.

I have no idea how to do this with an interpreter.  Maybe someone who 
reads this can figure it out.  If so - I want a copy (Please.)


Even:
def funct_foo(t1,t2,t3):
  call_token_check(3)  will not tell the incoming number
   they are on a stack or something
   somewhere else in memory.
With an interpreter this becomes an expensive overhead. Mine was only 
costly at compile time. Not at run time. And it shortened the code and 
the development time.




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


how to import MV module

2009-05-14 Thread guangshan chen

Hi all,

I am new. I just want to run a python program.

When I run it, python can not find MV module. The follow is the error  
information:

Traceback (most recent call last):
  File "MakeCouplerRestart.py", line 22, in 
import MV,struct,Numeric,string
ImportError: No module named MV

Could any one tell me how to import MV module. Where is it?

Thanks..

Guangshan

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


Re: Distributed locking

2009-05-14 Thread Piet van Oostrum
> James  (J) wrote:

>J> Hey all, I'm looking for suggestions on how to tackle distributed
>J> locking across several Python programs on several different machines.

Have you looked at the multiprocessing package? It has distributed
Locks's with timeouts which might well fit your requirements.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: [email protected]
-- 
http://mail.python.org/mailman/listinfo/python-list


Returning dictionary from a function

2009-05-14 Thread kk
Hi

I am working on something here and I cannot get the full dictionary
out of a function. I am sure I am missing something here.

Anyways here is a simple code that repeats my problem. Basically I am
just trying to get that values function to return the diky as a
dictionary so that I can query values later.

thanks




def values(x):
diky={}
for a in range(x):
a=a+100
diky={chr(a):a}

print diky
return diky


b=values(5)
print type(b),len(b), b['f'] # gives error
print type(b),len(b), b['h'] # does not give error
-- 
http://mail.python.org/mailman/listinfo/python-list


Block-Local Variables using "with"

2009-05-14 Thread Gunter Henriksen
Presuming there is a reason to want block-local variables,
does this seem like a good way to do something like it?

@contextlib.contextmanager
def blocklocal(**kwargs):
bl = type('', (object,), {})()
for (k, v) in kwargs.items():
bl.__setattr__(k, v)
yield bl
for k in bl.__dict__.copy():
bl.__delattr__(k)

with blocklocal(a=12, b="hello") as bl:
bl.c = "world"
print(bl.a, bl.b, bl.c)

The "bl" variable would still be there but empty.
Are there cleaner ways? (without nested "def"s)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get the formal args of a function object?

2009-05-14 Thread norseman

Scott David Daniels wrote:

kj wrote:

Suppose that f is an object whose type is 'function'.

Is there a way to find out f's list of formal arguments?

The reason for this is that I'm trying to write a decorator and
I'd like the wrapper to be able to check the number of arguments
passedbut I'm missing something like the hypothetical attribute
FORMAL_ARGS above.


I can write a wrapper now:

def tracer(function):
def internal(*args, **kwargs):
print('calling %s(%s)' % (function.__name__,
', '.join([repr(arg) for arg in args] +
  ['%s=%r' % ka for ka in sorted(kwargs)])))
result = function(*args, **kwargs)
print('=> %r' % result)
return internal

and call like so:
tracer(math.sin)(3.1415 / 6)

calling sin(0.52358334)
=> 0.49998662654663256

What would your missing something be for tracer(math.sin)?

--Scott David Daniels
[email protected]

=
Scott;
I'm lost with this.

If you use the same and add that it prints both the first_token/second 
and the first_token multiplied by second and pass it (pi, 6, 7)  what 
happens then?


ie - function mysin only expects pi and 6 and is to print both pi/6 and 
pi*6.  The 7 is an error, not supposed to be there.




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


Re: Returning dictionary from a function

2009-05-14 Thread kk
Btw my main problem is that when I assign the function to 'b' variable
I only get the last key from the dictionary. Sorry about that I forgot
to mention the main issue.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: introspection question: get return type

2009-05-14 Thread Terry Reedy

Aahz wrote:

In article <[email protected]>,
Bruno Desthuilliers   wrote:

Marco Mariani a �crit :

Bruno Desthuilliers wrote:
Oh, you meant the "return type" ? Nope, no way. It just doesn't make 
sense given Python's dynamic typing.

Unless he's really trying to write in Nohtyp,

You meant "Notype" ?-)


Marco's spelling is correct.


Right. Nohtyp is an abbreviation for Noh-type, which is very traditionalist.


Try "Nohtyp".reverse()


which give us the anti-traditionalist (Monty) Python style of play.

tjr




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


Re: Nimrod programming language

2009-05-14 Thread bearophileHUGS
Piet van Oostrum:
> You may not have seen it, but Fortran and Algol 60 belong to that
> category.

I see. It seems my ignorance is unbounded, even for the things I like.
I am very sorry.

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


Re: python copy method alters type

2009-05-14 Thread Terry Reedy

Zhenhai Zhang wrote:

Really weired; Here is my code:

   a = ["a", 1, 3, 4]
   print "a:", a
 c = copy(a)


SyntaxError: unexpected indent
If you correct that, you would get a NameError


   c[0] = "c"
   c[1] = 2
   print "c:", c
   print "a:",a


When posting, copy and paste the complete code that you actually ran to 
get the purported output.


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


  1   2   >