Re: python and ajax

2005-08-30 Thread Stephan Diehl
On Mon, 29 Aug 2005 12:04:46 -0700, Steve Young wrote:

> Hi, I was wondering if anybody knew of any good
> tutorial/example of AJAX/xmlhttprequest in python.
> Thanks.
> 
> -Steve

As all the others have said already, AJAX has nothing to do with python,
but everything with JavaScript.
You might want to check out MochiKit (http://mochikit.com), a lightweight
JavaScript library written by Bob Ippolito. Bob did a very good job in
turning programming JS into a more python like experience.
- stephan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing, was Re: Bug in slice type

2005-08-30 Thread Antoon Pardon
Op 2005-08-29, Steve Holden schreef <[EMAIL PROTECTED]>:
> Antoon Pardon wrote:
>> Op 2005-08-27, Steve Holden schreef <[EMAIL PROTECTED]>:
>> 

>>>If you want an exception from your code when 'w' isn't in the string you 
>>>should consider using index() rather than find.
>> 
>> 
>> Sometimes it is convenient to have the exception thrown at a later
>> time.
>> 
>> 
>>>Otherwise, whatever find() returns you will have to have an "if" in 
>>>there to handle the not-found case.
>> 
>> 
>> And maybe the more convenient place for this "if" is in a whole different
>> part of your program, a part where using -1 as an invalid index isn't
>> at all obvious.
>> 
>> 
>>>This just sounds like whining to me. If you want to catch errors, use a 
>>>function that will raise an exception rather than relying on the 
>>>invalidity of the result.
>> 
>> 
>> You always seem to look at such things in a very narrow scope. You never
>> seem to consider that various parts of a program have to work together.
>> 
> Or perhaps it's just that I try not to mix parts inappropriately.

I didn't know it was inappropriately to mix certain parts. Can you
give a list of modules in the standard list I shouldn't mix.

>> So what happens if you have a module that is collecting string-index
>> pair, colleted from various other parts. In one part you
>> want to select the last letter, so you pythonically choose -1 as
>> index. In an other part you get a result of find and are happy
>> with -1 as an indictation for an invalid index. Then these
>> data meet.
>> 
> That's when debugging has to start. Mixing data of such types is 
> somewhat inadvisable, don't you agree?

The type of both data is the same, it is a string-index pair in
both cases. The problem is that a module from the standard lib
uses a certain value to indicate an illegal index, that has
a very legal value in python in general.

> I suppose I can't deny that people do things like that, myself included, 

It is not about what people do. If this was about someone implementing
find himself and using -1 as an illegal index, I would certainly agree
that it was inadvisable to do so. Yet when this is what python with
its libary offers the programmer, you seem reluctant find fault with
it.

> but mixing data sets where -1 is variously an error flag and a valid 
> index is only going to lead to trouble when the combined data is used.

Yet this is what python does. Using -1 variously as an error flag and
a valid index and when  people complain about that, you say it sounds like
whining.

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


Re: OpenSource documentation problems

2005-08-30 Thread Bryan Olson
Adriaan Renting wrote:
[...]

 > I do agree that a lot of OSS projects seem to lack somewhat in
 > the documentation department, compared to a lot of commercial
 > software. I would give the man page of gcc as an example, it's
 > just one 6600 line blurb.

I don't see any need to look beyond Python for a good example of
poor documentation.  Are there serious Python programmers who
don't constantly struggle with errors and omissions in the doc?

I don't mind the 6600 line blurb form, just so long as the info
is there and is correct.


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


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing,was Re: Bug in slice type

2005-08-30 Thread Bryan Olson
Steve Holden wrote:
 > I'm all in favor of discussions to make 3.0 a better
 > language.

This one should definitely be two-phase. First, the non-code-
breaking change that replaces-and-deprecates the warty handling
of negative indexes, and later the removal of the old style. For
the former, there's no need to wait for a X.0 release; for the
latter, 3.0 may be too early.

The draft PEP went to the PEP editors a couple days ago. Haven't
heard back yet.


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


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing,was Re: Bug in slice type

2005-08-30 Thread Antoon Pardon
Op 2005-08-29, Steven Bethard schreef <[EMAIL PROTECTED]>:
> Antoon Pardon wrote:
>> I think a properly implented find is better than an index.
>
> See the current thread in python-dev[1], which proposes a new method, 
> str.partition().  I believe that Raymond Hettinger has shown that almost 
> all uses of str.find() can be more clearly be represented with his 
> proposed function.

Do we really need this? As far as I understand most of this
functionality is already provided by str.split and str.rsplit

I think adding an optional third parameter 'full=False' to these
methods, would be all that is usefull here. If full was set
to True, split and rsplit would enforce that a list with
maxsplit + 1 elements was returned, filling up the list with
None's if necessary.


  head, sep, tail = str.partion(sep)

would then almost be equivallent to

  head, tail = str.find(sep, 1, True)


Code like the following:

 head, found, tail = result.partition(' ')
 if not found:
 break
 result = head + tail


Could be replaced by:

 head, tail = result.split(' ', 1, full = True)
 if tail is None
 break
 result = head + tail


I also think that code like this:

  while tail:
  head, _, tail = tail.partition('.')
  mname = "%s.%s" % (m.__name__, head)
  m = self.import_it(head, mname, m)
  ...


Would probably better be written as follows:

  for head in tail.split('.'):
  mname = "%s.%s" % (m.__name__, head)
  m = self.import_it(head, mname, m)
  ...


Unless I'm missing something.


-- 
Antoon Pardon


[1]http://mail.python.org/pipermail/python-dev/2005-August/055781.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing,was Re: Bug in slice type

2005-08-30 Thread Terry Reedy

"Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message 
news:[EMAIL PROTECTED]

> Really it's x[-1]'s behavior that should go, not find/rfind.

I complete disagree, x[-1] as an abbreviation of x[len(x)-1] is extremely 
useful, especially when 'x' is an expression instead of a name.  But even 
if -1 were not a legal subscript, I would still consider it a design error 
for Python to mistype a non-numeric singleton indicator as an int.  Such 
mistyping is  only necessary in a language like C that requires all return 
values to be of the same type, even when the 'return value' is not really a 
return value but an error signal.  Python does not have that typing 
restriction and should not act as if it does by copying C.

> Will socket.connect_ex also go?

Not familiar with it.

>  How about dict.get?

A default value is not necessarily an error indicator.  One can regard a 
dict that is 'getted' as an infinite dict matching all keys with the 
default except for a finite subset of keys, as recorded in the dict.

If the default is to be regarded a 'Nothing to return' indicator, then that 
indicator *must not* be in the dict.  A recommended idiom is to then create 
a new, custom subset of object which *cannot* be a value in the dict. 
Return values can they safely be compared with that indicator by using the 
'is' operator.

In either case, .get is significantly different from .find.

Terry J. Reedy



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


Re: Writing Multithreaded Client-Server in Python.

2005-08-30 Thread google

Paul Rubin schreef:

> "Sidd" <[EMAIL PROTECTED]> writes:
> >I tried finding and example of multithreaded client-serve program in
> > python. Can any one please tell me how to write a multithreaded
> > client-server programn in python such that
> > 1.It can handle multiple connections
> > 2.It uses actual threads and not select() or some other function
>
> If you mean multiple threads on the server side, see the SocketServer
> module and its ThreadingMixin class.  You may have to look at the
> source code since up until recently the docs were incomplete.  There
> is a big helpful comment at the top of SocketServer.py which recently
> got merged into the library reference manual.

Yes, however the term 'ThreadingMixIn' is a bit confusing (at least it
was to me).
What it does do, is handle each request (from the same client too) in a
new separate thread. Convenient if your processing intensive handle may
otherwise slow down the main server process becoming less responsive to
other requests.
What it doesn't do (and what Sidd seems to search as is suggested by
his 'select()' remark) is handle each client in a separate thread.

This is in fact listed in the (scarce) doc as a 'ToDo' of the
SocketServer if my memory serves me right.
If you want to apply SocketServer such that each client corresponds to
one thread that handles its' requests (and maintains its state), don't
use ThreadingMixIn - only the thread-selection will be executed in a
separate thread.
You could maintain a dictionary of Threads running RequestHandlers for
each client in the server class.
I use a new Handler for each incoming request, parse a username
parameter from the message and select the thread-handler from the
server dict. Each handler in the dict contains an open outgoing socket,
so I can also e.g. broadcast and notify clients.
Alternatively, you can (probably) keep the client2server socket open as
well (on both client and server). Thread selection should then
(hopefully :-) happen magically by calling the handle() method in each
thread directly.

HTH


Thijs

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


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing,was Re: Bug in slice type

2005-08-30 Thread Paul Rubin
"Terry Reedy" <[EMAIL PROTECTED]> writes:
> > Really it's x[-1]'s behavior that should go, not find/rfind.
> 
> I complete disagree, x[-1] as an abbreviation of x[len(x)-1] is extremely 
> useful, especially when 'x' is an expression instead of a name.

There are other abbreviations possible, for example the one in the
proposed PEP at the beginning of this thread.

> But even 
> if -1 were not a legal subscript, I would still consider it a design error 
> for Python to mistype a non-numeric singleton indicator as an int.

OK, .find should return None if the string is not found.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing Multithreaded Client-Server in Python.

2005-08-30 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> What it does do, is handle each request (from the same client too) in a
> new separate thread. Convenient if your processing intensive handle may
> otherwise slow down the main server process becoming less responsive to
> other requests.
> What it doesn't do (and what Sidd seems to search as is suggested by
> his 'select()' remark) is handle each client in a separate thread.

I don't know what you mean by that.  It launches a new thread for each
client connection.  The connection is two-way and can last as long as
desired.  If you're imagining something like a web server handling
http requests, using http 1.1 keepalive, you could handle any number
of requests in that connection.

> If you want to apply SocketServer such that each client corresponds to
> one thread that handles its' requests (and maintains its state), don't
> use ThreadingMixIn - only the thread-selection will be executed in a
> separate thread.

What do you mean by "each client"?  If a client connects, does some
stuff, disconnects, and later reconnects, how do you know that it's
the same client that's come back?
-- 
http://mail.python.org/mailman/listinfo/python-list


wxnotebook and tooltips

2005-08-30 Thread klaus . roedel
Hi,
I've implemented a wxnotebook on my application.
I can set a tooltip for the complete notebook, but I want to set for
every page a tooltip, so that the user can get additionally information
over it before he change it.
Is this possible with python and wxwidgets?
Thanks for any help.
Greets Klaus

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


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing,was Re: Bug in slice type

2005-08-30 Thread Bryan Olson
Terry Reedy wrote:
 > "Paul Rubin" wrote:
 >
 >>Really it's x[-1]'s behavior that should go, not find/rfind.
 >
 > I complete disagree, x[-1] as an abbreviation of x[len(x)-1] is 
extremely
 > useful, especially when 'x' is an expression instead of a name.

Hear us out; your disagreement might not be so complete as you
think. From-the-far-end indexing is too useful a feature to
trash. If you look back several posts, you'll see that the
suggestion here is that the index expression should explicitly
call for it, rather than treat negative integers as a special
case.

I wrote up and sent off my proposal, and once the PEP-Editors
respond, I'll be pitching it on the python-dev list. Below is
the version I sent (not yet a listed PEP).


--
--Bryan


PEP: -1
Title: Improved from-the-end indexing and slicing
Version: $Revision: 1.00 $
Last-Modified: $Date: 2005/08/26 00:00:00 $
Author: Bryan G. Olson <[EMAIL PROTECTED]>
Status: Draft
Type: Standards Track
Content-Type: text/plain
Created: 26 Aug 2005
Post-History:


Abstract

 To index or slice a sequence from the far end, we propose
 using a symbol, '$', to stand for the length, instead of
 Python's current special-case interpretation of negative
 subscripts. Where Python currently uses:

 sequence[-i]

 We propose:

 sequence[$ - i]

 Python's treatment of negative indexes as offsets from the
 high end of a sequence causes minor obvious problems and
 major subtle ones. This PEP proposes a consistent meaning
 for indexes, yet still supports from-the-far-end
 indexing. Use of new syntax avoids breaking existing code.


Specification

 We propose a new style of slicing and indexing for Python
 sequences. Instead of:

 sequence[start : stop : step]

 new-style slicing uses the syntax:

 sequence[start ; stop ; step]

 It works like current slicing, except that negative start or
 stop values do not trigger from-the-high-end interpretation.
 Omissions and 'None' work the same as in old-style slicing.

 Within the square-brackets, the '$' symbol stands for the
 length of the sequence. One can index from the high end by
 subtracting the index from '$'. Instead of:

 seq[3 : -4]

 we write:

 seq[3 ; $ - 4]

 When square-brackets appear within other square-brackets,
 the inner-most bracket-pair determines which sequence '$'
 describes. The length of the next-outer sequence is denoted
 by '$1', and the next-out after than by '$2', and so on. The
 symbol '$0' behaves identically to '$'. Resolution of $x is
 syntactic; a callable object invoked within square brackets
 cannot use the symbol to examine the context of the call.

 The '$' notation also works in simple (non-slice) indexing.
 Instead of:

 seq[-2]

 we write:

 seq[$ - 2]

 If we did not care about backward compatibility, new-style
 slicing would define seq[-2] to be out-of-bounds. Of course
 we do care about backward compatibility, and rejecting
 negative indexes would break way too much code. For now,
 simple indexing with a negative subscript (and no '$') must
 continue to index from the high end, as a deprecated
 feature. The presence of '$' always indicates new-style
 indexing, so a programmer who needs a negative index to
 trigger a range error can write:

 seq[($ - $) + index]


Motivation

 From-the-far-end indexing is such a useful feature that we
 cannot reasonably propose its removal; nevertheless Python's
 current method, which is to treat a range of negative
 indexes as special cases, is warty. The wart bites novice or
 imperfect Pythoners by not raising an exceptions when they
 need to know about a bug. For example, the following code
 prints 'y' with no sign of error:

 s = 'buggy'
 print s[s.find('w')]

 The wart becomes an even bigger problem with more
 sophisticated use of Python sequences. What is the 'stop'
 value for a slice when the step is negative and the slice
 includes the zero index? An instance of Python's slice type
 will report that the stop value is -1, but if we use this
 stop value to slice, it gets misinterpreted as the last
 index in the sequence. Here's an example:

 class BuggerAll:

 def __init__(self, somelist):
 self.sequence = somelist[:]

 def __getitem__(self, key):
 if isinstance(key, slice):
 start, stop, step = key.indices(len(self.sequence))
 # print 'Slice says start, stop, step are:', start, 
stop, step
 return self.sequence[start : stop : step]


 print   range(10) [None : None : -2]
 print BuggerAll(range(10))[None : None : -2]

 The above prints:

 [9, 7, 5, 3, 1]
 []

 Un-commenting the print state

array of arrays question

2005-08-30 Thread Meo
Hi,

Here is what I'm doing in python 2.4.1 :

>>> aOfa=[[[]]*3]*4
>>> aOfa
[[[], [], []], [[], [], []], [[], [], []], [[], [], []]]
>>> aOfa[3][2].append(1)
>>> aOfa
[[[1], [1], [1]], [[1], [1], [1]], [[1], [1], [1]], [[1], [1], [1]]]

Ok, so there is something I didn't understand about python's arrays.

The result I was expecting was :

[[[], [], []], [[], [], []], [[], [], []], [[], [], [1]]]

Somebody understand what's going on here?

Thank

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


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing,was Re: Bug in slice type

2005-08-30 Thread Paul Rubin
Bryan Olson <[EMAIL PROTECTED]> writes:
>  Specifically, to support new-style slicing, a class that
>  accepts index or slice arguments to any of:
> 
>  __getitem__
>  __setitem__
>  __delitem__
>  __getslice__
>  __setslice__
>  __delslice__
> 
>  must also consistently implement:
> 
>  __len__
> 
>  Sane programmers already follow this rule.

It should be ok to use new-style slicing without implementing __len__
as long as you don't use $ in any slices.  Using $ in a slice without
__len__ would throw a runtime error.  I expect using negative
subscripts in old-style slices on objects with no __len__ also throws
an error.

Not every sequence needs __len__; for example, infinite sequences, or
sequences that implement slicing and subscripts by doing lazy
evaluation of iterators:

  digits_of_pi = memoize(generate_pi_digits())  # 3,1,4,1,5,9,2,...
  print digits_of_pi[5]   # computes 6 digits and prints '9'
  print digits_of_pi($-5)  # raises exception
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: array of arrays question

2005-08-30 Thread Paul Rubin
"Meo" <[EMAIL PROTECTED]> writes:
> Somebody understand what's going on here?

Yes, []*3 gives you three references to the same empty list, not three
separate empty lists.  You need something like

   [[] for i in xrange(3)]

to get separate lists.

Another example:

a = [1,2,3]
b = a
a[0] = 5
print b   # prints [5,2,3]

Do you understand now?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python port on Palm Treo?

2005-08-30 Thread tooper
I'm not aware of any Treo dedicated port, but as Treo is running Palm,
the Palm port of Python should be OK (if I remember well it's pypi or
pipy, standing for PYthon for palm PIlot)
Hope it helps...

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


time.mktime problem

2005-08-30 Thread McBooCzech
Hi, on Linux (Fedora FC4) and Python 2.4.1
I am trying to know the time delta in seconds between two times given
in the HHMMSS format. My code looks like:

import datetime, time
ta1=(time.strptime('01', '%H%M%S'))
ta2=(time.strptime('230344', '%H%M%S'))
t1=time.mktime(ta1)
t2=time.mktime(ta2)
print t1, t2

-2147483648.0 -2147483648.0

I just can not figure out, why the t1 and t2 are the same?


Thanks for your comments

Petr Jakes

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


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing,was Re: Bug in slice type

2005-08-30 Thread Antoon Pardon
Op 2005-08-30, Terry Reedy schreef <[EMAIL PROTECTED]>:
>
> "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message 
> news:[EMAIL PROTECTED]
>
>> Really it's x[-1]'s behavior that should go, not find/rfind.
>
> I complete disagree, x[-1] as an abbreviation of x[len(x)-1] is extremely 
> useful, especially when 'x' is an expression instead of a name.

I don't think the ability to easily index sequences from the right is
in dispute. Just the fact that negative numbers on their own provide
this functionality.

Because I sometimes find it usefull to have a sequence start and
end at arbitrary indexes, I have written a table class. So I
can have a table that is indexed from e.g. -4 to +6. So how am
I supposed to easily get at that last value?

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


Re: OpenSource documentation problems

2005-08-30 Thread Roel Schroeven
Bryan Olson wrote:
> Adriaan Renting wrote:
> [...]
> 
>  > I do agree that a lot of OSS projects seem to lack somewhat in
>  > the documentation department, compared to a lot of commercial
>  > software. I would give the man page of gcc as an example, it's
>  > just one 6600 line blurb.
> 
> I don't see any need to look beyond Python for a good example of
> poor documentation.  Are there serious Python programmers who
> don't constantly struggle with errors and omissions in the doc?

There certainly are some areas where the documentation could be 
improved, but on the whole I think it's pretty good. I guess I'm not 
what you call a serious Python programmer, but still so far the 
documentation has provided answers to practically all questions I had.

> I don't mind the 6600 line blurb form, just so long as the info
> is there and is correct.

I agree. And on the whole I like manpages better than GNU's info system. 
info is good for providing background information and an overview of how 
everything works, but when I need a reference about command line options 
or config file settings, my experience is that I can find the needed 
information much easier in man pages.

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

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


Re: Release of PyPy 0.7.0

2005-08-30 Thread holger krekel
Hi Valentino, Michael, all, 

On Sun, Aug 28, 2005 at 20:46 +0200, Valentino Volonghi aka Dialtone wrote:
> Michael Sparks <[EMAIL PROTECTED]> wrote:
> > Would it be useful for people to start trying out their modules/code to see
> > if they work with this release, and whether they can likewise be translated
> > using the C/LLVM backends, or would you say this is too early? (I'm more
> > thinking in terms of it providing real world usecases in the hope of
> > finding things that don't work - rather than anything else)
> 
> This is not how it works. Pypy doesn't translate your code to C/LLVM. 
> Currently PyPy can only translate a pretty simple subset of python
> called RPython which has a very C-like syntax (but without memory
> management code). This is needed to allow type inference inside the
> interpreter code.

This is mostly true but maybe a bit misleading.  The subset of Python 
that we can translate does not involve special syntax. For example
we can translate 

http://codespeak.net/pypy/dist/pypy/translator/goal/richards.py

and gain some speed up by a factor of 70 over interpretation with 
CPython.  The "RPython" limitation mainly refers to the way 
how dynamically you use Python and how unambigously your values
flow across your functions and methods.  Also you cannot, for example, 
create classes dynamically while creating instances is, of course, 
no problem.  Also, we support all Python control flow statements. 
For a more detailed list, look at: 


http://codespeak.net/pypy/dist/pypy/doc/coding-guide.html#rpython-definition-not

The real culprit is that we don't currently intend to try
offering a tool that can automatically translate Python
modules to C because we are still experimenting with and
targeting our own Python interpreter and tackling the
challenges that arise out of translating this efficiently. 
It's a matter of focus of the current dev group and not 
one of technical feasibility.  

If one or more people would want to care for producing,
testing and documenting such a tool on top of our current code
base then the next weeks might be good for that as we intend 
to go for some cleanup refactorings anyway. 

> The code in your application is application code and can be whatever you
> want, you may try to translate it to C/LLVM but it won't be that good of
> course because the annotator is not that intelligent.

See above.  You can try to translate python programs with a bit 
of effort and determination to find your way :-) 

> Just In Time compilation a-la-psyco is planned before the 1.0 release of
> pypy. 

We don't have a fixed version roadmap but indeed, we plan to work 
on JIT compilation and other niceties rather soon now. 

cheers, 

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


Re: Python port on Palm Treo?

2005-08-30 Thread tooper
I'm not aware of any Treo dedicated port, but as Treo is running Palm,
the Palm port of Python should be OK (if I remember well it's pypi or
pipy, standing for PYthon for palm PIlot)
Hope it helps...

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


Re: Release of PyPy 0.7.0

2005-08-30 Thread Michael Hudson
Michael Sparks <[EMAIL PROTECTED]> writes:

> Valentino Volonghi aka Dialtone wrote:
>
>> Michael Sparks <[EMAIL PROTECTED]> wrote:
>> 
>>> Would it be useful for people to start trying out their modules/code to
>>> see if they work with this release, and whether they can likewise be
>>> translated using the C/LLVM backends, or would you say this is too early?
>>> (I'm more thinking in terms of it providing real world usecases in the
>>> hope of finding things that don't work - rather than anything else)
>> 
>> This is not how it works. 
>
> I beg to differ - it is how it can work (just not the default or currently
> recommended). 

The chance of any random module you have written being rpython is more
or less zero, so it's not _that_ interesting for you to try to compile
them with PyPy.

> """You can also use the translate_pypy.py script to try out several smaller
> programs, e.g. a slightly changed version of Pystone:
> cd pypy/translator/goal
> python translate_pypy.py targetrpystone
> """
>
> Which is pretty cool of course. For those of interest running pystone with
> the pypy compiled native binary has the following results for pystones on
> my machine:
>
> [EMAIL PROTECTED]:~/pypy-0.7.0/pypy/translator/goal> ./pypy-c
> debug: entry point starting
> debug:  argv -> ./pypy-c
> debug: importing code
> debug: calling code.interact()
> Python 2.4.1 (pypy 0.7.0 build) on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> (InteractiveConsole)
> from test import pystone
> pystone.main(1000)
> Pystone(1.1) time for 1000 passes = 13.97
> This machine benchmarks at 71.582 pystones/second
>
>
> The same results for CPython:
> [EMAIL PROTECTED]:~/pypy-0.7.0/pypy/translator/goal> python
> Python 2.4 (#1, Mar 22 2005, 21:42:42)
> [GCC 3.3.5 20050117 (prerelease) (SUSE Linux)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 from test import pystone
 pystone.main()
> Pystone(1.1) time for 5 passes = 1.58
> This machine benchmarks at 31645.6 pystones/second
>
> Obviously therefore anyone seeking to translate their existing code from
> python to an executable directly using pypy would not be doing it for
> performance reasons (again, something I'm aware of watching the
> updates come out and having run svn checkouts at previous times).

No, you're still operating at the wrong level here (very easily done).
This is the _translated PyPy_ interpreting pystone.  If you run a
_translated pystone_ you'll (hopefully) get a different, faster
answer.

In expected order of execution speed:

interpreted pypy interpreting pystone
translated pypy interpreting pystone
cpython interpreting pystone
translated pystone

> Anyway, whether it's sensible or not I'm going to play with translating some
> of my modules :)

Whatever floats your boat :)

Cheers,
mwh

-- 
  Ability to type on a computer terminal is no guarantee of sanity,
  intelligence, or common sense.
 -- Gene Spafford's Axiom #2 of Usenet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DOM text

2005-08-30 Thread Richard Lewis

On Fri, 26 Aug 2005 11:43:18 +0100, "Richard Lewis"
<[EMAIL PROTECTED]> said:
> 
> I'm implementing a Cursor class now which keeps track of the current
> parent Element, text node and character position so that I can easily (I
> hope ;-) work out where the splitting and inserting needs to occur. Wish
> me luck!!
> 
Sorry to revive this thread, but there's something else thats causing me
confusion now!

My cursor class is going quite well and I can insert text and element
nodes. It also has methods to 'move' the 'cursor' forward and backward
by a node at a time. It keeps the current_node in an instance variable
which is initially assigned an element from a DOM tree instance created
elsewhere.

The problem I've come up against is when I use the next_node() method,
and the current_node is a (leaf) Text node, the nextSibling property of
current_node is None, where I know (from the document structure) that it
shouldn't be. To make matters more confusing, if I manually create an
instance of my DOM tree (interactively) and check the nextSibling of the
same Text node, it is the correct value (another Element node) while the
nextSibling property of the SectionCursor instance's current_node
property (referring to the same node) is None. I *think* it only applies
to leaf Text nodes.

Here is the *complete* code for my SectionCursor class:
(note that 'sections' are large(ish) document fragments from the main
document)
==
class SectionCursor:
  def __init__(self, section_element):
"""Create a SectionCursor instance using the 'section_element' as
the parent element."""
self.section_element = section_element
self.current_node = self.section_element.firstChild
self.char_pos = 0

  def forward(self, skip=1):
"""Move the cursor forward 'skip' character positions."""
if self.current_node.nodeType == Node.TEXT_NODE:
  self.char_pos += skip
  if self.char_pos > len(self.current_node.data):
self.next_node()
else: self.next_node()

  def backward(self, skip=1):
"""Move the cursor backward 'skip' character positions."""
if self.current_node.nodeType == Node.TEXT_NODE:
  self.char_pos -= skip
  if self.char_pos < 0:
self.previous_node()
else: self.previous_node()

  def next_node(self):
"""Move the cursor to the next node; either the first child or next
sibling."""
if self.current_node.hasChildNodes():
  self.current_node = self.current_node.firstChild
elif self.current_node.nextSibling is not None:
  self.current_node = self.current_node.nextSibling
else: return False
self.char_pos = 0
return True

  def previous_node(self):
"""Move the cursor to the previous node; either the previous sibling
or the parent."""
if self.current_node.previousSibling is not None:
  self.current_node = self.current_node.previousSibling
elif self.current_node.parentNode != self.section_element:
  self.current_node = self.current_node.parentNode
else: return False
if self.current_node.nodeType == Node.TEXT_NODE:
  self.char_pos = len(self.current_node.data) - 1
else:
  self.char_pos = 0
return True

  def jump_to(self, node, char_pos=0):
"""Jump to a node and character position."""
self.current_node = node
self.char_pos = char_pos

  def insert_node(self, ref_doc, new_node):
"""Insert a node (new_node); ref_doc is an instance of the Document
class."""
if self.current_node.nodeType == Node.TEXT_NODE: 
  parent_node = self.current_node.parentNode
  text_node = self.current_node
  next_node = text_node.nextSibling

  preceeding_portion =
  ref_doc.createTextNode(text_node.data[:self.char_pos])
  proceeding_portion =
  ref_doc.createTextNode(text_node.data[self.char_pos:])

  parent_node.replaceChild(preceeding_portion, text_node)
  parent_node.insertBefore(new_node, next_node)
  parent_node.insertBefore(proceeding_portion, next_node)
  # where is the cursor?
else:
  parent_node = self.current_node.parent_element
  parent_node.insertBefore(new_node, self.current_node)
  # where is the cursor?

  def append_child_node(self, ref_doc, new_node):
pass

  def insert_element(self, ref_doc, tag_name, attrs=None):
"""Insert an element called tag_name and with the attributes in the
attrs dictionary; ref_doc is an instance of the Document class."""
new_element = ref_doc.createElement(tag_name)
if attrs is not None:
  for name, value in attrs.items():
new_element.setAttribute(name, value)
self.insert_node(ref_doc, new_element)

  def insert_text(self, ref_doc, text):
"""Insert the text in 'text'; ref_doc is an instance of the Document
class."""
new_text = ref_doc.createTextNode(text)
self.insert_node(ref_doc, new_text)

  def remove_node(self):
"""Remove the current node."""
condemned_node = self.current_node
if not self.next

Re: File parser

2005-08-30 Thread MrJean1
Take a closer look at SimpleParse/mxTextTools



We have used these to parse log files of several 100 MB with simple and
complex grammars up to 250+ productions.  Highly recommended.

/Jean Brouwers

PS) For an introduction see also this story


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


Re: [Jython-users] Re: [Jython-dev] Parsing grammar for jython available (compatible with python 2.4)

2005-08-30 Thread Fabio Zadrozny
Well, if you post your problems in the pydev bug-tracker, maybe those 
cases can be sorted out...

(one area on where it is really difficult currently, is when you do 
code-completion and it is unable to parse your module... is this your case?)

Cheers,

Fabio

could ildg wrote:

> thanks.
> pydev is very nice, I like it.
> But sometimes the code completion will not work.
>
> On 8/30/05, *Frank Wierzbicki* <[EMAIL PROTECTED] 
> > wrote:
>
>
> The code, as well as the files for javacc and asdl (both were
> changed)
> are available in the pydev cvs at sourceforge, in the
> org.python.pydev.parser module (the packages should be the
> same jython
> uses -- org.python.parser and org.python.parser.ast).
>
> The tests I used are available in the tests source folder
> (org.python.pydev.parser.PyParserTest)
>
> Hey -- that's great!
> Unfortunately we probably will not be able to integrate 2.4
> features in until after we get a 2.3 version stable... But I hope
> you can remind us of this work (or I can remember it) when we do
> get to that point.  If you want to leave a strong reminder you
> could submit your changes as a patch -- but I mean this as only
> the gentlest of nudges since it will likely be quite a while
> before we could really look at it.
>
> Thanks,
> Frank
>  
>
>
>


-- 
Fabio Zadrozny
--
Software Developer

ESSS - Engineering Simulation and Scientific Software
www.esss.com.br

PyDev - Python Development Enviroment for Eclipse
pydev.sf.net
pydev.blogspot.com


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


Re: Pypy - Which C modules still need converting to py?

2005-08-30 Thread holger krekel
Hi Caleb, 

On Tue, Feb 08, 2005 at 22:32 -0500, Caleb Hattingh wrote:
> I saw it on a webpage a few days ago, can't seem to find it again.  Tried  
> a google search for
> 
> "pypy needed translate C modules"
> 
> but that didn't turn up what I was looking for.   Anyone have that page  
> ref handy listing the C modules that the pypy team need translated into  
> python?

I think that currently the best page for that actually 
is the compliancy test results page: 

http://codespeak.net/~hpk/pypy-testresult/

especially in the "non-core" section further below.  You'll
see a list of the currently not implemented C-level modules.
However, most interesting is completing full posix/os-module
support e.g.  for listdir() and process-creation
functionality.  Also having a socket-API wrapper at
RPython/low-level-function level and for e.g.  'zlib' seem
like "big time" enablers for allowing more programs/modules to
run on top of pypy-c/pypy-llvm. (we are employing a "pypy-XYZ" 
scheme where XYZ marks the backend). 

Recently, Niklaus Heidimann successfully implemented 
the array and _sre module as part of his SOC project, of 
which he got the latter to translate to low-level during the 
last Heidelberg sprint!  

cheers, 

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


Re: time.mktime problem

2005-08-30 Thread Matt Hammond
I don't get the same results:

>>> import datetime, time
>>> ta1=(time.strptime('01', '%H%M%S'))
>>> ta2=(time.strptime('230344', '%H%M%S'))
>>> t1=time.mktime(ta1)
>>> t2=time.mktime(ta2)
>>> print t1, t2
-2208988799.0 -2208905776.0
>>> print t1-t2
-83023.0

Suse 9.3, python 2.4 (all 64bit)


Matt

-- 

| Matt Hammond
| R&D Engineer, BBC Research and Development, Tadworth, Surrey, UK.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing,was Re: Bug in slice type

2005-08-30 Thread Robert Kern
Bryan Olson wrote:

>  Currently, user-defined classes can implement Python
>  subscripting and slicing without implementing Python's len()
>  function. In our proposal, the '$' symbol stands for the
>  sequence's length, so classes must be able to report their
>  length in order for $ to work within their slices and
>  indexes.
> 
>  Specifically, to support new-style slicing, a class that
>  accepts index or slice arguments to any of:
> 
>  __getitem__
>  __setitem__
>  __delitem__
>  __getslice__
>  __setslice__
>  __delslice__
> 
>  must also consistently implement:
> 
>  __len__
> 
>  Sane programmers already follow this rule.

Incorrect. Some sane programmers have multiple dimensions they need to
index.

  from Numeric import *
  A = array([[0, 1], [2, 3], [4, 5]])
  A[$-1, $-1]

The result of len(A) has nothing to do with the second $.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Re: Writing portable applications

2005-08-30 Thread Ulrich Hobelmann
Mike Meyer wrote:
> If your web apps are well-written, any of them should work. As
> previously stated, Sturgeon's law applies to the web, so chances are
> good they aren't well-written.

:)

>> But as soon as some user of platform 54 tries your website, she'll
>> encounter some weird behavior without even knowing why.  And maybe so
>> will you, especially if you don't have that platform there for
>> testing. I don't understand how this web thing changes anything...
> 
> The only difference is that the user of Platform 54 has a chance to
> use your app. Sure, it may not work because that platforms bugs are
> radically different from the bugs in the platforms you tested
> on. Raising the possibility of your app working from "no way in hell"
> to "maybe" is significant.

Ok, there's a chance...

>> With POSIX at least you have a real bug-report for the guy responsible
>> for it.  If a platform keeps being buggy, with no fixes coming, screw
>> them.  Every user will see that sooner or later, and these platforms
>> die.  Even Windows is quite stable/reliable after 10+ years NT!
> 
> You do? All your porters reliably give you bug reports? Can I have
> some?

No, I mean, when you compile something on POSIX and it doesn't work, you 
have a bug to report.  Of course many vendors might ignore them, and 
often don't send you any feedback at all (unfortunately), probably 
because contact between the company's programmer and you is considered 
bad for some reason (I'd consider it good support).

> These don't answer the question. Maybe because I didn't explain it
> fully. Do you have an example of an application that implements a
> simple protocol along with a client and server where HTTP+HTML were
> considered as an alternative, and rejected as "more difficult" than
> the path actually chosen?

No, because I don't know who considered HTTP+HTML before going the other 
way.  HTTP certainly is used increasingly (for XML transfers, WebDAV, 
RSS, ...), because it's quite simple widely implemented.  But as I said, 
there's RSS as a new standard, there's DAV and others.  They don't use 
HTML, because custom protocols can be easy but have advantages.  I guess 
it differs.  Some applications make a lot of sense in a hypertext 
context; others don't.

>> There's NNTP.  There's RSS.  There's Atom.  The latter two emerged
>> quite painlessly, even though you could maybe use some website for
>> what they provide.  But this way you have lots of clients for lots of
>> platforms already.
> 
> NNTP predates HTTP. Atom (and I assume RSS) uses HTTP as a transport,
> so there's no new protocol invovled - just a new file format.

Yes.  I consider HTML a kind of protocol in that sense, though.  It's a 
format, and it needs interpretation, too.

>> Sure, but you can tell your customers that unfortunately their system
>> vendor refuses to fix a bug and ask THEM to ask that vendor.  Boy,
>> will they consider another platform in the future, where bugs do get
>> fixed ;)
> 
> Yup. You and that platform vendor are no win the set of vendors that
> don't fix bugs. Personally, I'd rather provide a workaround and keep
> the customer.

Short-term definitely.  Long-term I'd try to migrate the customer 
(depending on how much influence I have in their IT context).

>>> Not all platforms are POSIX. If you're ok limiting your application
>>> to
>>> a small subset of the total number of platforms available, then
>>> there's no advantage to using web technologies. Some of us aren't
>>> satisifed with that, though.
>> Sure.  You have to look where your users are.  Chances are that with
>> obscure systems they can't use most web-apps either.
> 
> Right. Chances are they can only use well-written ones. If you write
> those, your stuff will stand out for them.

Very good point.  You give me back my faith in web-apps ;)

>> That's true, though I think the future of development lies in
>> overcoming that program-code-as-text thing (NOT visual programming,
>> just tool-based, structured).  Smalltalk did it decades ago.
> 
> Last time I looked at smalltalk, it still presented program code as
> text. So I think you need to clarify what you mean.

You have class and method browsers, while most Java and C code is still 
edited file-wise (though with options to hide methods except for their 
declaration header).  I think it makes sense to ignore the file thing 
and just use browsers like that (kind of like having every C function in 
one file, but with the headers and visibility of functions managed by 
your IDE/build system, not by you by hand.

>>> You don't have to guess - finding examples of XUL isn't hard at all. I
>>> think XML gets used in a lot of places where it isn't appropriate. One
>>> of the few places where it is appropriate is where you want a file
>>> format that lots of independent implementations are going to be
>>> reading. This could well be one of those times.
>> Maybe, but for applications that aren't predominantly concerned about
>> text, I'd 

Re: DOM text

2005-08-30 Thread Richard Lewis

On Tue, 30 Aug 2005 11:17:25 +0100, "Richard Lewis"
<[EMAIL PROTECTED]> said:
> 
> Here is the *complete* code for my SectionCursor class:

In case anyone's interested, I've just noticed a logical error in the
next_node() method:
=
def next_node(self):
  if self.current_node.hasChildNodes():
self.current_node = self.current_node.firstChild
  elif self.current_node.nextSibling is not None:
self.current_node = self.current_node.nextSibling
  else:
while self.current_node.parentNode.nextSibling is None\
 and self.current_node != self.section_element:
  self.current_node = self.current_node.parentNode
  if self.current_node != self.section_element:
self.current_node = self.current_node.parentNode.nextSibling
  else: return False
  self.char_pos = 0
  return True
=

which doesn't solve the original problem. Though I think it may be
causing a (related) problem: it says the self.current_node.parentNode is
of NoneType. If there is a problem with assigning parts of an existing
DOM tree to other variables, might this be another symptom?

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


micro-python - is it possible?

2005-08-30 Thread Evil Bastard
Hi,

Has anyone done any serious work on producing a subset of python's
language definition that would suit it to a tiny microcontroller
environment?

In its full form, python is a resource hog. If a microcontroller
implementation honoured the 'everything is an object' philosophy, the
code would spend 80% of the time in memory allocation/deallocation
routines, taking tens or hundreds of times longer for even the simplest
tasks.

One kludge I've come up with towards a micro-python is the use of 'magic
pseudo-functions' that lock in specific types and behaviour, eg:

  - in the mainline, outside of any functions:
  - x = int16(45)
 - creates a signed 16-bit global int called x, initialises it
   to 45
  - y = const32(0x3342)
 - creates a 32-bit constant called y, initialises it to 0x3342,
   any attempt to assign to it raises an exception at compile
   time
  - z = int8()
 - creates an uninitialised global byte var called z
  - within a function:
  - x = uint16(4)
 - creates an unsigned 16-bit int on the return stack frame,
   called x, initialised to 4

Another kludge is to legislate that 'None' is a 16-bit int with value of
zero, such that:
  - return
  - return None
  - return 0
all do the same thing

Is anyone working along similar lines?

Is it even possible to devise a tiny python subset that has at least
some of python's advantages, but at the same time can be compiled to
low-footprint resource-lean code?

And could such a mini-python be worth using over C, Forth, etc?

Your thoughts?

-- 
Cheers
EB

--

One who is not a conservative by age 20 has no brain.
One who is not a liberal by age 40 has no heart.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: array of arrays question

2005-08-30 Thread Meo
yes,

thank you for your help

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


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing,was Re: Bug in slice type

2005-08-30 Thread Antoon Pardon
Op 2005-08-30, Robert Kern schreef <[EMAIL PROTECTED]>:
> Bryan Olson wrote:
>
>>  Currently, user-defined classes can implement Python
>>  subscripting and slicing without implementing Python's len()
>>  function. In our proposal, the '$' symbol stands for the
>>  sequence's length, so classes must be able to report their
>>  length in order for $ to work within their slices and
>>  indexes.
>> 
>>  Specifically, to support new-style slicing, a class that
>>  accepts index or slice arguments to any of:
>> 
>>  __getitem__
>>  __setitem__
>>  __delitem__
>>  __getslice__
>>  __setslice__
>>  __delslice__
>> 
>>  must also consistently implement:
>> 
>>  __len__
>> 
>>  Sane programmers already follow this rule.
>
> Incorrect. Some sane programmers have multiple dimensions they need to
> index.

I don't see how that contradicts Bryan's statement.

>   from Numeric import *
>   A = array([[0, 1], [2, 3], [4, 5]])
>   A[$-1, $-1]
>
> The result of len(A) has nothing to do with the second $.

But that is irrelevant to the fact wether or not sane
programmes follow Bryan's stated rule. That the second
$ has nothing to do with len(A), doesn't contradict
__len__ has to be implemented nor that sane programers
already do.

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


Re: Jargons of Info Tech industry

2005-08-30 Thread axel
In comp.lang.perl.misc John Bokma <[EMAIL PROTECTED]> wrote:
> Alan Balmer <[EMAIL PROTECTED]> wrote:
 
>> On 29 Aug 2005 21:12:13 GMT, John Bokma <[EMAIL PROTECTED]> wrote:
 
 Now, go away. And please, stay away.

>>>Like I already said, it doesn't work that way.

>> Goodbye, John. Filters set.

> Saidly you didn't get the message. Moreover you think that the Usenet 
> /needs/ a public ploink message. Get a clue. People like you add more noise 
> to Usenet compared to a thread which runs a bit wide.

Why do I think of a Dutch expression 'mieren neuker' with regards to
Balmer's posts?

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


Re: sslerror: (8, 'EOF occurred in violation of protocol') ???

2005-08-30 Thread Robert

"Robert" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> On some connections only from some computers/network setups I get this
> error:
>
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "ClientCookie\_urllib2_support.pyo", line 524, in open
>   File "ClientCookie\_urllib2_support.pyo", line 424, in http_response
>   File "ClientCookie\_urllib2_support.pyo", line 541, in error
>   File "urllib2.pyo", line 306, in _call_chain
>   File "ClientCookie\_urllib2_support.pyo", line 185, in http_error_302
>   File "ClientCookie\_urllib2_support.pyo", line 518, in open
>   File "urllib2.pyo", line 326, in open
>   File "urllib2.pyo", line 306, in _call_chain
>   File "ClientCookie\_urllib2_support.pyo", line 759, in https_open
>   File "ClientCookie\_urllib2_support.pyo", line 608, in do_open
>   File "httplib.pyo", line 712, in endheaders
>   File "httplib.pyo", line 597, in _send_output
>   File "httplib.pyo", line 564, in send
>   File "httplib.pyo", line 985, in connect
>   File "socket.pyo", line 73, in ssl
> sslerror: (8, 'EOF occurred in violation of protocol')
>

In http://groups.google.de/group/comp.lang.python/msg/252b421a7d9ff037 Jp
Calderone wrote:

On 21 Jun 2005 08:39:02 -0700, Matthias Kluwe <[EMAIL PROTECTED]> wrote:



>> From: "Paul Rubin" "http://phr.cx"@NOSPAM.invalid

>>> "Matthias Kluwe" <[EMAIL PROTECTED]> writes:
>>> After getting a @gmail.com address, I recognized I had to use TLS in my
>>> python scripts using smtplib in order to get mail to the smtp.gmail.com
>>> server.


>>> [...]


>>> The server accepts and delivers my messages, but the last command
>>> raises


>>> socket.sslerror: (8, 'EOF occurred in violation of protocol')


>> [...]


>> Have you verified that its your end that is broken,  not gmail's,  do
other
>> servers give the same response ?


>No, I have not -- I should have, as I know now: Connecting, starttls,
>login and sending mail works fine without the above mentioned error
>using my previous mail provider.


>Does that mean Gmail is in error here? I don't know...



Most SSL servers and clients (primarily HTTP, but some SMTP as well) are
broken in this regard: they do not properly negotiate TLS connection
shutdown.  This causes one end or the other to notice an SSL protocol error.
Most of the time, the only thing left to do after the TLS connection
shutdown is normal TCP connection shutdown, so the error doesn't lead to any
problems (which is probably why so much software generates this problem).
Of course, there's no way to *tell* if this is the case or not, at least
programmatically.  If you receive an OK response to your DATA, you probably
don't need to worry, since you have gotten what you wanted out of the
conversation.

It's entirely possible that the fault here lies on gmail's end, but it is
also possible that the fault is in your code or the standard library ssl
support.  Unless you want to dive into Python's OpenSSL bindings or start
examining network traces of SSL traffic, you probably won't be able to
figure out who's to blame in this particular case.  The simplest thing to do
is probably just capture and discard that particular error (again, assuming
you are getting an OK resposne to your DATA command).




In fact I saw the same problem with SSL-SMTP and Googles GMAIL. the sslerror
can be ignored.

But in my case here (HTTPS) the transaction story (redirected https-request)
is not yet
completed. I don't have the essential data communicated at the moment of the
error. What can be done?

Robert



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


Re: time.mktime problem

2005-08-30 Thread Edvard Majakari
"McBooCzech" <[EMAIL PROTECTED]> writes:

> Hi, on Linux (Fedora FC4) and Python 2.4.1
> I am trying to know the time delta in seconds between two times given
> in the HHMMSS format. My code looks like:
>
> import datetime, time
> ta1=(time.strptime('01', '%H%M%S'))
> ta2=(time.strptime('230344', '%H%M%S'))
> t1=time.mktime(ta1)
> t2=time.mktime(ta2)
> print t1, t2
>
> -2147483648.0 -2147483648.0
>
> I just can not figure out, why the t1 and t2 are the same?

Hm. You are trying to convert (1900, 1, 1, 0, 0, 1, 0, 1, -1) to epoch. 
However, epochs start from 1970-01-01 00:00. So that at least is not right.

Hint... see what var ta1 is. With python2.3 you'll get overflow error, becuase
mktime argument is out of range.

-- 
# Edvard Majakari   Software Engineer
# PGP PUBLIC KEY available  Soli Deo Gloria!

$_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print
join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n";
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: variable hell

2005-08-30 Thread Fredrik Lundh
Steve Holden wrote:

> Yes. A large part of learning a language is discovering the many idioms
> that have already been established for doing certain things. These are a
> kind of shorthand, established by long convention, that allow one to
> avoid the "learning-by-use" curve.

it's not obvious that the OP has found the pydiomatic way to solve
his problem, though, given that most of this thread have been spent
on playing with exec, and that Robert Kern's question from the be-
ginning of this thread has still not been answered:

"Again, why unpack them into separate variables when they are *already*
in the form that you want to use them?"

 



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


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing,was Re: Bug in slice type

2005-08-30 Thread Robert Kern
Antoon Pardon wrote:
> Op 2005-08-30, Robert Kern schreef <[EMAIL PROTECTED]>:
> 
>>Bryan Olson wrote:
>>
>>> Currently, user-defined classes can implement Python
>>> subscripting and slicing without implementing Python's len()
>>> function. In our proposal, the '$' symbol stands for the
>>> sequence's length, so classes must be able to report their
>>> length in order for $ to work within their slices and
>>> indexes.
>>>
>>> Specifically, to support new-style slicing, a class that
>>> accepts index or slice arguments to any of:
>>>
>>> __getitem__
>>> __setitem__
>>> __delitem__
>>> __getslice__
>>> __setslice__
>>> __delslice__
>>>
>>> must also consistently implement:
>>>
>>> __len__
>>>
>>> Sane programmers already follow this rule.
>>
>>Incorrect. Some sane programmers have multiple dimensions they need to
>>index.
> 
> I don't see how that contradicts Bryan's statement.
> 
>>  from Numeric import *
>>  A = array([[0, 1], [2, 3], [4, 5]])
>>  A[$-1, $-1]
>>
>>The result of len(A) has nothing to do with the second $.
> 
> But that is irrelevant to the fact wether or not sane
> programmes follow Bryan's stated rule. That the second
> $ has nothing to do with len(A), doesn't contradict
> __len__ has to be implemented nor that sane programers
> already do.

Except that the *consistent* implementation is supposed to support the
interpretation of $. It clearly can't for multiple dimensions.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Re: micro-python - is it possible?

2005-08-30 Thread Robert

"Evil Bastard" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> Hi,
>
> Has anyone done any serious work on producing a subset of python's
> language definition that would suit it to a tiny microcontroller
> environment?
>

remember there was some work done for minimizing py1.5.2 for mics. see
Google.  even bare py1.5.2 would be possible with about 1.5MB overhead
statically compiled.
remember an own short trial on a AMD SC400 with Embedded Linux. all in 4 or
8 MB or so.

but Py2.x's became big nasty beasts with also nasty memory behaviour.

guess py1.5.2  is still very nice, tiny and fast for mics.  Happy to have a
good basic script lng you won't use new style / meta classes / iterators


> Is it even possible to devise a tiny python subset that has at least
> some of python's advantages, but at the same time can be compiled to
> low-footprint resource-lean code?
>
> And could such a mini-python be worth using over C, Forth, etc?

guess so if your app has  non-trivial complexity: Faktor 5 in programming
speed and clarity of code - if you can grant 0.5..2MB overhead.

but guess you still need some 1%..5% C for time critical stuff.


Robert


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


Code run from IDLE but not via double-clicking on its *.py

2005-08-30 Thread n00m
When I double-click on "some.py" file console window appears just for a
moment and right after that it's closed. If this script is started from
inside of IDLE (F5 key) then it executes as it should be (e.g.
executing all its print statements).

Any ideas? OS: Windows; Python 2.3.4. Thanks.

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


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing,was Re: Bug in slice type

2005-08-30 Thread Bryan Olson
Robert Kern wrote:
 > Bryan Olson wrote:
 >
 >
 >> Currently, user-defined classes can implement Python
 >> subscripting and slicing without implementing Python's len()
 >> function. In our proposal, the '$' symbol stands for the
 >> sequence's length, so classes must be able to report their
 >> length in order for $ to work within their slices and
 >> indexes.
 >>
 >> Specifically, to support new-style slicing, a class that
 >> accepts index or slice arguments to any of:
 >>
 >> __getitem__
 >> __setitem__
 >> __delitem__
 >> __getslice__
 >> __setslice__
 >> __delslice__
 >>
 >> must also consistently implement:
 >>
 >> __len__
 >>
 >> Sane programmers already follow this rule.
 >
 >
 > Incorrect. Some sane programmers have multiple dimensions they need to
 > index.
 >
 >   from Numeric import *
 >   A = array([[0, 1], [2, 3], [4, 5]])
 >   A[$-1, $-1]
 >
 > The result of len(A) has nothing to do with the second $.

I think you have a good observation there, but I'll stand by my
correctness.

My initial post considered re-interpreting tuple arguments, but
I abandoned that alternative after Steven Bethard pointed out
how much code it would break. Modules/classes would remain free
to interpret tuple arguments in any way they wish. I don't think
my proposal breaks any sane existing code.

Going forward, I would advocate that user classes which
implement their own kind of subscripting adopt the '$' syntax,
and interpret it as consistently as possible. For example, they
could respond to __len__() by returning a type that supports the
"Emulating numeric types" methods from the Python Language
Reference 3.3.7, and also allows the class's methods to tell
that it stands for the length of the dimension in question.


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


Re: DOM text

2005-08-30 Thread Richard Lewis

On Tue, 30 Aug 2005 12:05:38 +0100, "Richard Lewis"
<[EMAIL PROTECTED]> said:
> 
> On Tue, 30 Aug 2005 11:17:25 +0100, "Richard Lewis"
> <[EMAIL PROTECTED]> said:
> > 
> > Here is the *complete* code for my SectionCursor class:
> 
> In case anyone's interested, I've just noticed a logical error in the
> next_node() method:
OK, I'm beginning to wish I hadn't mentioned this now; I've changed the
insert_node() method as well:

def insert_node(self, ref_doc, new_node):
  if self.current_node.nodeType == Node.TEXT_NODE: 
parent_node = self.current_node.parentNode
text_node = self.current_node
next_node = text_node.nextSibling

preceeding_portion =
ref_doc.createTextNode(text_node.data[:self.char_pos])
proceeding_portion =
ref_doc.createTextNode(text_node.data[self.char_pos:])

parent_node.replaceChild(preceeding_portion, text_node)
if next_node is None:
  parent_node.appendChild(new_node)
  parent_node.appendChild(proceeding_portion)
else:
  parent_node.insertBefore(new_node, next_node)
  parent_node.insertBefore(proceeding_portion, next_node)
# where is the cursor?
  else:
parent_node = self.current_node.parentNode
next_node = self.current_node.nextSibling
if next_node is None:
  parent_node.appendChild(new_node)
else:
  parent_node.insertBefore(new_node, self.current_node)
# where is the cursor?


I've done some more testing and it seems that, after a call to
insert_node() when the current_node is a Text node, current_node's
parentNode, nextSibling and firstChild properties become None (assuming
they weren't None before, which firstChild was).

Hmm. Um...er, yeah. I don't think anyones following me anyway

I'll keep fiddling with it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Perl books (was: Experience regarding Python tutorials?)

2005-08-30 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
SamFeltus <[EMAIL PROTECTED]> wrote:
.
.
.
>with (google TMTOWTDI), so Perl will teach you to BE CAREFUL.  The
>O'Reilly Perl books are excellent.
>

Well, no.

I understand you writing that, and recognize it's a widespread
impression.  O'Reilly's Perl catalogue is indeed a notable 
achievement, with many high spots.

HOWEVER, there are over three dozen ORA Perl titles still in
print.  It's simply not true that they're all of uniformly 
superior quality.  Even among those which are unarguably
stylish, several are too idiosyncratic and even self-indulgent
to be "excellent" for a beginner at the level the original
poster described as his.
-- 
http://mail.python.org/mailman/listinfo/python-list


Dr. Dobb's Python-URL! - weekly Python news and links (Aug 30)

2005-08-30 Thread \"\" Diez B.Roggisch \"\"
QOTW:  "If I wanted to write five lines instead of one everywhere in a
Python program, I'd use Java." -- Paul Rubin
   http://groups.google.com/group/comp.lang.python/msg/6fac4f3022acd1fa?hl=de&;

"i think less buggy code is not the main concern for all." -- km
http://groups.google.com/group/comp.lang.python/msg/db5acbd68447ae33?hl=de&;


Bryan Olson discovers inconsistencies in the slice implementation
that lead to a new slicing PEP and a lively discussion about string
index semantics:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/402d770b6f503c27/66014427182265b9#66014427182265b9

Mark Dickinson finds strange runtime differences depending on the
existence of dummy variables - the riddle is solved by Stelios
Xanthakis who points out that min() can behave non-deterministically
when the compared entities have no well-defined comparision sematics:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/2ff00f12499233e5/8b658bc804020f08#8b658bc804020f08

Russell E. Owen tries to get unique ids for bound methods - and
discovers that id() can return the same value for two different
bound methods. The solution is to keep a reference to the bound
method, thus the id() won't be reused - which tkinters _register
does:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/143a9000bdc9847e/5b2d07b8e5470583#5b2d07b8e5470583

Ramza Brown wants a small footprint python distro - and gets
answers which shed light on the subject from varying perspectives:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/18e8f91c8e915c50/da5c5a740f7afe87#da5c5a740f7afe87

Diego AndrŽs Sanabria wonders about the apparent lack of a
binary tree data type in python:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/fb307dbdf7069b30/a0f94ea4a27ddb7c#a0f94ea4a27ddb7c

sysfault wants enlightenment about decorators and
metaclasses - and hopefully now has it:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/6bcb4d9ae934ac64/1060a20aaaf4b89a#1060a20aaaf4b89a

Roland Hedberg wants to speed up his client/server
implementation - and gets deep insight into the TCP/IP
protocol stacks:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/507a711c61df7ad5/d6e871a24d8506a6#d6e871a24d8506a6

As often before, Jp Calderone eloquently illustrates the
expressiveness Twisted affords those writing multitasking
network servers:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/dce3370299af324e/

max(01)* needs help on piping commands in python:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/5cbe3126675ac0e0/1b3d6b36341e8cad#1b3d6b36341e8cad

Pythoneers are nearly unanimous:  when you need dynamic
names for your variables ... you're probably doing
something wrong.  Python is plenty dynamic, though, so
of course it's *possible*:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/d9a99f17e0cad8f2/

Damien Elmes needs advice dealing with locales:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/8f44319aee701f71/ce6194ba78934818#ce6194ba78934818

KM compares apples with oranges - and gets told so:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/d1c6888eaec9930f/b444a3ec71e0e2b3#b444a3ec71e0e2b3

42 thinks he has new ideas about restricting python's
execution - it turns out to be old news again, though:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/89e733d60380741b/4831ed5d84026549#4831ed5d84026549



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

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

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily  
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html 
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

For far, FAR more Python reading than any one mind should
absorb, much of it quite interesting, several pages index
much of the universe of Pybloggers.
http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog
http://www.planetpython.org/
http://mechanicalcat.net/pyblagg.html

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

Re: time.mktime problem

2005-08-30 Thread McBooCzech
according to the Python documentation:
http://docs.python.org/lib/module-time.html

===snip===
Values 100-1899 are always illegal.
.
.
strptime(string[, format])
.
.
The default values used to fill in any missing data are:
(1900, 1, 1, 0, 0, 0, 0, 1, -1)
===snip===

BTW, check the following code:
>>import datetime, time
>>print time.gmtime(time.mktime((1900, 1, 1, 0, 0, 0, 0, 1, -1)))
(1901, 12, 13, 20, 45, 52, 4, 347, 0)

but (1900, 1, 1, 0, 0, 0, 0, 1, -1) is (IMHO) expected Hmmm. But I
am just a newbie!!! :)

Anyway, maybe I am just using a wrong way how to calculate time delta
between two time values given in the format "HHMMSS".

Does Python provide some other ways how to calculate it?

Petr Jakes

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


Re: micro-python - is it possible?

2005-08-30 Thread McBooCzech
Check Lua programing language. Maybe this can fit your requirements.
HTH
Petr Jakes

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


Re: Yielding a chain of values

2005-08-30 Thread Michael Hudson
Talin <[EMAIL PROTECTED]> writes:

> I'm finding that a lot of places within my code, I want to return the
> output of a generator from another generator. Currently the only
> method I know of to do this is to explicitly loop over the results
> from the inner generator, and yield each one:
>
> for x in inner():
> yield x
>
> I was wondering if there was a more efficient and concise way to do
> this. And if there isn't,

Greenlets, perhaps?  (for which, see google).

Cheers,
mwh

-- 
  LINTILLA:  You could take some evening classes.
ARTHUR:  What, here?
  LINTILLA:  Yes, I've got a bottle of them.  Little pink ones.
   -- The Hitch-Hikers Guide to the Galaxy, Episode 12
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Warning when doubly linked list is defined gloablly

2005-08-30 Thread chand
Hi Terry..,

Here is the code which gives the error...

Let me know exact reason for this Error


import os,sys,re,string,math
from xml.dom import minidom, Node
from Layer import Layer
from LMessage import *
from Param import *
from Message import *
from message_mapping import *
from protocol_mapping import *
from symbol_mapping import *
from opt_list_mapping import *
g_del_opt_list =[[],[],[],[],[],[],[]]
sflag = 0
index=0
del_index=0
radflag = 0
depth = 0
xmlflag = 0
opt_param_list = []
del_opt_param_list = []
#g_opt_list = []
MTAS_HOME="/home/chandras/XML_FILES/"
SIG_STANDARD_HOME = "/home/chandras/SIGNALLING_STANDARD/ANSI_SS7/"
symbols=['(',')','{','}','[',']','.']
reverse_symbols=['<','>','~']
layers=['MTP3','SCCP','IOS','CDTAPM2','CDTAPC2','ISUP','IS-41D-SQA']
GUI_API_COMMAND_LIST = [
"NEW",
"ADD_OPTIONAL_PARAM",
"DELETE_OPTIONAL_PARAM",
"DELETE_LAYER",
"RENAME"
]

BASE2 = "01"
BASE10 = "0123456789"
BASE16 = "0123456789ABCDEF"

Message_obj = Message()
filename =""
buffer = []
#LIST = []
def Process_GUI_Command(arg):
global Message_obj
global filename
print "### COMMAND ###", arg[0]
save_fd = os.dup(1)
if arg[0] ==  "DELETE_OPTIONAL_PARAM":
out_file = file('/tmp/te6.txt', 'w+')
elif arg[0] ==  "ADD_OPTIONAL_PARAM":
out_file = file('/tmp/te3.txt', 'w+')
else :
out_file = file('/tmp/te.txt', 'w+')
os.dup2(out_file.fileno(), sys.stdout.fileno())

if  arg[0]  ==  "NEW" :
global g_opt_list
Message_obj = Message()
layerList = listLayers("ANSI_Layers")
layerList = str(layerList)
layerList = layerList.replace(",","")
for i in range(0,len(g_opt_list)):
g_opt_list[i] = []
os.dup2(save_fd, 1)
return layerList


elifarg[0]  ==   "ADD_OPTIONAL_PARAM" :
global g_opt_list
global layers
global index
message_name = ""
layer_name   = arg[1]
#print "Layer Name", layer_name
for layer in layers:
if layer == layer_name:
if OPT_LIST_MAPPING.has_key(layer_name):
index = OPT_LIST_MAPPING[layer_name]
break

if arg[2] != 'Null':
optional_parameter_name = str(arg[2]).replace("+",",")
for symbol in reverse_symbols:
if symbol in optional_parameter_name:
if 
SYMBOL_REVERSE_MAPPING.has_key(symbol):
old_symbol = 
SYMBOL_REVERSE_MAPPING[symbol]
optional_parameter_name =
optional_parameter_name.replace(symbol,old_symbol)


Message_obj.AddParam(message_name,layer_name,
optional_parameter_name )
else : optional_parameter_name= 'Null'


add_delete_flag = 0

param_name = optional_parameter_name
show_opts(layer_name,add_delete_flag,param_name)
if int(add_delete_flag) == 0:
add_delete_flag = 0
if  optional_parameter_name != "Null":
optList =
Message_obj.showOptionalParameters(layer_name,add_delete_flag,optional_parameter_name)

g_opt_list[int(index)].append(optional_parameter_name)
for i in g_opt_list[int(index)]:
if g_opt_list[int(index)].count(i) == 1:
optList =
Message_obj.showOptionalParameters(layer_name,add_delete_flag,i)

displayoptparams(optList,layer_name,0,"Null")
i= "Null"
optional_parameter_name = "Null"
add_delete_flag = 1
os.dup2(save_fd, 1)

else:
print "Invalid Option"



def  show_opts(layer_name,add_delete_flag,param_name):
global index
global g_opt_list
#param_name = "Null"
List =
Message_obj.showOptionalParameters(layer_name,add_delete_flag,"Null")
if (len(List)== 0)  :
return "None"

displayoptparams(List,layer_name,add_delete_flag,Message_obj._message_name)
if param_name == 'Null':
for i in g_opt_list[int(index)]:
if g_opt_list[int(index)].count(i) == 1:
optList =
Message_obj.showOp

Dr. Dobb's Python-URL! - weekly Python news and links (Aug 30)

2005-08-30 Thread \"\" Diez B.Roggisch \"\"
QOTW:  "If I wanted to write five lines instead of one everywhere in a
Python program, I'd use Java." -- Paul Rubin
   http://groups.google.com/group/comp.lang.python/msg/6fac4f3022acd1fa?hl=de&;

"i think less buggy code is not the main concern for all." -- km
http://groups.google.com/group/comp.lang.python/msg/db5acbd68447ae33?hl=de&;


Bryan Olson discovers inconsistencies in the slice implementation
that lead to a new slicing PEP and a lively discussion about string
index semantics:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/402d770b6f503c27/66014427182265b9#66014427182265b9

Mark Dickinson finds strange runtime differences depending on the
existence of dummy variables - the riddle is solved by Stelios
Xanthakis who points out that min() can behave non-deterministically
when the compared entities have no well-defined comparision sematics:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/2ff00f12499233e5/8b658bc804020f08#8b658bc804020f08

Russell E. Owen tries to get unique ids for bound methods - and
discovers that id() can return the same value for two different
bound methods. The solution is to keep a reference to the bound
method, thus the id() won't be reused - which tkinters _register
does:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/143a9000bdc9847e/5b2d07b8e5470583#5b2d07b8e5470583

Ramza Brown wants a small footprint python distro - and gets
answers which shed light on the subject from varying perspectives:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/18e8f91c8e915c50/da5c5a740f7afe87#da5c5a740f7afe87

Diego AndrŽs Sanabria wonders about the apparent lack of a
binary tree data type in python:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/fb307dbdf7069b30/a0f94ea4a27ddb7c#a0f94ea4a27ddb7c

sysfault wants enlightenment about decorators and
metaclasses - and hopefully now has it:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/6bcb4d9ae934ac64/1060a20aaaf4b89a#1060a20aaaf4b89a

Roland Hedberg wants to speed up his client/server
implementation - and gets deep insight into the TCP/IP
protocol stacks:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/507a711c61df7ad5/d6e871a24d8506a6#d6e871a24d8506a6

As often before, Jp Calderone eloquently illustrates the
expressiveness Twisted affords those writing multitasking
network servers:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/dce3370299af324e/

max(01)* needs help on piping commands in python:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/5cbe3126675ac0e0/1b3d6b36341e8cad#1b3d6b36341e8cad

Pythoneers are nearly unanimous:  when you need dynamic
names for your variables ... you're probably doing
something wrong.  Python is plenty dynamic, though, so
of course it's *possible*:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/d9a99f17e0cad8f2/

Damien Elmes needs advice dealing with locales:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/8f44319aee701f71/ce6194ba78934818#ce6194ba78934818

KM compares apples with oranges - and gets told so:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/d1c6888eaec9930f/b444a3ec71e0e2b3#b444a3ec71e0e2b3

42 thinks he has new ideas about restricting python's
execution - it turns out to be old news again, though:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/89e733d60380741b/4831ed5d84026549#4831ed5d84026549



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

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

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily  
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html 
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

For far, FAR more Python reading than any one mind should
absorb, much of it quite interesting, several pages index
much of the universe of Pybloggers.
http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog
http://www.planetpython.org/
http://mechanicalcat.net/pyblagg.html

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

Re: Bug in string.find; was: Re: Proposed PEP: New style indexing,was Re: Bug in slice type

2005-08-30 Thread Robert Kern
Bryan Olson wrote:
> Robert Kern wrote:

>  >   from Numeric import *
>  >   A = array([[0, 1], [2, 3], [4, 5]])
>  >   A[$-1, $-1]
>  >
>  > The result of len(A) has nothing to do with the second $.
> 
> I think you have a good observation there, but I'll stand by my
> correctness.

len() cannot be used to determine the value of $ in the context of
multiple dimensions.

> My initial post considered re-interpreting tuple arguments, but
> I abandoned that alternative after Steven Bethard pointed out
> how much code it would break. Modules/classes would remain free
> to interpret tuple arguments in any way they wish. I don't think
> my proposal breaks any sane existing code.

What it does do is provide a second way to do indexing from the end that
can't be extended to multiple dimensions.

> Going forward, I would advocate that user classes which
> implement their own kind of subscripting adopt the '$' syntax,
> and interpret it as consistently as possible.

How? You haven't proposed how an object gets the information that
$-syntax is being used. You've proposed a syntax and some semantics; you
also need to flesh out the pragmatics.

> For example, they
> could respond to __len__() by returning a type that supports the
> "Emulating numeric types" methods from the Python Language
> Reference 3.3.7, and also allows the class's methods to tell
> that it stands for the length of the dimension in question.

I have serious doubts about __len__() returning anything but a bona-fide
integer. We shouldn't need to use incredible hacks like that to support
a core language feature.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Re: variable hell

2005-08-30 Thread Tim N. van der Leeuw
What you could do is to create a class for this; fill it's __dict__
instance; and use custom getattr() / setattr() methods for accessing
a0, a1, a2 etc.

cheers,

--Tim

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


SpamBayes wins PCW Editors Choice Award for anti-spam software.

2005-08-30 Thread Alan Kennedy
Hi All,

If there any contributors of SpamBayes reading, Congratulations! 
SpamBayes has won the Personal Computer World (pcw.co.uk) Editors Choice 
award for anti-spam software, in a review of anti-SPAM solutions in the 
October 2005 edition. (PCW, for those who don't know it, is sort of the 
UK's equivalent of Byte Magazine, except that it's still publishing 
after almost 25 years).

SpamBayes was one of two open-source apps in the group review, which 
included commercial products from Symantec, McAfee, and half a dozen 
other companies.

"""
... SpamBayes 1.0.1 is definitely in a league of its own: during our 
tests it obtained a 100% real success rate. It would have to be trained 
for several months in order to check that it isn't too strict on a daily 
basis and that it lets most of the "good" messages through. However, the 
fact that it's free, offers a high level of efficiency and is compatible 
with Outlook makes it ideal for anyone looking for a zero cost solution. 
As such, we think it deserves our Editor's Choice award. As with all 
Bayesian filters, it gets better with use, especially in terms of 
detecting wanted mail.
"""

The only problem was they listed the "manufacturer" of the software as 
SourceForge, so the product was known as "SourceForge SpamBayes". You 
guys need to come up a team/manufacturer name. (But there is a 
screenshot of the software in the review, and the "Python Powered" logo 
is right there for all to see).

Congratulations!

Unfortunately, PCW don't seem to have made the review available online 
(yet), so I can't provide a URL. Maybe someone else will have more 
success finding a URL?

thought-ye'd-like-to-know-ly'yrs,

-- 
alan kennedy
--
email alan:  http://xhaus.com/contact/alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: close failed: [Errno 0] No error goes to stdout

2005-08-30 Thread Yoav
Steve Holden wrote:
> Yoav wrote:
> 
>> I run a Java command line program. The point is, that it's not the 
>> program that output this error message for sure. And I don't expect 
>> popen3() to catch and report errors. I just want to keep my screen 
>> output clean, and I expect popen3() to run the program and not let 
>> anything slip to the screen, after all as I understood it is supposed 
>> to capture STDERR and STDOUT, but maybe I didn' t understand it right 
>> (it's quite probable). Anyway anyway I can do such a thing?
>>
> It would be helpful if you could verify your theory by running the 
> program from the command line with standard AND error output 
> redirection, verifying that no output at all apears on the console when 
> you type
> 
> cmd > /tmp/stdout 2>/tmp/stderr
> 
> You are correct in supposing that popen3 is supposed to trap all stdout 
> and stderr output.
> 
> regards
>  Steve

Thank you all for your help.
I managed to get rid of it, and I have this theory which I want to hear 
your opinion about it:
It seems like it happened because I didn't bother to close the files 
resulting from os.popen3(), and left Python to close them on it own. the 
STDERR file wasn't always created, and therefore when Python tried to 
close it, it generated an error. I thought that Python has better 
abilities at closing files on its own, but I guess I was wrong. So my 
conclusion is that whenever I open a file it MY job to close it. Again, 
thank you all, you have been a great help. So now I am closing it with a 
"try:... except: pass".

Thanks,

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


regexps with unicode-aware characterclasses?

2005-08-30 Thread Stefan Rank
Hi all,

in a python re pattern, how do I match all unicode uppercase characters 
(in a unicode string/in a utf-8 string)?

I know that there is string.uppercase/.lowercase which are 
'locale-aware', but I don't think there is a "all locales" locale.

I know that there is a re.U switch that makes \w match all unicode word 
characters, but there are no subclasses of that ([[:upper:]] or 
preferably \u).
Or is there a module/extension to get that?

There is the module unicodedata, but it has no unicodedata.uppercase 
that would correspond to string.uppercase.



   re.compile('|'.join([x.encode('utf8') for x in unicode.uppercase]))

or::

   re.compile('(?u)[[:upper:]]')

or::

   re.compile('(?u)\u')

for the latter two, to work on utf-8 strings, would I have to set the 
defaultencoding to utf-8?



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


Problem with select.poll and popen2

2005-08-30 Thread Magnus Lycka
I'm trying to read standard out in a process started with popen2
in a non-blocking way. (Other good ways of doing this than the
one I tried are appreciated.)

I've tried to dumb down my code to see what happens, and
socket.poll seems to behave very strangely. I've tried to
use the .poll method for the poll object with and without
a timeout, but in either case, the output randomly switches
between on of the versions below. It runs fast, there is
certainly no 1000 ms delay between printed full stops.

I suspect Python does things in the background with the
pipes that confuse select/poll.

import sys
import select
import popen2
import os

CMD = 'date'

#fi, fo = os.popen2(CMD) # Same result with this...
fo, fi = popen2.popen2(CMD)
p = select.poll()
p.register(fo, select.POLLOUT)
while 1:
 print '.',
 sys.stdout.flush()
 l = p.poll(1000)
 for (o, evt) in l:
if o == fo.fileno() and evt == select.POLLOUT:
 print 'Reading', fo
 c = fo.read(1)
 print c,

$ python clpy.py
. Reading 
T . Reading 
u . Reading 
e . Reading 
   . Reading 
A . Reading 
u . Reading 
g . Reading 
   . Reading 
3 . Reading 
0 . Reading 
   . Reading 
1 . Reading 
5 . Reading 
: . Reading 
4 . Reading 
5 . Reading 
: . Reading 
3 . Reading 
8 . Reading 
   . Reading 
C . Reading 
E . Reading 
S . Reading 
T . Reading 
   . Reading 
2 . Reading 
0 . Reading 
0 . Reading 
5 . Reading 

. Reading 
  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
[etc]

$ python clpy.py
. Reading 
T . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
[etc]

$ python clpy.py
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
[etc]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python and ajax

2005-08-30 Thread gene tani
http://www.modernmethod.com/sajax/
http://selenium.thoughtworks.com/usage.html

Stephan Diehl wrote:
> On Mon, 29 Aug 2005 12:04:46 -0700, Steve Young wrote:
>
> > Hi, I was wondering if anybody knew of any good
> > tutorial/example of AJAX/xmlhttprequest in python.
> > Thanks.
> >
> > -Steve
>
> As all the others have said already, AJAX has nothing to do with python,
> but everything with JavaScript.
> You might want to check out MochiKit (http://mochikit.com), a lightweight
> JavaScript library written by Bob Ippolito. Bob did a very good job in
> turning programming JS into a more python like experience.
> - stephan

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


Anyone know how to do this in pyOpenSSL

2005-08-30 Thread Scott Chapman
The pyOpenSSL list is _very_ quiet.  I'm hoping somebody here knows how to do 
this:

openssl smime -sign -in $tempfile -signer /path/to/my_cert -inkey 
/path/to/my_key -outform der -nodetach -binary | openssl smime -encrypt -des3 
-binary -outform pem /path/to/paypal_public_cert

... using pyOpenSSL.  M2Crypto won't compile on my box and I'm really lost in 
the pyOpenSSL library.

Cordially,
Scott


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


Re: reg email packages work

2005-08-30 Thread Sybren Stuvel
Steve Holden enlightened us with:
> It's obvious you aren't using that EXACT code, because it doesn't
> formulate a three-paragraph message. So the bit we really need to
> see is how you capture and formulate the argument to set_payload().

I'd rather see what I asked for, which is the output of
msg.as_string(). That contains all that's sent to the client.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: micro-python - is it possible?

2005-08-30 Thread Grant Edwards
On 2005-08-30, Evil Bastard <[EMAIL PROTECTED]> wrote:

> Has anyone done any serious work on producing a subset of python's
> language definition that would suit it to a tiny microcontroller
> environment?

No, not a tiny microcontroller environment.  In the
microcontroller world, "tiny" means 100 bytes of ram and 4KB of
code space.  OTOH, if you want to talk about medium-large uC
stuff (hundreds of KB or RAM and code space), somebody did port
and old version of Python to something like that.  Google for
"deeply embedded python".

> Is it even possible to devise a tiny python subset that has at least
> some of python's advantages, but at the same time can be compiled to
> low-footprint resource-lean code?

I doubt it.

-- 
Grant Edwards   grante Yow!  I appoint you
  at   ambassador to Fantasy
   visi.comIsland!!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regexps with unicode-aware characterclasses?

2005-08-30 Thread Fredrik Lundh
Stefan Rank wrote:

> I know that there is a re.U switch that makes \w match all unicode word
> characters, but there are no subclasses of that ([[:upper:]] or preferably 
> \u).

unicode character classes are not supported by the current RE engine.

it's usually possible to work around this by matching all characters ("\w") in 
Unicode
mode ("(?u)"), and postprocessing the result to get rid of invalid matches.

 



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


Re: Code run from IDLE but not via double-clicking on its *.py

2005-08-30 Thread max
"n00m" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> When I double-click on "some.py" file console window appears just
> for a moment and right after that it's closed. If this script is
> started from inside of IDLE (F5 key) then it executes as it
> should be (e.g. executing all its print statements).
> 
> Any ideas? OS: Windows; Python 2.3.4. Thanks.
> 
> 

It's a windows thing. The shell windows opens to run the script in is 
closing when the script finishes.

Try opening a shell (Start->Run: cmd.exe on NT/2k/XP or Start->Run: 
command.com on 95/98) and then either type the full path to the script 
or navigate to it and execute it.

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


Re: array of arrays question

2005-08-30 Thread gene tani
I think this is addressed somewhere in a python Gotchas list.  These
lists're huge, but if you scan thru these every once in a while,
they're big timesavers:

http://www.ferg.org/projects/python_gotchas.html
http://zephyrfalcon.org/labs/python_pitfalls.html
http://zephyrfalcon.org/labs/beginners_mistakes.html
http://www.python.org/doc/faq/
http://diveintopython.org/appendix/abstracts.html
http://www.onlamp.com/pub/a/python/2004/02/05/learn_python.html
http://www.norvig.com/python-iaq.html
http://www.faqts.com/knowledge_base/index.phtml/fid/245
http://amk.ca/python/writing/warts


Meo wrote:
> yes,
> 
> thank you for your help

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


how to join two Dictionary together?

2005-08-30 Thread DENG

dict1={...something...}

dict2={...somethind else ..}

dict1 + dict2


that's does works ..:(, it's not like List...


anyone can tell me how to get it?

thanks in advance

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


Re: how to join two Dictionary together?

2005-08-30 Thread Iain King

DENG wrote:
> dict1={...something...}
>
> dict2={...somethind else ..}
>
> dict1 + dict2
>
>
> that's does works ..:(, it's not like List...
>
>
> anyone can tell me how to get it?
>

Uh, I'm just learning python too, so there may be a much simpler way to
do this, but you could:

dict3 = {}
for k,i in dict1.iteritems():
dict3[k] = i
for k,i in dict2.iteritems():
dict3[k] = i

Think this should work.  Obviously, if the same key appears in both
dict1 and dict2 then dict2's value will overwrite dict1's.

Iain

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


Re: micro-python - is it possible?

2005-08-30 Thread Wouter van Ooijen (www.voti.nl)
>No, not a tiny microcontroller environment.  In the
>microcontroller world, "tiny" means 100 bytes of ram and 4KB of
>code space.  

That's medium :)

PIC10F200: 256 12-bit instructions, 16 bytes RAM.


Wouter van Ooijen

-- 
http://www.voti.nl
Webshop for PICs and other electronics
http://www.voti.nl/hvu
Teacher electronics and informatics
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to join two Dictionary together?

2005-08-30 Thread Benji York
See http://docs.python.org/lib/typesmapping.html for a description of 
the "update" method.
--
Benji York


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


Re: how to join two Dictionary together?

2005-08-30 Thread Will McGugan
DENG wrote:
> dict1={...something...}
> 
> dict2={...somethind else ..}
> 
> dict1 + dict2
> 
> 
> that's does works ..:(, it's not like List...

I think you want..

dict1.update(dict2)


Will McGugan
-- 
http://www.willmcgugan.com
"".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in 
"jvyy*jvyyzpthtna^pbz")
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to join two Dictionary together?

2005-08-30 Thread DENG
yes, that's really what i want!

the 2nd replace the 1st one' value!

thanks so much King

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


Re: how to join two Dictionary together?

2005-08-30 Thread Iain King

Iain King wrote:
> DENG wrote:
> > dict1={...something...}
> >
> > dict2={...somethind else ..}
> >
> > dict1 + dict2
> >
> >
> > that's does works ..:(, it's not like List...
> >
> >
> > anyone can tell me how to get it?
> >
>
> Uh, I'm just learning python too, so there may be a much simpler way to
> do this, but you could:
>
> dict3 = {}
> for k,i in dict1.iteritems():
> dict3[k] = i
> for k,i in dict2.iteritems():
> dict3[k] = i
>
> Think this should work.  Obviously, if the same key appears in both
> dict1 and dict2 then dict2's value will overwrite dict1's.
>
> Iain

Or, on reading the tutorial a bit more thoroughly, you can do:

dict1.update(dict2)

which will add all of dict2's key:value pairs to dict1

Iain

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


Re: how to join two Dictionary together?

2005-08-30 Thread Mikael Olofsson
DENG wrote:
> dict1={...something...}
> dict2={...somethind else ..}
> dict1 + dict2
> 
> that's does works ..:(, it's not like List...
> anyone can tell me how to get it?

I would do the following in most cases.

 >>> dict1={'a':'A'}
 >>> dict2={'b':'B'}
 >>> dict3=dict1.copy()
 >>> dict3
{'a': 'A'}
 >>> dict3.update(dict2)
 >>> dict3
{'a': 'A', 'b': 'B'}

HTH
/Mikael Olofsson

Universitetslektor (Senior Lecturer [BrE], Associate Professor [AmE])
Linköpings universitet

---
E-Mail:  [EMAIL PROTECTED]
WWW: http://www.dtr.isy.liu.se/en/staff/mikael
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
---
Linköpings kammarkör: www.kammarkoren.com   Vi söker tenorer och basar!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Jargons of Info Tech industry

2005-08-30 Thread Mark McIntyre
On Tue, 30 Aug 2005 11:30:19 GMT, in comp.lang.c ,
[EMAIL PROTECTED] wrote:

>Why do I think of a Dutch expression 'mieren neuker' with regards to
>Balmer's posts?

Its a complete mystery. Just as is the reason why you are x-posting
complete garbage to comp.lang.c...



-- 
Mark McIntyre
CLC FAQ 
CLC readme: 

== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: how to join two Dictionary together?

2005-08-30 Thread Michael . Coll-Barth
update works like append for lists

a = {}
a['a']='a'
a['c']='c'
b={}
b['b'] = 'b'
c={}
c.update(a)
c.update(b)



-Original Message-
From:
[EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED]
n.org]On Behalf Of DENG
Sent: Tuesday, August 30, 2005 10:45 AM
To: python-list@python.org
Subject: how to join two Dictionary together?



dict1={...something...}

dict2={...somethind else ..}

dict1 + dict2


that's does works ..:(, it's not like List...


anyone can tell me how to get it?

thanks in advance

-- 
http://mail.python.org/mailman/listinfo/python-list
___
The information contained in this message and any attachment may be
proprietary, confidential, and privileged or subject to the work
product doctrine and thus protected from disclosure.  If the reader
of this message is not the intended recipient, or an employee or
agent responsible for delivering this message to the intended
recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited.
If you have received this communication in error, please notify me
immediately by replying to this message and deleting it and all
copies and backups thereof.  Thank you.

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


Re: Code run from IDLE but not via double-clicking on its *.py

2005-08-30 Thread [EMAIL PROTECTED]

n00m wrote:
> When I double-click on "some.py" file console window appears just for a
> moment and right after that it's closed. If this script is started from
> inside of IDLE (F5 key) then it executes as it should be (e.g.
> executing all its print statements).
>
> Any ideas? OS: Windows; Python 2.3.4. Thanks.

Your console window closes when the program terminates.
And no, you won't necessarily see any of your print statements
before the window closed. They were buffered and the window
closed before they could be displayed.

Start a console window manually. From the command prompt,
type 

some.py

or

python some.py

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


Re: how to join two Dictionary together?

2005-08-30 Thread DENG
thanks  all!!

update is very useful!

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


Re: how to join two Dictionary together?

2005-08-30 Thread gene tani
look Pyth Cookbook 2nd edit, Sec 4.17: "Unions/intersections
dictionaries".  You'll see idioms like this for dict unions:

uniondict=dict(dict1, **dict2)
filter (dicta.has_key, dictb.keys())

DENG wrote:
> yes, that's really what i want!
> 
> the 2nd replace the 1st one' value!
> 
> thanks so much King

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


Re: how to join two Dictionary together?

2005-08-30 Thread Iain King

[EMAIL PROTECTED] wrote:
> update works like append for lists
>
> a = {}
> a['a']='a'
> a['c']='c'
> b={}
> b['b'] = 'b'
> c={}
> c.update(a)
> c.update(b)
>


So what do you think is the better way to do it, based on speed or
aesthetics?

(1)
c=a.copy()
c.update(b)

or

(2)
c={}
c.update(a)
c.update(b)

Iain

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


Re: ANN: PyDev 0.9.8 released

2005-08-30 Thread Max M
Fabio Zadrozny wrote:
> Hi All,
> 
> PyDev - Python IDE (Python Development Enviroment for Eclipse) version 
> 0.9.8 has just been released.


I read this, and thought it was time to check out both Eclipse, end the 
pydev plugin.

I got it all installed, along with a subversion plugin for eclipse, and 
it actually seems like a very sweet combo.

I was afraid that a Java based editor would be sluggish. But it doesn't 
seem so.

There are a few nice features too with a file navigator, refactoring, 
code folding and more.

So I have decided to give it a try. But before commiting to it, I just 
wondered what experiences other users might have when using it for 
production. Being that my text editing environment is my bread and butter.

Is it stable/effective etc?

Anybody cares to share?

-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to join two Dictionary together?

2005-08-30 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
DENG <[EMAIL PROTECTED]> wrote:
>
>dict1={...something...}
>
>dict2={...somethind else ..}
>
>dict1 + dict2
>
>
>that's does works ..:(, it's not like List...
>
>
>anyone can tell me how to get it?
>
>thanks in advance

First, you have to tell us what you want to happen when the two
dictionaries have overlapping keys.  Let's say I have:

d1 = {1: 'one', 2: 'two'}
d2 = {1: 'uno', 3: 'tres'}

if I do d3 = addDicts (d1, d2), what do you want d3 to have in it?
More specifically, what do you want the value of d3[1] to be?




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


Re: File parser

2005-08-30 Thread infidel

Angelic Devil wrote:
> I'm building a file parser but I have a problem I'm not sure how to
> solve.  The files this will parse have the potential to be huge
> (multiple GBs).  There are distinct sections of the file that I
> want to read into separate dictionaries to perform different
> operations on.  Each section has specific begin and end statements
> like the following:
>
> KEYWORD
> .
> .
> .
> END KEYWORD
>
> The very first thing I do is read the entire file contents into a
> string.  I then store the contents in a list, splitting on line ends
> as follows:
>
>
> file_lines = file_contents.split('\n')
>
>
> Next, I build smaller lists from the different sections using the
> begin and end keywords:
>
>
> begin_index = file_lines.index(begin_keyword)
> end_index = file_lines.index(end_keyword)
> small_list = [ file_lines[begin_index + 1] : file_lines[end_index - 1] ]
>
>
> I then plan on parsing each list to build the different dictionaries.
> The problem is that one begin statement is a substring of another
> begin statement as in the following example:
>
>
> BAR
> END BAR
>
> FOOBAR
> END FOOBAR
>
>
> I can't just look for the line in the list that contains BAR because
> FOOBAR might come first in the list.  My list would then look like
>
> [foobar_1, foobar_2, ..., foobar_n, ..., bar_1, bar_2, ..., bar_m]
>
> I don't really want to use regular expressions, but I don't see a way
> to get around this without doing so.  Does anyone have any suggestions
> on how to accomplish this? If regexps are the way to go, is there an
> efficient way to parse the contents of a potentially large list using
> regular expressions?
>
> Any help is appreciated!
>
> Thanks,
> Aaron

Some time ago I was toying around with writing a tool in python to
parse our VB6 code (the original idea was to write our own .NET
conversion tool because the Wizard that comes with VS.NET sucks hard on
some things).  I tried various parsing tools and EBNF grammars but VB6
isn't really an EBNF-esque syntax in all cases, so I needed something
else.  VB6 syntax is similar to what you have, with all kinds of
different "Begin/End" blocks, and some files can be rather big.  Also,
when you get to conditionals and looping constructs you can have
seriously nested logic, so the approach I took was to imitate a SAX
parser.  I created a class that reads VB6 source line by line, and
calls empty "event handler" methods (just like SAX) such as
self.begin_type or self.begin_procedure and self.end_type or
self.end_procedure.  Then I created a subclass that actually
implemented those event handlers by building a sort of tree that
represents the program in a more abstract fashion.  I never got to the
point of writing the tree out in a new language, but I had fun hacking
on the project for a while.  I think a similar approach could work for
you here.

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


Re: aproximate a number

2005-08-30 Thread billiejoex
I wanted the round up the number (5.0 = 5.0, not 6.0.). The ceil funciotn is 
the right one for me.
Thanks to all.


>> Grant Edwards wrote:
>>> On 2005-08-30, Devan L <[EMAIL PROTECTED]> wrote:
>>> >
>>> > RoundToInt(2.0) will give you 3.
>>>
>>> That's what the OP said he wanted.  The next bigger integer
>>> after 2.0 is 3.
>>
>> It's not really clear whether he wanted it to round up or to go to the
>> next biggest integer because he says he has bad english. I can't think
>> of a particular use of returning the next bigger integer.
>
> You're probably right.  I suspect what he really wants is
>
> i = int(math.ceil(x))
>
> -- 
> Grant Edwards   grante Yow!  Is it FUN to be
>  at   a MIDGET?
>   visi.com 


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


Re: micro-python - is it possible?

2005-08-30 Thread Grant Edwards
On 2005-08-30, Wouter van Ooijen (www.voti.nl) <[EMAIL PROTECTED]> wrote:
>>No, not a tiny microcontroller environment.  In the
>>microcontroller world, "tiny" means 100 bytes of ram and 4KB of
>>code space.  
>
> That's medium :)
>
> PIC10F200: 256 12-bit instructions, 16 bytes RAM.

Touché

-- 
Grant Edwards   grante Yow!  I HAVE a towel.
  at   
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


py2exe can't compile this program

2005-08-30 Thread billiejoex
Hi all. I tried to compile this little source with py2exe:
http://pastebin.com/350143
...but once I execute the program I encount this error:

C:\src\dist>sniffer.exe
Traceback (most recent call last):
  File "sniffer.py", line 24, in ?
  File "sniffer.py", line 18, in get_int
LookupError: no codec search functions registered: can't find encoding

Any idea? :-\





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


Re: micro-python - is it possible?

2005-08-30 Thread Magnus Lycka
Evil Bastard wrote:
> Hi,
> 
> Has anyone done any serious work on producing a subset of python's
> language definition that would suit it to a tiny microcontroller
> environment?

Isn't pypy meant to support different backends with different
requirements and constraints using the same basic language?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with select.poll and popen2

2005-08-30 Thread Magnus Lycka
Magnus Lycka wrote:
> I'm trying to read standard out in a process started with popen2
> in a non-blocking way. (Other good ways of doing this than the
> one I tried are appreciated.)

I'm starting to get on top of this. First of all, I was confused
by POLLIN and POLLOUT, since it's IN or OUT of the polling process,
so we want the POLLIN filter for the output of the spawned process...

Secondly, I thought that I'd get a fd, event pair for each kind of
event, but events are bitwise ORed together, and in my dumb downed
version I had used a command (date) that ends quickly, and then there
is a stream of POLLHUP that comes out of poll, even though I didn't
register for that. (Is it supposed to be like that?)

The following pair of programs (sender.py first) seems to behave as
I intended. Perhaps they can be of use for someone. After all, it's
not only sockets that we might want to read in an unblocking way,
but it seems most examples are geared towards that.


import time, sys
while 1:
 print 'HELLO'
 sys.stdout.flush()
 time.sleep(2)



import sys
import select
import os

CMD = 'python sender.py'

fi, fo = os.popen2(CMD)
fi.close()
p = select.poll()
p.register(fo, select.POLLIN)
while 1:
 l = p.poll(500)
 for (o, evt) in l:
if o == fo.fileno() and evt & select.POLLIN:
 c = fo.read(10)
 print c,
 else:
 print "Timeout!"

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


Re: What are new-style classes?

2005-08-30 Thread Colin J. Williams
Reinhold Birkenfeld wrote:
> Terry Hancock wrote:
> 
>>On Sunday 28 August 2005 04:47 am, Vaibhav wrote:
>>
>>>I recently heard about 'new-style classes'. I am very sorry if this
>>>sounds like a newbie question, but what are they? I checked the Python
>>>Manual but did not find anything conclusive. Could someone please
>>>enlighten me? Thanks!
>>
>>"New style" classes are becoming the standard in Python, and must
>>always be declared as a subclass of a new style class, including built-in
>>classes.
> 
> 
> [Warning, advanced stuff ahead!]
> 
> That's not entirely true. New-style classes need not be derived from a new-
> style class, they need to use the metaclass "type" or a derived.
> 
> So you can also declare a new-style class as
> 
> class new_class:
> __metaclass__ = type
> 
> Or, if you want to switch a whole module with many classes to new-style, just 
> set a
> 
> __metaclass__ = type
> 
> globally.
> 
> 
> Reinhold
What are the pros and cons of the alternate approach?

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


Re: pydoc, best practices, and Data class

2005-08-30 Thread Colin J. Williams
[EMAIL PROTECTED] wrote:
> I have a python program that I am trying to generate documentation for.
> But in one of my files I have a class called "Data", when pydoc gets to
> this class it just barfs. Well more specifically it generates
> documentation for only that one class in the file, it ignores the rest
> of the classes, plus it doesn't create the standard header, Package
> Contents section, Classes section, or anything else. Just wondering if
> this is a known bug, I can get around it by naming the class something
> else and then just changing all other references to this class.
> 
> Second question I have is is there somewhere that gives a good overview
> of best practices for documenting code in python. I read something
> about ReST (reStructuredText), is this supported by pydoc? Is it
> commonly used? I found links to docutils and other things, is pydoc
> still the standard method of creating python documentation?
> 
> Thanks,
> Nathan Bullock
> 
epydoc is an alternative.

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


Re: global interpreter lock

2005-08-30 Thread phil hunt
On Sun, 28 Aug 2005 20:34:07 GMT, Bryan Olson <[EMAIL PROTECTED]> wrote:
>phil hunt wrote:
> > Yes, find solutions. Don't find dangerous dead-ends that look like
> > solutions but which will give you lots of trouble.
>
>If concurrency is a dead end, why do the programs that provide
>the most sophisticated services of any in the world rely on it
>so heavily?

Some times concurrency is the best (or only) way to do a job. Other 
times, it's more trouble than its worth. A good programmer will know 
which is which, and will not use an overly complex solution for the 
project he is writing.

-- 
Email: zen19725 at zen dot co dot uk


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


Re: global interpreter lock

2005-08-30 Thread phil hunt
On Sun, 28 Aug 2005 19:25:55 -0400, Mike Meyer <[EMAIL PROTECTED]> wrote:
>Bryan Olson <[EMAIL PROTECTED]> writes:
>> phil hunt wrote:
>>  > Yes, find solutions. Don't find dangerous dead-ends that look like
>>  > solutions but which will give you lots of trouble.
>> If concurrency is a dead end, why do the programs that provide
>> the most sophisticated services of any in the world rely on it
>> so heavily?
>
>I don't know what Phil is saying, but I'm not calling concurrency a
>dead end. 

In general it isn't. However, in many programs, it might be, in that 
by using it you might end up with a very complex program that fails
unpredictably and if hard to debug: if you get in that situation, 
you may have to start again, in which case your previous work will 
have been a dead end.

(Actually I would suggest that knowing when to throw something away 
and start again is something that differentiates between good and 
bad programmers).

>I'm calling the tools available in most programming
>languages for dealing with it primitive.
>
>We need better tools.

I agree.

-- 
Email: zen19725 at zen dot co dot uk


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


Re: Code run from IDLE but not via double-clicking on its *.py

2005-08-30 Thread n00m
Thank you, guys, for your replies!

Now it works!

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


Re: ANN: PyDev 0.9.8 released

2005-08-30 Thread Fabio Zadrozny
Hi Max,

I may be a little (or maybe a lot) biased for it (as I'm its 
maintainer), but as I do 'eat my own dogfood', I though I might share it 
with you...

At my company, everybody that programs with python switched to pydev. 
Most people used 'highly customized' text-editors before pydev, as the 
company does not enforce one ambient for all... still, everybody changed 
to pydev, coming from vi, scintilla, komodo... and we have some really 
big projects (my current ambient has about 400 python modules, all 
managed in pydev). Also, there are no current bug reports for any 
instability in pydev.

Well, anyway, I would like to know other opinions in pydev too... as I 
said, I might bee too biased towards it :-)

Cheers,

Fabio

Max M wrote:

>Fabio Zadrozny wrote:
>  
>
>>Hi All,
>>
>>PyDev - Python IDE (Python Development Enviroment for Eclipse) version 
>>0.9.8 has just been released.
>>
>>
>
>
>I read this, and thought it was time to check out both Eclipse, end the 
>pydev plugin.
>
>I got it all installed, along with a subversion plugin for eclipse, and 
>it actually seems like a very sweet combo.
>
>I was afraid that a Java based editor would be sluggish. But it doesn't 
>seem so.
>
>There are a few nice features too with a file navigator, refactoring, 
>code folding and more.
>
>So I have decided to give it a try. But before commiting to it, I just 
>wondered what experiences other users might have when using it for 
>production. Being that my text editing environment is my bread and butter.
>
>Is it stable/effective etc?
>
>Anybody cares to share?
>
>  
>


-- 
Fabio Zadrozny
--
Software Developer

ESSS - Engineering Simulation and Scientific Software
www.esss.com.br

PyDev - Python Development Enviroment for Eclipse
pydev.sf.net
pydev.blogspot.com


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


Embedding Matplotlib images into wxPython

2005-08-30 Thread [EMAIL PROTECTED]
I am trying to embed images into a wxPython app (created using Boa
Constructor), but have not been able to do so. I know how to embed
plots, but images seem to be a problem. I've tried using code analogous
to the example given at the Matplotlib website to no avail. If anybody
has been successful at this could you please post some sample code?
That would be greatly appreciated. Thanks!

Randy

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


Re: File parser

2005-08-30 Thread Mike C. Fletcher
infidel wrote:

>Angelic Devil wrote:
>  
>
...

>Some time ago I was toying around with writing a tool in python to
>parse our VB6 code (the original idea was to write our own .NET
>conversion tool because the Wizard that comes with VS.NET sucks hard on
>some things).  I tried various parsing tools and EBNF grammars but VB6
>isn't really an EBNF-esque syntax in all cases, so I needed something
>else.  
>
...

You may find this project interesting to play with:
http://vb2py.sourceforge.net/index.html

Have fun,
Mike

-- 

  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://www.vrplumber.com
  http://blog.vrplumber.com

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


py2exe can't compile this program

2005-08-30 Thread Uwe Schmitt
> 
> Hi all. I tried to compile this little source with py2exe:
> http://pastebin.com/350143
> ...but once I execute the program I encount this error:
> 
> C:\src\dist>sniffer.exe
> Traceback (most recent call last):
>   File "sniffer.py", line 24, in ?
>   File "sniffer.py", line 18, in get_int
> LookupError: no codec search functions registered: can't find encoding
> 

http://starship.python.net/crew/theller/moin.cgi/EncodingsAgain

might help you,

greetings, uwe


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


Re: micro-python - is it possible?

2005-08-30 Thread Michael Hudson
Magnus Lycka <[EMAIL PROTECTED]> writes:

> Evil Bastard wrote:
>> Hi,
>> Has anyone done any serious work on producing a subset of python's
>> language definition that would suit it to a tiny microcontroller
>> environment?
>
> Isn't pypy meant to support different backends with different
> requirements and constraints using the same basic language?

Yup, not part of the project that I'm involved in, but it's part of
the plan.

Cheers,
mwh

-- 
59. In English every word can be verbed. Would that it were so in
our programming languages.
  -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing,was Re: Bug in slice type

2005-08-30 Thread phil hunt
On Tue, 30 Aug 2005 08:53:27 GMT, Bryan Olson <[EMAIL PROTECTED]> wrote:
> Specifically, to support new-style slicing, a class that
> accepts index or slice arguments to any of:
>
> __getitem__
> __setitem__
> __delitem__
> __getslice__
> __setslice__
> __delslice__
>
> must also consistently implement:
>
> __len__
>
> Sane programmers already follow this rule.


Wouldn't it be more sensible to have an abstract IndexedCollection 
superclass, which imlements all the slicing stuff, then when someone 
writes their own collection class they just have to implement 
__len__ and __getitem__ and slicing works automatically?


-- 
Email: zen19725 at zen dot co dot uk


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


Re: Writing Multithreaded Client-Server in Python.

2005-08-30 Thread Steve Holden
Paul Rubin wrote:
> [EMAIL PROTECTED] writes:
> 
>>What it does do, is handle each request (from the same client too) in a
>>new separate thread. Convenient if your processing intensive handle may
>>otherwise slow down the main server process becoming less responsive to
>>other requests.
>>What it doesn't do (and what Sidd seems to search as is suggested by
>>his 'select()' remark) is handle each client in a separate thread.
> 
> 
> I don't know what you mean by that.  It launches a new thread for each
> client connection.  The connection is two-way and can last as long as
> desired.  If you're imagining something like a web server handling
> http requests, using http 1.1 keepalive, you could handle any number
> of requests in that connection.
> 
I suspect he was trying to say that BaseHTTPServer has no mechanism for 
handling state. As you know, of course, this is most relevant across 
multiple successive connections to a server from the same client, and 
has little to do with threads.

> 
>>If you want to apply SocketServer such that each client corresponds to
>>one thread that handles its' requests (and maintains its state), don't
>>use ThreadingMixIn - only the thread-selection will be executed in a
>>separate thread.
> 
> 
> What do you mean by "each client"?  If a client connects, does some
> stuff, disconnects, and later reconnects, how do you know that it's
> the same client that's come back?

The assertion that ThreadingMixIn doesn't handle *sessions* might be 
more appropriate, but then there's no reason why it really should (since 
if they were handled at all they would be better handled in the base 
server classes). By "each client" I suspect the OP really meant "each 
session", and was ignoring the fact that the same client can have 
multiple sessions to the same server.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

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


Python2Html regex question

2005-08-30 Thread Gerard Flanagan
Hello

I've been using the Html Formatter at
http://www.manoli.net/csharpformat to format c# code (paste your code
into the box, click the button and get html/css).  Is there anything
similar for Python code, does anyone know?

Either way, the (c#) source is available for the above formatter and it
looks like it would be straightforward to create a Python formatter by
extending a base class and providing the following three things:

1) a list of python keywords
2) a regex to match python comments
3) a regex to match python strings

Even my limited talents can handle the first, can anyone help me with
2) and 3)?

C# uses '@' where Python uses 'r' as a 'raw-input' prefix for regex's,
but I'm assuming the expressions themselves are the same in both
languages?

Thanks in advance.

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


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing, was Re: Bug in slice type

2005-08-30 Thread Steve Holden
Antoon Pardon wrote:
> Op 2005-08-29, Steve Holden schreef <[EMAIL PROTECTED]>:
> 
>>Antoon Pardon wrote:
>>
>>>Op 2005-08-27, Steve Holden schreef <[EMAIL PROTECTED]>:
>>>
>>>
If you want an exception from your code when 'w' isn't in the string you 
should consider using index() rather than find.
>>>
>>>
>>>Sometimes it is convenient to have the exception thrown at a later
>>>time.
>>>
>>>
>>>
Otherwise, whatever find() returns you will have to have an "if" in 
there to handle the not-found case.
>>>
>>>
>>>And maybe the more convenient place for this "if" is in a whole different
>>>part of your program, a part where using -1 as an invalid index isn't
>>>at all obvious.
>>>
>>>
>>>
This just sounds like whining to me. If you want to catch errors, use a 
function that will raise an exception rather than relying on the 
invalidity of the result.
>>>
>>>
>>>You always seem to look at such things in a very narrow scope. You never
>>>seem to consider that various parts of a program have to work together.
>>>
>>
>>Or perhaps it's just that I try not to mix parts inappropriately.
> 
> 
> I didn't know it was inappropriately to mix certain parts. Can you
> give a list of modules in the standard list I shouldn't mix.
> 
> 
>>>So what happens if you have a module that is collecting string-index
>>>pair, colleted from various other parts. In one part you
>>>want to select the last letter, so you pythonically choose -1 as
>>>index. In an other part you get a result of find and are happy
>>>with -1 as an indictation for an invalid index. Then these
>>>data meet.
>>>
>>
>>That's when debugging has to start. Mixing data of such types is 
>>somewhat inadvisable, don't you agree?
> 
> 
> The type of both data is the same, it is a string-index pair in
> both cases. The problem is that a module from the standard lib
> uses a certain value to indicate an illegal index, that has
> a very legal value in python in general.
> 
Since you are clearly feeling pedantic enough to beat this one to death 
with a 2 x 4 please let me substitute "usages" for "types".

In the case of a find() result -1 *isn't* a string index, it's a failure 
flag. Which is precisely why it should be filtered out of any set of 
indexes. once it's been inserted it can no longer be distinguished as a 
failure indication.

> 
>>I suppose I can't deny that people do things like that, myself included, 
> 
> 
> It is not about what people do. If this was about someone implementing
> find himself and using -1 as an illegal index, I would certainly agree
> that it was inadvisable to do so. Yet when this is what python with
> its libary offers the programmer, you seem reluctant find fault with
> it.
> 
I've already admitted that the choice of -1 as a return value wasn't 
smart. However you appear to be saying that it's sensible to mix return 
values from find() with general-case index values. I'm saying that you 
should do so only with caution. The fact that the naiive user will often 
not have the wisdom to apply such caution is what makes a change desirable.

> 
>>but mixing data sets where -1 is variously an error flag and a valid 
>>index is only going to lead to trouble when the combined data is used.
> 
> 
> Yet this is what python does. Using -1 variously as an error flag and
> a valid index and when  people complain about that, you say it sounds like
> whining.
> 
What I am trying to say is that this doesn't make sense: if you want to 
combine find() results with general-case indexes (i.e. both positive and 
negative index values) it behooves you to strip out the -1's before you 
do so. Any other behaviour is asking for trouble.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

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


Re: Python2Html regex question

2005-08-30 Thread Trent Mick
[Gerard Flanagan wrote]
> I've been using the Html Formatter at
> http://www.manoli.net/csharpformat to format c# code (paste your code
> into the box, click the button and get html/css).  Is there anything
> similar for Python code, does anyone know?

Checkout SilverCity:
http://silvercity.sourceforge.net/

As a CGI script:
http://www.sweetapp.com/cgi-bin/cgi-styler-form.py

Cheers,
Trent

-- 
Trent Mick
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Precise timings ?

2005-08-30 Thread Madhusudan Singh
Hi

I am using time.clock() to get the current time of the processor in seconds.
For my application, I need really high resolution but currently seem to be
limited to 0.01 second. Is there a way to specify the resolution (say 1-10
microseconds) ? My processor is a 1.4 MHz Intel processor. Surely, it
should be able to report times a few (or at least 10) microseconds apart.

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


Re: variable hell

2005-08-30 Thread Steve Holden
Fredrik Lundh wrote:
> Steve Holden wrote:
> 
> 
>>Yes. A large part of learning a language is discovering the many idioms
>>that have already been established for doing certain things. These are a
>>kind of shorthand, established by long convention, that allow one to
>>avoid the "learning-by-use" curve.
> 
> 
> it's not obvious that the OP has found the pydiomatic way to solve
> his problem, though, given that most of this thread have been spent
> on playing with exec, and that Robert Kern's question from the be-
> ginning of this thread has still not been answered:
> 
> "Again, why unpack them into separate variables when they are *already*
> in the form that you want to use them?"
> 
Fair enough. I was trying to advocate the use of the suggested idioms, 
but some people seem to insist on going their own way even when it leads 
to a collision wiht a bricj wall.

You can lead an idiot to idioms, but you can't make him think ;-)

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

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


  1   2   >