Reg strip_tags function in Python.

2005-05-07 Thread praba kar

Dear All,

In Php I can use strip_tags() function to strip out
all html tags. I want to know that strip_tags()
equivalent function in Python.

regards 
praba


Yahoo! India Matrimony: Find your life partner online
Go to: http://yahoo.shaadi.com/india-matrimony
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Found python for delphi new web site

2005-05-07 Thread James
I didn't either since it needs some components to be installed. I will
surely try playing with the source. It should be a lot easier to
customerize than other IDEs.

I just installed the binary
http://mmm-experts.com/Downloads.aspx?ProductId=4

It does have code insight in the interpreter, but not in the editor
like SPE etc. Also, I could not figure what the shortcut for code
completion is. Should not be a problem once I compile the source since
it uses SynEdit.

The debugger feels very nice (Window layout wise. Visual Studio-ish
feel). Better than PythonWin even, though it doesn't do anything new as
far as I can tell.

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


Array programming

2005-05-07 Thread V.C.Sekhar
Hi there,
   I couldnt get to do the following task using Python. Can some pls 
suggest me a way to do this.

I have an array with duplicate strings filled in it. Now am looking for 
a way to extract only the DISTINCT Values from that array.

Could some one pls help me out.

Thanks in advance,
Sekhar


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


Re: Array programming

2005-05-07 Thread Sakesun Roykiattisak
V.C.Sekhar wrote:

Hi there,
   I couldnt get to do the following task using Python. Can some pls 
suggest me a way to do this.

I have an array with duplicate strings filled in it. Now am looking for 
a way to extract only the DISTINCT Values from that array.

Could some one pls help me out.

Thanks in advance,
Sekhar


  


try use set or frozenset, if you use python2.4
or try sets.Set or sets.ImmutableSet, if you use python2.3

  import sets
  s = sets.Set([1,1,2,3,2,4])
  for x in s: print x
1
2
3
4

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


Re: Reg strip_tags function in Python.

2005-05-07 Thread Terry Hancock
On Saturday 07 May 2005 01:25 am, praba kar wrote:
 In Php I can use strip_tags() function to strip out
 all html tags. I want to know that strip_tags()
 equivalent function in Python.

AFAIK, there's no such thing in the standard library,
however there is a very nice pure python module called
stripogram which provides functions both for completely
stripping HTML and for allowing a subset of it (if, for
example, you would like to keep bold and italic formatting,
but nothing else).

Just google for stripogram, it's hosted at zope.org.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: Encryption with Python?

2005-05-07 Thread Henk-Jan de Jong
Blake T. Garretson wrote:
 I want to save some sensitive data (passwords, PIN numbers, etc.) to
 disk in a secure manner in one of my programs.  What is the
 easiest/best way to accomplish strong file encryption in Python?  Any
 modern block cipher will do: AES, Blowfish, etc.  I'm not looking for
 public key stuff; I just want to provide a pass-phrase.
 
 I found a few modules out there, but they seem to be all but abandoned.
  Most seem to have died several years ago.  The most promising package
 is A.M. Kuchling's Python Cryptography Toolkit
 (http://www.amk.ca/python/code/crypto.html).
 
 Is this the defacto Python encryption solution?  What does everyone
 else use?  Any other suggestions?  The SSLCrypto package
 (http://www.freenet.org.nz/python/SSLCrypto/) may be a good alternative
 too, but I am not sure if it is actively maintained.
 
 Thanks,
 Blake
 

There's a DES implementation at

http://home.pacific.net.au/~twhitema/des.html
-- 
http://mail.python.org/mailman/listinfo/python-list


How to create email distribution list in yahoo mail?

2005-05-07 Thread egelendu
How to create email distribution list in yahoo mail?


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


Re: How to create email distribution list in yahoo mail?

2005-05-07 Thread Robert Kern
egelendu wrote:
 How to create email distribution list in yahoo mail?

This is a mailing list/newsgroup for the Python programming language. 
Questions about Yahoo Mail should go somewhere else.

-- 
Robert Kern
[EMAIL PROTECTED]

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

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


Re: Encryption with Python?

2005-05-07 Thread Anthra Norell
I rolled my own for relatively short sequences, like passwords. The key is
an integer. To decrypt use the negative encryption key. I consider the
encryption unbreakable, as it is indistinguishable from a random sequence.

Frederic

###

def crypt (sequence, key):
   import random
   sign = (key  0) * 2 - 1
   random.seed (abs (key * sign))
   s = ''
   for i in xrange (len (sequence)):
  r = random.randint (0, 255)
  s += chr ((ord (sequence [i]) + r * sign) % 256)
   return s

###

If unauthrorized use of the machine is a concern, crypt might not be an
appropriate name for the function. To help an intruder understand it, a doc
string such as the following one might be useful:

def cyrep (sequence, key):

   
  Cyclic Redundancy Preprocessor
 Cyclic redundancy checks often fail to differentiate relatively
short
 sequences that contain sequences of binary zeroes of different
length.
 This preporcessor applies a keyed randomizing filter to improve the
 capability of the cyclic redundancy algorithm. Use the output of
this
 function as input to a CRC routine.
Negative keys cannot be used. If passed they are positivized
rather
 than rejected.
   

###

- Original Message -
From: Blake T. Garretson [EMAIL PROTECTED]
Newsgroups: comp.lang.python
To: python-list@python.org
Sent: Thursday, May 05, 2005 10:20 PM
Subject: Encryption with Python?


 I want to save some sensitive data (passwords, PIN numbers, etc.) to
 disk in a secure manner in one of my programs.  What is the
 easiest/best way to accomplish strong file encryption in Python?  Any
 modern block cipher will do: AES, Blowfish, etc.  I'm not looking for
 public key stuff; I just want to provide a pass-phrase.

 I found a few modules out there, but they seem to be all but abandoned.
  Most seem to have died several years ago.  The most promising package
 is A.M. Kuchling's Python Cryptography Toolkit
 (http://www.amk.ca/python/code/crypto.html).

 Is this the defacto Python encryption solution?  What does everyone
 else use?  Any other suggestions?  The SSLCrypto package
 (http://www.freenet.org.nz/python/SSLCrypto/) may be a good alternative
 too, but I am not sure if it is actively maintained.

 Thanks,
 Blake

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

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


Re: Encryption with Python?

2005-05-07 Thread Paul Rubin
Anthra Norell [EMAIL PROTECTED] writes:
 I rolled my own for relatively short sequences, like passwords. The
 key is an integer. To decrypt use the negative encryption key. I
 consider the encryption unbreakable, as it is indistinguishable from
 a random sequence.

You're using the built-in random module which is designed to provide
only statistical randomness and not cryptographic security.  It should
not be used for encryption.  The math paper describing the function is
quite clear about that.  There is a lot of subtlety to this stuff and
it's easy to make mistakes even if you know what you're doing.  Even
using well-tested block ciphers (various people mentioned DES, AES,
and Blowfish modules) it's easy to make mistakes in choosing operation
modes, thinking you don't need authentication when you really do,
etc., etc.  The book Practical Cryptography by Bruce Schneier and
Niels Ferguson is worth looking at if you want to see what you're
getting yourself into.

I hate to come across as plugging my own stuff too much, but

http://www.nightsong.com/phr/crypto/p3.py

is designed to take care of most of the tricky issues for you while
still having a very simple interface, and also be reasonably fast
(much faster for large messages than any of the pure Python block
cipher modules).  Just use p3_encrypt(plain) to encrypt and
p3_decrypt(cipher) to decrypt.  The main penalty you pay is that the
ciphertext is a couple dozen bytes longer than the plaintext.  There
are cryptographically important reasons for that; don't try to escape
it without knowing exactly what's going on.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: py2exe + svn - the final drama

2005-05-07 Thread Just
In article [EMAIL PROTECTED],
 David Bolen [EMAIL PROTECTED] wrote:

 Just [EMAIL PROTECTED] writes:
 
  the zipimport module has an attr called _zip_directory_cache, which is a 
  dict you can .clear(). Still, reloading modules is hairy at best, its 
  probably easiest to relaunch your app when the .zip file has changed.
 
 Except that he's getting an error during the process exit of the
 current execution, which is needed to restart.  And if he updates to a
 different copy, there's the bootstrap problem of how to get it back
 into the standard location for the next restart since his application
 will need to have it to restart in the first place.

Right. It sounds like a module is imported at exit that wasn't imported 
before. If that's the case, it may help to make sure all modules needed 
for exit are imported beforehand.

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


Re: Encryption with Python?

2005-05-07 Thread Robert Kern
Anthra Norell wrote:
 I rolled my own for relatively short sequences, like passwords. The key is
 an integer. To decrypt use the negative encryption key. I consider the
 encryption unbreakable, as it is indistinguishable from a random sequence.
 
 Frederic
 
 ###
 
 def crypt (sequence, key):
import random
sign = (key  0) * 2 - 1
random.seed (abs (key * sign))
s = ''
for i in xrange (len (sequence)):
   r = random.randint (0, 255)
   s += chr ((ord (sequence [i]) + r * sign) % 256)
return s

The mind boggles.

You do realize that if I have two ciphertexts encrypted with the same 
key, I can subtract them? Then I have a sequence, that while not 
immediately readable, is just a straightforward combination of the two 
plaintexts without any encryption.

This function is also vulnerable to a chosen-plaintext attack. The 
underlying PRNG is definitely not suitable for cryptographic 
applications. The documentation even says so!

http://docs.python.org/lib/module-random.html
However, being completely deterministic, it is not suitable for all 
purposes, and is completely unsuitable for cryptographic purposes.

Do yourself a favor and don't try to roll your own cryptographic 
functions. Do everyone else a favor and don't call something 
unbreakable unless you actually have the domain expertise to make that 
determination.

And do read _Practical Cryptography_.

-- 
Robert Kern
[EMAIL PROTECTED]

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

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


Re: handling more databases with ZEO

2005-05-07 Thread Simon Percivall
You should take a look at
http://www.zope.org/Wikis/ZODB/FrontPage/guide/index.html

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


Re: Encryption with Python?

2005-05-07 Thread Anthra Norell
Thanks a lot for the feedback. This is certainly a great learning
experience. It's a fascinating topic too. Without wishing to annoy, I'd be
interested in knowing more. I insert questions below.

- Original Message -
From: Robert Kern [EMAIL PROTECTED]
To: python-list@python.org
Sent: Saturday, May 07, 2005 11:11 AM
Subject: Re: Encryption with Python?


 Anthra Norell wrote:
  I rolled my own for relatively short sequences, like passwords. The key
is
  an integer. To decrypt use the negative encryption key. I consider the
  encryption unbreakable, as it is indistinguishable from a random
sequence.
 
  Frederic
 
  ###
 
  def crypt (sequence, key):
 import random
 sign = (key  0) * 2 - 1
 random.seed (abs (key * sign))
 s = ''
 for i in xrange (len (sequence)):
r = random.randint (0, 255)
s += chr ((ord (sequence [i]) + r * sign) % 256)
 return s

 The mind boggles.

 You do realize that if I have two ciphertexts encrypted with the same
 key, I can subtract them? Then I have a sequence, that while not
 immediately readable, is just a straightforward combination of the two
 plaintexts without any encryption.

How do you know the same key was used?
What if the messages aren't the same length?
How does one reconstruct either or both of two messages from their
difference?

 This function is also vulnerable to a chosen-plaintext attack. The
 underlying PRNG is definitely not suitable for cryptographic
 applications. The documentation even says so!

What is a plain-text attack? Is it you give me a plain text. I encrypt it
using the same keys and hand you the result? Would I comply with the
request?

 http://docs.python.org/lib/module-random.html
 However, being completely deterministic, it is not suitable for all
 purposes, and is completely unsuitable for cryptographic purposes.

The logic escapes me if it is understood to mean that cryptography, in order
to be usable, has to be indeterministic. If, however, it is meant to suggest
that it is the reversible, direct one-on-one relation between all the
characters of a plain text and its encryption that falls short of
state-of-the-art technology, I'd have no problem with that. That doesn't
mean, however, that an exercise is required to measure up to
state-of-the-art standards in order to be taken seriously. I do invent my
own solutions for simple problems. I find it more challenging than stalking
other people's solutions how ever superior and typically it also saves me
time. It is not my ambition to excel in any field, nor to flaunt my
erudition. It is my ambition to satisfy the requirements of a given task.
And this, I think, my solution does. I can be wrong and if so, I'd
appreciate being proven wrong. I have now received well-meaning advice for
which I am grateful. But I haven't been proven wrong. I claim that my
solution satisfies the requirements of the task at hand and challenge anyone
to prove the contrary. You can meet the challenge by deciphering the
following tiny message, knowing now the encryption method, which in practice
would not be known and, as it seems, would hardly be suspected by
deciphering experts for its amateurishness.

 Do yourself a favor and don't try to roll your own cryptographic
 functions. Do everyone else a favor and don't call something
 unbreakable unless you actually have the domain expertise to make that
 determination.

Here's the challenge. Prove this breakable

'\x10\x88d\x1d\xba\xa1\xdcK\x05w\x02/s\xa7Q0\xeb8\xb6Gx\xef\xcb\x1e=\xf5\x7f
\x9bI\xcb(\x87\xa5\x04\xc1soF\xfd\xc6\xc6\xd9|\x971\xdb\xcdT\tw#\x86a\xdc\x
b8P\xfb=n\xda\x80\x9f\x84m\x12\x98\x98\xca=o\x0b\x8e\x08O\xb7\x0b\x04SC\x96\
xc7\xab*\x0b\x996\x06\x86\x83(\x8dQ\x9eG\x8f$\xb2x)\xa9fv\x0c1B\x9b\r\xde\xf
fc\x08'

When you give up we may try a plain-text attack. Okay?

 And do read _Practical Cryptography_.

I certainly will.

 --
 Robert Kern
 [EMAIL PROTECTED]

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

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

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


Re: Encryption with Python?

2005-05-07 Thread Jim
What machine did you say that was, again?

Jim

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


Re: Q: The `print' statement over Unicode

2005-05-07 Thread François Pinard
[Thomas Heller]
 François Pinard [EMAIL PROTECTED] writes:

  [...] given file `question.py' with this contents:

 # -*- coding: UTF-8 -*-
 texte = unicode(Fran\xe7ois, 'latin1')
 print type(texte), repr(texte), texte
 print type(texte), repr(texte), str(texte)

  doing `python question.py' yields:

 type 'unicode' u'Fran\xe7ois' François
 type 'unicode' u'Fran\xe7ois'
 Traceback (most recent call last):
   File question.py, line 4, in ?
 print type(texte), repr(texte), str(texte)
 UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' \
in position 4: ordinal not in range(128)

  [...] why is the first `print' working over its third argument, but
  not the second?  How does `print' convert that Unicode string to a
  8-bit string for output, if not through `str()'?  What is missing to
  the documentation, or to my way of understanding it?

 AFAIK, print uses sys.stdout.encoding to encode the unicode string.

Much thanks for this information.

I was not aware of this file attribute.  Looking around, I found a
quick description in the Library Reference, under 2.3.8 File Objects.
However, I did not find in the documentation the rules stating how
or when this attribute receives a value, and in particular here, for
the case of `sys.stdout'.  The Reference Manual, under 6.6 The print
statement, is silent about how Unicode strings are handled.

Am I looking in the wrong places, or else, should not the standard
documentation more handily explain such things?

-- 
François Pinard   http://pinard.progiciels-bpi.ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Need help subclassing Borg

2005-05-07 Thread Steven D'Aprano
I've been working with the Borg design pattern from here:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531

and I'm having problems subclassing it.

I'm a newbie, so I've probably missed something obvious.

I want two Borg-like classes where all instances share state within each
class, but not between them. This is what I tried:

py class Borg:
py _shared_state = {}
py def __init__(self):
py self.__dict__ = self._shared_state
py 
py class Duck(Borg):
py def __init__(self):
py Borg.__init__(self)
py self.covering = feathers # all ducks are feathered
py
py class Rabbit(Borg):
py def __init__(self):
py Borg.__init__(self)
py self.covering = fur # all rabbits are furry
py
py bugs = Bunny(); daffy = Duck()
py daffy.covering
'feathers'
py bugs.covering
'feathers'

Not what I wanted or expected. What I wanted was for the subclasses Rabbit
and Duck to each inherit Borg-like behaviour, but not to share state with
any other Borgs. In other words, all Ducks share state, and all Rabbits
share state, but Ducks and Rabbits do not share state with each other.

I now see why Ducks and Rabbits are sharing state: they both share the
same __dict__ as all Borg instances. But I don't see how to get the
behaviour I want. (Except by cutting and pasting the Borg code into each
one.) Can anyone help?

Thanks,



Steven.






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


Re: Encryption with Python?

2005-05-07 Thread Sergei Organov
Anthra Norell [EMAIL PROTECTED] writes:

 Thanks a lot for the feedback. This is certainly a great learning
 experience. It's a fascinating topic too. Without wishing to annoy, I'd be
 interested in knowing more. I insert questions below.

There is a lot of information about the issues on the net. Before asking
questions, isn't it better to make some research? For example, your last
question is perfectly answered here:

http://www.faqs.org/faqs/cryptography-faq/part02/


2.3. How do I present a new encryption scheme in sci.crypt?

  ``I just came up with this neat method of encryption. Here's some
  ciphertext: FHDSIJOYW^[EMAIL PROTECTED] Is it strong?'' Without a
  doubt questions like this are the most annoying traffic on sci.crypt.
  ...


I'd suggest you to start your education here before you invent yet
another simple solutions for a complex problem:

http://www.faqs.org/faqs/cryptography-faq/part01/

HTH.

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


RE: Array programming

2005-05-07 Thread Vijay Chandra Sekhar Parepalli
Thank you, Sakesun. 


-Original Message-
From: Sakesun Roykiattisak
[mailto:[EMAIL PROTECTED] 
Sent: Saturday, May 07, 2005 12:17 PM
To: V.C.Sekhar
Cc: python-list@python.org
Subject: Re: Array programming

V.C.Sekhar wrote:

Hi there,
   I couldnt get to do the following task using
Python. Can some pls 
suggest me a way to do this.

I have an array with duplicate strings filled in it.
Now am looking for 
a way to extract only the DISTINCT Values from that
array.

Could some one pls help me out.

Thanks in advance,
Sekhar


  


try use set or frozenset, if you use python2.4
or try sets.Set or sets.ImmutableSet, if you use
python2.3

  import sets
  s = sets.Set([1,1,2,3,2,4])
  for x in s: print x
1
2
3
4





__ 
Do you Yahoo!? 
Yahoo! Mail - Find what you need with new enhanced search. 
http://info.mail.yahoo.com/mail_250
-- 
http://mail.python.org/mailman/listinfo/python-list


Outlook-Python Issue

2005-05-07 Thread Vijay Chandra Sekhar Parepalli








Hi there,


Can any one please help in getting me Python-Outlook programming issue
clarified.



I just wanted to do the following using Python:

1)Open a New Oulook Mail Window

2) Fill the field: to-email address and Write some
body to it.(I DONt want to send it automatically)



Thats all. But, I am getting an error when I try to
initiate the MAPI-Session using 

 object = win32com.client.Dispatch(Outlook.Application)

 ns =
object.GetNamespace(MAPI)

 mapi =
win32com.client.dynamic.Dispatch(MAPI.session)



Error I see is :

 File C:\Program Files\GNU\WinCvs
2.0\Macros\TemplateCvsMacro.py, line 140, in SendMAPIMail


mapi = win32com.client.Dispatch(MAPI.session)

 File
C:\Python24\Lib\site-packages\win32com\client\__init__.py, line 95,
in Dispatch


dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)

 File
C:\Python24\Lib\site-packages\win32com\client\dynamic.py, line 91,
in _GetGoodDispatchAndUserName


return (_GetGoodDispatch(IDispatch, clsctx), userName)

 File
C:\Python24\Lib\site-packages\win32com\client\dynamic.py, line 79,
in _GetGoodDispatch


IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx,
pythoncom.IID_IDispatch)

pywintypes.com_error:
(-2147221005, 'Invalid class string', None, None)



Can any one please help me in this regard.



Thanks,

Sekhar








__Do You Yahoo!?Tired of spam?  Yahoo! Mail has the best spam protection around http://mail.yahoo.com -- 
http://mail.python.org/mailman/listinfo/python-list

Re: Encryption with Python?

2005-05-07 Thread Robert Kern
Anthra Norell wrote:
 Thanks a lot for the feedback. This is certainly a great learning
 experience. It's a fascinating topic too. Without wishing to annoy, I'd be
 interested in knowing more. I insert questions below.
 
 - Original Message -
 From: Robert Kern [EMAIL PROTECTED]
 To: python-list@python.org
 Sent: Saturday, May 07, 2005 11:11 AM
 Subject: Re: Encryption with Python?
 
 
 
Anthra Norell wrote:

I rolled my own for relatively short sequences, like passwords. The key
 
 is
 
an integer. To decrypt use the negative encryption key. I consider the
encryption unbreakable, as it is indistinguishable from a random
 
 sequence.
 
Frederic

###

def crypt (sequence, key):
   import random
   sign = (key  0) * 2 - 1
   random.seed (abs (key * sign))
   s = ''
   for i in xrange (len (sequence)):
  r = random.randint (0, 255)
  s += chr ((ord (sequence [i]) + r * sign) % 256)
   return s

The mind boggles.

You do realize that if I have two ciphertexts encrypted with the same
key, I can subtract them? Then I have a sequence, that while not
immediately readable, is just a straightforward combination of the two
plaintexts without any encryption.
 
 How do you know the same key was used?

I don't necessarily, but if the same key *is* used, I'll know. The 
differences of the ciphertexts will have distinctly non-random 
characteristics (well, assuming the plaintexts aren't one-time pads 
themselves).

 What if the messages aren't the same length?

Then I just look at the common portion.

 How does one reconstruct either or both of two messages from their
 difference?

Analyzing patterns, frequencies, and also using prior knowledge I may 
know or guess about the contents. This is only slightly worse (for the 
attacker) than tackling a straight substitution cipher.

This function is also vulnerable to a chosen-plaintext attack. The
underlying PRNG is definitely not suitable for cryptographic
applications. The documentation even says so!
 
 What is a plain-text attack?

Chosen-plaintext, please.

 Is it you give me a plain text. I encrypt it
 using the same keys and hand you the result?

More or less.

 Would I comply with the
 request?

Depending on how your cryptosystem is deployed, you may not have a 
choice. A cryptosystem ought to be resistent to chosen-plaintext attacks 
regardless of how you intend to deploy it.

http://docs.python.org/lib/module-random.html
However, being completely deterministic, it is not suitable for all
purposes, and is completely unsuitable for cryptographic purposes.
 
 The logic escapes me if it is understood to mean that cryptography, in order
 to be usable, has to be indeterministic.

The two characteristics completely deterministic and unsuitable for 
cryptographic purposes are only mildly related. One *definitely* 
wouldn't use any PRNG to generate keying material. You should rely on 
physical sources of randomness. Most modern OSes have some way to access 
reliable entropy from your machine. Unices usually have this as 
/dev/random. But that's a separate issue.

Additionally, one should not use the Mersenne Twister PRNG, which is 
what Python uses, as the PRNG for the stream cipher. Given a particular 
value or series of values, it is possible to determine one's position in 
the PRNG sequence and can, in essence derive the key. Some techniques 
can be used to hide actual current state of the PRNG like applying a 
cryptographic hash to the value from the PRNG. However, it's easier and 
far better to just use a cryptographically strong PRNG from the start.

 If, however, it is meant to suggest
 that it is the reversible, direct one-on-one relation between all the
 characters of a plain text and its encryption that falls short of
 state-of-the-art technology, I'd have no problem with that. That doesn't
 mean, however, that an exercise is required to measure up to
 state-of-the-art standards in order to be taken seriously. I do invent my
 own solutions for simple problems.

This is not a simple problem.

But fortunately, there *is* a relatively simple answer. Besides Paul 
Rubin's p3.py (which to my limited ability to determine is probably 
best-of-breed for the limits imposed upon it), there is a very 
simply-coded stream cipher that *is* cryptographically strong if the 
appropriate details are observed. It's called RC4 (or ARCFOUR). A 
reasonably good cryptosystem built around that cipher is called 
Ciphersaber-2.

http://ciphersaber.gurus.com/cryptanalysis.html

There are dozens of implementations floating around, but it's 
ridiculously easy to code up by yourself.

 I find it more challenging than stalking
 other people's solutions how ever superior and typically it also saves me
 time. It is not my ambition to excel in any field, nor to flaunt my
 erudition. It is my ambition to satisfy the requirements of a given task.
 And this, I think, my solution does. I can be wrong and if so, I'd
 appreciate being proven wrong. I have now received well-meaning advice 

Re: Ask for a tool to protect my .pyc file :)

2005-05-07 Thread Robert Kern
Lily Kakm wrote:
 when I distribute my software, I will give the users .pyc file (maybe I can 
 use py2exe, but I think there's no essential different), because I don't 
 like them to know my source code.
 
 But actually, through .pyc file is not so directly as .py file, but the user 
 can also easily guest the detail of the program. Because in the .pyc file, 
 the name of the variables are exist.
 
 I ask you for a tool. Maybe it can hide the name of the variables.

That's not going to provide you any security. Any competent attacker 
won't care what you name the variables.

If you want real security, don't distribute your code. Expose the 
critical parts as a web service (or similar) instead.

If you want pretend security, .pycs or py2exe executables are enough.

 For example:
 
 good_node = 100
 bad_node = 500 - good_node
 
 Using this tool, it can be like this :
 
 xx = 100
 xy = 500 - xx
 
 It has the same function, but it can not easily be seen by the users.

Reads just fine to me.

 Do you know where to download a tool like this.

You ask an open source software community for a free tool to keep your 
source proprietary? High expectations.

-- 
Robert Kern
[EMAIL PROTECTED]

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

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


Re: hard memory limits

2005-05-07 Thread Philippe C. Martin
Hi,

Why don't you catch the exception and print the trace ?

Regards,

Philippe



Maurice LING wrote:

 John Machin wrote:
 On Sat, 07 May 2005 02:29:48 GMT, [EMAIL PROTECTED] (Bengt Richter) wrote:
 
 
On Sat, 07 May 2005 11:08:31 +1000, Maurice LING [EMAIL PROTECTED]
wrote:

It doesn't seems to help. I'm thinking that it might be a SOAPpy
problem. The allocation fails when I grab a list of more than 150k
elements through SOAP but allocating a 1 million element list is fine in
python.

Now I have a performance problem...

Say I have 3 lists (20K elements, 1G elements, and 0 elements), call
them 'a', 'b', and 'c'. I want to filter all that is in 'b' but not in
'a' into 'c'...


a = range(1, 10, 5)
b = range(0, 100)
c = []
for i in b:

... if i not in a: c.append(i)
...

This takes forever to complete. Is there anyway to optimize this?


Checking whether something is in a list may average checking equality
with each element in half the list. Checking for membership in a set
should be much faster for any significant size set/list. I.e., just
changing to

 a = set(range(1, 10, 5))

should help. I assume those aren't examples of your real data ;-)
You must have a lot of memory if you are keeping 1G elements there and
copying a significant portion of them. Do you need to do this
file-to-file, keeping a in memory? Perhaps page-file thrashing is part of
the time problem?
 
 
 Since when was 100 == 1G??
 
 Maurice, is this mucking about with 1M or 1G lists in the same
 exercise as the vm_malloc fails when allocating a 20K-element list
 problem? Again, it might be a good idea if you gave us a little bit
 more detail. You haven't even posted the actual *PYTHON* error message
 and stack trace that you got from the original problem. In fact,
 there's a possible interpretation that the (system?) malloc merely
 prints the vm_malloc message and staggers on somehow ...
 
 Regards,
 John
 
 This is the exact error message:
 
 *** malloc: vm_allocate(size=9203712) failed (error code=3)
 *** malloc[489]: error: Can't allocate region
 
 Nothing else. No stack trace, NOTHING.
 
 maurice

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


Re: Q: The `print' statement over Unicode

2005-05-07 Thread Martin v. Löwis
François Pinard wrote:
 Am I looking in the wrong places, or else, should not the standard
 documentation more handily explain such things?

It should, but, alas, it doesn't. Contributions are welcome.

The algorithm to set sys.std{in,out}.encoding is in
sysmodule.c:_PySys_Init and pythonrun.c:Py_InitializeEx
and goes roughly as follows:

- On Windows, if isatty returns true, use GetConsoleCP and
  GetConsoleOutputCP.
- On Unix, if isatty returns true, langinfo.h is present,
  CODESET is defined, and nl_langinfo(CODESET) returns a
  non-empty string, use that.
- otherwise, .encoding will not be set.

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


Re: hard memory limits

2005-05-07 Thread Robert Kern
Philippe C. Martin wrote:
 Hi,
 
 Why don't you catch the exception and print the trace ?

I don't think a Python exception is ever raised. The error message 
quoted below comes from the system, not Python.

 Regards,
 
 Philippe
 
 Maurice LING wrote:

This is the exact error message:

*** malloc: vm_allocate(size=9203712) failed (error code=3)
*** malloc[489]: error: Can't allocate region

Nothing else. No stack trace, NOTHING.

-- 
Robert Kern
[EMAIL PROTECTED]

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

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


Re: New Python regex Doc (was: Python documentation moronicities)

2005-05-07 Thread Skip Montanaro

Xah I don't know what kind of system is used to generate the Python
Xah docs, but it is quite unpleasant to work with manually, as there
Xah are egregious errors and inconsistencies.

The main Python documentation is written in LaTeX.  I believe most, if not
all, HTML is generated by latex2html.  I suspect most of the HTML cruftiness
arises from latex2html.

Skip


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


Re: hard memory limits

2005-05-07 Thread John Roth
Maurice LING [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 Hi,

 I think I've hit a system limit in python when I try to construct a list 
 of 200,000 elements. My error is

 malloc: vm_allocate (size = 2400256) failed..

 Just wondering is this specific to my system or what? Will adding more RAM 
 helps in this case?

 Thanks and cheers
 Maurice

malloc (which is the memory manager Python uses when it
runs out of its own heap memory) is trying to get another
2.4 megabyte block of memory from the operating system
so it can expand the heap.

The operating system is refusing to fill the request. There are
a lot of reasons why this might happen, ranging from system
limits (too little swap space, too little real memory), to an
inability to find a 2.4 meg block in the user part of the
address space, etc.

I'd check swap space, and then balance redesigning the
application to not try to get large blocks of memory with
spending money on more hardware memory that might not
solve the problem.

John Roth




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


Re: Listening to changes in a C++ variable from python

2005-05-07 Thread lamthierry
Is there some python method which can do the polling you are talking
about? Or can you send me a link to some existing example?

 It is not possible to listen to something that is not emitting
change
 notifications. Your variable val isn't talking.

 Some languages let you listen to every variable, but that is because
 behind the scenes it is emitting every variable change as an event.

 In C++, in keeping with its general philosophy, it is not going to be
 possible to listen to an int. You must either poll it, or wrap that
int
 in something that *will* emit change messages in some fashion that
 satisfies you. Given the circumstance of updating a progress bar, I'd
poll
 it about every quarter to half second.

 The correct answer changes depending on what you are doing with the
info
 and the level of control you exert over the source C++.

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


Ask for a tools to protect my .pyc file :)

2005-05-07 Thread Lily Kakm
I am sorry, may be I have not explain my mind clearly.
But I just want a tool like this : It can change the variable name into 
meaningless ones.
I know it will not be safe enough, but I need one.
So I ask for help.
Thank you !!

Robert Kern wrote:
Lily Kakm wrote:
when I distribute my software, I will give the users .pyc file (maybe I 
can use py2exe, but I think there's no essential different), because I 
don't like them to know my source code.

But actually, through .pyc file is not so directly as .py file, but the 
user can also easily guest the detail of the program. Because in the .pyc 
file, the name of the variables are exist.

I ask you for a tool. Maybe it can hide the name of the variables.

That's not going to provide you any security. Any competent attacker
won't care what you name the variables.

If you want real security, don't distribute your code. Expose the
critical parts as a web service (or similar) instead.

If you want pretend security, .pycs or py2exe executables are enough.

For example:

good_node = 100
bad_node = 500 - good_node

Using this tool, it can be like this :

xx = 100
xy = 500 - xx

It has the same function, but it can not easily be seen by the users.

Reads just fine to me.

Do you know where to download a tool like this.

You ask an open source software community for a free tool to keep your
source proprietary? High expectations.

--
Robert Kern
rkern at ucsd.edu

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

_
Express yourself instantly with MSN Messenger! Download today it's FREE! 
http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/

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


Re: Ask for a tool to protect my .pyc file :)

2005-05-07 Thread Steven D'Aprano
On Sat, 07 May 2005 06:45:32 -0700, Robert Kern wrote:

 Lily Kakm wrote:
 when I distribute my software, I will give the users .pyc file (maybe I can 
 use py2exe, but I think there's no essential different), because I don't 
 like them to know my source code.
 
 But actually, through .pyc file is not so directly as .py file, but the user 
 can also easily guest the detail of the program. Because in the .pyc file, 
 the name of the variables are exist.
 
 I ask you for a tool. Maybe it can hide the name of the variables.
 
 That's not going to provide you any security. Any competent attacker 
 won't care what you name the variables.
 
 If you want real security, don't distribute your code. Expose the 
 critical parts as a web service (or similar) instead.
 
 If you want pretend security, .pycs or py2exe executables are enough.

Lily, I think the point that Robert is making is that you have to ask,
Why do I want to keep my code secret?

If the answer is My code is very bad and I don't want people to see it
because I am ashamed, then distributing .pyc files is good enough. Or
better, learn to write better code.

If the answer is, My code is worth a lot of money, and I don't want
people to copy it, then hiding variable names will not protect you. If
your code is worth enough money, then people will spend hundreds of hours
cracking whatever security you use. The more valuable your code, the more
time and effort they will spend.

And using variables like xxxy won't protect you from competent
programmers. As soon as they read the code and realise that xxxy is a
node, they will do a Search and Replace of xxxy to some_node and
have readable code again.

So why do you want to hide your code? Who do you expect to hide it from?

[snip]
 xx = 100
 xy = 500 - xx
 
 It has the same function, but it can not easily be seen by the users.
 
 Reads just fine to me.

In fairness Robert, would you really want to read 10,000 lines of code
like that? I know I wouldn't -- not even 100 lines. 

Obfuscated code like that is, well, obfuscated. That makes it the
opposite of well-written, easily maintained and understood code. This
isn't a impenetrable barrier to a motivated programmer, but it is hardly
easy to read.


 Do you know where to download a tool like this.
 
 You ask an open source software community for a free tool to keep your 
 source proprietary? High expectations.

Again, in fairness, source code obfuscation isn't wrong in and of itself.
For example, Lily might be a teacher running a course on
reverse-engineering, and wants some Python code that can't easily be
understood by just reading the source.

Well, it's possible *wink*

Lily, if you are still reading, I think it is very important that you
think about why you want to keep your source code secret. Then think about
the alternative: publish your code as Open Source software.

There are many companies these days who make money from Open Source
software, including IBM, Red Hat, Apple, Sun, all the way down to small
businesses like the one I work for. (Modesty prevents me mentioning the
name, but if you look at my email address you should be able to work it
out.)

If you aren't selling your software, but just want people to be able to
download it and use it, then think about the advantages of making the code
available. If you can't think what those advantages are, please ask, I'm
sure many people here will be more than happy to discuss it with you.

Finally, if you still decide that you want to keep your code secret, that
Open Source is not for you, then I suggest you do a Google search on
python obfuscater. If you don't find anything, then you can always write
your own.



Steven.




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


globbing multiple wildcards

2005-05-07 Thread utabintarbo
I have a path spec similar to '/home/*/.mozilla/*/*/cache*/*' (this
will probably look familiar to *nix users) with multiple wildcards. I
am finding it difficult gathering ALL file pathnames which match this
spec. Can anyone shed some light on this for a python noob?

TIA
Bob

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


Re: hard memory limits

2005-05-07 Thread Bengt Richter
On Sat, 07 May 2005 14:03:34 +1000, Maurice LING [EMAIL PROTECTED] wrote:

John Machin wrote:
 On Sat, 07 May 2005 02:29:48 GMT, [EMAIL PROTECTED] (Bengt Richter) wrote:
 
 
On Sat, 07 May 2005 11:08:31 +1000, Maurice LING [EMAIL PROTECTED] wrote:

It doesn't seems to help. I'm thinking that it might be a SOAPpy 
problem. The allocation fails when I grab a list of more than 150k 
elements through SOAP but allocating a 1 million element list is fine in 
python.

Now I have a performance problem...

Say I have 3 lists (20K elements, 1G elements, and 0 elements), call 
them 'a', 'b', and 'c'. I want to filter all that is in 'b' but not in 
'a' into 'c'...


a = range(1, 10, 5)
b = range(0, 100)
c = []
for i in b:

... if i not in a: c.append(i)
...

This takes forever to complete. Is there anyway to optimize this?


Checking whether something is in a list may average checking equality with
each element in half the list. Checking for membership in a set should
be much faster for any significant size set/list. I.e., just changing to

 a = set(range(1, 10, 5))

should help. I assume those aren't examples of your real data ;-)
You must have a lot of memory if you are keeping 1G elements there and
copying a significant portion of them. Do you need to do this file-to-file,
keeping a in memory? Perhaps page-file thrashing is part of the time problem?
 
 
 Since when was 100 == 1G??
 
 Maurice, is this mucking about with 1M or 1G lists in the same
 exercise as the vm_malloc fails when allocating a 20K-element list
 problem? Again, it might be a good idea if you gave us a little bit
 more detail. You haven't even posted the actual *PYTHON* error message
 and stack trace that you got from the original problem. In fact,
 there's a possible interpretation that the (system?) malloc merely
 prints the vm_malloc message and staggers on somehow ...
 
 Regards,
 John

This is the exact error message:

*** malloc: vm_allocate(size=9203712) failed (error code=3)
*** malloc[489]: error: Can't allocate region

Nothing else. No stack trace, NOTHING.

1. Can you post minimal exact code that produces the above exact error message?
2. Will you? ;-)

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


Re: globbing multiple wildcards

2005-05-07 Thread [EMAIL PROTECTED]
what about :
[EMAIL PROTECTED]:~$ python
Python 2.4.1 (#2, Mar 30 2005, 21:51:10)
[GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2
Type help, copyright, credits or license for more information.
 import glob
 print glob.glob('/home/*/.mozilla/*/*/Cache*/*')
['/home/martin/.mozilla/firefox/dem8d5eu.default/Cache/_CACHE_MAP_',
'/home/martin/.mozilla/firefox/dem8d5eu.default/Cache/_CACHE_001_',
.
'/home/martin/.mozilla/firefox/dem8d5eu.default/Cache/66FA72F2d01',
'/home/martin/.mozilla/firefox/dem8d5eu.default/Cache/85F82253d01',
'/home/martin/.mozilla/firefox/dem8d5eu.default/Cache/CE3B4D9Cd01']


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


get file modification time in mm/dd/yyyy format?

2005-05-07 Thread beliavsky
Using Python 2.4 on Windows, for me the command

print os.stat(temp.txt)[stat.ST_MTIME]

gives

1115478343 ,

which is seconds since the epoch. How can I get the modification time
in a format such as

05/07/2005  11:05 AM

as in Windows with the dir command? Ideal would be a tuple of 6 values,
(year,month,day,hour,minute,second). Thanks.

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


Re: Need help subclassing Borg

2005-05-07 Thread [EMAIL PROTECTED]
See mr Martellis comment of 2001/09/06 in mentiond recipe, you then get
something like this

-#!/usr/bin/env python
-class Borg(object):
-_shared_state = {}
-def __init__(self):
-self.__dict__ = self._shared_state
-
-class Duck(Borg):
-def __init__(self):
-super(Duck, self).__init__()
-self.__covering = feathers # all ducks are feathered
-def covering(self):
-return self.__covering
-
-class Rabbit(Borg):
-def __init__(self):
-super(Rabbit, self).__init__()
-self.__covering = fur # all rabbits are furry
-def covering(self):
-return self.__covering
-
-bugs = Rabbit()
-daffy = Duck()
-print daffy.covering()
-print bugs.covering()

[EMAIL PROTECTED]:~$ ./test2.py
feathers
fur
[EMAIL PROTECTED]:~$

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


Re: get file modification time in mm/dd/yyyy format?

2005-05-07 Thread Peter Hansen
[EMAIL PROTECTED] wrote:
 Using Python 2.4 on Windows, for me the command
 
 print os.stat(temp.txt)[stat.ST_MTIME]
 
 gives
 
 1115478343 ,
 
 which is seconds since the epoch. How can I get the modification time
 in a format such as
 
 05/07/2005  11:05 AM
 
 as in Windows with the dir command? Ideal would be a tuple of 6 values,
 (year,month,day,hour,minute,second). Thanks.

Do you want the time formatted as above, or as a tuple, since you seem 
unclear?

time.strftime('%m/%d/%Y  %H:%M %p', time.localtime(time.time()))

time.localtime(time.time())[:6] would do the latter...

Check the time module docs for more.

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


Re: get file modification time in mm/dd/yyyy format?

2005-05-07 Thread [EMAIL PROTECTED]
Tried this it on linux, should work under windows as well I think
[EMAIL PROTECTED]:~$ python
Python 2.4.1 (#2, Mar 30 2005, 21:51:10)
[GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2
Type help, copyright, credits or license for more information.
py import time
py t = time.localtime(1115478343)
py print t
(2005, 5, 7, 17, 5, 43, 5, 127, 1)
py print time.asctime(t)
Sat May  7 17:05:43 2005
py

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


Shell Commands in Python Code

2005-05-07 Thread Sara Khalatbari
There are a lot of commands that I need to use in my
code  I don't know how to do it

Is there a way to use shell commands in Python code?



__ 
Do you Yahoo!? 
Yahoo! Mail - Helps protect you from nasty viruses. 
http://promotions.yahoo.com/new_mail
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ask for a tools to protect my .pyc file :)

2005-05-07 Thread Philippe C. Martin
Is it stable ? I tried it a few months ago and it crashed on my code  I
do not code that badly ;-)

Regards,

Philippe



[EMAIL PROTECTED] wrote:

 pyobfuscate
 
 http://www.lysator.liu.se/~astrand/projects/pyobfuscate/

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


Re: globbing multiple wildcards

2005-05-07 Thread utabintarbo
OK, I guess it WAS that easy. :-P

Thanks for the replys.

Bob

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


Re: New Python regex Doc (was: Python documentation moronicities)

2005-05-07 Thread Philippe C. Martin
This is nice! I just might understand regex eventually.


Xah Lee wrote:

 erratum:
 
 the correct URL is:
 http://xahlee.org/perl-python/python_re-write/lib/module-re.html
 
  Xah
  [EMAIL PROTECTED]
  http://xahlee.org/

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

Re: Encryption with Python?

2005-05-07 Thread Philippe C. Martin
I use http://www.amk.ca/python/code/crypto.html

Regards,

Philippe



Blake T. Garretson wrote:

 I want to save some sensitive data (passwords, PIN numbers, etc.) to
 disk in a secure manner in one of my programs.  What is the
 easiest/best way to accomplish strong file encryption in Python?  Any
 modern block cipher will do: AES, Blowfish, etc.  I'm not looking for
 public key stuff; I just want to provide a pass-phrase.
 
 I found a few modules out there, but they seem to be all but abandoned.
  Most seem to have died several years ago.  The most promising package
 is A.M. Kuchling's Python Cryptography Toolkit
 (http://www.amk.ca/python/code/crypto.html).
 
 Is this the defacto Python encryption solution?  What does everyone
 else use?  Any other suggestions?  The SSLCrypto package
 (http://www.freenet.org.nz/python/SSLCrypto/) may be a good alternative
 too, but I am not sure if it is actively maintained.
 
 Thanks,
 Blake

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


Re: get file modification time in mm/dd/yyyy format?

2005-05-07 Thread F. Petitjean
Le 7 May 2005 08:23:48 -0700, [EMAIL PROTECTED] a écrit :
 Using Python 2.4 on Windows, for me the command
 
 print os.stat(temp.txt)[stat.ST_MTIME]
 
 gives
 
 1115478343 ,
 
 which is seconds since the epoch. How can I get the modification time
 in a format such as
 
 05/07/2005  11:05 AM
 
 as in Windows with the dir command? Ideal would be a tuple of 6 values,
 (year,month,day,hour,minute,second). Thanks.
 
I type
import time
dir(time)
lot of stuff
help(time.localtime)
localtime([seconds]) -
(tm_year,tm_mon,tm_day,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst)

Convert seconds since the Epoch to a time tuple expressing local time.
When 'seconds' is not passed in, convert the current time instead.

 time.localtime(1115478343)
(2005, 5, 7, 17, 5, 43, 5, 127, 1)
it seems to be  7 may 2005  17h 5 minutes 43 seconds

To have such a formatting you have to type help(time.strptime) which
sadly will say
See the library reference manual for formatting codes (same as strftime()).

--- 
there is no perfect world

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


path(file)

2005-05-07 Thread Sara Khalatbari
Suppose I have a list of files  I wanna know  their
path.
is there a command that helps me do so in python?



Yahoo! Mail
Stay connected, organized, and protected. Take the tour:
http://tour.mail.yahoo.com/mailtour.html

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


Re: globbing multiple wildcards

2005-05-07 Thread Leif K-Brooks
[EMAIL PROTECTED] wrote:
 I have a path spec similar to '/home/*/.mozilla/*/*/cache*/*' (this
 will probably look familiar to *nix users) with multiple wildcards. I
 am finding it difficult gathering ALL file pathnames which match this
 spec. Can anyone shed some light on this for a python noob?

import glob
glob.glob('/home/*/.mozilla/*/*/cache*/*')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ask for a tools to protect my .pyc file :)

2005-05-07 Thread utabintarbo
pyobfuscate

http://www.lysator.liu.se/~astrand/projects/pyobfuscate/

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


Re: Q: The `print' statement over Unicode

2005-05-07 Thread François Pinard
[Martin von Löwis]

 François Pinard wrote:

  Am I looking in the wrong places, or else, should not the standard
  documentation more handily explain such things?

 It should, but, alas, it doesn't. Contributions are welcome.

My contributions are not that welcome.  If they were, the core team
would not try forcing me into using robots and bug trackers! :-)

 The algorithm to set sys.std{in,out}.encoding is in
 sysmodule.c:_PySys_Init and pythonrun.c:Py_InitializeEx
 and goes roughly as follows:

 - On Windows, if isatty returns true, use GetConsoleCP and
   GetConsoleOutputCP.
 - On Unix, if isatty returns true, langinfo.h is present,
   CODESET is defined, and nl_langinfo(CODESET) returns a
   non-empty string, use that.
 - otherwise, .encoding will not be set.

Thanks.  Your kind explanation, above, should make it, as is, somewhere
in the documentation -- until Xah decides to rewrite it, of course! :-).

-- 
François Pinard   http://pinard.progiciels-bpi.ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Shell Commands in Python Code

2005-05-07 Thread [EMAIL PROTECTED]
start to take a look at the call function of the subprocess module -
see http://docs.python.org/lib/node231.html

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


Re: path(file)

2005-05-07 Thread [EMAIL PROTECTED]
What about start reading http://docs.python.org/lib/module-os.path.html?

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


Re: python and glut

2005-05-07 Thread max(01)*
Lonnie Princehouse wrote:

 DRI not working could also be a permissions issue; check to see if it
 works as root.

that's it! :-)

now, how can i make it work as joe user?

bye

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


Re: Need help subclassing Borg

2005-05-07 Thread Steven D'Aprano
On Sat, 07 May 2005 08:35:21 -0700, [EMAIL PROTECTED] wrote:

 See mr Martellis comment of 2001/09/06 in mentiond recipe, you then get
 something like this
 
 -#!/usr/bin/env python
 -class Borg(object):
 -_shared_state = {}
 -def __init__(self):
 -self.__dict__ = self._shared_state
 -
 -class Duck(Borg):
 -def __init__(self):
 -super(Duck, self).__init__()
 -self.__covering = feathers # all ducks are feathered

What version of Python are you using? I'm using 2.3.3 and I get this:

py donald = Duck()
Traceback (most recent call last):
  File stdin, line 1, in ?
  File stdin, line 3, in __init__
TypeError: super() argument 1 must be type, not classobj



-self.__covering = feathers # all ducks are feathered
-def covering(self):
-return self.__covering
-
-class Rabbit(Borg):
-def __init__(self):
-super(Rabbit, self).__init__()
-self.__covering = fur # all rabbits are furry
 -def covering(self):
 -return self.__covering

Hmmm... I hate to be ungrateful, but apart from being inelegant, it means
having to write get_attribute() and set_attribute() methods for every
attribute the caller might conceivably use. I'm sure to miss at least one.
*wink*

Either that or muck around with __getattr__ and __setattr__, which is
getting uglier by the minute.

I'm thinking what I might need is a function that generates a Borg-like
class. So I would do something like:

Rabbit = MakeBorgClass()
# Rabbit is now a class implementing shared state
# all instances of Rabbit share the same state
Duck = MakeBorgClass()
# Duck is now a class implementing shared state
# all instances of Duck share the same state
# but instances of Duck do not share state with instances of Rabbit

Problem is, I haven't got the foggiest idea how to implement something
like that. Am I on the right track? Where do I go from here?



Thanks,


Steven.











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


Re: Reg strip_tags function in Python.

2005-05-07 Thread Dave Benjamin
praba kar wrote:
 In Php I can use strip_tags() function to strip out
 all html tags. I want to know that strip_tags()
 equivalent function in Python.

Here's a simple function based on Python's HTMLParser class. If you need 
to reject only certain tags, you'll probably want to subclass 
HTMLParser, but for simply stripping all tags, this works:

from HTMLParser import HTMLParser
def strip_tags(html):
 result = []
 parser = HTMLParser()
 parser.handle_data = result.append
 parser.feed(html)
 parser.close()
 return ''.join(result)

See the docs for more details on HTMLParser:
http://docs.python.org/lib/module-HTMLParser.html

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


Re: Need help subclassing Borg

2005-05-07 Thread Bengt Richter
On Sat, 07 May 2005 22:28:34 +1000, Steven D'Aprano [EMAIL PROTECTED] wrote:

I've been working with the Borg design pattern from here:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531

and I'm having problems subclassing it.

I'm a newbie, so I've probably missed something obvious.

I want two Borg-like classes where all instances share state within each
class, but not between them. This is what I tried:

py class Borg:
py _shared_state = {}
py def __init__(self):
py self.__dict__ = self._shared_state
py 
py class Duck(Borg):
py def __init__(self):
py Borg.__init__(self)
py self.covering = feathers # all ducks are feathered
py
py class Rabbit(Borg):
py def __init__(self):
py Borg.__init__(self)
py self.covering = fur # all rabbits are furry
py
py bugs = Bunny(); daffy = Duck()
py daffy.covering
'feathers'
py bugs.covering
'feathers'

Not what I wanted or expected. What I wanted was for the subclasses Rabbit
and Duck to each inherit Borg-like behaviour, but not to share state with
any other Borgs. In other words, all Ducks share state, and all Rabbits
share state, but Ducks and Rabbits do not share state with each other.

I now see why Ducks and Rabbits are sharing state: they both share the
same __dict__ as all Borg instances. But I don't see how to get the
behaviour I want. (Except by cutting and pasting the Borg code into each
one.) Can anyone help?


If you are using old-style classes (which you need for this Borg), then you 
could
keep different shared state dicts within a _shared_states dict, e.g. based on
the name of the subclassed classes, e.g.,

  class Borg:
 ... _shared_states = {} #note plural
 ... def __init__(self):
 ... self.__dict__ = 
self._shared_states.setdefault(self.__class__.__name__, {})
 ...
  class Duck(Borg):
 ... def __init__(self):
 ... Borg.__init__(self)
 ... self.covering = feathers # all ducks are feathered
 ...
  class Rabbit(Borg):
 ... def __init__(self):
 ... Borg.__init__(self)
 ... self.covering = fur # all rabbits are furry
 ...
  bugs = Bunny(); daffy = Duck()
 Traceback (most recent call last):
   File stdin, line 1, in ?
 NameError: name 'Bunny' is not defined

Hm, where'd that Bunny come from?

  bugs = Rabbit(); daffy = Duck()
  daffy.covering
 'feathers'
  bugs.covering
 'fur'
  vars(Borg)
 {'__module__': '__main__', '__doc__': None, '__init__': function __init__ at 
0x02EE8D14, '_sha
 red_states': {'Rabbit': {'covering': 'fur'}, 'Duck': {'covering': 'feathers'}}}
  donald = Duck()
  donald.covering
 'feathers'
  roger = Rabbit()
  roger.covering
 'fur'
  Borg._shared_states['Duck']
 {'covering': 'feathers'}
  Borg._shared_states['Rabbit']
 {'covering': 'fur'}

Since you are calling Borg.__init__(self), you could specify some other
classifier than the implicit class name, e.g., Borg.__init__(self, 'feathered')
vs Borg.__init__(self, 'furred') and use that as the key in the setdefault call.

As mentioned in the recipe discussion, new style classes differ somewhat, but 
you
can accomplish the same functionality, just that if you have special things like
__slots__ or descriptors, you may have to think about how they might interact 
with
your shared state access.

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


Re: Q: The `print' statement over Unicode

2005-05-07 Thread Martin v. Löwis
François Pinard wrote:
 My contributions are not that welcome.  If they were, the core team
 would not try forcing me into using robots and bug trackers! :-)

Ok, then we need to wait for somebody else to contribute a documentation
patch.

 Thanks.  Your kind explanation, above, should make it, as is, somewhere
 in the documentation

But how will that happen? Unless somebody contributes a documentation
patch, the documentation will not change magically!

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


Re: Shell Commands in Python Code

2005-05-07 Thread Paul Watson
Sara Khalatbari [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 There are a lot of commands that I need to use in my
 code  I don't know how to do it

 Is there a way to use shell commands in Python code?

Yes, there are many popen() forms that you may wish to investigate.  Below 
is a brief clip.  However, if you can find the functionality already built 
into Python, such as globbing filenames, that would be better.  It will be 
more portable to more systems and probably faster.

x = os.popen(ls -al)
for aline in x.readlines():
print aline,


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


Newbie: saving dialog variables

2005-05-07 Thread jeff elkins
Howdy,

I've written a program that calls an imported dialog to gather some needed 
input. What's the common method for passing that data back to the caller? I've 
tried a 'return data' prior to self.Close() ... all that happens then is the 
dialog won't close. I'm sure this is obvious, but this newbie's stuck!

Thanks,

Jeff

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


Re: Shell Commands in Python Code

2005-05-07 Thread F. Petitjean
Le Sat, 7 May 2005 08:55:35 -0700 (PDT), Sara Khalatbari a écrit :
 There are a lot of commands that I need to use in my
 code  I don't know how to do it
 
 Is there a way to use shell commands in Python code?
Python is a scrpting language. So you can substitute most shell scripts
idioms with pythonic ones. A large number of shell scripts can be
replaced with python scripts without any semantic loss.

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


win32- system call - getting results back into python

2005-05-07 Thread [EMAIL PROTECTED]
Hey everyone,

I'm trying to call a system command svnlook log \arms from within
python and process the results.  However I'm having trouble getting the
results of the command back into python.  I'm using windows if that
matters.

Here's what I have so far:

os.system(svnlook) #works but doesn't give me the output from
svnlook, just the status

commands.gettegetstatusoutput(svnlook) only works in unix?

Here's my final code which really should work:

pipe=os.popen(svnlook log \arms)  #works from console
text=pipe.read()
print text

 I get blank

However this works fine and gives me many lines of output:
pipe=os.popen(dir)
text=pipe.read()
print text

Any idea what I'm doing wrong?  When I call my command from the command
prompt in windows I get a line of text.  By the way, I tried posting
this on the subversion group but I'm thinking maybe it's a python
question, or both?

Thanks,

Greg

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


Re: Newbie: saving dialog variables

2005-05-07 Thread jeff elkins
On Saturday 07 May 2005 01:24 pm, jeff elkins wrote:
 Howdy,

 I've written a program that calls an imported dialog to gather some needed
 input. What's the common method for passing that data back to the caller?
 I've tried a 'return data' prior to self.Close() ... all that happens then
 is the dialog won't close. I'm sure this is obvious, but this newbie's
 stuck!

 Thanks,

 Jeff

If it makes any difference, the data is contained in an array...

Thanks again,

Jeff

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


Re: Encryption with Python?

2005-05-07 Thread Philippe C. Martin
PS: remmember that single DES has been brocken. If you're also interested in
signature, this is an interesting article (a big upsate if true)
http://it.slashdot.org/article.pl?sid=05/02/16/0146218tid=93

Regards,

Philippe
 

Philippe C. Martin wrote:

 I use http://www.amk.ca/python/code/crypto.html
 
 Regards,
 
 Philippe
 
 
 
 Blake T. Garretson wrote:
 
 I want to save some sensitive data (passwords, PIN numbers, etc.) to
 disk in a secure manner in one of my programs.  What is the
 easiest/best way to accomplish strong file encryption in Python?  Any
 modern block cipher will do: AES, Blowfish, etc.  I'm not looking for
 public key stuff; I just want to provide a pass-phrase.
 
 I found a few modules out there, but they seem to be all but abandoned.
  Most seem to have died several years ago.  The most promising package
 is A.M. Kuchling's Python Cryptography Toolkit
 (http://www.amk.ca/python/code/crypto.html).
 
 Is this the defacto Python encryption solution?  What does everyone
 else use?  Any other suggestions?  The SSLCrypto package
 (http://www.freenet.org.nz/python/SSLCrypto/) may be a good alternative
 too, but I am not sure if it is actively maintained.
 
 Thanks,
 Blake

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


Re: win32- system call - getting results back into python

2005-05-07 Thread runes
You wil have to use rsvnlook log \arms) or svnlook log \\arms) to
escape the \.

Popen usually return a file-like object, so you maye to use file
methods like .read()

ex:
d = os.popen('dir /b')
print d.read()

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


Re: Listening to changes in a C++ variable from python

2005-05-07 Thread Jeremy Bowers
On Sat, 07 May 2005 07:16:58 -0700, lamthierry wrote:

 Is there some python method which can do the polling you are talking
 about? Or can you send me a link to some existing example?

Take a moment to go back to the basics. C++ is, in general, a simple
system. The *language* is complicated at times, but it does actually
strive for no unknown magic taking place. When you say int i = 4, there
is some literal value in memory somewhere taking the value of 4. If you
say i = 5, that value in memory now says five.

The reason you can't listen to this is quite literally because you RAM
does not have that ability (for good reason); there are no circuits that
are triggered when a value is changed. (I'm talking conventional RAM here,
with no hardware mapping or anything else special.)

Polling here simply means checking periodically. You don't need any
special functions or libraries, you just need to check periodically. Your
GUI system should have a system for creating timeouts, but without telling
me what that is, I can't give the code. (*I* may not be able to even so; I
have not used them all extensively enough to know about all the
schedulers.) Your timeout function should simply check the new value and
do the appropriate thing based on the new value.

So, there isn't really a method, it's just combining your GUI scheduler
with a simple == or  or  or whatever else is appropriate in your case. 

If it takes more than about four or five lines to write the basic poller,
you're probably on the wrong track. (Correctly handling what the poller
sees may be more complicated, but the periodic checking should be simple.)

If you need more help (though I strongly suggest that you try to get the
scheduler to do something two seconds from now or something, and after
that it *should* be obvious what to do next), you'll need to include what
GUI toolkit you are using, and possibly the current Python code that you
are using to access the value you'd like the GUI to track. You may also
want to explain how you are connecting the apps; is the C++ part and the
Python part in one app in different threads, or are you using some other
communication form?

One warning: You might be tempted to use time.sleep(); don't do that. That
works OK in a Python program where only your code is running, but in any
GUI program the GUI itself is also running. Using time.sleep() will
completely stop *everything* during the duration of the sleep, completely
freezing the GUI as if it were locked up; that's why all GUIs have
schedulers, so they can keep running while your code waits.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need help subclassing Borg

2005-05-07 Thread Jeremy Bowers
On Sun, 08 May 2005 02:42:09 +1000, Steven D'Aprano wrote:
 I'm thinking what I might need is a function that generates a Borg-like
 class. So I would do something like:
 
 Rabbit = MakeBorgClass()
 # Rabbit is now a class implementing shared state
 # all instances of Rabbit share the same state
 Duck = MakeBorgClass()
 # Duck is now a class implementing shared state
 # all instances of Duck share the same state
 # but instances of Duck do not share state with instances of Rabbit
 
 Problem is, I haven't got the foggiest idea how to implement something
 like that. Am I on the right track? Where do I go from here?

Bengt's answer is better than this track, but this question is worth
answering because it is so wonderfully easy in Python.

Remember class is an executable statement, not a declaration:

Python 2.3.5 (#1, Mar  3 2005, 17:32:12) 
[GCC 3.4.3  (Gentoo Linux 3.4.3, ssp-3.4.3-0, pie-8.7.6.6)] on linux2
Type help, copyright, credits or license for more information.
 def makeBorg():
... class Borg(object):
... _shared_state = {}
... def __init__(self):
... self.__dict__ = self._shared_state
... return Borg
... 
 Duck = makeBorg()
 Rabbit = makeBorg()
 d = Duck()
 d2 = Duck()
 d.cover = fur
 d2.cover
'fur'
 r = Rabbit()
 r.cover
Traceback (most recent call last):
  File stdin, line 1, in ?
AttributeError: 'Borg' object has no attribute 'cover'
 r.cover = feathers
 d.cover
'fur'
 r2 = Rabbit()
 r2.cover
'feathers'
 

(I flipped around the fur and feathers, but don't feel like fixing it :-) )

Now, the problem with this and the reason why Bengt's is more likely
better is that each of these Borg classes is unrelated, so there's no
using issubclass or anything like that. You *could* hack around this, but
it's not worth it. (It is possible to dynamically choose the bases of a
class; you can't do it in the class statement itself, but you can do
something like:

def makeBorg(base = object):
class Borg(base): 
etc.

but this is definitely not the best way to go. Still, as above, it does
have its place other times; I've used it to dynamically pick up whether
the user has certain modules installed and add support depending on the
environment. I often do this when I'm writing something currently embedded
in an app I'm writing, but may have use elsewhere outside of the
environment of the app, allowing me to write code that both takes full
advantage of the app environment, while not being completely tied to it.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: saving dialog variables

2005-05-07 Thread Jeremy Bowers
On Sat, 07 May 2005 13:24:34 +, jeff elkins wrote:

 Howdy,
 
 I've written a program that calls an imported dialog to gather some needed 
 input. What's the common method for passing that data back to the caller? 
 I've 
 tried a 'return data' prior to self.Close() ... all that happens then is the 
 dialog won't close. I'm sure this is obvious, but this newbie's stuck!
 
 Thanks,
 
 Jeff

In general, the dialog is an instance of a class. Once the dialog closes,
the window should be gone but the instance variable should still be around. 
Common practice is to put the relevant data in the dialog instance member
for retrieval after closing. In certain cases, the method used to invoke
the dialog will return the relevant value, but this is somewhat limiting.
In even more rare cases, the dialog will be popped up by a function,
giving no direct reference to the dialog at any point, and the value is
returned by the function; this is generally limited to the Yes/No/Cancel
style dialog or its simpler bretheren (OK/Cancel and OK).

I'm assuming that last one is not the case.

To be more directly helpful, we'd need more data, ideally a code snippet
fully demonstrating the problem (i.e., a runnable program). But at a bare
minimum, we'd need to know where this dialog came from. Tk? PyGTK?
wxPython? Some curses library? MFC?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python and glut

2005-05-07 Thread max(01)*
Lonnie Princehouse wrote:
 Welcome to the exciting world of trying to make graphics work on Linux
 =)
 
 DRI is direct rendering.
[...]
 DRI not working could also be a permissions issue; check to see if it
 works as root.

that's it! :-)

now, how can i make it work as joe user?

bye

max

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


Re: Q: The `print' statement over Unicode

2005-05-07 Thread Jeremy Bowers
On Sat, 07 May 2005 12:10:46 -0400, Franois Pinard wrote:

 [Martin von Lwis]
 
 Franois Pinard wrote:

  Am I looking in the wrong places, or else, should not the standard
  documentation more handily explain such things?
 
 It should, but, alas, it doesn't. Contributions are welcome.
 
 My contributions are not that welcome.  If they were, the core team
 would not try forcing me into using robots and bug trackers! :-)

I'm not sure that the smiley completely de-fangs this comment.

Have you every tried managing a project even a tenth the size of Python
*without* those tools? If you had any idea of the kind of continuous,
day-in, day-out *useless busywork* you were asking of the developers,
merely to save you a minute or two on the one occasion you have something
to contribute, you'd apologize for the incredibly unreasonable demand you
are making from people giving you an amazing amount of free stuff. (You'd
get a lot less of it, too; administration isn't coding, and excessive
administration makes the coding even less fun and thus less likely to be
done.) An apology would not be out of line, smiley or no.

I've never administered anything the size of Python. I have, however, been
up close and personal with a project that had about five developers
full-time, and administering *that* without bug trackers would have been a
nightmare. I can't even imagine trying to run Python by hand at least
not that and getting useful work done too.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Need help subclassing Borg

2005-05-07 Thread Bengt Richter
On Sun, 08 May 2005 02:42:09 +1000, Steven D'Aprano [EMAIL PROTECTED] wrote:

On Sat, 07 May 2005 08:35:21 -0700, [EMAIL PROTECTED] wrote:

 See mr Martellis comment of 2001/09/06 in mentiond recipe, you then get
 something like this
 
 -#!/usr/bin/env python
 -class Borg(object):
 -_shared_state = {}
 -def __init__(self):
 -self.__dict__ = self._shared_state
 -
 -class Duck(Borg):
 -def __init__(self):
 -super(Duck, self).__init__()
 -self.__covering = feathers # all ducks are feathered

What version of Python are you using? I'm using 2.3.3 and I get this:

py donald = Duck()
Traceback (most recent call last):
  File stdin, line 1, in ?
  File stdin, line 3, in __init__
TypeError: super() argument 1 must be type, not classobj



-self.__covering = feathers # all ducks are feathered
-def covering(self):
-return self.__covering
-
-class Rabbit(Borg):
-def __init__(self):
-super(Rabbit, self).__init__()
-self.__covering = fur # all rabbits are furry
 -def covering(self):
 -return self.__covering

Hmmm... I hate to be ungrateful, but apart from being inelegant, it means
having to write get_attribute() and set_attribute() methods for every
attribute the caller might conceivably use. I'm sure to miss at least one.
*wink*

Either that or muck around with __getattr__ and __setattr__, which is
getting uglier by the minute.

I'm thinking what I might need is a function that generates a Borg-like
class. So I would do something like:

Rabbit = MakeBorgClass()
# Rabbit is now a class implementing shared state
# all instances of Rabbit share the same state
Duck = MakeBorgClass()
# Duck is now a class implementing shared state
# all instances of Duck share the same state
# but instances of Duck do not share state with instances of Rabbit

Problem is, I haven't got the foggiest idea how to implement something
like that. Am I on the right track? Where do I go from here?

On to new-style classes perhaps? You could have a base class that automatically
gives a subclass its own _shared_state if it isn't there, and tacks that onto
the new instance. That way you don't have to do it in your subclass inits. E.g.,
(warning, not tested beyond what you see. Just thought of this ;-)

  class Borgomat(object):
 ... def __new__(cls, *args, **kw):
 ... if '_shared_state' not in cls.__dict__:
 ... cls._shared_state = {}
 ... obj = object.__new__(cls)
 ... obj.__dict__ = cls._shared_state
 ... return obj
 ...
  class Duck(Borgomat):
 ... def __init__(self, **kw):
 ... self.covering = 'feathers'
 ... self.__dict__.update(kw)
 ...
  daffy = Duck()
  daffy.covering
 'feathers'
  Duck._shared_state
 {'covering': 'feathers'}
  class Rabbit(Borgomat):
 ... def __init__(self):
 ... self.covering = 'fur'
 ...
  bugs = Rabbit()
  bugs.covering
 'fur'
  Rabbit._shared_state
 {'covering': 'fur'}
  bugs.food = 'carrots'
  Rabbit._shared_state
 {'food': 'carrots', 'covering': 'fur'}
  roger = Rabbit()
  roger.food
 'carrots'

Oops, forgot to use the optional keyword arg in Duck ...

  donald = Duck(food='Disney duck chow')
  donald.food
 'Disney duck chow'
  donald.covering
 'feathers'
  daffy.food
 'Disney duck chow'

Some shared state may not be all that appropriate ;-)

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


Re: Newbie: saving dialog variables

2005-05-07 Thread jeff elkins
On Saturday 07 May 2005 02:34 pm, Jeremy Bowers wrote:
 On Sat, 07 May 2005 13:24:34 +, jeff elkins wrote:
  Howdy,
 
  I've written a program that calls an imported dialog to gather some
  needed input. What's the common method for passing that data back to the
  caller? I've tried a 'return data' prior to self.Close() ... all that
  happens then is the dialog won't close. I'm sure this is obvious, but
  this newbie's stuck!
 
  Thanks,
 
  Jeff

 In general, the dialog is an instance of a class. Once the dialog closes,
 the window should be gone but the instance variable should still be around.
 Common practice is to put the relevant data in the dialog instance member
 for retrieval after closing. In certain cases, the method used to invoke
 the dialog will return the relevant value, but this is somewhat limiting.
 In even more rare cases, the dialog will be popped up by a function,
 giving no direct reference to the dialog at any point, and the value is
 returned by the function; this is generally limited to the Yes/No/Cancel
 style dialog or its simpler bretheren (OK/Cancel and OK).

 I'm assuming that last one is not the case.

 To be more directly helpful, we'd need more data, ideally a code snippet
 fully demonstrating the problem (i.e., a runnable program). But at a bare
 minimum, we'd need to know where this dialog came from. Tk? PyGTK?
 wxPython? Some curses library? MFC?

Jeremy,

The dialog is from wxPython, generated using Boa Constructor. I'm cutting out 
hunks to try to be concise...

===
import wx

def create(parent):
return vents(parent)

[wxID_VENTS, wxID_VENTSEXITBUTTON, 
 wxID_VENTSVENTTYPETEXT,
[snip]

] = [wx.NewId() for _init_ctrls in range(14) ]

class vents(wx.Dialog):
def _init_ctrls(self, prnt):
wx.Dialog.__init__(self, id=wxID_VENTS, name=u'prefs', parent=prnt,
  pos=wx.Point(418, 320), size=wx.Size(321, 285),
  style=wx.DEFAULT_DIALOG_STYLE, title=u'Ventilator Settings')
self.SetClientSize(wx.Size(321, 285))

self.exitButton = wx.Button(id=wxID_VENTSEXITBUTTON, label=u'OK',
  name=u'exitButton', parent=self, pos=wx.Point(60, 250),
  size=wx.Size(85, 30), style=0)
self.exitButton.Bind(wx.EVT_BUTTON, self.OnExitButtonButton,
  id=wxID_VENTSEXITBUTTON)

self.venttypeText = wx.TextCtrl(id=wxID_VENTSVENTTYPETEXT,
  name=u'venttypeText', parent=self, pos=wx.Point(64, 24),
  size=wx.Size(144, 25), style=0, value=u'')

[snip]

def __init__(self, parent):
self._init_ctrls(parent)
 
# build an array of values entered in the dialog
# return array to calling program


def OnExitButtonButton(self, event):
  self.Close()

==

The dialog above is called by:

 def OnVentButtonButton(self, event):
dlg = vents.vents(self)
try:
dlg.ShowModal()
finally:
dlg.Destroy()


Thanks again,

Jeff

  




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


Re: python and glut

2005-05-07 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], max(01)* wrote:

 Lonnie Princehouse wrote:
 
 DRI not working could also be a permissions issue; check to see if it
 works as root.
 
 that's it! :-)
 
 now, how can i make it work as joe user?

I have this in my XF86Config and I'm in the `video` group::

  Section DRI
  Group  video
  Mode   0660
  EndSection

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


Re: Newbie: saving dialog variables

2005-05-07 Thread Jeremy Bowers
On Sat, 07 May 2005 15:43:08 +, jeff elkins wrote:
 ===
 import wx
 
 def create(parent):
 return vents(parent)
 
 [wxID_VENTS, wxID_VENTSEXITBUTTON, 
  wxID_VENTSVENTTYPETEXT,
 [snip]
 
 ] = [wx.NewId() for _init_ctrls in range(14) ]
 
 class vents(wx.Dialog):
 def _init_ctrls(self, prnt):
 wx.Dialog.__init__(self, id=wxID_VENTS, name=u'prefs', parent=prnt,
   pos=wx.Point(418, 320), size=wx.Size(321, 285),
   style=wx.DEFAULT_DIALOG_STYLE, title=u'Ventilator Settings')
 self.SetClientSize(wx.Size(321, 285))
 
 self.exitButton = wx.Button(id=wxID_VENTSEXITBUTTON, label=u'OK',
   name=u'exitButton', parent=self, pos=wx.Point(60, 250),
   size=wx.Size(85, 30), style=0)
 self.exitButton.Bind(wx.EVT_BUTTON, self.OnExitButtonButton,
   id=wxID_VENTSEXITBUTTON)
 
 self.venttypeText = wx.TextCtrl(id=wxID_VENTSVENTTYPETEXT,
   name=u'venttypeText', parent=self, pos=wx.Point(64, 24),
   size=wx.Size(144, 25), style=0, value=u'')
 
 [snip]
 
 def __init__(self, parent):
 self._init_ctrls(parent)
  
 # build an array of values entered in the dialog
 # return array to calling program
 
 
 def OnExitButtonButton(self, event):
   self.Close()
 
 ==
 
 The dialog above is called by:
 
  def OnVentButtonButton(self, event):
 dlg = vents.vents(self)
 try:
 dlg.ShowModal()
 finally:
 dlg.Destroy()

OK, I can't quite directly run this, but assuming you're trying to get the
user to enter some text into the text control, you should be able to add
  print dlg.venttypeText.GetValue()
to print what the user entered; this comes after the try: finally: (i.e.,
on the same indentation as dlg = vents.vents(self)).

The dialog window is gone, but the widgets and such inside it should
remain until it is garbage collected. (One of the keys to effective UI use
is dissociating the screen representation from the widget data structure
representation; certainly they are related but they are not identical,
generally the widget data structure is around both before and after the
actual display of the widget.)

On an unrelated note, somehow, the dialog should indicate if it was
cancelled or not; you'll need to consult the docs for that. It looks like
you don't want the user to be able to cancel, but watch out for sneaky
cancelling techniques; ESC might be automatically mapped to some sort of
cancel by the wx.Dialog class, and the user might also be able to click
on a close window button on the resulting dialog box, which may also get
processed as a cancel. I don't think it'll affect your code in this
particular case (it can sometimes), but it's bad UI; there should be a
style that shows a window with no close button on it. (Default may be it,
but I'd be surprised.) That style will probably also not do the default
keyboard mapping, so it should take care of both problems.

If you pull up the dialog and it has no close button and ESC does nothing,
disregard this :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: saving dialog variables

2005-05-07 Thread jeff elkins
On Saturday 07 May 2005 04:39 pm, Jeremy Bowers wrote:
 OK, I can't quite directly run this, but assuming you're trying to get the
 user to enter some text into the text control, you should be able to add
   print dlg.venttypeText.GetValue()
 to print what the user entered; this comes after the try: finally: (i.e.,
 on the same indentation as dlg = vents.vents(self)).

Thanks!  That did the trick.

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


plug-ins

2005-05-07 Thread Eric Nieuwland
Hi all,

The app I'm working on keeps getting new transforms and I'm tired of 
adding them by hand. So here it goes:
Can anyone provide me with clues/examples/references on how to create a 
plug-in framework?

tx,
--eric

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


Trouble saving unicode text to file

2005-05-07 Thread Svennglenn
I'm working on a program that is supposed to save
different information to text files.

Because the program is in swedish i have to use
unicode text for ÅÄÖ letters.

When I run the following testscript I get an error message.

# -*- coding: cp1252 -*-

titel = åäö
titel = unicode(titel)

print Titel type, type(titel)

fil = open(testfil.txt, w)
fil.write(titel)
fil.close()


Traceback (most recent call last):
  File D:\Documents and
Settings\Daniel\Desktop\Programmering\aaotest\aaotest2\aaotest2.pyw,
line 5, in ?
titel = unicode(titel)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0:
ordinal not in range(128)


I need to have the titel variable in unicode format because when I
write
åäö in a entry box in Tkinkter it makes the value to a unicode
format
automaticly.

Are there anyone who knows an easy way to save this unicode format text
to a file?

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


Newbie : checking semantics

2005-05-07 Thread LDD
Hi everyone,

I am new to python and was very enthustic about its possibilities when
I discover that python is really what it is : just a scripting
language.

What disappoints me is that pyton will happily accept and execute this
code :

if ( aConditionThatIsFalse ):
 AFunctionThatIsntDefined()

print Hello world

The fact that python doesn't check if the symbol
AFunctionThatIsntDefined is defined, is really bad when you develop big
pieces of code. You will never be sure that your code is free of this
kind of dummy errors and testing every possible execution paths is
nightmarish !

Is there a way to force Python to check the definition of symbol ?

LDD

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


Re: Trouble saving unicode text to file

2005-05-07 Thread Skip Montanaro

Svennglenn Traceback (most recent call last):
Svennglenn   File D:\Documents and
Svennglenn 
Settings\Daniel\Desktop\Programmering\aaotest\aaotest2\aaotest2.pyw,
Svennglenn line 5, in ?
Svennglenn titel = unicode(titel)
Svennglenn UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in 
position 0:
Svennglenn ordinal not in range(128)

Try:

import codecs

titel = åäö
titel = unicode(titel, iso-8859-1)
fil = codecs.open(testfil.txt, w, iso-8859-1)
fil.write(titel)
fil.close()

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


Re: globbing multiple wildcards

2005-05-07 Thread utabintarbo
Is there any way to make this recursive? That is what I was looking
for.

Sorry I wasn't too clear before.

Bob

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


Re: globbing multiple wildcards

2005-05-07 Thread [EMAIL PROTECTED]
Then take a look at os.walk, see
http://docs.python.org/lib/os-file-dir.html

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


Re: Newbie : checking semantics

2005-05-07 Thread Jeremy Bowers
On Sat, 07 May 2005 15:05:20 -0700, LDD wrote:
 The fact that python doesn't check if the symbol
 AFunctionThatIsntDefined is defined, is really bad when you develop big
 pieces of code. You will never be sure that your code is free of this
 kind of dummy errors and testing every possible execution paths is
 nightmarish !

Your unsubstantiated claim flies in the face of many man-years of
experience writing Python programs... and also has been discussed here so
many times it's hardly possible to count them. 

Summary: We know better, from experience. Quote dogma until you're blue in
the face, but nobody has managed to prove that large Python apps don't
exist, nor have they been able to show they were harder to write than
equivalent apps in more structured languages, which is also a tough sell
since they were easier.

To win this point, you need to produce evidence that doesn't exist.

Why not try opening your mind to the possibility that the dogma is wrong?

Points to ponder:

http://www.mindview.net/WebLog/log-0025
http://www.artima.com/weblogs/viewpost.jsp?thread=4639

The other point worth making is that if you want a language that you
already know, why not stick with it?

 Is there a way to force Python to check the definition of symbol ?

Look up pychecker, but beyond that, no. It turns out such a thing is
meaningless in the sense you are used to (static analysis), because a
symbol may not have a referent until much later, and based on arbitrary
code. Python is late-binding, unlike C/C++/Java and friends.

I think that about summarizes the current state of the art on this point.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie : checking semantics

2005-05-07 Thread [EMAIL PROTECTED]
I do not know of a check like the one you desire. But you always can
use some clever testing, e.g. facilitated with the unittest module to
prevent situations like yours, see
http://docs.python.org/lib/module-unittest.html

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


Re: plug-ins

2005-05-07 Thread Dave Brueck
Eric Nieuwland wrote:
 The app I'm working on keeps getting new transforms and I'm tired of 
 adding them by hand. So here it goes:
 Can anyone provide me with clues/examples/references on how to create a 
 plug-in framework?

The biggest task is defining the interface between your app and the plugins - 
you need to decide at what points plugins can interact with your application, 
what data from your application they'll need to have access to, etc. You'll 
also 
need to decide how your app becomes aware of new plugins - perhaps the data 
specifies it, or a config file. IOW, most of the initial work is just deciding 
on a convention you want to follow. Here is a simple example:

Plugins are Python modules that are placed in the app/plugins directory. A 
plugin may optionally have an Init() function that is called when the plugin is 
first loaded. A plugin is required to have a Process() function. This function 
takes an input buffer and return a transformed output buffer.

Here's some quickie code to load a plugin (untested):

import new

def LoadPlugin(name):
   'Loads a plugin and returns a plugin module object'
   # TODO: Decide on and implement an error-handling convention
   # Create a new module
   m = new.module(name)
   source = file('plugins/%s' % name).read()
   exec source in m.__dict__

   assert hasattr(m, 'Process'), 'Plugin %s has no Process function' % name
   # Optionally run its Init function
   if hasattr(m, 'Init'):
 m.Init()

   return m

If you need plugins at different times, you could have a plugin cache:

pluginCache = {} # name - plugin module
def GetPlugin(name):
   'Returns the named plugin from the cache, creating it if needed'
   try:
 return pluginCache[name]
   except KeyError:
 plugin = pluginCache[name] = LoadPlugin(name)
 return plugin

You might use a plugin like this:

def Transform(name, data):
   'Applies the named transform to the data and returns the result'
   plugin = GetPlugin(name)
   return plugin.Process(data)

In practice, your plugins will probably have a much richer interface. You may 
even decide to have an application object of some sort that you can pass to 
the plugins to provide services to them (logging facility, supporting routines 
that many plugins need, etc.). Instead of a module-based approach, you may 
instead decide that all plugins inherit from a plugin base class.

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


Re: Newbie : checking semantics

2005-05-07 Thread Mike Meyer
LDD [EMAIL PROTECTED] writes:

 I am new to python and was very enthustic about its possibilities when
 I discover that python is really what it is : just a scripting
 language.

That just covers a *very* big application space. So-called scripting
languages are being used in an ever-widening variety of ways.

 The fact that python doesn't check if the symbol
 AFunctionThatIsntDefined is defined, is really bad when you develop big
 pieces of code. You will never be sure that your code is free of this
 kind of dummy errors and testing every possible execution paths is
 nightmarish !

Testing every possible execution path may be nighmarish, but it's a
*requirement* for writing robust software. This is true whether
undefined variables are caught at compile time, execution time, or
later(*). You're never sure your code is free of bugs no matter what
you do, but adequate testing can help eliminate most of the dummy
ones. Failure to do that testing will ensure the presence of dummy
bugs in the code if you're developing a big piece of code, no matter
when they are detected.

Personally, I'm neutral on this issue. Clearly, declaring variables
saves time by catching such typos early. Equally clearly, not
declaring the variables saves time in that you don't have to enter the
declarations. While most RAD languages don't use variable
declarations, there are a number of factors that contribute to them
being faster than conventional languages, so the individual
contribution of this particular factor is unclear.

   mike

*) There are languages out there that quietly plug in a default value
when you reference an unassigned variable. That means the bug doesn't
show up until you start checking output values, at which point you
find garbage. Adequate testing will uncover these bugs, but finding
the actual bug is a PITA.

-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Python regex Doc (was: Python documentation moronicities)

2005-05-07 Thread Xah Lee
Let me expose one another fucking incompetent part of Python doc, in
illustration of the Info Tech industry's masturbation and ignorant
nature.

The official Python doc on regex syntax (
http://python.org/doc/2.4/lib/re-syntax.html ) says:

--begin quote--

|
A|B, where A and B can be arbitrary REs, creates a regular expression
that will match either A or B. An arbitrary number of REs can be
separated by the | in this way. This can be used inside groups (see
below) as well. As the target string is scanned, REs separated by |
are tried from left to right. When one pattern completely matches, that
branch is accepted. This means that once A matches, B will not be
tested further, even if it would produce a longer overall match. In
other words, the | operator is never greedy. To match a literal |,
use \|, or enclose it inside a character class, as in [|].

--end quote--

Note: In other words, the | operator is never greedy.

Note the need to inject the high-brow jargon greedy here as a
latch on sentence.

never greedy? What is greedy anyway?

Greedy, when used in the context of computing, describes a
certain characteristics of algorithms. When a algorithm for a
minimizing/maximizing problem is such that, whenever it faced a choice
it simply chose the shortest path, without considering whether that
choice actually results in a optimal solution.

The rub is that such stratedgy will often not obtain optimal result in
most problems. If you go from New York to San Francisco and always
choose the road most directly facing your destination, you'll never get
on.

For a algorithm to be greedy, it is implied that it faces choices. In
the case of alternatives in regex regex1|regex2|regex3, there is
really no selection involved, but following a given sequence.

What the writer were thinking when he latched on about greediness, is
that the result may not be from the pattern that matches the most
substring, therefore it is not greedy. It's not greedy Python
docer's ass.

Such blind jargon throwing, as found everywhere in tech docs, is a
significant reason why the computing industry is filled with shams the
likes of unix, Perl, Programing Patterns, eXtreme Programing,
Universal Modeling Language, fucking shits.


A better writen doc for the complete regex module is at:
http://xahlee.org/perl-python/python_re-write/lib/module-re.html

See also: Responsible Software Licensing
http://xahlee.org/UnixResource_dir/writ/responsible_license.html

 Xah
 [EMAIL PROTECTED]
 http://xahlee.org/

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

Re: Newbie : checking semantics

2005-05-07 Thread Bengt Richter
On 7 May 2005 15:05:20 -0700, LDD [EMAIL PROTECTED] wrote:

Hi everyone,

I am new to python and was very enthustic about its possibilities when
I discover that python is really what it is : just a scripting
language.
Not just. 

What disappoints me is that pyton will happily accept and execute this
code :

if ( aConditionThatIsFalse ):
 AFunctionThatIsntDefined()

print Hello world

The fact that python doesn't check if the symbol
AFunctionThatIsntDefined is defined, is really bad when you develop big
pieces of code. You will never be sure that your code is free of this
kind of dummy errors and testing every possible execution paths is
nightmarish !
If you aren't going to test your functions, how will you know they don't
have dummy errors??

Is there a way to force Python to check the definition of symbol ?

If _are_ going to test your functions, how long will it take to discover that
a function doesn't exist?

IOW, do you mean that if you know a function is defined, you will assume
it is free of dummy errors? Such faith ;-)

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


Re: Need help subclassing Borg

2005-05-07 Thread Steven D'Aprano
On Sat, 07 May 2005 22:28:34 +1000, Steven D'Aprano wrote:

 I've been working with the Borg design pattern from here:
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531


Thanks to everyone who took the time to answer. I've learnt a lot from the
discussion, not the least of which was to watch out for those mysterious
bunnies.


Steven.

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


Re: New Python regex Doc (was: Python documentation moronicities)

2005-05-07 Thread James Stroud
On Saturday 07 May 2005 04:28 pm, Xah Lee wrote:
 Note: In other words, the | operator is never greedy.

 Note the need to inject the high-brow jargon greedy here as a
 latch on sentence.

The first definition of jargon in the Collaborative International Dictionary 
of English is:

To utter jargon; to emit confused or unintelligible sounds; to talk 
unintelligibly, or in a harsh and noisy manner.

Despite your misuse of the word jargon, jargon seems to be an area in which 
you are carving yourself a niche.

The term greedy has a particular meaning in regex, as does the word 
algorithm in computer science. Take a look at Mastering Regular Expressions 
for an exhaustive discussion of the meaning of greedy as it applies to 
regular expressions. Of course I anticipate that you will confusedly and 
unintelligibly bash this book, even though it is quite obvious that you have 
yet to read or understand it.


-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Trouble saving unicode text to file

2005-05-07 Thread John Machin
On 7 May 2005 14:22:56 -0700, Svennglenn [EMAIL PROTECTED]
wrote:

I'm working on a program that is supposed to save
different information to text files.

Because the program is in swedish i have to use
unicode text for ÅÄÖ letters.

program is in Swedish: to the extent that this means names of
variables are in Swedish, this is quite irrelevant. The variable
names could be in some other language, like Slovak, Slovenian, Swahili
or Strine. Your problem(s) (PLURAL) arise from the fact that your text
data is in Swedish, the representation of which uses a few non-ASCII
characters. Problem 1 is the representation of Swedish in text
constants in your program; this is causing the exception you show
below but curiously didn't ask for help with.


When I run the following testscript I get an error message.

# -*- coding: cp1252 -*-

titel = åäö
titel = unicode(titel)

You should use titel = uåäö
Works, and saves wear  tear on your typing fingers.


print Titel type, type(titel)

fil = open(testfil.txt, w)
fil.write(titel)
fil.close()


Traceback (most recent call last):
  File D:\Documents and
Settings\Daniel\Desktop\Programmering\aaotest\aaotest2\aaotest2.pyw,
line 5, in ?
titel = unicode(titel)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0:
ordinal not in range(128)


I need to have the titel variable in unicode format because when I
write
åäö in a entry box in Tkinkter it makes the value to a unicode
format
automaticly.

The general rule in working with Unicode can be expressed something
like work in Unicode all the time i.e. decode legacy text as early as
possible; encode into legacy text (if absolutely required) as late as
possible (corollary: if forced to communicate with another
Unicode-aware system over an 8-bit wide channel, encode as utf-8, not
cp666)

Applying this to Problem 1 is, as you've seen, trivial: To the extent
that you have text constants at all in your program, they should be in
Unicode.

Now after all that, Problem 2: how to save Unicode text to a file?

Which raises a question: who or what is going to read your file? If a
Unicode-aware application, and never a human, you might like to
consider encoding the text as utf-16. If Unicode-aware app plus
(occasional human developer or not CJK and you want to save space),
try utf-8. For general use on Windows boxes in the Latin1 subset of
the universe, you'll no doubt want to encode as cp1252. 


Are there anyone who knows an easy way to save this unicode format text
to a file?

Read the docs of the codecs module -- skipping over how to register
codecs, just concentrate on using them.

Try this:

# -*- coding: cp1252 -*-
import codecs
titel = uåäö
print Titel type, type(titel)
f1 = codecs.open('titel.u16', 'wb', 'utf_16')
f2 = codecs.open('titel.u8', 'w', 'utf_8')
f3 = codecs.open('titel.txt', 'w', 'cp1252')
# much later, maybe in a different function
# maybe even in a different module
f1.write(titel)
f2.write(titel)
f3.write(titel)
# much later
f1.close()
f2.close()
f3.close()

Note: doing it this way follows the encode as late as possible rule
and documents the encoding for the whole file, in one place. Other
approaches which might use the .encode() method of Unicode strings and
then write the 8-bit-string results at different times and in
different functions/modules are somewhat less clean and more prone to
mistakes.

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


Re: New Python regex Doc (was: Python documentation moronicities)

2005-05-07 Thread John Bokma
Xah Lee wrote:

 Let me expose one another fucking incompetent part of

your writing capablities?

If you really had a point, there wouldn't be any need of swearing...

-- 
John   MexIT: http://johnbokma.com/mexit/
   personal page:   http://johnbokma.com/
Experienced programmer available: http://castleamber.com/
Happy Customers: http://castleamber.com/testimonials.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Python regex Doc

2005-05-07 Thread Ron Adam
Xah Lee wrote:
 Let me expose one another fu

Hello Xah,

I think you will continue to have difficulty getting respect on this 
matter as long as you show disrespect to those who have come before you.

When you refer to the documentation as being f'ing stupid, and other 
disrespectful terms, you are in an indirect, or depending on your 
intent, directly insulting the people who have done their best, as 
*volunteers* in most cases, to provide the existing documentation.

Text is never F'ing, Stupid, or any of the other terms you refer to as 
it being.  However it can be uninformative, hard to read, confusing, and 
even plain wrong.  But it is only text, and does not have a mind of it's 
own.  Referring to it as if it does, in such angry tones, reflects back 
on yourself and gives others a poor impression of you.

At the start, you choose to approach this matter as a personal and 
competitive agenda, ie.. You vs those who came before you.  Is this 
really the correct way to do this?  You don't have to insult those who 
came before you in order to make your case.  If you do, then maybe your 
case isn't strong enough.  But even this is wrong because it isn't a 
competition.

I suppose that if you respectfully offer something even a little better 
it would be respectfully accepted, after due review of course.  You will 
probably even get many helpful suggestions along they way because you 
will have created a situation where every one wins.

But by approaching it in the way you are, you make it very hard for 
people to support you, because to do so, they have to take on the role 
of losers in order for you to be a winner.

Just some thoughts, you might consider.

Cheers, and good luck with whatever aproach you decide.

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


Language documentation ( was Re: Computing Industry shams)

2005-05-07 Thread vermicule
Xah Lee [EMAIL PROTECTED] writes:

 A|B, where A and B can be arbitrary REs, creates a regular expression
 that will match either A or B. An arbitrary number of REs can be
 separated by the | in this way. This can be used inside groups (see
 below) as well. As the target string is scanned, REs separated by |
 are tried from left to right. When one pattern completely matches, that
 branch is accepted. This means that once A matches, B will not be
 tested further, even if it would produce a longer overall match. In
 other words, the | operator is never greedy. To match a literal |,
 use \|, or enclose it inside a character class, as in [|].

 --end quote--

 Note: In other words, the | operator is never greedy.

 Note the need to inject the high-brow jargon greedyhere as a
 latch on sentence.

What is so hard to understand ?
Should be perfectly clear even to a first year undergraduate.

As for greedy even a minimal exposure to Djikstra's shortest path
algorithm would have made the concept intuitive. And from memory,
that is the sort of thing done in Computing 101 and in  Data Structures and
Algorithms 101

It seems to me that you want the Python doc to be written for morons.
And that is not a valid complaint. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Python Pseudo-Switch

2005-05-07 Thread James Stroud
Hello All,

Because of my poorly designing a database, I have recently found it necessary 
to explore the wonders of the Python pseudo-switch:

do_case = { A : lambda x: x[bob],
B : lambda x: x[carol],
C : lambda x: Ted,
D : lambda x: do_something(x) }

my_thing = do_case[get_value_from_thin_air()](adict)


How to handle this kind of thing when lambda is removed from the language, 
beside the obvious def'ing those tiny little functions?

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Language documentation ( was Re: Computing Industry shams)

2005-05-07 Thread Måns Rullgård
vermicule [EMAIL PROTECTED] writes:

 Xah Lee [EMAIL PROTECTED] writes:

[...]


 It seems to me that you want the Python doc to be written for morons.

Not for morons, but for trolls.  Don't feed them.

-- 
Måns Rullgård
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hard memory limits

2005-05-07 Thread Maurice LING
Bengt Richter wrote:

 On Sat, 07 May 2005 14:03:34 +1000, Maurice LING [EMAIL PROTECTED] wrote:
 
 
John Machin wrote:

On Sat, 07 May 2005 02:29:48 GMT, [EMAIL PROTECTED] (Bengt Richter) wrote:



On Sat, 07 May 2005 11:08:31 +1000, Maurice LING [EMAIL PROTECTED] wrote:


It doesn't seems to help. I'm thinking that it might be a SOAPpy 
problem. The allocation fails when I grab a list of more than 150k 
elements through SOAP but allocating a 1 million element list is fine in 
python.

Now I have a performance problem...

Say I have 3 lists (20K elements, 1G elements, and 0 elements), call 
them 'a', 'b', and 'c'. I want to filter all that is in 'b' but not in 
'a' into 'c'...



a = range(1, 10, 5)
b = range(0, 100)
c = []
for i in b:

... if i not in a: c.append(i)
...

This takes forever to complete. Is there anyway to optimize this?


Checking whether something is in a list may average checking equality with
each element in half the list. Checking for membership in a set should
be much faster for any significant size set/list. I.e., just changing to

a = set(range(1, 10, 5))

should help. I assume those aren't examples of your real data ;-)
You must have a lot of memory if you are keeping 1G elements there and
copying a significant portion of them. Do you need to do this file-to-file,
keeping a in memory? Perhaps page-file thrashing is part of the time 
problem?


Since when was 100 == 1G??

Maurice, is this mucking about with 1M or 1G lists in the same
exercise as the vm_malloc fails when allocating a 20K-element list
problem? Again, it might be a good idea if you gave us a little bit
more detail. You haven't even posted the actual *PYTHON* error message
and stack trace that you got from the original problem. In fact,
there's a possible interpretation that the (system?) malloc merely
prints the vm_malloc message and staggers on somehow ...

Regards,
John

This is the exact error message:

*** malloc: vm_allocate(size=9203712) failed (error code=3)
*** malloc[489]: error: Can't allocate region

Nothing else. No stack trace, NOTHING.

 
 1. Can you post minimal exact code that produces the above exact error 
 message?
 2. Will you? ;-)
 
 Regards,
 Bengt Richter

I've re-tried the minimal code mimicking the error in interactive mode 
and got this:

  from SOAPpy import WSDL
  serv = 
WSDL.Proxy('http://eutils.ncbi.nlm.nih.gov/entrez/eutils/soap/v1.1/eutils.wsdl' 
)
  result = serv.run_eSearch(db='pubmed', term='mouse', retmax=50)
*** malloc: vm_allocate(size=9121792) failed (error code=3)
*** malloc[901]: error: Can't allocate region
Traceback (most recent call last):
   File stdin, line 1, in ?
   File /sw/lib/python2.3/site-packages/SOAPpy/Client.py, line 453, in 
__call__
 return self.__r_call(*args, **kw)
   File /sw/lib/python2.3/site-packages/SOAPpy/Client.py, line 475, in 
__r_call
 self.__hd, self.__ma)
   File /sw/lib/python2.3/site-packages/SOAPpy/Client.py, line 347, in 
__call
 config = self.config)
   File /sw/lib/python2.3/site-packages/SOAPpy/Client.py, line 212, in 
call
 data = r.getfile().read(message_len)
   File /sw/lib/python2.3/socket.py, line 301, in read
 data = self._sock.recv(recv_size)
MemoryError
 


When changed retmax to 15, it works nicely.

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


Out of Office AutoReply: Hello

2005-05-07 Thread Ian Holsman
Title: Out of Office AutoReply: Hello






i am currently out of the office until May 23rd.
if the matter is urgent, please contact tech-pma or
my manager Paul Osterhus




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

Re: New Python regex Doc

2005-05-07 Thread Peter Hansen
Ron Adam rote:
 I suppose that if you respectfully offer something even a little better 
 it would be respectfully accepted, after due review of course.  You will 
 probably even get many helpful suggestions along they way because you 
 will have created a situation where every one wins.

Remarkably, and because of the special nature of this newsgroup, Ron is 
right: something even a little better would be respectfully accepted, 
in spite of the incredibly anti-social nature of nearly all of Xah' past 
postings here.

In the (unlikely, IMHO) event that Xah can change, and wants to submit 
something even a little better, here are a few suggestions:

1. Use a spell checker.

2. Use a grammar checker.  Many people can get away without this tool, 
but pretty clearly Xah cannot.

3. Realize that posting partial improvements to this newsgroup will not 
really help anyone, unless you are explicitly soliciting feedback on the 
wording or structure with the intent of submitting the changes via the 
proper channels at a later time.

4. Clean up all loose ends, including removing comments of the sort to 
be rewritten later, and still needs work and such.  Somebody has to 
do the work; if you leave it undone, the changes are unlikely to be 
accepted.

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


Re: Trouble saving unicode text to file

2005-05-07 Thread Ivan Van Laningham
Hi All--

John Machin wrote:
 
 
 The general rule in working with Unicode can be expressed something
 like work in Unicode all the time i.e. decode legacy text as early as
 possible; encode into legacy text (if absolutely required) as late as
 possible (corollary: if forced to communicate with another
 Unicode-aware system over an 8-bit wide channel, encode as utf-8, not
 cp666)
 

+1 QOTW

And true, too.

i-especially-like-the-cp666-part-ly y'rs,
Ivan
--
Ivan Van Laningham
God N Locomotive Works
http://www.andi-holmes.com/
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps:  Cu Chi, Class of '70
Author:  Teach Yourself Python in 24 Hours
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie : checking semantics

2005-05-07 Thread George Sakkis
 What disappoints me is that pyton will happily accept and execute
this
 code :

 if ( aConditionThatIsFalse ):
  AFunctionThatIsntDefined()

 print Hello world

 The fact that python doesn't check if the symbol
 AFunctionThatIsntDefined is defined, is really bad when you develop
big
 pieces of code. You will never be sure that your code is free of this
 kind of dummy errors and testing every possible execution paths is
 nightmarish !

You're absolutely right. Any real language should catch these types of
errors, just as it would verify that the program below is correct:


if (aCondition):
AFunctionThatIsDefined()
.
.
.
.
def AFunctionThatIsDefined():
return 0 / (0-0)


Moral: There are *many* more reasons for testing every execution path
than catching name or type errors.

George

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


[ANN] pysqlite 2.0.beta1

2005-05-07 Thread Gerhard Haering
==
pysqlite 2.0.beta1
==

I'm glad to announce pysqlite 2.0.beta1. The API is 98 % stable now. And
pysqlite itself should be a lot more stable too, now.

The most notable changes are a lot of fixed refcount bugs, and the added
documentation.

Download the release here:

Sources: 
http://initd.org/pub/software/pysqlite/releases/2.0/2.0.beta1/pysqlite-2.0.beta1.tar.gz
win32 binaries for Python 2.3: 
http://initd.org/pub/software/pysqlite/releases/2.0/2.0.beta1/pysqlite-2.0.beta1.win32-py2.3.exe
win32 binaries for Python 2.4: 
http://initd.org/pub/software/pysqlite/releases/2.0/2.0.beta1/pysqlite-2.0.beta1.win32-py2.4.exe

pysqlite homepage, bug tracker, wiki: http://pysqlite.org/


Changes since 2.0.alpha4:
=

- Added pysqlite 2.0 documentation: usage guide and source installation guide.
  Adapted from kinterbasdb documentation with the permission of David Rushby.

- Fixed several refcount problems. Per test suite run, lose 0 references
  instead of 550 per test suite run like in alpha4.

- If a database file cannot be opened, raise an OperationalError specifically
  instead of a DatabaseError.

- Call the row factory with (cursor, row_tuple) instead of (row_tuple).

- Fixed a crash in .connect() when you tried to set a keyword argument. It's
  quite annoying that Python doesn't offer a method to extract a single keyword
  argument at C-level easily. Argh! So I bit the bullet and duplicated the
  parameter extraction code.

- The type name of PrepareProtocol was corrected. Only interesting for
  introspection.

- Added more tests to the test suite.

- Implemented cursor.arraysize.

- cursor.rowcount is now -1 instead of None in case of not determined, like
  the DB-API requires.

- Implemented autocommit mode which replaces the ''no_implicit_begin''
  parameter to the module-level connect(). This way, we're more compatible with
  other DB-API modules. autocommit parameter in module-level connect and also
  an autocommit property of connections. -- The begin method of connections
  is gone.


- Completely reworked the advanced type detection:
o connection.register_converter is gone
o instead, the dictionary connection.converters is exposed directly.
o The parameter more_types to the module-level connect is gone.
o Instead, use any combination of PARSE_DECLTYPES and PARSE_COLNAMES for
  the new paramter detect_types.

  PARSE_DECLTYPES will parse out the first word of a declared type and look
  up a converter in connection.converters:

create table foo(col mytype not null)

The decltype would be mytype not null, but PARSE_DECLTYPES will cut
out mytype and look for a converter in converters[mytype]. If it
finds any, it will use it to convert the value. Otherwise, the standard
SQLite manifest typing will be used.

PARSE_COLNAMES will parse out the column names and look up a converter in
connection.converters:

  cur.execute(select 1 as colname [mytype])

  the column names will be parsed for [...], in this case mytype will be
  found as the type for the colum, and the converters dictionary will be
  consulted for an appropriate converter function. If none is found, the
  standard SQLite manifest typing will be used.

   Also, the column names in cursor.description will only consist of the first
   word. So it would be colname in our example, not colname [mytype].

- cursor.coltypes is gone.

- The connection attribute of cursors is now made available at Python level.
  That's an optional DB-API extension.

- The exception classes are now attributes of the connection objects. That's an
  optional DB-API extension.

- Optimized the _sqlite_step_with_busyhandler() function by making time.time()
  and time.sleep() available at module import instead of importing the time
  module each time and getting out the time and sleep functions each time.
  Big performance improvement.

- Some work on the benchmarks.


- Made the destructor of the Cursor class more stable. It used to crash when an
  error occured in the Cursor *constructor*.

- Implemented a check that the parameter for Cursor() is actually an instance
  of the Connection class (or a subclass thereof).


- Allow long integers as parameters. Re-enable test cases for this.
-- 
Gerhard Häring - [EMAIL PROTECTED] - Python, web  database development

pysqlite - Powerful and fast embedded database engine SQLite for Python.


signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python Pseudo-Switch

2005-05-07 Thread Dan Bishop
James Stroud wrote:
 Hello All,

 Because of my poorly designing a database, I have recently found it
necessary
 to explore the wonders of the Python pseudo-switch:

 do_case = { A : lambda x: x[bob],
 B : lambda x: x[carol],
 C : lambda x: Ted,
 D : lambda x: do_something(x) }

 my_thing = do_case[get_value_from_thin_air()](adict)


 How to handle this kind of thing when lambda is removed from the
language,
 beside the obvious def'ing those tiny little functions?

You can always re-invent lambda.

 def lambda2(arg_names, expression):
...exec 'def _(%s): return %s' % (','.join(arg_names), expression)
...return _
...
 add = lambda2(('x', 'y'), 'x + y')
 add(3, 4)
7

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


Re: New Python regex Doc

2005-05-07 Thread Mike Meyer
Xah Lee [EMAIL PROTECTED] writes:

 Let me expose one another fucking incompetent part of Python doc, in
 illustration of the Info Tech industry's masturbation and ignorant
 nature.

What you actually expose is your own ignorance.

 Note: “In other words, the | operator is never greedy.”

 Note the need to inject the high-brow jargon “greedy” here as a
 latch on sentence.

Actually, greedy is a standard term when dealing with regular
expression matching. Anyone who's done even a little work with regular
expressions - which is pretty much all I've done, as I prefer to avoid
them - will know what it means.

 “never greedy”? What is greedy anyway?

 “Greedy”, when used in the context of computing, describes a
 certain characteristics of algorithms. When a algorithm for a
 minimizing/maximizing problem is such that, whenever it faced a choice
 it simply chose the shortest path, without considering whether that
 choice actually results in a optimal solution.

Except that's not the *only* meaning for greedy in a computing
context. That's what it means when you're talking about a specific
kind of problem solving algorithm. Those algorithms have *nothing* to
do with regular expressions, so this definition is irrelevant.

After doing a google for regular expression greedy, the second match
starts with the text:

 By default, pattern matching is greedy, which means that the matcher
 returns the longest match possible.

Now, it can be argued that the term ought not to be used, except that
it's a standard term with a well-known meaning, and exactly describes
the behavior in question.

You can argue that it ought to be defined. The problem is, you can't
explain things to a rock. You have to assume some basic level of
understanding. In particular, documentation on a regular expression
package should explain *how to use the package*, not what regular
expressions are, and the terminology associated with them.

As I've suggested before, what's really needed is a short tutorial on
regular expressions in general. That page could include a definition
of terms that are unique to regular expressions, and the re package
documentation could link the word greedy to that definition.

  mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie : checking semantics

2005-05-07 Thread elbertlev
 I am new to python and was very enthustic about its possibilities
when
 I discover that python is really what it is : just a scripting
 language.
..
 The fact that python doesn't check if the symbol ... is defined, is
really bad ...

1. For a language like Python full static checking is IMPOSSIBLE.
Consider setattr() with attribute name read from a file (f.e. names of
the columns in the database).

2. Trust me (and other Python programmers most likely would agree) this
type of error happens much more seldom then newbies (especially coming
from strongly typed languages) imagine while adjusting to the language.

3. Python advantages overpower drawbacks 10 to 1.

4. Most likely you never used Fortran :)

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


  1   2   >