P3D visualization package

2009-12-21 Thread Massimo Di Pierro

http://www.web2py.com/p3d

A Python library that generates processing.js code for 3D rendering  
and visualization including a pure python algorithm for computing iso- 
surfaces from VTK files. The generated 3D objects can rotated in the  
browser. Requires a browser with canvas support, jquery and  
processing.js.


This is implemented in modules/p3d.py and works with any python web  
framework including web2py, Django and Pylons.


License BSD.

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

   Support the Python Software Foundation:
   http://www.python.org/psf/donations/


ANN: eGenix mx Base Distribution 3.1.3

2009-12-21 Thread eGenix Team: M.-A. Lemburg


ANNOUNCING

eGenix.com mx Base Distribution

   Version 3.1.3 for Python 2.3 - 2.6

   Open Source Python extensions providing
 important and useful services
for Python programmers.

This announcement is also available on our web-site for online reading:
http://www.egenix.com/company/news/eGenix-mx-Base-Distribution-3.1.3-GA.html



ABOUT

The eGenix.com mx Base Distribution for Python is a collection of
professional quality software tools which enhance Python's usability
in many important areas such as fast text searching, date/time
processing and high speed data types.

The tools have a proven record of being portable across many Unix and
Windows platforms. You can write applications which use the tools on
Windows and then run them on Unix platforms without change due to the
consistent platform independent interfaces.

Contents of the distribution:

 * mxDateTime - Date/Time Library for Python
 * mxTextTools - Fast Text Parsing and Processing Tools for Python
 * mxProxy - Object Access Control for Python
 * mxBeeBase - On-disk B+Tree Based Database Kit for Python
 * mxURL - Flexible URL Data-Type for Python
 * mxUID - Fast Universal Identifiers for Python
 * mxStack - Fast and Memory-Efficient Stack Type for Python
 * mxQueue - Fast and Memory-Efficient Queue Type for Python
 * mxTools - Fast Everyday Helpers for Python

All available packages have proven their stability and usefulness in
many mission critical applications and various commercial settings all
around the world.

For more information, please see the distribution page:

http://www.egenix.com/products/python/mxBase/



NEWS

The 3.1.3 release of the eGenix mx Base Distribution is the latest
release of our open-source Python extensions.

The new version addresses a serious problem with mxBeeBase on
BSD-based platforms such as FreeBSD and Mac OS X. We encourage all
users to upgrade to this new release.

As always, we are providing pre-built binaries for all supported
platforms: Windows 32-bit, Linux 32/64-bit, FreeBSD 32/64-bit, Mac OS X
32-bit Intel and PPC.

Whether you are using a pre-built package or the source distribution,
installation is a simple python setup.py install command in all
cases. The only difference is that the pre-built packages do not
require a compiler to be installed.

For a list of changes, please refer to the eGenix mx Base Distribution
change log at

http://www.egenix.com/products/python/mxBase/changelog.html

and the change logs of the various included Python packages.



DOWNLOADS

The download archives and instructions for installing the packages can
be found on the eGenix mx Base Distribution page:

http://www.egenix.com/products/python/mxBase/



LICENSE

The eGenix mx Base package is distributed under the eGenix.com Public
License 1.1.0 which is an Open Source license similar to the Python
license. You can use the packages in both commercial and non-commercial
settings without fee or charge.

The package comes with full source code



SUPPORT

Commercial support for this product is available from eGenix.com.
Please see

http://www.egenix.com/services/support/

for details about our support offerings.

Enjoy,
-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Dec 21 2009)
 Python/Zope Consulting and Support ...http://www.egenix.com/
 mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
 mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


::: Try our new mxODBC.Connect Python Database Interface for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
   http://www.egenix.com/company/contact/
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations/


ANN: PyBindGen 0.13 released

2009-12-21 Thread Gustavo Carneiro
PyBindGen is a Python module that is geared to generating C/C++ code that
binds a C/C++ library for Python. It does so without extensive use of either
C++ templates or C pre-processor macros. It has modular handling of C/C++
types, and can be easily extended with Python plugins. The generated code is
almost as clean as what a human programmer would write.

It can be downloaded from:

http://code.google.com/p/pybindgen/

Bug reports should be filed here:

https://bugs.launchpad.net/ https://bugs.launchpad.net/pybindgen
pybindgen https://bugs.launchpad.net/pybindgen

https://bugs.launchpad.net/pybindgenDocumentation:

http://packages.python.org/PyBindGen/

NEWS:

- Lots of small bug fixes

- Custodian/ward-style memory management works better now

- Add 'reference_existing_object' and 'return_interal_reference'
  options for pointer/reference return values

- New Sphinx based documentation
-- 
Gustavo J. A. M. Carneiro
INESC Porto, Telecommunications and Multimedia Unit
The universe is always one step beyond logic. -- Frank Herbert
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations/


PyTrie 0.1

2009-12-21 Thread George Sakkis
I'm pleased to announce the first release of PyTrie, a pure Python
implementation of the trie (prefix tree) data structure [1].

Tries extend the mapping interface with methods that facilitate
finding the keys/values/items for a given prefix, and vice versa,
finding the prefixes (or just the longest one) of a given key K.

Project links:
- PyPI entry: http://pypi.python.org/pypi/PyTrie
- Documentation: http://packages.python.org/PyTrie
- Repository: http://bitbucket.org/gsakkis/pytrie

Regards,
George


[1] http://en.wikipedia.org/wiki/Trie
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations/


Re: Creating Classes

2009-12-21 Thread Steven D'Aprano
On Sun, 20 Dec 2009 11:11:54 -0500, Steve Holden wrote:

 Dave Angel wrote:
 [...]
 We were talking about 2.x   And I explicitly mentioned 3.x because if
 one develops code that depends on old-style classes, they'll be in
 trouble with 3.x, which has no way to specify old-style classes.  In
 3.x, all classes are new-style.  And although it'll no longer matter
 whether you specify (object), it doesn't do any harm.  As I said, it's
 a good habit for a beginner to get into when defining classes.
 
 I maintain that this almost-cargo-cult belief over-complicates things
 for language beginners. How long do you have to be using Python before
 you make your first super() call? 

That depends on who you are and what you're doing.

Are you a n00b who has never programmed before?

An old Fortran or Pascal dinosaur who doesn't like that new fangled 
object stuff?

A former Java OO guru whose class hierarchies are 85 classes deep on 
average?

Someone who just discovered multiple inheritance and now everything looks 
like a nail?



 How many programs behave differently
 with old-style vs. new-style classes?

Any program that uses properties will behave differently.

__getattribute__ and __slots__ will not work at all in old-style classes.

There will be subtle differences, e.g. isinstance(type, MyClass) will 
return False if MyClass is old-style. The default repr and str of 
instances will look different (which may or may not count as different 
behaviour). Speed and efficiency will be different.

So I guess the correct answer to your question is All of them. The 
interesting question is, what's the magnitude of the differences?

The advice I used to give was, unless you care about the difference, 
always inherit from object because new-style classes are the way of the 
future. Unfortunately, it is no longer obvious whether something in 
isolation is a new-style or old-style class, as you have to know the 
target Python version.




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


Re: Windows, IDLE, __doc_, other

2009-12-21 Thread Alf P. Steinbach

* Alf P. Steinbach:

* W. eWatson:
When I use numpy.__doc__ in IDLE under Win XP, I get a heap of words 
without reasonable line breaks.


\nNumPy\n=\n\nProvides\n  1. An array object of arbitrary 
homogeneous items\n  2. Fast mathematical operations over arrays\n  3. 
Linear Algebra, Fourier Transforms, Random Number

...

Is there a way to get this formated properly.


print( numpy.__doc__ )

(For Python 2.x you can and best should leave out the parenthesis)



If I use dir(numpy), I get yet a very long list that starts as:
['ALLOW_THREADS', 'BUFSIZE', 'CLIP', 'DataSource', 'ERR_CALL', 
'ERR_DEFAULT', 'ERR_DEFAULT2', 'ERR_IGNORE', 'ERR_LOG', 'ERR_PRINT', 
'ERR_RAISE', 'ERR_WARN', 'FLOATING_POINT_SUPPORT', 'FPE_DIVIDEBYZERO', 
'FPE_INVALID', 'FPE_OVERFLOW', 'FPE_UNDERFLOW', 'False_', 'Inf', 
'Infinity', 'MAXDIMS', 'MachAr', 'NAN', 'NINF', 'NZERO', 'NaN', 
'PINF', 'PZERO', 'PackageLoader', 'RAISE', 'RankWarning', 
'SHIFT_DIVIDEBYZERO', 'SHIFT_INVALID', 'SHIFT_OVERFLOW', 
'SHIFT_UNDERFLOW', 'ScalarType', 'Tester', 'True_', 
'UFUNC_BUFSIZE_DEFAULT'

...
I see this might be a dictionary. What can I do to make it more 
readable or useful, or is that it? Is there a more abc as in Linux?


Something like (off the cuff, fix if eroRs!)

  for name in dir[numpy]:
  if name.startswith( _ ):
  pass
  else:
  doc_lines = getattr( numpy, name ).__doc__.split()


Uh oh, 'splitlines' not 'split' !



  print( format( {0:25} {1}.format( name, doc_lines[0] ) )

Should ideally work whether you use Python 2.x or 3.x.

But as mentioned I just typed that in so there may be eroRs.


It the IDLE shell, it's not possible to retrieve lines entered earlier 
without copying them. Is there an edit facility?


I suggest you download a programmers' editor (like Notepad++ or PsPad) 
for programming work and use the basic Python interpreter for 
interactive work. The basic interpreter lives in a standard Window 
console window where you can use up and down arrow keys, F8 completion, 
F7 for list of earlier commands, etc (as documented by the doskey 
command in the Windows command interpreter). Just forget IDLE in 
windows: while Windows console windows are something from the middle 
ages, IDLE seems to stem from a period before that! g



Cheers  hth.,

- Alf

PS: Shameless plug: take a look at url: 
http://tinyurl.com/programmingbookP3, it's for Windows.

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


Re: tkinter import problem

2009-12-21 Thread Gabriel Genellina
En Sun, 20 Dec 2009 02:04:17 -0300, harish anand nsharish@gmail.com  
escribió:



I have Mandriva 2010.0 in my laptop.
I installed python3.1 from the repository.
But i am unable to import tkinter in python console.
When I try to import tkinter I get the following error,
`ImportError : No module named _tkinter`

Am I doing something wrong?


I don't know Mandriva, but probably tkinter comes from a separate package  
(like tkinter, python-tkinter, python-tk, or something like that)


--
Gabriel Genellina

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


Re: PyArg_ParseTupleAndKeywords in Python3.1

2009-12-21 Thread Gabriel Genellina

En Sat, 19 Dec 2009 07:36:59 -0300, Emeka emekami...@gmail.com escribió:

Okay if that is the case, why do we need it? By having int a = 65, b =  
66 ,

why should we also have *kwlist[]?



static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds)
{
   int a=65, b=66;
   char *kwlist[] = {a, b, NULL};
   if (!PyArg_ParseTupleAndKeywords(args, kwrds, |CC, kwlist, a,
b))
   return NULL;
   return Py_BuildValue((CC), a, b);
}


It's not related to default values. foo(x=30) should raise an error; the
allowed parameter names are only 'a' and 'b', not 'x'.

--
Gabriel Genellina

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


Re: Anybody use web2py?

2009-12-21 Thread Bruno Desthuilliers

AppRe Godeck a écrit :
(snip)
Thanks for your replies, I was hoping to hear from some django people as 
well. Especially if you choose django over web2py, and why.


I don't know what a django people is - but if you mean django core 
developper, I'm not one of them. Now wrt while I use Django instead of 
web2py, the answer is quite simple: web2py didn't exist when I started 
using Django !-)


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


Re: Anybody use web2py?

2009-12-21 Thread Bruno Desthuilliers

Thadeus Burgess a écrit :
(snip)

Spend one
day working on a simple django application, polls, blog, image
gallery, family pet tree, you name it. Then take the next day, and
write the same application with web2py, and you decide. In the end,
both are tools and you need to figure out what is best for YOU.


The problem is not how easy it makes to write a *simple* (should I say 
braindead ?) dummy test app, but how easy - or even possible -it makes 
writing and maintaining a *real-world* complex application.

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


Re: Anybody use web2py?

2009-12-21 Thread Lacrima
On Dec 20, 1:35 am, mdipierro massimodipierr...@gmail.com wrote:
 Errata. I said The dal supports transactions where I meant the dal
 supports migrations.
 Of course it also supports transactions as well as distributed
 transactions.


Sorry, if this is not related to this topic.
Does web2py support distributed transactions with Google App Engine
Datastore?
-- 
http://mail.python.org/mailman/listinfo/python-list


Vectorized laziness 2

2009-12-21 Thread Bearophile
Do you remember my post about Vectorized laziness that was fully
ignored by everyone here?
http://groups.google.com/group/comp.lang.python/browse_thread/thread/2637aafa1274629d/

The latest Clojure v.1.1 has implemented the same idea, they are named
Chunked Sequences:
http://www.infoq.com/news/2009/12/clojure-11-rc1-transients
See:
http://clojure.googlegroups.com/web/chunks.pdf

(I know they can have some problematic corner cases.)

Bye and be well,
bearophile
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: numpy performance and random numbers

2009-12-21 Thread sturlamolden
On 20 Des, 01:46, Lie Ryan lie.1...@gmail.com wrote:

 Not necessarily, you only need to be certain that the two streams don't
 overlap in any reasonable amount of time. For that purpose, you can use
 a PRNG that have extremely high period like Mersenne Twister and puts
 the generators to very distant states.

Except there is no way to find two very distant states and prove they
are distant enough.

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


Re: Anybody use web2py?

2009-12-21 Thread Bruno Desthuilliers

mdipierro a écrit :

On Dec 19, 12:42 am, AppRe Godeck a...@godeck.com wrote:

Just curious if anybody prefers web2py over django, and visa versa. I
know it's been discussed on a flame war level a lot. I am looking for a
more intellectual reasoning behind using one or the other.


Of course I am the most biased person in the world on this topic


Indeed !-)



- In web2py models and controllers are not modules. They are not
imported. They are executed.


I assume you mean executed in an environment defined by the framework...


This means you do not need to import
basic web2py symbols. They are already defined in the environment that
executes the models and controllers 


Ok. As far as I'm concerned : show stops here.


(like in Rails). This also means
you do not need to restart the web server when you edit your app.


The dev server that comes with Django do the autorestart thing. And you 
*don't* edit yoour app directly on the production server, do you ?



- You have a web based IDE with editor,


Why should I care ? I have a way better development environment on my 
own box.



some conflict resolution,
Mercurial integration,


What if use something else than mercurial ?


ticketing system,


...doesn't belong to the framework. FWIW, I already have a ticketing 
system that's language/techno agnostic, thanks.




- The DAL supports transactions. It means it will create and/or ALTER
tables for you as your model changes. 


Err... how does schema changes relates to transactions ???

Now FWIW, when my schema do change, the create/alter table code is 
usually the most trivial part - there are quite a few other things to 
do, that no framework will ever be abale to guess. IOW, you *do* have to 
write a migration script anyway.




- The DAL has partial support for some legacy databases that do not
have an 'id' auto increment primary key.


Django's ORM has full support for tables that don't use an auto_id key.



Anyway, I think both system are great. Spend 15 minutes (no more) with
each to make up your mind, and stick with it.


Once again, while doing a quick dummy test app can give you a first 
general feel of the tool, it means nothing wrt/ complex real-world 
applications.


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


Re: Anybody use web2py?

2009-12-21 Thread Bruno Desthuilliers

Anand Vaidya a écrit :

On Dec 19, 2:42 pm, AppRe Godeck a...@godeck.com wrote:

Just curious if anybody prefers web2py over django, and visa versa. I
know it's been discussed on a flame war level a lot. I am looking for a
more intellectual reasoning behind using one or the other.


Hi,

I am not very familiar with Django, anyway, my reasons for selecting
web2py are:

- I believe Django naturally fits in to a publishing type of
application. 


I just don't get why so many people have this antipattern... None of the 
 projects I did with Django were on the CMS side. Django is *NOT* a 
CMS-growned-into-a-framework in any way, it's a web development 
framework, period.


Don't believe, check.



web2py seems to be more focussed on being a front-end to
applications not so much for CMS type or newspaper type publishing.


Please provide *any* evidence of your (plain wrong) assertions and 
assumptions...


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


Re: AttributeError: logging module bug ?

2009-12-21 Thread Peter

On 12/21/2009 08:35 AM, Gabriel Genellina wrote:

En Sat, 19 Dec 2009 00:18:26 -0300, Peter vm...@mycircuit.org escribió:

This was somehow unexpected for me, since in a module using 
logger.py, I could use either import:


from mylogger import logger  # without package name

or

from of.mylogger import logger  # with package name

but this does not seem to work for the class specification in the 
config file (only the former works).


Then you have a big problem with the Python search path (sys.path): you
should *not* have two different (absolute) ways to refer to the same
module, ever.
If of is a package, it should not be listed in sys.path

Thanks a lot for this helpful advice, in fact the package/module system 
is for me ( coming from compiled languages with libaries ) the most 
unintuitive thing in python.


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


Re: [ANN] pylint 0.19 / astng 0.19.2

2009-12-21 Thread Jean-Michel Pichavant

Sylvain Thénault wrote:

On 18 décembre 18:24, Jean-Michel Pichavant wrote:
  

Sylvain Thénault wrote:


Hi,

I'm very pleased to announce the release of pylint 0.19 / astng 0.19.2 release!

More information / download  on http://www.logilab.org/project/pylint/0.19.0.

This is a community release, including the work we've done during the pylint
bug day [1] and patches mostly from James Lingard and Vincent Ferotin.

Many thanks to James Lingard which provided two long waited features:

* check of function call arguments
* check string interpolation consistency


So, happy christmas, enjoy!

[1] http://www.logilab.org/blogentry/19260
  

I have troubles after updating pylint:

easy_install pylint -U --install-dir
/opt/tools/python/python2.3/site-packages



pylint
  

 File 
/opt/tools/python/python2.3/site-packages/logilab_astng-0.19.2-py2.5.egg/logilab/astng/infutils.py,
line 28, in module
   from logilab.astng._nodes import Proxy_, List, Tuple, Function,
If, TryExcept
ImportError: No module named _nodes

There is no _nodes.py file within the egg. Has anyone experienced
the same issue ?



yep someone else on the list have the same pb. I think I've identified it:

  python setup.py register sdist upload

*doesn't* regenerate MANIFEST if one is found... So packages uploaded to pypi 
had some missing files. Should be fixed now, sorry for this pb.
  

Works fine by now.
Thanks for providing such great tool.

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


use mudflap with python extensions?

2009-12-21 Thread Neal Becker
Is it possible to build python extensions using gcc's -fmudflap to check 
memory access?  I'm not real familiar with mudflap usage, not sure if it 
works on building shared objects.  Perhaps it requires a rebuilt python 
main?  Hopefully not.

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


[no subject]

2009-12-21 Thread petro



--
Petro Khoroshyy
Institute of Biophysics
Biological Research Center of the
Hungarian Academy of Sciences
Temesvari krt. 62, P.O.Box 521
Szeged, Hungary, H-6701



This message was sent using IMP, the Internet Messaging Program.


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


[no subject]

2009-12-21 Thread petro



--
Petro Khoroshyy
Institute of Biophysics
Biological Research Center of the
Hungarian Academy of Sciences
Temesvari krt. 62, P.O.Box 521
Szeged, Hungary, H-6701



This message was sent using IMP, the Internet Messaging Program.


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


Re: Moving from PHP to Python. Is it Possible

2009-12-21 Thread Bruno Desthuilliers

AppRe Godeck a écrit :

On Mon, 14 Dec 2009 12:25:16 +0100, Bruno Desthuilliers wrote:


r0g a écrit :

Bruno Desthuilliers wrote:

Sancar Saran a écrit :
(snip)

My problem is with PHP syntax and performance.  I'm just trying to
replicate my recepies in python...

Python is not PHP, and trying to write PHP in Python won't buy you
much except pain and frustration.


I think people are being a little harsh here. Replicating exactly what
PHP code does on a micro level i.e. line by line is probably a bad idea
but for all we know a lot of the macro level stuff might be fine, or
mostly fine i.e. structures, algorithms, classes and functions etc.

I was talking about trying to replicate PHP's execution model and idioms
in Python - the framework part -, not about application specific
algos, data structures etc.


Try web2py I think you will surprise yourself with its simplicity and 
speed :)


I don't like what I've seen from web2py, thanks. Also and FWIW, I don't 
see how it relates to the OP ?

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


Regex help needed!

2009-12-21 Thread Oltmans
Hello,. everyone.

I've a string that looks something like

lksjdfls div id ='amazon_345343' kdjff lsdfs /div sdjfls div id
=   amazon_35343433sdfsd/divdiv id='amazon_8898'welcome/div


From above string I need the digits within the ID attribute. For
example, required output from above string is
- 35343433
- 345343
- 8898

I've written this regex that's kind of working
re.findall(\w+\s*\W+amazon_(\d+),str)

but I was just wondering that there might be a better RegEx to do that
same thing. Can you kindly suggest a better/improved Regex. Thank you
in advance.
-- 
http://mail.python.org/mailman/listinfo/python-list


difflib get_close_matches improvement?

2009-12-21 Thread Neal Becker
difflib.get_close_matches looks useful.  But, I don't see where it defines 
'close'.  Besides that, wouldn't it be much more useful if one could supply 
their own distance metric?

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


Re: Regex help needed!

2009-12-21 Thread Umakanth
How about re.findall(r'\d+(?:\.\d+)?',str)

extracts only numbers from any string

~uk

On Dec 21, 4:38 pm, Oltmans rolf.oltm...@gmail.com wrote:
 Hello,. everyone.

 I've a string that looks something like
 
 lksjdfls div id ='amazon_345343' kdjff lsdfs /div sdjfls div id
 =   amazon_35343433sdfsd/divdiv id='amazon_8898'welcome/div
 

 From above string I need the digits within the ID attribute. For
 example, required output from above string is
 - 35343433
 - 345343
 - 8898

 I've written this regex that's kind of working
 re.findall(\w+\s*\W+amazon_(\d+),str)

 but I was just wondering that there might be a better RegEx to do that
 same thing. Can you kindly suggest a better/improved Regex. Thank you
 in advance.

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


Re: Python3.1: gzip encoding with UTF-8 fails

2009-12-21 Thread Antoine Pitrou

Hello,

Le Sun, 20 Dec 2009 17:08:33 +0100, Johannes Bauer a écrit :
 
 #!/usr/bin/python3
 import gzip
 x = gzip.open(testdatei, wb)
 x.write(ä)

The bug here is that you are trying to write an unicode text string (ä)
to a binary file (a gzip file). This bug has been fixed now; in the next 
3.x versions it will raise a TypeError:

 x = gzip.open(testdatei, wb)
 x.write(ä)
Traceback (most recent call last):
  File stdin, line 1, in module
  File /home/antoine/py3k/__svn__/Lib/gzip.py, line 227, in write
self.crc = zlib.crc32(data, self.crc)  0x
TypeError: must be bytes or buffer, not str

You have to encode manually if you want to write text strings to a gzip 
file:

 x = gzip.open(testdatei, wb)
 x.write(ä.encode('utf8'))


Regards

Antoine.


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


Re: Regex help needed!

2009-12-21 Thread mik3
On Dec 21, 7:38 pm, Oltmans rolf.oltm...@gmail.com wrote:
 Hello,. everyone.

 I've a string that looks something like
 
 lksjdfls div id ='amazon_345343' kdjff lsdfs /div sdjfls div id
 =   amazon_35343433sdfsd/divdiv id='amazon_8898'welcome/div
 

 From above string I need the digits within the ID attribute. For
 example, required output from above string is
 - 35343433
 - 345343
 - 8898

 I've written this regex that's kind of working
 re.findall(\w+\s*\W+amazon_(\d+),str)

 but I was just wondering that there might be a better RegEx to do that
 same thing. Can you kindly suggest a better/improved Regex. Thank you
 in advance.

don't need regular expression. just do a split on amazon

 s=lksjdfls div id =\'amazon_345343\' kdjff lsdfs /div sdjfls div id 
 =   amazon_35343433sdfsd/divdiv id=\'amazon_8898\'welcome/div

 for item in s.split(amazon_)[1:]:
...   print item
...
345343' kdjff lsdfs /div sdjfls div id =   
35343433sdfsd/divdiv id='
8898'welcome/div

then find  ' or  indices and do index  slicing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regex help needed!

2009-12-21 Thread Peter Otten
Oltmans wrote:

 I've a string that looks something like
 
 lksjdfls div id ='amazon_345343' kdjff lsdfs /div sdjfls div id
 =   amazon_35343433sdfsd/divdiv id='amazon_8898'welcome/div
 
 
 From above string I need the digits within the ID attribute. For
 example, required output from above string is
 - 35343433
 - 345343
 - 8898
 
 I've written this regex that's kind of working
 re.findall(\w+\s*\W+amazon_(\d+),str)
 
 but I was just wondering that there might be a better RegEx to do that
 same thing. Can you kindly suggest a better/improved Regex. Thank you
 in advance.

 from BeautifulSoup import BeautifulSoup
 bs = BeautifulSoup(lksjdfls div id ='amazon_345343' kdjff lsdfs 
/div sdjfls div id
... =   amazon_35343433sdfsd/divdiv id='amazon_8898'welcome/div)
 [node[id][7:] for node in bs(id=lambda id: id.startswith(amazon_))]
[u'345343', u'35343433', u'8898']

I think BeautifulSoup is a better tool for the task since it actually 
understands HTML.

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


Re: Regex help needed!

2009-12-21 Thread Oltmans
On Dec 21, 5:05 pm, Umakanth cum...@gmail.com wrote:
 How about re.findall(r'\d+(?:\.\d+)?',str)

 extracts only numbers from any string


Thank you. However, I only need the digits within the ID attribute of
the DIV. Regex that you suggested fails on the following string


lksjdfls div id ='amazon_345343' kdjff lsdfs /div sdjfls div id
=   amazon_35343433sdfsd/divdiv id='amazon_8898'welcome/div
hello, my age is 86 years old and I was born in 1945. Do you know that
PI is roughly 3.1443534534534534534





 ~uk

 On Dec 21, 4:38 pm, Oltmans rolf.oltm...@gmail.com wrote:

  Hello,. everyone.

  I've a string that looks something like
  
  lksjdfls div id ='amazon_345343' kdjff lsdfs /div sdjfls div id
  =   amazon_35343433sdfsd/divdiv id='amazon_8898'welcome/div
  

  From above string I need the digits within the ID attribute. For
  example, required output from above string is
  - 35343433
  - 345343
  - 8898

  I've written this regex that's kind of working
  re.findall(\w+\s*\W+amazon_(\d+),str)

  but I was just wondering that there might be a better RegEx to do that
  same thing. Can you kindly suggest a better/improved Regex. Thank you
  in advance.



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


Re: Class variables static by default?

2009-12-21 Thread Daniel Fetchinson
 In python, 'class variable' is a variable that belongs to a class; not
 to the instance and is shared by all instance that belong to the class.

 Surely, since string variables are strings, and float variables are
 floats, and bool variables are bools, and module variables are modules, a
 class variable will be a class and an instance variable will be an
 instance?

 In contrast, 'instance variable' belongs to the instance, and each
 instance can make their instance variables refers to different objects
 than the other instances.

 The usual term used in Python is class attribute and instance
 attribute for the named fields of a class or instance.

 I agree with your interpretation of class variable, but you'll have to
 rewrite parts of the official Python documentation so it becomes
 consistent with it. The phrase class variable appears about 30 times,
 always meaning class attribute; four of them in the Language Reference,
 section Class definitions, where the OP's issue is discussed:

 Programmer’s note: Variables defined in the class definition are class
 variables; they are shared by all instances. To create instance variables,
 they can be set in a method with self.name = value. Both class and
 instance variables are accessible through the notation “self.name“, and an
 instance variable hides a class variable with the same name when accessed
 in this way. Class variables can be used as defaults for instance
 variables, but using mutable values there can lead to unexpected results.
 For new-style classes, descriptors can be used to create instance
 variables with different implementation details.

I don't think Steven cares much, he loves this type of nitpicking and
uber pedantic formulations, but only if he can apply it to other
people's post :)

I found that his posts are generally useful and helpful, one just has
to cut all the nitpicking, an example of which is the one you
responded to, and then everything is fine.

Duck and run.
Daniel

-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regex help needed!

2009-12-21 Thread Umakanth
Ok. how about re.findall(r'\w+_(\d+)',str) ?

returns ['345343', '35343433', '8898', '8898'] !

On Dec 21, 6:06 pm, Oltmans rolf.oltm...@gmail.com wrote:
 On Dec 21, 5:05 pm, Umakanth cum...@gmail.com wrote:

  How about re.findall(r'\d+(?:\.\d+)?',str)

  extracts only numbers from any string

 Thank you. However, I only need the digits within the ID attribute of
 the DIV. Regex that you suggested fails on the following string

 
 lksjdfls div id ='amazon_345343' kdjff lsdfs /div sdjfls div id
 =   amazon_35343433sdfsd/divdiv id='amazon_8898'welcome/div
 hello, my age is 86 years old and I was born in 1945. Do you know that
 PI is roughly 3.1443534534534534534
 

  ~uk

  On Dec 21, 4:38 pm, Oltmans rolf.oltm...@gmail.com wrote:

   Hello,. everyone.

   I've a string that looks something like
   
   lksjdfls div id ='amazon_345343' kdjff lsdfs /div sdjfls div id
   =   amazon_35343433sdfsd/divdiv id='amazon_8898'welcome/div
   

   From above string I need the digits within the ID attribute. For
   example, required output from above string is
   - 35343433
   - 345343
   - 8898

   I've written this regex that's kind of working
   re.findall(\w+\s*\W+amazon_(\d+),str)

   but I was just wondering that there might be a better RegEx to do that
   same thing. Can you kindly suggest a better/improved Regex. Thank you
   in advance.



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


[no subject]

2009-12-21 Thread petro



--
Petro Khoroshyy
Institute of Biophysics
Biological Research Center of the
Hungarian Academy of Sciences
Temesvari krt. 62, P.O.Box 521
Szeged, Hungary, H-6701



This message was sent using IMP, the Internet Messaging Program.


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


For...in statement and generators

2009-12-21 Thread Lucas Prado Melo
Is there a way to send() information back to a generator while using the
for...in statement?

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


Re: switch

2009-12-21 Thread Albert van der Horst
In article pan.2009.12.10.05.47...@remove.this.cybersource.com.au,
Steven D'Aprano  ste...@remove.this.cybersource.com.au wrote:
On Wed, 09 Dec 2009 18:50:29 +, Nobody wrote:

 Compiled languages' switch statements typically require constant labels
 as this enables various optimisations.

Pascal, for example, can test against either single values, enumerated
values, or a range of values:

case n of
   0:
 writeln('zero');
   1, 2:
 writeln('one or two');
   3...10:
 writeln('something between three and ten');
   else writeln('something different');
 end;

This shows where the merit of a switch/case statement lies.
It guarantees both to the compiler and to the human reader
that we are dealing with mutually exclusive and constant cases.
This allows optimisation (c) and verification (h) advantages.

A chain of elif's OTOH doesn't do that. On the top of my toes
I will have to check every line whether the regularity
breaks down.

As regards polymorphism. It is dubious that an inherently
different technique can be consistently and confidently
promoted as an alternative. Sometimes it is, sometimes it
isn't. Polymorphism is IMO promoted for far too much
situations. As a maintenance programmer (being at least
twice as smart as the people who wrote the original code)
I can testify that code can be polymorphed to the point
that it stops working and/or that it practically stops
working and/or that it stops working practically.

I'm the author of PostItFixup assembler. This assembler
manages to assemble code with no control structures
at all. 1]
No IF, no FOR, no WHILE, no CASES. Nothing conditional,
and no looping. How's that for a change?
Although this is truly remarkable and well worth studying,
I will not promote this style of programming as the ultimate
alternative for everything. (And it breaks down at a point,
sure.)

Bottom line: Give to the Caesar what belongs to the Caesar...

Not adding a switch to python is a matter of taste,
good taste as far as I'm concerned.

Adding a switch to C was also good taste, by the way.

--
Steven

Groetjes Albert

--

1] Only in the  error checking there is an IF.
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
alb...@spearc.xs4all.nl =n http://home.hccnet.nl/a.w.m.van.der.horst

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


Re: Anybody use web2py?

2009-12-21 Thread mdipierro
  On Dec 19, 12:42 am, AppRe Godeck a...@godeck.com wrote:
  Just curious if anybody prefers web2py over django, and visa versa. I
  know it's been discussed on a flame war level a lot. I am looking for a
  more intellectual reasoning behind using one or the other.

  Of course I am the most biased person in the world on this topic

 Indeed !-)
  - In web2py models and controllers are not modules. They are not
  imported. They are executed.

 I assume you mean executed in an environment defined by the framework...

yes

  This means you do not need to import
  basic web2py symbols. They are already defined in the environment that
  executes the models and controllers

 Ok. As far as I'm concerned : show stops here.

It is your choice but, why?
Exec/eval is only true distinctive feature of an interpreted language
vs a compiled language.

 (like in Rails). This also means
  you do not need to restart the web server when you edit your app.

 The dev server that comes with Django do the autorestart thing. And you
 *don't* edit yoour app directly on the production server, do you ?

Unfortunately it has happened.
In my experience the distinction between development and production is
fiction.

  - You have a web based IDE with editor,

 Why should I care ? I have a way better development environment on my
 own box.

I only use emacs. I do not use the web based IDE much myself but I
found it really helps in learning how to use the framework.

  some conflict resolution,
  Mercurial integration,

 What if use something else than mercurial ?

You can use any version control you want, the same way you would in
Django. web2py itself is version controlled in both bazaar and
mercurial. The only think about mercurial is that, if you have it
installed, the web based IDE lets you commit at the click on a
button.

  ticketing system,

 ...doesn't belong to the framework. FWIW, I already have a ticketing
 system that's language/techno agnostic, thanks.

Perhaps we are not talking about the same thing. if an error occurs in
a web2py application and I want: 1) notify the user, 2) assign the
user a ticket number; 3) log the error in the framework; 4) allow
administrator to browse past error logs; I think this belongs to the
framework else it gets clunky. Web2py tickets are out of the box and
always on.

  - The DAL supports transactions. It means it will create and/or ALTER
  tables for you as your model changes.

 Err... how does schema changes relates to transactions ???

Type migrations not transactions sorry.

 Now FWIW, when my schema do change, the create/alter table code is
 usually the most trivial part - there are quite a few other things to
 do, that no framework will ever be abale to guess. IOW, you *do* have to
 write a migration script anyway.

No. We do not have migration scripts. It is nothing like Rails. You
just edit a model and, voila', database is migrated. Nothing to type.
Nothing to click on. (you can disable it)

I respect you choosing Django but it looks like you have never tried
web2py.

  - The DAL has partial support for some legacy databases that do not
  have an 'id' auto increment primary key.

 Django's ORM has full support for tables that don't use an auto_id key.

web2py too has support for legacy databases for tables without an
auto_id but not yet for all database back-ends.

  Anyway, I think both system are great. Spend 15 minutes (no more) with
  each to make up your mind, and stick with it.

 Once again, while doing a quick dummy test app can give you a first
 general feel of the tool, it means nothing wrt/ complex real-world
 applications.

While this may be true as a general statement could you explain which
feature you find in Django that is not in web2py and that is is
crytical for building large web applications? Could you provide a
coding example of such feature? This is an honest question because it
can help us make web2py better. I have personally learned a lot from
Django and thank the Django developers for their work, I would be
happy to learn more.

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


Re: which pi formula is given in the decimal module documentation?

2009-12-21 Thread Albert van der Horst
In article a266b155-02df-4294-8b91-41be4a1e4...@a32g2000yqm.googlegroups.com,
Mark Dickinson  dicki...@gmail.com wrote:
On Dec 11, 10:30=A0am, Mark Dickinson dicki...@gmail.com wrote:
  It looks like an infinite series with term `t`, where`n` =3D (2k-1)^2
  and `d` =3D d =3D 4k(4k+2) for k =3D 1... Does it have a name?

 Interesting. =A0So the general term here is
 3 * (2k choose k) / (16**k * (2*k+1)), =A0k =3D 0.

 I've no idea what its name is or where it comes from, though. =A0I
 expect Raymond Hettinger would know.

After a cup of coffee, it's much clearer:  this just comes from the
Taylor series for arcsin(x), applied to x =3D 1/2 to get asin(1/2) =3D pi/
6.

Curious. It seems better to calculate the zero of sin(pi/6)-1/2.
Not that we can forego the need of a Taylor series, but sin
converges much faster than arcsin.
The derivative is known analytically, and we have a 5th order process
before we know it.
It would be a big win for large precisions.
(Especially if we remember a previous value of pi to start up.)
The trick with temporarily increasing precision could be superfluous.

(I implemented this once in FORTRAN and was much disappointed that
double precision wasn't enough to show off the 5th order convergence. )

--
Mark

Groetjes Albert

--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
alb...@spearc.xs4all.nl =n http://home.hccnet.nl/a.w.m.van.der.horst

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


Re: Regex help needed!

2009-12-21 Thread MRAB

Oltmans wrote:

Hello,. everyone.

I've a string that looks something like

lksjdfls div id ='amazon_345343' kdjff lsdfs /div sdjfls div id
=   amazon_35343433sdfsd/divdiv id='amazon_8898'welcome/div



From above string I need the digits within the ID attribute. For

example, required output from above string is
- 35343433
- 345343
- 8898

I've written this regex that's kind of working
re.findall(\w+\s*\W+amazon_(\d+),str)

but I was just wondering that there might be a better RegEx to do that
same thing. Can you kindly suggest a better/improved Regex. Thank you
in advance.


Try:

re.findall(rdiv\s*id\s*=\s*[']amazon_(\d+)['], str)

You shouldn't be using 'str' as a variable name because it hides the
builtin string class 'str'.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Anybody use web2py?

2009-12-21 Thread Yarko
On Dec 19, 8:39 pm, AppRe Godeck a...@godeck.com wrote:
 On Sat, 19 Dec 2009 12:48:07 -0800, Yarko wrote:
  On Dec 19, 12:42 am, AppRe Godeck a...@godeck.com wrote:



 It seems that this is the biggest issue surrounding web2py, from my
 research, is the ability to customize the defaults (the easy). If all
 web2py offers is default views, then it may be good for proof of concept
 projects, however I can't see in my right mind, proofing an application,
 and then turning around to write it in django because more than the
 defaults is needed.


Perhaps I can clarify this:
- You CAN customize defaults easily ... but the default setup is so
easy, sometimes it's not initially clear where / how to do this in
web2py.

For example:  default views:

I updated (recently) the PyCon-2010  registration site so that it
looked like the base PyCon-2010 (django) site.  I copied some key
css and image files, replaced the big header/footers in the web2py
base layout (which is inherited by other views - also by default - so
he effect cascaded exactly as I wanted).

To quickly morph what I wanted from the web2py app's existing view
onto the new template (e.g., the menus, and the color/highlits of it's
pulldowns)  I went into a PC app (thru virtualbox):  stylizer - and
moved things around, changed the colors (e.g. of highlites) and saved
the result.   I then had cleaned it up.   Total time to change the
look:  about 45 minutes (20 minutes of that playing around with
Stylizer, enough to decide to use that for what I wanted to do).

In the result,  the templating (or view) language in Web2Py is...
um... *cough* ... *ahem* ... _simply pure python.

How to I update the view?  comes up often for new people.   Just
write the code and references you want to call up in the view.
How do I write them?   Python.

This comes up over and over.  How can you write python in view (html
files)?   How is indenting handled?  That's perhaps the only thing the
templateing language does:  It makes some assumptions about
indenting, so (for example) where context would signal the natural end
of indenting, in the template language you add a hint to the
template language:   {{ pass }}.

To output to the view, leave the left side empty:   {{ var='Output
this text'; =var }}
(result of var is output).

Another how do I customize question that comes up: data validation:
there are 2 levels in the DAL:  constraints which are defined in a
table field, and passed on as a constraint in the db engine;
constraints which are runtime in the request (e.g. in the web app).
The latter is easy to programmatically modify per context.   The first
time you do validation this becomes clear.

Another place is form customization.  You can customize forms.  There
are layers to this: in web2py, forms are automatically created for
data objects.  At one level, you have control over what data fields
are exposed.  At another, you have control over the type of object
that is presented in the form (list? text field?)  by the form of the
validator you setup.  This is one place where you have control over
default behaviors, but still used lots of the default engine.  And
you can create custom forms altogether.

Then there are viewports:  Beside layouts / template (all the basic
stuff you will recognize from most other frameworks - not just
django), and more-or-less the same kind of inheritence model of views
you might expect, there are a few things:  the classes for HTML you
asked about:  If you reference those classes in your view, output and
integration with any view code will happen for you (that is, prefer
the class definition of bold to the html syntax, for you can pass
arguments, escape, and put in other activity on the content and output
within the HTML tag for which there is a class member.  You'd
mentioned class not being view - the first thing to let go of is
executable python code is not the same thing as controller, eg.
view-logic != behavior-logic (business-rule, controller, whatever you
are accustomed to calling this).   Views have logic (just think of
ajax calls, javascript, and now Python-for-template code).   It's not
is it code that runs that is the important question, it is what is
this code affecting?  - Presentation, business logic, or
persistence/data/model?

And then there's is automatic association of behavior with some part
of your view: automatic controller assignment and ajax setup...

All the tools within web2py provide what you need to customize /
change defaults.  Perhaps forms are the ... least clear... have the
most layers / ways to approach (or is it views? ;-).  But there is a
way for all, no reason to prototype and throw away.  But you WILL be
asking how at first, not doubt.

Hope this has been somewhat helpful.

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


Sending ^C

2009-12-21 Thread Rick
Hi,
I am to write script which is to read data from log file which resides on 
remote host. It's a simple text file but grows to couple of MBytes. I want to 
do ssh connection to remote, and run 'tail -f _some_file_' command to read only 
new coming data and process them in the loop. The problem is, I don't know how 
to deal with it when log file rotates and change name. I need then to break 
running 'tail -f _some_file_' and excecute 'tail -f _other_file'. Can you give 
me hints how to do this?
Regards
Rick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Anybody use web2py?

2009-12-21 Thread Yarko
On Dec 21, 2:32 am, Bruno Desthuilliers bruno.
42.desthuilli...@websiteburo.invalid wrote:
 Thadeus Burgess a écrit :
 (snip)

  Spend one
  day working on a simple django application, polls, blog, image
  gallery, family pet tree, you name it. Then take the next day, and
  write the same application with web2py, and you decide. In the end,
  both are tools and you need to figure out what is best for YOU.

 The problem is not how easy it makes to write a *simple* (should I say
 braindead ?) dummy test app, but how easy - or even possible -it makes
 writing and maintaining a *real-world* complex application.

Bruno -

Check out the 50 minute coding-dojo we did at PyCon-2009:  a complete
news aggregation system, with authentication.  There were people (who
encouraged us to do the dojo) who doubted that we could cover so much
ground in so little time.   We asked WingIDE folks if they would
donate a WingIDE for raffling at the dojo (to help draw people) - not
only did they agree, then came and sat thru the dojo.  At the end of
the dojo,

I think most people there were amazed: they had a complete system, and
insight into how to extend and keep going with developing it further
(e.g. for their own needs).  I know the person who won the copy of
WingIDE was on the web2py list after, continuing to work on apps.
Wing wrote up a how-to develop web2py apps directly from wing, and
we added a hook to defer tickets (web2py traceback logs) to the wing
exception reporting system, if running under Wing (http://
www.wingware.com/doc/howtos/web2py).

Hardly brain-dead (that is just a loaded term you threw out, but I
see your skepticism).  At some level, each programming activity decays
to a brain-dead one, that is - to a trivially simple activity.
However, a trivial activity (define a news aggregator, data tables;
define a service to aggregate other data sources)  does not equal a
trivial result: in fact, the higher the level of abstraction I can
make a _programmer_ activity trivially easy and still accomplish
significant function, the more attention and time the programmer can
spend on thinking about _the problem at hand_, rather than the
_setting up of the system_ This is precisely one of the benefits
I've seen touted in numerous papers arguing for teaching either Flash
(adobe) over Java, or Python over Java -- the decrease in time spent
worrying about setup of the system used to address a given problem/
algorithm.

Easier / trivial setup in tool is good when it accomplishes what you
need (e.g. gets out of your way, leaves more attention to the problem
at hand).

- Yarko

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


Re: Sending ^C

2009-12-21 Thread Grant Edwards
On 2009-12-21, Rick rick2...@op.pl wrote:

 I am to write script which is to read data from log file which
 resides on remote host. It's a simple text file but grows to
 couple of MBytes. I want to do ssh connection to remote, and
 run 'tail -f _some_file_' command to read only new coming data
 and process them in the loop. The problem is, I don't know how
 to deal with it when log file rotates and change name. I need
 then to break running 'tail -f _some_file_' and excecute 'tail
 -f _other_file'. Can you give me hints how to do this?

import os,signal

os.kill(pid,signal.SIGINT)

-- 
Grant Edwards   grante Yow! !  Now I understand
  at   advanced MICROBIOLOGY and
   visi.comth' new TAX REFORM laws!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For...in statement and generators

2009-12-21 Thread Mark Tolonen


Lucas Prado Melo lukepada...@gmail.com wrote in message 
news:9f4be2240912210639g58da0549jb0c81450947ef...@mail.gmail.com...

Is there a way to send() information back to a generator while using the
for...in statement?

Thanks in advance.


Yes, see send(), (generator method) or yield expressions in the help.

-Mark 



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


I need your opinion...

2009-12-21 Thread logan tag
It should be interesting to add new funcionality to copytree function into
a shutil.py module?, I mean...I have developed a very silly function
copytree with a different fourth argument. I have modified the ignore
parameter to target parameter; this new one is used to copy the files wich
matched with the given pattern.
Basically, the opposite of the current copytree.

Maybe were a stupid idea but I throw it anyway.

Thanks in advance.

Logan!!

PS:
def copytree(src, dst, symlinks=False, target=None)
def target_patterns(*patterns)
-- 
http://mail.python.org/mailman/listinfo/python-list


how to register with pypi

2009-12-21 Thread Phlip

Pythonistas:

I'm stuck on the PGP Key ID. When I whip out my trusty Ubuntu and run pgp -kg, 
I get a 16-digit DSA / EIGamal key.


When I enter it into http://pypi.python.org/pypi?%3Aaction=register_form , I get 
a helpful PGP Key ID is invalid.


Should I try a key of some other algorithm?

--
  Phlip
  http://c2.com/cgi/wiki?ZeekLand
--
http://mail.python.org/mailman/listinfo/python-list


Re: Object Relational Mappers are evil (a meditation)

2009-12-21 Thread J Kenneth King
Lie Ryan lie.1...@gmail.com writes:

 On 12/17/2009 3:17 PM, J Kenneth King wrote:
 A language is a thing.  It may have syntax and semantics that bias it
 towards the conventions and philosophies of its designers.  But in the
 end, a language by itself would have a hard time convincing a human
 being to adopt bad practises.

 Perhaps someone should make a research whether if you teach a language
 to kids, where one group is taught the language filtered from bad
 words and another group is taught all the languages' bad words on
 purpose. Will one group have more behavioral problems compared to the
 other?

I would be curious to know, but the test is likely impossible without
trespassing on ethical boundaries. ;)

I would hypothesize that you would not find an increase in behavioural
problems.

a) Without cultural context bad words have little meaning

b) Behavioural issues can be attributed to several factors such as
physiology, health, environment, etc.

c) This has nothing to do with programming languages.  A programmer that
lacks critical thinking is a bad programmer.  The language they use has
no bearing on such human facilities.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: numpy performance and random numbers

2009-12-21 Thread Robert Kern

On 2009-12-19 09:14 AM, Carl Johan Rehn wrote:

On Dec 19, 2:49 pm, sturlamoldensturlamol...@yahoo.no  wrote:

On 19 Des, 11:05, Carl Johan Rehncar...@gmail.com  wrote:


I plan to port a Monte Carlo engine from Matlab to Python. However,
when I timed randn(N1, N2) in Python and compared it with Matlab's
randn, Matlab came out as a clear winner with a speedup of 3-4 times.
This was truly disappointing. I ran tthis test on a Win32 machine and
without the Atlas library.


This is due to the algorithm. Matlab is using Marsaglia's ziggurat
method. Is is the fastest there is for normal and gamma random
variates. NumPy uses the Mersenne Twister to produce uniform random
deviates, and then applies trancendental functions to transform to the
normal distribution. Marsaglia's C code for ziggurat is freely
available, so you can compile it yourself and call from ctypes, Cython
or f2py.

The PRNG does not use BLAS/ATLAS.


Thank you, this was very informative. I know about the Mersenne
Twister, but had no idea about Marsaglia's ziggurat method. I will
definitely try f2py or cython.


It's worth noting that the ziggurat method can be implemented incorrectly, and 
requires some testing before I will accept such in numpy. That's why we don't 
use the ziggurat method currently. C.f.


  http://www.doornik.com/research/ziggurat.pdf

Requests for the ziggurat method come up occasionally on the numpy list, but so 
far no one has shown code or test results. Charles Harris and Bruce Carneal seem 
to have gotten closest. You can search numpy-discussion's archive for their 
email addresses and previous threads. Additionally, you should ask future numpy 
questions on the numpy-discussion mailing list.


  http://www.scipy.org/Mailing_Lists

--
Robert Kern

I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth.
  -- Umberto Eco

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


Opening File Object

2009-12-21 Thread Ray Holt
I use the following code:
fileobject = open(e:\\Ray Holts Documents\\Word Documents\\1850 Warren MS
Jenkins, 'y')
line = fileobject.readline()
 
I get the following error message:Traceback (most recent call last):
  File C:/Python26/Reading_and_Writing_Files, line 5, in module
fileobject = open(E:\\Ray Holts Documents\Word Documents\\1850 Warren
MS Jenkins, 'r')
IOError: [Errno 2] No such file or directory: 'E:\\Ray Holts Documents\\Word
Documents\\1850 Warren MS Jenkins'

I know the file exists because I opened it in MS Word. Can someone help me?
Thanks, Ray Holt
-- 
http://mail.python.org/mailman/listinfo/python-list


Ch 3 of my writings, first few sections posted

2009-12-21 Thread Alf P. Steinbach

Tentatively titled Foundations.

Also, these first 2/3 sections may be moved to some later point, i.e. even the 
structure is tentative, but I'd value comments!


  url: http://tinyurl.com/programmingbookP3

Table of contents:

3  Foundations 1
3.1  Some necessary math notation  terminology. 2
3.1.1  The vocabulary and notation of basic arithmetic, including Σ and Π. 2
3.1.2  Quadratic and exponential time  memory (also introducing timeit). 5
-EOT_ 9


Cheers,

- Alf

PS: Hm, Open Office's PDF generation does funny things with Greek sigmas inside 
formulas! I don't mind so much that it makes table divider lines very fat and 
bold and that it can't handle certain figures (which I have to paste in manually 
as bitmaps), but really it should be able to handle simple text. Grr.

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


Re: Opening File Object

2009-12-21 Thread MRAB

Ray Holt wrote:

I use the following code:
fileobject = open(e:\\Ray Holts Documents\\Word Documents\\1850 Warren 
MS Jenkins, 'y')

line = fileobject.readline()
 
I get the following error message:Traceback (most recent call last):

  File C:/Python26/Reading_and_Writing_Files, line 5, in module
fileobject = open(E:\\Ray Holts Documents\Word Documents\\1850 
Warren MS Jenkins, 'r')
IOError: [Errno 2] No such file or directory: 'E:\\Ray Holts 
Documents\\Word Documents\\1850 Warren MS Jenkins'
I know the file exists because I opened it in MS Word. Can someone help 
me?



Look for the file using Windows Explorer. I expect that the filename has
an extension, which you're omitting.
--
http://mail.python.org/mailman/listinfo/python-list


py2exe for loop hangs in compiled program

2009-12-21 Thread p_tierchen

Dear reader,

the application is an interface to a sqlite database and stores image
metadata (such as year, event, photographer, people on image etc.). i use
pyqt4 for the interface and developed this application on a linux platform
(python 2.5.4). friends of mine liked what i have done an want it for their
windows computers. so i setup a test system (win XP and python 2.6.?).
copying the code to this system and starting it: works as intended. however
they complain python whats this, this is sooo complicated etc. so i took
refuge in using py2exe, planing to give them a zip compressed archive ...
testing this option i found out that on the surface all looks nice (GUI and
functions etc) however:
extending to larger datasets (~50 images) some of the for loops stop
after some time.
e.g:
def update_allImages(self):  
self.set_statusbar(unicode(Daten werden für alle angezeigten Bilder
eingetragen))
for row in range(self.liwi.count()):
item=self.liwi.item(row)
md5=item.toolTip()#.split()[0]
md5=unicode(md5.split()[0])
   
self.md5TOimdata[md5].addyear(self.ui.year_comboBox.currentText())
   
self.md5TOimdata[md5].addEvent(self.ui.event_comboBox.currentText())
self.md5TOimdata[md5].addauth(self.ui.Author_cb.currentText())
comment=self.ui.CommentInput_text.toPlainText()
if comment:
comment.append(; )
self.md5TOimdata[md5].addcomment(comment)

for i in range(self.ui.people_listWidget.count()):
pitem=self.ui.people_listWidget.item(i)
name=pitem.text()
self.md5TOimdata[md5].addperson(name)

item.setToolTip(self.md5TOimdata[md5].generateToolTip())
self.liwi.setCurrentItem(item) 
self.md5TOimdata[md5].update_DB()
self.set_statusbar(unicode(Alles eingetragen: Bereit))

sorry for the german strings in the statusbar (to be changed in future
versions)

in the third line the problematic for starts. at about item 42 or 43 the
statusbar stays on what is in line 2 and nothing more happens. so the first
42 items get updated the rest not. well i can restart this process but
success is limited only view more items get updated. note that this code
works fine in linux and in windows (python commandline) but hangs as
described after py2exe.

a second example is when i try to load many images (~130) again here is a
for loop iterating over filenames. the pure python versions work as they
should but not the py2exe.

def ImLoad(self):
 This method is called by clicking on the load images button.
It loads the 
selected images from the source and copies them to the db
filesystem.
Of course it is checked whether the image is allready in the db
(no insertion
happens) or if its is even loaded (not going to be loaded twice)

fileNames = QtGui.QFileDialog.getOpenFileNames(self,
 Bild(er) laden, , Bild Dateien (*.png *.jpg *.bmp *.tif))
 
for fileName in fileNames:  
#work is done

therefore i think its in the for loops.

thanks in advance. just ask if you need more info. kind regards Jo
-- 
View this message in context: 
http://old.nabble.com/py2exe-%22for-loop%22-hangs-in-compiled-program-tp26877033p26877033.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Please Help Publicize PyCon

2009-12-21 Thread John Nagle

Steve Holden, Chairman, PSF wrote:

Hi,everyone.

This year I hope all readers of this list will assist me in crass
commercial promotion of next year's PyCon. 

...

One particularly effective way for you prodigious email producers to
assist is to something to your signature (as you will see I have done).

...

   This guy wants people to spam for him to promote his $300 conference.

   Don't support spammers.  Boycott PyCon.

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


web development in python 2.6 and 3.0

2009-12-21 Thread Simon Moses
hi,

i am new to python but have programming experience in few other languages. 
i am trying to start with python 2.6 or 3.0. my requirement is accessing 
database (mysql and/or postgresql) and web development. 

what all i should install for my requirement?
to connect to database (mysql and/or postgresql)
for web development


thanks and regards,
Simon Moses.


  The INTERNET now has a personality. YOURS! See your Yahoo! Homepage. 
http://in.yahoo.com/-- 
http://mail.python.org/mailman/listinfo/python-list


Re: web development in python 2.6 and 3.0

2009-12-21 Thread Stephen Hansen
On Mon, Dec 21, 2009 at 9:22 AM, Simon Moses ksmo...@ymail.com wrote:

 hi,

 i am new to python but have programming experience in few other languages.
 i am trying to start with python 2.6 or 3.0. my requirement is accessing
 database (mysql and/or postgresql) and web development.

 what all i should install for my requirement?
 to connect to database (mysql and/or postgresql)
 for web development


3.0 is a bit hard right now as there are a lot of libraries that have not
yet been ported which may be required for certain frameworks, but this
question is a bit hard on its own to answer... because you have a lot of
choices :)

For 2.6, what's your requirements? What's web development for you, ie what
kind of development on the web are you talking about doing? If you're
looking to do a database-driven web app, I've seen both Django and web2py in
use and both have active communities and seem to be quite mature and
interesting.

But there's a lot of other options. Personally, I'm using Pylons and am very
happy with it-- its a bit more low-level but that makes it better for me
because I'm integrating it into an existing non-web based system. Then
there's TurboGears which is built on top of Pylons in its 2.0 version, but a
bit more focused on the end goal of providing a complete solution instead of
a complete set of tools for you to make a solution out of. (That might be
woefully mischaracterizing their perspectives on my part, if so I
apologize!)

Depending on what you need to do, there's for sure a framework for you to
make life easier out there. At the moment, Python seems to have a million
solutions to this problem and all seem quite interesting in their own
regard. Then again, you could go retro and skip the framework and just use
what's in the standard library and make CGI scripts... but doing it the
cave-man way will make you seem less cool :)

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


Re: For...in statement and generators

2009-12-21 Thread Gabriel Genellina
En Mon, 21 Dec 2009 11:39:46 -0300, Lucas Prado Melo  
lukepada...@gmail.com escribió:



Is there a way to send() information back to a generator while using the
for...in statement?


No. You have to write the iteration as a while loop.

--
Gabriel Genellina

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


How to validate the __init__ parameters

2009-12-21 Thread Denis Doria
Hi;

I'm checking the best way to validate attributes inside a class. Of
course I can use property to check it, but I really want to do it
inside the __init__:

class A:
def __init__(self, foo, bar):
self.foo = foo #check if foo is correct
self.bar = bar

All examples that I saw with property didn't show a way to do it in
the __init__. Just to clarify, I don't want to check if the parameter
is an int, or something like that, I want to know if the parameter do
not use more than X chars; and want to do it when I'm 'creating' the
instance; not after the creation:

a = A('foo', 'bar')

not

class A:
def __init__(self, foo = None, bar = None):
self._foo = foo
self._bar = bar
def  set_foo(self, foo):
if len(foo)  5:
 raise something
_foo = foo
foo = property(setter = set_foo)

a = A()
a.foo = 'foo'


I thought in something like:

class A:
def __init__(self, foo = None, bar = None):
set_foo(foo)
self._bar = bar
def  set_foo(self, foo):
if len(foo)  5:
 raise something
_foo = foo
foo = property(setter = set_foo)

But looks too much like java
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Please Help Publicize PyCon

2009-12-21 Thread mdipierro
There is huge difference between what Steve is asking and spam.

Spam is Unsolicited e-mail, often of a commercial nature, sent
indiscriminately to multiple mailing lists, individuals, or
newsgroups.

Steve is asking us help him to identify communities that we may be
part of and that we believe may be interested in the PyCon conference
and inform them.

Not every communication on the internet is spam.

Massimo


On Dec 21, 11:31 am, John Nagle na...@animats.com wrote:
 Steve Holden, Chairman, PSF wrote: Hi,everyone.

  This year I hope all readers of this list will assist me in crass
  commercial promotion of next year's PyCon.
 ...
  One particularly effective way for you prodigious email producers to
  assist is to something to your signature (as you will see I have done).

 ...

     This guy wants people to spam for him to promote his $300 conference.

     Don't support spammers.  Boycott PyCon.

                                         John Nagle

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


Re: I need your opinion...

2009-12-21 Thread Stephen Hansen
On Mon, Dec 21, 2009 at 8:23 AM, logan tag logan...@gmail.com wrote:

 It should be interesting to add new funcionality to copytree function
 into a shutil.py module?, I mean...I have developed a very silly function
 copytree with a different fourth argument. I have modified the ignore
 parameter to target parameter; this new one is used to copy the files wich
 matched with the given pattern.
 Basically, the opposite of the current copytree.

 Maybe were a stupid idea but I throw it anyway.

 Thanks in advance.


I don't understand what you're actually asking. Are you asking if its
possible to 'add' new functionality into shutil yourself/manually? If so,
yes, you can just 'shutil.mynewfunction = myfunction'. But doing so is
highly discouraged, it's best to simply put this function into your own
module and import that module when needed.

Or are you asking if such a function would be useful as an addition to the
shutil in the standard library? If so, I'd say no: every ignore option can
trivially be turned into a target by simply inverting the test and
vice-versa. There's no reason to expand the stdlib's API and make people
choose between two functions which do the same thing in opposite directions.

Meaning, an argument which defines ignore= can serve the purpose of
target= by simply choosing to ignore everything which doesn't match what
you want to target.

Or you might be asking something else entirely, in which case I'm sorry, I'm
not sure what it is :)

HTH,

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


Re: How to validate the __init__ parameters

2009-12-21 Thread Stephen Hansen
On Mon, Dec 21, 2009 at 9:41 AM, Denis Doria denisdo...@gmail.com wrote:

 All examples that I saw with property didn't show a way to do it in
 the __init__. Just to clarify, I don't want to check if the parameter
 is an int, or something like that, I want to know if the parameter do
 not use more than X chars; and want to do it when I'm 'creating' the
 instance; not after the creation:

 a = A('foo', 'bar')

 not

 class A:
def __init__(self, foo = None, bar = None):
self._foo = foo
self._bar = bar
def  set_foo(self, foo):
if len(foo)  5:
 raise something
_foo = foo
foo = property(setter = set_foo)

 a = A()
 a.foo = 'foo'


If I understand your requirements correctly-- you should just use
  self.foo = foo
in your __init__, as opposed to the backdoor
  self._foo = foo

Properties are probably the best way to get what you want, and if you want
to have the verification done, just don't bypass properties by assigning
into the private variable. Just because its fair-game for methods of a
class(and especially a classes initializer) to assign to the
pseudo-private member variables, doesn't mean it /has/ to or even /should/
:)

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


Re: difflib get_close_matches improvement?

2009-12-21 Thread Peter Otten
Neal Becker wrote:

 difflib.get_close_matches looks useful.  But, I don't see where it defines
 'close'.  Besides that, wouldn't it be much more useful if one could
 supply their own distance metric?

If you have a distance function you can find the N best matches with

 from heapq import nsmallest
 from functools import partial
 from Levenshtein import distance
 possibilities = [ape, apple, peach, puppy]
 nsmallest(3, possibilities, key=partial(distance, appel))
['ape', 'apple', 'puppy']

With a cutoff it gets a bit messier...

 pairs = ((distance(appel, v), v) for v in possibilities)
 pairs = ((score, v) for score, v in pairs if score = 2)
 [v for score, v in nsmallest(3, pairs)]
['ape', 'apple']

so you would want to wrap it in a function, but if you have a look into 
difflib.get_close_matches()...

def get_close_matches(word, possibilities, n=3, cutoff=0.6):
if not n   0:
raise ValueError(n must be  0: %r % (n,))
if not 0.0 = cutoff = 1.0:
raise ValueError(cutoff must be in [0.0, 1.0]: %r % (cutoff,))
result = []
s = SequenceMatcher()
s.set_seq2(word)
for x in possibilities:
s.set_seq1(x)
if s.real_quick_ratio() = cutoff and \
   s.quick_ratio() = cutoff and \
   s.ratio() = cutoff:
result.append((s.ratio(), x))

# Move the best scorers to head of list
result = heapq.nlargest(n, result)
# Strip scores for the best n matches
return [x for score, x in result]

there is a lot of stuff that only makes sense if you use a SequenceMatcher 
to calculate the similarity. For a generalized version you will probably 
have to throw out the range check for the cuttof and the optimizations.

I don't think it's worthwile.

Peter

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


Re: How to validate the __init__ parameters

2009-12-21 Thread Jean-Michel Pichavant

Denis Doria wrote:

Hi;

I'm checking the best way to validate attributes inside a class. Of
course I can use property to check it, but I really want to do it
inside the __init__:

class A:
def __init__(self, foo, bar):
self.foo = foo #check if foo is correct
self.bar = bar

All examples that I saw with property didn't show a way to do it in
the __init__. Just to clarify, I don't want to check if the parameter
is an int, or something like that, I want to know if the parameter do
not use more than X chars; and want to do it when I'm 'creating' the
instance; not after the creation:

a = A('foo', 'bar')

not

class A:
def __init__(self, foo = None, bar = None):
self._foo = foo
self._bar = bar
def  set_foo(self, foo):
if len(foo)  5:
 raise something
_foo = foo
foo = property(setter = set_foo)

a = A()
a.foo = 'foo'


I thought in something like:

class A:
def __init__(self, foo = None, bar = None):
set_foo(foo)
self._bar = bar
def  set_foo(self, foo):
if len(foo)  5:
 raise something
_foo = foo
foo = property(setter = set_foo)

But looks too much like java
  

One possible way, straight and simple

class A:
   def __init__(self, foo = None, bar = None):
   if len(foo)  5:
raise ValueError('foo cannot exceed 5 characters')
self._foo = foo
   self._bar = bar


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


Re: Opening File Object

2009-12-21 Thread Benjamin Kaplan
On Mon, Dec 21, 2009 at 11:48 AM, Ray Holt mrhol...@sbcglobal.net wrote:
 I use the following code:
 fileobject = open(e:\\Ray Holts Documents\\Word Documents\\1850 Warren MS
 Jenkins, 'y')
 line = fileobject.readline()

 I get the following error message:Traceback (most recent call last):
   File C:/Python26/Reading_and_Writing_Files, line 5, in module
     fileobject = open(E:\\Ray Holts Documents\Word Documents\\1850 Warren
 MS Jenkins, 'r')
 IOError: [Errno 2] No such file or directory: 'E:\\Ray Holts Documents\\Word
 Documents\\1850 Warren MS Jenkins'
 I know the file exists because I opened it in MS Word. Can someone help me?
 Thanks, Ray Holt

Files usually have an extension (like .txt or .doc) but Microsoft
feels that those are too complicated so they try to hide them from
you. It's probably 1850 Warren MS Jenkins.doc if you're opening it
with word which provides you with another problem- when you're
programming, there's no such thing as a Word document, just a
collection of 1s and 0s which will be complete nonsense if you don't
understand how Word does its formatting. Make sure it's saved as plain
text (.txt) if you're trying to open it programatically.

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


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


Re: How to validate the __init__ parameters

2009-12-21 Thread Alf P. Steinbach

* Denis Doria:


I thought in something like:

class A:
def __init__(self, foo = None, bar = None):
set_foo(foo)
self._bar = bar
def  set_foo(self, foo):
if len(foo)  5:
 raise something
_foo = foo
foo = property(setter = set_foo)

But looks too much like java


Yeah.

If member _foo has this constraint regardless then it's logically part of that 
member's type, so make it a type:


  class _Foo:
def __init__( self, seq ):
  if seq is None:
self.items = []
  elif len( seq )  5:
raise something
  else:
self.items = seq

  class A:  # Your example
def __init__( self, foo = None, Bar = None ):
  self._foo = _Foo( foo )
  self._bar = bar
def set_foo( self, foo ):
  self._foo = _Foo( foo )
foo = property( setter = set_foo )


Cheers  hth.,

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


Python 3.1.1 installer botches upgrade when installation is not on C drive.

2009-12-21 Thread John Nagle
   I just installed python3.1.1.msi on a system that had python3.1.msi 
installed in D:/python31.  The installer found the old installation in

D:/python31, partially trashed it, and then installed the new version
in C:/python31.

   I uninstalled the failed install, and reinstalled.  On a new install,
the installer prompts for the destination dir, and that works.
Upgrade installs, though, are botched.

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


Re: (unknown)

2009-12-21 Thread GilJohnson
 petro at brc.hu writes:

 
 
petro,
I think you need to use e-mail, not IMP
Gil



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


Re: web development in python 2.6 and 3.0

2009-12-21 Thread Simon Moses
to code a web page which connects to a database and displays some rows, what 
minimum software and libraries i should install?

python 2.6, mysql 5.0, apache 2.2 and Django? thats enough?






From: Stephen Hansen apt.shan...@gmail.com
To: Simon Moses ksmo...@ymail.com
Cc: python-list@python.org
Sent: Mon, 21 December, 2009 1:37:38 PM
Subject: Re: web development in python 2.6 and 3.0

On Mon, Dec 21, 2009 at 9:22 AM, Simon Moses ksmo...@ymail.com wrote:


hi,

i am new to python but have programming experience in few other languages. 
i am trying to start with python 2.6 or 3.0. my requirement is accessing 
database (mysql and/or postgresql) and web development. 

what all i should install for my requirement?
to connect to database (mysql and/or postgresql)
for web development

3.0 is a bit hard right now as there are a lot of libraries that have not yet 
been ported which may be required for certain frameworks, but this question is 
a bit hard on its own to answer... because you have a lot of choices :)

For 2.6, what's your requirements? What's web development for you, ie what 
kind of development on the web are you talking about doing? If you're looking 
to do a database-driven web app, I've seen both Django and web2py in use and 
both have active communities and seem to be quite mature and interesting. 

But there's a lot of other options. Personally, I'm using Pylons and am very 
happy with it-- its a bit more low-level but that makes it better for me 
because I'm integrating it into an existing non-web based system. Then there's 
TurboGears which is built on top of Pylons in its 2.0 version, but a bit more 
focused on the end goal of providing a complete solution instead of a complete 
set of tools for you to make a solution out of. (That might be woefully 
mischaracterizing their perspectives on my part, if so I apologize!)

Depending on what you need to do, there's for sure a framework for you to make 
life easier out there. At the moment, Python seems to have a million solutions 
to this problem and all seem quite interesting in their own regard. Then again, 
you could go retro and skip the framework and just use what's in the standard 
library and make CGI scripts... but doing it the cave-man way will make you 
seem less cool :)
 
--S


  The INTERNET now has a personality. YOURS! See your Yahoo! Homepage. 
http://in.yahoo.com/-- 
http://mail.python.org/mailman/listinfo/python-list


Re: web development in python 2.6 and 3.0

2009-12-21 Thread Stephen Hansen
On Mon, Dec 21, 2009 at 10:34 AM, Simon Moses ksmo...@ymail.com wrote:

 to code a web page which connects to a database and displays some rows, what 
 minimum software and libraries i should install?

 python 2.6, mysql 5.0, apache 2.2 and Django? thats enough?

Depending on your requirements, you might not need mysql at all;
Python comes with SQLite which is actually quite often more then
sufficient for smaller sites. Its very fast and handles moderate
concurrency quite well.

Personally, I prefer to set up my web-apps with Apache + mod_wsgi, on
which you can use any WSGI-compliant framework, which includes Django.

http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango

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


Re: I need your opinion...

2009-12-21 Thread logan tag
Thanks for the answer, it's perfect for my purposes.
See you in other thread!!!

On Mon, Dec 21, 2009 at 6:47 PM, Stephen Hansen apt.shan...@gmail.comwrote:

 On Mon, Dec 21, 2009 at 8:23 AM, logan tag logan...@gmail.com wrote:

 It should be interesting to add new funcionality to copytree function
 into a shutil.py module?, I mean...I have developed a very silly function
 copytree with a different fourth argument. I have modified the ignore
 parameter to target parameter; this new one is used to copy the files wich
 matched with the given pattern.
 Basically, the opposite of the current copytree.

 Maybe were a stupid idea but I throw it anyway.

 Thanks in advance.


 I don't understand what you're actually asking. Are you asking if its
 possible to 'add' new functionality into shutil yourself/manually? If so,
 yes, you can just 'shutil.mynewfunction = myfunction'. But doing so is
 highly discouraged, it's best to simply put this function into your own
 module and import that module when needed.

 Or are you asking if such a function would be useful as an addition to the
 shutil in the standard library? If so, I'd say no: every ignore option can
 trivially be turned into a target by simply inverting the test and
 vice-versa. There's no reason to expand the stdlib's API and make people
 choose between two functions which do the same thing in opposite directions.

 Meaning, an argument which defines ignore= can serve the purpose of
 target= by simply choosing to ignore everything which doesn't match what
 you want to target.

 Or you might be asking something else entirely, in which case I'm sorry,
 I'm not sure what it is :)

 HTH,

 --S

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


Re: web development in python 2.6 and 3.0

2009-12-21 Thread Simon Moses
so python 2.6, mysql 5.0, apache 2.2, mod_wsgi, MySQL-python-1.2.2.win32-py2.6 
and Django should be sufficient for my requirement.


  The INTERNET now has a personality. YOURS! See your Yahoo! Homepage. 
http://in.yahoo.com/-- 
http://mail.python.org/mailman/listinfo/python-list


linking error after swig

2009-12-21 Thread whatazor
Hi All,
I have a mac os x, and I try to replicate the sample in swig tutorial
but when I try to link, I have these linking errors:

ld  example.o example_wrap.o -o _example.so
Undefined symbols:
  _PyType_Type, referenced from:
  _PyType_Type$non_lazy_ptr in example_wrap.o
  _PyExc_SystemError, referenced from:
  _PyExc_SystemError$non_lazy_ptr in example_wrap.o
  _PyDict_New, referenced from:
  _SWIG_Python_NewShadowInstance in example_wrap.o
  _SWIG_Python_NewShadowInstance in example_wrap.o
  _SWIG_Python_SetSwigThis in example_wrap.o
  _SWIG_Python_TypeCache in example_wrap.o
  _fputs$UNIX2003, referenced from:
  _PySwigObject_print in example_wrap.o
  _PySwigPacked_print in example_wrap.o
  _PySwigPacked_print in example_wrap.o
  _PyExc_IOError, referenced from:
  _PyExc_IOError$non_lazy_ptr in example_wrap.o
  _PyCObject_Import, referenced from:
  _SWIG_Python_GetModule in example_wrap.o
  _PyList_Append, referenced from:
  _SWIG_Python_AppendOutput in example_wrap.o
  _PyTuple_Type, referenced from:
  _PyTuple_Type$non_lazy_ptr in example_wrap.o
  _PyExc_MemoryError, referenced from:
  _PyExc_MemoryError$non_lazy_ptr in example_wrap.o
  _PyArg_ParseTuple, referenced from:
  __wrap_fact in example_wrap.o
  __wrap_my_mod in example_wrap.o
  __wrap_get_time in example_wrap.o
  _strstr, referenced from:
  _SWIG_Python_ConvertFunctionPtr in example_wrap.o
  _SWIG_Python_FixMethods in example_wrap.o
  _fwrite$UNIX2003, referenced from:
  _PySwigPacked_print in example_wrap.o
  _PySwigPacked_print in example_wrap.o
  _swig_varlink_print in example_wrap.o
  _PyInstance_NewRaw, referenced from:
  _SWIG_Python_NewShadowInstance in example_wrap.o
  _PyDict_SetItemString, referenced from:
  _SWIG_Python_SetConstant in example_wrap.o
  _SWIG_Python_InstallConstants in example_wrap.o
  _init_example in example_wrap.o
  _PyFloat_AsDouble, referenced from:
  _SWIG_AsVal_double in example_wrap.o
  _PyArg_UnpackTuple, referenced from:
  _PySwigObject_own in example_wrap.o
  _PyObject_Str, referenced from:
  _SWIG_Python_AddErrorMsg in example_wrap.o
  _SWIG_Python_AddErrMesg in example_wrap.o
  _SWIG_Python_TypeError in example_wrap.o
  _PyDict_GetItem, referenced from:
  _SWIG_Python_GetSwigThis in example_wrap.o
  _SWIG_Python_TypeQuery in example_wrap.o
  _PyExc_TypeError, referenced from:
  _PyExc_TypeError$non_lazy_ptr in example_wrap.o
  _PyString_FromString, referenced from:
  _PySwigObject_format in example_wrap.o
  _PySwigObject_str in example_wrap.o
  _PySwigPacked_str in example_wrap.o
  __SWIG_This in example_wrap.o
  _SWIG_Python_TypeQuery in example_wrap.o
  _swig_varlink_repr in example_wrap.o
  _swig_varlink_str in example_wrap.o
  _swig_varlink_str in example_wrap.o
  _swig_varlink_str in example_wrap.o
  _swig_varlink_str in example_wrap.o
  _PyBool_FromLong, referenced from:
  _PySwigObject_own in example_wrap.o
  _PyString_AsString, referenced from:
  _SWIG_Python_AddErrorMsg in example_wrap.o
  _PySwigObject_repr in example_wrap.o
  _PySwigObject_print in example_wrap.o
  _SWIG_Python_AddErrMesg in example_wrap.o
  _SWIG_Python_AddErrMesg in example_wrap.o
  _SWIG_Python_TypeError in example_wrap.o
  _swig_varlink_print in example_wrap.o
  _PyObject_IsTrue, referenced from:
  _PySwigObject_own in example_wrap.o
  _PyList_Type, referenced from:
  _PyList_Type$non_lazy_ptr in example_wrap.o
  _PyInt_AsLong, referenced from:
  _SWIG_AsVal_double in example_wrap.o
  _SWIG_AsVal_long in example_wrap.o
  _PyErr_SetString, referenced from:
  _SWIG_Python_SetErrorMsg in example_wrap.o
  _SWIG_Python_UnpackTuple in example_wrap.o
  _swig_varlink_getattr in example_wrap.o
  _swig_varlink_setattr in example_wrap.o
  _malloc, referenced from:
  _PySwigClientData_New in example_wrap.o
  _PySwigPacked_New in example_wrap.o
  _SWIG_Python_addvarlink in example_wrap.o
  _SWIG_Python_addvarlink in example_wrap.o
  _SWIG_Python_FixMethods in example_wrap.o
  _PyList_New, referenced from:
  _SWIG_Python_AppendOutput in example_wrap.o
  _PyErr_SetObject, referenced from:
  _SWIG_Python_SetErrorObj in example_wrap.o
  _strncmp, referenced from:
  _PySwigPacked_compare in example_wrap.o
  _SWIG_Python_FixMethods in example_wrap.o
  _PyObject_Malloc, referenced from:
  _PySwigObject_New in example_wrap.o
  _PySwigPacked_New in example_wrap.o
  _SWIG_Python_newvarlink in example_wrap.o
  _PyExc_RuntimeError, referenced from:
  _PyExc_RuntimeError$non_lazy_ptr in example_wrap.o
  _PyCFunction_Type, referenced from:
  _PyCFunction_Type$non_lazy_ptr in example_wrap.o
  __Py_NoneStruct, referenced from:
  __Py_NoneStruct$non_lazy_ptr in example_wrap.o
  __PyWeakref_CallableProxyType, referenced from:
  

Re: Python-list Digest, Vol 75, Issue 226

2009-12-21 Thread Pulkit Agrawal
Hi,

I am writing a script wherein I need to merge files into existing tar.gz
files. Currently, I am using tarfile module. I extract the tar.gz to a
tempdir and copy the new file there and re-compress all the files back into
a tar.gz.  Is there a better way to do it?

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


Merging files into tar.gz archives

2009-12-21 Thread Pulkit Agrawal
Hi,

I am writing a script wherein I need to merge files into existing tar.gz
archives. Currently, I am using tarfile module. I extract the tar.gz to a
tempdir and copy the new file there and re-compress all the files back into
a tar.gz.  Is there a better way to do it?

Thanks
Pulkit

(Sorry for the subject earlier)


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


Re: web development in python 2.6 and 3.0

2009-12-21 Thread Stephen Hansen
On Mon, Dec 21, 2009 at 11:09 AM, Simon Moses ksmo...@ymail.com wrote:
 so python 2.6, mysql 5.0, apache 2.2, mod_wsgi,
 MySQL-python-1.2.2.win32-py2.6 and Django should be sufficient for my
 requirement.

I don't know for certain; you're asking a bit too much specific detail here :)

Just go to http://docs.djangoproject.com/en/dev/topics/install/ -- it
shows you everything you need to install to get Django going :)

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


Re: converting string to a date format

2009-12-21 Thread tekion
Ben,
I do not have python 2.6 install, my version of Python is 2.4.
Because of my version of Python I believe I have to perform what you
have suggested:

This should, ideally, consist of two separate operations:

  * parse the string, using a specific format, to create a ‘datetime’
object

  * create a string representation of the datetime using your
preferred
string format

So I guess I am stuck on parsing the string 24/Nov/2009:12:00:00
-0500 using regex and or string function to get the output to
2009-11-24 12:00:00.  It looks like I may have to use regex to
accomplish this and also re-map Nov to 11.  Does any one have any
idea that would take 24/Nov/2009:HH:MM:SS and format it to
2009-11-24 HH:MM:SS? Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Windows, IDLE, __doc_, other

2009-12-21 Thread W. eWatson

Lie Ryan wrote:

On 12/21/2009 1:19 PM, W. eWatson wrote:

When I use numpy.__doc__ in IDLE under Win XP, I get a heap of words 
without reasonable line breaks.


\nNumPy\n=\n\nProvides\n  1. An array object of arbitrary 
homogeneous items\n  2. Fast mathematical operations over arrays\n  3. 
Linear Algebra, Fourier Transforms, Random Number



Is there a way to get this formated properly.


help(object)



If I use dir(numpy), I get yet a very long list that starts as:
['ALLOW_THREADS', 'BUFSIZE', 'CLIP', 'DataSource', 'ERR_CALL', 
'ERR_DEFAULT', 'ERR_DEFAULT2', 'ERR_IGNORE', 'ERR_LOG', 'ERR_PRINT', 
'ERR_RAISE', 'ERR_WARN', 'FLOATING_POINT_SUPPORT', 'FPE_DIVIDEBYZERO', 
'FPE_INVALID', 'FPE_OVERFLOW', 'FPE_UNDERFLOW', 'False_', 'Inf', 
'Infinity', 'MAXDIMS', 'MachAr', 'NAN', 'NINF', 'NZERO', 'NaN', 
'PINF', 'PZERO', 'PackageLoader', 'RAISE', 'RankWarning', 
'SHIFT_DIVIDEBYZERO', 'SHIFT_INVALID', 'SHIFT_OVERFLOW', 
'SHIFT_UNDERFLOW', 'ScalarType', 'Tester', 'True_', 
'UFUNC_BUFSIZE_DEFAULT'


I see this might be a dictionary. What can I do to make it more 
readable or useful, or is that it? Is there a more abc as in Linux?


You can use pprint module:

import pprint
pprint.pprint(dir(object))

though help() is usually better

It the IDLE shell, it's not possible to retrieve lines entered earlier 
without copying them. Is there an edit facility?


Press Alt+P (Previous) and Alt+N (Next). Or you can click/select on the 
line you want to copy and press Enter.



Add to this. Isn't there a way to see the arguments and descriptions of
functions?


Use help(). Or if you're doing this without human intervention, use 
`inspect` module.
Wow, did I get a bad result. I hit Ctrl-P, I think instead of Alt-P, and 
a little window came up showing it was about to print hundreds of pages. 
 I can canceled it, but too late. I turned off my printer quickly and 
eventually stopped the onslaught.


I couldn't get Alt-P or N to work.

Another question. In interactive mode, how does one know what modules 
are active? Is there a way to list them with a simple command?

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


Re: Live Video Capture using Python

2009-12-21 Thread W. eWatson

David Lyon wrote:

Also try..

http://www.unixuser.org/~euske/python/vnc2flv/index.html

On Mon, 21 Dec 2009 11:15:32 +0530, Banibrata Dutta
banibrata.du...@gmail.com wrote:

Have you searched the archives of this list ? I remember seeing a related
discussion 5-6 months back.

On Mon, Dec 21, 2009 at 2:35 AM, aditya shukla
adityashukla1...@gmail.comwrote:


Hello Guys,

I am trying to capture images from a live broadcast of a cricket match
or
say any video using python. I can see the video in the browser.My aim is
to
capture the video at any moment and create an images.Searching on google
turns up  http://videocapture.sourceforge.net/ .I am not sure if this
would be help here.I would appreciate if someone points me in the right
direction.


Thanks

Aditya

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


I somehow clipped the posts above this thread, so am not sure what 
prompted this thread. Is there an open source set of modules to do all this?

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


ANN: eGenix mx Base Distribution 3.1.3

2009-12-21 Thread eGenix Team: M.-A. Lemburg


ANNOUNCING

eGenix.com mx Base Distribution

   Version 3.1.3 for Python 2.3 - 2.6

   Open Source Python extensions providing
 important and useful services
for Python programmers.

This announcement is also available on our web-site for online reading:
http://www.egenix.com/company/news/eGenix-mx-Base-Distribution-3.1.3-GA.html



ABOUT

The eGenix.com mx Base Distribution for Python is a collection of
professional quality software tools which enhance Python's usability
in many important areas such as fast text searching, date/time
processing and high speed data types.

The tools have a proven record of being portable across many Unix and
Windows platforms. You can write applications which use the tools on
Windows and then run them on Unix platforms without change due to the
consistent platform independent interfaces.

Contents of the distribution:

 * mxDateTime - Date/Time Library for Python
 * mxTextTools - Fast Text Parsing and Processing Tools for Python
 * mxProxy - Object Access Control for Python
 * mxBeeBase - On-disk B+Tree Based Database Kit for Python
 * mxURL - Flexible URL Data-Type for Python
 * mxUID - Fast Universal Identifiers for Python
 * mxStack - Fast and Memory-Efficient Stack Type for Python
 * mxQueue - Fast and Memory-Efficient Queue Type for Python
 * mxTools - Fast Everyday Helpers for Python

All available packages have proven their stability and usefulness in
many mission critical applications and various commercial settings all
around the world.

For more information, please see the distribution page:

http://www.egenix.com/products/python/mxBase/



NEWS

The 3.1.3 release of the eGenix mx Base Distribution is the latest
release of our open-source Python extensions.

The new version addresses a serious problem with mxBeeBase on
BSD-based platforms such as FreeBSD and Mac OS X. We encourage all
users to upgrade to this new release.

As always, we are providing pre-built binaries for all supported
platforms: Windows 32-bit, Linux 32/64-bit, FreeBSD 32/64-bit, Mac OS X
32-bit Intel and PPC.

Whether you are using a pre-built package or the source distribution,
installation is a simple python setup.py install command in all
cases. The only difference is that the pre-built packages do not
require a compiler to be installed.

For a list of changes, please refer to the eGenix mx Base Distribution
change log at

http://www.egenix.com/products/python/mxBase/changelog.html

and the change logs of the various included Python packages.



DOWNLOADS

The download archives and instructions for installing the packages can
be found on the eGenix mx Base Distribution page:

http://www.egenix.com/products/python/mxBase/



LICENSE

The eGenix mx Base package is distributed under the eGenix.com Public
License 1.1.0 which is an Open Source license similar to the Python
license. You can use the packages in both commercial and non-commercial
settings without fee or charge.

The package comes with full source code



SUPPORT

Commercial support for this product is available from eGenix.com.
Please see

http://www.egenix.com/services/support/

for details about our support offerings.

Enjoy,
-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Dec 21 2009)
 Python/Zope Consulting and Support ...http://www.egenix.com/
 mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
 mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


::: Try our new mxODBC.Connect Python Database Interface for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
   http://www.egenix.com/company/contact/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: converting string to a date format

2009-12-21 Thread MRAB

tekion wrote:

Ben,
I do not have python 2.6 install, my version of Python is 2.4.
Because of my version of Python I believe I have to perform what you
have suggested:

This should, ideally, consist of two separate operations:

  * parse the string, using a specific format, to create a ‘datetime’
object

  * create a string representation of the datetime using your
preferred
string format

So I guess I am stuck on parsing the string 24/Nov/2009:12:00:00
-0500 using regex and or string function to get the output to
2009-11-24 12:00:00.  It looks like I may have to use regex to
accomplish this and also re-map Nov to 11.  Does any one have any
idea that would take 24/Nov/2009:HH:MM:SS and format it to
2009-11-24 HH:MM:SS? Thanks


If you don't have the 'datetime' module then you can use the 'time'
instead. Use time.strptime() to parse the string and time.strftime() to
create the new string.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Which version of MSVC?90.DLL's to distribute with Python 2.6 based Py2exe executables?

2009-12-21 Thread Jonathan Hartley
On Dec 17, 8:39 pm, Christian Heimes li...@cheimes.de wrote:
 Jonathan Hartley wrote:
  Only this week I sent a py2exe-derived executable to someone else (a
  non-developer) and it would not run on their WinXP machine ('The
  system cannot execute the specified program') - my current favourite
  hypothesis is that my omission of this dll or something similar was to
  blame.

  To diagnose what's wrong, I can't get access to the machine that gives
  the above error. To try and reproduce, I'm right now in the process of
  creating a bare-bones WindowsXP installed on a VM.

 MSVCR90 is a side-by-side assembly (SxS). You can't just copy a SxS
 assembly to another computer. You must at least ship the manifest file,
 too. The easiest way to get your program running is the installation of
 the MSVCR redistributable installer.

 Christian


Hey Christian,

Many thanks for that, but my issue is that my programs work fine for
me on my computer - but then fail on other people's computers. I'd
very strongly prefer for my users to not have to install the MSVCR
redistributable installer as well as my program - it would be much
better if I could bundle everything up into my py2exe package so that
it 'just works' on any Windows computer. So I think that means I'm
looking for a stand-alone DLL (or several, plus the manifest file, it
sounds like) to bundle up with my py2exe.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: which pi formula is given in the decimal module documentation?

2009-12-21 Thread Albert van der Horst
In article kv0dvx@spenarnc.xs4all.nl,
Albert van der Horst  alb...@spenarnc.xs4all.nl wrote:
In article a266b155-02df-4294-8b91-41be4a1e4...@a32g2000yqm.googlegroups.com,
Mark Dickinson  dicki...@gmail.com wrote:
On Dec 11, 10:30=A0am, Mark Dickinson dicki...@gmail.com wrote:
  It looks like an infinite series with term `t`, where`n` =3D (2k-1)^2
  and `d` =3D d =3D 4k(4k+2) for k =3D 1... Does it have a name?

 Interesting. =A0So the general term here is
 3 * (2k choose k) / (16**k * (2*k+1)), =A0k =3D 0.

 I've no idea what its name is or where it comes from, though. =A0I
 expect Raymond Hettinger would know.

After a cup of coffee, it's much clearer:  this just comes from the
Taylor series for arcsin(x), applied to x =3D 1/2 to get asin(1/2) =3D pi/
6.

Curious. It seems better to calculate the zero of sin(pi/6)-1/2.
Not that we can forego the need of a Taylor series, but sin
converges much faster than arcsin.
The derivative is known analytically, and we have a 5th order process
before we know it.
It would be a big win for large precisions.
(Especially if we remember a previous value of pi to start up.)
The trick with temporarily increasing precision could be superfluous.

(I implemented this once in FORTRAN and was much disappointed that
double precision wasn't enough to show off the 5th order convergence. )

--
Mark

Groetjes Albert

What the heck. I tried it all out. It turns out that sin(pi/6)=.5
is not favourable because the derivative contains sqrt(3)
So I tried to find the zero of cos(x) near pi/2 which is pi/2.
The derivative of the cos is -sin. So a better approximation than
x is x+cos(x). The second derivative is cos which is zero.
The third derivative is again -cos(x).
So a still better approximation is x+cos(x)+cos(x)^3/6.
This can be iterated. [The remaining error is 3/40.cos(x)^5.
I found that experimentally and a proof is left to the reader.]

Below you see cos which just calculates cosine with a
Taylor series.
Then there is pi2() that uses it to calculate pi, for the
normal fp precision.
pi3() shows the algorithm in its glory and should work for
any floating point package.
pi4() does the same, if precision is given.
And last but not least pi5() that uses the Decimal package
to advantage. It precalculates a starting point in 1/5 of
the precision. Then it does one more iteration in the full precision.
For 1000 digits it is about 5 times faster than pi(), for
a moderate increase in complexity.

# --- 88---
# $Id: pi.py,v 1.3 2009/12/21 19:01:15 albert Exp albert $
# Copyright (2008): Albert van der Horst {by GNU Public License}
# http:// docs.python.org/library/decimal.html#recipes

from decimal import getcontext,Decimal

def pi():
Compute Pi to the current precision.

 print pi()
3.141592653589793238462643383


getcontext().prec += 2  # extra digits for intermediate steps
three = Decimal(3)  # substitute three=3.0 for regular floats
lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
while s != lasts:
print s
lasts = s
n, na = n+na, na+8
d, da = d+da, da+32
t = (t * n) / d
s += t
getcontext().prec -= 2
return +s   # unary plus applies the new precision


def cos(halfpi):
Compute cos of halfpi

x = halfpi**2
t = 1
lasts = 1
s = 0 # First term is actually 1
n=1

while s != lasts:
print s
lasts = s
t = -t*x / (n*(n+1))
n += 2
s += t

# Add 1 now, this saves iterations that don't contribute to precision.
return 1+s

def pi2():
' Calculate pi by a correction based on derivatives '
x=1.57
q=cos(1.57)
# Deviation 3/40.q^5
return 2*(x+q+q**3/6)

def pi3():
' Calculate pi by a 5th order process '
x=1.5
xold =1.
while x != xold:
xold  = x
q = cos(x)
x += q*(1+q*q/6)
return 2*x

def pi4():
' Calculate pi by a 5th order process, with favorable stop criterion'
precision = 10e-20
rp = precision ** .2 # Required precision with room to spare.
print rp
x=1.5
q=1
while qrp:
q = cos(x)
x += q*(1+q*q/6)
return 2*x

def pi5():
' Calculate pi by a 5th order process, adjusting precision'
oldprec = getcontext().prec
getcontext().prec = oldprec/4+1
rp = Decimal(10)**(-getcontext().prec+1)

x=Decimal(1.5)
q = x
while q rp:
print x,q,rp
q = cos(x)
x += q*(1+q*q/6)

# One more iteration with full precision
getcontext().prec = oldprec + 2
q = cos(x)
x += q*(1+q*q/6)
getcontext().prec = oldprec
return 2*x
# --- 88---


--
--
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
alb...@spearc.xs4all.nl =n http://home.hccnet.nl/a.w.m.van.der.horst



--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS

Re: Anybody use web2py?

2009-12-21 Thread Yarko
On Dec 21, 2:50 am, Bruno Desthuilliers bruno.
42.desthuilli...@websiteburo.invalid wrote:
 mdipierro a écrit :
...
  This means you do not need to import
  basic web2py symbols. They are already defined in the environment that
  executes the models and controllers

 Ok. As far as I'm concerned : show stops here.

Sorry- I don't _think_ I'm following:  If you want to write an app all
yourself, and use components to put it together, that's fine - more
control, and more responsibility (e.g. watch for security, etc.).

But most web applications simply do not require or justify this much
effort spent on this level of responsibility;  but maybe I'm missing
something less obvious that you mean, that makes the show stop here
for you.  If so, maybe you can be a bit more explicit about it.



  - You have a web based IDE with editor,

 Why should I care ? I have a way better development environment on my
 own box.


For example, on a running system, simple things are possible simply:
change the cutoff date on something; change a class size.  Yeah, sure
- my app could write a controller for all those _little_ unanticipated
tweaks that inevitably come, but why bother?  You can just do it with
existing environment:   Want 100 coupons for that vendor?  No problem
(lets say that's in a controller).   Want to make it a special thingy
for that special vendor - put his image on his coupons? his words and
instructions?  Ok - I suppose i might have written a wiki interface so
someone can do this one thing, this one time - but (again) why
bother?  I'll do it thru the dev. interface on a running system.  If
I'm convinced it was an un-captured requirement (e.g. no one thought
of it until the system was running, or it was assumed but somehow
missed by everyone)  then I'll write the associated code, and add it
to the running system.  In fact, this is quite an agile way to do
it.   Both the dev. environ, and the command line shell help in this
(I can write a small loop in the shell to effect what might be a
controller for a customer, and output to a file instead of a view, and
ask the customer Is this what you're looking for?  - tweak, confirm
happy client, and then put the code I just used into a controller - if
it's short enough, right in the interface on the running system, and
have the client try it while we're still on the phone/IM/whatever.

The things I didn't think would be that useful - proved to have useful
application.


..

 Now FWIW, when my schema do change, the create/alter table code is
 usually the most trivial part - there are quite a few other things to
 do, that no framework will ever be abale to guess. IOW, you *do* have to
 write a migration script anyway.

In practice, this is /should be much less than you would think...
ADDING columns to tables is simple.
REMOVING columns... perhaps unnecessary on running systems...
ALTERING columns... can probably be handled instead by adding.

I think for most useful (and certain development time) cases, the
framework can do reasonable things, usefully.  But I do not deny that
there are cases where there is not way around doing things smarter
than that.  I think it is just that there are times where that is not
as necessary as at first appears.


.

 Once again, while doing a quick dummy test app can give you a first
 general feel of the tool, it means nothing wrt/ complex real-world
 applications.

Actually, I agree - and I would go a bit further:  NO FRAMEWORK / tool
has anything much to do wrt/ complex real-world apps.  In fact, at the
framework / coding level, things should be as simple as possible (that
is where the cost is, anyway).

Good analysis of the problem domain will suggest the shape of the
solution needed.   Prototyping will then help with things like can it
be a web app? and what technologies / implementation languages are
appropriate?  Once you're at that stage, _any tool_ (and most likely,
combination of tools / set of tools) come into play: what do they do
to help at this level, how do they enable the process you want to
follow, how do they get out of the way.  Are they too rigid (too many
defaults / too few options for a given solution decision)?

But this is so far down the path of designing a solution that complex
real-world doesn't fitthis discussion, without getting more specific,
e.g. _a_ specific real-world app.   For PyCon, web2py registration was
done, reviewed, and put into place with little more than a month's
worth of discussion / prep.  Yeah, it didn't look like the main
PyCon site the first year (and didn't take much at all to change that
when I decided to).  Yeah, there are still details about integrating
w/ the django part of the site that could be taken care of from the
web2py end (I don't know, but was lead to believe it would be easier
from the web2py end than the django end, e.g. multiple database
connections).  As with many projects, if it is volunteer programming,
and if it's _really_ important, it will happen, or if 

Re: Which version of MSVC?90.DLL's to distribute with Python 2.6 based Py2exe executables?

2009-12-21 Thread Jonathan Hartley
On Dec 17, 11:16 pm, Mark Hammond skippy.hamm...@gmail.com wrote:
 On 18/12/2009 7:44 AM, Ross Ridge wrote:

  The P DLL is for C++ and so the original poster may not actually need
  it.  I'm pretty sure Python itself doesn't need it, and py2exe shouldn't
  either, but wxPython, or more precisely wxWidgets, almost certainly does.
  So in your case you'll probably need to redistribute both DLLs.

 FYI, my experience is that an entire manifest must be distributed.  As
 the manifest in question actually lists 3 DLLs, IIUC, you must ship all
 4 files - the 3 DLLs and the manifest, even if only one of the DLLs is
 actually used.

 This is from memory some time back though, so apologies in advance if
 I'm mis-remembering.

 Mark


Thanks to everyone who replied, especially Ross obviously for such
comprehensive info.

I'll go percolate on what you wrote, and try some experiments on my
new VM, see if it all makes sense for me when I put it into practice.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which version of MSVC?90.DLL's to distribute with Python 2.6 based Py2exe executables?

2009-12-21 Thread Ross Ridge
Jonathan Hartley  tart...@tartley.com wrote:
Many thanks for that, but my issue is that my programs work fine for
me on my computer - but then fail on other people's computers. I'd
very strongly prefer for my users to not have to install the MSVCR
redistributable installer as well as my program - it would be much
better if I could bundle everything up into my py2exe package so that
it 'just works' on any Windows computer. So I think that means I'm
looking for a stand-alone DLL (or several, plus the manifest file, it
sounds like) to bundle up with my py2exe.

Microsoft's documentation describes several possible ways you can
redistribute the Visual C++ runtime:

http://msdn.microsoft.com/en-us/library/ms235299.aspx

From the sounds of things, if you only have Visual C++ 2008 Express your
only option may be to use Visual C++ Redistributable Package.

Ross Ridge

-- 
 l/  //   Ross Ridge -- The Great HTMU
[oo][oo]  rri...@csclub.uwaterloo.ca
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Windows, IDLE, __doc_, other

2009-12-21 Thread Lie Ryan

On 12/22/2009 6:39 AM, W. eWatson wrote:

Wow, did I get a bad result. I hit Ctrl-P, I think instead of Alt-P, and
a little window came up showing it was about to print hundreds of pages.
I can canceled it, but too late. I turned off my printer quickly and
eventually stopped the onslaught.

I couldn't get Alt-P or N to work.

Another question. In interactive mode, how does one know what modules
are active? Is there a way to list them with a simple command?


What do you mean by active? All loaded modules, whether it is in your 
namespace or not? Then sys.modules.
Else if you want all names in your namespace, dir() would do, though 
it'll show other things as well.

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


RotatingFileHandler key error when parsing a logging config file

2009-12-21 Thread jordilin
Hi,
 I've a config for logging where I set up a file rotation with
handlers.RotatingFileHandler and when the app parses the logging
config it says keyError when trying to parse that section
('RotatingFileHandler' is not defined). Curiously enough, I can do
import logging and from logging.handlers import RotatingFileHandler.

Example:

[handlers]
keys=handlers.RotatingFileHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=handlers.RotatingFileHandler

[handler_handlers.RotatingFileHandler]
class=handlers.RotatingFileHandler
level=DEBUG
formatter=simpleFormatter


I'm using python 2.4 in the servers. I'm having this in a particular
one, which seems like there must be some kind of configuration error.
Any suggestions,
Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ch 3 of my writings, first few sections posted

2009-12-21 Thread Alf P. Steinbach

This is an introduction to programming based on Python 3.x in Windows.

It's posted as PDFs on Google Docs.

Currently 2 full chapters plus a little of chapter 3, about 120 pages in total; 
chapters 1 and 2 reviewed by [comp.programming] and [comp.lang.python] residents 
(although I have no doubt that there are many errors etc., all mine!).



* Alf P. Steinbach, in [comp.lang.python]:

Tentatively titled Foundations.

Also, these first 2/3 sections may be moved to some later point, i.e. 
even the structure is tentative, but I'd value comments!


  url: http://tinyurl.com/programmingbookP3

Table of contents:

3  Foundations 1
3.1  Some necessary math notation  terminology. 2
3.1.1  The vocabulary and notation of basic arithmetic, including Σ and 
Π. 2

3.1.2  Quadratic and exponential time  memory (also introducing timeit). 5
-EOT_ 9


Cheers,

- Alf

PS: Hm, Open Office's PDF generation does funny things with Greek sigmas 
inside formulas! I don't mind so much that it makes table divider lines 
very fat and bold and that it can't handle certain figures (which I have 
to paste in manually as bitmaps), but really it should be able to handle 
simple text. Grr.


I forgot to cross-post this to [comp.programming], the quoted article above was 
only posted to [comp.lang.python]. I now cross-posted it also to 
[comp.lang.c++]. I know, it's a bit OT in clc++, but it makes a nice contrast, 
and can be relevant for all those threads about how do I learn programming...


And I've now posted an updated and full table of contents to Google Docs site, 
URL above.


Comments very welcome  --  now it's Christmas and I'll probably not be able to 
respond or fix anything until early January, but still comments very welcome!



Cheers,

- Alf


PS: For clc++: why did I give up writing a beginner's book based on C++? Well, 
for one, in C++ it got too complicated and long the way I wanted it, real. And 
secondly, Francis, Andrew  Barbara and Bjarne have by now got that covered!


PPS: Also for clc++: where is my C++ tutorial, referenced from the FAQ (§29.21)? 
Well, first it moved to another URL, since [start.no] discontinued their 
service. Then that new free provider ceased to exist, so that now it's nowhere, 
and I've forgotten all about it. And probably will, yet again! I've CC-ed this 
to Marshall Cline so that perhaps he can update the FAQ to e.g. 
[http://cplusplus.com/doc/tutorial/], which by now is, well, acceptable quality!

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


Re: How to validate the __init__ parameters

2009-12-21 Thread r0g
Denis Doria wrote:
 Hi;
 
 I'm checking the best way to validate attributes inside a class. Of
 course I can use property to check it, but I really want to do it
 inside the __init__:
 
 class A:
 def __init__(self, foo, bar):
 self.foo = foo #check if foo is correct
 self.bar = bar
 
 All examples that I saw with property didn't show a way to do it in
 the __init__. Just to clarify, I don't want to check if the parameter
 is an int, or something like that, I want to know if the parameter do
 not use more than X chars; and want to do it when I'm 'creating' the
 instance; not after the creation:
 
 a = A('foo', 'bar')
 
 not
 
 class A:
 def __init__(self, foo = None, bar = None):
 self._foo = foo
 self._bar = bar
 def  set_foo(self, foo):
 if len(foo)  5:
  raise something
 _foo = foo
 foo = property(setter = set_foo)
 
 a = A()
 a.foo = 'foo'
 
 
 I thought in something like:
 
 class A:
 def __init__(self, foo = None, bar = None):
 set_foo(foo)
 self._bar = bar
 def  set_foo(self, foo):
 if len(foo)  5:
  raise something
 _foo = foo
 foo = property(setter = set_foo)
 
 But looks too much like java



I use assertions myself e.g.

 foo = 123456
 assert len(foo) = 5
Traceback (most recent call last):
  File stdin, line 1, in module
AssertionError


Dunno if this would be considered good or bad programming practice by
those more experienced than I (comment always welcome!) but it works for
me :)


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


Re: How to validate the __init__ parameters

2009-12-21 Thread Steven D'Aprano
On Mon, 21 Dec 2009 09:41:22 -0800, Denis Doria wrote:

 Hi;
 
 I'm checking the best way to validate attributes inside a class. 

There is no best way, since it depends on personal taste.


 Of
 course I can use property to check it, but I really want to do it inside
 the __init__:

If you really want to do it inside the __init__, then copy the code 
that you would put in the property's setter into the __init__ method. But 
why do you care that the check is inside the __init__ method? All that is 
really important is that the __init__ method *calls* the check, not where 
the check lives.



 class A:
 def __init__(self, foo, bar):
 self.foo = foo #check if foo is correct
 self.bar = bar

Here are some ways of doing this, more or less in order of complexity and 
difficulty.


(1) Don't validate at all. Just document that foo must be no more than 
five characters long, and if the caller pays no attention and passes a 
too-long string, any explosions that happen are their fault, not yours.

class A:
Class A does blah blah.
If foo is longer than five characters, behaviour is undefined.

def __init__(self, foo = None, bar = None):
self.foo = foo
self.bar = bar

(This may seem silly, but for more difficult constraints which are hard 
to test, it may be your only choice.)


(2) Validate once only, at initialisation time:

class A:
def __init__(self, foo = None, bar = None):
if len(foo)  5:
raise ValueError(foo is too big)
self.foo = foo
self.bar = bar


Note that further assignments to instance.foo will *not* be validated.


(3) Move the validation into a method. This is particularly useful if the 
validation is complex, or if you expect to want to over-ride it in a sub-
class.

class A:
def __init__(self, foo = None, bar = None):
self.validate(foo)
self.foo = foo
self.bar = bar
def validate(self, foo):
if len(foo)  5:
raise ValueError(foo is too big)


Further assignments to instance.foo are still not validated.


(4) Validate on every assignment to foo by using a property. Note that 
for this to work, you MUST use a new-style class. In Python 3, you don't 
need to do anything special, but in Python 2.x you must inherit from 
object:

class A(object):
def __init__(self, foo = None, bar = None):
self.foo = foo  # calls the property setter
self.bar = bar
def _setter(self, foo):
if len(foo)  5:
raise ValueError(foo is too big)
self._foo = foo
def _getter(self):
return self._foo
foo = property(_getter, _setter, None, optional doc string for foo)


If you think this looks too much like Java, well, sorry, but that's 
what getters and setters look like. But note that you never need to call 
the getter or setter explicitly, you just access instance.foo as normal.


(5) Use explicit Java-style getter and setter methods. This avoids using 
property, so it doesn't need to be a new-style class:

class A:
def __init__(self, foo = None, bar = None):
self.setfoo(foo)
self.bar = bar
def setfoo(self, foo):
if len(foo)  5:
raise ValueError(foo is too big)
self._foo = foo
def getfoo(self):
return self._foo

If you want to write Java using Python syntax, this may be the solution 
for you. But be aware that Python programmers will laugh at you.


(5) If the constraint on foo is significant enough, perhaps it should be 
made part of the type of foo.

class FooType(str):  # or inherit from list, or whatever...
def __init__(self, x):
if len(x)  5:
raise ValueError(initial value is too big, invalid FooType)


class A:
def __init__(self, foo = None, bar = None):
self.foo = FooType(foo)
self.bar = bar
 

Other, more complex solutions include using decorators or even metaclass 
programming. Don't worry about these at this point, I'm just showing off 
*wink*


Hope this helps,




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


Re: Windows, IDLE, __doc_, other

2009-12-21 Thread W. eWatson

Lie Ryan wrote:

On 12/22/2009 6:39 AM, W. eWatson wrote:

Wow, did I get a bad result. I hit Ctrl-P, I think instead of Alt-P, and
a little window came up showing it was about to print hundreds of pages.
I can canceled it, but too late. I turned off my printer quickly and
eventually stopped the onslaught.

I couldn't get Alt-P or N to work.

Another question. In interactive mode, how does one know what modules
are active? Is there a way to list them with a simple command?


What do you mean by active? All loaded modules, whether it is in your 
namespace or not? Then sys.modules.
Else if you want all names in your namespace, dir() would do, though 
it'll show other things as well.
Let's forget active. Isn't it true that math is automatically available 
to every module? From help(math):


Help on built-in module math:

NAME
math

FILE
(built-in)

DESCRIPTION
This module is always available.  It provides access to the
mathematical functions defined by the C standard.
=
So why do I need math.cos(...)? This is got to be some namespace issue.

Maybe the help is incorrect. I have:
 dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 
'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 
'Exception', 'False', 'FloatingPointError', 'FutureWarning', 
'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 
'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 
'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 
'NotImplementedError', 'OSError', 'OverflowError', 
'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 
'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 
'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 
'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 
'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 
'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 
'WindowsError', 'ZeroDivisionError', '_', '__debug__', '__doc__', 
'__import__', '__name__', 'abs', 'all', 'any', 'apply', 'basestring', 
'bool', 'buffer', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 
'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 
'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 
'float', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 
'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 
'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min', 
'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range', 
'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 
'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 
'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']

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


Re: converting string to a date format

2009-12-21 Thread tekion
On Dec 21, 3:05 pm, MRAB pyt...@mrabarnett.plus.com wrote:
 tekionwrote:
  Ben,
  I do not have python 2.6 install, my version of Python is 2.4.
  Because of my version of Python I believe I have to perform what you
  have suggested:

  This should, ideally, consist of two separate operations:

    * parse the string, using a specific format, to create a ‘datetime’
      object

    * create a string representation of the datetime using your
  preferred
      string format

  So I guess I am stuck on parsing the string 24/Nov/2009:12:00:00
  -0500 using regex and or string function to get the output to
  2009-11-24 12:00:00.  It looks like I may have to use regex to
  accomplish this and also re-map Nov to 11.  Does any one have any
  idea that would take 24/Nov/2009:HH:MM:SS and format it to
  2009-11-24 HH:MM:SS? Thanks

 If you don't have the 'datetime' module then you can use the 'time'
 instead. Use time.strptime() to parse the string and time.strftime() to
 create the new string.

Thanks.  This is what I have:

time.strftime(%Y-%m-%d %H:%M:%S, time.strptime(24/Nov/
2009:12:00:00, %d/%b/%Y:%H:%M:%S)

and it seems to work.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: converting string to a date format

2009-12-21 Thread Ben Finney
tekion tek...@gmail.com writes:

 Ben,
 I do not have python 2.6 install, my version of Python is 2.4.

Ouch :-( Upgrade as soon as possible, 2.4 is no longer receiving bug
fixes URL:http://www.python.org/download/releases/2.4.6/.

 So I guess I am stuck on parsing the string 24/Nov/2009:12:00:00
 -0500 using regex and or string function

No, as I suggested, you can use the ‘datetime.datetime’ constructor with
the ‘time.strptime’ output. You only have available the formatting in
URL:http://docs.python.org/library/time.html#time.strftime, so the
numeric time zone will be un-parseable by ‘time.strptime’::

 import datetime
 import time
 in_text = 24/Nov/2009:12:00:00 -0500
 in_time_format = %d/%b/%Y:%H:%M:%S %Z
 time.strptime(in_text, in_time_format)
Traceback (most recent call last):
  File stdin, line 1, in ?
  File /usr/lib/python2.4/_strptime.py, line 293, in strptime
raise ValueError(time data did not match format:  data=%s  fmt=%s %
ValueError: time data did not match format:  data=24/Nov/2009:12:00:00 
-0500  fmt=%d/%b/%Y:%H:%M:%S %Z

Instead you'll need to do as has already been suggested: strip the
numeric time zone and parse the remaining data::

 in_text = 24/Nov/2009:12:00:00 -0500.split(' ', 1)[0]
 in_text
'24/Nov/2009:12:00:00'
 in_time_format = %d/%b/%Y:%H:%M:%S
 time.strptime(in_text, in_time_format)
(2009, 11, 24, 12, 0, 0, 1, 328, -1)

and use the hack documented in Python 2.6's ‘datetime.datetime.strptime’
function to create a ‘datetime’ object::

 in_time = datetime.datetime(*(time.strptime(in_text, 
in_time_format)[0:6]))
 in_time
datetime.datetime(2009, 11, 24, 12, 0)

The benefit of upgrading to Python 2.6 is that you don't need to go
through these contortions with the ‘time’ type's output, you can use the
new ‘datetime.datetime.strptime’ method to get there in one step
URL:http://docs.python.org/library/datetime.html#datetime.datetime.strptime.

 to get the output to 2009-11-24 12:00:00.

Once you have a ‘datetime’ object, you can use its ‘strftime’ function
URL:http://docs.python.org/library/datetime.html#strftime-behavior to
create a string representation::

 out_time_format = %Y-%m-%d %H:%M:%S
 in_time.strftime(out_time_format)
'2009-11-24 12:00:00'

-- 
 \  “I find the whole business of religion profoundly interesting. |
  `\ But it does mystify me that otherwise intelligent people take |
_o__)it seriously.” —Douglas Adams |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Line indexing in Python

2009-12-21 Thread r0g
seafoid wrote:
 Hi Guys,
 
 When python reads in a file, can lines be referred to via an index?
 
 Example:
 
 for line in file:
  if line[0] == '0':
  a.write(line)
 
 This works, however, I am unsure if line[0] refers only to the first line or
 the first character in all lines.
 
 Is there an easy way to refer to a line with the first character being a
 single letter that you know?
 
 Thanks in advance,
 Seafoid.


If you want to know the index number of an item in a sequence you are
looping through (whether it be a file of lines or a list of characters,
whatever) use enumerate...

 for index, value in enumerate(ABCD):
print index, value
...
0 A
1 B
2 C
3 D


If you want to extract an index number from the first part of of a given
line use split( split_character, maximum_splits_to_do ) and then angle
brackets to reference the first part (index 0)...


 a = 20 GOTO 10
 int( a.split(' ',1)[0] )
20


Cheers,


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


Re: Windows, IDLE, __doc_, other

2009-12-21 Thread Stephen Hansen
On Mon, Dec 21, 2009 at 1:51 PM, W. eWatson wolftra...@invalid.com wrote:
 Lie Ryan wrote:

 On 12/22/2009 6:39 AM, W. eWatson wrote:

 Wow, did I get a bad result. I hit Ctrl-P, I think instead of Alt-P, and
 a little window came up showing it was about to print hundreds of pages.
 I can canceled it, but too late. I turned off my printer quickly and
 eventually stopped the onslaught.

 I couldn't get Alt-P or N to work.

 Another question. In interactive mode, how does one know what modules
 are active? Is there a way to list them with a simple command?

 What do you mean by active? All loaded modules, whether it is in your
 namespace or not? Then sys.modules.
 Else if you want all names in your namespace, dir() would do, though it'll
 show other things as well.

 Let's forget active. Isn't it true that math is automatically available to
 every module? From help(math):

No, its not true. A built-in module does not mean its available
everywhere. It means its built into Python itself-- e.g., its directly
linked into the python dll and not a separate file (like most of the
the standard library).

Lots of modules are built-in, but they don't pollute the __builtins__
/ universal namespace. You import them to access them. If you want you
can from math import * if you want the math module to fill out your
module namespace (I don't recommend *'s personally, its better to
import symbols explicitly by name)

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


Re: How to validate the __init__ parameters

2009-12-21 Thread Lie Ryan

On 12/22/2009 4:41 AM, Denis Doria wrote:

Hi;

I'm checking the best way to validate attributes inside a class. Of
course I can use property to check it, but I really want to do it
inside the __init__:

class A:
 def __init__(self, foo, bar):
 self.foo = foo #check if foo is correct
 self.bar = bar



A nice sugar to do that:

import functools

class CheckError(Exception): pass

def func_check(*argcheckers):
def _checked(func):
def _function(*args):
res = [(check(arg), check, arg) for check, arg in 
zip(argcheckers, args)]

if all(r[0] for r in res):
return func(*args)
else:
raise CheckError(filter(lambda x: x[0] == False, res))
return _function
return _checked

method_check = functools.partial(func_check, lambda a: True)

##
def check_foo(arg):
return 5 = arg = 10

def check_bar(arg):
return 10 = arg  20

class A(object):
@method_check(check_foo, check_bar)
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
--
http://mail.python.org/mailman/listinfo/python-list


Re: Class variables static by default?

2009-12-21 Thread Steven D'Aprano
On Mon, 21 Dec 2009 15:03:03 +0100, Daniel Fetchinson wrote:

 I don't think Steven cares much, he loves this type of nitpicking and
 uber pedantic formulations, but only if he can apply it to other
 people's post :)

Heh heh :)

I actually do care, because (not having a Java/C++ background) I actually 
do get a mental double-take every time I read about class variables. 
It takes a real effort of will to remind myself that they're probably not 
talking about something like this:

for theclass in (int, float, Decimal, Fraction):
do_something_with(theclass)




 I found that his posts are generally useful and helpful, one just has to
 cut all the nitpicking, ...

Technically you don't have to cut *all* the nitpicking, cutting 87.3% of 
it is sufficient.


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


ANN: logbuilder 0.1.0a

2009-12-21 Thread Filip Gruszczyński
This is a one-time post to annouce the creation of logbuilder project,
an open source tool for change log creation based on version control
commit messages. Using conventions in commit messages logbuilder
detects messages that can be imported into the change log and
painlessly creates on for every version of software.

Home page: http://code.google.com/p/logbuilder/

Features:
* Subersion support
* Mercurial support
* Filtering using wildcards, regular expressions and string matching
* (planned) Using templates for displaying results

Requirements:
* Python 2.6+
* pysvn or mercurial

For more information, please come to http://code.google.com/p/logbuilder/.

-- 
Filip Gruszczyński
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to register with pypi

2009-12-21 Thread Martin v. Loewis
 I'm stuck on the PGP Key ID. When I whip out my trusty Ubuntu and run
 pgp -kg, I get a 16-digit DSA / EIGamal key.
 
 When I enter it into http://pypi.python.org/pypi?%3Aaction=register_form
 , I get a helpful PGP Key ID is invalid.
 
 Should I try a key of some other algorithm?

If you merely try to register with PyPI, you don't need to provide a PGP
key id at all.

The key ID should be an eight-digit string, such as EA5BBD71 (i.e. a
32-bit key ID).

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


Re: how to register with pypi

2009-12-21 Thread Phlip

Martin v. Loewis wrote:

I'm stuck on the PGP Key ID. When I whip out my trusty Ubuntu and run
pgp -kg, I get a 16-digit DSA / EIGamal key.

When I enter it into http://pypi.python.org/pypi?%3Aaction=register_form
, I get a helpful PGP Key ID is invalid.

Should I try a key of some other algorithm?


If you merely try to register with PyPI, you don't need to provide a PGP
key id at all.


I want to upload a crypto library I invented.

That's a joke. But I want to upload a library.


The key ID should be an eight-digit string, such as EA5BBD71 (i.e. a
32-bit key ID).


pretend I was someone who had never ever used PGP before.

pgp -kg, then what?
--
http://mail.python.org/mailman/listinfo/python-list


Re: numpy performance and random numbers

2009-12-21 Thread r0g
sturlamolden wrote:
 On 19 Des, 16:20, Carl Johan Rehn car...@gmail.com wrote:
 
 How about mulit-core or (perhaps more exciting) GPU and CUDA? I must
 admit that I am extremely interested in trying the CUDA-alternative.

 Obviously, cuBLAS is not an option here, so what is the safest route
 for a novice parallel-programmer?
 
 The problem with PRNG is that they are iterative in nature, and
 maintain global states. They are therefore very hard to vectorize. A
 GPU will not help. The GPU has hundreds of computational cores that
 can run kernels, but you only get to utilize one.
 
 Parallel PRNGs are an unsolved problem in computer science.
 
 
 
 
 



Surely you could have as many totally independent cores as you like
independently spitting out random bits whenever they feel like it to
make an equally random bitstream?  would have thought the only issue
would be ensuring high quality bitstream was used to seed each thread no?

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


Re: Windows, IDLE, __doc_, other

2009-12-21 Thread W. eWatson

Stephen Hansen wrote:

On Mon, Dec 21, 2009 at 1:51 PM, W. eWatson wolftra...@invalid.com wrote:

Lie Ryan wrote:

On 12/22/2009 6:39 AM, W. eWatson wrote:

Wow, did I get a bad result. I hit Ctrl-P, I think instead of Alt-P, and




No, its not true. A built-in module does not mean its available
everywhere. It means its built into Python itself-- e.g., its directly
linked into the python dll and not a separate file (like most of the
the standard library).

Lots of modules are built-in, but they don't pollute the __builtins__
/ universal namespace. You import them to access them. If you want you
can from math import * if you want the math module to fill out your
module namespace (I don't recommend *'s personally, its better to
import symbols explicitly by name)

--S
This has got to be some sort of IDLE issue then. When I run a simple 
program. If I open this program in the IDLE editor:

#import math
print hello, math world.
print cos(0.5)
print sin(0.8)

then I get
print cos(0.5)
NameError: name 'cos' is not defined

OK,  dir()
['__builtins__', '__doc__', '__file__', '__name__', 'idlelib']

Fine. I now change the code to include import mat get the same:
print cos(0.5)
NameError: name 'cos' is not defined

Now,  dir()
['__builtins__', '__doc__', '__file__', '__name__', 'idlelib', 'math']

math is now available. so I change cos(0.5) to math.cos(0.5) and get
print sin(0.8)
NameError: name 'sin' is not defined
Fine, it needs math.
dir() is the same.

Now, I go to the script and enter
from math import *
dir is now bulked up with the math functions. I change back math.cos to 
cos and the program runs well.


This sort of figures. Apparently, I've added to the namespace by 
importing with *.


My point is that I'm betting different results. OK, fine. It appears the 
same thing happens with I modify the program itself with from math import *


So IDLE is not clearing the namespace each time I *run* the program. 
This is not good. I've been fooled. So how do I either clear the 
namespace before each Run? Do I have to open the file in the editor 
again each time before trying to Run it? I hope there's a better way.


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


Re: C Structure rebuild with ctypes

2009-12-21 Thread Georg
Hi Mark,

many thanks for your help. I tried your code in my program and it worked.

I would like to understand what the code is doing and I have some questions 
to it.

 Are you passing in these values, or are they being returned?  To me the 
 depth of the pointer references implies numVars, varNames, and varTypes 
 are out parameters. I'll assume that for now.  If they are in/out 
 parameters let me know.

Your exactly right: the parameters numVars, varNames and VarTypes are out
paramters.

 I mocked up a DLL to test returning values of these types.  I used VS2008 
 and compiled with cl /LD func.c:

 --- func.c ---
 #include stdlib.h
 #define FUNCDLL
 #include func.h

 static char* g_data[] = {one,two,three};
 static int g_types[] = {1,2,3};

 FUNCAPI int func (int handle, int *numVars, char ***varNames, int 
 **varTypes)
 {
 *numVars = _countof(g_data);
 *varNames = g_data;
 *varTypes = g_types;
 return handle + 1;
 }

What does the signature FUNCAPI do in this context?




 --- func.h ---
 #ifdef FUNCDLL
 #define FUNCAPI __declspec(dllexport)
 #else
 #define FUNCAPI __declspec(dllimport)
 #endif

 FUNCAPI int func (int handle, int *numVars, char ***varNames, int 
 **varTypes);


Do I need to wrap the compiled DLL file this way? I can load the DLL with 
the CDLL method, make calls to simple functions, e.g. no parameters, 
returning stirng and get the right values.


I added all the code from your func.py module to the code I already had. 
And -- it works fine and delivers the expected results.

 --- func.py ---
... cut ...

 # int func (int handle, int *numVars, char ***varNames, int **varTypes)
 func = c.CDLL('func').func
 func.restype = INT
 func.argtypes = [INT,PINT,PPPCHAR,PPINT]

I added this part to my program.

 # allocate storage for the out parameters
 numVars = INT()
 varNames = PPCHAR()
 varTypes = PINT()

I added this part also.

 print func(5,c.byref(numVars),c.byref(varNames),c.byref(varTypes))

I called the library routine.

 # numVars contains size of returned arrays.  Recast to access.
 varNamesArray = c.cast(varNames,c.POINTER(PCHAR * numVars.value))
 varTypesArray = c.cast(varTypes,c.POINTER(INT * numVars.value))

What does this cast? How do I know how I have to cast the objects returned 
from the library function?

What kind of objects do I get? I learned that the values of objects created 
by the ctypes module are accessed using object.value?

Best regards

Georg


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


Threading with queues

2009-12-21 Thread Gib Bogle

Hi,
I'm learning Python, jumping in the deep end with a threading application.  I 
came across an authoritative-looking site that recommends using queues for 
threading in Python.

http://www.ibm.com/developerworks/aix/library/au-threadingpython/index.html
The author provides example code that fetches data from several web sites, using 
threads.  I have modified his code slightly, just adding a couple of print 
statements and passing an ID number to the thread.


#!/usr/bin/env python
import Queue
import threading
import urllib2
import time

hosts = [http://yahoo.com;, http://google.com;, http://amazon.com;, 
http://ibm.com;, http://apple.com;]


queue = Queue.Queue()

class ThreadUrl(threading.Thread):
#Threaded Url Grab
  def __init__(self, queue,i):
threading.Thread.__init__(self)
self.queue = queue
self.num = i
print Thread: ,self.num

  def run(self):
while True:
  #grabs host from queue
  host = self.queue.get()
  print num, host: ,self.num,host
  #grabs urls of hosts and prints first 1024 bytes of page
  url = urllib2.urlopen(host)
  print url.read(1024)

  #signals to queue job is done
  self.queue.task_done()

start = time.time()
def main():

  #spawn a pool of threads, and pass them queue instance
  for i in range(5):
t = ThreadUrl(queue,i)
t.setDaemon(True)
t.start()

 #populate queue with data
for host in hosts:
  queue.put(host)

 #wait on the queue until everything has been processed
queue.join()

main()
print Elapsed Time: %s % (time.time() - start)

Executed on Windows with Python 2.5 this program doesn't do what you want, which 
is to fetch data from each site once.  Instead, it processes the first host in 
the list 5 times, the next 4 times, etc, and the last just once.  I don't know 
whether it is a case of the code simply being wrong (which seems unlikely), or 
the behaviour on my system being different from AIX (also seems unlikely).


Naively, I would have expected the queue to enforce processing of its members 
once only.  Is there a simple change that will make this code execute as 
required?  Or is this author out to lunch?


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


  1   2   3   >