failed to install PIL in fedora core 6

2007-02-23 Thread Frank Potter
I use "python setup.py install" to install PIL in fedora with python
2.4,
But I got these errors:
running build_ext
building '_imaging' extension
creating build/temp.linux-i686-2.4
creating build/temp.linux-i686-2.4/libImaging
gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wall -Wp,-
D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-
size=4 -m32 -march=i386 -mtune=generic -fasynchronous-unwind-tables -
D_GNU_SOURCE -fPIC -fPIC -DHAVE_LIBZ -I/usr/include/freetype2 -
IlibImaging -I/usr/include -I/usr/local/include -I/usr/include/
python2.4 -c _imaging.c -o build/temp.linux-i686-2.4/_imaging.o
_imaging.c:76:20: error: Python.h: No such file or directory
In file included from libImaging/Imaging.h:14,
 from _imaging.c:78:
libImaging/ImPlatform.h:10:20: error: Python.h: No such file or
directory
libImaging/ImPlatform.h:14:2: error: #error Sorry, this library
requires support for ANSI prototypes.
libImaging/ImPlatform.h:17:2: error: #error Sorry, this library
requires ANSI header files.
libImaging/ImPlatform.h:55:2: error: #error Cannot find required 32-
bit integer type
In file included from _imaging.c:78:
libImaging/Imaging.h:90: error: expected specifier-qualifier-list
before 'INT32'
libImaging/Imaging.h:265: error: expected specifier-qualifier-list
before 'INT32'
libImaging/Imaging.h:393: error: expected '=', ',', ';', 'asm' or
'__attribute__' before 'ImagingCRC32'
_imaging.c:123: error: expected specifier-qualifier-list before
'PyObject_HEAD'
.
_imaging.c: At top level:
_imaging.c:316: error: expected ')' before '*' token
_imaging.c:413: error: expected '=', ',', ';', 'asm' or
'__attribute__' before '*' token
_imaging.c:468: error: expected ')' before '*' token
_imaging.c:536: error: expected '=', ',', ';', 'asm' or
'__attribute__'
.
 before '*' token
_imaging.c:773: error: expected '=', ',', ';', 'asm' or
'__attribute__'  before 'functions'
_imaging.c:3138: warning: return type defaults to 'int'
_imaging.c: In function 'DL_EXPORT':
_imaging.c:3138: error: expected declaration specifiers before
'init_imaging'
_imaging.c:3149: error: expected '{' at end of input
error: command 'gcc' failed with exit status 1

What should I do if I want to successfully have pil installed?

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


Re: Rational numbers

2007-02-23 Thread Martin Manns
On 23 Feb 2007 22:19:30 -0800
[EMAIL PROTECTED] wrote:

> > Looks pretty much the same as mx.Number
> >
> > Does this warning come up from gmp? Do I have to compile it with
> > different flags?
> > Or do both wrappers use the same code?
> >
> > I would like to encourage the python community (i.e. the guys
> > maintaining the python docs) to point out a recommended rational
> > library. In one of the rational PEPs, it is stated that there are
> > multiple robust rational wrappers for python. But it is not stated,
> > which ones were thoroughly reviewed.
> >
> That specific error message is only a warning that occurs the first
> time a comparison operation is performed. I've successfully used gmpy
> and just ignored the one-time only error. You can use the "warnings"
> module to filter out that error. If I remember correctly, it was fixed
> in version 1.01. I know it is fixed in the SVN version.
> 
> Which specific version of gmpy are you using? (What is
> gmpy.version()?)
> 
$ python
Python 2.4.3 (#1, Jan 13 2007, 20:53:15) 
[GCC 4.1.1 (Gentoo 4.1.1-r3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gmpy
>>> gmpy.version()
'1.01'
>>> 

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


Re: Rational numbers

2007-02-23 Thread casevh
> Looks pretty much the same as mx.Number
>
> Does this warning come up from gmp? Do I have to compile it with
> different flags?
> Or do both wrappers use the same code?
>
> I would like to encourage the python community (i.e. the guys
> maintaining the python docs) to point out a recommended rational
> library. In one of the rational PEPs, it is stated that there are
> multiple robust rational wrappers for python. But it is not stated,
> which ones were thoroughly reviewed.
>
That specific error message is only a warning that occurs the first
time a comparison operation is performed. I've successfully used gmpy
and just ignored the one-time only error. You can use the "warnings"
module to filter out that error. If I remember correctly, it was fixed
in version 1.01. I know it is fixed in the SVN version.

Which specific version of gmpy are you using? (What is
gmpy.version()?)

I just compiled Alex's most recent SVN version on Linux without any
problems. I'll make Windows binaries next.

casevh





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


Re: Parsing HTML

2007-02-23 Thread John Nagle
BeautifulSoup does parse HTML well, but there are a few issues:

1.  It's rather slow; it can take seconds of CPU time to parse
some larger web pages.

2.  There's no error reporting.  It tries to do the right thing,
but when it doesn't, you have no idea what went wrong.

BeautifulSoup would be a good test case for the PyPy crowd to
work on.  It really needs the speedup.

John Nagle

sofeng wrote:
> On Feb 8, 11:43 am, "metaperl" <[EMAIL PROTECTED]> wrote:
>>On Feb 8, 2:38 pm, "mtuller" <[EMAIL PROTECTED]> wrote:
>>>I am trying to parse a webpage and extract information.
>>BeautifulSoup is a great Python module for this purpose:
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding non ascii characters in a set of files

2007-02-23 Thread Scott David Daniels
[EMAIL PROTECTED] wrote:
> I'm updating my program to Python 2.5, but I keep running into
> encoding problems. I have no ecodings defined at the start of any of
> my scripts. What I'd like to do is scan a directory and list all the
> files in it that contain a non ascii character. How would I go about
> doing this?


def non_ascii(files):
 for file_name in files:
 f = open(file_name, 'rb')
 if '~' < max(f.read(), ' '):
 yield file_name
 f.close()

if __name__ == '__main__':
 import os.path
 import glob
 import sys
 for dirname in sys.path[1:] or ['.']:
 for name in non_ascii(glob.glob(os.path.join(dirname, '*.py')) +
  glob.glob(os.path.join(dirname, '*.pyw'))):
 print name


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


Re: Solved: Question about idiomatic use of _ and private stuff.

2007-02-23 Thread goodwolf
> If you say
>
> from foo import _fooa, _foob,
>
> then the import will fail because the _ is used only by the import to
> decide that you shouldn't see _fooa or _foob.

???

Read Python manuals, please.

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


Re: Solved: Question about idiomatic use of _ and private stuff.

2007-02-23 Thread Steven D'Aprano
On Fri, 23 Feb 2007 23:17:32 -0500, Steven W. Orr wrote:

> On Friday, Feb 23rd 2007 at 11:12 -0500, quoth Steven W. Orr:
> 
> =>I understand that two leading underscores in a class attribute make the 
> =>attribute private. But I often see things that are coded up with one 
> =>underscore. Unless I'm missing something, there's a idiom going on here.
> =>
> =>Why do people sometimes use one leading underscore?
> 
> I found the answer. 

Not quite.


> It turns out that if you say:
> 
> import foo 
> 
> then you get access to all of the attributes that are not mangled. A 
> single leading underscore does not cause mangling.
> 
> If you say 
> 
> from foo import _fooa, _foob, 
> 
> then the import will fail because the _ is used only by the import to 
> decide that you shouldn't see _fooa or _foob.

Incorrect.

Let's try it. From the shell:

$ cat data.py
fear = "The chief weapon of the Spanish Inquisition"
_parrot = "A green bird"
__spam = "A nasty treat"


And then from Python:

>>> from data import fear, _parrot, __spam
>>> fear
'The chief weapon of the Spanish Inquisition'
>>> _parrot
'A green bird'
>>> __spam
'A nasty treat'

Python only ignores _names when you call "from module import *".

Here are the underscore rules:

(1) In the interactive interpreter, the name "_" is automatically set to
the result of the last command.

(2) Names with a SINGLE lead underscore are ignored when you say "from
module import *". They are imported if you ask for them directly, and in
the normal "import module" form.

(3) Class attributes, but not other objects, with TWO leading underscores
have their names mangled by Python. E.g. Parrot.__method is mangled to
Parrot._Parrot__method.

(4) Names with two leading underscores and two trailing underscores may be
reserved for special methods (e.g. __init__, __str__, etc.) and objects
(e.g. __all__ in packages, __name__, etc.). While Python doesn't prohibit
you from creating your own methods with leading and trailing underscores,
it is discouraged.

(5) If you want to give an object a name which clashes with a built-in,
the convention is to append a single TRAILING underscore to the name (e.g.
print_).


Hope that's clear now.



-- 
Steven.

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


Re: Rational numbers

2007-02-23 Thread Martin Manns
On Fri, 23 Feb 2007 20:20:12 -0300
"Gabriel Genellina" <[EMAIL PROTECTED]> wrote:

> En Fri, 23 Feb 2007 12:35:19 -0300, Martin Manns <[EMAIL PROTECTED]>
> escribió:
> 
> > I am starting to use rationals and since I found no batteries
> > included, I tried out the mxNumber package.
> >
> > However, I get strange warnings on comparison operations
> > (which however seem to yield correct results):
> 
> mx.Number.Rational is horribly broken. They break this rule:
> 
> a==b => hash(a)==hash(b)
> 
> so they can'b be used as dictionary keys, by example.
> Try the other packages suggested. I've used clnum without problems.
> 

I would be interested, under which circumstances the rule is broken.
In my (few) tests, hash(a)==hash(b) worked.

But I will definitely try clnum.
However, I already started trying out gmpy (1.1):

$ python
Python 2.4.3 (#1, Jan 13 2007, 20:53:15) 
[GCC 4.1.1 (Gentoo 4.1.1-r3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from gmpy import *
>>> a=mpq(0,1)
>>> a
mpq(0)
>>> b=-500
>>> a==b
__main__:1: RuntimeWarning: tp_compare didn't return -1, 0 or 1
False
>>>

Looks pretty much the same as mx.Number

Does this warning come up from gmp? Do I have to compile it with
different flags?
Or do both wrappers use the same code?

I would like to encourage the python community (i.e. the guys
maintaining the python docs) to point out a recommended rational
library. In one of the rational PEPs, it is stated that there are
multiple robust rational wrappers for python. But it is not stated,
which ones were thoroughly reviewed.

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


Solved: Question about idiomatic use of _ and private stuff.

2007-02-23 Thread Steven W. Orr
On Friday, Feb 23rd 2007 at 11:12 -0500, quoth Steven W. Orr:

=>I understand that two leading underscores in a class attribute make the 
=>attribute private. But I often see things that are coded up with one 
=>underscore. Unless I'm missing something, there's a idiom going on here.
=>
=>Why do people sometimes use one leading underscore?

I found the answer. It turns out that if you say:

import foo 

then you get access to all of the attributes that are not mangled. A 
single leading underscore does not cause mangling.

If you say 

from foo import _fooa, _foob, 

then the import will fail because the _ is used only by the import to 
decide that you shouldn't see _fooa or _foob.

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Possible to set cpython heap size?

2007-02-23 Thread Tony Nelson
In article <[EMAIL PROTECTED]>,
 "Andy Watson" <[EMAIL PROTECTED]> wrote:

 ...
> If I could have a heap that is larger and does not need to be
> dynamically extended, then the Python GC could work more efficiently.
 ...

GC!  If you're allocating lots of objects and holding on to them, GC 
will run frequently, but won't find anything to free.  Maybe you want to 
turn off GC, at least some of the time?  See the GC module, esp. 
set_threshold().

Note that the cyclic GC is only really a sort of safety net for 
reference loops, as normally objects are free'd when their last 
reference is lost.

TonyN.:'[EMAIL PROTECTED]
  '  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to build Hierarchies of dict's? (Prototypes in Python?)

2007-02-23 Thread Gabriel Genellina
At Friday 23/2/2007 22:12, Charles D Hixson wrote:

> This is going to take a bit of work (I've gone over the example 5 times,  
> and it's still not quite making
> sense), but this looks like just what I was hoping to find.

Just remember that:

obj.name = value
is the same as:
setattr(obj, "name", value)
(notice the quoted name), and likewise:

x = obj.name
is the same as:
x = getattr(obj, "name")

They are described in http://docs.python.org/lib/built-in-funcs.html

-- 
Gabriel Genellina

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


Re: Parsing HTML

2007-02-23 Thread sofeng
On Feb 8, 11:43 am, "metaperl" <[EMAIL PROTECTED]> wrote:
> On Feb 8, 2:38 pm, "mtuller" <[EMAIL PROTECTED]> wrote:
>
> > I am trying to parse a webpage and extract information.
>
> BeautifulSoup is a great Python module for this purpose:
>
>http://www.crummy.com/software/BeautifulSoup/
>
> Here's an article on screen scraping using it:
>
>http://iwiwdsmi.blogspot.com/2007/01/how-to-use-python-and-beautiful-...

This article has moved to 
http://iwiwdsmp.blogspot.com/2007/02/how-to-use-python-and-beautiful-soup-to.html

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


Re: Regex Speed

2007-02-23 Thread John Machin
On Feb 24, 11:51 am, greg <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > the author of this citation states that
> > any regex can be expressed as a  DFA machine. However ...
>
>  > I appear to have found one example of a regex
>
> > which breaks this assumption.
>
> > "ab+c|abd"
>
> > Am I correct?
>
> No. Any NFA can be converted to an equivalent DFA.

Correct. However ...

> This is how scanner generators like Lex work -- they
> first construct an NFA from the regex, and then
> convert it to a DFA. Going directly from the regex
> to a DFA, like you're trying to do, would be a lot
> harder, and I'd be surprised if anyone ever does
> it that way.

>From "Compilers; Principles, Techniques, and Tools" aka "the dragon
book" by Aho, Sethi and Ullman, 1986, page 134: "The first algorithm
is suitable for inclusion in a Lex compiler because it constructs a
DFA directly from a regular expression, without constructing an
intermediate NFA along the way."

>
> There's a description of the NFA-to-DFA algorithm
> here:
>
> http://www.gamedev.net/reference/articles/article2170.asp

which is on a really serious site (pop-up flashing whizz-bangs
inciting one to get an iPod now!) and which uses the (a|b)*abb example
from the dragon book (and the diagram of its Thompson-constructed NFA)
without any credit or mention of the book,  in fact no references or
attributions at all.


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


Re: Regex Speed

2007-02-23 Thread John Machin
On Feb 24, 10:15 am, [EMAIL PROTECTED] wrote:
> On Feb 21, 10:34 am, [EMAIL PROTECTED] wrote:
>
> > On Feb 20, 6:14 pm, Pop User <[EMAIL PROTECTED]> wrote:
> > >http://swtch.com/~rsc/regexp/regexp1.html
>
> Going back a bit on a tangent, the author of this citation states that
> any regex can be expressed as a  DFA machine. However, while
> investigating this more I appear to have found one example of a regex
> which breaks this assumption.
>
> "ab+c|abd"
>
> Am I correct?

No.

> Can you think of a deterministic method of computing
> this expression?

Firstly rewrite a bit:

ab+c|abd
a(b+c|bd)
a(bb*c|bd)
ab(b*c|d)
ab(b+c|c|d)

Here's a DFA that recognises that:
State 0:
a -> 1
State 1:
b -> 2
State 2:
b -> 3 # start of the b+c branch
c -> 4 # the c branch
d -> 4 # the d branch
State 3:
b -> 3
c -> 4
State 4:
accepting state

> It would be easier with a NFA machine,

What is "It"?

> but given that
> the Python method of computing RE's involves pre-compiling a re
> object,

AFAIK all serious regex engines precompile a regex into an internal
representation which can be saved for reuse.

> optimizing the matching engine

What does that mean?

> would make the most sense to
> me.

Compared to what alternatives?

>
> Here's what I have so far:

[big snip]

> >>> a = compile("ab+c|abd")
[snip]
> >>> a.match("abbd")
> Match!

Bzzzt. Neither "ab+c" nor "abd" match a prefix of "abbd".

HTH,
John

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


Re: Regex Speed

2007-02-23 Thread greg
[EMAIL PROTECTED] wrote:
> the author of this citation states that
> any regex can be expressed as a  DFA machine. However ...
 > I appear to have found one example of a regex
> which breaks this assumption.
> 
> "ab+c|abd"
> 
> Am I correct?

No. Any NFA can be converted to an equivalent DFA.
This is how scanner generators like Lex work -- they
first construct an NFA from the regex, and then
convert it to a DFA. Going directly from the regex
to a DFA, like you're trying to do, would be a lot
harder, and I'd be surprised if anyone ever does
it that way.

There's a description of the NFA-to-DFA algorithm
here:

http://www.gamedev.net/reference/articles/article2170.asp

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


Re: How to build Hierarchies of dict's? (Prototypes in Python?)

2007-02-23 Thread Charles D Hixson
Larry Bates wrote:
> Charles D Hixson wrote:
>   
>> I'm sure I've read before about how to construct prototypes in Python,
>> but I haven't been able to track it down (or figure it out).
>>
>> What I basically want is a kind of class that has both class and
>> instance level dict variables, such that descendant classes
>> automatically create their own class and instance level dict variables. 
>> The idea is that if a member of this hierarchy looks up something in
>> it's local dict, and doesn't find it, it then looks in the class dict,
>> and if not there it looks in its ancestral dict's.  This is rather like
>> what Python does at compile time, but I want to do it at run time.
>>
>> I'm sure I've seen how to do it...but have no idea where, or what it was
>> called, or when (probably around the time Prothon was being discussed,
>> as I have the idea of prototype associated with it for no clear reason).
>> 
>
> What you describe is exactly how Zope works so you might want to spend
> some time looking at it.
>
> http://www.zope.org
>
> -Larry
>   
Thanks for the suggestion, and I'll do that if I must, but Zope is 
pretty heavy to drag into something for just one function, and I don't 
really see any use for most parts of it in what I'm doing.  And that's a 
LOT of code to wade through for one technique.

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


Re: How to build Hierarchies of dict's? (Prototypes in Python?)

2007-02-23 Thread Charles D Hixson
Gabriel Genellina wrote:
>> En Fri, 23 Feb 2007 17:53:59 -0300, Charles D Hixson  
>> <[EMAIL PROTECTED]> escribió:
>>
>>  
>>> I'm sure I've read before about how to construct prototypes in Python,
>>> but I haven't been able to track it down (or figure it out).
>>>
>>> What I basically want is a kind of class that has both class and
>>> instance level dict variables, such that descendant classes
>>> automatically create their own class and instance level dict variables.
>>> The idea is that if a member of this hierarchy looks up something in
>>> it's local dict, and doesn't find it, it then looks in the class dict,
>>> and if not there it looks in its ancestral dict's.  This is rather like
>>> what Python does at compile time, but I want to do it at run time.
>>> 
>>
>> Well, the only thing on this regard that Python does at compile time, 
>> is  to determine whether a variable is local or not. Actual name 
>> lookup is  done at runtime.
>> You can use instances and classes as dictionaries they way you 
>> describe.  Use getattr/setattr/hasattr/delattr:
>>
>> py> class A:
>> ...   x = 0
>> ...   y = 1
>> ...
>> py> class B(A):
>> ...   y = 2
>> ...
>> py> a = A()
>> py> setattr(a, 'y', 3) # same as a.y = 3 but 'y' may be a variable
>> py> print 'a=',vars(a)
>> a= {'y': 3}
>> py>
>> py> b = B()
>> py> print 'b=',vars(b)
>> b= {}
>> py> setattr(b,'z',1000)
>> py> print 'b=',vars(b)
>> b= {'z': 1000}
>> py> print 'x?', hasattr(b,'x')
>> x? True
>> py> print 'w?', hasattr(b,'w')? False
> The trouble is, I'd want to be adding variables at run time.  At 
> least, I *think* that's a problem.  Perhaps I'm misunderstanding what 
> Python's capabilities already are.  How would one write a member 
> function to add a variable to a class?
>
>
>   

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


Re: Rational numbers

2007-02-23 Thread aleaxit
On Feb 23, 3:44 pm, [EMAIL PROTECTED] wrote:
   ...
> I can keep building gmpy for Windows. I actually use MINGW since
> getting GMP compiled under MSVC is "challanging". I should be able to
> build new binaries for Windows this weekend. And I would be happy to
> point everyone to a real release.

Great!  May I add you as a Member to the Google Code gmpy project?
After which, you should be able to use svn to get the latest sources,
make fixes, etc, etc -- including (if I understand the Google Code
mechanics correctly) simply uploading the Windows installer or
whatever, if it passes all tests (formal and informal) satisfactorily.

Please don't use the "1.02 prerelease" sources zip -- the SVN trunk is
more updated, I'll make a "1.02 definitive" sources zip once we have
gmpy built and working correctly on all variants of Windows and Mac
that we're going to support (I suggest that the binaries be made for
Python 2.3, 2.4 and 2.5, for Windows, Mac intel and Mac PPC -- unless
we can make Mac Universal work, but I'm finding that quite
problematic... a PPC Mac somewhere I shd be able to find:-).


Thanks,

Alex

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


Re: Shed Skin Optimizing Python-to-C++ Compiler 0.0.19

2007-02-23 Thread Michael
I randomly scribbled :

> Mark Dufour wrote:
> 
>> This
>> latest release adds basic support for iterators and generators
> 
> Oooh, I may try our miniaxon tutorial against shed skin in that case.
> (ie http://kamaelia.sourceforge.net/MiniAxon/)

I thought some people may be interested to hear that I did do this, and
whilst ShedSkin does have some limitations, and needs one piece of manual 
assistance, Shed Skin *can* compile a Kamaelia Mini-Axon.

A Kamaelia Mini-Axon is something we use for teaching how a Kamaelia core
can be created, but still features the core message passing, compositional
nature of Kamaelia. It's essentially the smallest sufficient subset.

Personally I think ShedSkin is pretty spectacular for being able to do
this, and also generate highly readable C++ code as a result. The code
it compiles to C++, the thing I had to manually assist shedskin with, &
the code shed skin generates for that are attached on this page:

   http://yeoldeclue.com/cgi-bin/blog/blog.cgi?rm=viewpost&nodeid=1172157410

I was half expecting as I went through doing this that this would fail at
some point, but for me this is a relatively complex, relatively substantial
system that *does* compile. (It also shows me that Kamaelia's approach is
implementable in C++ beyond a naive approach, which is a nice bonus :)

Shedskin home:
   http://mark.dufour.googlepages.com

Many congrats to Mark on this :-)


Michael.
--
Kamaelia Project Lead
http://kamaelia.sourceforge.net/Home
http://yeoldeclue.com/blog

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


Re: Question about idiomatic use of _ and private stuff.

2007-02-23 Thread goodwolf
On Feb 23, 5:12 pm, "Steven W. Orr" <[EMAIL PROTECTED]> wrote:
> I understand that two leading underscores in a class attribute make the
> attribute private. But I often see things that are coded up with one
> underscore. Unless I'm missing something, there's a idiom going on here.
>
> Why do people sometimes use one leading underscore?
>
> TIA
>
> --
> Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
> happened but none stranger than this. Does your driver's license say Organ ..0
> Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
> individuals! What if this weren't a hypothetical question?
> steveo at syslang.net

One underscore stay for 'protected'. Protected in OOP means that the
attribute is hidden outside the class but visible for subclasses. In
python one undersore is only a good convention for say that the
attribute is protected.
So users will ignore attributes with initial undersocre. Users who
subclass must know of that attributes existence for prevent unwonted
overriding.

Sory for my english.

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


Re: Pep 3105: the end of print?

2007-02-23 Thread Aahz
In article <[EMAIL PROTECTED]>,
Jay Tee <[EMAIL PROTECTED]> wrote:
>
>On the other hand, C++ is firmly established as a "serious" language
>in our community while python is not.  So the programmers tend to be
>more forgiving.  There is no perception that compiler developers are
>*trying* to be difficult by changing the language to break backwards
>compatibility.  That's the difference I think.

Consider the difference between "Python 3.0 is designed to break
backward compatibility" and "Python 3.0 cleans up a lot of accumulated
cruft".
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"I disrespectfully agree."  --SJM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about idiomatic use of _ and private stuff.

2007-02-23 Thread Gabriel Genellina
En Fri, 23 Feb 2007 13:12:20 -0300, Steven W. Orr <[EMAIL PROTECTED]>  
escribió:

> I understand that two leading underscores in a class attribute make the
> attribute private. But I often see things that are coded up with one
> underscore. Unless I'm missing something, there's a idiom going on here.
>
> Why do people sometimes use one leading underscore?

Just a single leading underscore means "not for public usage".
Double leading underscore (without trailing underscores), means that  
Python will "mangle" the name in an attempt to make the name unique along  
the class hierarchy (so two classes in the same hierarchy may use the same  
attribute name without conflicting).
Double leading and trailing underscores are used by the Python interpreter  
itself.

__names have some pitfalls so better avoid them except on the specific use  
case for which they were designed.  
http://docs.python.org/ref/atom-identifiers.html

-- 
Gabriel Genellina

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


Re: Possible to set cpython heap size?

2007-02-23 Thread Andrew MacIntyre
Chris Mellon wrote:
> On 22 Feb 2007 11:28:52 -0800, Andy Watson <[EMAIL PROTECTED]> wrote:
>> On Feb 22, 10:53 am, a bunch of folks wrote:
>>
>>> Memory is basically free.
>> This is true if you are simply scanning a file into memory.  However,
>> I'm storing the contents in some in-memory data structures and doing
>> some data manipulation.   This is my speculation:
>>
>> Several small objects per scanned line get allocated, and then
>> unreferenced.  If the heap is relatively small, GC has to do some work
>> in order to make space for subsequent scan results.  At some point, it
>> realises it cannot keep up and has to extend the heap.  At this point,
>> VM and physical memory is committed, since it needs to be used.  And
>> this keeps going on.  At some point, GC will take a good deal of time
>> to compact the heap, since I and loading in so much data and creating
>> a lot of smaller objects.
>>
>> If I could have a heap that is larger and does not need to be
>> dynamically extended, then the Python GC could work more efficiently.
>>
> 
> I haven't even looked at Python memory management internals since 2.3,
> and not in detail then, so I'm sure someone will correct me in the
> case that I am wrong.
> 
> However, I believe that this is almost exactly how CPython GC does not
> work. CPython is refcounted with a generational GC for cycle
> detection. There's a memory pool that is used for object allocation
> (more than one, I think, for different types of objects) and those can
> be extended but they are not, to my knowledge, compacted.
> 
> If you're creating the same small objects for each scanned lines, and
> especially if they are tuples or new-style objects with __slots__,
> then the memory use for those objects should be more or less constant.
> Your memory growth is probably related to the information you're
> saving, not to your scanned objects, and since those are long-lived
> objects I simple don't see how heap pre-allocation could be helpful
> there.

Python's internal memory management is split:
- allocations up to 256 bytes (the majority of objects) are handled by
a custom allocator, which uses 256kB arenas malloc()ed from the OS on
demand.  With 2.5 some additional work was done to allow returning
completely empty arenas to the OS; 2.3 and 2.4 don't return arenas at
all.
- all allocations over 256 bytes, including container objects that are
extended beyond 256 bytes, are made by malloc().

I can't recall off-hand whether the free-list structures for ints (and
floats?) use the Python allocator or direct malloc(); as the free-lists
don't release any entries, I suspect not.

The maximum allocation size and arena size used by the Python allocator
are hard-coded for algorithmic and performance reasons, and cannot be
practically be changed, especially at runtime.  No active compaction
takes place in arenas, even with GC.  The only time object data is
relocated between arenas is when an object is resized.

If Andy Watson is creating loads of objects that aren't being managed
by Python's allocator (by being larger than 256 bytes, or in a type 
free-list), then the platform malloc() behaviour applies.  Some platform
allocators can be tuned via environment variables and the like, in which
case review of the platform documentation is indicated.

Some platform allocators are notorious for poor behaviour in certain 
circumstances, and coalescing blocks while deallocating is one 
particularly nasty problem for code that creates and destroys lots
of small variably sized objects.

-- 
-
Andrew I MacIntyre "These thoughts are mine alone..."
E-mail: [EMAIL PROTECTED]  (pref) | Snail: PO Box 370
[EMAIL PROTECTED] (alt) |Belconnen ACT 2616
Web:http://www.andymac.org/   |Australia
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Having multiple instances of a single application start a single instance of another one

2007-02-23 Thread Larry Bates
buffinator wrote:
> I have two applications that should work together, let's call them A and B.
> 
> The first time A starts, it should open a B process and start
> communicating with it. All other times an A instance starts it should
> simply talk with the B that already is open.
> 
> The problem here is, if I start say 40 A applications at once... how do
> I check if a B is open "fast enough" so that the other A's (not the
> first one) won't spawn new B's?
> 
> Im programming this in windows and am currently using the horrible
> solution in A
> 
> if not win32gui.FindWindow(None, "Name of B"):
> spawn_B_here()
> 
> This only works well if there is a small time between the A's started
> first...
> 
> What would the best solution for my problem be?
> 
> /buffis

Others have answered your specific question on the forum, I thought
I would make a suggestion.  You should consider writing application B
as a Windows Service that gets started once (maybe even auto start
when the machine boots) and runs forever in the background.  Then have
all your A's bind to it and communication (via sockets, pipes, filesystem,
database, ...).  That way your A's won't have the problem you describe.

Just a suggestion.

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


Re: How to build Hierarchies of dict's? (Prototypes in Python?)

2007-02-23 Thread Gabriel Genellina
En Fri, 23 Feb 2007 17:53:59 -0300, Charles D Hixson  
<[EMAIL PROTECTED]> escribió:

> I'm sure I've read before about how to construct prototypes in Python,
> but I haven't been able to track it down (or figure it out).
>
> What I basically want is a kind of class that has both class and
> instance level dict variables, such that descendant classes
> automatically create their own class and instance level dict variables.
> The idea is that if a member of this hierarchy looks up something in
> it's local dict, and doesn't find it, it then looks in the class dict,
> and if not there it looks in its ancestral dict's.  This is rather like
> what Python does at compile time, but I want to do it at run time.

Well, the only thing on this regard that Python does at compile time, is  
to determine whether a variable is local or not. Actual name lookup is  
done at runtime.
You can use instances and classes as dictionaries they way you describe.  
Use getattr/setattr/hasattr/delattr:

py> class A:
...   x = 0
...   y = 1
...
py> class B(A):
...   y = 2
...
py> a = A()
py> setattr(a, 'y', 3) # same as a.y = 3 but 'y' may be a variable
py> print 'a=',vars(a)
a= {'y': 3}
py>
py> b = B()
py> print 'b=',vars(b)
b= {}
py> setattr(b,'z',1000)
py> print 'b=',vars(b)
b= {'z': 1000}
py> print 'x?', hasattr(b,'x')
x? True
py> print 'w?', hasattr(b,'w')
w? False


-- 
Gabriel Genellina

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


Re: Rational numbers

2007-02-23 Thread casevh
On Feb 23, 3:27 pm, [EMAIL PROTECTED] wrote:
> On Feb 23, 12:00 pm, [EMAIL PROTECTED] wrote:
>...
>
> > > > + gmpy is looking pretty unmaintained (dead) to me (newest update of
> > > > cvs 10 months ago).
>
> > I worked withAlex Martelli(gmpy's maintainer) to fix a bug found by
> > mensanator. With Alex's permission, I released it as gmpy 1.04a. Alex
> > has not updated cvs with the fix.
>
> Heh, I see why one might get that impression -- I'm in the process of
> moving gmpy from sourceforge (where I find it harder and harder, and
> ever more problematic, to work) to code.google.com 's new hosting
> facility -- gmpy 1.02 prerelease (more updated than that "1.04a", and
> particularly including your fix, Case) is already available 
> athttp://code.google.com/p/gmpy/but I have made no official
> announcement yet (partly because what's available is yet limited:
> sources, and binaries for Python 2.3, 2.4 and 2.5 but only for MacOSX
> 10.4 on Macs with intel processors)... building binaries for Windows
> (not having a Windows machine or development system) or Universal
> binaries for the Mac (due to problems building Universal versions of
> the underlying GMP in its latest, 4.2 incarnation... I'm running out
> of PPC-based Macs, and have none left with MaxOSX 10.3...) is much
> more problematic for me.
>
> To call this (Google Code) release 1.02, with a "1.04" (?) out from
> another source, may be confusing, but I'd rather not "force" the
> number upwards
>
> I do have one new co-owner on the Google Code "version" of gmpy (Chip
> Turner, once author of a similar GMP wrapper for perl, now a Python
> convert and a colleague of mine) but I suspect that won't make the
> building of Windows (and Universal Mac) binaries much easier.  If
> anybody who has easy access to Microsoft's MSVC++.NET (and is willing
> to try building GMP 4.2 with/for it), or a PPC Mac with XCode
> installed (possibly with MacOSX 10.3...), wants to volunteer to build
> "the missing binaries" for the platforms that the current owners of
> gmpy can't easily support, we could complete, test and release the
> definitive 1.02, and move on with the development (I could get
> enthusiastic about this again, if I could develop just the sources,
> and the binaries for the one architecture I really use -- Macs w/intel
> -- rather than strive each time with binaries for architectures that
> are quite a pain for me...!-).
>
> Anybody who's interested in helping out is welcome to mail me and/or
> use the "wiki" and "issues" entry of the Google Code gmpy site...
>
> Thanks,
>
> Alex

I can keep building gmpy for Windows. I actually use MINGW since
getting GMP compiled under MSVC is "challanging". I should be able to
build new binaries for Windows this weekend. And I would be happy to
point everyone to a real release.

casevh

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


Re: How to build Hierarchies of dict's? (Prototypes in Python?)

2007-02-23 Thread Larry Bates
Charles D Hixson wrote:
> I'm sure I've read before about how to construct prototypes in Python,
> but I haven't been able to track it down (or figure it out).
> 
> What I basically want is a kind of class that has both class and
> instance level dict variables, such that descendant classes
> automatically create their own class and instance level dict variables. 
> The idea is that if a member of this hierarchy looks up something in
> it's local dict, and doesn't find it, it then looks in the class dict,
> and if not there it looks in its ancestral dict's.  This is rather like
> what Python does at compile time, but I want to do it at run time.
> 
> I'm sure I've seen how to do it...but have no idea where, or what it was
> called, or when (probably around the time Prothon was being discussed,
> as I have the idea of prototype associated with it for no clear reason).

What you describe is exactly how Zope works so you might want to spend
some time looking at it.

http://www.zope.org

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


Re: Having multiple instances of a single application start a single instance of another one

2007-02-23 Thread Jerry Hill
On 2/23/07, buffinator <[EMAIL PROTECTED]> wrote:
> 2. How do I check if a process ID is bound to a running application.

Under windows, this should work:
>>> import win32process
>>> running_pids = win32process.EnumProcesses()
>>> running_pids
(0, 4, 1048, 1496, 1656, 1836, 1896, 756, 988, 1712, 220, 1156, 240,
1600, 1932, 428, 1100, 1880, 1152, 1444, 296, 624, 536, 412, 1812,
3384, 2064, 2164, 2344, 2516, 2816, 2992, 3412, 3628, 2836, 3168,
3420, 3408, 816, 1676, 504, 3244, 2404, 452, 1624, 3924, 2660, 3736,
3608, 1304)

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


Re: Rational numbers

2007-02-23 Thread aleaxit
On Feb 23, 2:52 pm, [EMAIL PROTECTED] wrote:
> > Am I hallucinating? Didn't I see at least some version
> > of gmpy for Python 2.5 on SourceForge awhile back?
> > I distinctly remember thinking that I don't have to
> > direct people to your site, but SourceForge is not
> > showing anything beyond vesion 1.01 for Python 2.4.
>
> Alex released versions 1.02 and 1.03 as CVS updates only. I think he
> may have made an announcement that 1.02 included alpha support for
> Python 2.5. 1.04a is 1.03 with one additional fix. I don't think there
> has been an official release, though.

Right: apparently sourceforce doesn't want me to do "releases" any
more (quite apart from the utter mess that doing a "release" on
sourceforce always was and still is), though I can still update the
cvs repository -- that's part of why I'm moving to Google Code
hosting.


Alex

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


Re: Rational numbers

2007-02-23 Thread aleaxit
On Feb 23, 12:00 pm, [EMAIL PROTECTED] wrote:
   ...
> > > + gmpy is looking pretty unmaintained (dead) to me (newest update of
> > > cvs 10 months ago).
>
> I worked withAlex Martelli(gmpy's maintainer) to fix a bug found by
> mensanator. With Alex's permission, I released it as gmpy 1.04a. Alex
> has not updated cvs with the fix.

Heh, I see why one might get that impression -- I'm in the process of
moving gmpy from sourceforge (where I find it harder and harder, and
ever more problematic, to work) to code.google.com 's new hosting
facility -- gmpy 1.02 prerelease (more updated than that "1.04a", and
particularly including your fix, Case) is already available at
http://code.google.com/p/gmpy/ but I have made no official
announcement yet (partly because what's available is yet limited:
sources, and binaries for Python 2.3, 2.4 and 2.5 but only for MacOSX
10.4 on Macs with intel processors)... building binaries for Windows
(not having a Windows machine or development system) or Universal
binaries for the Mac (due to problems building Universal versions of
the underlying GMP in its latest, 4.2 incarnation... I'm running out
of PPC-based Macs, and have none left with MaxOSX 10.3...) is much
more problematic for me.

To call this (Google Code) release 1.02, with a "1.04" (?) out from
another source, may be confusing, but I'd rather not "force" the
number upwards

I do have one new co-owner on the Google Code "version" of gmpy (Chip
Turner, once author of a similar GMP wrapper for perl, now a Python
convert and a colleague of mine) but I suspect that won't make the
building of Windows (and Universal Mac) binaries much easier.  If
anybody who has easy access to Microsoft's MSVC++.NET (and is willing
to try building GMP 4.2 with/for it), or a PPC Mac with XCode
installed (possibly with MacOSX 10.3...), wants to volunteer to build
"the missing binaries" for the platforms that the current owners of
gmpy can't easily support, we could complete, test and release the
definitive 1.02, and move on with the development (I could get
enthusiastic about this again, if I could develop just the sources,
and the binaries for the one architecture I really use -- Macs w/intel
-- rather than strive each time with binaries for architectures that
are quite a pain for me...!-).

Anybody who's interested in helping out is welcome to mail me and/or
use the "wiki" and "issues" entry of the Google Code gmpy site...


Thanks,

Alex

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


Re: Rational numbers

2007-02-23 Thread Gabriel Genellina
En Fri, 23 Feb 2007 12:35:19 -0300, Martin Manns <[EMAIL PROTECTED]> escribió:

> I am starting to use rationals and since I found no batteries included,
> I tried out the mxNumber package.
>
> However, I get strange warnings on comparison operations
> (which however seem to yield correct results):

mx.Number.Rational is horribly broken. They break this rule:

a==b => hash(a)==hash(b)

so they can'b be used as dictionary keys, by example.
Try the other packages suggested. I've used clnum without problems.

-- 
Gabriel Genellina

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


Re: Regex Speed

2007-02-23 Thread garrickp
On Feb 21, 10:34 am, [EMAIL PROTECTED] wrote:
> On Feb 20, 6:14 pm, Pop User <[EMAIL PROTECTED]> wrote:
> >http://swtch.com/~rsc/regexp/regexp1.html

Going back a bit on a tangent, the author of this citation states that
any regex can be expressed as a  DFA machine. However, while
investigating this more I appear to have found one example of a regex
which breaks this assumption.

"ab+c|abd"

Am I correct? Can you think of a deterministic method of computing
this expression? It would be easier with a NFA machine, but given that
the Python method of computing RE's involves pre-compiling a re
object, optimizing the matching engine would make the most sense to
me.

Here's what I have so far:

class State(object):
def __init__(self):
self.nextState = {}
self.nextStateKeys = []
self.prevState = None
self.isMatchState = True
def setNextState(self, chars, iNextState):
self.nextState[chars] = iNextState
self.nextStateKeys = self.nextState.keys()
self.isMatchState = False
def setPrevState(self, iPrevState):
self.prevState = iPrevState
def moveToNextState(self, testChar):
if testChar in self.nextStateKeys:
return self.nextState[testChar]
else:
return None

class CompiledRegex(object):
def __init__(self, startState):
self.startState = startState
def match(self, matchStr):
match_set = []
currentStates = [self.startState]
nextStates = [self.startState]
for character in matchStr:
for state in currentStates:
nextState = state.moveToNextState(character)
if nextState is not None:
nextStates.append(nextState)
if nextState.isMatchState:
print "Match!"
return
currentStates = nextStates
nextStates = [self.startState]
print "No Match!"

def compile(regexStr):
startState = State()
currentState = startState
backRefState = None
lastChar = ""
for character in regexStr:
if character == "+":
currentState.setNextState(lastChar, currentState)
elif character == "|":
currentState = startState
elif character == "?":
backRefState = currentState.prevState
elif character == "(":
# Implement "("
pass
elif character == ")":
# Implement ")"
pass
elif character == "*":
currentState = currentState.prevState
currentState.setNextState(lastChar, currentState)
else:
testRepeatState = currentState.moveToNextState(character)
if testRepeatState is None:
newState = State()
newState.setPrevState(currentState)
currentState.setNextState(character, newState)
if backRefState is not None:
backRefState.setNextState(character, newState)
backRefState = None
currentState = newState
else:
currentState = testRepeatState
lastChar = character
return CompiledRegex(startState)

>>> a = compile("ab+c")
>>> a.match("abc")
Match!
>>> a.match("abbc")
Match!
>>> a.match("ac")
No Match!
>>> a = compile("ab+c|abd")
>>> a.match("abc")
Match!
>>> a.match("abbc")
Match!
>>> a.match("ac")
No Match!
>>> a.match("abd")
Match!
>>> a.match("abbd")
Match!
>>>

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


Re: Having multiple instances of a single application start a single instance of another one

2007-02-23 Thread Troy Melhase
> Three very simple questions then.
>
> 1. How do I find out a running applications process ID

import os
mypid = os.getpid()

> 2. How do I check if a process ID is bound to a running application.

this is os-specific.  i'm sure there's a windows api provided for it.

> 3. There won't be any issues with different applications trying to read
> and write the same file doing this?

shouldn't be any problem:  only the first app started will write to the file.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-23 Thread casevh

> Am I hallucinating? Didn't I see at least some version
> of gmpy for Python 2.5 on SourceForge awhile back?
> I distinctly remember thinking that I don't have to
> direct people to your site, but SourceForge is not
> showing anything beyond vesion 1.01 for Python 2.4.

Alex released versions 1.02 and 1.03 as CVS updates only. I think he
may have made an announcement that 1.02 included alpha support for
Python 2.5. 1.04a is 1.03 with one additional fix. I don't think there
has been an official release, though.

casevh

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


Re: ANN: IbPy 0.7.0-9.00 - Interactive Brokers Python API

2007-02-23 Thread Troy Melhase
On 23 Feb 2007 14:36:24 -0800, vj <[EMAIL PROTECTED]> wrote:
> Cool. Why is python 2.5 required, will it not work with python 2.4?

Short answer:  because java2python produces python 2.5 syntax.

Long answer:

I wrote java2python specifically to translate the IB reference code.
That reference code makes heavy use of the java ternary operator, and
I wanted the most direct representation of that -- which is the
conditional expression provided in python 2.5.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Having multiple instances of a single application start a single instance of another one

2007-02-23 Thread buffinator
Troy Melhase wrote:
>> The first time A starts, it should open a B process and start
>> communicating with it. All other times an A instance starts it should
>> simply talk with the B that already is open.
> 
> B should write its process id to a location known by both
> applications.  When A starts, it should read that PID from the file
> and attempt to communicate with the process having that PID.
> 
> When B starts, it should also check for the file.  If it's found and
> if the PID in it is present in the process table, then B should exit.
> Otherwise, it should start normally and write its own PID to the file.

Three very simple questions then.

1. How do I find out a running applications process ID

2. How do I check if a process ID is bound to a running application.

3. There won't be any issues with different applications trying to read 
and write the same file doing this?

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


Re: Question about idiomatic use of _ and private stuff.

2007-02-23 Thread Chris Mellon
On 2/23/07, James Stroud <[EMAIL PROTECTED]> wrote:
> Troy Melhase wrote:
> >> Why do people sometimes use one leading underscore?
> >
> >
> > Many folks like to use the single leading underscore to emphasize that
> > the attribute isn't part of the normal way to use the class or
> > instance.
> >
> > It's bad style in my opinion, but I'm probably in the minority.
>
> I've increasingly found that leading underscores are unnecessary as well
> if not using a "magic" attribute with the bounding double underscores.
> --

I use the single underscore a lot and should use it more. It indicates
something that you shouldn't look at unless you understand and are
willing to bind yourself to the class internals.

For example, I have a network interface that buffers data as it's
being parsed. The internal buffer is a list named _buffer, and messing
with the buffer is a good way to break the parser.

There's an exterior interface, which is a guaranteed consistent buffer
called "message", but (even for me, the author) it's easy to get
confused about which one is the safe, public attribute and which one
is private. The underscore disambiguates.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: IbPy 0.7.0-9.00 - Interactive Brokers Python API

2007-02-23 Thread vj
Cool. Why is python 2.5 required, will it not work with python 2.4?

VJ

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


Re: Having multiple instances of a single application start a single instance of another one

2007-02-23 Thread Troy Melhase
> The first time A starts, it should open a B process and start
> communicating with it. All other times an A instance starts it should
> simply talk with the B that already is open.

B should write its process id to a location known by both
applications.  When A starts, it should read that PID from the file
and attempt to communicate with the process having that PID.

When B starts, it should also check for the file.  If it's found and
if the PID in it is present in the process table, then B should exit.
Otherwise, it should start normally and write its own PID to the file.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about idiomatic use of _ and private stuff.

2007-02-23 Thread James Stroud
Troy Melhase wrote:
>> Why do people sometimes use one leading underscore?
> 
> 
> Many folks like to use the single leading underscore to emphasize that
> the attribute isn't part of the normal way to use the class or
> instance.
> 
> It's bad style in my opinion, but I'm probably in the minority.

I've increasingly found that leading underscores are unnecessary as well 
if not using a "magic" attribute with the bounding double underscores.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-23 Thread [EMAIL PROTECTED]
On Feb 23, 2:00 pm, [EMAIL PROTECTED] wrote:
> On Feb 23, 10:34 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > On Feb 23, 10:39 am, Martin Manns <[EMAIL PROTECTED]> wrote:
>
> > > On Fri, 23 Feb 2007 09:52:06 -0600
>
> > > Larry Bates <[EMAIL PROTECTED]> wrote:
> > > > I quick search of Google turned up:
>
> > > >http://books.google.com/books?id=1Shx_VXS6ioC&pg=PA625&lpg=PA625&dq=p...
> > > >http://calcrpnpy.sourceforge.net/clnum.html
> > > >http://gmpy.sourceforge.net/
>
> > > Sorry that I did not point these out initially.
>
> > > + clnum seems to be slower and for speed may be compiled to wrap gmp so
> > > that it is just an additional layer between python and gmp .
>
> > > + gmpy is looking pretty unmaintained (dead) to me (newest update of
> > > cvs 10 months ago).
>
> I worked with Alex Martelli (gmpy's maintainer) to fix a bug found by
> mensanator. With Alex's permission, I released it as gmpy 1.04a. Alex
> has not updated cvs with the fix.
>
> gmpy 1.04a compiles cleanly with the latest releases of Python and
> GMP, so I consider it stable.

Am I hallucinating? Didn't I see at least some version
of gmpy for Python 2.5 on SourceForge awhile back?
I distinctly remember thinking that I don't have to
direct people to your site, but SourceForge is not
showing anything beyond vesion 1.01 for Python 2.4.


>
> > Actually, gmpy is being maitained even if SourceForge isn't up to
> > date.
>
> > I got my gmpy 1.04a for Python 2.5 Windows binary from
>
> > 
>
> > I haven't used the rationals all that much, but been very
> > happy with them when I have.
>
> casevh

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


Having multiple instances of a single application start a single instance of another one

2007-02-23 Thread buffinator
I have two applications that should work together, let's call them A and B.

The first time A starts, it should open a B process and start 
communicating with it. All other times an A instance starts it should 
simply talk with the B that already is open.

The problem here is, if I start say 40 A applications at once... how do 
I check if a B is open "fast enough" so that the other A's (not the 
first one) won't spawn new B's?

Im programming this in windows and am currently using the horrible 
solution in A

if not win32gui.FindWindow(None, "Name of B"):
spawn_B_here()

This only works well if there is a small time between the A's started 
first...

What would the best solution for my problem be?

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


Re: Found a product for running Python-based websites off CDROM -have anybody tried it?

2007-02-23 Thread Paul Boddie
David Wishnie wrote:
>
> We've looked at XAMPP, and it has the following disadvantages compared
> to Stunnix:

I've only read the Stunnix Web site, and I've only seen XAMPP in
passing. However...

> * it's not targeted for putting to CDs at all (it's "unzip and run apache and
>stuff"type of thing). This means it probably can't autochoose port 
> numbers
>for mysql and http. It has no functionality for easy stopping of webserver
>and stuff from inside a script (that allows to release media on Linux and
>OSX). It's seems not to be tested for running from read-only media. It has
>no "showing logo at startup" functionality.

I guess XAMPP isn't what you're looking for. But then, if it's just an
issue of having Apache in a filesystem on a CD, the distance between
convenient installation/unpacking of an Apache instance onto a normal
disk and the preparation of a ready-to-run instance isn't that great:
the two activities overlap, with the former perhaps providing the
means to enable the latter. I do wonder how database writes are
handled, though, or are bundled databases read-only?

> * XAMPP for Linux and OSX is considered beta

It shouldn't be too hard to work with anything UNIX-like. CD-ROMs are
just read-only filesystems, and we're not even talking about live CD
magic here.

> * XAMPP is unsupported as a whole
>
> * XAMPP for Linux and OSX seem not to support Tomcat and mod_python

Yes, but do we really care about Tomcat? ;-)

> * XAMPP for OSX won't work on OSX 10.3
>
> * Even if one will be able to somehow create a CD with XAMPP, the database
>   files and content of document root needs to be replicated for each platform.

Doesn't everything understand ISO-9660 plus various extensions these
days?

> The only advantage of XAMPP is the price. But given a time needed for
> highly-skilled enginer (with good programming skills) to spend on XAMPP
> to make it ready for creating commercial CDs for Windows, Mac OSX -
> cost of Stunnix tool is very attractive, and don't forget about updates and 
> support.

It's up to everyone to decide themselves how they spend their money,
but remember that software like Apache doesn't require rocket science
to set up in arbitrary locations, and database systems aren't that
difficult to install in various places either. Perhaps the most
difficult bit might be binary compatibility, and there'd be some
discipline required in making sure the library dependencies could be
satisfied on the target systems. Either that or you could give up and
distribute a virtual machine image - there was a Python Web
development image publicised a while back, in fact.

Paul

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


Re: timeout in urllib.open()

2007-02-23 Thread John J. Lee
Paul Rubin  writes:

> Stefan Palme <[EMAIL PROTECTED]> writes:
> > is there a way to modify the time a call of
> > 
> >   urllib.open(...)
> > 
> > waits for an answer from the other side? Have a tool which
> > automatically checks a list of websites for certain content. The
> > tool "hangs" when one of the contacted websites behaves badly and
> > "never" answers...
> 
> Other than by using socket timeouts, at least in Un*x, you can also
> use signal.alarm.  You can only have one OS-provided alarm pending at
> a time, so if you want multiple overlapping timeouts you have to
> schedule them yourself with a single alarm.

Note that neither of these is guaranteed to time out urllib.open(),
though usually they will.

Another way to solve the underlying problem is not to try to time out
the network operation(s) at all, but to use threads or non-blocking
sockets (e.g. using Twisted).


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


Re: timeout in urllib.open()

2007-02-23 Thread John J. Lee
Steve Holden <[EMAIL PROTECTED]> writes:
[...]
> This has recently been discussed on python-dev. It's likely that
> certain libraries will acquire a timeout keyword argument in the next
> release, but only if someone is concerned enough to develop the
> appropriate patches - the principle appears to be accepted.

I didn't read the recent python-dev thread, but ISTM this has been
true since the socket timeout feature was added (Python 2.3?).
Apparently so far nobody wanted it enough to actually implement it.


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


Re: Question about idiomatic use of _ and private stuff.

2007-02-23 Thread Troy Melhase
> Why do people sometimes use one leading underscore?

Many folks like to use the single leading underscore to emphasize that
the attribute isn't part of the normal way to use the class or
instance.

It's bad style in my opinion, but I'm probably in the minority.
-- 
http://mail.python.org/mailman/listinfo/python-list


Question about idiomatic use of _ and private stuff.

2007-02-23 Thread Steven W. Orr
I understand that two leading underscores in a class attribute make the 
attribute private. But I often see things that are coded up with one 
underscore. Unless I'm missing something, there's a idiom going on here.

Why do people sometimes use one leading underscore?

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BDFL in wikipedia

2007-02-23 Thread John J. Lee
Robin Becker <[EMAIL PROTECTED]> writes:

> Carl Banks wrote:
> ..
> > Since when is Larry Wall benevolent?  He should be called the SDFL.
> >
> .
> 
> even the great leader has been referred to as the MDFL :)
[...]

By you?-)


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


Re: Looking for contract developer(s) - where can I find them?

2007-02-23 Thread John J. Lee
[EMAIL PROTECTED] writes:

> On Feb 21, 9:51 pm, Scott SA <[EMAIL PROTECTED]> wrote:
> >
> > I've just sent a job listing to python.org and posted this message on
> > comp.lang.python,
> 
> Interesting, so Python-list@python.org and comp.lang.python are
> _related_. I guess that means I'm the new guy on the block. Well I
> guess this joke is on me this time ... LOL!

Yes, there's a bidirectional gateway between the two -- post to one
and it shows up on the other.


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


How to build Hierarchies of dict's? (Prototypes in Python?)

2007-02-23 Thread Charles D Hixson
I'm sure I've read before about how to construct prototypes in Python, 
but I haven't been able to track it down (or figure it out).

What I basically want is a kind of class that has both class and 
instance level dict variables, such that descendant classes 
automatically create their own class and instance level dict variables.  
The idea is that if a member of this hierarchy looks up something in 
it's local dict, and doesn't find it, it then looks in the class dict, 
and if not there it looks in its ancestral dict's.  This is rather like 
what Python does at compile time, but I want to do it at run time.

I'm sure I've seen how to do it...but have no idea where, or what it was 
called, or when (probably around the time Prothon was being discussed, 
as I have the idea of prototype associated with it for no clear reason).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Who has not attended these free tutorial courses ?

2007-02-23 Thread kilian heckrodt
[EMAIL PROTECTED] wrote:

Please note that this is a math newsgroup and
not a i-post-my-favoured-conspiracy-theory newsgroup


> "President Bush ... you are under arrest" - 911 truth video by Dr
> Morgan Reynolds, Former Chief Economist under Bush
> 
> You can also save them by right clicking the
> links and saving them as flv files and download a free flv player.
> google is your best friend.
> 
> "Bush Administration Insider Says U.S. Government Behind 911.flv"
> "http://ash-v31.ash.youtube.com/get_video?video_id=HkpOsUmp-9w";  <---
> key video
> 
> "911 Truth, Scott Forbes describes power-downs in WTC.flv" "http://
> youtube-609.vo.llnwd.net/d1/04/D1/fEJmcvTzYfo.flv"
> 
> "911 Truth, Consequences of Revealing the Truth about 911.flv"
> "http://
> youtube-609.vo.llnwd.net/d1/04/D1/fEJmcvTzYfo.flv"
> 
> "U.S. Army General Says Flight 77 Did Not Hit Pentagon.flv"
> "http://lax-v8.lax.youtube.com/get_video?video_id=Zsn4JA450iA";
> 
> "911 Truth, Bush Administration Lied About Iraq 911.flv" "http://lax-
> v8.lax.youtube.com/get_video?video_id=Zsn4JA450iA"
> 
> "Bush gets caught off guard on 9/11 prior knowledge question.flv"
> "http://lax-v222.lax.youtube.com/get_video?video_id=0eH5qbrpwlM";
> 
> "Bush gets caught off guard on 911 prior knowledge question.flv"
> "http://lax-v222.lax.youtube.com/get_video?video_id=0eH5qbrpwlM";
> 
> "World Trade Center -- Controlled Demolition.flv" "http://
> v187.youtube.com/get_video?video_id=87fyJ-3o2ws"
> 
> "911 Truth, The Moles, the Patsies, State-Sponsored Terror.flv"
> "http://chi-v43.chi.youtube.com/get_video?video_id=u0K9BM9oo90";
> 
> The Answer: Why do they hate our freedoms :
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-23 Thread Martin Manns
On 23 Feb 2007 12:00:10 -0800
[EMAIL PROTECTED] wrote:
> 
> I worked with Alex Martelli (gmpy's maintainer) to fix a bug found by
> mensanator. With Alex's permission, I released it as gmpy 1.04a. Alex
> has not updated cvs with the fix.
> 
> gmpy 1.04a compiles cleanly with the latest releases of Python and
> GMP, so I consider it stable.
> 
> >
> > Actually, gmpy is being maitained even if SourceForge isn't up to
> > date.
> >
> > I got my gmpy 1.04a for Python 2.5 Windows binary from
> >
> > 
> >
> > I haven't used the rationals all that much, but been very
> > happy with them when I have.
> >
> 
> casevh
> 

Thank you for all the replies.

I think that I am going to switch to gmpy.

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


Re: Finding non ascii characters in a set of files

2007-02-23 Thread Tim Arnold
"Marc 'BlackJack' Rintsch" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> In <[EMAIL PROTECTED]>, Tim Arnold wrote:
>
>> Here's what I do (I need to know the line number).
>>
>> import os,sys,codecs
>> def checkfile(filename):
>> f = codecs.open(filename,encoding='ascii')
>>
>> lines = open(filename).readlines()
>> print 'Total lines: %d' % len(lines)
>> for i in range(0,len(lines)):
>> try:
>> l = f.readline()
>> except:
>> num = i+1
>> print 'problem: line %d' % num
>>
>> f.close()
>
> I see a `NameError` here.  Where does `i` come from?  And there's no need
> to read the file twice.  Untested:
>
> import os, sys, codecs
>
> def checkfile(filename):
>f = codecs.open(filename,encoding='ascii')
>
>try:
>for num, line in enumerate(f):
>pass
>except UnicodeError:
>print 'problem: line %d' % num
>
>f.close()
>
> Ciao,
> Marc 'BlackJack' Rintsch

well, I take it backthat code doesn't work, or at least it doesn't for 
my test case.
but thanks anyway, I'm sticking to my original code. the 'i' came from for i 
in range.
--Tim


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


Re: Found a product for running Python-based websites off CDROM -have anybody tried it?

2007-02-23 Thread David Wishnie
Hello,

Thank you for your input!

We've looked at XAMPP, and it has the following disadvantages compared
to Stunnix:

* it's not targeted for putting to CDs at all (it's "unzip and run apache and
   stuff"type of thing). This means it probably can't autochoose
port numbers
   for mysql and http. It has no functionality for easy stopping of webserver
   and stuff from inside a script (that allows to release media on Linux and
   OSX). It's seems not to be tested for running from read-only media. It has
   no "showing logo at startup" functionality.

* XAMPP for Linux and OSX is considered beta

* XAMPP is unsupported as a whole

* XAMPP for Linux and OSX seem not to support Tomcat and mod_python

* XAMPP for OSX won't work on OSX 10.3

* Even if one will be able to somehow create a CD with XAMPP, the database
  files and content of document root needs to be replicated for each platform.

The only advantage of XAMPP is the price. But given a time needed for
highly-skilled
enginer (with good programming skills) to spend on XAMPP to make it ready for
creating commercial CDs for Windows, Mac OSX - cost of Stunnix tool is
very attractive, and don't forget about updates and support.

-David



On 2/20/07, Don Taylor <[EMAIL PROTECTED]> wrote:
> David Wishnie wrote:
> > Hello,
> >
> > Recently I've found a product that allows to create CDs or DVDs with
> > mod_python  -based websites
> > (and CGI python of  course) so that apache-based webserver, python and
> > mod_python are run directly
> > off CD on  Windows, MacOS X  and Linux at the same time (also it seems
> > to support perl, java,
> > php and mysql + SQLite as databases).
> >
> > http://www.stunnix.com/prod/aws/overview.shtml
> >
> > Have anybody tried it? I'm considering to use it for several projects.
> >
> > Thanks,
> >   David
> >
> That is an expensive product ($789) especially considering it mostly
> consists of FOSS pieces.
>
> I found XAMPP, a FOSS, that is almost the same thing:
>
> http://portableapps.com/apps/development/xampp
>
> and this thread for getting mod_python running (scroll down a bit to the
> second post):
>
> http://www.apachefriends.org/f/viewtopic.php?t=21169&highlight=python
>
> I have not tried this yet.
>
> Don.
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding non ascii characters in a set of files

2007-02-23 Thread Martin v. Löwis
Tim Arnold schrieb:
> That looks much cleaner. I didn't know the 'num' from the enumerate would 
> persist so the except block could report it.

It's indeed guaranteed that the for loop index variables will keep the
value they had when the loop stopped (either through regular
termination, break, or an exception) (unlike list comprehensions, where
the variable also stays, but only as a side effect of the implementation
strategy).

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


Re: Rational numbers

2007-02-23 Thread casevh
On Feb 23, 10:34 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> On Feb 23, 10:39 am, Martin Manns <[EMAIL PROTECTED]> wrote:
>
> > On Fri, 23 Feb 2007 09:52:06 -0600
>
> > Larry Bates <[EMAIL PROTECTED]> wrote:
> > > I quick search of Google turned up:
>
> > >http://books.google.com/books?id=1Shx_VXS6ioC&pg=PA625&lpg=PA625&dq=p...
> > >http://calcrpnpy.sourceforge.net/clnum.html
> > >http://gmpy.sourceforge.net/
>
> > Sorry that I did not point these out initially.
>
> > + clnum seems to be slower and for speed may be compiled to wrap gmp so
> > that it is just an additional layer between python and gmp .
>
> > + gmpy is looking pretty unmaintained (dead) to me (newest update of
> > cvs 10 months ago).

I worked with Alex Martelli (gmpy's maintainer) to fix a bug found by
mensanator. With Alex's permission, I released it as gmpy 1.04a. Alex
has not updated cvs with the fix.

gmpy 1.04a compiles cleanly with the latest releases of Python and
GMP, so I consider it stable.

>
> Actually, gmpy is being maitained even if SourceForge isn't up to
> date.
>
> I got my gmpy 1.04a for Python 2.5 Windows binary from
>
> 
>
> I haven't used the rationals all that much, but been very
> happy with them when I have.
>

casevh

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


Re: With PIL... paste image on top of other with dropshadow

2007-02-23 Thread Matimus
two things,

change the following line:
[code]
  back = Image.new(image.mode, (totalWidth, totalHeight), background)
[/code]
To:
[code]
  back = Image.new("RGBA", (totalWidth, totalHeight), background)
[/code]

and then do something like this:
[code]
  import sys

  bg = Image.open(sys.argv[1])
  image = Image.open(sys.argv[2])

  image = dropShadow(image,shadow=(0x00,0x00,0x00,0xff))
  bg.paste( image, (50,50), image )

  bg.show()
[/code]

Where the shadow color specifies an alpha transparency value.

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


Re: What is the best queue implemetation in Python?

2007-02-23 Thread sunheaver
On Feb 22, 12:40 pm, hg <[EMAIL PROTECTED]> wrote:
> John Machin wrote:
> > On Feb 23, 11:12 am, "John" <[EMAIL PROTECTED]> wrote:
> >> I want to write a code for Breadth First Traveral for Graph, which needs
> >> a queue to implement.
>
> >> I wonder that for such a powerful language as Python, whether there is a
> >> better and simpler implementation for a traditional FIFO queue?
>
> > Better and simpler than *WHAT*?
>
> Sorry, but you do that all the time ... "ask the question as you know the
> answer, otherwise shut the f u ..."
>
> Can't you assume for a second that other people do not have your wonderful
> brain and still have to make it through 60+ years of life of learning ?
>
> hg



Um... first off, you have to admit that a lot of what is posted
on the internet in general and even on groups like this is rambling,
poorly thought out, missing necessary context, and just generally a
mess and hard to understand.

So maybe a little peer pressure on folks to clean up their posts and
try
to express themselves clearly isn't such a bad thing.

And finally, let's face it: if the internet ever does cease to be a
place
where you can see crotechety know-it-all programmers roasting clueless
noobs,
then, honestly, what is the point of owning a computer?

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


Who has not attended these free tutorial courses ?

2007-02-23 Thread stj911
"President Bush ... you are under arrest" - 911 truth video by Dr
Morgan Reynolds, Former Chief Economist under Bush

You can also save them by right clicking the
links and saving them as flv files and download a free flv player.
google is your best friend.

"Bush Administration Insider Says U.S. Government Behind 911.flv"
"http://ash-v31.ash.youtube.com/get_video?video_id=HkpOsUmp-9w";  <---
key video

"911 Truth, Scott Forbes describes power-downs in WTC.flv" "http://
youtube-609.vo.llnwd.net/d1/04/D1/fEJmcvTzYfo.flv"

"911 Truth, Consequences of Revealing the Truth about 911.flv"
"http://
youtube-609.vo.llnwd.net/d1/04/D1/fEJmcvTzYfo.flv"

"U.S. Army General Says Flight 77 Did Not Hit Pentagon.flv"
"http://lax-v8.lax.youtube.com/get_video?video_id=Zsn4JA450iA";

"911 Truth, Bush Administration Lied About Iraq 911.flv" "http://lax-
v8.lax.youtube.com/get_video?video_id=Zsn4JA450iA"

"Bush gets caught off guard on 9/11 prior knowledge question.flv"
"http://lax-v222.lax.youtube.com/get_video?video_id=0eH5qbrpwlM";

"Bush gets caught off guard on 911 prior knowledge question.flv"
"http://lax-v222.lax.youtube.com/get_video?video_id=0eH5qbrpwlM";

"World Trade Center -- Controlled Demolition.flv" "http://
v187.youtube.com/get_video?video_id=87fyJ-3o2ws"

"911 Truth, The Moles, the Patsies, State-Sponsored Terror.flv"
"http://chi-v43.chi.youtube.com/get_video?video_id=u0K9BM9oo90";

The Answer: Why do they hate our freedoms :

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


Re: Finding non ascii characters in a set of files

2007-02-23 Thread Tim Arnold
"Marc 'BlackJack' Rintsch" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> In <[EMAIL PROTECTED]>, Tim Arnold wrote:
>


>   Untested:
>
> import os, sys, codecs
>
> def checkfile(filename):
>f = codecs.open(filename,encoding='ascii')
>
>try:
>for num, line in enumerate(f):
>pass
>except UnicodeError:
>print 'problem: line %d' % num
>
>f.close()
>
> Ciao,
> Marc 'BlackJack' Rintsch

Thanks Marc,
That looks much cleaner. I didn't know the 'num' from the enumerate would 
persist so the except block could report it.

thanks again,
--Tim


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


Re: Finding non ascii characters in a set of files

2007-02-23 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Tim Arnold wrote:

> Here's what I do (I need to know the line number).
> 
> import os,sys,codecs
> def checkfile(filename):
> f = codecs.open(filename,encoding='ascii')
> 
> lines = open(filename).readlines()
> print 'Total lines: %d' % len(lines)
> for i in range(0,len(lines)):
> try:
> l = f.readline()
> except:
> num = i+1
> print 'problem: line %d' % num
> 
> f.close()

I see a `NameError` here.  Where does `i` come from?  And there's no need
to read the file twice.  Untested:

import os, sys, codecs

def checkfile(filename):
f = codecs.open(filename,encoding='ascii')

try:
for num, line in enumerate(f):
pass
except UnicodeError:
print 'problem: line %d' % num

f.close()

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


Re: Rational numbers

2007-02-23 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Martin Manns wrote:

> + gmpy is looking pretty unmaintained (dead) to me (newest update of
> cvs 10 months ago).

What CSV activities do you expect?  This package seems to be pretty
stable.  As long as there is no bug or incompatible changes in the
underlying library I would not expect changes to that package.

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


Re: Rational numbers

2007-02-23 Thread [EMAIL PROTECTED]
On Feb 23, 10:39 am, Martin Manns <[EMAIL PROTECTED]> wrote:
> On Fri, 23 Feb 2007 09:52:06 -0600
>
> Larry Bates <[EMAIL PROTECTED]> wrote:
> > I quick search of Google turned up:
>
> >http://books.google.com/books?id=1Shx_VXS6ioC&pg=PA625&lpg=PA625&dq=p...
> >http://calcrpnpy.sourceforge.net/clnum.html
> >http://gmpy.sourceforge.net/
>
> Sorry that I did not point these out initially.
>
> + clnum seems to be slower and for speed may be compiled to wrap gmp so
> that it is just an additional layer between python and gmp .
>
> + gmpy is looking pretty unmaintained (dead) to me (newest update of
> cvs 10 months ago).

Actually, gmpy is being maitained even if SourceForge isn't up to
date.

I got my gmpy 1.04a for Python 2.5 Windows binary from



I haven't used the rationals all that much, but been very
happy with them when I have.


>
> + boost indeed is a quite nice C++ library. However, I fear that I
> would end up writing the python wrappers for operators (+ - * / min
> max cmp etc.) myself. I would like to avoid this since these operators
> should work correctly for any type (not just int and float) and I have
> little experience with verifying such generic code. The problems
> encountered in the mxNumber wrapper support this notion.
>
> Martin


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


Re: Rational numbers

2007-02-23 Thread bearophileHUGS
Martin Manns:
> + gmpy is looking pretty unmaintained (dead) to me (newest update of
> cvs 10 months ago).

I have used it on Py2.5, so it seems to work anyway, and it's fast
enough for my purposes. And probably soon some alex-shaped life will
show up elsewhere.

Bye,
bearophile

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


Re: CSV(???)

2007-02-23 Thread Neil Cerutti
On 2007-02-23, David C  Ullrich <[EMAIL PROTECTED]> wrote:
> Is there a csvlib out there somewhere?
>
> And/or does anyone see any problems with
> the code below?
>
> What csvline does is straightforward: fields
> is a list of strings. csvline(fields) returns
> the strings concatenated into one string
> separated by commas. Except that if a field
> contains a comma or a double quote then the
> double quote is escaped to a pair of double
> quotes and the field is enclosed in double
> quotes.
>
> The part that seems somewhat hideous is
> parsecsvline. The intention is that
> parsecsvline(csvline(fields)) should be
> the same as fields. Haven't attempted
> to deal with parsecsvline(data) where
> data is in an invalid format - in the
> intended application data will always
> be something that was returned by
> csvline. It seems right after some
> testing... also seems blechitudinous.
>
> (Um: Believe it or not I'm _still_ using python 1.5.7. So
> comments about iterators, list comprehensions, string methods,
> etc are irrelevent. Comments about errors in the algorithm
> would be great. Thanks.)

Two member functions of indexedstring are not used: next and
lookahead. __len__ and __getitem__ appear to serve no real
purpose.

> def parsecsvline(csvline):
>   """Inverts csvline(). Assumes csvline is valid, ie
>   is something as returned by csvline(); output undefined
>   if csvline is in invalid format"""
>
>   s = indexedstring(csvline)
>   res = []
>
>   while not s.eos():
>res.append(s.getfield())
>
>   return res

You'll be happy to know that iterators and list comprehensions
will make your code better after you upgrade. ;-)

In the meantime, I think your (relative lack of) error handling
is OK. GIGO, as they say (garbage in, garbage out).

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


Re: Local class variables? (mod_python problem)

2007-02-23 Thread Diez B. Roggisch
> 
> Many thanks for your reply. The use case is per request, and I would be
> grateful to learn more about thread-local storage.

There are several ways. I'm not familiar with mod_python, but I guess you
get a dict-like object for the request parameters. In python, this is
usually writable (in contrast to the darn J2EE-spec'ed HttpRequest)

So just add a new key, e.g. "working_state", to it. Under that, file those
variables.

Alternatively, there are recipes out there
(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302088
)

that give you basically a dictionary keyed with the current thread.

That is helpful if you have computations deeper in code that can't get a
hold on the request object. Might be the case in mod_python - in cherrypy,
the request itself is thread-locally stored, so you can get it whereever
you need.

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


Re: Rational numbers / alternatives to mxNumber

2007-02-23 Thread Martin Manns
On Fri, 23 Feb 2007 11:39:11 -0500
Martin Manns <[EMAIL PROTECTED]> wrote:

> + boost indeed is a quite nice C++ library. However, I fear that I
> would end up writing the python wrappers for operators (+ - * / min
> max cmp etc.) myself. I would like to avoid this since these operators
> should work correctly for any type (not just int and float) and I have
> little experience with verifying such generic code. The problems
> encountered in the mxNumber wrapper support this notion.


I just saw the pyboost-linux-0.1.1 package and tried it out.

ImportError: /home/mn/notes/libboost_python.so.1.34.0: undefined
symbol: PyUnicodeUCS4_FromEncodedObject

It seems to have problems with UCS2 compiled python.
Any robust rational wrapper out there?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding non ascii characters in a set of files

2007-02-23 Thread Tim Arnold
"Peter Bengtsson" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On Feb 23, 2:38 pm, [EMAIL PROTECTED] wrote:
>> Hi,
>>
>> I'm updating my program to Python 2.5, but I keep running into
>> encoding problems. I have no ecodings defined at the start of any of
>> my scripts. What I'd like to do is scan a directory and list all the
>> files in it that contain a non ascii character. How would I go about
>> doing this?
>>
>
> How about something like this:
> content = open('file.py').read()
> try:
>content.encode('ascii')
> except UnicodeDecodeError:
>print "file.py contains non-ascii characters"
>
Here's what I do (I need to know the line number).

import os,sys,codecs
def checkfile(filename):
f = codecs.open(filename,encoding='ascii')

lines = open(filename).readlines()
print 'Total lines: %d' % len(lines)
for i in range(0,len(lines)):
try:
l = f.readline()
except:
num = i+1
print 'problem: line %d' % num

f.close()



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


Re: c_string missing from ctypes?

2007-02-23 Thread Simon Brunning
On 23 Feb 2007 09:03:21 -0800, Jacob Rael <[EMAIL PROTECTED]> wrote:
> I was following along with this site:
>
> http://www.brunningonline.net/simon/blog/archives/000659.html

You don't want to be messing around with that old rubbish. I should
know - I wrote it.

Instead, take a look at .

> In [9]: import ctypes
> In [10]: dir(ctypes.c_string)
> ---
> Traceback (most recent call
> last)
> : 'module' object has no attribute
> 'c_string'

I think that c_string has been replaced by c_buffer in recent versions
of ctypes.

-- 
Cheers,
Simon B
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: c_string missing from ctypes?

2007-02-23 Thread Chris Mellon
On 23 Feb 2007 09:03:21 -0800, Jacob Rael <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I was following along with this site:
>
> http://www.brunningonline.net/simon/blog/archives/000659.html
>
> and I got a error. It boils down to:
>
> 
>
> In [9]: import ctypes
> In [10]: dir(ctypes.c_string)
> ---
> Traceback (most recent call
> last)
>
> P:\ in ()
>
> : 'module' object has no attribute
> 'c_string'
>
> 

The tutorial is out of date, ctypes.c_string was removed somewhere
around version 0.6 (theres a comment to this effect in the comments
under the tutorial). You want ctypes.c_buffer instead.

>
>
> I google ctypes.c_string and many people use it.
>
> I am using python 2.5 with ctypes version: 1.0.1  on a windows
> machine.
>
> I have to admit I don't know where ctypes came from. I tried to re-
> install it but the window binaries only support 2.4.
>

As of Python 2.5 ctypes is part of the standard library.

> Also:
>
> http://starship.python.net/crew/theller/ctypes/tutorial.html
>
> seems dead.
>
> An info is greatly appreciated.
>
> jr
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


c_string missing from ctypes?

2007-02-23 Thread Jacob Rael
Hello,

I was following along with this site:

http://www.brunningonline.net/simon/blog/archives/000659.html

and I got a error. It boils down to:



In [9]: import ctypes
In [10]: dir(ctypes.c_string)
---
Traceback (most recent call
last)

P:\ in ()

: 'module' object has no attribute
'c_string'




I google ctypes.c_string and many people use it.

I am using python 2.5 with ctypes version: 1.0.1  on a windows
machine.

I have to admit I don't know where ctypes came from. I tried to re-
install it but the window binaries only support 2.4.

Also:

http://starship.python.net/crew/theller/ctypes/tutorial.html

seems dead.

An info is greatly appreciated.

jr

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


Re: Finding non ascii characters in a set of files

2007-02-23 Thread John Machin
On Feb 24, 2:44 am, Larry Bates <[EMAIL PROTECTED]> wrote:
> Peter Bengtsson wrote:
> > On Feb 23, 2:38 pm, [EMAIL PROTECTED] wrote:
> >> Hi,
>
> >> I'm updating my program to Python 2.5, but I keep running into
> >> encoding problems. I have no ecodings defined at the start of any of
> >> my scripts. What I'd like to do is scan a directory and list all the
> >> files in it that contain a non ascii character. How would I go about
> >> doing this?
>
> > How about something like this:
> > content = open('file.py').read()
> > try:
> > content.encode('ascii')
> > except UnicodeDecodeError:
> > print "file.py contains non-ascii characters"
>
> The next problem will be that non-text files will contain non-ASCII
> characters (bytes).  The other 'issue' is that OP didn't say how large
> the files were, so .read() might be a problem.
>
> -Larry

The way I read it, the OP's problem is to determine in one big hit
which Python source files need a

# coding: whatever

line up the front to stop Python 2.5 complaining ... I hope none of
them are so big as to choke .read()

Cheers,
John

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


Re: Rational numbers

2007-02-23 Thread Martin Manns
On Fri, 23 Feb 2007 09:52:06 -0600
Larry Bates <[EMAIL PROTECTED]> wrote:
> I quick search of Google turned up:
> 
> http://books.google.com/books?id=1Shx_VXS6ioC&pg=PA625&lpg=PA625&dq=python+rational+number+library&source=web&ots=BA8_4EXdQ4&sig=aDEnYA99ssKe7PSweVNyi8cS2eg
> http://calcrpnpy.sourceforge.net/clnum.html
> http://gmpy.sourceforge.net/

Sorry that I did not point these out initially.

+ clnum seems to be slower and for speed may be compiled to wrap gmp so
that it is just an additional layer between python and gmp .

+ gmpy is looking pretty unmaintained (dead) to me (newest update of
cvs 10 months ago).

+ boost indeed is a quite nice C++ library. However, I fear that I
would end up writing the python wrappers for operators (+ - * / min
max cmp etc.) myself. I would like to avoid this since these operators
should work correctly for any type (not just int and float) and I have
little experience with verifying such generic code. The problems
encountered in the mxNumber wrapper support this notion.

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


Re: Local class variables? (mod_python problem)

2007-02-23 Thread Rory Campbell-Lange
On 23/02/07, Diez B. Roggisch ([EMAIL PROTECTED]) wrote:
> > It is not desirable for the class variable to keep incrementing outside
> > of invocations of '__main__', as is the case when it is loaded under
> > mod_python under apache2 on linux.
> > 
> 
> I'm still not clear on what you want to accomplish. In the end it boils down
> to who is supposed to share that information in the variables, or in other
> words: which scope has it.
> 
> Is it per request? Then using some thread-local storage would be in order,
> or "abusing" a possible request-object.
> 
> Is it per user, over several requests? Then you need a session-mechanism.
> 
> Is it per application, for several users, over several requests? Then your
> approach is ok, but needs guarding against concurrrent access using
> threading.Lock for example. However, I presume that is not the desired
> usecase, from what I can extract from your posts I presume it's case two.

Many thanks for your reply. The use case is per request, and I would be
grateful to learn more about thread-local storage.

Kind regards
Rory

-- 
Rory Campbell-Lange 
<[EMAIL PROTECTED]>

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


Re: Rational numbers

2007-02-23 Thread Larry Bates
Martin Manns wrote:
> Hi,
> 
> I am starting to use rationals and since I found no batteries included,
> I tried out the mxNumber package.
> 
> However, I get strange warnings on comparison operations
> (which however seem to yield correct results):
> 
> ---
> $ python
> Python 2.4.3 (#1, Jan 15 2007, 15:46:19) 
> [GCC 4.1.1 (Gentoo 4.1.1-r3)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 from mx.Number import *
 a=Rational(0,1)
 a
> 0/1
 str(a)
> '0.0'
 b=-50
 b
> -50L
 a==b
> __main__:1: RuntimeWarning: tp_compare didn't return -1, 0 or 1
> False
> ---
> 
> How do I get rid of these warnings?
> 
> Is there any rational number library around that
> 1) is comparably fast for large denominators
> 2) allows deriving types from Rationals without wrapping?
> 
> Regards
> 
> Martin
> 
> P.S. The respective mailing list does not like me, so that I try my
> luck here.

I quick search of Google turned up:

http://books.google.com/books?id=1Shx_VXS6ioC&pg=PA625&lpg=PA625&dq=python+rational+number+library&source=web&ots=BA8_4EXdQ4&sig=aDEnYA99ssKe7PSweVNyi8cS2eg
http://calcrpnpy.sourceforge.net/clnum.html
http://gmpy.sourceforge.net/

-Larry

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


Re: Apache Cgi (70007)The timeout specified has expired

2007-02-23 Thread abubakerkiter2003

[EMAIL PROTECTED] أرسلت:
> Hello,
>
> When i run my python script, it works a moment and then stop with this
> message in the log:
>
> (70007)The timeout specified has expired: ap_content_length_filter:
> apr_bucket_read() failed refers to ..
>
> I think my script is too long therefore the server stop it...
>
> how can i do to run all my python script?
>
> thanks for your help

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

Re: Apache Cgi (70007)The timeout specified has expired

2007-02-23 Thread abubakerkiter2003

[EMAIL PROTECTED] أرسلت:
> Hello,
>
> When i run my python script, it works a moment and then stop with this
> message in the log:
>
> (70007)The timeout specified has expired: ap_content_length_filter:
> apr_bucket_read() failed refers to ..
>
> I think my script is too long therefore the server stop it...
>
> how can i do to run all my python script?
>
> thanks for your help

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

Re: Finding non ascii characters in a set of files

2007-02-23 Thread John Machin
On Feb 24, 2:35 am, "John Machin" <[EMAIL PROTECTED]> wrote:
> On Feb 24, 2:12 am, "Peter Bengtsson" <[EMAIL PROTECTED]> wrote:
>
> > On Feb 23, 2:38 pm, [EMAIL PROTECTED] wrote:
>
> > > Hi,
>
> > > I'm updating my program to Python 2.5, but I keep running into
> > > encoding problems. I have no ecodings defined at the start of any of
> > > my scripts. What I'd like to do is scan a directory and list all the
> > > files in it that contain a non ascii character. How would I go about
> > > doing this?
>
> > How about something like this:
> > content = open('file.py').read()
> > try:
> > content.encode('ascii')
> > except UnicodeDecodeError:
> > print "file.py contains non-ascii characters"

Sorry, I fell face down on the Send button :-)

To check all .py files in the current directory, modify Peter's code
like this:

import glob
for filename in glob.glob('*.py'):
   content = open(filename).read()

maybe that UnicodeDecodeError should be ...Encode...
and change the print statement to cater for filename being variable.

If you have hundreds of .py files in the same directory, you'd better
modify the code further to explicitly close each file.

HTH,
John

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


Apache Cgi (70007)The timeout specified has expired

2007-02-23 Thread naima . mans
Hello,

When i run my python script, it works a moment and then stop with this
message in the log:

(70007)The timeout specified has expired: ap_content_length_filter:
apr_bucket_read() failed refers to ..

I think my script is too long therefore the server stop it...

how can i do to run all my python script?

thanks for your help

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


Re: Finding non ascii characters in a set of files

2007-02-23 Thread Larry Bates
Peter Bengtsson wrote:
> On Feb 23, 2:38 pm, [EMAIL PROTECTED] wrote:
>> Hi,
>>
>> I'm updating my program to Python 2.5, but I keep running into
>> encoding problems. I have no ecodings defined at the start of any of
>> my scripts. What I'd like to do is scan a directory and list all the
>> files in it that contain a non ascii character. How would I go about
>> doing this?
>>
> 
> How about something like this:
> content = open('file.py').read()
> try:
> content.encode('ascii')
> except UnicodeDecodeError:
> print "file.py contains non-ascii characters"
> 
> 
The next problem will be that non-text files will contain non-ASCII
characters (bytes).  The other 'issue' is that OP didn't say how large
the files were, so .read() might be a problem.

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


Re: Creating a daemon process in Python

2007-02-23 Thread Eirikur Hallgrimsson
I didn't actually write this module.  I believe I found it in a 
discussion in ASPN at Active State.

Thanks for the input, and when I get a chance I will try these alternate 
approaches.  This module has been working fine for me as is--so far.

Eirikur


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


Re: Convert to binary and convert back to strings

2007-02-23 Thread Eric Pederson
Harlin Seritt wrote:

>Hi...
>
>I would like to take a string like 'supercalifragilisticexpialidocius'
>and write it to a file in binary forms -- this way a user cannot read
>the string in case they were try to open in something like ascii text
>editor. I'd also like to be able to read the binary formed data back
>into string format so that it shows the original value. Is there any
>way to do this in Python?
>
>Thanks!
>
>Harlin
>
>  
>

To my mind, the more sensible job you do at programming this the worse 
off you are, unless you use strong encryption.  There are nearly 
infinite approaches, so the random approach you use will be part of the 
"security" of the obfuscation.

OK, I am not really taking this so seriously, but it is a fun question 
(Python makes these minor things fun).  Is there anyway to do this in 
Python?  You bet, so many ways... here's another:

s="""I would like to take a string like 'supercalifragilisticexpialidocius'
and write it to a file in binary forms -- this way a user cannot read
the string in case they were try to open in something like ascii text
editor. I'd also like to be able to read the binary formed data back
into string format so that it shows the original value. Is there any
way to do this in Python?"""

s0=s+"$"
s2="0 ".join([str(ord(c)) for c in s])
s1="".join([chr(int(i[:-1])) for i in s2.split(" 
")[:-1]])+chr(int(s2[-1]))[:-1]

def codeMe(s):
s0=s+"$"
return "0 ".join([str(ord(c)) for c in s0])

def uncodeMe(s):
return "".join([chr(int(i[:-1])) for i in s.split(" 
")[:-1]])+chr(int(s[-1]))[:-1]

def testit(s):
s2=codeMe(s)
s1=uncodeMe(s2)
strings={"original":s, "obfuscated":s2, "decoded":s1}
for k in strings.keys():
print k,":  ","\n",strings[k], "\n\n"
   
testit(s)

-
the obfuscated looks like this:

730 320 1190 1110 1170 1080 1000 320 1080 1050 1070 1010 320 1160 1110 
320 1160 970 1070 1010 320 970 320 1150 1160 1140 1050 1100 1030 320 
1080 1050 1070 1010 320 390 1150 1170 1120 1010 1140 990 970 1080 1050 
1020 1140 970 1030 1050 1080 1050 1150 1160 1050 990 1010 1200 1120 1050 
970 1080 1050 1000 1110 990 1050 1170 1150 390 100 970 1100 1000 320 
1190 1140 1050 1160 1010 320 1050 1160 320 1160 1110 320 970 320 1020 
1050 1080 1010 320 1050 1100 320 980 1050 1100 970 1140 1210 320 1020 
1110 1140 1090 1150 320 450 450 320 1160 1040 1050 1150 320 1190 970 
1210 320 970 320 1170 1150 1010 1140 320 990 970 1100 1100 1110 1160 320 
1140 1010 970 1000 100 1160 1040 1010 320 1150 1160 1140 1050 1100 1030 
320 1050 1100 320 990 970 1150 1010 320 1160 1040 1010 1210 320 1190 
1010 1140 1010 320 1160 1140 1210 320 1160 1110 320 1110 1120 1010 1100 
320 1050 1100 320 1150 1110 1090 1010 1160 1040 1050 1100 1030 320 1080 
1050 1070 1010 320 970 1150 990 1050 1050 320 1160 1010 1200 1160 100 
1010 1000 1050 1160 1110 1140 460 320 730 390 1000 320 970 1080 1150 
1110 320 1080 1050 1070 1010 320 1160 1110 320 980 1010 320 970 980 1080 
1010 320 1160 1110 320 1140 1010 970 1000 320 1160 1040 1010 320 980 
1050 1100 970 1140 1210 320 1020 1110 1140 1090 1010 1000 320 1000 970 
1160 970 320 980 970 990 1070 100 1050 1100 1160 1110 320 1150 1160 1140 
1050 1100 1030 320 1020 1110 1140 1090 970 1160 320 1150 1110 320 1160 
1040 970 1160 320 1050 1160 320 1150 1040 1110 1190 1150 320 1160 1040 
1010 320 1110 1140 1050 1030 1050 1100 970 1080 320 1180 970 1080 1170 
1010 460 320 730 1150 320 1160 1040 1010 1140 1010 320 970 1100 1210 100 
1190 970 1210 320 1160 1110 320 1000 1110 320 1160 1040 1050 1150 320 
1050 1100 320 800 1210 1160 1040 1110 1100 630 36

Of course some overly curious application user may note the pattern of 
"0" endings, strip those off, concatenate the numbers, and try several 
conversions on them, at which point they may figure this out-  and 
contact you to gloat that they have hacked the file.

That's when you recruit them onto your development team and give them 
some real work.  :-)

Have fun


EP

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


Rational numbers

2007-02-23 Thread Martin Manns
Hi,

I am starting to use rationals and since I found no batteries included,
I tried out the mxNumber package.

However, I get strange warnings on comparison operations
(which however seem to yield correct results):

---
$ python
Python 2.4.3 (#1, Jan 15 2007, 15:46:19) 
[GCC 4.1.1 (Gentoo 4.1.1-r3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from mx.Number import *
>>> a=Rational(0,1)
>>> a
0/1
>>> str(a)
'0.0'
>>> b=-50
>>> b
-50L
>>> a==b
__main__:1: RuntimeWarning: tp_compare didn't return -1, 0 or 1
False
>>> 
---

How do I get rid of these warnings?

Is there any rational number library around that
1) is comparably fast for large denominators
2) allows deriving types from Rationals without wrapping?

Regards

Martin

P.S. The respective mailing list does not like me, so that I try my
luck here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding non ascii characters in a set of files

2007-02-23 Thread John Machin
On Feb 24, 2:12 am, "Peter Bengtsson" <[EMAIL PROTECTED]> wrote:
> On Feb 23, 2:38 pm, [EMAIL PROTECTED] wrote:
>
> > Hi,
>
> > I'm updating my program to Python 2.5, but I keep running into
> > encoding problems. I have no ecodings defined at the start of any of
> > my scripts. What I'd like to do is scan a directory and list all the
> > files in it that contain a non ascii character. How would I go about
> > doing this?
>
> How about something like this:
> content = open('file.py').read()
> try:
> content.encode('ascii')
> except UnicodeDecodeError:
> print "file.py contains non-ascii characters"


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


Re: CSV(???)

2007-02-23 Thread John Machin
On Feb 23, 10:11 pm, David C. Ullrich <[EMAIL PROTECTED]>
wrote:
> Is there a csvlib out there somewhere?

I can make available the following which should be capable of running
on 1.5.2 -- unless they've suffered bitrot :-)

(a) a csv.py which does simple line-at-a-time hard-coded-delimiter-etc
pack and unpack i.e. very similar to your functionality *except* that
it doesn't handle newline embedded in a field. You may in any case be
interested to see a different way of writing this sort of thing: my
unpack does extensive error checking; it uses a finite state machine
so unexpected input in any state is automatically an error.

(b) an extension module (i.e. written in C) with the same API. The
python version (a) imports and uses (b) if it exists.

(c) an extension module which parameterises everything including the
ability to handle embedded newlines.

The two extension modules have never been compiled & tested on other
than Windows but they both should IIRC be compilable with both gcc
(MinGW) and the free Borland 5.5 compiler -- in other words vanilla C
which should compile OK on Linux etc.

If you are interested in any of the above, just e-mail me.

>
> And/or does anyone see any problems with
> the code below?
>
> What csvline does is straightforward: fields
> is a list of strings. csvline(fields) returns
> the strings concatenated into one string
> separated by commas. Except that if a field
> contains a comma or a double quote then the
> double quote is escaped to a pair of double
> quotes and the field is enclosed in double
> quotes.
>
> The part that seems somewhat hideous is
> parsecsvline. The intention is that
> parsecsvline(csvline(fields)) should be
> the same as fields. Haven't attempted
> to deal with parsecsvline(data) where
> data is in an invalid format - in the
> intended application data will always
> be something that was returned by
> csvline.

"Always"? Famous last words :-)

> It seems right after some
> testing... also seems blechitudinous.

I agree that it's bletchworthy, but only mildly so. If it'll make you
feel better, I can send you as a yardstick csv pack and unpack written
in awk -- that's definitely *not* a thing of beauty and a joy
forever :-)

I presume that you don't write csvline() output to a file, using
newline as a record terminator and then try to read them back and pull
them apart with parsecsvline() -- such a tactic would of course blow
up on the first embedded newline. So as a matter of curiosity, where/
how are you storing multiple csvline() outputs?

>
> (Um: Believe it or not I'm _still_ using
> python 1.5.7. So comments about iterators,
> list comprehensions, string methods, etc
> are irrelevent. Comments about errors in
> the algorithm would be great. Thanks.)

1.5.7 ?
[big snip]

Cheers,
John

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


Re: Module trouble [newbie]

2007-02-23 Thread Goldfish
On Feb 23, 6:44 am, Boris Ozegovic <[EMAIL PROTECTED]>
wrote:
> Can somebody explaint this to me:
>
> I have module a.py
> A = 100
> import b
> print "A printing"
> print "B is %s" % b.B
>
> and module b.py
> B = 2000
> import a
> print "B printing"
> print "A is %s" % a.A
>
> I thought that output would be:
> B printing
> A is 100
> A printing
> B is 2000
>
> Because import b would execute b.py, and in b.py line "import a" would be
> ignored, but my output is:
>
> >>> import a
>
> 100
> A printing
> B is 100
>
> ??
>
> :)
>
> --http://www.nacional.hr/articles/view/23894/23

a.py
===
A = 100
import b
print "A printing"
print "B is %s" % b.B

b.py
===
B = 2000
import a
print "B printing"
print "A is %s" % a.A

Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import a
B printing
A is 100
A printing
B is 2000
>>>

Looks okay to me.

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


Re: Finding non ascii characters in a set of files

2007-02-23 Thread Peter Bengtsson
On Feb 23, 2:38 pm, [EMAIL PROTECTED] wrote:
> Hi,
>
> I'm updating my program to Python 2.5, but I keep running into
> encoding problems. I have no ecodings defined at the start of any of
> my scripts. What I'd like to do is scan a directory and list all the
> files in it that contain a non ascii character. How would I go about
> doing this?
>

How about something like this:
content = open('file.py').read()
try:
content.encode('ascii')
except UnicodeDecodeError:
print "file.py contains non-ascii characters"


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


With PIL... paste image on top of other with dropshadow

2007-02-23 Thread Peter Bengtsson
I love the dropshadow effect I managed to make with this recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/474116

Here's what it can look like:
http://www.peterbe.com/test/188-tequilacat.2.jpg

It takes a background as a parameter but it's just a colour. What I
want is to put the image on top of another but doing so with a
dropshadow. I guess the solution would be something like putting the
dropshadow on the first image without a background colour but instead
a transparant background and then paste this onto another image.

I just have no idea to do that?

The final result I want is something like programmtically fake that a
picture (the foreground) is hanging on a wall (the background) with a
dropshadow so that it looks like it's hanging in a inch-deep frame.

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


Re: Creating a daemon process in Python

2007-02-23 Thread Jean-Paul Calderone
On Fri, 23 Feb 2007 08:30:07 -0600, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
>Eirikur Hallgrimsson <[EMAIL PROTECTED]> wrote:
>
> [snip]
>
>>  if (not os.fork()):
>>  # hang around till adopted by init
>>  ppid = os.getppid()
>>  while (ppid != 1):
>>  time.sleep(0.5)
>>  ppid = os.getppid()
>
>Why do you need hang around until adopted by init?  I've never see
>that in a daemonize recipe before?
>

I think it simplifies some signal handling logic.  I'd never seen it before
in a deamonizer either, but it caught my eye in this one.  I haven't had time
to investigate further though.  I hope Eirikur will explain. :)

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


Re: What is the best queue implemetation in Python?

2007-02-23 Thread Szabolcs Nagy
> For that purpose I have used the good deque that you can find in
> collections in the standard library. It's very good for queues, and
> it's a bit faster than regular lists for stacks too.

you mean *much* faster (since a list is a reference array so pop(0) is
O(n) operation)

never use a list as queue if len(queue) > 1

=== benchmark

$ time ./deque_queue.py
34359607296

real0m0.286s
user0m0.264s
sys 0m0.016s

$ time ./list_queue.py
34359607296

real1m20.915s
user1m18.649s
sys 0m0.396s


=== the sources

--- deque_queue.py:
#!/usr/bin/python2.5

from collections import deque

def f(n):
sum = 0
queue = deque()
for i in range(n):
queue.append(i)
while queue:
sum += queue.popleft()
print sum

if __name__=='__main__':
f(1<<18)

--- list_queue.py:
#!/usr/bin/python2.5

def f(n):
sum = 0
queue = list()
for i in range(n):
queue.append(i)
while queue:
sum += queue.pop(0)
print sum

if __name__=='__main__':
f(1<<18)

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


Finding non ascii characters in a set of files

2007-02-23 Thread bg_ie
Hi,

I'm updating my program to Python 2.5, but I keep running into
encoding problems. I have no ecodings defined at the start of any of
my scripts. What I'd like to do is scan a directory and list all the
files in it that contain a non ascii character. How would I go about
doing this?

Thanks,

Barry.

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


Re: Creating a daemon process in Python

2007-02-23 Thread Nick Craig-Wood
Eirikur Hallgrimsson <[EMAIL PROTECTED]> wrote:
>  def daemonize():
>  if (not os.fork()):
>  # get our own session and fixup std[in,out,err]
>  os.setsid()
>  sys.stdin.close()
>  sys.stdout = NullDevice()
>  sys.stderr = NullDevice()

That doesn't close the underlying file descriptors...

Here is another method which does :-

  null = os.open(os.devnull, os.O_RDWR)
  os.dup2(null, sys.stdin.fileno())
  os.dup2(null, sys.stdout.fileno())
  os.dup2(null, sys.stderr.fileno())
  os.close(null)


>  if (not os.fork()):
>  # hang around till adopted by init
>  ppid = os.getppid()
>  while (ppid != 1):
>  time.sleep(0.5)
>  ppid = os.getppid()

Why do you need hang around until adopted by init?  I've never see
that in a daemonize recipe before?

>  else:
>  # time for child to die
>  os._exit(0)
>  else:
>  # wait for child to die and then bail
>  os.wait()
>  sys.exit()

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


compile python with sqlite3

2007-02-23 Thread Nader Emami
L.S.,

I have to compile (install) locally Python 2.5, because I don't have 
'root' permission. Besides I would use 'sqlite3' as a database for 
TurboGears/Django. I have installed 'sqlite3' somewhere on my Linux 
(/path/to/sqlite'). What do I have to do if I want to compile 'Python' 
with 'sqlite3'? I would appreciate if somebody tells me to solve this 
problem.

With regards,
Nader
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Module trouble [newbie]

2007-02-23 Thread Boris Ozegovic
Diez B. Roggisch wrote:

> I use it sometimes myself, to avoid otherwise circular imports. 

Circular imports are the reason why I have module issues.  Last question:
if I put modules in some package and then try to import one I get
"AttributeError: 'module' object has no attribute 'a'

Code is:

a.py
A = 756
import someFolder.b as b
print "A printing"
print "B is %s" % b.B

b.py
B = 2000
import someFolder.a as a
print "B printing"
print "A is %s" % a.A

How can I do circular imports if I use packages?  Darn.  I don't remeber
this module gothcas when reading Learning Python.

-- 
http://www.nacional.hr/articles/view/23894/23
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Local class variables? (mod_python problem)

2007-02-23 Thread Diez B. Roggisch
> It is not desirable for the class variable to keep incrementing outside
> of invocations of '__main__', as is the case when it is loaded under
> mod_python under apache2 on linux.
> 

I'm still not clear on what you want to accomplish. In the end it boils down
to who is supposed to share that information in the variables, or in other
words: which scope has it.

Is it per request? Then using some thread-local storage would be in order,
or "abusing" a possible request-object.

Is it per user, over several requests? Then you need a session-mechanism.

Is it per application, for several users, over several requests? Then your
approach is ok, but needs guarding against concurrrent access using
threading.Lock for example. However, I presume that is not the desired
usecase, from what I can extract from your posts I presume it's case two.

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


Re: jython import search path

2007-02-23 Thread Diez B. Roggisch
> Accepted strategy? It doesn't seem very portable. It assumes that
> everyone puts their library
> modules in the exact same place. Or do they just figure that changing
> the sys.path.append
> line is easy enough?

Portability has nothing to do with it. If you arrange your project in a way
that these paths can be figured out at runtime, it's fine.

If not, you might need some installation routine that will figure them out
when installing the software, hard-coding such paths in some way (as
parameter lists or whatsoever)
 
>> java -Dpython.path=
> 
> I'm not using Java at all. I just want to generate Java bytecode for
> purposes of code analysis
> by existing tools.

If you are using jython, you are using java. 

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


Re: Finding a tuple in a tuple

2007-02-23 Thread Duncan Booth
Philipp Pagel <[EMAIL PROTECTED]> wrote:

> Another way to go instead of using sets, although probably less elegant:
> 
 True in [x in t1 for x in t2]
> True
 True in [x in t1 for x in t3]
> True
 True in [x in t1 for x in t4]
> False
 True in [x in t1 for x in t5]
> False

Slightly more elegant for Python 2.5 users:

>>> any(x in t1 for x in t2)
True
>>> any(x in t1 for x in t3)
True
>>> any(x in t1 for x in t4)
False
>>> any(x in t1 for x in t5)
False


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


Re: Module trouble [newbie]

2007-02-23 Thread Diez B. Roggisch
Boris Ozegovic wrote:

> Diez B. Roggisch wrote:
> 
>> Are you sure the above is what you really used for your test? Because
>> your output features a single 100, which the above lacks a
>> print-statement for.
> 
> Yeah, I cancelled the message, but synchronization allready happened.  :)
> 
> Problem was in some other place.
> 
> One more question: is calling import inside function definition poor
> design?  e.g.
> 
> def foo():
>doSomething:
>import someModule
>someModule.doSomethin

I use it sometimes myself, to avoid otherwise circular imports. However, I
don't like it very much. Try to go without it I'd say, but that is just a
gut-feeling.

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


python float-point problem

2007-02-23 Thread unidevel
I just compiled python 2.4.2 using openembedded for my zaurus C750.
I test some comparison for float-pointing number, for example:
3.1<3.0 True
3.2<3.0 True
3.3<3.0 False
8.4<4.0 True
I use the cross compiler that compiled python to make a simple C
program,
got correct results.
Anyone have some idea about that?

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

Re: Module trouble [newbie]

2007-02-23 Thread Boris Ozegovic
Diez B. Roggisch wrote:

> Are you sure the above is what you really used for your test? Because your
> output features a single 100, which the above lacks a print-statement for.

Yeah, I cancelled the message, but synchronization allready happened.  :)

Problem was in some other place.

One more question: is calling import inside function definition poor
design?  e.g.

def foo():
   doSomething:
   import someModule
   someModule.doSomethin

-- 
http://www.nacional.hr/articles/view/23894/23
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >