Re: best way to get data into a new instance?

2006-09-29 Thread Maxim Sloyko
tobiah wrote:
[snip]
> class Employee:
>
>   __init__(self, id):
>   self.id = id
>
> e = Employee(32445)
>
> ... later
>
>
> e.firstname = 'foo'
> e.lastname = 'bar'
>
> ... more as the information comes about.

Personally, I think that this is not a good solution. How would the
reader of your code guess what properties your object has? If you don't
like to write too many assignments, you can at least do something like
this:

def __init__(self, id, **kw):
self.id = id
for name in ['first_name', 'last_name', 'age', 'salary',
'whatever']:
self.__dict__[name] = kw.get(name, None)

--
Maxim Sloyko

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


Re: QuoteSQL

2006-09-29 Thread Duncan Booth
Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:

> In message <[EMAIL PROTECTED]>, LI wrote:
> 
> execfile("QuoteSQL.py")
> EscapeSQLWild(r"\%")
>> '%'
> SQLString("%" + EscapeSQLWild(r"\%") + "%")
>> '"%%%"'
> EscapeSQLWild(r"\%") == r"\\%"
>> True
> SQLString("%" + EscapeSQLWild(r"\%") + "%") == r'"%%%"'
>> True
> 
> With the correction to EscapeSQLWild, this becomes:
> 
 execfile("QuoteSQL.py")
 EscapeSQLWild(r"\%")
> '\\%'
 SQLString("%" + EscapeSQLWild(r"\%") + "%")
> '"%%%"'
 EscapeSQLWild(r"\%") == r"\\\%"
> True
 SQLString("%" + EscapeSQLWild(r"\%") + "%") == r'"%\\%%"'
> True
> 

True but irrelevant. The point is that it isn't relevant whether you are 
seeing 4, 6, 8, or 12 backslashes, because you wrote the code to produce 
the number you thought you wanted and you had misunderstood how MySQL 
works. That's why it is important in a situation like this to test against 
the code that actually uses the string. I had no idea how MySQL would 
handle escapes in this situation, but I didn't need to know, I just wrote 
some tests and figured out which strings would make them pass or fail.

Anyway, congratulations on finally getting the message.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-29 Thread Steve Holden
MonkeeSage wrote:
> Steve Holden wrote:
> 
>>  >>> to_bin(0)
>>''
> 
> 
> Doh! Oh, yeah...that! ;)
> 
> OK...
> 
> def to_bin(x):
>   out=[]
>   while x > 0:
> out.insert(0, str(x % 2))
> x /= 2
>   else:
> out.append(str(x))
>   return ''.join(out)
> 
It's an often-missed and almost invariably untested corner case that 
one's first attempt to solve the problem usually rids one of. I have 
written binary format code about thirteen times in a lifetime of 
programming so it was easy for me to spot. You'll never make *that* 
mistake again ;-)

Unfortunately forty years of programming experience has taught me that 
there's an essentially infinite supply of mistakes to make ... your 
mistakes just get smarter most of the time.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: wxPython and threading issue

2006-09-29 Thread [EMAIL PROTECTED]
Patrick Smith wrote:
> Hi,
> Thanks for your reply.
>
> <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > [Re: cancelling a worker thread from the GUI thread]
> >
> > Have the main thread set a flag telling the worker thread to exit, and
> > have the worker thread check that periodically when it knows it's in a
> > safe state to exit.
> >
>
> This would work, unfortunately, the thread that it spawns calls a function
> in a loop, that function has an incredibly long run-time, on the order of
> minutes (possibly hours depending on the input), and that function, its self
> is multithreaded.
> This means that the worker thread could only check the flag after each
> completion of this long-running function.
>
> Given that this is the situation, is it possible to do what I mentioned
> above?  Or does the long running function prevent any nice way of doing
> this?

Well, the problem is that you can't simply kill a thread--it shares
memory with other threads that it could be leaving in an inconsistent
state.  Imagine that it was, say, holding a lock when it was forceably
killed.  Now any other thread that tries to acquire that lock will
block forever.

You really do need the thread's cooperation so that it only exits when
everything is in a kosher state.  Can you dig into the incredibly long
function and change it to do the flag-checking and exiting safely?

I second the notion to consider using subprocesses instead of threads;
that's almost always a good idea unless you're really sharing a lot of
complex data structures.

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


Re: License / Registration key enabled software

2006-09-29 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Mike Playle wrote:

> License keys exist to make it easier for honest users to
> remain honest.

It was Ed Felten who said that "keeping honest people honest is like keeping
tall people tall".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eval(source, {'builtins': {}}) archived as Faq

2006-09-29 Thread Erik Max Francis
Duncan Booth wrote:

> I'm slightly surprised that nobody has yet pointed out that the OP failed 
> at the very first hurdle here. If you are going to do this dangerous trick 
> then 'builtins' should be spelled '__builtins__':

I did, because otherwise the exploit I gave wouldn't have worked so easily.

The bottom line here is that you shouldn't even try to go through the 
exercise of seeing if you can bullet-proof a solution using eval; 
instead, you shouldn't even try.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   Everyone wants to look good at his own funeral.
-- Louis Wu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to find number of characters in a unicode string?

2006-09-29 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Marc 'BlackJack'
Rintsch wrote:

> In <[EMAIL PROTECTED]>,
> Preben Randhol wrote:
> 
>> Is there a way to calculate in characters
>> and not in bytes to represent the characters.
> 
> Decode the byte string and use `len()` on the unicode string.

Hmmm, for some reason

len(u"C\u0327")

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


Re: vector and particle effects

2006-09-29 Thread Richard Jones
Jay wrote:
> Sorry for the double post.  Google groups was being stubborn.
> Jay wrote:
>> I'd like to experiment a little bit with vector graphics in python.
>> When I say 'vector graphics' I don't mean regular old svg-style.  I
>> mean vector game style as in simulation of vector beam drawn graphics.
>> If you still don't know what I'm talking about, see Grid Wars 2
>> (http://gridwars.marune.de/) or Battlezone
>> (http://en.wikipedia.org/wiki/Battlezone).
>>
>> Anyway, I need help choosing a module or modules to support this.
>> Would pygame support this or should I try pyopengl?  Or is there a
>> better module for this?
>> 
>> Any tutorials for the basics would be GREATLY appreciated.

I'd suggest PyOpenGL because it'll be a *lot* faster. Something like
gridwars won't be possible in pygame.


Richard

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


Re: for: else: - any practical uses for the else clause?

2006-09-29 Thread metaperl
Actually right after posting this I came up with a great usage. I use
meld3 for my Python based dynamic HTML generation. Whenever I plan to
loop over a tree section I use a for loop, but if there is no data to
iterate over, then I simply remove that section from the tree or
populate it with a "no data" message.

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


Re: eval(source, {'builtins': {}}) archived as Faq

2006-09-29 Thread Duncan Booth
Erik Max Francis <[EMAIL PROTECTED]> wrote:

> This is an _extremely_ bad idea.  _Never_ use eval in a case where you 
> are trying to validate input.
> 
> >>> def e(source): return eval(source, {'builtins': {}})
> ...
> >>> e('__import__("sys").exit()')
> 
> Oops, the interpreter exited.

I'm slightly surprised that nobody has yet pointed out that the OP failed 
at the very first hurdle here. If you are going to do this dangerous trick 
then 'builtins' should be spelled '__builtins__':

>>> def e(source): return eval(source, {'__builtins__': {}})

>>> e('__import__("sys").exit()')

Traceback (most recent call last):
  File "", line 1, in 
e('__import__("sys").exit()')
  File "", line 1, in e
def e(source): return eval(source, {'__builtins__': {}})
  File "", line 1, in 
NameError: name '__import__' is not defined
>>> 

but it is still not going to stop nasty things happening, it just makes 
them a little more complex:

>>> e("[ c for c in 1 .__class__.__bases__[0].__subclasses__() if 
c.__name__=='Quitter'][0]('bang')()")

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


Re: running commands with sudo & python

2006-09-29 Thread db

Hi there,

I think you can do that with pexpect

http://pexpect.sourceforge.net/

good luck

On Thu, 28 Sep 2006 14:18:14 -0700, coldsoul4e wrote:
> Hi!
> I must execute a command with os.command(), but with root permissions.
> Is there anyway to do that with python? 
> Thanks



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


Re: PATCH: Speed up direct string concatenation by 20+%!

2006-09-29 Thread Robin Becker
Larry Hastings wrote:
__
> THE PATCH
> 
> The core concept: adding two strings together no longer returns a pure
> "string" object.  Instead, it returns a "string concatenation" object
> which holds references to the two strings but does not actually
> concatenate
> them... yet.  The strings are concatenated only when someone requests
> the
> string's value, at which point it allocates all the space it needs and
> renders the concatenated string all at once.
> 
> More to the point, if you add multiple strings together (a + b + c),
> it *doesn't* compute the intermediate strings (a + b).
> 
> Upsides to this approach:


wouldn't this approach apply to other additions eg list+list seq+seq etc 
etc.

I suppose the utility of such an approach depends on the frequency with 
which multiple strings/lists/sequences etc are added together in real code.
-- 
Robin Becker
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to find number of characters in a unicode string?

2006-09-29 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Lawrence D'Oliveiro wrote:

> In message <[EMAIL PROTECTED]>, Marc 'BlackJack'
> Rintsch wrote:
> 
>> In <[EMAIL PROTECTED]>,
>> Preben Randhol wrote:
>> 
>>> Is there a way to calculate in characters
>>> and not in bytes to represent the characters.
>> 
>> Decode the byte string and use `len()` on the unicode string.
> 
> Hmmm, for some reason
> 
> len(u"C\u0327")
> 
> returns 2.

Okay, decode and normalize and then use `len()` on the unicode string.

Ciao,
Marc 'BlackJack' Rintsch

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


Re: analyzing removable media

2006-09-29 Thread Nick Vatamaniuc
glenn wrote:
> Hi
> can anyone tell me how given a directory or file path, I can
> pythonically  tell if that item is on 'removable media', or sometype of
> vfs, the label of the media (or volume) and perhaps any other details
> about the media itself?
> thanks
> Glenn

It won't be trivial because one of the goals of the operating systems
is to hide the differences between various types of storage devices and
make them all look the same (i.e. a jump drive, a CD-ROM, a network
volume are presented uniformly to the user as just another path in the
file system).

But you can probably use guesswork on unix OS's, as somebody above
suggested, and examine the path. If the path contains common media
mount points then that should give you a clue. On Windows you cannot
easily know. For example if your file is on D:\file.txt, it is not
immediatly obvious if D is a jumpdrive, a networked drive, a hard
drive, or a CD-ROM.

The only thing I can think of is to try to examine the Windows registry
with the _winreg module. Here are the docs:
http://docs.python.org/lib/module--winreg.html  There might be a key
burried in there some place that will tell you which drives are what
type.

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


Re: Questions on Using Python to Teach Data Structures and Algorithms

2006-09-29 Thread Bruno Desthuilliers
Dennis Lee Bieber wrote:
> On 28 Sep 2006 21:17:38 -0700, "MonkeeSage" <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
> 
>   (Coming in from the cold)
>> I guess you were talking about implementing the _structure_ of lisp
>> lists in python syntax (as you seem to imply), not trying to emulate
> 
>   Well The subject line does refer "data structures" 

Noticed that too ?-)

>   Though if this suddenly inspires the creation of a Common LISP
> interpreter written in Python, I may want to close my eyes 

Well... Not quite Common Lisp yet, but :
http://www.biostat.wisc.edu/~annis/creations/PyLisp/


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to find number of characters in a unicode string?

2006-09-29 Thread Gabriel Genellina
At Friday 29/9/2006 04:52, Lawrence D'Oliveiro wrote:

> >> Is there a way to calculate in characters
> >> and not in bytes to represent the characters.
> >
> > Decode the byte string and use `len()` on the unicode string.
>
>Hmmm, for some reason
>
> len(u"C\u0327")
>
>returns 2.

That's correct, these are two unicode characters, 
C and combining-cedilla; display as Ç. From 
:

"Unicode takes the role of providing a unique 
code point — a number, not a glyph — for each 
character. In other words, Unicode represents a 
character in an abstract way, and leaves the 
visual rendering (size, shape, font or style) to 
other software [...] This simple aim becomes 
complicated, however, by concessions made by 
Unicode's designers, in the hope of encouraging a 
more rapid adoption of Unicode. [...] A lot of 
essentially identical characters were encoded 
multiple times at different code points to 
preserve distinctions used by legacy encodings 
and therefore allow conversion from those 
encodings to Unicode (and back) without losing 
any information. [...] Also, while Unicode allows 
for combining characters, it also contains 
precomposed versions of most letter/diacritic 
combinations in normal use. These make conversion 
to and from legacy encodings simpler and allow 
applications to use Unicode as an internal text 
format without having to implement combining 
characters. For example é can be represented in 
Unicode as U+0065 (Latin small letter e) followed 
by U+0301 (combining acute) but it can also be 
represented as the precomposed character U+00E9 
(Latin small letter e with acute)."

Gabriel Genellina
Softlab SRL 





__
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas

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


Re: How to find number of characters in a unicode string?

2006-09-29 Thread Leif K-Brooks
Lawrence D'Oliveiro wrote:
> Hmmm, for some reason
> 
> len(u"C\u0327")
> 
> returns 2.

Is len(unicodedata.normalize('NFC', u"C\u0327")) what you want?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython and threading issue

2006-09-29 Thread Nick Vatamaniuc
If your thread is long running and it is not possible to easily set a
flag for it to check and bail out, then how does it display the
progress in the progress dialog. How often does that get updated? If
the progress dialog is updated often, then at each update have the
thread check a self.please_die flag, for example, and break out
(possibly after releasing some resources...).


Having the work done in an external process might or might not work
easily for your problem. It will make it easy to kill the execution but
it might be OS dependent, and you will have to define some
communication interface between your processes (for example, how would
an external process easily provide progress feedback to its parent?).


Patrick Smith wrote:
> Hi,
> I'm hoping someone here will be able to help as I've been struggling with
> this problem for a few days now.
>
> I'm working on an application that is creating a ProgressDialog, and then
> creating a thread that runs a function from another module in the program.
>
> The problem is, when the cancel button on the ProgressDialog is pressed, the
> thread that was created continues to run.  How can I make it so that when
> the cancel button on the dialog is clicked, the spawned thread dies?
> 
> thanks

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


Re: Can recursive descent parser handle Python grammar?

2006-09-29 Thread Ben Sizer
[EMAIL PROTECTED] wrote:
> I'm a compiler newbie and was curious if Python's language/grammar
> can be handled by a recursive descent parser.

I believe a recursive descent parser can handle any grammar; it just
depends on how pure you want it to be.

-- 
Ben Sizer

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


Re: License / Registration key enabled software

2006-09-29 Thread Hendrik van Rooyen
 "Steve Holden" <[EMAIL PROTECTED]> Wrote:

> Sybren Stuvel wrote:
> > Mike Playle enlightened us with:
> >
> >>Imagine you're an IT manager for a medium-to-large company who wants
> >>to use some expensive piece of software. You talk to the vendor and
> >>buy a licence to use the software on up to 5 machines at once, but
> >>you don't know who in the company will want to use it, so for
> >>convenience you want to install it on every PC in the building.
> >>
> >>Having installed it all over the shop, how can you be sure that only
> >>5 people are using it at any one time?
> >
> >
> > Write the software in such a way that it needs a certificate on a
> > smartcard, then supply the company with five smartcards.
> >

And 500 smart card readers - can I quote for the job?


> And you guarantee that the contents of the smartcard is only used by one
> user at a time by building a licensing system for the smartcards?
>
> regards
>   Steve

Yes - this is the point - it makes a simple implementation increasingly complex
and paranoid - and is a large part of the cost that makes the software
expensive - the other part is called greed...

- Hendrik



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


Re: a different question: can you earn a living with *just* python?

2006-09-29 Thread Magnus Lycka
John Salerno wrote:
> It's a nice thought that a person can earn a living programming with 
> Python, which is fun enough to use just for its own sake. But for 
> someone like me (i.e. no programming experience) it's always a little 
> disheartening to see that most (if not all) job descriptions that ask 
> for Python still require some C/C++ or other language knowledge. I 
> suppose this isn't an issue if you studied CS in college, because you 
> would have been exposed to many languages.
> 
> But what if you are an expert Python program and have zero clue about 
> other languages? Can you still earn a living that way, or do most/all 
> companies require multiple language proficiency?

Being a programmer isn't just a matter of knowing one or several
programming languages, just as being an author isn't merely a matter
of knowing writing and a language.

I've been involved in one development project where COBOL programmers
were handed detailed design descriptions written in pseudo code. The
SQL code used to access the database was complete in the spec. These
programmer just needed to know how to translate pseudo code to COBOL
one module at a time, and of course, they needed to know how to operate
the IDE and run tests etc.

In all other projects I've worked in, programmers were also involved in
design etc, often in the whole loop from requirements gathering to
deployment and maintenance of the product.

Knowing a programming language is a tiny part of that. Knowing two or
three languages is still a tiny part of the set of skill and abilities
required. I'm talking about communication skills, ability to extract
relevant information from people who know a problem domain, but lack
system design skills etc, strong analytical abilities, design skills,
problem solving skills, the general ability to get things done in a
reliable and timely manner etc etc.

I'd be reluctant to employ someone without at least a B.Sc. in some
relevant subject unless they had a proven track record.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-29 Thread Frederic Rentsch
[EMAIL PROTECTED] wrote:
> Frederic Rentsch:
>   
>> Good idea, but shorter with ->
>>  >>> SE.SE ('se_definition_files/int_to_binary.se') ('%X' % 987654321)
>> '0011101011000110100010110001'
>> 
>
> Note that your version keeps the leading zeros.
> Have you tested the relative speeds too?
> (I'll probably have to learn to use SE.)
>
> Bye,
> bearophile
>
>   
If you say speed, I presume you mean speed of execution. No I have not 
tested that. I know it can't be fast on a test bench. After all, SE is 
written in Python. I did a first version fifteen years ago in C, am 
still using it today on occasion and it runs much, much faster than this 
Python SE. This SE here could be done in C if it passes the test of 
acceptance.
 Professionals need to measure execution speed as a part of 
documenting their products. I am not a professional and so I am free to 
define my own scale of grades: A (fast enough) and F (not fast enough). 
I have yet to encounter a situation where SE gets an F. But that says 
less about SE than about my better knowledge which prevents me from 
using SE to, say, change colors in a 50 Mb bitmap. Obviously, "fast 
enough" and "not fast enough" pertains not to code per se, but to code 
in a specific situation. So, as the saying goes: the proof of the 
pudding ...
 Another kind of speed is production speed. I do believe that SE 
rather excels on that side. I also believe that the two kinds of speed 
are economically related by the return-on-investment principle.
 The third kind of speed is learning speed. SE is so simple that it 
has no technical learning curve to speak of. It's versatility comes from 
a wealth of application techniques that invite exploration, invention 
even. Take leading zeroes:

Leading zeroes can be stripped in a second pass if they are made 
recognizable in the first pass by some leading mark that is not a zero 
or a one. ([^01]; I use "@" in the following example). To purists this 
may seem hackish. So it is! And what's wrong with that if it leads to 
simpler solutions?

 >>> Hex_To_Binary = SE.SE ('0= 1=0001 2=0010 3=0011 4=0100 5=0101 
6=0110 7=0111 8=1000 9=1001 A=1010 a=1010 B=1011 b=1011 C=1100 c=1100 
D=1101 d=1101 E=1110 e=1110 F= f= | ~[^01]0*~=')
 >>> Hex_To_Binary.set (keep_chain = 1)
 >>> Hex_To_Binary ('@%x' % 1234567890)
'100100110010110001011010010'
 >>> Hex_To_Binary.show ()

... snip ...

Data Chain
--
  @499602d2
0 

  @0100100110010110001011010010
1 

  100100110010110001011010010
--


Frederic

(The previously posted example "Int_To_Binary = SE.SE (SE.SE ( ..." was 
a typo, or course. One (SE.SE  does it. Sorry about that.)

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


Re: PATCH: Speed up direct string concatenation by 20+%!

2006-09-29 Thread Rob Williscroft
Larry Hastings wrote in news:1159495643.213830.289620
@m7g2000cwm.googlegroups.com in comp.lang.python:

> _
> THE PATCH
> 
> The core concept: adding two strings together no longer returns a pure
> "string" object.  Instead, it returns a "string concatenation" object
> which holds references to the two strings but does not actually
> concatenate
> them... yet.  The strings are concatenated only when someone requests
> the
> string's value, at which point it allocates all the space it needs and
> renders the concatenated string all at once.

On the python 3k list there is a thread about stings becoming "views", 
I think this is similar to what you are doing here.

http://search.gmane.org/?
query=string+view&author=&group=gmane.comp.python.python-
3000.devel&sort=relevance&DEFAULTOP=and&xP=string.view.
&xFILTERS=Gcomp.python.python-3000.devl---A>

http://tinyurl.com/kadco

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


Re: vector and particle effects

2006-09-29 Thread Nick Vatamaniuc
Panda3D is pretty good http://www.panda3d.org/  . It is very well
documented and it comes with many examples.

There is also pygame.



Jay wrote:
> I'd like to experiment a little bit with vector graphics in python.
> When I say 'vector graphics' I don't mean regular old svg-style.  I
> mean vector game style as in simulation of vector beam drawn graphics.
> If you still don't know what I'm talking about, see Grid Wars 2
> (http://gridwars.marune.de/) or Battlezone
> (http://en.wikipedia.org/wiki/Battlezone).
>
> Anyway, I need help choosing a module or modules to support this.
> Would pygame support this or should I try pyopengl?  Or is there a
> better module for this?
> 
> Any tutorials for the basics would be GREATLY appreciated.

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


BoaConstructor

2006-09-29 Thread Matthew Warren



..I'm just about to 
start a project, I have a threaded python app currently around 3000 lines / 
12-15 source files that is cli driven, and I am about to start using 
boaConstructor to build a GUI around it.
 
Has anyone here any 
advice on wether boaConstructor is actually a good tool for this? The only IDE I 
have used before was netbeans with Java, and not very extensivley. I'm not 
neccesarily into getting a boat-load of bells and whistles with my IDE, to start 
I will be using it generally just as a tool to build a GUI and edit the 
code.
 
eventually, the App 
will become big and complicated.
 
 
Thanks,
 
MattW

 
This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. 
You should not copy the email, use it for any purpose or disclose its contents to any other person.Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica.It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email.
UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UKReception Tel: + 44 (0) 115 977 1177Support Centre: 0845 607 7070Fax: + 44 (0) 115 977 7000http://www.digica.com
SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South AfricaTel: + 27 (0) 21 957 4900Fax: + 27 (0) 21 948 3135http://www.digica.com
 
 
This message has been scanned for viruses by BlackSpider in Partnership with Digica
 

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

Re: Recursive descent algorithm able to parse Python?

2006-09-29 Thread Diez B. Roggisch
Lawrence D'Oliveiro wrote:

> In message <[EMAIL PROTECTED]>, Diez B. Roggisch wrote:
> 
>> [EMAIL PROTECTED] schrieb:
>>> I'm a compiler newbie and curious if Python grammar is able to
>>> be parsed by a recursive descent parser or if it requires
>>> a more powerful algorithm.
>> 
>> I might be mistaken, but isn't recursive descent one of the more
>> powerful parsing techniques - for the price of non-linearity and even
>> potentially non-termination?
> 
> No, you're thinking of LR(k) bottom-up parsers. Recursive descent is a

No, I'm not.

> top-down parser--might be the same thing as LL(1), I'm not sure. It's easy
> to implement and easy to understand, to the point where there is strong
> pressure on programming-language designers to make sure their languages
> can be parsed with recursive descent.

http://en.wikipedia.org/wiki/Recursive_descent_parser

"""
Recursive descent with backup is a technique that determines which
production to use by trying each production in turn. Recursive descent with
backup is not limited to LL(k) grammars, but is not guaranteed to terminate
unless the grammar is LL(k). Even when they terminate, parsers that use
recursive descent with backup may require exponential time.
"""

I have to admit that I have difficulties to compare LR(k) to recursive
descent, but the fact that the latter contains backtracking makes it at
least more powerful than LL(k)

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


Re: PATCH: Speed up direct string concatenation by 20+%!

2006-09-29 Thread Felipe Almeida Lessa
28 Sep 2006 19:07:23 -0700, Larry Hastings <[EMAIL PROTECTED]>:
> THE BENCHMARKS
>
> Benchmark 1:
> def add(a, b, c, ... t): return a + b + c + ... + t
> for i in range(1000): add("aaa", "bbb", "ccc", ..., "ttt")
[snip]

What about "a + b"? Or "a + b + c"? Does it have a large overhead on
small string concatenations?

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


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-29 Thread Simon Brunning
On 9/29/06, Steve Holden <[EMAIL PROTECTED]> wrote:
> Unfortunately forty years of programming experience has taught me that
> there's an essentially infinite supply of mistakes to make ... your
> mistakes just get smarter most of the time.

+1 QOTW.

-- 
Cheers,
Simon B,
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with Python 2.5 installer.

2006-09-29 Thread paw

John Machin wrote:
> paw wrote:
> > I have ran the MSI installer for Python 2.5 several times attempting to
> > install to C:
> > Python, however all of the files are placed in C:\ .  The installer is
> > told to only install files for me, beyond that I have only chosen the
> > defaults.
>
> What do you mean by "install to C:  Python"? Can you tell us
> (unambiguously, on one line) what directory you chose? Is there any
> good reason why you didn't take the default, which is
> C:\Python25
> ?

The  should have been \ , the keyboard I am using sucks and
places the backslash below Enter vs. above like I am used to.  I just
didn't catch that when posting.

I really don't know why I always change the directory, I've just always
installed Python on MS Windows into C:\Python.  No practical reason, I
do the same with other programs.

> > Google turned up nothing useful that I could find, is anyone else
> > seeing this problem?
>
> There's been no mention that I've noticed.

I'm thinking this is a local issue.  I came in today and used the same
MSI installer as before and there were no problems.

I'm looking through the local logs to see if there has been any change
on this system in the past day or two right now.

Wayne

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


File I/O

2006-09-29 Thread Kirt
Hi! I need some help in file I/O

I have an xml file..


xyz


I want to open these file in append mode and add the line
abd

Such that i have:


xyz
xyz


can anyone show me the way to achieve this?? 

thanx

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


Re: windev vs python SOS

2006-09-29 Thread aaaWindev
Hi Bruno,

Let me guess, your favorite book is the "I HATE THE FRENCH OFFICIAL
HANDBOOK". People here deserve a more objective opinion.

Here you can find what WinDev users have to say about WinDev

http://www.windev.com/pcsoft/testimonials/

There are more testimonials here (in french).

http://www.pcsoft.fr/pcsoft/120pages/html/porsche.htm

By the way, Python is a great programming language. What is cool about
WinDev is that the language is closely embedded with the GUI. For
example, to select a line in a browsing table, you may just write:
MyTable = 15 as if MyTable was a variable (it is a powerfull widget
indeed, with searching, sorting, export to Excel, and so on).

--
PatBiker

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


Re: windev vs python SOS

2006-09-29 Thread MC
Thank you, Jean-Marc, for translation. I am not capable of this work.

:-)

-- 
@-salutations

Michel Claveau


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


Re: windev vs python SOS

2006-09-29 Thread MC
Thanks.
The essential, is that peoples (& you) can understand. Bbut, perso, I 
don't understand the message translated (much unknowed words...)

-- 
@-salutations

Michel Claveau


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


Organising unit tests

2006-09-29 Thread jimburton
I have a number of unit tests organised hierarchically, all of which
inherit fixtures from a base class. To run these all at once I started
out using

from basic import map, directionalpan, layerorder, layervisibility,
listlayers, streamlayerlist
# ... lots more ...

suite0 =
unittest.TestLoader().loadTestsFromTestCase(directionalpan.TestPan)
suite1 =
unittest.TestLoader().loadTestsFromTestCase(layerorder.TestLayerorder)
# ... lots more ...

alltests = unittest.TestSuite([suite0
   , suite1
   ])
unittest.TextTestRunner(verbosity=2).run(alltests)

Which is unmaintainable. the TestLoader docs warn that
loadTestsFromModule will not play nicely with my situation and indeed
if I try

suite0 = unittest.TestLoader().loadTestsFromModule(basic)

then run the tests, it hasn't picked any up. I suppose I could collect
and run the tests with a shell script...what are my options here to
avoid hardcoding and maintaining the list of tests, and how is it
normally done?

Thanks.

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


Re: File I/O

2006-09-29 Thread jimburton

Kirt wrote:
> Hi! I need some help in file I/O
>
> I have an xml file..
[snip]
See http://diveintopython.org/xml_processing/

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


Re: File I/O

2006-09-29 Thread Kirt

jimburton wrote:
> Kirt wrote:
> > Hi! I need some help in file I/O
> >
> > I have an xml file..
> [snip]
> See http://diveintopython.org/xml_processing/

i dont wanna parse the xml file..

Just open the file as:

f=open('test.xml','a')

and write a line "abc" before  tag http://mail.python.org/mailman/listinfo/python-list


Re: File I/O

2006-09-29 Thread Kirt

jimburton wrote:
> Kirt wrote:
> > Hi! I need some help in file I/O
> >
> > I have an xml file..
> [snip]
> See http://diveintopython.org/xml_processing/

i dont wanna parse the xml file..

Just open the file as:

f=open('test.xml','a')

and append a line "abc" before  tag 

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


Pysqlite tables in RAM

2006-09-29 Thread Ranjitha
Hi all,

I'm relatively new to python and am facing a problem with database
access

I want to store my data in a database on the disk. I also want to be
able to reload the tables into the RAM whenever I have a lot of disk
accesses and commit the changes back to the database. There is an
option of storing the data in the RAM where you connect to :memory:
instead of a DB file. The problem with this is that the data is lost
everytime you close the connection to the database. Could somebody
suggest a way to load the tables into the RAM as tables and not as some
lists or dictionaries?

Thanks,
Simba

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


Re: windev vs python SOS

2006-09-29 Thread aaaWindev
Hi Stéphane,

stéphane bard wrote:
> hello, my boss ask me to prefer windev to python.
> I have to argue

First, no matter how good is Python, you should not desagree with your
boss.
Second, Windew is quite good and fun, you will love it.

--
PatBiker

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


Re: Generating a PDF file on Linux (try using xtopdf)

2006-09-29 Thread vasudevram

George Adams wrote:
> Sorry for what is probably a very basic question...
>
> I have a database of contact info data (names, addresses, phone, etc.)
> I want to take that data and generate a printable booklet-form directory
> that can be handed out to people.
>
> So the database may look something like this:
>
>FNAME,LNAME,ADDRESS,HOMEPHONE,WORKPHONE,HOMEEMAIL,WORKEMAIL
>
>"George","Adams","123 Faketreet",
>NULL,"555-1212",NULL,"[EMAIL PROTECTED]"
>
>"John","Doe","456 Nowhere Lane",
>"555-","555-","[EMAIL PROTECTED]","[EMAIL PROTECTED]"
>
>
> and I want the printable output to "look" something like this:
>
>Adams, George
>123 Fake Street
>Work phone: 555-1212
>Work e-mail: [EMAIL PROTECTED]
>
>Doe, John
>456 Nowhere Lane
>Home phone: 555-
>Work phone: 555-
>Home e-mail: [EMAIL PROTECTED]
>Work e-mail: [EMAIL PROTECTED]
>
> I can use a scripting language like Perl to handle any programming logic
> I may need (such as not printing out a line for any fields that are
> empty in the database).  What I don't know is how to generate a nicely
> formatted PDF file containing the line breaks, red text, bold text, etc.
> that's ready for printing.
>
> Can anyone point me to the tool I need to make this happen?  (maybe it's
> a Perl module?  Maybe a standalone tool that takes my pseudocode
>  and turns it into valid PDF code?)
>
> Thanks to anyone who can help!

My xtopdf toolkit may be of help. It has both end-user tools (some
command-line, some GUI (using wxPython (v 2.6 or higher needed)), and
an API for developers. Both the tools and the API are quite easy to
use.

Check the links here:

http://www.dancingbison.com
This page has a link to an article I wrote for Packt Publishing
(http://www.packtpub.com), on how to use xtopdf to generate PDF from
CSV data - which is the kind you have. You can use the article and the
accompanying code (links available in the article) as a model for your
needs.

http://www.dancingbison.com/products.html
This page has links to get xtopdf, a guide to installing and using it
(on Windows), etc.
xtopdf is cross-platform, works on both Linux and Windows. I haven't
yet written a Linux-specific install and use guide, but the generic
instructions in the README should suffice if you know Linux some, how
to install software on it, and how to set up additional Python
libraries on it. You can also post here if you have problems making
xtopdf work on Linux, and I'll try to help. (I developed and tested it
on Linux, then tested it on Windows, so it should work ok on Linux).

xtopdf is written in Python (http://www.python.org, needs v2.2 or
higher) and uses the open source version of the ReportLab toolkit
(http://www.reportlab.org, needs v1.17 or higher, but use the 1.x
series, its not tested with Reportlab v2.x, though it might work with
it).

IMO, Python is easier to learn and develop in than Perl, so if you say
you can do it in Perl, you should be able to do it in Python.

To get the line breaks you can write code to read each cell of each row
of the CSV file, and put the line breaks wherever you want to.

For color changes, its a little more difficult - though the ReportLab
toolkit supports colors, I didn't expose that support in the xtopdf
API, though I may in future. (I did expose the ability to set the font
for any chunk of text, though). If you don't mind digging into the
source, you can try making the changes to allow colors to be specified
for arbitrary chunks of text, as per your need. It shouldn't be too
difficult, since the code is written for understandability, and there
are enough comments.

The CSV and other new formats support (TDV, XLS) is alpha and may have
some bugs. Also, CSV is know to be a variable format - different
products like different spreadsheets, generate various "dialects" of
it. I've not (yet) tested the CSV support with many differing CSV
dialects, only with the MS Excel format of Office 2000.

Feel free to let me know if you find any bugs.

If you make the changes for color support, do consider sending them to
me, to include in the next release of xtopdf. Otherwise, I'll probably
add it myself.

HTH
Vasudev Ram

Software training and consulting
http://www.dancingbison.com
10.times say "Truly rural"


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


Re: File I/O

2006-09-29 Thread jimburton

Kirt wrote:
> i dont wanna parse the xml file..
>
> Just open the file as:
>
> f=open('test.xml','a')
>
> and append a line "abc" before  tag 

Use a regex to split the contents and insert new stuff, eg

import re
prog = prog = re.compile('^(.*)()', re.DOTALL)
m = prog.search(f.read())

then m.group(1) is everything before  and m.group(2) is .
Put them together with your new tag and write it back to the file

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


Re: File I/O

2006-09-29 Thread Diez B. Roggisch
Kirt wrote:

> 
> jimburton wrote:
>> Kirt wrote:
>> > Hi! I need some help in file I/O
>> >
>> > I have an xml file..
>> [snip]
>> See http://diveintopython.org/xml_processing/
> 
> i dont wanna parse the xml file..

If you play soccer, do you insist on playing with a baseball bat?

The game is called XML, and to play it, you should use a parser. If you
don't, you're up for trouble. 

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


RE: Problems with Python 2.5 installer.

2006-09-29 Thread Matthew Warren

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On
Behalf Of paw
Sent: 29 September 2006 11:01
To: python-list@python.org
Subject: Re: Problems with Python 2.5 installer.


John Machin wrote:
> paw wrote:
> > I have ran the MSI installer for Python 2.5 several times attempting
to
> > install to C:
> > Python, however all of the files are placed in C:\ .  The installer
is
> > told to only install files for me, beyond that I have only chosen
the
> > defaults.
>
> What do you mean by "install to C:  Python"? Can you tell us
> (unambiguously, on one line) what directory you chose? Is there any
> good reason why you didn't take the default, which is
> C:\Python25
> ?


Could this happen if c:\python does not exists and creating it fails for
some reason, or if permissions are incorrect? 


This email is confidential and may be privileged. If you are not the intended 
recipient please notify the sender immediately and delete the email from your 
computer. 

You should not copy the email, use it for any purpose or disclose its contents 
to any other person.
Please note that any views or opinions presented in this email may be personal 
to the author and do not necessarily represent the views or opinions of Digica.
It is the responsibility of the recipient to check this email for the presence 
of viruses. Digica accepts no liability for any damage caused by any virus 
transmitted by this email.

UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK
Reception Tel: + 44 (0) 115 977 1177
Support Centre: 0845 607 7070
Fax: + 44 (0) 115 977 7000
http://www.digica.com

SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South 
Africa
Tel: + 27 (0) 21 957 4900
Fax: + 27 (0) 21 948 3135
http://www.digica.com
-- 
http://mail.python.org/mailman/listinfo/python-list


[ANN] IronPython Community Edition 1.0r2

2006-09-29 Thread Sanghyeon Seo
This is the second release of IronPython Community Edition (IPCE),
1.0 revision 2, based on IronPython 1.0.

Get it here:
http://sparcs.kaist.ac.kr/~tinuviel/download/IPCE-1.0r2.zip

Binary is built with Mono 1.1.17.1.

BIG WARNING: it won't work with Mono versions below 1.1.17. Please
don't mail me or IronPython mailing list before checking your Mono version!

IPCE has a new home on SourceForge:
http://fepy.sourceforge.net/

And here's the license and the summary of applied patches:
http://fepy.sourceforge.net/license.html
http://fepy.sourceforge.net/patches.html

Changes in this revision:

* Includes the Python standard library from CPython 2.4.3.
(Not everything is included -- that would be pointless. Those I tested and
work reasonably are included.)

* Includes following CPython-compatible wrappers for .NET library:
md5, pyexpat, select, sha, socket, ssl, unicodedata.

* Includes DB-API wrapper for ADO.NET.

* Includes BeautifulSoup and ElementTree for you to test. (Both work
great with IronPython!)

* Does not include Doc, Src, Tutorial from the original IronPython release.
You know where to get them... Reduces size by about half.

* Extracts to IPCE-1.0r2. (The first revision extracted to IronPython-1.0
and it could overwrite existing installation. Thanks to Anthony Baxter
for pointing this out.)

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


Re: Pysqlite tables in RAM

2006-09-29 Thread Bruno Desthuilliers
Ranjitha wrote:
> Hi all,
> 
> I'm relatively new to python 

And to databases ?

> and am facing a problem with database
> access
> 
> I want to store my data in a database on the disk. I also want to be
> able to reload the tables into the RAM whenever I have a lot of disk
> accesses and commit the changes back to the database.

This should be the database duty, not yours. Serious RDBMS are highly
optimized wrt/ caching and file I/O, and there are very few chances you
can do anything better by yourself.

> There is an
> option of storing the data in the RAM where you connect to :memory:
> instead of a DB file. The problem with this is that the data is lost
> everytime you close the connection to the database.

Seems quite obvious !-)

> Could somebody
> suggest a way to load the tables into the RAM as tables and not as some
> lists or dictionaries?

There's nothing like a "table" in Python's builtin datatypes !-)

More seriously: don't bother.

Focus first on writing correct code. Then, *if* and *when* you *really*
have a performance problem, *first* use a profiler to check where the
*real* problem is. If it then happens that SQLite is the bottleneck, try
switching to a real RDBMS like PostgreSQL.

Remember the 3 golden rules about optimisation:
1/ don't optimize
2/ don't optimize
3/ for the experts only: don't optimize


My 2 cents...
-- 
bruno desthuilliers
"Premature optimization is the root of all evil."
(some wise guy)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Socks server and client code in Python (Twisted?)

2006-09-29 Thread MaR
The answer may depend somewhat on whether your app is doing mostly
storage (filessystem) or calculations (cpu).

If you need to handle a fair number of sockets but do little
processing, you may wish to look at the standard modules
asyncore/asynchat.

But Twisted is not a bad advice :o) Maybe a little more threshold to
get started and you will have to co-deploy it with your app.

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


Hai Friends

2006-09-29 Thread NRI Events
Hello Everybody,

Happy Navaratri & Happy Dasara

I found excellent yellow pages about
Indian Temples in USA.

http://www.nrievents.com/indiantemples.htm

And also info about latest NRI News and
NRI Events and NRI services.


Regards,

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


Re: Making sure script only runs once instance at a time.

2006-09-29 Thread MaR
A very brutal but simple and effective method is to bind() to a socket
on localhost eg (127.0.0.1, 4711), listen() but never accept().
Any other process trying to to bind() on the same port will fail..
When the process dies, the port is released automatically, pending som
timedelay..

But this assumes you have an execution environment where this is
acceptable. A sysadmin may have objections ;o)

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


Re: [IronPython] [ANN] IronPython Community Edition 1.0r2

2006-09-29 Thread Sylvain Hellegouarch
Brilliant Seo. Thanks a lot :)

BTW, if it can be useful and you're happy with the code, don't hesitate to
include my port of the Gzip module. Its a BSD license :)

- Sylvain

> This is the second release of IronPython Community Edition (IPCE),
> 1.0 revision 2, based on IronPython 1.0.
>
> Get it here:
> http://sparcs.kaist.ac.kr/~tinuviel/download/IPCE-1.0r2.zip
>
> Binary is built with Mono 1.1.17.1.
>
> BIG WARNING: it won't work with Mono versions below 1.1.17. Please
> don't mail me or IronPython mailing list before checking your Mono
> version!
>
> IPCE has a new home on SourceForge:
> http://fepy.sourceforge.net/
>
> And here's the license and the summary of applied patches:
> http://fepy.sourceforge.net/license.html
> http://fepy.sourceforge.net/patches.html
>
> Changes in this revision:
>
> * Includes the Python standard library from CPython 2.4.3.
> (Not everything is included -- that would be pointless. Those I tested and
> work reasonably are included.)
>
> * Includes following CPython-compatible wrappers for .NET library:
> md5, pyexpat, select, sha, socket, ssl, unicodedata.
>
> * Includes DB-API wrapper for ADO.NET.
>
> * Includes BeautifulSoup and ElementTree for you to test. (Both work
> great with IronPython!)
>
> * Does not include Doc, Src, Tutorial from the original IronPython
> release.
> You know where to get them... Reduces size by about half.
>
> * Extracts to IPCE-1.0r2. (The first revision extracted to IronPython-1.0
> and it could overwrite existing installation. Thanks to Anthony Baxter
> for pointing this out.)
>
> --
> Seo Sanghyeon
> ___
> users mailing list
> users@lists.ironpython.com
> http://lists.ironpython.com/listinfo.cgi/users-ironpython.com
>

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


Re: Python and Win95B

2006-09-29 Thread Ciar�n � Duibh
Thanks. Python 2.4.3 is fine.
Ciarán.

- Original Message -
From: "Martin v. Löwis" <[EMAIL PROTECTED]>
Newsgroups: comp.lang.python
To: "Ciarán Ó Duibhín" <[EMAIL PROTECTED]>
Sent: Thursday, September 28, 2006 7:28 PM
Subject: Re: Python and Win95B


> Ciarán Ó Duibhín schrieb:
> > I've just installed Python 2.5 under Win95B, and when run it says "The
> > PYTHON25.DLL file is linked to missing export
> > KERNEL32.DLL.GetFileAttributesExA".
> >
> > Does Python 2.5 not run under Win95?
>
> Apparently not. I knew this would be a problem when I wrote the code
> that uses GetFileAttributes; I then forgot to fix it before the
> release was made, and nobody reported that problem during the beta
> tests. If you think it should be fixed, please report it to
> sf.net/projects/python.
>
> > If not, is there an earlier version of Python which does?
>
> This specific problem shouldn't exist in Python 2.4, and I recall
> that I tested some 2.4 release on Windows 95.
>
> Regards,
> Martin
>


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


Execute external code and get return value

2006-09-29 Thread Michele Petrazzo
Hi,
I want to execute an external code, that become from a text file (pe),
call a function inside it and get its return value:

# ext_code.txt

def funct2Call():
  return True

# test.py

sourcecode = open("ex_code.txt").read()
comp_code = compile(sourcecode, "My_test", "exec")

#do something like this
return_value = comp_code.funct2Call()

But I can't...

I find this:
http://tinyurl.com/nwbpk

but here, it call from the external code a function inside my code. I
want the opposite!
Is there a solution for do this?

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


Re: windev vs python SOS

2006-09-29 Thread Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
> Hi Bruno,

Heck. PC-Soft marketing droids are pursuing us even here now.

> Let me guess, your favorite book is the "I HATE THE FRENCH OFFICIAL
> HANDBOOK". 

je suis français, pauvre semoule.

> People here deserve a more objective opinion.

"objective" ? Lol.

> Here you can find what WinDev users have to say about WinDev
> 
> http://www.windev.com/pcsoft/testimonials/

yes, very objective...

> There are more testimonials here (in french).
> 
> http://www.pcsoft.fr/pcsoft/120pages/html/porsche.htm

just as objective.

> By the way, Python is a great programming language. What is cool about
> WinDev is that the language is closely embedded with the GUI.

The one and only  "cool" thing about Windev is that I'll never have to
use this piece of shit again.

> For
> example, to select a line in a browsing table, you may just write:
> MyTable = 15 as if MyTable was a variable (it is a powerfull widget
> indeed, with searching, sorting, export to Excel, and so on).

Yeah, great. And you forgot to say that it generates the whole
application by itself, and even make coffee for the programmer.

NB : transmitted to [EMAIL PROTECTED] who will appreciate if OT
commercial adds are welcomes here.

> --
> PatBiker
> 


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


"ValueError: Empty module name" on basic import

2006-09-29 Thread alain MONTMORY

Hello everybody,

I am a newbie to python so I hope I am at the right place to expose my 
problem. :-[


I am working on linux mandrake 10.1 with python :
python -V
Python 2.3.4
I am trying o run the example which stay in the documentation in paragraph
http://www.python.org/doc/2.4.2/ext/pure-embedding.html 5.3 Pure Embedding
I download the code example from
http://www.python.org/doc/2.4.2/ext/run-func.txt
I call the file "TestOfficiel.c" and I compile it with :
gcc -g -I/usr/include/python2.3/ TestOfficiel.c -o TestOfficiel 
-lpython2.3 -ldl

all is OK (or seems to be...).
as stated in the documentation  I creat a file "TestPythonFoo.py" which 
contain

"
def multiply(a,b):
   print "Will compute", a, "times", b
   c = 0
   for i in range(0, a):
   c = c + b
   return c
"
I launch
./TestOfficiel ./TestPythonFoo.py multiply 3 2
and as a result :
ValueError: Empty module name
Failed to load "./TestPythonFoo.py"
if I try an absolute path to the python file :
./TestOfficiel `pwd`/TestPythonFoo.py multiply 3 2
I obtain :
ImportError: No module named 
/space/ESOPPE_PROJET/Outils/SwigPython/swigCallPython/TestPythonFoo.py
Failed to load 
"/space/ESOPPE_PROJET/Outils/SwigPython/swigCallPython/TestPythonFoo.py"

Of course the file exist :
[EMAIL PROTECTED] swigCallPython]$ ll 
/space/ESOPPE_PROJET/Outils/SwigPython/swigCallPython/TestPythonFoo.py
-rwxrwx--x  1 montmory esoppe 126 sep 29 14:04 
/space/ESOPPE_PROJET/Outils/SwigPython/swigCallPython/TestPythonFoo.py*


I found lot of post about "ValueError: Empty module name" but no clear 
solution (clear for me...).

What's wrong ?
my python version?
Additionnal informations :
gcc version 3.4.1 (Mandrakelinux 10.1 3.4.1-4mdk)

Thanks for your help,

best regards,

Alain



#include 

int
main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pDict, *pFunc;
PyObject *pArgs, *pValue;
int i;

if (argc < 3) {
fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
return 1;
}

Py_Initialize();
pName = PyString_FromString(argv[1]);
/* Error checking of pName left out */

pModule = PyImport_Import(pName);
Py_DECREF(pName);

if (pModule != NULL) {
pDict = PyModule_GetDict(pModule);
/* pDict is a borrowed reference */

pFunc = PyDict_GetItemString(pDict, argv[2]);
/* pFun: Borrowed reference */

if (pFunc && PyCallable_Check(pFunc)) {
pArgs = PyTuple_New(argc - 3);
for (i = 0; i < argc - 3; ++i) {
pValue = PyInt_FromLong(atoi(argv[i + 3]));
if (!pValue) {
Py_DECREF(pArgs);
Py_DECREF(pModule);
fprintf(stderr, "Cannot convert argument\n");
return 1;
}
/* pValue reference stolen here: */
PyTuple_SetItem(pArgs, i, pValue);
}
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
if (pValue != NULL) {
printf("Result of call: %ld\n", PyInt_AsLong(pValue));
Py_DECREF(pValue);
}
else {
Py_DECREF(pModule);
PyErr_Print();
fprintf(stderr,"Call failed\n");
return 1;
}
/* pDict and pFunc are borrowed and must not be Py_DECREF-ed */
}
else {
if (PyErr_Occurred())
PyErr_Print();
fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
}
Py_DECREF(pModule);
}
else {
PyErr_Print();
fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
return 1;
}
Py_Finalize();
return 0;
}
def multiply(a,b):
print "Will compute", a, "times", b
c = 0
for i in range(0, a):
c = c + b
return c
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: PATCH: Speed up direct string concatenation by 20+%!

2006-09-29 Thread Carl Friedrich Bolz
Robin Becker wrote:
> Larry Hastings wrote:
> __
>> THE PATCH
>>
>> The core concept: adding two strings together no longer returns a pure
>> "string" object.  Instead, it returns a "string concatenation" object
>> which holds references to the two strings but does not actually
>> concatenate
>> them... yet.  The strings are concatenated only when someone requests
>> the
>> string's value, at which point it allocates all the space it needs and
>> renders the concatenated string all at once.
>>
>> More to the point, if you add multiple strings together (a + b + c),
>> it *doesn't* compute the intermediate strings (a + b).
>>
>> Upsides to this approach:
> 
> 
> wouldn't this approach apply to other additions eg list+list seq+seq etc 
> etc.

no, I think it depends on strings being immutable. If you do list1 +
list2 that way and list1 is mutated then the resulting list would be
changed too.

> I suppose the utility of such an approach depends on the frequency with 
> which multiple strings/lists/sequences etc are added together in real code.

I think there are quite a lot of string additions around, it's just that
people get told to use join all the time, so they are not written using "+".

Cheers,

Carl Friedrich

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


Re: PATCH: Speed up direct string concatenation by 20+%!

2006-09-29 Thread Carl Friedrich Bolz
Robin Becker wrote:
> Larry Hastings wrote:
> __
>> THE PATCH
>>
>> The core concept: adding two strings together no longer returns a pure
>> "string" object.  Instead, it returns a "string concatenation" object
>> which holds references to the two strings but does not actually
>> concatenate
>> them... yet.  The strings are concatenated only when someone requests
>> the
>> string's value, at which point it allocates all the space it needs and
>> renders the concatenated string all at once.
>>
>> More to the point, if you add multiple strings together (a + b + c),
>> it *doesn't* compute the intermediate strings (a + b).
>>
>> Upsides to this approach:
> 
>
> wouldn't this approach apply to other additions eg list+list seq+seq etc
> etc.

no, I think it depends on strings being immutable. If you do list1 +
list2 that way and list1 is mutated then the resulting list would be
changed too.

> I suppose the utility of such an approach depends on the frequency with
> which multiple strings/lists/sequences etc are added together in real
code.

I think there are quite a lot of string additions around, it's just that
people get told to use join all the time, so they are not written using "+".

Cheers,

Carl Friedrich

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


Re: a different question: can you earn a living with *just* python?

2006-09-29 Thread Antoon Pardon
On 2006-09-28, Roy Smith <[EMAIL PROTECTED]> wrote:
> In article <[EMAIL PROTECTED]>,
>  "Carl J. Van Arsdall" <[EMAIL PROTECTED]> wrote:
>
>> > Things like decorators and metaclasses certainly add power, but they add 
>> > complexity too.  It's no longer a simple language.
>> >   
>> Well, I think a simple language is a language that makes the simple 
>> things simple and some of the complex things simple.  But I also like a 
>> language where, if I need it, I can tap into some raw power and do that 
>> really wild stuff.  So its simple to use if that's all you need yet 
>> offers the complexity to get things done that a purely "simple" language 
>> can't do.  I'd say its as simple as you want it to be :)
>
> The problem is, if the complex features are there, people will use them.  
> On any large project, there will always be some people who revel in using 
> every obscure feature of a language.  That forces everybody else on the 
> team (and all future members of the team) to know (or learn) those features 
> in order to be able to use and maintain the code base.

I would think that this kind of issues is the responsibility of the
project leader. Otherwise you might as well remove the possibilty
of a recursive function. There may always be someone that writes complicated
recursive functions whenever a simple iterative solution would do fine.

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


Re: PATCH: Speed up direct string concatenation by 20+%!

2006-09-29 Thread cfbolz
Robin Becker wrote:
> Larry Hastings wrote:
> __
>> THE PATCH
>>
>> The core concept: adding two strings together no longer returns a pure
>> "string" object.  Instead, it returns a "string concatenation" object
>> which holds references to the two strings but does not actually
>> concatenate
>> them... yet.  The strings are concatenated only when someone requests
>> the
>> string's value, at which point it allocates all the space it needs and
>> renders the concatenated string all at once.
>>
>> More to the point, if you add multiple strings together (a + b + c),
>> it *doesn't* compute the intermediate strings (a + b).
>>
>> Upsides to this approach:
> 
>
> wouldn't this approach apply to other additions eg list+list seq+seq etc
> etc.

no, I think it depends on strings being immutable. If you do list1 +
list2 that way and list1 is mutated then the resulting list would be
changed too (at least if you don't do additional things).

> I suppose the utility of such an approach depends on the frequency with
> which multiple strings/lists/sequences etc are added together in real code.

I think there are quite a lot of string additions around, it's just
that people get told to use join all the time, so they are not written
using "+".

Cheers,

Carl Friedrich Bolz

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


Re: windev vs python SOS

2006-09-29 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
> Hi Stéphane,
> 
> stéphane bard wrote:
>> hello, my boss ask me to prefer windev to python.
>> I have to argue
> 
> First, no matter how good is Python, you should not desagree with your
> boss.
> Second, Windew is quite good and fun, you will love it.

Yes, the boss is always right, shut up and drink your Kool-Aid!

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


Re: PATCH: Speed up direct string concatenation by 20+%!

2006-09-29 Thread Carl Friedrich Bolz
Robin Becker wrote:
> Larry Hastings wrote:
> __
>> THE PATCH
>>
>> The core concept: adding two strings together no longer returns a pure
>> "string" object.  Instead, it returns a "string concatenation" object
>> which holds references to the two strings but does not actually
>> concatenate
>> them... yet.  The strings are concatenated only when someone requests
>> the
>> string's value, at which point it allocates all the space it needs and
>> renders the concatenated string all at once.
>>
>> More to the point, if you add multiple strings together (a + b + c),
>> it *doesn't* compute the intermediate strings (a + b).
>>
>> Upsides to this approach:
> 
>
> wouldn't this approach apply to other additions eg list+list seq+seq etc
> etc.

no, I think it depends on strings being immutable. If you do list1 +
list2 that way and list1 is mutated then the resulting list would be
changed too.

> I suppose the utility of such an approach depends on the frequency with
> which multiple strings/lists/sequences etc are added together in real
code.

I think there are quite a lot of string additions around, it's just that
people get told to use join all the time, so they are not written using "+".

Cheers,

Carl Friedrich

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


Re: windev vs python SOS

2006-09-29 Thread Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
> Hi Stéphane,
> 
> stéphane bard wrote:
>> hello, my boss ask me to prefer windev to python.
>> I have to argue

You don't. You're one of the marketing droids from PC-Soft


To everyone here : such interventions are a well-known part of PC-Soft
(the company that sells the "product" discussed here) marketing
strategy. We've seen quite a lot of such posts on the windew-users
mailing list and newsgroup.


> First, no matter how good is Python, you should not desagree with your
> boss.

Ho yes ? Even if the boss finally decides that he'd better trust his
team than marketing droids ?

> Second, Windew is quite good and fun, 

Yes, sooo good and fun. A good and fun unusable clickodrom nightmare
with a good and fun dumbed-down basic as language and a good and fun
indexed sequential file format as "RDBMS".

lol.

> you will love it.

I've never met a programmer that "loved" Windev. I've met some
"programmers" that where able to bear with it mostly because they didn't
even knew anything else, but even these guys didn't "love" trying to
make this crap do something useful.

Heck, compared to PC-Soft, one could find that Microsoft's marketing
strategy is based on delivering smart, usable, cleanly debugged products
and being helpful to users...

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Organising unit tests

2006-09-29 Thread jimburton
OK, so I'm trying to collect the tests with python and add them to the
test suite dynamically, but I have a problem with module names. Here's
what I've got:
#
import os
from os.path import join
import unittest

alltests = unittest.TestSuite()

def mightBeATest(f):
#TODO check whether it really is a test
return f.endswith('.py') and f != '__init__.py'

def isModule(d):
if not os.path.isdir(d):
return False
for f in os.listdir(d):
if f == '__init__.py':
  return True
return False


def getTestsFromDir(dir, currentmod):
for f in os.listdir(dir):
if not f.startswith('.'):
if isModule(f):
#TODO how to check whether we are several modules in?
mod = __import__(f)
getTestsFromDir(os.path.join(dir, f), mod)
elif mightBeATest(os.path.join(dir, f)):
fname, etx = os.path.splitext(f)
print 'adding test
with',('alltests.addTests(unittest.TestLoader().loadTestsFromTestCase('+(currentmod.__dict__[fname])+'))')

eval('alltests.addTests(unittest.TestLoader().loadTestsFromTestCase('+currentmod.__dict__[fname]+'))')


getTestsFromDir(os.curdir, None)
print alltests.countTestCases()


it's importing and referring to the current module that I have a
problem with...it gives me a key error.

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


Re: Execute external code and get return value

2006-09-29 Thread Peter Otten
Michele Petrazzo wrote:

> I want to execute an external code, that become from a text file (pe),
> call a function inside it and get its return value:

namespace = {}
execfile("ext_code.txt", namespace)
print namespace["funct2Call"]()

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


Re: Execute external code and get return value

2006-09-29 Thread Michele Petrazzo
Michele Petrazzo wrote:

Auto reply:

> I find this: http://tinyurl.com/nwbpk
> 

Following this link, here is my solution:


code = """
def funct2Call():
  return "It work!"

object.method(funct2Call)
"""

class Object(object):
 def method(self, value):
 self._callable = value
 def __call__(self):
 return self._callable()

# populate the namespace
namespace = {
 "object": Object()
 }

# execute the code
exec code in namespace

namespace["object"]()

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


Re: PATCH: Speed up direct string concatenation by 20+%!

2006-09-29 Thread Carl Friedrich Bolz
Carl Friedrich Bolz wrote:
> Robin Becker wrote:
>> Larry Hastings wrote:
>> __
>>> THE PATCH
>>>
>>> The core concept: adding two strings together no longer returns a pure
>>> "string" object.  Instead, it returns a "string concatenation" object
>>> which holds references to the two strings but does not actually
>>> concatenate
>>> them... yet.  The strings are concatenated only when someone requests
>>> the
>>> string's value, at which point it allocates all the space it needs and
>>> renders the concatenated string all at once.
>>>
>>> More to the point, if you add multiple strings together (a + b + c),
>>> it *doesn't* compute the intermediate strings (a + b).
>>>
>>> Upsides to this approach:
>> 
>>
>> wouldn't this approach apply to other additions eg list+list seq+seq etc
>> etc.
> 
> no, I think it depends on strings being immutable. If you do list1 +
> list2 that way and list1 is mutated then the resulting list would be
> changed too.
> 
>> I suppose the utility of such an approach depends on the frequency with
>> which multiple strings/lists/sequences etc are added together in real
> code.
> 
> I think there are quite a lot of string additions around, it's just that
> people get told to use join all the time, so they are not written using "+".

Sorry for the multiple post :-(

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


Re: File I/O

2006-09-29 Thread jimburton

Diez B. Roggisch wrote:
> Kirt wrote:
>
> >
> > jimburton wrote:
> >> Kirt wrote:
> >> > Hi! I need some help in file I/O
> >> >
> >> > I have an xml file..
> >> [snip]
> >> See http://diveintopython.org/xml_processing/
> >
> > i dont wanna parse the xml file..
>
> If you play soccer, do you insist on playing with a baseball bat?
> 
I've been known to open a bottle of wine with a pencil. Works fine.

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


Re: Execute external code and get return value

2006-09-29 Thread Michele Petrazzo
Peter Otten wrote:
> Michele Petrazzo wrote:
> 
>> I want to execute an external code, that become from a text file
>> (pe), call a function inside it and get its return value:
> 
> namespace = {} execfile("ext_code.txt", namespace) print
> namespace["funct2Call"]()
> 

Sorry, I forgot to say that "ext_code.txt" isn't a real file, but a text
become from a db, so or I create a temp file where I save the code and
pass its path to execfile, or use my post.

> Peter

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


Re: A critique of cgi.escape

2006-09-29 Thread Magnus Lycka
Jon Ribbens wrote:
> In article <[EMAIL PROTECTED]>, Fredrik Lundh wrote:
>> maybe you haven't done software long enough to understand that
>> software works better if you use it the way it was intended to be
>> used, but that's no excuse for being stupid.
> 
> So what's your excuse?

If you don't like Fredrik's manner I suggest that you simply
don't use any code he's written. Good luck using Python! :^)


Don't bite the hand that feeds you...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Making sure script only runs once instance at a time.

2006-09-29 Thread Hari Sekhon
Seeing as there doesn't seem to be a good answer to this (or at least 
not one that we have so far some up with) I have decided to fall back to 
my old friend the unix shell. It's as portable as python, but is very 
flexible and fast at doing real things and will tell me if another 
process by this name is running. If so, print msg and exit. simple.

-h

Hari Sekhon



MaR wrote:
> A very brutal but simple and effective method is to bind() to a socket
> on localhost eg (127.0.0.1, 4711), listen() but never accept().
> Any other process trying to to bind() on the same port will fail..
> When the process dies, the port is released automatically, pending som
> timedelay..
>
> But this assumes you have an execution environment where this is
> acceptable. A sysadmin may have objections ;o)
>
>   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: XSLT speed comparisons

2006-09-29 Thread uche . ogbuji
Damian wrote:
> Hi, I'm from an ASP.NET background an am considering making the switch
> to Python. I decided to develop my next project in tandem to test the
> waters and everything is working well, loving the language, etc.
>
> What I've got is:
> two websites, one in ASP.NET v2 and one in Python 2.5 (using 4suite for
> XML/XSLT)
> both on the same box (Windows Server 2003)
> both using the same XML, XSLT, CSS
>
> The problem is, the Python version is (at a guess) about three times
> slower than the ASP one. I'm very new to the language and it's likely

The ASP one being MSXML, right?  In that case that result doesn't
surprise me.

> that I'm doing something wrong here:

Now wrong, but we can definitely simplify your API

> from os import environ
> from Ft.Lib.Uri import OsPathToUri
> from Ft.Xml import InputSource
> from Ft.Xml.Xslt import Processor
>
> def buildPage():
> try:
> xsluri = OsPathToUri('xsl/plainpage.xsl')
> xmluri = OsPathToUri('website.xml')
>
> xsl = InputSource.DefaultFactory.fromUri(xsluri)
> xml = InputSource.DefaultFactory.fromUri(xmluri)
>
> proc = Processor.Processor()
> proc.appendStylesheet(xsl)
>
> params = {"url":environ['QUERY_STRING'].split("=")[1]}
> for i, v in enumerate(environ['QUERY_STRING'].split("/")[1:]):
> params["selected_section%s" % (i + 1)] = "/" + v
>
> return proc.run(xml, topLevelParams=params)
> except:
> return "Error blah blah"
>
> print "Content-Type: text/html\n\n"
> print buildPage()

This should work:

from os import environ
from Ft.Xml.Xslt import Transform

def buildPage():
try:
params = {"url":environ['QUERY_STRING'].split("=")[1]}
for i, v in enumerate(environ['QUERY_STRING'].split("/")[1:]):
params["selected_section%s" % (i + 1)] = "/" + v

return Transform('website.xml', 'xsl/plainpage.xsl',
topLevelParams=params)
except:
return "Error blah blah"

print "Content-Type: text/html\n\n"
print buildPage()

-- % --

For what it's worth I just developed, and switched to WSGI middleware
that only does the transform on the server side if the client doesn't
understand XSLT.  It's called applyxslt and is part of wsgi.xml [1].
That reduces server load, and with caching (via Myghty), there's really
no issue for me.  For more on WSGI middleware see [2].

[1] http://uche.ogbuji.net/tech/4suite/wsgixml/
[2] http://www.ibm.com/developerworks/library/wa-wsgi/

--
Uche Ogbuji   Fourthought, Inc.
http://uche.ogbuji.nethttp://fourthought.com
http://copia.ogbuji.net   http://4Suite.org
Articles: http://uche.ogbuji.net/tech/publications/

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


Re: Execute external code and get return value

2006-09-29 Thread Peter Otten
Michele Petrazzo wrote:

> Following this link, here is my solution:
> 
> 
> code = """
> def funct2Call():
>   return "It work!"
> 
> object.method(funct2Call)
> """
> 
> class Object(object):
>  def method(self, value):
>  self._callable = value
>  def __call__(self):
>  return self._callable()
> 
> # populate the namespace
> namespace = {
>  "object": Object()
>  }
> 
> # execute the code
> exec code in namespace
> 
> namespace["object"]()

Just in case you didn't see it -- the following will work as well:

code = """
def funct2Call():
  return "It work!"
"""

namespace = {}
exec code in namespace
namespace["funct2Call"]()

Peter

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


Re: windev vs python SOS

2006-09-29 Thread M�ta-MCI
Re-Bonjour !

J'avais écrit, dans le message précédent, que la société PC-Soft avait eu 
des difficultés financières, il y a plusieurs années.

Comme je n'ai pas eu l'occasion de vérifier cette information, (et à la 
demande de la société PC-Soft), je demande donc aux lecteurs de considérer 
cette information comme nulle.

Concentrez-vous sur le reste du message.

@-salutations

Michel Claveau



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

RE: windev vs python SOS

2006-09-29 Thread Tim Golden
[Méta-MCI - translated for non-Francophones]

| Re-Bonjour !

Hello again!

| J'avais écrit, dans le message précédent, que la société 
| PC-Soft avait eu des difficultés financières, 
| il y a plusieurs années.

I wrote in the last message that PC-Soft had had financial
difficulties a few years ago.

| Comme je n'ai pas eu l'occasion de vérifier cette 
| information, (et à la demande de la société PC-Soft), 
| je demande donc aux lecteurs de considérer 
| cette information comme nulle.

As I have not had the opportunity to verify this
information (and at the request of PC-Soft),
I ask that reads consider this information null and void

| Concentrez-vous sur le reste du message.

Focus on the rest of the message.

| @-salutations
| 
| Michel Claveau

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: Making sure script only runs once instance at a time.

2006-09-29 Thread Paul Rubin
Hari Sekhon <[EMAIL PROTECTED]> writes:
> Seeing as there doesn't seem to be a good answer to this (or at least
> not one that we have so far some up with) I have decided to fall back
> to my old friend the unix shell. It's as portable as python, but is
> very flexible and fast at doing real things and will tell me if
> another process by this name is running. If so, print msg and
> exit. simple.

Huh?  The obvious way to check for another instance is with a lock
file.  Just open the file and use fcntl to set an exclusive lock.  If
the lock acquisition fails, another instance has the file.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: XSLT speed comparisons

2006-09-29 Thread uche . ogbuji
Ross Ridge wrote:
> Damian wrote:
> It could just be that 4suite is slower than MSXML.  If so, you can use
> MSXML in Python if you want.  You'll need to install the Python for
> Windows extensions.  Something like this:
>
>   from os import environ
>   import win32com.client
>
>   def buildPage():

[SNIP]

Added to:

http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/python-xslt

--
Uche Ogbuji   Fourthought, Inc.
http://uche.ogbuji.nethttp://fourthought.com
http://copia.ogbuji.net   http://4Suite.org
Articles: http://uche.ogbuji.net/tech/publications/

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


There's another Timbot on the loose!

2006-09-29 Thread Paul Rubin
http://web.cecs.pdx.edu/~mpj/timbot/index.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: There's another Timbot on the loose!

2006-09-29 Thread Jorge Godoy
Paul Rubin  writes:

> http://web.cecs.pdx.edu/~mpj/timbot/index.html

Should we tell them that we have the original and have a patent on him? :-) 

-- 
Jorge Godoy  <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pysqlite tables in RAM

2006-09-29 Thread Steve Holden
Ranjitha wrote:
> Hi all,
> 
> I'm relatively new to python and am facing a problem with database
> access
> 
> I want to store my data in a database on the disk. I also want to be
> able to reload the tables into the RAM whenever I have a lot of disk
> accesses and commit the changes back to the database. There is an
> option of storing the data in the RAM where you connect to :memory:
> instead of a DB file. The problem with this is that the data is lost
> everytime you close the connection to the database. Could somebody
> suggest a way to load the tables into the RAM as tables and not as some
> lists or dictionaries?
> 
As long as your data isn't too voluminous it's quite practical to read 
it from a SQLite database on disk into a SQLite database in memory, 
given the same table structures on each.

But if the data isn't too voluminous then probably any 
halfway-reasonable database will also cache it effectively. So you may 
win less performance that you expect.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: preemptive OOP?

2006-09-29 Thread John Salerno
Steve Holden wrote:

> You're right, it *is* just a name change in the code, but if you *do* 
> later want to specialise the notebook behaviour you can replace the 
> assignment with a class definition without changing any of your other code.

Oh! I wasn't quite thinking along those lines, but now it sounds good! :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: License / Registration key enabled software

2006-09-29 Thread Paul Boddie
Mike Playle wrote:
> Worry instead about the people who DON'T want to use it illegitimately. Can a 
> license key
> scheme help them?

That's "help them" as in "we can help you to stay in our good books and
avoid us dragging you through the courts, you bad people", I presume?
Hardly a vendor-customer relationship I'd want to get into as the
customer.

I've had experience with both hardware protection schemes (unreliable)
and floating licences (annoying, since users tend to "drop anchor"),
and both schemes penalise the people who've paid for (or have been
bought) software whilst supposedly inconveniencing those who will
nevertheless have cracked the software within a short period of time
before exchanging it with friends and strangers. So, the software will
probably roam around of its own accord, anyway. Here, the moderating
factor in propagation is (or should be amongst people with any degree
of cautiousness) the lack of trust in the cracked product: what malware
also gets installed along with the original software?

Meanwhile, the big company scenario that advocates of restrictive
technical licensing solutions like to mention actually suggests
incompetence in the management of customer relations at such companies:
you sell the big company five licences of your software because they
tell you that's all they need, but you secretly suspect that everyone
is using the software. But any interest in the number of people using
the software is presumably driven by some per-seat pricing that could
be totally inappropriate. Some desire to have a 1980s-style
shrinkwrapped box retail price tag has constrained the business's
ability to judge the value of the software on a case-by-case basis,
which you'd want to do with important customers. The big company might
not be an important customer as it turns out, but by focusing on the
relationship itself, rather than auditing and threatening them, you
might actually get a chance to find this out in a way which presents
opportunities other than a face-off in court.

Interestingly, the innovation in this area would seem to be happening
either in companies offering dual-licensed solutions, where one of the
licences is the GPL, or even in companies only offering GPL-licensed
solutions but with paid support options available in addition. That's
how stagnant the style of proprietary software business referred to
here would appear to be with respect to business innovation these days.

Paul

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


Re: Making sure script only runs once instance at a time.

2006-09-29 Thread Hari Sekhon




I'm not sure if that is a very old way of doing it, which is why I was
reluctant to do it. My way actually uses the process list of the os
(linux) and counts the number of instances. If it is more than 0 then
another process is running and the script exits gracefully.

Also, apart from the fact the using lockfiles feels a bit 1970s, I have
found that in real usage of other programs within the company that use
lockfiles, it sometimes causes a bit of troubleshooting time when it
stops working due to a stale lockfile. This especially happens when the
program is killed, the lockfile remains and causes minor annoyance (to
somebody who knows that is, more annoyance to somebody who doesn't).

-h
Hari Sekhon


Paul Rubin wrote:

  Hari Sekhon <[EMAIL PROTECTED]> writes:
  
  
Seeing as there doesn't seem to be a good answer to this (or at least
not one that we have so far some up with) I have decided to fall back
to my old friend the unix shell. It's as portable as python, but is
very flexible and fast at doing real things and will tell me if
another process by this name is running. If so, print msg and
exit. simple.

  
  
Huh?  The obvious way to check for another instance is with a lock
file.  Just open the file and use fcntl to set an exclusive lock.  If
the lock acquisition fails, another instance has the file.
  



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

Re: sqlite3 error

2006-09-29 Thread John Salerno
John Machin wrote:

> The problems are (1) there are cultures that don't have the concept of
> a surname, and if they do, it may not be the "last name" (2) the name
> may consist of only one word (giving you problems with "not null") or
> not even be a word.
> 
> It gets better:
> 
> Iceland: Jon Bjornsson and Hildur Bjornsdottir are the children of
> Bjorn Eiriksson
>
> etc. etc.

Ok, you make me want to crawl under my desk and whimper until 5pm. :)

Fortunately my program is just a test to give me something to do, and 
will only use the names of people already working here that happen to 
(for the most part) fit into my model (although they *are* all foreign, 
so it's good to keep these exceptions in mind.) And I guess it never 
hurts to consider these things for future expansion either.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pysqlite tables in RAM

2006-09-29 Thread John Salerno
Ranjitha wrote:
> Hi all,
> 
> I'm relatively new to python and am facing a problem with database
> access
> 
> I want to store my data in a database on the disk. I also want to be
> able to reload the tables into the RAM whenever I have a lot of disk
> accesses and commit the changes back to the database. There is an
> option of storing the data in the RAM where you connect to :memory:
> instead of a DB file. The problem with this is that the data is lost
> everytime you close the connection to the database. Could somebody
> suggest a way to load the tables into the RAM as tables and not as some
> lists or dictionaries?
> 
> Thanks,
> Simba
> 

Just a side note: judging from your subject line, are you using the 
pysqlite extension? In case you are, SQLite support comes with the 
standard library in 2.5 as sqlite3, in case you want to switch.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: There's another Timbot on the loose!

2006-09-29 Thread John Machin

Jorge Godoy wrote:
> Paul Rubin  writes:
>
> > http://web.cecs.pdx.edu/~mpj/timbot/index.html
>
> Should we tell them that we have the original and have a patent on him? :-)
>
> --

Page last updated in 2002 ... site looks like the Marie Celeste.
Perhaps our timbot undertook a preemptive strike on the would-be
usurper :-)

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


RE: Making sure script only runs once instance at a time.

2006-09-29 Thread Matthew Warren



 

  
  
  From: 
  [EMAIL PROTECTED] 
  [mailto:[EMAIL PROTECTED] On Behalf 
  Of Hari SekhonSent: 29 September 2006 14:55To: 
  python-list@python.orgSubject: Re: Making sure script only runs 
  once instance at a time.
  
  I'm not sure if that is a very old way of doing it, which is why I was 
  reluctant to do it. My way actually uses the process list of the os (linux) 
  and counts the number of instances. If it is more than 0 then another process 
  is running and the script exits gracefully.Also, apart from the fact 
  the using lockfiles feels a bit 1970s, I have found that in real usage of 
  other programs within the company that use lockfiles, it sometimes causes a 
  bit of troubleshooting time when it stops working due to a stale lockfile. 
  This especially happens when the program is killed, the lockfile remains and 
  causes minor annoyance (to somebody who knows that is, more annoyance to 
  somebody who doesn't). 
   

 
This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. 
You should not copy the email, use it for any purpose or disclose its contents to any other person.Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica.It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email.
UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UKReception Tel: + 44 (0) 115 977 1177Support Centre: 0845 607 7070Fax: + 44 (0) 115 977 7000http://www.digica.com
SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South AfricaTel: + 27 (0) 21 957 4900Fax: + 27 (0) 21 948 3135http://www.digica.com
 
 
This message has been scanned for viruses by BlackSpider in Partnership with Digica
 

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

Re: File I/O

2006-09-29 Thread Diez B. Roggisch
jimburton wrote:

> 
> Diez B. Roggisch wrote:
>> Kirt wrote:
>>
>> >
>> > jimburton wrote:
>> >> Kirt wrote:
>> >> > Hi! I need some help in file I/O
>> >> >
>> >> > I have an xml file..
>> >> [snip]
>> >> See http://diveintopython.org/xml_processing/
>> >
>> > i dont wanna parse the xml file..
>>
>> If you play soccer, do you insist on playing with a baseball bat?
>> 
> I've been known to open a bottle of wine with a pencil. Works fine.

Good to know that you can get drunk under any circumstances.

I have seen a bazillion bad xml/html parsing-hacks using regexes and the
like, which stopped working after somehow the xml came all in one line, or
some other implicit assumption about its layout failed to be met. 




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


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-29 Thread Neil Cerutti
On 2006-09-29, Steve Holden <[EMAIL PROTECTED]> wrote:
> MonkeeSage wrote:
>> So far as unobfuscated versions go, how about the simple:
>> 
>> def to_bin(x):
>>   out = []
>>   while x > 0:
>> out.insert(0, str(x % 2))
>> x = x / 2
>>   return ''.join(out)
>> 
>> Regards,

It was surprising that

>>> i = int("111010101", 2)

is a one-way operation.

>>> s = str(i, 2)
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: str() takes at most 1 argument (2 given)

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


Problems wth os.stat().st_mtime on Mac

2006-09-29 Thread Michael Glassford
The Python 2.5 News at 
http://www.python.org/download/releases/2.5/NEWS.txt states that Python 
2.5 was changed to "Use Win32 API to implement os.stat/fstat. As a 
result, subsecond timestamps are reported, the limit on path name 
lengths is removed, and stat reports WindowsError now (instead of OSError)."

Although not mentioned in the Python 2.5 News, apparently there was a 
similar change on Mac that I'm having some problems with. On the Mac, 
just as on Windows, os.stat().st_mtime now returns a float instead of an 
integer. My problem is that the decimal part of the float is 
inconsistent in two ways.

1) The more serious problem (for me), is that on two machines (PowerPC 
Mac Mini running Tiger and Intel Mac Mini running Tiger), the decimal 
part of the returned float always appears to be ".0". On an iBook 
running Panther, however, the decimal part appears to be ".0" for many 
files, but for other files it contains actual significant digits. For 
example:

 import os
 f = open("/tmp/tmp.tmp", "w")
 f.close()
 print os.stat("/tmp/tmp.tmp").st_mtime

 #Both Mac Minis: 1159536137.0
 #iBook: 1159536233.08

a) Why the difference between machines?

Also, on the iBook, I created this listing:

 >>> for x in os.listdir("/tmp"): os.stat(os.path.join("/tmp", 
x)).st_mtime, x
 (1159466888.0, '502')
 (1159469259.0, '505')
 (1159472677.0, 'hsperfdata_build')
 (1159466868.0, 'mcx_compositor')
 (1159466908.0, 'SoftwareUpdateCheck.pkgcatalog')
 (1159532547.2405169, 'test.xxx')
 (1159536233.0794201, 'tmp.tmp')

b) Why do most files on this machine have ".0", while some (generally 
those I created myself using Python 2.5, I think) don't?


2) Even on the same machine, the results are different depending on how 
I access them. For example, after setting up as follows:

 strPath = "/tmp/test.xxx"
 f = open(strPath, "w")
 f.close()

I get the following output:

 >>> os.stat(strPath)
 (33188, 1822331L, 234881030L, 1, 505, 0, 0L, 1159532547, 
1159532547, 1159533628)
 #Note that the results are all integers, including mtime

 >>> os.stat(strPath).st_mtime
 1159532547.2405169
 #The result has 7 decimal places

I understand how the results can be different: the os.stat() function 
returns a posix.stat_result object, which gives back an integer value 
for the mtime if you call __str__ or __repr__, or if you iterate on it; 
and a float if you get the st_mtime attribute. But I would consider it a 
bug that the results are different: a float should be returned in either 
case.


Mike

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


Re: wxPython and threading issue

2006-09-29 Thread Patrick Smith
> Well, the problem is that you can't simply kill a thread--it shares
> memory with other threads that it could be leaving in an inconsistent
> state.  Imagine that it was, say, holding a lock when it was forceably
> killed.  Now any other thread that tries to acquire that lock will
> block forever.
>
> You really do need the thread's cooperation so that it only exits when
> everything is in a kosher state.  Can you dig into the incredibly long
> function and change it to do the flag-checking and exiting safely?
>
> I second the notion to consider using subprocesses instead of threads;
> that's almost always a good idea unless you're really sharing a lot of
> complex data structures.
>

Hi,
Thanks again for your replies.

The way this was originally working was actually using a subprocess,
however, the people who this program is for were having problems that when
the application was closed, the subprocess was still around in the system,
which was why they wanted the other module it is using to have a function it
could call, rather then using popen on the main method.

Also, the people who I am doing this for need something ASAP and for now are
fine with the cancel button completely closing the entire program.  Is there
at least a nice way to do this?

Thanks for all your replies,they've all been very helpful.


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


Re: PATCH: Speed up direct string concatenation by 20+%!

2006-09-29 Thread Larry Hastings
Steve Holden wrote:

> you should diff your source against the current
> SVN repository and lodge that diff as a patch on SourceForge.

Okay, I'll try to do that today.


> Your suggested bug isn't, I think a real bug in the current
> implementation because as I understand it Python strings do always
> include a trailing null byte to act as a terminator when the string
> is passed to C code in extensions.

Ah!  Excellent point.  So the Python source tree *does* have an
official position on what the first byte of a zero-length string should
be.  I'll fix my code so that is ensured.


> Nice idea, though. You might also see how it does on tasks like
>
> s = ""
> for i in range(10):
> s += "a"

Sure.  Here are the results, but with range (1000):
Python 2.5 release: 31.0s
Python 2.5 locally built: 30.7s
Python 2.5 concat: 4.4s
% Improvement: *697%*!

Woah!  Thanks for suggesting a benchmark where it really shines :)

The real big win here is storing eight pointers per concatenation
object.  That means 1/8th as many objects created/destroyed.

In testing your suggested benchmark, it overflowed the stack
when freeing the concatenation tree.  So I changed deallocation
of string concatenation objects so it's iterative down the
left-hand side like rendering; now it's happy again.  Thanks
again for suggesting the test.

It would still blow up if you ran
  s = ""
  for i in range(1000):
s = "a" + s
because it's only clever about recursion down the left-hand side.
So my advice is, don't.  :)

> Also note that some optimisation has recently been performed on string
> concatenation, which I presume your code has already taken into account.

Totally.  I'm just glad there was something left for me to contribute!


Rob Williscroft wrote:
> On the python 3k list there is a thread about stings becoming "views",
> I think this is similar to what you are doing here.

As I understand it, sort-of.  Definitely moreso in my section on THE
FUTURE--adding another subtype of string for slices which point into
other strings.  I believe views are more sophisticated however.


Felipe Almeida Lessa wrote:
> What about "a + b"? Or "a + b + c"? Does it have a large overhead on
> small string concatenations?

It's *slightly* slower for two:

def addTwoThings(a, b):
return a + b
for i in range(1000):
x = addTwoThings("aaa", "bbb")

Python 2.5 release: 6.219s
Python 2.5 locally built: 6.219s
Python 2.5 concat: 6.234s
% improvement: -0.03%

But starts paying off already, even with three:

def addThreeThings(a, b, c):
return a + b + c
for i in range(1000):
x = addThreeThings("aaa", "bbb", "ccc")

Python 2.5 release: 7.9s
Python 2.5 locally built: 7.7s
Python 2.5 concat: 7.2s
% improvement: 6.94%

Note that I was lazy and only did one benchmark run apiece.

Also, keep in mind that memory utilization will be a little higher
with the string concatenation objects.


Carl Friedrich Bolz wrote:
> Robin Becker wrote:
> > wouldn't this approach apply to other additions eg list+list seq+seq etc
> > etc.
> no, I think it depends on strings being immutable.

Exactly.


/larry/

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


Re: Pysqlite tables in RAM

2006-09-29 Thread Fredrik Lundh
Ranjitha wrote:

> I want to store my data in a database on the disk. I also want to be
> able to reload the tables into the RAM whenever I have a lot of disk
> accesses and commit the changes back to the database.

using the cache_size and synchronous pragmas sounds like a better way to 
trade reliability against speed/memory use.  e.g.

table_memory = 1 # bytes
cur.execute("pragma cache_size = %d;" % (table_memory / 1500))

...

cur.execute("pragma synchronous = off;")
# do lots of stuff
cur.execute("pragma synchronous = full;")

for more on this, see: http://www.sqlite.org/pragma.html



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


Re: wxPython and threading issue

2006-09-29 Thread Patrick Smith

"Nick Vatamaniuc" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> If your thread is long running and it is not possible to easily set a
> flag for it to check and bail out, then how does it display the
> progress in the progress dialog. How often does that get updated? If
> the progress dialog is updated often, then at each update have the
> thread check a self.please_die flag, for example, and break out
> (possibly after releasing some resources...).
>
>
> Having the work done in an external process might or might not work
> easily for your problem. It will make it easy to kill the execution but
> it might be OS dependent, and you will have to define some
> communication interface between your processes (for example, how would
> an external process easily provide progress feedback to its parent?).
>
>

Hi,
The external process was their original approach, but when cancel was
pressed or the UI was closed they found the subprocess still around.  Also,
it must work on windows, linux, and mac.

thanks.


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


How to iterate through a sequence, grabbing subsequences?

2006-09-29 Thread Matthew Wilson
I wrote a function that I suspect may already exist as a python builtin,
but I can't find it:

def chunkify(s, chunksize):
"Yield sequence s in chunks of size chunksize."
for i in range(0, len(s), chunksize):
yield s[i:i+chunksize]

I wrote this because I need to take a string of a really, really long
length and process 4000 bytes at a time.

Is there a better solution?

Matt

-- 
A better way of running series of SAS programs:
http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-29 Thread Georg Brandl
Neil Cerutti wrote:
> On 2006-09-29, Steve Holden <[EMAIL PROTECTED]> wrote:
>> MonkeeSage wrote:
>>> So far as unobfuscated versions go, how about the simple:
>>> 
>>> def to_bin(x):
>>>   out = []
>>>   while x > 0:
>>> out.insert(0, str(x % 2))
>>> x = x / 2
>>>   return ''.join(out)
>>> 
>>> Regards,
> 
> It was surprising that
> 
 i = int("111010101", 2)
> 
> is a one-way operation.
> 
 s = str(i, 2)
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: str() takes at most 1 argument (2 given)

str() is not only for converting integers, but all other types too.
An explicit argument for this special case is not Pythonic IMO.

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


Re: Questions on Using Python to Teach Data Structures and Algorithms

2006-09-29 Thread sturlamolden
MonkeeSage wrote:

> > def cons(car,cdr): return (car,cdr) # or [car,cdr]
> > def car(cons): return cons[0]
> > def cdr(cons): return cons[1]
>
> I guess you were talking about implementing the _structure_ of lisp
> lists in python syntax (as you seem to imply), not trying to emulate
> their _behavior_ with one-dimensional python lists.

The original poster was asking about using Python for teaching data
structures and algorithms, and the implementation details of Python
lists in particular. It may not be obvious that they are essentially
arrays under the hood.

The Lisp discussion became a digression; I was not trying to implement
Lisp in Python, but rather demonstrate the difference between Lisp
lists and Python lists.

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


Re: XSLT speed comparisons

2006-09-29 Thread uche . ogbuji
[EMAIL PROTECTED] wrote:
> For what it's worth I just developed, and switched to WSGI middleware
> that only does the transform on the server side if the client doesn't
> understand XSLT.  It's called applyxslt and is part of wsgi.xml [1].
> That reduces server load, and with caching (via Myghty), there's really
> no issue for me.  For more on WSGI middleware see [2].
>
> [1] http://uche.ogbuji.net/tech/4suite/wsgixml/
> [2] http://www.ibm.com/developerworks/library/wa-wsgi/

I just wanted to clarify that not only does the applyxslt middleware
approach reduce server load, but in the case of clients running IE6 or
IE7, the XSLT *does* end up being executed in MSXML after all: MSXML on
the client's browser, rather than on the server.  In the case of
Mozilla it's Transformiix, which is between MSXML and 4Suite in
performance.  Not sure what's the XSLT processor in the case of Safari
(only the most recent versions of Safari).  But regardless, with that
coverage you can write apps using XSLT, support the entire spectrum of
browsers (and mobile apps, spiders, etc.) and yet rarely ever require
XSLT applied on the server side.


> --
> Uche Ogbuji   Fourthought, Inc.
> http://uche.ogbuji.nethttp://fourthought.com
> http://copia.ogbuji.net   http://4Suite.org
> Articles: http://uche.ogbuji.net/tech/publications/

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


Re: Making sure script only runs once instance at a time.

2006-09-29 Thread Fredrik Lundh
Hari Sekhon wrote:

> I'm not sure if that is a very old way of doing it, which is why I was 
> reluctant to do it. My way actually uses the process list of the os 
> (linux) and counts the number of instances. If it is more than 0 then 
> another process is running and the script exits gracefully.

the code that reliably identifies instances of a given program would be 
interesting to see.

> Also, apart from the fact the using lockfiles feels a bit 1970s, I have
 > found that in real usage of other programs within the company that use
 > lockfiles, it sometimes causes a bit of troubleshooting time when
 > it stops working due to a stale lockfile.

to minimize that risk, store the pid in the lockfile (and preferrably 
also the host name), and make sure that the program checks that the pid 
is still active before it "stops working".



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


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-29 Thread Neil Cerutti
On 2006-09-29, Georg Brandl <[EMAIL PROTECTED]> wrote:
> Neil Cerutti wrote:
>> On 2006-09-29, Steve Holden <[EMAIL PROTECTED]> wrote:
>>> MonkeeSage wrote:
 So far as unobfuscated versions go, how about the simple:
 
 def to_bin(x):
   out = []
   while x > 0:
 out.insert(0, str(x % 2))
 x = x / 2
   return ''.join(out)
 
 Regards,
>> 
>> It was surprising that
>> 
> i = int("111010101", 2)
>> 
>> is a one-way operation.
>> 
> s = str(i, 2)
>> Traceback (most recent call last):
>>   File "", line 1, in ?
>> TypeError: str() takes at most 1 argument (2 given)
>
> str() is not only for converting integers, but all other types
> too. An explicit argument for this special case is not Pythonic
> IMO.

I suppose two wrongs wouldn't make a right. ;)

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


Re: "ValueError: Empty module name" on basic import

2006-09-29 Thread John Machin
alain MONTMORY wrote:
> Hello everybody,
>
> I am a newbie to python so I hope I am at the right place to expose my
> problem. :-[
>
> I am working on linux mandrake 10.1 with python :
> python -V
> Python 2.3.4
> I am trying o run the example which stay in the documentation in paragraph
> http://www.python.org/doc/2.4.2/ext/pure-embedding.html 5.3 Pure Embedding
> I download the code example from
> http://www.python.org/doc/2.4.2/ext/run-func.txt
> I call the file "TestOfficiel.c" and I compile it with :
> gcc -g -I/usr/include/python2.3/ TestOfficiel.c -o TestOfficiel
> -lpython2.3 -ldl
> all is OK (or seems to be...).
> as stated in the documentation  I creat a file "TestPythonFoo.py" which
> contain
> "
> def multiply(a,b):
> print "Will compute", a, "times", b
> c = 0
> for i in range(0, a):
> c = c + b
> return c
> "
> I launch
> ./TestOfficiel ./TestPythonFoo.py multiply 3 2
> and as a result :
> ValueError: Empty module name
> Failed to load "./TestPythonFoo.py"

This is (I believe) because of the "." at the front.

> if I try an absolute path to the python file :
> ./TestOfficiel `pwd`/TestPythonFoo.py multiply 3 2
> I obtain :
> ImportError: No module named
> /space/ESOPPE_PROJET/Outils/SwigPython/swigCallPython/TestPythonFoo.py

It's quite correct, there never could be a module named that. The name
of your module is TestPythonFoo -- so all you should have to do is
./TestOfficiel TestPythonFoo multiply 3 2

> Failed to load
> "/space/ESOPPE_PROJET/Outils/SwigPython/swigCallPython/TestPythonFoo.py"


> Of course the file exist :
> [EMAIL PROTECTED] swigCallPython]$ ll
> /space/ESOPPE_PROJET/Outils/SwigPython/swigCallPython/TestPythonFoo.py
> -rwxrwx--x  1 montmory esoppe 126 sep 29 14:04
> /space/ESOPPE_PROJET/Outils/SwigPython/swigCallPython/TestPythonFoo.py*
>
> I found lot of post about "ValueError: Empty module name" but no clear
> solution (clear for me...).
> What's wrong ?
> my python version?
> Additionnal informations :
> gcc version 3.4.1 (Mandrakelinux 10.1 3.4.1-4mdk)
>
> Thanks for your help,
>
> best regards,
>
> Alain
>
>
>
>
> --07010503090108070407
> Content-Type: text/plain
> Content-Disposition: inline;
>   filename="TestOfficiel.c"
> X-Google-AttachSize: 2022
>
> #include 
>
> int
> main(int argc, char *argv[])
> {
> PyObject *pName, *pModule, *pDict, *pFunc;
> PyObject *pArgs, *pValue;
> int i;
>
> if (argc < 3) {
> fprintf(stderr,"Usage: call pythonfile funcname [args]\n");

"pythonfile" is confusing; it should be "modulename".


> return 1;
> }
>
> Py_Initialize();
> pName = PyString_FromString(argv[1]);
> /* Error checking of pName left out */
>
> pModule = PyImport_Import(pName);

As the docs for this function say, it just calls the same routine that
is called by the __import__ built-in function. One can experiment with
that:


OS-prompt>copy con foo.py
print 'hello fubar world'
^Z
1 file(s) copied.

OS-prompt>python
Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> __import__("foo")
hello fubar world

>>> __import__("foo.py")
Traceback (most recent call last):
  File "", line 1, in ?
ImportError: No module named py
>>> __import__("")
Traceback (most recent call last):
  File "", line 1, in ?
ValueError: Empty module name
>>> __import__(r".\foo")
Traceback (most recent call last):
  File "", line 1, in ?
ValueError: Empty module name
>>> __import__(r"./foo")
Traceback (most recent call last):
  File "", line 1, in ?
ValueError: Empty module name
>>> __import__(r"/foo")
Traceback (most recent call last):
  File "", line 1, in ?
ImportError: No module named /foo
>>> __import__(r".foo")
Traceback (most recent call last):
  File "", line 1, in ?
ValueError: Empty module name
>>>

Hmmm ... "empty module name" is rather misleading when it starts with a
"." -- I can feel a bugfix^^ enhancement request coming on :-)

HTH,
John

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


[ANN] Spasmoidal 0.1.0 - Asynchronous I/O with Python 2.5 Extended Generators

2006-09-29 Thread [EMAIL PROTECTED]
"...from little towns with strange names like Smegma, Spasmodic, Frog,
and the far-flung Isles of Langerhans".

Someone on SourceForge has a project that includes the name
'spasmodic' so I'm using the name spasmoidal. But this code will
always be spasmodic to me.

Asynchronous I/O (and other tasks) proceeding in fits and spasms
The SpasmodicEngine selects tasks (spasmoids) from a (heapqueue based)
priority queue. The tasks are Python 2.5 extended generators (some
call them coroutines: PEP 342). The engine calls task.send() with an
appropriate argument. One of the library of tasks is Pollster.
Pollster calls poll() with for tasks that are waiting I/O. Tasks that
are ready for I/O are fed to the priority queue.

Spasmodic provides an efficient way to manage a large number of
sockets and/or files. Other processing works well too, if it can be
subdivided into brief spasms.

Project
http://code.google.com/p/spasmoidal/

Download
http://cheeseshop.python.org/pypi/spasmoidal/0.1.0
--
Doug Fort, Consulting Programmer
http://www.dougfort.com

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


Re: How to iterate through a sequence, grabbing subsequences?

2006-09-29 Thread Bruno Desthuilliers
Matthew Wilson wrote:
> I wrote a function that I suspect may already exist as a python builtin,
> but I can't find it:
> 
> def chunkify(s, chunksize):
> "Yield sequence s in chunks of size chunksize."
> for i in range(0, len(s), chunksize):
> yield s[i:i+chunksize]
> 
> I wrote this because I need to take a string of a really, really long
> length and process 4000 bytes at a time.
> 
> Is there a better solution?

I don't know if it's better, but StringIO let you read a string as if it
was a file:

def chunkify(s, chunksize):
  f = StringIO.StringIO(long_string)
  chunk = f.read(chunksize)
  while chunk:
yield chunk
chunk = f.read(chunksize)
  f.close()

Now I'm sure someone will come up with a solution that's both far better
and much more obvious (at least if you're Dutch )

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >