Re: New to threads. How do they work?

2006-07-22 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Dennis Lee Bieber
wrote:

> On Sat, 22 Jul 2006 17:19:22 +1200, Lawrence D'Oliveiro
> <[EMAIL PROTECTED]> declaimed the following in
> comp.lang.python:
> 
>> 
>> Perhaps because with threads, data is shared by default. Whereas with
>> processes, it is private by default, and needs to be explicitly shared if
>> you want that.
> 
> Or just that the "name" "thread" was a late-comer for some of us...
> 
> The Amiga had "tasks" at the lowest level (these were what the core
> OS library managed -- that core handled task switching, memory
> allocation, and IPC [event flags, message ports]). "Processes" were
> scheduled by the executive, but had additional data -- like stdin/stdout
> and environment variables... all the stuff one could access from a
> command line. Or, confusing for many... Processes were "DOS" level,
> Tasks were "OS" level.

Or for a more up-to-date example, how about the Linux way, where "processes"
and "threads" are just two points on a spectrum of possibilities, all
controlled by options to the clone(2) system call.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Isn't there a better way?

2006-07-22 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, T wrote:

> 
> I am using an optparse to get command line options, and then pass them
> to an instance of another class:
> 
> 
> 
> # Class that uses optparse.OptionParser
> foo = Parse_Option()
> 
> # Class that does the real work
> bar = Processor()
> 
> bar.index = foo.options.index
> bar.output  = foo.options.output
> bar.run()
> 
> 
> 
> This works, but it feels hokey or unnatural to "pass" data from one
> class to another.  Isn't there a better way???

I don't see the problem. If you're calling a number of different routines in
the Processor class, all accessing the same data, then it makes perfect
sense to only pass it once.
-- 
http://mail.python.org/mailman/listinfo/python-list


Is it possible to get image size before/without downloading?

2006-07-22 Thread aldonnelley
Hi there: a bit of a left-field question, I think.
I'm writing a program that analyses image files downloaded with a basic
crawler, and it's slow, mainly because I only want to analyse files
within a certain size range, and I'm having to download all the files
on the page, open them, get their size, and then only analyse the ones
that are in that size range.
Is there a way (in python, of course!) to get the size of images before
or without downloading them? I've checked around, and I can't seem to
find anything promising...

Anybody got any clues?

Cheers, Al.

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


Re: Is it possible to get image size before/without downloading?

2006-07-22 Thread Josiah Manson
In the head of an HTTP response, most servers will specify a
Content-Length that is the number of bytes in the body of the response.
Normally, when using the GET method, the header is returned with the
body following. It is possible to make a HEAD request to the server
that will only return header information that will hopefully tell you
the file size.

If you want to know the actual dimensions of the image, I don't know of
anything in HTTP that will tell you. You will probably just have to
download the image to find that out. Relevant HTTP specs below if you
care.

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

The above is true regardless of language. In python it appears there an
httplib module. I would call request using the method head.

http://docs.python.org/lib/httpconnection-objects.html

[EMAIL PROTECTED] wrote:
> Hi there: a bit of a left-field question, I think.
> I'm writing a program that analyses image files downloaded with a basic
> crawler, and it's slow, mainly because I only want to analyse files
> within a certain size range, and I'm having to download all the files
> on the page, open them, get their size, and then only analyse the ones
> that are in that size range.
> Is there a way (in python, of course!) to get the size of images before
> or without downloading them? I've checked around, and I can't seem to
> find anything promising...
> 
> Anybody got any clues?
> 
> Cheers, Al.

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


Re: random shuffles

2006-07-22 Thread danielx
Boris Borcic wrote:
> does
>
> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
>
> pick a random shuffle of x with uniform distribution ?
>
> Intuitively, assuming list.sort() does a minimal number of comparisons to
> achieve the sort, I'd say the answer is yes. But I don't feel quite 
> confortable
> with the intuition... can anyone think of a more solid argumentation ?
>
> - BB
> --
> "On naît tous les mètres du même monde"

Someone has already said this, but I'm not sure we can ignore exactly
what algorithm we are using. With that in mind, I'll just arbitrarily
choose an algorithm to use for analysis. I know you want something that
works in N*log(N) where N is the length of the list, but I'm going to
ignore that and consider selection sort for the sake of a "more solid
argument".

In that case, you would NOT achieve a "uniform" distribution. I quote
that because I'm going to make up a definition, which I hope
corresponds to the official one ;). To me, uniform will mean if we look
at any position in the list, element e has 1/N chance of being there.

Let e be the element which was in the first position to begin with.
What are its chances of being there after being "sorted"? Well, in
order for it to still be there, it would have to survive N rounds of
selection. In each selection, it has 1/2 chance of surviving. That
means its total chance of survival is 1/(2**N), which is much less than
1/N. QED!

***

After writting that down, I thought of an argument for an N*log(N)
algorithm, which would cause the resulting list to be uniformly random:
tournament sort (I think this is also called binary tree sort). How
many rounds does an element have to win in order to come out on top? A
number which approaches log2(N). This is like before, except this
element doesn't have to survive as many rounds; therefore, it's total
chance of coming out on top is 1/(2**log2(N)) ==  1/N. Hoorah!

***

After considering that, I realized that even if your idea to shuffle a
list did work (can't tell because I don't know how Python's sort
works), it would not be an optimal way to shuffle a list even though
Python uses an N*log(N) sort (at least I hope so :P). This is because
you can shuffle in time proportional the the length of the list.

You can accomplish this by doing what I will call "random selection".
It would be like linear selection, except you wouldn't bother checking
the head against every other element. When you want to figure out what
to put at the head, just pick at random! I suspect this is what Python
does in random.shuffle, since it is rather an easy to see it would
result in something uniform (I swear I haven't looked at the source
code for random.shuffle :P).

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


Re: Is it possible to get image size before/without downloading?

2006-07-22 Thread aldonnelley
Thanks Josiah

I thought as much... Still, it'll help me immensely to cut the
downloads from a page to only those that are within a file-size range,
even if this gets me some images that are out-of-spec dimensionally.

Cheers, Al.

(Oh, and if anyone still has a bright idea about how to get image
dimensions without downloading, it'd be great to hear!)

Josiah Manson wrote:
> In the head of an HTTP response, most servers will specify a
> Content-Length that is the number of bytes in the body of the response.
> Normally, when using the GET method, the header is returned with the
> body following. It is possible to make a HEAD request to the server
> that will only return header information that will hopefully tell you
> the file size.
>
> If you want to know the actual dimensions of the image, I don't know of
> anything in HTTP that will tell you. You will probably just have to
> download the image to find that out. Relevant HTTP specs below if you
> care.
>
> http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
> http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
>
> The above is true regardless of language. In python it appears there an
> httplib module. I would call request using the method head.
>
> http://docs.python.org/lib/httpconnection-objects.html
>
> [EMAIL PROTECTED] wrote:
> > Hi there: a bit of a left-field question, I think.
> > I'm writing a program that analyses image files downloaded with a basic
> > crawler, and it's slow, mainly because I only want to analyse files
> > within a certain size range, and I'm having to download all the files
> > on the page, open them, get their size, and then only analyse the ones
> > that are in that size range.
> > Is there a way (in python, of course!) to get the size of images before
> > or without downloading them? I've checked around, and I can't seem to
> > find anything promising...
> > 
> > Anybody got any clues?
> > 
> > Cheers, Al.

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


Re: Is it possible to get image size before/without downloading?

2006-07-22 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> Hi there: a bit of a left-field question, I think.
> I'm writing a program that analyses image files downloaded with a basic
> crawler, and it's slow, mainly because I only want to analyse files
> within a certain size range, and I'm having to download all the files
> on the page, open them, get their size, and then only analyse the ones
> that are in that size range.
> Is there a way (in python, of course!) to get the size of images before
> or without downloading them? I've checked around, and I can't seem to
> find anything promising...
> 
> Anybody got any clues?

The PIL can determine the size of an image from some "large enough" chunk at
the beginning of the image, e. g:

import Image
import urllib
from StringIO import StringIO

f = urllib.urlopen("http://www.python.org/images/success/nasa.jpg";)
s = StringIO(f.read(512))
print Image.open(s).size

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


Re: Is it possible to get image size before/without downloading?

2006-07-22 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, aldonnelley
wrote:

> (Oh, and if anyone still has a bright idea about how to get image
> dimensions without downloading, it'd be great to hear!)

Most image formats have some sort of header with the dimensions
information so it's enough to download this header.  Depends on the image
format how much of the file has to be read and how the information is
encoded.

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


Re: using array as execute parameter in dbapi

2006-07-22 Thread gglegrp112
This is a really neat trick.

Thank you very much.

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


Wxpython, using more than 1 timer?

2006-07-22 Thread janama
Hi all,

Using wx
When adding a second timer as i have the first,  the second timer
adding  stops the first timer (updating or stops?) . In this example im
updating a uptime and localtime label. It works fine for displaying the
last "self.startTimer2()" called. But prevents the previous
self.startTimer1() from running . Im doing something fundamentally
wrong i guess?

def __init__(self, parent):
self._init_ctrls(parent)

#Start timers
self.startTimer1()
self.startTimer2()

def startTimer1(self):
self.t1 = wx.Timer(self)
self.t1.Start(360) # 36 ms = 1/10 hour
self.Bind(wx.EVT_TIMER, self.OnUpTime)

def startTimer2(self):
self.t2 = wx.Timer(self)
self.t2.Start(1000) # run every second
self.Bind(wx.EVT_TIMER, self.OnTime)

def OnTime(self,evt):
self.lblTime.SetLabel(str(time.localtime()))

def OnUpTime(self, evt):
self.lblUptime.SetLabel('Running ' + (str(myTimerText[0])) + '
hours') # 1/10  hour count
myTimerText[0] = myTimerText[0] + .1

Any help appreciated, ta

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


Re: Python newbie needs constructive suggestions

2006-07-22 Thread David G. Wonnacott
Many thanks to those of you who responded to my question about
anonymous functions with local variables, filling me in on

  e) do something else clever and Pythonic that I don't know about yet?

by pointing out that I can use (among other good things) lambda with
default arguments. That should suit my immediate needs well, since I
don't need to maintain state (or avoid maintaning state); I may also
look into closures (possibly anonymous ones?) and callable classes if
I need to go beyond this. And, of course, if the code is complex
enough, then one should give up the anonymous function and name it.

Rest assured that I will _not_ be attempting to write "let" in Python
and use it.

It looks like Python may be every much as big an improvement over C++
as I had hoped.

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


Re: Wxpython, using more than 1 timer?

2006-07-22 Thread nikie
janama wrote:

> Hi all,
>
> Using wx
> When adding a second timer as i have the first,  the second timer
> adding  stops the first timer (updating or stops?) . In this example im
> updating a uptime and localtime label. It works fine for displaying the
> last "self.startTimer2()" called. But prevents the previous
> self.startTimer1() from running . Im doing something fundamentally
> wrong i guess?
>
> def __init__(self, parent):
> self._init_ctrls(parent)
>
> #Start timers
> self.startTimer1()
> self.startTimer2()
>
> def startTimer1(self):
> self.t1 = wx.Timer(self)
> self.t1.Start(360) # 36 ms = 1/10 hour
> self.Bind(wx.EVT_TIMER, self.OnUpTime)
>
> def startTimer2(self):
> self.t2 = wx.Timer(self)
> self.t2.Start(1000) # run every second
> self.Bind(wx.EVT_TIMER, self.OnTime)
>
> def OnTime(self,evt):
> self.lblTime.SetLabel(str(time.localtime()))
>
> def OnUpTime(self, evt):
> self.lblUptime.SetLabel('Running ' + (str(myTimerText[0])) + '
> hours') # 1/10  hour count
> myTimerText[0] = myTimerText[0] + .1
>
> Any help appreciated, ta

The problem is not that the first timer ist stopped, the problem is
that both timers happen to call the same method in the end.

Think of the "Bind" method as an assignment: it assigns a handler
function to an event source. If you call it twice for the same event
source, the second call will overwrite the first event handler. That's
what happens in your code.

The easiest way to change this is by using different ids for the
timers:

def startTimer1(self):
self.t1 = wx.Timer(self, id=1)
self.t1.Start(2000)
self.Bind(wx.EVT_TIMER, self.OnUpTime, id=1)

def startTimer2(self):
self.t2 = wx.Timer(self, id=2)
self.t2.Start(1000)
self.Bind(wx.EVT_TIMER, self.OnTime, id=2)

This way, the timers launch two different events, which are bound to
two different methods.

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


How to force a thread to stop

2006-07-22 Thread Hans
Hi all,

Is there a way that the program that created and started a thread also stops 
it.
(My usage is a time-out).

E.g.

thread = threading.Thread(target=Loop.testLoop)
thread.start() # This thread is expected to finish within a second
thread.join(2)# Or time.sleep(2) ?

if thread.isAlive():
# thread has probably encountered a problem and hangs
# What should be here to stop thread  ??

Note that I don't want to change the target (too much), as many possible 
targets exist,
together thousands of lines of code.

Thanks,
Hans 


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


Re: Wxpython, using more than 1 timer?

2006-07-22 Thread janama
Thanks for that, cheers

Regards


nikie wrote:
> janama wrote:
>
> > Hi all,
> >
> > Using wx
> > When adding a second timer as i have the first,  the second timer
> > adding  stops the first timer (updating or stops?) . In this example im
> > updating a uptime and localtime label. It works fine for displaying the
> > last "self.startTimer2()" called. But prevents the previous
> > self.startTimer1() from running . Im doing something fundamentally
> > wrong i guess?
> >
> > def __init__(self, parent):
> > self._init_ctrls(parent)
> >
> > #Start timers
> > self.startTimer1()
> > self.startTimer2()
> >
> > def startTimer1(self):
> > self.t1 = wx.Timer(self)
> > self.t1.Start(360) # 36 ms = 1/10 hour
> > self.Bind(wx.EVT_TIMER, self.OnUpTime)
> >
> > def startTimer2(self):
> > self.t2 = wx.Timer(self)
> > self.t2.Start(1000) # run every second
> > self.Bind(wx.EVT_TIMER, self.OnTime)
> >
> > def OnTime(self,evt):
> > self.lblTime.SetLabel(str(time.localtime()))
> >
> > def OnUpTime(self, evt):
> > self.lblUptime.SetLabel('Running ' + (str(myTimerText[0])) + '
> > hours') # 1/10  hour count
> > myTimerText[0] = myTimerText[0] + .1
> >
> > Any help appreciated, ta
>
> The problem is not that the first timer ist stopped, the problem is
> that both timers happen to call the same method in the end.
>
> Think of the "Bind" method as an assignment: it assigns a handler
> function to an event source. If you call it twice for the same event
> source, the second call will overwrite the first event handler. That's
> what happens in your code.
>
> The easiest way to change this is by using different ids for the
> timers:
>
> def startTimer1(self):
> self.t1 = wx.Timer(self, id=1)
> self.t1.Start(2000)
> self.Bind(wx.EVT_TIMER, self.OnUpTime, id=1)
>
> def startTimer2(self):
> self.t2 = wx.Timer(self, id=2)
> self.t2.Start(1000)
> self.Bind(wx.EVT_TIMER, self.OnTime, id=2)
>
> This way, the timers launch two different events, which are bound to
> two different methods.

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


Converting argv to variable

2006-07-22 Thread tgiles
(now that I've posted in the wrong flipping newsgroup the first thing,
here's my question to the lovely python folks)

I've taken a year off (or so) using Python and the first thing I run
into utterly stumped me. Been too long and none of the searches I've
done seems to have helped any.
Basically, I'm trying to create a little script which will make a new
directory, using the argument passed to it to give the directory a
name:

#!/usr/bin/python

import sys, os

newDirectory = str(sys.argv[1:])

currentPath =  str(os.getcwd())

create =  currentPath + '/' + newDirectory

print create

# os.mkdir(create)

Now, in a perfect universe I would get an output something like the
following (if I run the script with the argument 'python':

/Volumes/Home/myuser/python

However, Python still hangs on to all the fluff and prints out
something else:

/Volumes/Home/myuser/['python']

I know there must be some way to convert the argument to a 'normal'
variable, but it escapes me how to do so. Any pointers? 

Thanks! 

tom

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


Re: Converting argv to variable

2006-07-22 Thread Tim Chase
 > newDirectory = str(sys.argv[1:])
[cut]
 > Now, in a perfect universe I would get an output something
 > like the following (if I run the script with the argument
 > 'python':
 >
 > /Volumes/Home/myuser/python
 >
 > However, Python still hangs on to all the fluff and prints
 > out something else:
 >
 > /Volumes/Home/myuser/['python']

Your "newDirectory = ..." line is asking for a slice of a
list, which returns a list.  Python then dutifully converts
that list to a string representation and tacks that onto
your string/path.

What you want is sys.argv[1] (the first argument) not
sys.argv[1:] (a list of all but the first argv--namely, all
the arguments as [0] is the name of your python script)

-tkc





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


Re: Converting argv to variable

2006-07-22 Thread Klaus Alexander Seistrup
Tom skrev:

> newDirectory = str(sys.argv[1:])

Try

newDir = '/'.join(sys.argv[1:])
or
newDir = sys.argv[1]
or
for newDir in sys.argv[1:]:
:

or something along those lines, depending on how you wish to 
interpret the commandline.

Cheers, 

-- 
Klaus Alexander Seistrup
Copenhagen, Denmark
http://surdej.dk/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New to threads. How do they work?

2006-07-22 Thread Grant Edwards
On 2006-07-22, Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:

>> I've never understood the aversion people seem to have to
>> threads.
>
> Perhaps because with threads, data is shared by default.
> Whereas with processes, it is private by default, and needs to
> be explicitly shared if you want that.

Only global data is shared.  I guess if you use a lot of global
data that's an issue.  I tend not to.  The problem with
processes is that sharing data is hard.

-- 
Grant Edwards   grante Yow!  Are you mentally here
  at   at Pizza Hut??
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Application Generators

2006-07-22 Thread walterbyrd

Steve Hannah wrote:
> I know that this is an older thread, but I came across it on Nabble.com.
> Just wanted add some updated info on Walter's observations about Dataface
> (http://fas.sfu.ca/dataface) .  It is much further along in development now
> and it does support authentication now.
>

Thanks, for the particular project that I was working on, I went with
AppGeni, and added my own authentication.

I do have other projects in mind. Dataface seems almost like a free
version of codecharge. One thing I don't much like about codecharge, is
that it's windows only.

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


Re: random shuffles

2006-07-22 Thread David G. Wonnacott
   From: "danielx" <[EMAIL PROTECTED]>
   Date: 22 Jul 2006 01:43:30 -0700

   Boris Borcic wrote:
   > does
   >
   > x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
   >
   > pick a random shuffle of x with uniform distribution ?

...

   Let e be the element which was in the first position to begin with.
   What are its chances of being there after being "sorted"? Well, in
   order for it to still be there, it would have to survive N rounds of
   selection. In each selection, it has 1/2 chance of surviving. That
   means its total chance of survival is 1/(2**N), which is much less than
   1/N. QED!


This proof makes sense to me if the sorting algorithm makes a random
decision every time it swaps.

Couldn't we easily get an n*log(n) shuffle by performing a _single_
mapping of each element in the collection to a pair made up of a
random key and its value, and then sorting based on the keys and
stripping them out? i.e., in O(n) time, turn

   "2 clubs", "2 diamonds", "2 hearts", "2 spades", "3 clubs"

into something like

   [0.395, "2 clubs"], [0.158, "2 diamonds"], [0.432, "2 hearts"], [0.192, "2 
spades"], [0.266, "3 clubs"]

and then in O(n*log(n)) time, sort it into

   [0.158, "2 diamonds"], [0.192, "2 spades"], [0.266, "3 clubs"], [0.395, "2 
clubs"], [0.432, "2 hearts"]

and then strip out the keys again in O(n) time?

Or perhaps this has been discussed already and I missed that part? I
just joined the list... apologies if this is a repeat.



   You can accomplish this by doing what I will call "random selection".
   It would be like linear selection, except you wouldn't bother checking
   the head against every other element. When you want to figure out what
   to put at the head, just pick at random! I suspect this is what Python
   does in random.shuffle, since it is rather an easy to see it would
   result in something uniform (I swear I haven't looked at the source
   code for random.shuffle :P).


But, after making the linear selection, don't you still need to use
O(log(n)) time to find and remove the item from the collection? I
don't know much about Python's internal data structures, but if
there's an array in there, you need O(n) time to move up everything
after the deleted item; if there's a list, you need O(n) time to find
the element you picked at random; if there's a balanced tree, you
could find it and delete it in O(log(n)) time...

Help me review my undergraduate data structures here -- is there some
way to pick each item _exactly_once_ in O(n) time?

Dave Wonnacott

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


Re: IronPython and scipy/pyExcelerator

2006-07-22 Thread Fuzzyman

[EMAIL PROTECTED] wrote:
> I'm looking forward to the release IronPython, primarily for its IDE. I
> currently use scipy and pyExcelerator to crunch numbers and write them
> to Excel: does can these packages be used with IronPython as well?
>
> Thanks in advance

You could try Python for .NET. This is a version of cPython with
support for .NET built in.

You may have to amend the code that Visual Studio produces to work with
Python for .NET rather than for IronPython  (necessary changes may be
restricted to the import syntax).

SciPy makes extensive use of C extensions which aren't currently
supoorted by IronPython. There has been some preliminary work done dy
Seo Sanghyeon on a 'reflector' that uses ctypes to allow IronPython to
access cPython C extensions. My understanding is that it works (at
least partially) but that the exceptions it returns are (currently)
confusing.

See
http://groups.google.com/group/comp.lang.python/browse_frm/thread/842a8011a1a2a26c/9d7e157124943e9f

and also search the IronPython mailing lists. Alternatively you could
use interprocess communication between cPython and IronPython ;-)

All the best,


Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

> 
> Thomas Philips

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


Re: How to force a thread to stop

2006-07-22 Thread bryanjugglercryptographer

Hans wrote:
> Hi all,
>
> Is there a way that the program that created and started a thread also stops
> it.
> (My usage is a time-out).
>
> E.g.
>
> thread = threading.Thread(target=Loop.testLoop)
> thread.start() # This thread is expected to finish within a second
> thread.join(2)# Or time.sleep(2) ?

No, Python has no threadicide method, and its absence is not an
oversight. Threads often have important business left to do, such
as releasing locks on shared data; killing them at arbitrary times
tends to leave the system in an inconsistent state.

> if thread.isAlive():
> # thread has probably encountered a problem and hangs
> # What should be here to stop thread  ??

At this point, it's too late. Try to code so your threads don't hang.

Python does let you arrange for threads to die when you want to
terminate the program, with threading's Thread.setDaemon().


-- 
--Bryan

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


Re: What is a type error?

2006-07-22 Thread Benjamin Franksen
Darren New wrote:
> Chris Smith wrote:
>> Specialized
>> language already exist that reliably (as in, all the time) move array
>> bounds checking to compile time;
> 
> It sounds like this means the programmer has to code up what it means to
> index off an array, yes? Otherwise, I can't imagine how it would work.
> 
> x := read_integer_from_stdin();
> write_to_stdout(myarray[x]);
> 
> What does the programmer have to do to implement this semantic in the
> sort of language you're talking about? Surely something somewhere along
> the line has to  "fail" (for some meaning of failure) at run-time, yes?

You should really take a look at Epigram. One of its main features is that
it makes it possible not only to statically /check/ invariants, but also
to /establish/ them.

In your example, of course the program has to check the integer at runtime.
However, in a dependent type system, the type of the value returned from
the check-function can very well indicate whether it passed the test (i.e.
being a valid index for myarray) or not.

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


httplib, threading, wx app freezing after 4 hours

2006-07-22 Thread Mark rainess
The program displays images from a motion jpeg webcam.
(Motion jpeg is a bastardization of multi-part mime.)


It runs perfectly for about 4 hours, then freezes.
I'm stuck. How do I debug this?

(Using: Python 2.4.3, wxPython 2.6.3.2, Windows 2000 and XP)

There are no tracebacks, the gui continues to run,
isAlive() and activeCount() indicate that the thread is OK,
"print I'm alive" stops. CPU % usage is 0

I figure it is hanging in r.readline() or f.read()

Can anyone suggest techniques to help me learn what is going on.

I'm using httplib.HTTP instead of httplib.HTTPConnection because
I don't find that HTTPConnection has readline().


Mark Rainess


=
class mjpeg_get(threading.Thread):
 def run(self):
 while 1:
 while 1:
 # print I'm connecting
 h = httplib.HTTP(self.url)
 h.putrequest('GET','VIDEO.CGI')
 h.putheader('Accept','text/html')
 h.endheaders()
 if errcode == 200:
 f = h.getfile()
 break
 # cleanup and try again

 s = cStringIO()
 while 1:
 # print I'm alive
 try:
 # do f.readline() to get headers
 # get count from 'Content-length:'
 s.reset()
 s.write(f.read(count))
 s.truncate()
 wx.CallAfter(self.window.onUpdateImg, s)
 continue
 except:
 # print error
 # cleanup and try again
 break

class Frame(wx.Frame):
 def OnIdle(self, event):
 # for debugging display result of
 # Thread.isAlive()
 # threading.activeCount()
 if self.gotImage is True:
 # do display self.sImage
 self.gotImage = False
 def onUpdateImg(self, parm):
 if self.gotImage is False:
 self.sImage.reset()
 self.sImage.write(parm.getvalue())
 self.sImage.truncate()
 self.sImage.reset()
 self.gotImage = True
=
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nested function scope problem

2006-07-22 Thread Justin Azoff
Josiah Manson wrote:
> I just did some timings, and found that using a list instead of a
> string for tok is significantly slower (it takes 1.5x longer). Using a
> regex is slightly faster for long strings, and slightly slower for
> short ones. So, regex wins in both berevity and speed!

I think the list.append method of building strings may only give you
speed improvements when you are adding bigger chunks of strings
together instead of 1 character at a time. also:

http://docs.python.org/whatsnew/node12.html#SECTION000121

"""String concatenations in statements of the form s = s + "abc" and s
+= "abc" are now performed more efficiently in certain circumstances.
This optimization won't be present in other Python implementations such
as Jython, so you shouldn't rely on it; using the join() method of
strings is still recommended when you want to efficiently glue a large
number of strings together. (Contributed by Armin Rigo.)"""

I tested both, and these are my results for fairly large strings:

[EMAIL PROTECTED]:/tmp$ python /usr/lib/python2.4/timeit.py -s'import
foo' 'foo.test(foo.breakLine)'
10 loops, best of 3: 914 msec per loop

[EMAIL PROTECTED]:/tmp$ python /usr/lib/python2.4/timeit.py -s'import
foo' 'foo.test(foo.breakLineRE)'
10 loops, best of 3: 289 msec per loop

-- 
- Justin

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


GUIDE: Using xtopdf to create PDF from text and DBF files (including creating simple PDF e-books)

2006-07-22 Thread vasudevram

Hi,

I'm giving below, steps to install and use my xtopdf PDF
creation/conversion toolkit.

This post is for end-users. xtopdf is both a set of end-user tools and
a library for use by developers, to create PDF from various input
formats.
I'll post another message here about how developers can use it in
various ways, sometime later.

The steps are for the Windows platform. Will do another post for Linux.

1. Get Python v2.4.3 here:
http://www.python.org/ftp/python/2.4.3/python-2.4.3.msi
Size is not more than 10 MB. Install it - its an MSI, so just
double-click.

(Any Python version >= 2.2 will work for xtopdf).

2. Get Reportlab open source version 1.21 here:
http://www.reportlab.org/ftp/ReportLab_1_21.tgz

Size is not more than 3 MB.

(Don't use ReportLab 2.0 although it is available. I've not yet tested
xtopdf with it. ReportLab 1.21 is the latest stable version in the
version 1 series.)

Install it following the instructions in the README file.
It should be straightforward. The main points to take care of are:

2.1 First, before installing ReportLab, run Python once (you may have
to add the dir. where Python got installed, say C:\Python24, to your
PATH variable first). Once that dir. is added to your PATH (preferably
via Control Panel), open a DOS prompt.
At this prompt, type:

python

This should start the Python interpreter. You will get a one or two
line message with the Python version, and then the Python interpreter
prompt.

2.2. At this prompt, type the following two lines:

import sys
print sys.path

This should display a list of all the dirs. that are in the Python PATH
- an internal Python variable that gets set automatically, upon startup
of the interpreter, to a set of default dirs. This variable is
analogous to the DOS PATH variable. In this list of dirs., look for
"C:\Python24\lib\site-packages" as one of the dirs. It should be there
by default.

If it is there, then exit the Python interpreter by typing Ctrl-Z and
Enter.

3. Now install Reportlab:

Unzip the ReportLab_1_21.tgz file with WinZip, into some folder, say
c:\reportlab.
This will create a folder called either:
a) reportlab_1.21 with a folder called reportlab under it
or
b) just a folder called reportlab.

If a), then move the reportlab folder (which is under reportlab_1.21)
to under C:\Python24\Lib\site-packages .
If b), then move the reportlab folder to under
C:\Python24\Lib\site-packages.

The above steps should make ReportLab work.

An alternative way is to just unzip the reportlab  .tgz file into some
folder, say, C:\RL, and then create a file called, say, reportlab.pth,
which contains just one line - the path to this folder where the
extracted contents get stored.e.g. C:\RL\reportlab . Please check that
step out (in the ReportLab .tgz file's  README file for the exact
details).

4. After the above steps, to check that Reportlab works, go to a DOS
prompt again, run python again as before, and then at the Python
prompt, enter either or both of the following commands (on separate
lines):

import reportlab

from reportlab import pdfgen

If either or both of these above commands work (and if there is no
error message), it means that Reportlab is properly installed.

5. Now you can install xtopdf.

Get xtopdf here: http://sourceforge.net/projects/xtopdf (click on the
green rectangle which says "Download Conversion of other formats to
PDF".
After downloading the file, unzip it into a folder, say c:\temp. This
will create a folder called xtopdf-1.0 under C:\temp.
Go to that folder.

There are many Python programs here with extension .py.

To run, e.g., WritePDF.py, do this:

python WritePDF.py some_file.txt

This will run it and the output will be a file called some_file.pdf.
Try opening it in Adobe Reader.

Similarly try running some more programs:

python DBFReader.py test1.dbf (or test2.dbf or test3.dbf or test4.dbf -
all of which are in the package)

This should read the DBF file and display its metadata (file header and
field headers) and data records to standard output - the screen.

python DBFToPDF.py test1.dbf  test1.pdf

This should do the same as the above (DBFReader.py), except that
instead of the output going to the screen, it will go to a file called
test1.pdf.

And so on, try out a few others. Most of all of the programs can be run
as "python prog_name.py". Some require one or
more command-line arguments (all of them require at least one
command-line argument, at least an input file).
Some of them give usage messages if you run them without any
command-line arguments, but this is not necessarily the case for
all of them, nor are the messages always user-friendly enough - I'm
working on fixing that in the next release. (Developers who have at
least
a working knowledge of Python should be easily able to figure out the
usage, though, just by reading the start of the main() function for
each program -
the part where the code checks the command-line arguments.)

But you should be able to run at least a few of them like this

Python website problem?

2006-07-22 Thread Tim N. van der Leeuw
Hi,

Does the Python.org website have a problem? I only get a directory
index, and clicking on any of the HTML files in there shows a page
without any CSS makeup.

Anyone noticed this too?

--Tim

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


How to test if object is sequence, or iterable?

2006-07-22 Thread Tim N. van der Leeuw
Hi,

I'd like to know if there's a way to check if an object is a sequence,
or an iterable. Something like issequence() or isiterable().

Does something like that exist? (Something which, in case of iterable,
doesn't consume the first element of the iterable)

Regards,

--Tim

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


Re: Python website problem?

2006-07-22 Thread Tim N. van der Leeuw

Tim N. van der Leeuw wrote:
> Hi,
>
> Does the Python.org website have a problem? I only get a directory
> index, and clicking on any of the HTML files in there shows a page
> without any CSS makeup.
>
> Anyone noticed this too?
> 
> --Tim

Well, it seems fixed again...

--Tim

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


Sansung YH-920 + Linux + yh-925-db-0.1.py = AttributeError: 'module' object has no attribute 'decode'

2006-07-22 Thread rsd
Hi,

I'm trying get Samsung YH-920 mp3 player to work with Debian GNU/Linux. 
To do that I need to run
   http://www.paul.sladen.org/toys/samsung-yh-925/yh-925-db-0.1.py 
script, the idea behind the script is described at
   http://www.paul.sladen.org/toys/samsung-yh-925/

I'm getting errors and hoping someone could give me some hints, for I 
have no python background.

This is what I've done:
1. mounted YH-920 as /mnt/usb and transfered my MP3s to 
/mnt/usb/System/music/mp3 folder. That was easy.

2. Now, I need to run "yh-925-db-0.1.py" to update the database.

test:/mnt/usb# ls -l
total 64
drwxr-xr-x 3 root root 16384 2006-07-22 10:31 backup
drwxr-xr-x 8 root root 16384 2006-07-22 10:33 System
drwxr-xr-x 2 root root 16384 2002-01-01 11:00 tmp


test:/mnt/usb/System# ls -l
total 2480
drwxr-xr-x 2 root root 16384 2006-06-26 16:31 audible
drwxr-xr-x 2 root root 16384 2006-06-26 16:31 data
drwxr-xr-x 6 root root 16384 2006-06-26 16:31 music
drwxr-xr-x 2 root root 16384 2006-06-26 16:31 Parms
drwxr-xr-x 2 root root 16384 2006-06-26 16:31 playlist
-rwxr-xr-x 1 root root 2424832 2004-07-31 10:47 pp5020.mi4
drwxr-xr-x 2 root root 16384 2006-06-26 16:31 Recordings
-rwxr-xr-x 1 root root 7305 2006-07-22 10:34 yh-925-db-0.1.py


test:/mnt/usb/System# ./yh-925-db-0.1.py
Traceback (most recent call last):
File "./yh-925-db-0.1.py", line 195, in ?
de.add_from_dict(e.unpack3(f))
File "./yh-925-db-0.1.py", line 53, in unpack3
u = utf_16_le.decode(fp.read(size))
AttributeError: 'module' object has no attribute 'decode'

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


Re: Isn't there a better way?

2006-07-22 Thread Bruno Desthuilliers
Lawrence D'Oliveiro a écrit :
> In message <[EMAIL PROTECTED]>, T wrote:
> 
> 
>>I am using an optparse to get command line options, and then pass them
>>to an instance of another class:
>>
>>
>>
>># Class that uses optparse.OptionParser
>>foo = Parse_Option()
>>
>># Class that does the real work
>>bar = Processor()
>>
>>bar.index = foo.options.index
>>bar.output  = foo.options.output
>>bar.run()
>>
>>
>>
>>This works, but it feels hokey or unnatural to "pass" data from one
>>class to another.  Isn't there a better way???
> 
> 
> I don't see the problem. 

The problem is setting bar attributes from the outside IMHO. Which is 
easily solved by passing the relevant stuff either at instanciation time 
or at call time.

> If you're calling a number of different routines in
> the Processor class, all accessing the same data, then it makes perfect
> sense to only pass it once.

Actually they are not "passed".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if object is sequence, or iterable?

2006-07-22 Thread Bruno Desthuilliers
Tim N. van der Leeuw a écrit :
> Hi,
> 
> I'd like to know if there's a way to check if an object is a sequence,
> or an iterable. Something like issequence() or isiterable().
> 
> Does something like that exist? (Something which, in case of iterable,
> doesn't consume the first element of the iterable)

isiterable = lambda obj: isinstance(obj, basestring) \
  or getattr(obj, '__iter__', False)


Should cover most cases.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python newbie needs constructive suggestions

2006-07-22 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> What is the idiomatically appropriate Python way to pass, as a
> "function-type parameter", code that is most clearly written with a
> local variable?

def functionWithLocal(andArg):
   localVar = 42
   return andArg+localVar

map(functionWithLocal, range(42))


> For example, map takes a function-type parameter:
> 
> map(lambda x: x+1, [5, 17, 49.5])
> 
> What if, instead of just having x+1, I want an expression that is
> most clearly coded with a variable that is needed _only_ inside the
> lambda, e.g. if I wanted to use the name "one" instead of 1:
> 
> map(lambda x: (one = 1  x+one), [5, 17, 49.5])

map(lambda x, one=42 : x + one, [5, 17, 49.5])

> This sort of thing is of course straightforward in many other
> languages with anonymous functions (Scheme, Haskell, Smalltalk, etc),
> and I saw in the archives the discussion from 2003 about "How do I
> get Scheme-like let bindings in Python". Many of the answers seem to
> boil down to "You should not write Scheme programs in Python, you
> should write Python programs in Python".

A very sensible advice IMHO. Python - while having some support for FP - 
is still statement-based and mostly on the OO/procedural side.

(snip)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: random shuffles

2006-07-22 Thread danielx
David G. Wonnacott wrote:
> From: "danielx" <[EMAIL PROTECTED]>
>Date: 22 Jul 2006 01:43:30 -0700
>
>Boris Borcic wrote:
>> does
>>
>> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
>>
>> pick a random shuffle of x with uniform distribution ?
>
> ...
>
>Let e be the element which was in the first position to begin with.
>What are its chances of being there after being "sorted"? Well, in
>order for it to still be there, it would have to survive N rounds of
>selection. In each selection, it has 1/2 chance of surviving. That
>means its total chance of survival is 1/(2**N), which is much less than
>1/N. QED!
>
>
> This proof makes sense to me if the sorting algorithm makes a random
> decision every time it swaps.
>
> Couldn't we easily get an n*log(n) shuffle by performing a _single_
> mapping of each element in the collection to a pair made up of a
> random key and its value, and then sorting based on the keys and
> stripping them out? i.e., in O(n) time, turn
>
>"2 clubs", "2 diamonds", "2 hearts", "2 spades", "3 clubs"
>
> into something like
>
>[0.395, "2 clubs"], [0.158, "2 diamonds"], [0.432, "2 hearts"], [0.192, "2 
> spades"], [0.266, "3 clubs"]
>
> and then in O(n*log(n)) time, sort it into
>
>[0.158, "2 diamonds"], [0.192, "2 spades"], [0.266, "3 clubs"], [0.395, "2 
> clubs"], [0.432, "2 hearts"]
>
> and then strip out the keys again in O(n) time?
>
> Or perhaps this has been discussed already and I missed that part? I
> just joined the list... apologies if this is a repeat.
>

Yes, that would work beautifully. You could use the key argument of
list.sort. What we are talking about though, is using the cmp argument.
I.e. will list.sort(cmp=lambda:???) be able to give you a shuffle? I
think most of us think this depends on what sort algorithm Python uses.

>
>
>You can accomplish this by doing what I will call "random selection".
>It would be like linear selection, except you wouldn't bother checking
>the head against every other element. When you want to figure out what
>to put at the head, just pick at random! I suspect this is what Python
>does in random.shuffle, since it is rather an easy to see it would
>result in something uniform (I swear I haven't looked at the source
>code for random.shuffle :P).
>
>
> But, after making the linear selection, don't you still need to use
> O(log(n)) time to find and remove the item from the collection? I
> don't know much about Python's internal data structures, but if
> there's an array in there, you need O(n) time to move up everything
> after the deleted item; if there's a list, you need O(n) time to find
> the element you picked at random; if there's a balanced tree, you
> could find it and delete it in O(log(n)) time...

I'm almost sure there's a C array back there as well (well, not
techinically an array, but something from malloc), because indexing a
Python list is supposed to be "fast". It would take constant time to
put something at the head. Just swap with the thing that's already
there. Since you have to do this swap for each position, it takes time
proportional to N.

When I originally came up with this idea, I was thinking you would not
choose a new head among previously chosen heads. But if you do allow
that, I think it will still be uniform. So my original idea was
something like this:

  1  2  3  4
# ^ head pos
stage 0: we need to choose something to put in pos 0. We can choose
anything to go there.

(swap)
  3  2  1  4
#^ head pos
stage 1: we need to choose something to put in pos 1. We can choose
among things in positions greater than or equal to 1 ie, we may choose
among 2 1 4.

etc.

This is what I meant when I said this would be like linear selection,
because once something is in its correct position, it doesn't get
moved. But you might also be able to achieve a uniform sort if in
stages 1 and up, you are still allowed to choose anything you want to
be the head. I'll let someone else figure it out :P.

>
> Help me review my undergraduate data structures here -- is there some
> way to pick each item _exactly_once_ in O(n) time?

I think I answered this in the first segment of this post. Let me know
if I don't seem clear.

> 
> Dave Wonnacott

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


Re: How to test if object is sequence, or iterable?

2006-07-22 Thread Tim N. van der Leeuw

Bruno Desthuilliers wrote:
> Tim N. van der Leeuw a écrit :
> > Hi,
> >
> > I'd like to know if there's a way to check if an object is a sequence,
> > or an iterable. Something like issequence() or isiterable().
> >
> > Does something like that exist? (Something which, in case of iterable,
> > doesn't consume the first element of the iterable)
>
> isiterable = lambda obj: isinstance(obj, basestring) \
>   or getattr(obj, '__iter__', False)
>
>
> Should cover most cases.

Yes, that seems to cover all cases I can think of, indeed. Funny
though, that string objects do not have an '__iter__' method, but are
still iterable... But it will make most of my use-cases easier: Often I
want to iterate over something, if it's an iterable, except when it's a
string.


Thanks,

--Tim

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


Re: Converting argv to variable

2006-07-22 Thread Terry Reedy

"tgiles" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> (now that I've posted in the wrong flipping newsgroup the first thing,
> here's my question to the lovely python folks)
>
> I've taken a year off (or so) using Python and the first thing I run
> into utterly stumped me. Been too long and none of the searches I've
> done seems to have helped any.
> Basically, I'm trying to create a little script which will make a new
> directory, using the argument passed to it to give the directory a
> name:
>
> #!/usr/bin/python
> import sys, os
> newDirectory = str(sys.argv[1:])

If you are only going to make one dir at a time, newDir = sys.argv[1]

> currentPath =  str(os.getcwd())
> create =  currentPath + '/' + newDirectory

os.path has platform-independent function to do this

tjr



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


Re: How to automate user input at the command prompt?

2006-07-22 Thread M�ta-MCI
Hi!


>>> There are typically only two output streams from a command line program. 
>>> stdout and stderr... Some of the OS triggered error messages
(abort, retry, fail) might be going to stderr -- so if you were looking at 
stdout, you won't see them.

- when you use  RD TOTO/S , win show the text "Are-you sure (Y/N)?" on 
stdout, and no stderr
- when the text is send, by win, on stdout, there are no RC ; consequently, 
subprocess (or popen) don't see anything
- it's possible, with popen4, with subprocess, to merge stdout & stderr in 
the same pipe


The problem remain entire.


@-salutations
-- 
Michel Claveau



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


Re: How to test if object is sequence, or iterable?

2006-07-22 Thread Terry Reedy

"Tim N. van der Leeuw" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi,
>
> I'd like to know if there's a way to check if an object is a sequence,
> or an iterable. Something like issequence() or isiterable().

How about
try: it = iter(possible_iterable)
except TypeError: bail()

Terry Jan Reedy



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


Re: Nested function scope problem

2006-07-22 Thread Bruno Desthuilliers
Josiah Manson a écrit :
> I found that I was repeating the same couple of lines over and over in
> a function and decided to split those lines into a nested function
> after copying one too many minor changes all over. The only problem is
> that my little helper function doesn't work! It claims that a variable
> doesn't exist. If I move the variable declaration, it finds the
> variable, but can't change it. Declaring the variable global in the
> nested function doesn't work either.
> 
> But, changing the variable in the containing scope is the whole purpose
> of this helper function.
> 
> I'm new to python, so there is probably some solution I haven't
> encountered yet. Could you please suggest a nice clean solution? The
> offending code is below. Thanks.
> 
> def breakLine(s):
>   """Break a string into a list of words and symbols.
>   """
>   def addTok():
>   if len(tok) > 0:

 if tok:

An empty sequence evals to False in a boolean context.

>   ls.append(tok)
>   tok = ''
> 

First point: the nested function only have access to names that exists 
in the enclosing namespace at the time it's defined.

Second point: a nested function cannot rebind names from the enclosing 
namespace. Note that in Python, rebinding a name and modifying the 
object bound to a name are very distinct operations.

Third point : functions modifying their environment this way are usually 
considered bad form.

Here's a possible solution - but note that there are probably much 
better ways to get the same result...

def breakline(line):
   """Break a string into a list of words and symbols."""
   class TokenList(list):
 def append(self, token):
   if token:
 list.append(self, token)
   return ''

   tokens = TokenList()
   token = ''
   splitters = '?()&|:~,'
   whitespace = ' \t\n\r'
   specials = splitters + whitespace

   for char in line:
 if char in specials:
token = tokens.append(token)
 if char in splitters:
   tokens.append(char)
 else:
   token += char

   tokens.append(token)
   return list(tokens)

(snip)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nested function scope problem

2006-07-22 Thread Bruno Desthuilliers
Justin Azoff a écrit :
> Simon Forman wrote:
> 
>>That third option seems to work fine.
> 
> 
> Well it does, but there are still many things wrong with it
> 
(snip)

> tok = ''
> tok = toc + c
> should be written as
> tok = []
> tok.append(c)
> and later
> ''.join(toc)

IIRC, string concatenation slowness has been fixed a few versions ago - 
at least in CPython - , so there's  no more reason to use this idiom.

(snip)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nested function scope problem

2006-07-22 Thread Bruno Desthuilliers
Justin Azoff a écrit :
> Simon Forman wrote:
> 
>>That third option seems to work fine.
> 
> 
> Well it does, but there are still many things wrong with it
> 
> if len(tok) > 0:
> should be written as
> if(tok):
> 

actually, the parenthesis are useless.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nested function scope problem

2006-07-22 Thread Bruno Desthuilliers
Lawrence D'Oliveiro a écrit :
> In message <[EMAIL PROTECTED]>, Justin 
> Azoff wrote:
> 
> 
>>Simon Forman wrote:
>>
>>>That third option seems to work fine.
>>
>>Well it does, but there are still many things wrong with it
>>
>>if len(tok) > 0:
>>should be written as
>>if(tok):
> 
> 
> I prefer the first way.

This is your right, but it's not the python idiom.

> Besides, your way is sub-optimal.

Care to explain ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python newbie needs constructive suggestions

2006-07-22 Thread Bruno Desthuilliers
Lawrence D'Oliveiro a écrit :
> In message <[EMAIL PROTECTED]>,
> [EMAIL PROTECTED] wrote:
> 
> 
>>  b) give up on using an anonymous function and create a named "successor"
>>  function with "def",
> 
> 
> This is what you have to do.

Not necessarily.

map(lambda x, one=1: one + x, range(42))

> For some reason mr van Rossum has this aversion
> to anonymous functions, and tries to cripple them as much as possible.

For some reasons, including the fact that Python is statement based and 
have significative indentation, it's actually not trivial to come with a 
better syntax for lambdas. The horse has been beaten to hell and back, 
and no one managed to propose anything worth implementing so far. But if 
you have the solution to this problem, please share...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function v. method

2006-07-22 Thread danielx
Bruno Desthuilliers wrote:
> danielx wrote:
> > Bruno Desthuilliers wrote:
> >
> >>danielx wrote:
> >>
> (snip)
> >>>
> >>>Obviously, such things would be omitted from your docs, but users also
> >>>learn by interacting with Python, which is really one of Python's great
> >>>virtues. When supporting documents aren't sufficient to learn an api
> >>>(I'm sure this never happens, so just humor me), you can always turn to
> >>>interactive Python.
> >>
> >>...and source code...
> >
> >
> > *shudders* What happened to all the goodness of abstraction?
>
> Compared to machine language, Python source code is really abstration.
>

And machine language is an abstraction of pushing electrons around
circuits. I'm not sure I see your point, unless it is simply that
Python is easier than asm.

> --
> bruno desthuilliers
> python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
> p in '[EMAIL PROTECTED]'.split('@')])"

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


Re: Nested function scope problem

2006-07-22 Thread Justin Azoff
Bruno Desthuilliers wrote:
> Justin Azoff a écrit :
> > if len(tok) > 0:
> > should be written as
> > if(tok):
> >
>
> actually, the parenthesis are useless.

yes, that's what happens when you edit something instead of typing it
over from scratch :-)

-- 
- Justin

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


Re: New to threads. How do they work?

2006-07-22 Thread Edmond Dantes
Dennis Lee Bieber wrote:

> On Sat, 22 Jul 2006 17:19:22 +1200, Lawrence D'Oliveiro
> <[EMAIL PROTECTED]> declaimed the following in
> comp.lang.python:
> 
>> 
>> Perhaps because with threads, data is shared by default. Whereas with
>> processes, it is private by default, and needs to be explicitly shared if
>> you want that.
> 
> Or just that the "name" "thread" was a late-comer for some of us...
> 
> The Amiga had "tasks" at the lowest level (these were what the core
> OS library managed -- that core handled task switching, memory
> allocation, and IPC [event flags, message ports]). "Processes" were
> scheduled by the executive, but had additional data -- like stdin/stdout
> and environment variables... all the stuff one could access from a
> command line. Or, confusing for many... Processes were "DOS" level,
> Tasks were "OS" level.

On the Amiga, everything was essentially a "thread". There was *no* memory
protection whatsoever, which made for a wickedly fast -- and unstable --
OS.

Now, before Commordore went the way of the Dodo Bird, there was some
discussion about adding memory protection to the OS, but that was a very
difficult proposition since most if not all of the OS control structures
were just that -- basically c "structs", with live memory pointers handed
around from application to kernel and back.

I think we could've done it eventually, but that ship sank. All because of
the idiots there that was upper management. But I digress.
 
-- 
-- Edmond Dantes, CMC
And Now for something Completely Different:
  http://baskets.giftsantiquescollectables.com
  http://vacation-packages.YouDeserveItNow.com
  http://cold-remedy.WomenLite.com
  http://investments.BankOrLoan.com
  http://coils.IndustrialMetalz.com
  http://brackets.Auto1Parts.com
  http://windmill.industrialtips.com


 Posted Via Usenet.com Premium Usenet Newsgroup Services
--
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
--
http://www.usenet.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function v. method

2006-07-22 Thread danielx

Gerhard Fiedler wrote:
> On 2006-07-20 18:10:21, danielx wrote:
>
> >>> When supporting documents aren't sufficient to learn an api (I'm sure
> >>> this never happens, so just humor me), you can always turn to
> >>> interactive Python.
> >>
> >> ...and source code...
> >
> > *shudders* What happened to all the goodness of abstraction?
>
> Abstraction as you seem to use it requires complete docs of the interface.
> Which is what you said you don't have... So the original abstractor broke
> the abstraction when publishing insufficient docs, not the one who looks
> into the sources to find out what actually happens.

Absolutely. I didn't mean the user was breaking abstraction (let's not
blame the victim). I was saying that we should really have more
sympathy for him.

> 
> (This independently of the merits of abstraction.)
> 
> Gerhard

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


Re: function v. method

2006-07-22 Thread Bruno Desthuilliers
danielx a écrit :
> Bruno Desthuilliers wrote:
> 
>>danielx wrote:
>>
>>>Bruno Desthuilliers wrote:
>>>
>>>
danielx wrote:

>>
>>(snip)
>>
>Obviously, such things would be omitted from your docs, but users also
>learn by interacting with Python, which is really one of Python's great
>virtues. When supporting documents aren't sufficient to learn an api
>(I'm sure this never happens, so just humor me), you can always turn to
>interactive Python.

...and source code...
>>>
>>>
>>>*shudders* What happened to all the goodness of abstraction?
>>
>>Compared to machine language, Python source code is really abstration.
>>
> And machine language is an abstraction of pushing electrons around
> circuits. I'm not sure I see your point, unless it is simply that
> Python is easier than asm.

Python is very hi-level, and very often well-written Python code is it's 
own better documentation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function v. method

2006-07-22 Thread danielx
fuzzylollipop wrote:
> danielx wrote:
> > Bruno Desthuilliers wrote:
> > > danielx wrote:
> > > > At first I was going to post the following:
> > > >
> > > > 
> > > >
> > > (snip)
> > > >
> > > > 
> > > >
> > > > but then I tried this:
> > > >
> > > >
> > > res = Foo.__dict__['func']
> > > res is dan
> > > >
> > > > True
> > > >
> > > > And it all started to make sense. The surprising thing turned out to be
> > > > not so surprising: When the expression Foo.func gets evaluated, we get
> > > > a method which is just a wrapper around dan. Therefore, f is not dan!
> > > > This is still a little bit of magic,
> > >
> > > FWIW, the function class implements the descriptor protocol... Here's
> > > the "magic".
> > >
> > > > which gets me thinking again about
> > > > the stuff I self-censored. Since the dot syntax does something special
> > > > and unexpected in my case,
> > >
> > > "unexpected" ? Did you ever wondered how the instance or class was
> > > passed as first arg when doing method calls ?
> >
> > Not knowing what's going on during method calls is exactly what
> > motivated me to post.
> >
> > >
> > > > why not use some more dot-magic to implement
> > > > privates?
> > >
> > > What for ? What makes you think we need language-inforced access
> > > restriction ?
> >
> > I knew someone would bring this up. The motivation would not be to
> > provide restriction, but to help maintain clean api's. If you intended
> > for users to use only a subset of the methods in your class, why not
> > help them learn your api by presenting the stuff they can use not along
> > side the stuff they should not?
> >
> > Obviously, such things would be omitted from your docs, but users also
> > learn by interacting with Python, which is really one of Python's great
> > virtues. When supporting documents aren't sufficient to learn an api
> > (I'm sure this never happens, so just humor me), you can always turn to
> > interactive Python. This is exactly what it's there for. If nothing is
> > hidden, a user could be easily mislead to believe he can use a method
> > when he really shouldn't.
> >
>
>
> if you prefix with a single underscore, that tells the user, DON'T MESS
> WITH ME FROM OUTSIDE! I AM AN IMPLEMENTATION DETAIL!
>
> and it gets ommited from all the doc generation
>
> if you prefix with a double underscore, then they have to go even
> FARTHER out of their way to shoot themselves in the foot.
>
> Python takes the stance of "personal responsiblity" when it comes to
> access control. Which in NO WAY dimishes its "robustness" or anything
> else.
>
> just read the DailyWTF.com, incompentent people will abuse any language
> features in any language, and will figure out how to break programatic
> access control no matter how it is implemented. Matter of fact, Java
> which in another thread someone was ADAMANT that did not expose private
> anything from reflection ( and was wrong ) specifically allows you to
> access all the private members, functions, everything. You just need to
> tell it to turn all the "safeties" off.
>
> >From the api:
>
> public void setAccessible(boolean flag)
> throws SecurityException
>
> Set the accessible flag for this object to the indicated boolean value.
> A value of true indicates that the reflected object should suppress
> Java language access checking when it is used. A value of false
> indicates that the reflected object should enforce Java language access
> checks.
>
> Setting the accessible flag in a reflected object permits sophisticated
> applications with sufficient privilege, such as Java Object
> Serialization or other persistence mechanisms, to manipulate objects in
> a manner that would normally be prohibited.
>
> so anything added to Python to enforce "access control" would
> immediately be forced to provide some means to over-ride the checks for
> pickle and the like. Not to even mention the argument that it would
> break crap loads of existing code base.

Sigh. I TOTALLY realize that Python works by politeness and not
enforcement. I think you are misinterpreting why I think this would be
a good idea. My concern is not with control, but with convenience. My
suggestion was that privates would only be invisible if you use the dot
syntax (ie if you are an external user); they would not be invisible
altogether (they would still be in __dict__ with no name games).

One problem which was brought up about this was that self.meth and
outsider.meth would have to be interpretted differently. I suspect (but
I haven't finished my reading assignment :P) that you could find a good
way around this.

With respect to breaking stuff. I'm not sure why that would be
necessary. If current code does not say any member is private,
everything that was visible before (ie everything) would still be
visible after.

Last thing. You mentioned that auto doc generation omits
underscore-prefixed and name mangled members. dir on the other hand
does not. Maybe this suggests only a minor future improvement.


Re: Isn't there a better way?

2006-07-22 Thread Dave Hansen
On 21 Jul 2006 07:51:15 -0700 in comp.lang.python, "T"
<[EMAIL PROTECTED]> wrote:

>
>I am using an optparse to get command line options, and then pass them
>to an instance of another class:
>
>
>
># Class that uses optparse.OptionParser
>foo = Parse_Option()
>
># Class that does the real work
>bar = Processor()
>
>bar.index = foo.options.index
>bar.output  = foo.options.output
>bar.run()


How about

   class Processor(whatever):
  ...
  def __init__(self,whatever_else):
  ...
  self.op = Parse_Option()

   ...
   bar = Processor()
   bar.run()

This would even let you do some preliminary option processing during
object initialization.

Regards,

   
-=Dave

-- 
Change is inevitable, progress is not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function v. method

2006-07-22 Thread danielx
Bruno Desthuilliers wrote:
> danielx a écrit :
> > Bruno Desthuilliers wrote:
> >
> >>danielx wrote:
> >>
> >>>Bruno Desthuilliers wrote:
> >>>
> >>>
> danielx wrote:
> 
> >>
> >>(snip)
> >>
> >Obviously, such things would be omitted from your docs, but users also
> >learn by interacting with Python, which is really one of Python's great
> >virtues. When supporting documents aren't sufficient to learn an api
> >(I'm sure this never happens, so just humor me), you can always turn to
> >interactive Python.
> 
> ...and source code...
> >>>
> >>>
> >>>*shudders* What happened to all the goodness of abstraction?
> >>
> >>Compared to machine language, Python source code is really abstration.
> >>
> > And machine language is an abstraction of pushing electrons around
> > circuits. I'm not sure I see your point, unless it is simply that
> > Python is easier than asm.
>
> Python is very hi-level, and very often well-written Python code is it's
> own better documentation.

Yes, Python is very easy to read, but who's supposed to be reading it?
Maintainers or users? I'm really against code acting as its own
documentation. Of course the code is authoritative, but should we
really EXPECT it to serve as a reference to users??

Appearantly, this view puts me in the minority...

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


Re: function v. method

2006-07-22 Thread Bruno Desthuilliers
danielx a écrit :
> 
(snip)
> Sigh. I TOTALLY realize that Python works by politeness and not
> enforcement. I think you are misinterpreting why I think this would be
> a good idea. My concern is not with control, but with convenience.

Having free access to implementation is convenient IMHO.

> My
> suggestion was that privates would only be invisible if you use the dot
> syntax (ie if you are an external user); they would not be invisible
> altogether (they would still be in __dict__ with no name games).

How would this work for class attributes ? (implementation methods, 
implementation descriptors etc...)

Also, it would impact lookup perfs, which is already a somewhat weak 
point in Python.




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


Re: function v. method

2006-07-22 Thread danielx
Bruno Desthuilliers wrote:
> Antoon Pardon wrote:
> > On 2006-07-21, fuzzylollipop <[EMAIL PROTECTED]> wrote:
> >
> >>danielx wrote:
> >>
> (snip)
> >>
> >>
> >>if you prefix with a single underscore, that tells the user, DON'T MESS
> >>WITH ME FROM OUTSIDE! I AM AN IMPLEMENTATION DETAIL!
> >
> >
> > Personnaly I don't like this convention.
>
> To bad for you.
>
> > It isn't clear enough.
>
> Oh yes ?
>
> > Suppose I am writing my own module, I use an underscore, to
> > mark variables which are an implementation detail for my
> > module.
> >
> > Now I need to import an other module in my module and need access
> > to an implementation variable from that module.
> >
> > So now I have
> > variables with an underscore which have two different meanings:
> >
> >   1) This is an implemantation detail of this module, It is the
> >  users of my module who have to be extra carefull using it.
> >
> >   2) This is an implemantation detail of the other module,
> >  I should be extra carefull using it.
>
> Either you imported with the "from othermodule import *" form (which you
> shouldn't do), and you *don't* have the implementation of othermodule,
> or your used the "import othermodule" form, in which case it's pretty
> obvious which names belongs to othermodule.
>
> Have any other, possibly valid, reason ?
>
> > And I find variable starting or ending with an underscore ugly. :-)
>
> Too bad for you. Choose another language then... PHP, Perl, Ruby ?-)
>

"Too bad for you": While you have a valid point that this contention is
really just arbitrary (just like all conventions), could we be a little
gentler?

Personally, I don't think it looks very good either, but you just have
to deal with it if you're going to use the language properly.

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


Re: How to test if object is sequence, or iterable?

2006-07-22 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Bruno Desthuilliers wrote:

> Tim N. van der Leeuw a écrit :
>> Hi,
>> 
>> I'd like to know if there's a way to check if an object is a sequence,
>> or an iterable. Something like issequence() or isiterable().
>> 
>> Does something like that exist? (Something which, in case of iterable,
>> doesn't consume the first element of the iterable)
> 
> isiterable = lambda obj: isinstance(obj, basestring) \
>   or getattr(obj, '__iter__', False)
> 
> 
> Should cover most cases.

What about objects that just implement an apropriate `__getitem__()`
method?

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

Re: function v. method

2006-07-22 Thread Bruno Desthuilliers
danielx a écrit :
> Bruno Desthuilliers wrote:
> 
>>danielx a écrit :
>>
>>>Bruno Desthuilliers wrote:
>>>
>>>
danielx wrote:


>Bruno Desthuilliers wrote:
>
>
>
>>danielx wrote:
>>

(snip)


>>>Obviously, such things would be omitted from your docs, but users also
>>>learn by interacting with Python, which is really one of Python's great
>>>virtues. When supporting documents aren't sufficient to learn an api
>>>(I'm sure this never happens, so just humor me), you can always turn to
>>>interactive Python.
>>
>>...and source code...
>
>
>*shudders* What happened to all the goodness of abstraction?

Compared to machine language, Python source code is really abstration.

>>>
>>>And machine language is an abstraction of pushing electrons around
>>>circuits. I'm not sure I see your point, unless it is simply that
>>>Python is easier than asm.
>>
>>Python is very hi-level, and very often well-written Python code is it's
>>own better documentation.
> 
> 
> Yes, Python is very easy to read, but who's supposed to be reading it?
> Maintainers or users?

In an ideal world, nobody !-)

> I'm really against code acting as its own
> documentation. 

I'm really for it, because :

> Of course the code is authoritative,

indeed.

> but should we
> really EXPECT it to serve as a reference to users??

Unless you're able to maintain a good, accurate and always up to date 
documentation, you can be sure users (ie other programmers) will turn to 
the code. Also, there are cases where even a pretty good doc is not 
enough, and you really have to turn to the code to know for sure how to 
best implement something.

FWIW, reading source code can be very instructive...

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


Re: How to test if object is sequence, or iterable?

2006-07-22 Thread Bruno Desthuilliers
Marc 'BlackJack' Rintsch a écrit :
> In <[EMAIL PROTECTED]>, Bruno Desthuilliers wrote:
> 
> 
>>Tim N. van der Leeuw a écrit :
>>
>>>Hi,
>>>
>>>I'd like to know if there's a way to check if an object is a sequence,
>>>or an iterable. Something like issequence() or isiterable().
>>>
>>>Does something like that exist? (Something which, in case of iterable,
>>>doesn't consume the first element of the iterable)
>>
>>isiterable = lambda obj: isinstance(obj, basestring) \
>>  or getattr(obj, '__iter__', False)
>>
>>
>>Should cover most cases.
> 
> 
> What about objects that just implement an apropriate `__getitem__()`
> method?

Hmmm... (quick test)

Good point.

FWIW, Terry's solution might be far better.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python website problem?

2006-07-22 Thread Aahz
In article <[EMAIL PROTECTED]>,
Tim N. van der Leeuw <[EMAIL PROTECTED]> wrote:
>
>Does the Python.org website have a problem? I only get a directory
>index, and clicking on any of the HTML files in there shows a page
>without any CSS makeup.
>
>Anyone noticed this too?

Yes, we're having problems with the build system.  Nothing to see here,
move along.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are, by
definition, not smart enough to debug it."  --Brian W. Kernighan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: random shuffles

2006-07-22 Thread Ross Ridge
David G. Wonnacott wrote:
> Couldn't we easily get an n*log(n) shuffle...

Why are you trying to get an O(n*log(n)) shuffle when an O(n) shuffle
algorithim is well known and implemented in Python as random.shuffle()?

 Ross Ridge

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


Re: using names before they're defined

2006-07-22 Thread Nick Vatamaniuc
Dave,

Sometimes generating classes from .ini or XML files is not the best
way. You are just translating one language into another and are making
bigger headaches for your self. It is certainly cool and bragable to
say that "my classes get generated on the fly from XML" but  Python is
terse and reasonable enough to just write it in Python. In other words
instead of saying  2MW just write
some Python code that instantiates a turbine  with a 2MW power based on
your class. Then you can evaluate Python code in Python and you even
got your on-the-fly generation.
As a general rule, I would say to think 3 times before touching XML in
Python unless you are absolutely forced to. Config .ini files can be
more acceptable but Python is still best. Why write
;;My turbine class
[turbine]
power=2MW
speed=800rpm
...
when you can just say:
#my turbine class
t=Turbine( power="2MW", \
   speed="800rpm", \
   ...
First case is a little shorter but then you have to use a parser for it
while in the second case you just execute the file, and besides, you
can edit it with any Python editor.

Hope this helps,
Nick V.


[EMAIL PROTECTED] wrote:
> Hi
>
> > Also, I gave the example using Python code as 'config' format, but any
> > structured enough text format could do, ie JSON, XML, or even ini-like:
> >
> > # schema.ini
> > objects = turbine1, frobnicator2
> >
> > [turbine1]
> > class=Turbine
> > upstream=frobnicator2
> > downstream=
> >
>
> yes, I like the idea of using .ini type file format or XML, very much.
> There are parser available which will automatically building python
> objects from this, won't they (like configparser)? I'll have to get
> reading over the weekend...
>
> > >>def get_class_by_name(name):
> > >>  return globals()[name]
> > >
> >
> > Q&D way to retrieve the class object (Python's classes are themselves
> > objects) known by it's name (as a string).
>
> ok, so it actually returns the class object itself.
> One thing that confuses me is that objects have a name (self.name) but
> object instances also have a name (e.g. myspecialturbine = turbine(...)
>  how do I discover the name 'myspecialturbine' ?). And object
> instances have a class name too ('turbine'). Aaargh, too many names!
> what if just want to know what the name of the instance is (in this
> case 'myspecialturbine'?)
>
> Right. I'll have a go at pulling all this together over the weekend
> hopefully. Hurrah! Thanks for all the help, to everyone.
> Dave

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


Re: subprocess module

2006-07-22 Thread Tim Roberts
"placid" <[EMAIL PROTECTED]> wrote:

>Hi all,
>
>If someone could give me an example of creating a subprocess (on
>Windows) using the subprocess module and Popen class and connecting to
>its stdout/stdin file handles. I googled for a bit but the only example
>i found was here ;

"Use the source, Luke."  The best examples of the use of subprocess are
contained in the introductory comments in the module itself.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if object is sequence, or iterable?

2006-07-22 Thread Nick Vatamaniuc
Tim,

An object is iterable if it implements the iterator protocol. A good
enough check to see if it does is to check for the presense of the
__iter__() method. The way to do it is:
hasattr(object,'__iter__')

You are correct in the fact that you check if an object is iterable
rather than using isinstance to check if it is of a partucular type.
You are doing things 'the pythonic way' ;)

Nick Vatamaniuc


Tim N. van der Leeuw wrote:
> Hi,
>
> I'd like to know if there's a way to check if an object is a sequence,
> or an iterable. Something like issequence() or isiterable().
>
> Does something like that exist? (Something which, in case of iterable,
> doesn't consume the first element of the iterable)
> 
> Regards,
> 
> --Tim

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


Type signature

2006-07-22 Thread Yacao Wang
Hi, I'm a newbie to Python. I've recently read some books about this language and none of them have answered my question. As a dynamically-typed language Python doesn't need any form of type signature which makes the syntax very clean and concise. However, type signatures are not only a kind of information provided for the compiler, but also for the programmer, or more important, for the programmer. Without it, we have to "infer" the return type or required agument types of a function, and this can't be done without seeing the implementation of it, and sometimes it is still difficult to extract the above information even if the implementation is available. Haskell can also determine type information dynamically, but it still supports and recommends the programming style with type signatures, which makes the code very readable and maitainable. As I understand, Python relies too much on run-time type-checking, that is, whenever you give the wrong type, you just end up with an exception, which is logically correct, but not that useful as type signatures.
Any ideas on this issue? -- Alex
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: httplib, threading, wx app freezing after 4 hours

2006-07-22 Thread Nick Vatamaniuc
Mark,

httplib will block waiting for a server connection. I am not sure if
that is your problem but you could try a quick and dirty workaround of
recording a timestamp of the last data transfer and then have a timer
in a separate thread and if too much time passed, restart the retrieval
thread and issue a warning.  Also check the memory on your machine in
case some buffer fills the memory up and the machine gets stuck.
To understand what's really happening try to debug the program. Try
Winpdb debugger you can find it here:
http://www.digitalpeers.com/pythondebugger/
Nick Vatamaniuc

Mark rainess wrote:
> The program displays images from a motion jpeg webcam.
> (Motion jpeg is a bastardization of multi-part mime.)
> 
>
> It runs perfectly for about 4 hours, then freezes.
> I'm stuck. How do I debug this?
>
> (Using: Python 2.4.3, wxPython 2.6.3.2, Windows 2000 and XP)
>
> There are no tracebacks, the gui continues to run,
> isAlive() and activeCount() indicate that the thread is OK,
> "print I'm alive" stops. CPU % usage is 0
>
> I figure it is hanging in r.readline() or f.read()
>
> Can anyone suggest techniques to help me learn what is going on.
>
> I'm using httplib.HTTP instead of httplib.HTTPConnection because
> I don't find that HTTPConnection has readline().
>
>
> Mark Rainess
>
>
> =
> class mjpeg_get(threading.Thread):
>  def run(self):
>  while 1:
>  while 1:
>  # print I'm connecting
>  h = httplib.HTTP(self.url)
>  h.putrequest('GET','VIDEO.CGI')
>  h.putheader('Accept','text/html')
>  h.endheaders()
>  if errcode == 200:
>  f = h.getfile()
>  break
>  # cleanup and try again
>
>  s = cStringIO()
>  while 1:
>  # print I'm alive
>  try:
>  # do f.readline() to get headers
>  # get count from 'Content-length:'
>  s.reset()
>  s.write(f.read(count))
>  s.truncate()
>  wx.CallAfter(self.window.onUpdateImg, s)
>  continue
>  except:
>  # print error
>  # cleanup and try again
>  break
>
> class Frame(wx.Frame):
>  def OnIdle(self, event):
>  # for debugging display result of
>  # Thread.isAlive()
>  # threading.activeCount()
>  if self.gotImage is True:
>  # do display self.sImage
>  self.gotImage = False
>  def onUpdateImg(self, parm):
>  if self.gotImage is False:
>  self.sImage.reset()
>  self.sImage.write(parm.getvalue())
>  self.sImage.truncate()
>  self.sImage.reset()
>  self.gotImage = True
> =

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


Re: Type signature

2006-07-22 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Yacao Wang
wrote:

> However, type signatures are not only a kind of information provided for
> the compiler, but also for the programmer, or more important, for the
> programmer. Without it, we have to "infer" the return type or required
> agument types of a function, and this can't be done without seeing the
> implementation of it,

That's what documentation is meant for.  If you are forced to look at the
implementation, the documentation is bad.

> Haskell can also determine type information dynamically, but it still
> supports and recommends the programming style with type signatures,

Does Haskell really determine the type information dynamically!?  AFAIK
it's done at compile time.

> which makes the code very readable and maitainable. As I understand,
> Python relies too much on run-time type-checking, that is, whenever you
> give the wrong type, you just end up with an exception, which is
> logically correct, but not that useful as type signatures. Any ideas on
> this issue?

Which issue?  ;-)

Just stop thinking in terms of types.  Python is about *behavior*.  If
the docs say `this functions takes an iterable as input` then `iterable`
isn't a specific type but an object that implements the behavior of an
iterable.  You can't check that reliable without actually trying to
iterate over it.  Search for "duck typing".

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


Re: Type signature

2006-07-22 Thread hanumizzle

Yacao Wang wrote:
> Hi, I'm a newbie to Python. I've recently read some books about this
> language and none of them have answered my question.
> As a dynamically-typed language Python doesn't need any form of type
> signature which makes the syntax very clean and concise.

OK...

> However, type
> signatures are not only a kind of information provided for the compiler

Statically-typed code tends (generally) to be faster than
dynamically-typed code, obviously. Often, it doesn't really matter,
though. (This is an old argument.)

Lush is an interesting Lisp-like language that supports admixture of
dynamic and static typing, and uses type signatures to support it. It
can produce high performance machine code because of this.

> Python relies too much on run-time type-checking, that is,
> whenever you give the wrong type, you just end up with an exception, which
> is logically correct, but not that useful as type signatures.

As said before, polymorphism plays an important role. In addition to
looking up 'duck typing' (c.f. Programming Ruby), it might also be
useful to look for Damian Conway's observations on 'interface
polymorphism' (standard practice in Perl, Python, Ruby, etc.) vs.
'inheritance polymorphism' (what you get with C++ and IIRC Java).

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


Dive Into Python -- Still Being Updated?

2006-07-22 Thread hanumizzle
I find Dive Into Python generally an excellent text, and I am not
surprised to see people recommending it...but I have noticed a few
errors already:

http://diveintopython.org/getting_to_know_python/indenting_code.html

The function called fib (presumably short for Fibonacci) appears to
produce factorials. Anyway, 'fib' should really be called 'hem'. :)

http://diveintopython.org/native_data_types/tuples.html#odbchelper.tuplemethods

I think tuples have methods, na?

[EMAIL PROTECTED]:~$ python
Python 2.4.3 (#1, Jun 20 2006, 11:52:59)
[GCC 3.3.5 (Debian 1:3.3.5-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "\n".join(dir(tuple))
__add__
__class__
__contains__
__delattr__
__doc__
__eq__
__ge__
__getattribute__
__getitem__
__getnewargs__
__getslice__
__gt__
__hash__
__init__
__iter__
__le__
__len__
__lt__
__mul__
__ne__
__new__
__reduce__
__reduce_ex__
__repr__
__rmul__
__setattr__
__str__
>>>

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


Re: Sansung YH-920 + Linux + yh-925-db-0.1.py = AttributeError: 'module' object has no attribute 'decode'

2006-07-22 Thread John Machin
rsd wrote:
> Hi,
>
> I'm trying get Samsung YH-920 mp3 player to work with Debian GNU/Linux.
> To do that I need to run
>http://www.paul.sladen.org/toys/samsung-yh-925/yh-925-db-0.1.py
> script, the idea behind the script is described at
>http://www.paul.sladen.org/toys/samsung-yh-925/
>
> I'm getting errors and hoping someone could give me some hints, for I
> have no python background.
>
> This is what I've done:
> 1. mounted YH-920 as /mnt/usb and transfered my MP3s to
> /mnt/usb/System/music/mp3 folder. That was easy.
>
> 2. Now, I need to run "yh-925-db-0.1.py" to update the database.
>
[snip]

>
>
> test:/mnt/usb/System# ./yh-925-db-0.1.py
> Traceback (most recent call last):
> File "./yh-925-db-0.1.py", line 195, in ?
> de.add_from_dict(e.unpack3(f))
> File "./yh-925-db-0.1.py", line 53, in unpack3
> u = utf_16_le.decode(fp.read(size))
> AttributeError: 'module' object has no attribute 'decode'
>
> Any ideas? Thanks

You don't say which version of Python you are running ... but my guess
is that it's 2.3 or earlier.

What the author is doing appears to be undocumented in Python 2.4 and
not supported in 2.3 & earlier.


Option (1): Upgrade your Python to 2.4 (visit www.python.org).
Option (2): Pass this problem description on to the author:

C:\junk>python
Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.

|>> from encodings import utf_16_le
# The above is not documented.

# get some sample data in utf-16-le encoding:
|>> u = u'abcdef'
|>> u
u'abcdef'
|>> le16 = u.encode('utf-16-le')
|>> le16
'a\x00b\x00c\x00d\x00e\x00f\x00'

|>> utf_16_le.decode(le16)
(u'abcdef', 12)
# Doesn't work on Python 2.3 and earlier -- the decode() and encode()
functions are not exposed.
# Note: returns a tuple containing (unicode_object, length_in_bytes).
In the Python script for the music player,  the length is not used and
the unicode object has to be extracted by doing the_tuple[0]

# One documented way of decoding a string strg using encoding enc is
strg.decode(enc)
|>> le16.decode('utf-16-le')
u'abcdef'
# ... but this was introduced in 2.2. The builtin unicode(strg, enc)
function (also documented) does the same thing & works all the way back
to Python 2.1 at least (I didn't keep copies of 1.6 & 2.0) . I've heard
of Linux users stuck on 2.1 for whatever reason but not on earlier
versions.

C:\junk>c:\python21\python
Python 2.1.3 (#35, Apr  8 2002, 17:47:50) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
|>> from encodings import utf_16_le
|>> u = u'abcdef'
|>> u
u'abcdef'
|>> le16 = u.encode('utf-16-le')
|>> le16
'a\x00b\x00c\x00d\x00e\x00f\x00'
|>> utf_16_le.decode(le16)
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: 'encodings.utf_16_le' module has no attribute 'decode'
|>> unicode(le16, 'utf-16-le')
u'abcdef'
|>>

Option (3): hack the source code along the above lines ...
Option (4): hope somebody will hack it for you 

HTH,
John

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


Compiler for external modules for python

2006-07-22 Thread pretoriano_2001
Hello:
I have interesting external modules that I want to incorporate to
python 2.4.3 and python 2.5b2 also. Some of them requires C/C++
compiler. I work with Win XP Sp2 and have installed VC2005 express (I
do not know if the compiler is the one with optimizing
characterisitics), when trying to install some module using "distutils"
program, it asks for C/C++ VC7 that is part of VS2003, it seems
distutils is not configured for VC8 that is part of VC2005.
Under this circumstances I tried to find the VC7 compiler from
microsoft sites, however it deflect to the new version of VS2005, so I
"lost the cord and the goat" .
I do not know what to do. Does anybody has some guidelines about this
matter?
Thanks!!!

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


Re: How to use pdb?

2006-07-22 Thread R. Bernstein
[EMAIL PROTECTED] writes:

> R. Bernstein wrote:
> > Perhaps what you are looking for is:
> >   python /usr/lib/python2.4/pdb.py Myprogram.py
> 
> I tried this and it did not work.  pdb did not load the file so it
> could be debugged.

lol. Yes, if you are not in the same directory as Myprogram.py you may
have to add be more explicit about where Myprogram.py is. 

Reminds me of the story of the guy who was so lazy that when he got an
award for "laziest person alive" he said, "roll me over and put it in
my back pocket." :-)

Glad you were able to solve your problem though.

For other similarly confused folks I have updated pydb's
documentation (in CVS):

  In contrast to running a program from a shell (or gdb), no path
  searching is performed on the python-script. Therefore python-script
  should be explicit enough (include relative or absolute file paths)
  so that the debugger can read it as a file name. Similarly, the
  location of the Python interpeter used for the script will not
  necessarily be the one specified in the magic field (the first line
  of the file), but will be the Python interpreter that the debugger
  specifies. (In most cases they'll be the same and/or it won't
  matter.)

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


Which Pyton Book For Newbies?

2006-07-22 Thread W. D. Allen
I want to write a retirement financial estimating program. Python was 
suggested as the easiest language to use on Linux. I have some experience 
programming in Basic but not in Python.

I have two questions:
 1. What do I need to be able to make user GUIs for the program, and
 2. Which book would be easiest to use to learn Python programming?

Thanks,

WDA
[EMAIL PROTECTED]

end
 


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


Re: Which Pyton Book For Newbies?

2006-07-22 Thread pretoriano_2001

W. D. Allen wrote:
> I want to write a retirement financial estimating program. Python was
> suggested as the easiest language to use on Linux. I have some experience
> programming in Basic but not in Python.
>
> I have two questions:
>  1. What do I need to be able to make user GUIs for the program, and

Try in: www.wxpython.org
or in
http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython&title=More%20Information

>  2. Which book would be easiest to use to learn Python programming?

Try in: http://docs.python.org/tut/tut.html
I nice Book I has is in:
http://www.amazon.com/gp/product/159059519X/sr=8-1/qid=1153612000/ref=pd_bbs_1/104-182-3979942?ie=UTF8

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


Re: Which Pyton Book For Newbies?

2006-07-22 Thread pretoriano_2001

W. D. Allen wrote:
> I want to write a retirement financial estimating program. Python was
> suggested as the easiest language to use on Linux. I have some experience
> programming in Basic but not in Python.
>
> I have two questions:
>  1. What do I need to be able to make user GUIs for the program, and

Try in: www.wxpython.org
or in
http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython&title=More%20Information

>  2. Which book would be easiest to use to learn Python programming?

Try in: http://docs.python.org/tut/tut.html
I nice Book I has is in:
http://www.amazon.com/gp/product/159059519X/sr=8-1/qid=1153612000/ref=pd_bbs_1/104-182-3979942?ie=UTF8

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


Re: using names before they're defined

2006-07-22 Thread Patrick Maupin

[EMAIL PROTECTED] wrote:
> I have a problem. I'm writing a simulation program with a number of
> mechanical components represented as objects. When I create instances
> of objects, I need to reference (link) each object to the objects
> upstream and downstream of it, i.e.
>
> supply = supply()
> compressor = compressor(downstream=combustor, upstream=supply)
> combuster = combuster(downstream=turbine, upstream=compressor)
> etc.
>
> the problem with this is that I reference 'combustor' before is it
> created. If I swap the 2nd and 3rd lines I get the same problem
> (compressor is referenced before creation).
>
>
> aargh!!! any ideas on getting around this?
>
> Dave

I have done similar things in the past.  One useful trick is to define
a special class for connections, create a single instance of this
class, and make all your connections as attributes of this instance.
For example:

world = Simulation()

world.supply = Supply()
world.compressor = Compressor(downstream=world.cumbustor,
upstream=world.supply)
world.cumbuster = Combuster(downstream=world.turbine,
upstream=world.compressor)

Because Python lets you control attribute access to your simulation
world object, it is relatively easy to make proxy objects for
attributes which don't yet exist via __getattr__, and then to insert
the real object into the proxy via __setattr__.

Alternatively, the script (using the same syntax as shown above!) can
simply collect all the connection information when it is run, then make
a "real" structure later.  This works best if your simulation objects
(Supply, Compressor, Cumbuster) allow setting of the connection
attributes after instantiation.

Regards,
Pat

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


Re: Python proficiency test

2006-07-22 Thread Richard Jones
Kent Johnson wrote:
> I recently helped create an on-line Python proficiency test. The
> publisher of the test is looking for beta testers to try the test and
> give feedback. If you are interested, here is an announcement from the
> publisher:

Had a look. In between my browser blocking a popup on every page and the
registration asking far more details that I felt necessary, I stopped
before looking at the actual test.


Richard

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


Re: Which Pyton Book For Newbies?

2006-07-22 Thread hanumizzle

W. D. Allen wrote:
> I want to write a retirement financial estimating program. Python was
> suggested as the easiest language to use on Linux. I have some experience
> programming in Basic but not in Python.
>
> I have two questions:
>  1. What do I need to be able to make user GUIs for the program, and
>  2. Which book would be easiest to use to learn Python programming?

I am a fairly experienced programmer and I have been reading Dive Into
Python. If you have prior experience, you may find it very
satisfactory. (But see a recent thread I started which points out a few
small mistakes...nothing too bad over all.) If you have less
programming experience, you may wish to look at Byte of Python. The
great thing about Python is that there is a ton of online material to
peruse...

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


""DRUG EMPIRE - INVEST IN QUANTUM COMPTERS GODS WEPON"""

2006-07-22 Thread switzerland qunatium computer
""DRUG EMPIRE - INVEST IN QUANTUM COMPTERS GODS WEPON"""

http://www.beyond-science.com RUN THIS WITH A QUNATIUM COMPUTER

THE GREATEST PROTECTION AND RIVAL'S ANY INTELLGENCE AGNECY'S

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


Re: How to test if object is sequence, or iterable?

2006-07-22 Thread Terry Reedy

"Nick Vatamaniuc" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Tim,
>
> An object is iterable if it implements the iterator protocol

There are presently two iterator protocols.  The old one will be likely be 
dropped in 3.0 (currently being discussed).

>. A good
> enough check to see if it does is to check for the presense of the
> __iter__() method. The way to do it is:
> hasattr(object,'__iter__')

Sorry, this check for the newer and nicer protocol but not the older one.

>>> hasattr('abc', '__iter__')
False

This may change in 2.6.  The defacto *version-independent* way to determine 
iterability is to call iter(ob).  If it returns an iterator, you can 
iterate; if it raises TypeError, you cannot.  Any it should be patched as 
necessary by the developers to continue doing the right thing in future 
versions.

Terry Jan Reedy



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


Re: Sansung YH-920 + Linux + yh-925-db-0.1.py = AttributeError: 'module' object has no attribute 'decode'

2006-07-22 Thread rsd
> 
> You don't say which version of Python you are running ... but my guess
> is that it's 2.3 or earlier.

Yes, you're right. I was using version 2.3.5

I'll see if I can get it working with 2.4

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


Re: getaddrinfo not found on SCO OpenServer 5.0.5

2006-07-22 Thread Martin v. Löwis
[EMAIL PROTECTED] wrote:
> 1) I've seen mention of native vs. Python getaddrinfo implementations.
> If that's true, how can I force the program to use the Python one?
> 
> 2) Is there an option to not use the BSD Library function?
> 
> 3) Finally, is there a trick to searching for shared libaries?

There is an autoconf test to determine whether getaddrinfo is
available on the system. You should study that test to find out
why it thinks the function is available when it is actually not.
If you can't do that, you can manually edit pyconfig.h to
change the outcome of configure.

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


Re: Compiler for external modules for python

2006-07-22 Thread Martin v. Löwis
[EMAIL PROTECTED] wrote:
> Under this circumstances I tried to find the VC7 compiler from
> microsoft sites, however it deflect to the new version of VS2005, so I
> "lost the cord and the goat" .
> I do not know what to do. Does anybody has some guidelines about this
> matter?

You need to use VS 2003 to build Python extensions; VS 2005 does not
work. As Microsoft has stopped shipping VS 2003, you could try to get
a copy on ebay.

Alternatively, you can use GNU MingW to build Python extensions.

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