Re: Cannot install pysqlite on Cygwin

2008-09-29 Thread Gerhard Häring

Tilman Kispersky wrote:

I am trying to install sqlite for use with python on cygwin. I have
installed the sqlite packages from cygwin (that is libsqlite3-devel
and libsqlite3_0).  When attempting to easy_install pysqlite I get:
[...]
build/temp.cygwin-1.5.25-i686-2.5/src/connection.o: In function
`pysqlite_enable_load_extension':
/cygdrive/c/Users/Tilman/AppData/Local/Temp/easy_install-876nHz/
pysqlite-2.5.0/src/connection.c:922: undefined reference to
`_sqlite3_enable_load_extension' [...]


It might be that Cygwin's SQLite doesn't support loading extensions.

Either:

Rebuild SQLite from source on Cygwin and be sure to include

--enable-load-extension when calling ./configure.

Or hack the pysqlite sources and remove these lines in src/connection.c:

#if SQLITE_VERSION_NUMBER >= 3003008
#define HAVE_LOAD_EXTENSION
#endif

I'm very interested how you can fix the problem.

-- Gerhar

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


Detecting dir (tree) changes fast?

2008-09-29 Thread robert
I want to detect changes in a directory tree fast with minimum 
overhead/load. In order to check the need for sync tasks at high 
frequency.
It must not be 100% reliable (its also forced time periodic), so 
kind of hashing would be ok.

How?


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


Re: Detecting dir (tree) changes fast?

2008-09-29 Thread Christian Heimes

robert wrote:
I want to detect changes in a directory tree fast with minimum 
overhead/load. In order to check the need for sync tasks at high frequency.
It must not be 100% reliable (its also forced time periodic), so kind of 
hashing would be ok.

How?


Almost every modern OS has some sort of support for IO notifications. 
For example pynotify on Linux, kqueue on BSD or ReadDirectoryChanges on 
Windows. You can also use polling and check the directories yourself 
every few seconds but that's expensive and doesn't scale.


Christian

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


Re: Detecting dir (tree) changes fast?

2008-09-29 Thread Steven D'Aprano
On Mon, 29 Sep 2008 10:05:10 +0200, robert wrote:

> I want to detect changes in a directory tree fast with minimum
> overhead/load. In order to check the need for sync tasks at high
> frequency.
> It must not be 100% reliable (its also forced time periodic), so kind of
> hashing would be ok.
> How?

Google is your friend. Googling for "python directory watcher" gives the 
following top three links:

http://www.amk.ca/python/simple/

http://timgolden.me.uk/python/win32_how_do_i/
watch_directory_for_changes.html
 (sorry for the broken URL)

http://code.activestate.com/recipes/217829/


There are probably many others. Which one is most suitable will depend on 
the details of, e.g. the OS you are using, the types of changes you're 
expecting, how many files are in the directory.



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


Re: Python is slow?

2008-09-29 Thread Lawrence D'Oliveiro
In message
<[EMAIL PROTECTED]>,
sturlamolden wrote:

> ... and possibility of interfacing with gnuplot ...

Gnuplot is non-Free software.

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


Re: how to replace and string in a "SELECT ... IN ()"

2008-09-29 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, D'Arcy
J.M. Cain wrote:

> On Fri, 26 Sep 2008 11:00:59 -0500
> "Michael Mabin" <[EMAIL PROTECTED]> wrote:
>
>> So we can drop a table in an in clause?  How is this a use case. 
>> Cartoons are funny but actual proof that this example using an in-clause
>> provides an exploit would be more helpful I think.
> 
> I'm not sure what proof you require.

I would say Mr Mabin is displaying thinking characteristic of a PHP
programmer
. :)

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


Re: how to search multiple textfiles ? (Python is slow ?)

2008-09-29 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Stef
Mientki wrote:

> - Pyscripter 110 sec ( PyScripter is the default IDE I use now)
> - Delphi  20 .. 35 sec
> - Findstr  4 sec

What order did you try try them in? Did you try each one more than once, in
different orders? Just to rule out filesystem caching effects.

> I'm really amazed by the speed of Python !!
> It can only be beaten by findstr, which is only available on windows.

Did you try find -exec grep -F?
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to search multiple textfiles ?

2008-09-29 Thread Lawrence D'Oliveiro
In message
<[EMAIL PROTECTED]>, George
Sakkis wrote:

> $ find -name "*py" | xargs egrep "\bword\b"

Better:

find -name '*.py' -exec grep -E "\bword\b" {} \;

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


Re: Python style: exceptions vs. sys.exit()

2008-09-29 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Ross Ridge wrote:

> You need either use trial and error to find out, or look at the source.

So what's wrong with using the source as documentation? :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Test if list contains another list

2008-09-29 Thread bearophileHUGS
Derek Martin:
>Quite a lot faster than mine... even without using psyco.<

It's designed for Psyco.


>However they don't appear to buy you much, given that the cases they optimize 
>would probably be rare, and the difference in execution time gained by the 
>optimization is not noticable to the user.<

http://www-igm.univ-mlv.fr/~lecroq/string/node7.html


>Unless you're doing lots and lots of these in your application,<

I don't agree. That's library code, so it has to be efficient and
flexible, because it's designed to be used in many different
situations (if you don't agree, then you can try to suggest a
replacement of the C code of the string search of CPython written by
effbot with some slower code).

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


Re: how to make smtplib.SMTP('localhost') work on window xp

2008-09-29 Thread zxo102
On 9月29日, 下午2时53分, Lawrence D'Oliveiro <[EMAIL PROTECTED]
central.gen.new_zealand> wrote:
> In message
> <[EMAIL PROTECTED]>, zxo102
> wrote:
>
> > SMTPServerDisconnected: Connection unexpectedly closed
>
> Does the SMTP server on localhost mention anything about the connection
> attempt in its log?
>
> If you telnet/netcat to port 25 on localhost, does anything interesting
> happen?

Thanks for your mentioning of the SMTP server on localhost. I did not
install that. After I install a free smtp server downloaded from
http://www.softstack.com/freesmtp.html,
and run the following python script again, everything is fine now.

import smtplib
server = smtplib.SMTP('localhost')
...

Thanks for your message.

ouyang


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

Re: how to make smtplib.SMTP('localhost') work on window xp

2008-09-29 Thread Steve Holden
zxo102 wrote:
> Hi,
>  I am trying to use python module smtplib to send my email out on
> window xp (localhost).
> 
> import smtplib
> server = smtplib.SMTP('localhost')
> 
> but I got the error information as follows:
> 
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "c:\python24\lib\smtplib.py", line 244, in __init__
> (code, msg) = self.connect(host, port)
>   File "c:\python24\lib\smtplib.py", line 311, in connect
> (code, msg) = self.getreply()
>   File "c:\python24\lib\smtplib.py", line 355, in getreply
> raise SMTPServerDisconnected("Connection unexpectedly closed")
> SMTPServerDisconnected: Connection unexpectedly closed
> 
> I am not sure what is wrong with it. Should I configure my window xp
> somewhere to run smtplib.SMTP('localhost')?
> 
> Thanks in advance.
> 
Well your code certainly expects *something* to be listening on port 25
on localhost. It's fairly unusual to run an SMTP server on Windows XP,
though not impossible.

usually your email system is set up to use some external host as uts
SMPT server: if you look in your mail client's configuration you will
probably find out whihc host you should be using.

regards
 Steve

-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: cups.Connection.printFile

2008-09-29 Thread Antoon Pardon
On 2008-09-26, Mike Driscoll <[EMAIL PROTECTED]> wrote:
> On Sep 19, 9:01 am, Antoon Pardon <[EMAIL PROTECTED]> wrote:
>> On 2008-09-16, Graham Jenkins <[EMAIL PROTECTED]> wrote:
>>
>>
>>
>> > I'm trying to print a file from within a Python program.
>>
>> > The quick-and-dirty solution is to use something like:
>>
>> > fd = os.popen("lp -d MyPrinter", "wb")
>> > fd.write(MyFileContents)
>>
>> > But it seems to me that there should be a clean solution like:
>>
>> > import cups
>> > stat =
>> > cups.Connection.printFile("MyFile","MyPrinter","MyTitle","MyOptions")
>>
>> What about systems that don't use cups for printing?
>>
>> --
>> Antoon Pardon
>
> For Windows, there's a few different ways to print. Tim Golden has a
> list on his website:
>
> http://timgolden.me.uk/python/win32_how_do_i/print.html

I have a linux system that doesn't use cups for printing.
So his "clean" solution won't work on my box. Unless
of course his cups.Connection.printFile is just a wrapper
around os.popen("lp -d MyPrinter", "wb") or something
similar.

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


Re: cups.Connection.printFile

2008-09-29 Thread Tim Golden

Antoon Pardon wrote:

On 2008-09-26, Mike Driscoll <[EMAIL PROTECTED]> wrote:

On Sep 19, 9:01 am, Antoon Pardon <[EMAIL PROTECTED]> wrote:

On 2008-09-16, Graham Jenkins <[EMAIL PROTECTED]> wrote:




I'm trying to print a file from within a Python program.
The quick-and-dirty solution is to use something like:
fd = os.popen("lp -d MyPrinter", "wb")
fd.write(MyFileContents)
But it seems to me that there should be a clean solution like:
import cups
stat =
cups.Connection.printFile("MyFile","MyPrinter","MyTitle","MyOptions")

What about systems that don't use cups for printing?

--
Antoon Pardon

For Windows, there's a few different ways to print. Tim Golden has a
list on his website:

http://timgolden.me.uk/python/win32_how_do_i/print.html


I have a linux system that doesn't use cups for printing.
So his "clean" solution won't work on my box. Unless
of course his cups.Connection.printFile is just a wrapper
around os.popen("lp -d MyPrinter", "wb") or something
similar.



Well I certainly don't pretend to offer any solutions on
my "Win32 How do I?" pages except for how to do things
on Win32 ;) .

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


Re: generate random digits with length of 5

2008-09-29 Thread dusans
On Sep 29, 12:06 am, Mensanator <[EMAIL PROTECTED]> wrote:
> On Sep 28, 3:54 pm, "Aaron \"Castironpi\" Brady"
>
>
>
>
>
> <[EMAIL PROTECTED]> wrote:
> > On Sep 28, 3:44 pm, Mensanator <[EMAIL PROTECTED]> wrote:
>
> > > On Sep 28, 3:11 pm, "Gary M. Josack" <[EMAIL PROTECTED]> wrote:
>
> > > > Chris Rebert wrote:
> > > > > On Sun, Sep 28, 2008 at 12:59 PM, sotirac <[EMAIL PROTECTED]> wrote:
>
> > > > >> Wondering if there is a better way to generate string of numbers with
> > > > >> a length of 5 which also can have a 0 in the front of the number.
>
> > > > >> 
> > > > >> random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
> > > > >> elements
> > > > >> code = 'this is a string' + str(random_number[0]) +
> > > > >> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
> > > > >> + str(random_number[4])
>
> > > > > code = ''.join(str(digit) for digit in random_number)
>
> > > > > Regards,
> > > > > Chris
>
> > > > >> 
>
> > > > >> --
> > > > >>http://mail.python.org/mailman/listinfo/python-list
>
> > > > will random.randint(1,9) work for you?
>
> > > It doesn't meet the OP's requirement that the number
> > > can start with 0. Also, the method the OP asks about
> > > returns a list of unique numbers, so no number can
> > > be duplicated. He can get 02468 but not 13345.
>
> > > Now, IF it's ok to have an arbitrary number of leading
> > > 0s, he can do this:
>
> > > >>> str(random.randint(0,9)).zfill(5)
> > > '00089'
> > > >>> str(random.randint(0,9)).zfill(5)
> > > '63782'
> > > >>> str(random.randint(0,9)).zfill(5)
> > > '63613'
> > > >>> str(random.randint(0,9)).zfill(5)
>
> > > '22315'
>
> > Is a while loop until there are 5 distinct digits best otherwise?
>
> Of course not.
>
>
>
> > while 1:
> > a= '%05i'% random.randint( 0, 9 )
> > if len( set( a ) )== 5: break
>
> How is this better than the OP's original code?

Wow didnt know about '%05i' :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Spring Python 0.7.0 is released

2008-09-29 Thread Goldfish
Key Features

The following features have been implemented:

* Inversion Of Control - The idea is to decouple two classes at
the interface level. This lets you build many reusable parts in your
software, and your whole application becomes more pluggable. You can
use either the XmlApplicationContext or the
DecoratorBasedApplicationContext.
* Aspect-oriented Programming - Spring Python provides great ways
to wrap advice around objects. It is utilized for remoting. Another
use is for debug tracers and performance tracing.
* DatabaseTemplate - Reading from the database requires a
monotonous cycle of opening cursors, reading rows, and closing
cursors, along with exception handlers. With this template class, all
you need is the SQL query and row-handling function. Spring Python
does the rest.
* Database Transactions - Wrapping multiple database calls with
transactions can make your code hard to read. This module provides
multiple ways to define transactions without making things
complicated.
* Security - Plugin security interceptors to lock down access to
your methods, utilizing both authentication and domain authorization.
* Remoting - It is easy to convert your local application into a
distributed one. If you have already built your client and server
pieces using the IoC container, then going from local to distributed
is just a configuration change.
* Samples - to help demonstrate various features of Spring Python,
some sample applications have been created:
  o PetClinic - Everybody's favorite Spring sample application
has been rebuilt from the ground up using various web containers
including: CherryPy. Go check it out for an example of how to use this
framework.
  o Spring Wiki - Wikis are powerful ways to store and manage
content, so we created a simple one as a demo!
  o Spring Bot - Use Spring Python to build a tiny bot to
manage the IRC channel of your open source project.

For more information, please visit the website at 
http://springpython.webfactional.com,
where you will also find more detailed documentation at
http://springpython.webfactional.com/reference/html/.

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


Re: What is not objects in Python?

2008-09-29 Thread George Sakkis
On Sep 29, 2:34 am, Carl Banks <[EMAIL PROTECTED]> wrote:
> On Sep 29, 1:44 am, George Sakkis <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Sep 29, 12:08 am, Terry Reedy <[EMAIL PROTECTED]> wrote:
>
> > > George Sakkis wrote:
> > > > On Sep 28, 2:29 pm, process <[EMAIL PROTECTED]> wrote:
>
> > > >> I have heard some criticism about Python, that it is not fully object-
> > > >> oriented.
>
> > > > That's not a bug, it's a feature ;-)
>
> > > >> Why isn't len implemented as a str.len and list.len method instead of
> > > >> a len(list) function?
>
> > > > As Terry Reedy wrote, partly history and partly practicality. There's
> > > > no philosophical reason why we write "len(x)" (generic builtin),
> > > > "x.append(1)" (method) or "del x[i]" (statement). The latter in
> > > > particular is IMHO a design wart; there's no reason for not writing it
> > > > as "x.delete(i)".
>
> > > As a general rule and matter of practice, methods that apply to all or
> > > most classes (or all number classes) have built-in functions that call
> > > the corresponding special method (or C-level slot).
>
> > It would be easier to justify this rule if it was more clear-cut, and
> > specifically if it was applied only to methods that are available to
> > *all* classes (such as type() and getattr()) rather than the ill-
> > defined "most classes".
>
> That wasn't your original claim, though.  You claimed there was no
> philosophical reason, then Terry gave you one, then you said, well
> there's no clear cut reason.  Unless you define "philosophical" as
> "clear cut" (a definition I'm not sure many would agree with).

I won't argue about that, just s/philosophical/clear cut/ then.

> Anyway, you are right to claim there's no clear cut distinction, just
> as there's never any clear cut distinction over whether something
> should be an operator or not. Addition is only available to the ill-
> defined "most classes", yet not only is it not a method, it has its
> own syntax.  There's no clear cut distinction there, it's just a
> design decision.
>
> Likewise, making len() into a function is just a
> design decision, that len is a common enough operation that it need
> elevated status.  It's really nothing more.  Python wouldn't suffer
> much regardless if len is a method, a built-in function, or an
> operator with its own syntax.

I'm not quite sure it's exactly the same. The distinction between
operators and non-operators is syntactically clear cut: operators
consist of punctuation characters and (binary operators) use infix
syntax. Yes, from a pure semantics standpoint this distinction is
redundant; a language could support a method-only syntax, but there is
much value in using terse intuitive symbols for certain domains (with
math being the prominent one). For example I would be much less
opposed to len() being defined as, say, |x| if "|...|" was a valid
operator.

I don't see the same value in creating a distinction between methods
and builtin functions unless the latter are truly generic (and even
then I wouldn't mind having them as methods of the base object class,
e.g. object.type()). Having a builtin len(x) delegate to x.__len__()
seems harder to justify.

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


Re: What is not objects in Python?

2008-09-29 Thread bearophileHUGS
George Sakkis:
> I don't see the same value in creating a distinction between methods
> and builtin functions unless the latter are truly generic (and even
> then I wouldn't mind having them as methods of the base object class,
> e.g. object.type()). Having a builtin len(x) delegate to x.__len__()
> seems harder to justify.

I have shown few usage examples of the len() one of the posts in this
thread. Can you take a look at them and show how you can better
rewrite them without a len function?

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


writing dll in python?

2008-09-29 Thread nishalrs
Hello All,

My main motivation is to build a collection of useful mathematical
models (that I have developed over the years) to design ultrasonic
sensors. This should be some sort of a library that should be able to
be used for desktop/web application development, to run in variety of
operating systems.

I am more than convinced after looking at python.org website, it is
the right tool for the job. I intend to learn python, but I am not
really sure, where to begin. 

Should I write all the functions as simple python scripts? Or is there
some facility for creating a .dll like library, that could be more
suitable for what in intend to develop?

Any help is much appreciated.

Regards,
Nishal


   

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


Re: Fastest way to max() list

2008-09-29 Thread Gabriel Genellina
En Fri, 26 Sep 2008 01:42:59 -0300, Chris Rebert <[EMAIL PROTECTED]>  
escribió:



B. Assuming by "distance" you meant "difference" and/or that the
distance is only in 1 dimension:

from operator import itemgetter
firsts = map(itemgetter(0), main_list)
distance = max(firsts) - min(firsts)


I think the above expression is overcomplicated. The code below does the  
exact same thing and is easier to understand, IMHO:


firsts = [item[0] for item in main_list]
distance = max(firsts) - min(firsts)

--
Gabriel Genellina

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


SPECIAL DISCOUNTS - Online Python Training

2008-09-29 Thread Jeanne Allen
Do you know anyone who is looking for training on Python?  We have two
courses taught online with hands-on exercises done on remote PCs.

 

. Python Intro Part 1 - Live On-Line, 8:30am - 12:30pm EST, November 10
to 13, 2008

. Python Intro Part 2 - Live On-Line, 8:30am - 12:30pm EST, November 17
to 20, 2008

 

When you sign up for either course we will give you a special $200 discount
bringing the price to $695. If you sign up for both Part 1 and Part 2 and
we'll give you a total discount of $500 (bringing the total price for both
courses to $1,290. Please be sure to mention Coupon Code 1214 to receive the
discount. You can call me to enroll, or enroll online at
http://www.dashcourses.com/public-courses.html.

 

Python Intro Part 1 introduces the student to the basics of writing and
running Python scripts, such as variables, file operations, and flow
control. Emphasis is placed on features unique to Python, such as tuples,
array slices, and output formatting. This is a hands-on programming class.
All concepts are reinforced by informal practice during the lecture followed
by graduated lab exercises, and all labs are done using remote PC's so
there's nothing to download on your office or home PC. For more information,
click on
http://www.dashcourses.com/public-courses/public-courses/python-intro-part-1
-public-training-course.html.

 

Python Intro Part 2 moves the beginning Python programmer on to more
advanced features such as regular expressions, working with binary data, and
using the extensive functionality of Python modules. As with Part 1, extra
emphasis is placed on features unique to Python. This is also a hands-on
programming class. All concepts are reinforced by informal practice during
the lecture followed by graduated lab exercises, and all labs are done using
remote PC's so there's nothing to download on your office or home PC. This
course provides a practical introduction to a working programming language,
not an academic overview of syntax and grammar. Students will immediately be
able to use Python to complete tasks in the real world. For more details,
click on
http://www.dashcourses.com/public-courses/public-courses/python-intro-part-2
-public-training-course.html.

 

Thanks for passing this along -

 

 

Come enjoy our FREE PowerHours!  

* Oct 27: Python or Perl

* Nov 5: USB - Where are we going?

* Nov 19: Spring Security to Secure your Java Web Application

http://www.dashcourses.com/contests/dashconnect.html

 

Check out our full schedule of online classes!  

Project Management, Java, PCI, USB, Perl, Python.and much, much more

http://www.dashcourses.com/public-courses.html

 

Sincerely,

 

Jeanne Allen

Director of Distance Learning

Dashcourses International

(540) 349-0875

  www.dashcourses.com

 

 

 

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

One class per file?

2008-09-29 Thread HCB
Hello:

The book "Code Complete" recommends that you put only one class in a
source file, which seems a bit extreme for me. It seems that many
classes are small, so that putting several of them in a file seems
reasonable. I noticed that the decimal.py module in the standard
library has several classes, all of which of course revolve around the
"decimal" topic. Perhaps a better rule of thumb is "one idea per
file." I checked the Python style guide and there seems to be no
mention of this topic. I know this is an elementary question, but what
is the Python way of doing this?

Thanks for your time.
HCB
--
http://mail.python.org/mailman/listinfo/python-list


Using re to find unicode ranges

2008-09-29 Thread Eric Abrahamsen
Is it possible to use the re module to find runs of characters within  
a certain Unicode range?


I'm writing a Markdown extension to go over text and wrap blocks of  
consecutive Chinese characters in  tags for  
nice styling in an HTML page. The available hooks appear to be a pre- 
processor (which is a "for line in lines" situation) or an inline  
pattern (which uses regular expressions). The regular expression  
solution would be much simpler and faster, but something tells me  
there's no way to use a regex to find character ranges... Chinese  
characters appear to fall between 19968 and 40959 using ord(), and I  
suppose I can go that route if necessary, but I think it would be ugly.


Any hints or suggestions would be appreciated!

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


Re: One class per file?

2008-09-29 Thread Ben Finney
HCB <[EMAIL PROTECTED]> writes:

> The book "Code Complete" recommends that you put only one class in a
> source file, which seems a bit extreme for me.

For Python, that is extreme, and for most applications I've seen it
would be counterproductive. Which edition of Code Complete recommends
this, and on which page?

> Perhaps a better rule of thumb is "one idea per file." I checked the
> Python style guide and there seems to be no mention of this topic. I
> know this is an elementary question, but what is the Python way of
> doing this?

You have it right: modules are most naturally used for conceptual
grouping of objects (not just classes, but all objects) related to a
discrete area of functionality, into a discrete namespace.

-- 
 \  “The WWW is exciting because Microsoft doesn't own it, and |
  `\  therefore, there's a tremendous amount of innovation |
_o__)  happening.” —Steve Jobs |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Re: writing dll in python?

2008-09-29 Thread Tino Wildenhain

nishalrs wrote:

Hello All,

My main motivation is to build a collection of useful mathematical
models (that I have developed over the years) to design ultrasonic
sensors. This should be some sort of a library that should be able to
be used for desktop/web application development, to run in variety of
operating systems.

I am more than convinced after looking at python.org website, it is
the right tool for the job. I intend to learn python, but I am not
really sure, where to begin. 


Should I write all the functions as simple python scripts? Or is there
some facility for creating a .dll like library, that could be more
suitable for what in intend to develop?


This is called a module in python, you can also collect modules
to a package. Once you have your package ready, you can distribute
them as egg if you want (basically a distribution as zip file) -
look up python eggs and easy-install with your search engine of
choice.

Regards
Tino


smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list

Re: Web programming in Python.

2008-09-29 Thread Paul Boddie
On 29 Sep, 01:51, Kurda Yon <[EMAIL PROTECTED]> wrote:
> 1. On my server (in my directory) I found "cgi-bin" subdirectory.
>
> 2. In the "cgi-bin" I have created a file "test.py".
>
> 3. In that file I put:
> #!/usr/bin/python2.4 python
> print "Hello, World!"
> (I have checked, I have "/usr/bin/python2.4" directory.)

What's the spare "python" for at the end of the first line? You should
also try and run the program directly just to see whether it runs and
what it prints.

> 4. I give the following permissions to the "test.py":
> -rwx---r-x
>
> 5. The "cgi-bin" directory has the following permissions:
> drwx---r-x

This is probably acceptable.

> 6. In the "cgi-bin" I have created the ".htaccess" file which
> contains:
> Options +ExecCGI
> AddHandler cgi-script .py
>
> And it still does not work! If I try to see the page by my browser I
> see:
> Internal Server Error
> The server encountered an internal error or misconfiguration and was
> unable to complete your request.
> ...

Read the error log, possibly found in a log directory in your home
directory (since you seem to be in a hosting environment, but you'd
look in /var/log/httpd or /var/log/apache for a system-wide Web server
installation) and see what the complaint is. You might also consider
looking at the following page for guidance:

http://wiki.python.org/moin/CgiScripts

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


Re: Python OOP question

2008-09-29 Thread Gabriel Genellina

En Thu, 25 Sep 2008 11:45:21 -0300, k3xji <[EMAIL PROTECTED]> escribió:


Hi all,

I am trying to develop a game-server in python. Design is as
following:

- ConnectionManager - handling/distributing incoming connections
- IOManager - handling IO recv/send operations on sockets.
(inheritable)
- Socket - basic async socket object
- SocketServer - handling multiple socket object requests.
(inheritable)
- Options - holds the server options (inheritable)

I want this code to be extensible as it can be. So I have developed it
like this. I f one is going to implement some new feature, all needs
to be done is to inherit IOManager or Server object to do it.
Inheritable objects are IOManager, SocketServer and Options.

But there is some feeling about this design that it can be better.
Here is the main.py which I am using to execute the server:

from Base.SocketServer import SocketServer
from testIOManager import testIOManager
from Base.Options import Options
from Base.ConnectionManager import ConnectionManager

iomgr = testIOManager()
opts = Options()

# calculate how many server objects to create
# according to the maximum allowed client count.
serverCnt = opts.MAX_CLIENT_COUNT / opts.MAX_CLIENT_COUNT_PER_SERVER
Servers = []
for i in range(serverCnt):
server = Server(i)
Servers.append(server)


cmgr = ConnectionManager(Servers, iomgr, opts)
cmgr.start()

With current design as server object is inheritable, I need to pass it
to ConnectionManager object. I just have a feeling that above design
is bad in the sense of readability.


You may imitate how asyncore [1] handles channels: make the library  
contain a (global) list of servers; the Server (base) constructor adds  
itself to the list; and ConnectionManager uses that list if not  
explicitely supplied one.
But I'm not sure it improves readability: there is no explicit link  
between the Servers you construct and the ConnectionManager, but the  
latter "magically" knows about all the formers. It's easier to manage,  
though.


(I don't undersantd exactly why you insist in the inheritable part; isn't  
the same if it were not inheritable? Maybe I don't get your main concerns  
correctly...)


--
Gabriel Genellina

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


Re: Web programming in Python.

2008-09-29 Thread Steve Holden
Kurda Yon wrote:
> 1. On my server (in my directory) I found "cgi-bin" subdirectory.
> 
> 2. In the "cgi-bin" I have created a file "test.py".
> 
> 3. In that file I put:
> #!/usr/bin/python2.4 python

OK, if /usr/bin/python2.4 really *is* a directory then you will need to
make that first line

#!/usr/bin/python2.4/python

(The phrase folowing the "#!" should be a reference to your Python
interpreter).

> print "Hello, World!"

Also, this isn't going to be adequate as an HTTP response, which a CGI
script is always supposed to provide. A minimal example would have a
single header followed by a blank like (which marks the end of the
headers) and your content, like this:

print """Content-Type: text/plain

Hello, World!
"""
> (I have checked, I have "/usr/bin/python2.4" directory.)
> 
> 4. I give the following permissions to the "test.py":
> -rwx---r-x
> 
> 5. The "cgi-bin" directory has the following permissions:
> drwx---r-x
> 
> 6. In the "cgi-bin" I have created the ".htaccess" file which
> contains:
> Options +ExecCGI
> AddHandler cgi-script .py
> 
> 
> And it still does not work! If I try to see the page by my browser I
> see:
> Internal Server Error
> The server encountered an internal error or misconfiguration and was
> unable to complete your request.
> ...
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
If that doesn't get your script working then you should look at the
error logs.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: how to make smtplib.SMTP('localhost') work on window xp

2008-09-29 Thread zxo102
On 9月29日, 下午7时29分, Steve Holden <[EMAIL PROTECTED]> wrote:
> zxo102 wrote:
> > Hi,
> >  I am trying to use python module smtplib to send my email out on
> > window xp (localhost).
>
> > import smtplib
> > server = smtplib.SMTP('localhost')
>
> > but I got the error information as follows:
>
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> >   File "c:\python24\lib\smtplib.py", line 244, in __init__
> > (code, msg) = self.connect(host, port)
> >   File "c:\python24\lib\smtplib.py", line 311, in connect
> > (code, msg) = self.getreply()
> >   File "c:\python24\lib\smtplib.py", line 355, in getreply
> > raise SMTPServerDisconnected("Connection unexpectedly closed")
> > SMTPServerDisconnected: Connection unexpectedly closed
>
> > I am not sure what is wrong with it. Should I configure my window xp
> > somewhere to run smtplib.SMTP('localhost')?
>
> > Thanks in advance.
>
> Well your code certainly expects *something* to be listening on port 25
> on localhost. It's fairly unusual to run an SMTP server on Windows XP,
> though not impossible.
>
> usually your email system is set up to use some external host as uts
> SMPT server: if you look in your mail client's configuration you will
> probably find out whihc host you should be using.
>
> regards
>  Steve
>
> --
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC  http://www.holdenweb.com/

In my case, I implement an application with python to accomplish
collecting real time data from a serial port: com1 which is connected
to some xbee hardwares.
The python logging module is used to save the information generated at
runtime into a log file. Since the site is far away from my office, I
try to
use a smtp server with the python smtplib module to send the log file
into my email account regularly so that I can check it from anywhere.

Thanks for your suggestion.

Ouyang

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

Re: Cannot install pysqlite on Cygwin

2008-09-29 Thread Steve Holden
Tilman Kispersky wrote:
> I am trying to install sqlite for use with python on cygwin. I have
> installed the sqlite packages from cygwin (that is libsqlite3-devel
> and libsqlite3_0).  When attempting to easy_install pysqlite I get:
> 
> $ easy_install pysqlite
> Searching for pysqlite
> Reading http://pypi.python.org/simple/pysqlite/
> Reading http://pysqlite.org/
> Reading http://initd.org/pub/software/pysqlite/releases/2.3/2.3.3/
> Reading http://pysqlite.sourceforge.net/
> Reading http://initd.org/pub/software/pysqlite/releases/2.3/2.3.4/
> Reading http://initd.org/tracker/pysqlite/wiki/PysqliteDownloads
> Reading http://oss.itsystementwicklung.de/trac/pysqlite
> Reading http://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.0/
> Reading http://initd.org/pub/software/pysqlite/releases/2.3/2.3.5/
> Reading http://oss.itsystementwicklung.de/download/pysqlite/2.4/2.4.1/
> Reading http://initd.org/pub/software/pysqlite/releases/2.4/2.4.0/
> Best match: pysqlite 2.5.0
> Downloading 
> http://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.0/pysqlite-2.5.0.tar.gz
> Processing pysqlite-2.5.0.tar.gz
> Running pysqlite-2.5.0/setup.py -q bdist_egg --dist-dir /cygdrive/c/
> Users/Tilman/AppData/Local/Temp/easy_install-876nHz/pysqlite-2.5.0/egg-
> dist-tmp-7mr3WS
> warning: no files found matching 'doc/*.html'
> warning: no files found matching 'doc/code/*.py'
> src/statement.c: In function `pysqlite_statement_recompile':
> src/statement.c:351: warning: `sqlite3_transfer_bindings' is
> deprecated (declared at /usr/include/sqlite3.h:3985)
> build/temp.cygwin-1.5.25-i686-2.5/src/connection.o: In function
> `pysqlite_enable_load_extension':
> /cygdrive/c/Users/Tilman/AppData/Local/Temp/easy_install-876nHz/
> pysqlite-2.5.0/src/connection.c:922: undefined reference to
> `_sqlite3_enable_load_extension'
> collect2: ld returned 1 exit status
> error: Setup script exited with error: command 'gcc' failed with exit
> status 1
> $
> 
> 
> It seems to me this is due to some missing library (undefined
> reference...) but I have no idea what these missing files might be.
> I've tried installing everything that made any reference to sqlite
> form the cygwin interface.  Does anyone know how I might get a working
> install of sqlite for python on cygwin?

I believe it's a glitch in the 2.5.1 distribution current on Cygwin - I
had to install the _sqlite DLL separately to get it to work, but no
recompilation was necessary AFAICR.

Chui Tey detailed the necessary steps in his blog post "Cygwin Python
and sqlite3", but sadly it got lost and he hasn't replenished it, so you
will have to stab around to see if there's a cached copy anywhere.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: One class per file?

2008-09-29 Thread Roy Smith
In article 
<[EMAIL PROTECTED]>,
 HCB <[EMAIL PROTECTED]> wrote:

> Hello:
> 
> The book "Code Complete" recommends that you put only one class in a
> source file, which seems a bit extreme for me. It seems that many
> classes are small, so that putting several of them in a file seems
> reasonable. I noticed that the decimal.py module in the standard
> library has several classes, all of which of course revolve around the
> "decimal" topic. Perhaps a better rule of thumb is "one idea per
> file." I checked the Python style guide and there seems to be no
> mention of this topic. I know this is an elementary question, but what
> is the Python way of doing this?
> 
> Thanks for your time.
> HCB

Steve McConnell writes a lot of good stuff.  Like most people who write a 
lot of good stuff, not everything he writes should be taken as gospel.  
With that in mind...

Consider this.  You're slogging through some code in a large project trying 
to debug a problem when you come upon the line (in pseudo-code):

   foo = SomeClass::SomeFunction(bar)

You want to go look at the source for SomeClass.  What file do you open to 
find it?  If you follow the "one class per file" rule, the answer is easy; 
it's in SomeClass.xxx!

That being said, the "one class per file" rule is a means to an end.  If 
your code is written in such a way that it's easy to figure out where the 
source for a given class/function/whatever is, then you've done the right 
thing.  The specifics of how you do that depend on the language you're 
using.

In Python (as other posters have pointed out), modules give you a good way 
to group logical collections of classes (etc).  If you see in some code:

   foo = some_module.SomeClass.SomeFunction(bar)

you should instantly know that the source code is in some_module.py.  
Perhaps one way to look at this is that Python automatically follows the 
"one class per file" rule, except that "class" is crossed out and "module" 
written in with crayon.

On the other hand, if you prefer self-abuse, Python gives you plenty of 
ways to do that.  If you preface all your source files with:

from some_module import *
from some_other_module import *
from yet_a_third_module import *
from another_module import *

and then see

   foo = SomeClass.SomeFunction(bar)

you're right back to having no clue what file to open to find the source 
for SomeClass.  Global namespace is sacred; treat it with respect!
--
http://mail.python.org/mailman/listinfo/python-list


os.path.exists() function does not work for http paths

2008-09-29 Thread dudeja . rajat
Hi,

I have used os.path.exists() many a times for any file system paths in local
system. But this does not seem to work for an Http path.

e.g:


To check is the Results folder exists at the following path, I do:


if not os.path.exists("http://subversion.myCom.com/Testing/Results";):
print 'Path does not exist'


This always prints the above print statements whether or not the Results
folder exists or not.

Is there any such function to check existence of files. / folder at Http
paths?


-- 
Thanks and regards,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list

Re: closures and dynamic binding

2008-09-29 Thread Paul Boddie
On 29 Sep, 05:56, Terry Reedy <[EMAIL PROTECTED]> wrote:
>
> As I understand it, partly from postings here years ago...
>
> Lexical: The namespace scope of 'n' in inner is determined by where
> inner is located in the code -- where is is compiled.  This is Python
> (and nearly all modern languages).  Even without closures, the global
> scope of a function is the module it is defined in.

This is how I understand it, too. The confusing part involves the
definition of any inner function and how any "external" names are
bound or defined. As we've seen...

  def f(x):
def g():
  return x
x += 1 # added for illustration
return g

...it might look at first glance like the function known as g (within
f) should return the initial value of x (as known within f), since
that was the value x had when g was defined. The following is an
example execution trace based on that mental model:

fn = f(1)
-> def f(1):
->   def g(): # g defined with x as 1
-> return x # would be 1
->   x += 1 # x becomes 2
->   return g
fn()
-> def g():
->   return x # would still be 1

However, as we know, this isn't the case in real Python since g isn't
initialised with the value of x at the time of its definition - it
instead maintains access to the namespace providing x. We must
therefore revise the example:

fn = f(1)
-> def f(1):
->   def g(): # g refers to x within f(1)
-> return x # would be the current value of x within f(1)
->   x += 1 # x becomes 2
->   return g
fn()
-> def g(): # g refers to x within f(1)
->   return x # would be the current value of x within f(1), which is
2

This is the dynamic aspect of closures: values aren't used to
initialise inner functions; names are looked up from their origin.

> Dynamic: The namespace scope of 'n' in inner, how it is looked up, is
> determined by where inner is called from. This is what you seemed to be
> suggesting -- look up 'n' based on the scope it is *used* in.

Indeed. Dynamic scoping is confusing in that one has to set up an
appropriate "environment" for the closure to access so that references
to names can be meaningfully satisfied; obviously, this creates all
sorts of encapsulation problems. The confusing aspect of lexical
scoping, however, especially if non-local names can be changed, is
that the effects of closures are potentially distant - one doesn't
always invoke inner functions in the place where they were defined, as
we see above - and such effects may thus happen within "abandoned
namespaces" - that is, namespaces which can no longer be revisited and
used in their original context. So, in the above, once f has been
invoked, the namespace for that invocation effectively lives on, but
that namespace is not a general one for f - if we invoke f again, we
get another namespace as one should reasonably expect.

A somewhat separate issue is illustrated by the modification of x
within f. Although for most statements, we would expect the value of x
to evolve following from a top-to-bottom traversal of the code within
a unit, function definition statements do not behave like, say, "for",
"if" or "while" statements. Now although this should be obvious at the
module global level, I feel that it can be easy to overlook within a
function where one normally expects to find plain old control-flow
constructs, expressions, assignments and so on. It is pertinent to
note, with respect to the original inquiry, that lambda functions are
subject to the same caveats, and I believe that lexical scoping was
introduced precisely to make lambda functions less cumbersome to
employ, eliminating the need to explicitly initialise them using the
"identity" default parameters trick, but obviously introducing the
consequences and potential misunderstandings described above.

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


Re: closures and dynamic binding

2008-09-29 Thread Michele Simionato
On Sep 28, 6:43 am, "Aaron \"Castironpi\" Brady"
<[EMAIL PROTECTED]> wrote:
> Hello all,
>
> To me, this is a somewhat unintuitive behavior.  I want to discuss the
> parts of it I don't understand.
>
> >>> f= [ None ]* 10
> >>> for n in range( 10 ):
>
> ...     f[ n ]= lambda: n
> ...>>> f[0]()
> 9
> >>> f[1]()
>
> 9
>

You may want to read this old thread that goes in detail explaining
scoping issues
with closures in for loops:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/d691240a5cfebcdf/93503c5b9c66226e?hl=en&lnk=gst&q=simionato+jacek#93503c5b9c66226e

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


Re: Using re to find unicode ranges

2008-09-29 Thread Paul McGuire
On Sep 29, 8:17 am, Eric Abrahamsen <[EMAIL PROTECTED]> wrote:
> Is it possible to use the re module to find runs of characters within  
> a certain Unicode range?
>
> I'm writing a Markdown extension to go over text and wrap blocks of  
> consecutive Chinese characters in  tags for  
> nice styling in an HTML page. The available hooks appear to be a pre-
> processor (which is a "for line in lines" situation) or an inline  
> pattern (which uses regular expressions). The regular expression  
> solution would be much simpler and faster, but something tells me  
> there's no way to use a regex to find character ranges... Chinese  
> characters appear to fall between 19968 and 40959 using ord(), and I  
> suppose I can go that route if necessary, but I think it would be ugly.
>
> Any hints or suggestions would be appreciated!
>
> Eric

Eric -

This sounds similar to what zhpy (http://pyparsing.wikispaces.com/
WhosUsingPyparsing#Zhpy) does to extract Chinese words from code, to
generate executable English Python.  You might give that a look.

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


blocking all threads

2008-09-29 Thread Alexandru Mosoi
how can I block all threads for a specific amount of time? (i need to
sleep whole process for testing purposes). i thought of accessing GIL
and sleep for some amount of time, but I don't know how to do this and
whether GIL is recursive.
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is not objects in Python?

2008-09-29 Thread George Sakkis
On Sep 29, 9:02 am, [EMAIL PROTECTED] wrote:

> George Sakkis:
>
> > I don't see the same value in creating a distinction between methods
> > and builtin functions unless the latter are truly generic (and even
> > then I wouldn't mind having them as methods of the base object class,
> > e.g. object.type()). Having a builtin len(x) delegate to x.__len__()
> > seems harder to justify.
>
> I have shown few usage examples of the len() one of the posts in this
> thread. Can you take a look at them and show how you can better
> rewrite them without a len function?
>
> Bye,
> bearophile

You mean this ?

>>> seq = ["", "bb", "c", "ddd"]
>>> seq2 = [[1,1,1,1], [2,2], [3], [4,4,4]]
>>> sorted(seq, key=lambda x:x.__len__())
['c', 'bb', 'ddd', '']
>>> sorted(seq2, key=lambda x:x.__len__())
[[3], [2, 2], [4, 4, 4], [1, 1, 1, 1]]

Sure, "len" looks better than lambda x:x.__len__(), but the same would
be true if there was an "upper" builtin for the following example:

>>> s = ['a', 'd', 'B', 'C']
>>> s2 = [u'a', u'd', u'B', u'C']
>>> upper = lambda x: x.upper()
>>> sorted(s, key=upper)
['a', 'B', 'C', 'd']
>>> sorted(s2, key=upper)
[u'a', u'B', u'C', u'd']

No difference in principle, just len() happens to be implemented more
often than upper().

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


Re: Using re to find unicode ranges

2008-09-29 Thread Mark Tolonen


"Eric Abrahamsen" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
Is it possible to use the re module to find runs of characters within  a 
certain Unicode range?


I'm writing a Markdown extension to go over text and wrap blocks of 
consecutive Chinese characters in  tags for 
nice styling in an HTML page. The available hooks appear to be a pre- 
processor (which is a "for line in lines" situation) or an inline  pattern 
(which uses regular expressions). The regular expression  solution would 
be much simpler and faster, but something tells me  there's no way to use 
a regex to find character ranges... Chinese  characters appear to fall 
between 19968 and 40959 using ord(), and I  suppose I can go that route if 
necessary, but I think it would be ugly.


# coding: utf-8
import re
sample = u'My name is 马克. I am 美国人.'
for n in re.findall(ur'[\u4e00-\u9fff]+',sample):
   print n

output:

马克
美国人

--Mark

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

Re: Web programming in Python.

2008-09-29 Thread afrogazer
Not to be a condescending, but there are a lot of manuals out there on
how to do this and asking on a forum would really not be the best way
to get started. Do some research and some reading and you should be up
and running in a short time. You can ask questions on the forum if you
have difficulties while/after reading.

Good luck



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


Re: What is not objects in Python?

2008-09-29 Thread Mel
George Sakkis wrote:
> As Terry Reedy wrote, partly history and partly practicality. There's
> no philosophical reason why we write "len(x)" (generic builtin),
> "x.append(1)" (method) or "del x[i]" (statement). The latter in
> particular is IMHO a design wart; there's no reason for not writing it
> as "x.delete(i)".

`del x` has almost nothing to do with `x`, and almost everything to do with
a namespace containing `x`.  The object doesn't know what namespace it's
in.

Mel.

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


Re: What is not objects in Python?

2008-09-29 Thread Marc 'BlackJack' Rintsch
On Mon, 29 Sep 2008 11:14:36 -0400, Mel wrote:

> George Sakkis wrote:
>> As Terry Reedy wrote, partly history and partly practicality. There's
>> no philosophical reason why we write "len(x)" (generic builtin),
>> "x.append(1)" (method) or "del x[i]" (statement). The latter in
>> particular is IMHO a design wart; there's no reason for not writing it
>> as "x.delete(i)".
> 
> `del x` has almost nothing to do with `x`, and almost everything to do
> with a namespace containing `x`.  The object doesn't know what namespace
> it's in.

But George's example was ``del x[i]`` which *has* something to do with 
`x` as it mutates the object (or at least calls `x.__delitem__()`).

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


Re: What is not objects in Python?

2008-09-29 Thread bearophileHUGS
George Sakkis:
> No difference in principle, just len() happens to be implemented more
> often than upper().

That's an important point. In a language that tries to be both
practical, readable, and elegant, the things that are done more may
deserve some sugar, to avoid code like this in many cases:

sorted(seq, key=lambda x:x.__len__())

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


Re: What is not objects in Python?

2008-09-29 Thread George Sakkis
On Sep 29, 11:37 am, [EMAIL PROTECTED] wrote:
> George Sakkis:
>
> > No difference in principle, just len() happens to be implemented more
> > often than upper().
>
> That's an important point. In a language that tries to be both
> practical, readable, and elegant, the things that are done more may
> deserve some sugar, to avoid code like this in many cases:
>
> sorted(seq, key=lambda x:x.__len__())

If this was the most compelling use case of having len as builtin, I
would be even less convinced. How often do you sort by len? FWIW, the
most common sorting keys I see in real world are attrgetter(some_attr)
or itemgetter(some_index)  and both are imported functions, not
builtins.

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


Re: Test if list contains another list

2008-09-29 Thread Derek Martin
On Mon, Sep 29, 2008 at 04:12:13AM -0700, [EMAIL PROTECTED] wrote:
> Derek Martin:
> >Unless you're doing lots and lots of these in your application,<
> 
> I don't agree. That's library code, so it has to be efficient and
> flexible, because it's designed to be used in many different
> situations 

That's fair, but lots of folks writing Python code will look at that
and say, "What the [EMAIL PROTECTED] is this doing?!?"  As I already suggested,
code that implements non-obvious algorithms ought to explain what it's
doing in comments, so that the neophyte programmers charged with
maintaining the library aren't tempted to rewrite the code so that 
it's easier to understand what it's doing.  It can be as simple as:

  # Use Morris-Pratt algorithm to search data

Then, anyone not familiar with the algorithm can easily look it up,
and see why it was written that way.  

I think it's just as important to do that in code you post on the
list, since a) the person asking the question obviously doesn't know
what you're doing, or they wouldn't have needed to ask the question,
and b) there are lots of other folks reading the list who could
benefit from the same knowledge. :)

-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D



pgpsqKgyV2byd.pgp
Description: PGP signature
--
http://mail.python.org/mailman/listinfo/python-list

Re: destructor not called

2008-09-29 Thread Marcin201
> Others have already replied to your main question; in short you
> shouldn't rely on __del__ being called. Regardless, is there a (good)
> reason for having an instance reference to the method ? Without
> further information, that seems like a code smell.

I have dictionary of fxns to do import/export based on the type of
request from user so I can call self.Import['html'] or
self.Import['text'].

Thanks for everyones help.

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


Re: Tkinter: scrollbar - unable to scroll the scrollbar if I click on arrow buttons of scroll bars

2008-09-29 Thread dudeja . rajat
On Sun, Sep 28, 2008 at 4:51 PM, <[EMAIL PROTECTED]> wrote:

>
> Hi,
>
>
> Im using a tkinter scrollbars for horinzontal and vertical scrolling. Well
> the problem is I'm unable to scroll if I click on the arrows buttons of
> scrollbars ( with both types of scrollbars)
>
>
> Please suggest if I m missing some configuration.
>
>
> My code is as below:
>
> self.hsb = Scrollbar(appGuiFrame, orient = HORIZONTAL)
> self.hsb.grid(row = 2,column = 0, sticky = E+W)
> #vertical scroll bar
> self.vsb = Scrollbar(appGuiFrame)
> self.vsb.grid(row = 1,column = 2, sticky = N+S)
>
>
>
> self.txtLogger = Text(appGuiFrame, \
>  height = 20,\
>  width = 100, \
>  state = DISABLED, \
>  xscrollcommand = self.hsb.set, \
>  yscrollcommand = self.vsb.set, \
>  wrap = NONE, \
>  font = ("courier",12))
>  self.hsb.config(command = self.txtLogger.xview())
>  self.vsb.config(command = self.txtLogger.yview())
>
>
> Please help.
>
>
> Thanks and regards,
> Rajat
>


Hi folks,

Any help on the above problem.

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

Re: Python is slow?

2008-09-29 Thread Fly Away
On Sep 29, 3:05 am, Lawrence D'Oliveiro <[EMAIL PROTECTED]
central.gen.new_zealand> wrote:
> In message
> <[EMAIL PROTECTED]>,
>
> sturlamolden wrote:
> > ... and possibility of interfacing with gnuplot ...
>
> Gnuplot is non-Free software.

Yes, it is.

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


Re: Test if list contains another list

2008-09-29 Thread bearophileHUGS
Derek Martin:
> code that implements non-obvious algorithms ought to explain what it's
> doing in comments,

I am sorry, you are right, of course.

In my libs/code there are always docstrings and doctests/tests, and
most times comments too, like you say. When I post code here I often
strip away part of those things, mostly to reduce the length of my
posts -.- I guess that I have to leave more of that meta-
information...

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


Re: Music knowledge representation

2008-09-29 Thread D'Arcy J.M. Cain
On Sun, 28 Sep 2008 16:37:11 +0200
"Mr.SpOOn" <[EMAIL PROTECTED]> wrote:
> Hi,
> I'm working on an application to analyse music (melodies, chord sequences 
> etc.)

Sounds interesting.  Will this be Open Source?

> I need classes to represent different musical entities. I'm using a
> class Note to represent all the notes. Inside it stores the name of
> the natural version of the note (C, D, E, F...) and an integer to
> calculate the accidentals.

Have you considered having the object take a key option with default to
'C' so that you don't have to mark as many accidentals - or, more
correctly, mark actual accidentals rather than always marking the
"black keys?"

The other advantage here is that the notes can be given as numbers and
octaves (middle C would be (1, 3, 0) in the key of C for example) and
you can transpose by changing the argument when instantiating the class.

> Then I have a class Pitch, to represent the different 12 pitch
> classes, because different notes, such as C# and Db, belong to the
> same pitch class.

Couldn't the note class simply have a list of all the notes and have a
simple method calculate the actual pitch?

> In these classes I also have some arithmetic method to perform
> additions or subtractions between pitches and integers.
> 
> I also need to represent intervals between notes. An interval must
> have a degree (first, second, third), that may be represented with a
> simple integer and a size counted in semitones. Then, with these
> informations it can retrieve its name, for example: perfect fifth.

Seems easy given the pitch location indeces.  Subtract the two and do a
lookup into a list of intervals.  E.g:  ["Unison", "Semi-tone",
"Second", "Minor third", Major third", ...]

> The degree is calculated between natural notes. So the degree of
> Interval(C, E) is "third", or 3. This may be simple, if I put the
> notes in an ordered sequence. But, when I have to calculate, for
> example Interval(E, C). It should count till the end of the sequence,
> so if I have:
> 
> C D E F G A B
> 
> after the B it should continue with C. I'm not sure how to implement
> this. Is there a suitable data structure for this purpose?

def interval(self, lower, higher)
if lower > higher:
# uncomment one of the two following lines depending
# on the behaviour you want
#lower,higher = higher,lower
#higher += 12

# could use some error trapping
return self.interval_name[higher - lower]

Note that lower and higher could be a note object that you have to
convert to integers first.

Hope this gives you some ideas.

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Generate documentation for a Python developed software

2008-09-29 Thread Alfons Nonell-Canals
Dear all,
I have a complex program developed using Python. It contains lot of
files and classes. 

Now I have the lazy task to documentate it. I have some notes about is
class but I would like to know if there is something to auto-generate
the doucmentation with the program code. I know I will have to explain
each class and variable but, if an external software canprepare it, the
template, it will be great!

Thanks in advance!

Regards,

-- 

Alfons Nonell-Canals
Chemogenomics Lab
Research Group on Biomedical Informatics (GRIB) - IMIM/UPF
Parc de Recerca Biomèdica de Barcelona (PRBB)
C/ Doctor Aiguader, 88 - 08003 Barcelona 
[EMAIL PROTECTED] - http://cgl.imim.es

http://alfons.elmeuportal.cat
http://www.selenocisteina.info

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

Re: Python is slow?

2008-09-29 Thread bearophileHUGS
Lawrence D'Oliveiro:
>> Gnuplot is non-Free software.

Fly Away:
> Yes, it is.

From:
http://www.gnuplot.info/faq/faq.txt

1.7 Does gnuplot have anything to do with the FSF and the GNU project?
   [...]
   Gnuplot is freeware in the sense that you don't have to pay for it.
However
   it is not freeware in the sense that you would be allowed to
distribute a
   modified  version  of  your gnuplot freely. [...]

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


Re: One class per file?

2008-09-29 Thread George Boutsioukis
On Mon, 29 Sep 2008 06:12:35 -0700, HCB wrote:

> Hello:
> 
> The book "Code Complete" recommends that you put only one class in a
> source file, which seems a bit extreme for me. It seems that many
> classes are small, so that putting several of them in a file seems
> reasonable. I noticed that the decimal.py module in the standard library
> has several classes, all of which of course revolve around the "decimal"
> topic. Perhaps a better rule of thumb is "one idea per file." I checked
> the Python style guide and there seems to be no mention of this topic. I
> know this is an elementary question, but what is the Python way of doing
> this?
> 
> Thanks for your time.
> HCB

That sounds terrible! Imagine having a million source files to edit, 
rename, create, delete each time you make a change. Sure, every Java fan 
can give you a million reasons why the universe will collapse otherwise, 
but this is totally impractical in python. Python's module organization 
and namespaces are more than enough if used reasonably.
--
http://mail.python.org/mailman/listinfo/python-list


PYTHON WORKING WITH PERL ??

2008-09-29 Thread Blubaugh, David A.
To All,


I was wondering if it was possible to have a situation where a
programming project would utilized BOTH python and perl?  Such as
utilizing python for internet programming and then utilize perl for text
processing and systems programming?  Is this even feasible???


Thanks,


David Blubaugh





This e-mail transmission contains information that is confidential and may be 
privileged. It is intended only for the addressee(s) named above. If you 
receive 
this e-mail in error, please do not read, copy or disseminate it in any manner. 
If you are not the intended recipient, any disclosure, copying, distribution or 
use of the contents of this information is prohibited. Please reply to the 
message immediately by informing the sender that the message was misdirected. 
After replying, please erase it from your computer system. Your assistance in 
correcting this error is appreciated.

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


Re: Generate documentation for a Python developed software

2008-09-29 Thread Chris Rebert
On Mon, Sep 29, 2008 at 9:45 AM, Alfons Nonell-Canals
<[EMAIL PROTECTED]> wrote:
> Dear all,
> I have a complex program developed using Python. It contains lot of
> files and classes.
>
> Now I have the lazy task to documentate it. I have some notes about is
> class but I would like to know if there is something to auto-generate
> the doucmentation with the program code. I know I will have to explain
> each class and variable but, if an external software canprepare it, the
> template, it will be great!

Sphinx (http://sphinx.pocoo.org/) is pretty slick and was used to
generate the spiffy new python docs (http://docs.python.org/dev/).
There's also epydoc (http://epydoc.sourceforge.net/), the standard
library module 'pydoc', and [to a lesser degree] Doxygen
(http://www.stack.nl/~dimitri/doxygen/)

Regards,
Chris

>
> Thanks in advance!
>
> Regards,
>
> --
> 
> Alfons Nonell-Canals
> Chemogenomics Lab
> Research Group on Biomedical Informatics (GRIB) - IMIM/UPF
> Parc de Recerca Biomèdica de Barcelona (PRBB)
> C/ Doctor Aiguader, 88 - 08003 Barcelona
> [EMAIL PROTECTED] - http://cgl.imim.es
>
> http://alfons.elmeuportal.cat
> http://www.selenocisteina.info
>
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list

Re: One class per file?

2008-09-29 Thread Matimus

> The book "Code Complete" recommends that you put only one class in a
> source file, which seems a bit extreme for me. It seems that many
> classes are small, so that putting several of them in a file seems
> reasonable. I noticed that the decimal.py module in the standard
> library has several classes, all of which of course revolve around the
> "decimal" topic. Perhaps a better rule of thumb is "one idea per
> file." I checked the Python style guide and there seems to be no
> mention of this topic. I know this is an elementary question, but what
> is the Python way of doing this?


I'm in a similar situation. I've been reading Robert C. Martins book
"Agile Software Development" and he suggests something similar. I
would highly recommend that book by the way. He also has a couple of
chapters on packaging where he makes some very good points about the
reasoning behind it. Basically that you want to organize your code in
such a way that package dependencies move in the direction of
increasing stability. In this case stability is a metric which is
defined as how likely the code is going to change in the future as
determined by how many packages depend on it as opposed to how many
packages it depends on. He paints a couple of scenarios in which he
groups packages together that _seem_ to be related, only to see that
it results in all of his packages needing to be re-built every time a
change is required. Obviously we don't have to re-build python code,
but it is still useful to organize your code in such a way that you
don't have to constantly re-visit collections of code.

I have actually started using his suggestion and have been putting one
class per file. When one class depends on another I include it with a
"from x import X". This makes it very easy to determine the
dependencies (well, the non-abstract dependencies anyway, interfaces
are a different story*). Then I put all of my classes together in a
package, and make the "public" classes visible on a package level by
importing them into the package __init__ module.

With that being said, If I made a class that was _only_ used by one
other single class, and it was clear that it would never be made
visible outside of that file, I would certainly put it in the same
file as that class. Heck, you might even refactor your code and
determine at that time that some piece of code is only used by one
other piece. It is much easier to put code together after the fact
than it is to separate it, especially later in the game.

My advice: don't knock it until you try it. I think my code has
improved quite a bit since taking this advice. It can be much more
difficult to determine which classes to package together until much
later in the development cycle. One thing that can help is to find an
IDE that helps you to easily switch between files. I use WingIDE, but
I have even used vim with a tags file and it wasn't terrible. I
wouldn't call it a hard rule, but at the same time I wouldn't just
ignore it. Give it a shot and adapt your development technique to see
what works best for you.

Example:

[mypackage/__init__.py]
__all__ = ["X"]

from .x import X
[end mypackage/__init__.py]

[mypackage/x.py]
from .y import Y

__all__ = ["X"]

class X(object):
   # code - using Y hopefully
[end mypackage/x.py]

[mypackage/y.py]
__all__ = ["Y"]

class Y(object):
   # code
[end mypackage/y.py]


Matt



* Interfaces in python represent an implicit dependency. The Zen of
Python states: "Explicit is better than implicit". I plan to
experiment with the ABC module in python 2.6/3.0. I want to make my
interfaces explicitly defined, but on the other hand I still want it
to be easy for people who use my code to duck-type. This _seems_ to be
possible since you can .register a class with an interface after it
has been created, but I'm not sure that it is very pythonic to
explicitly check for an interface every time it is used. It would seem
silly however to import an interface into a file where it isn't
explicitly used just to document the dependency. If anybody has
pointers let me know.
--
http://mail.python.org/mailman/listinfo/python-list


Re: closures and dynamic binding

2008-09-29 Thread Terry Reedy

Paul Boddie wrote:

On 29 Sep, 05:56, Terry Reedy <[EMAIL PROTECTED]> wrote:

...

Dynamic: The namespace scope of 'n' in inner, how it is looked up, is
determined by where inner is called from. This is what you seemed to be
suggesting -- look up 'n' based on the scope it is *used* in.

...


A somewhat separate issue is illustrated by the modification of x
within f. Although for most statements, we would expect the value of x
to evolve following from a top-to-bottom traversal of the code within
a unit, function definition statements do not behave like, say, "for",
"if" or "while" statements. Now although this should be obvious at the
module global level, I feel that it can be easy to overlook within a
function where one normally expects to find plain old control-flow
constructs, expressions, assignments and so on. It is pertinent to
note, with respect to the original inquiry, that lambda functions are
subject to the same caveats,


Please: Python does not have 'lambda functions'.  Def statements and 
lambda expressions both define instances of the function class.  So this 
amounts to saying "functions are subject to the same caveats as functions."


> and I believe that lexical scoping was introduced precisely to make
> lambda functions less cumbersome to

employ, eliminating the need to explicitly initialise them using the
"identity" default parameters trick, but obviously introducing the
consequences and potential misunderstandings described above.


As I meant when I wrote "Even without closures, the global scope of a 
function is the module it is defined in.", the concept of lexical 
scoping applies even to non-nested top-level functions.


Yes, closures for nested functions were introduced in part to replace 
the pseudo-default parameter trick (which does not require the confusion 
of using the same name in both local namespaces).  But this applies to 
both syntactical forms of function definition and had nothing to do in 
particular with easing the quite limited lambda form, which Guido does 
not like and once thought to delete in 3.0.


Closures were also introduced because default parameters are limited to 
capturing a value at the time of function definition instead of at 
function invocation.  Consider your example which I have moved down to here.


> This is how I understand it, too. The confusing part involves the
> definition of any inner function and how any "external" names are
> bound or defined. As we've seen...
>
>   def f(x):
> def g():
>   return x
> x += 1 # added for illustration
> return g
>
> ...it might look at first glance like the function known as g (within
> f) should return the initial value of x (as known within f), since
> that was the value x had when g was defined.

Only if one is confused about the difference between default parameter 
expressions, which are evaluated when the function is defined, and body 
expressions, which are evaluated when the function is called.  If you 
want g to use the 'initial' value that x has when g is defined, then say so.


def f(x):
  def g(y=x) # or x=x if you really prefer
return y # or x, with the consequent possibility of confusion
  x += 1
  return g

If 'x' is fixed, this is a difference without effect.  If 'x' is not, as 
in this pair of examples, the difference is important.


The introduction of the 'nonlocal' keyword will make the latter case 
more common and hence the second reason more important.  Consider code like


def f(*args)
  x = [0]
  def g()
...
x[0] += 1
...
  
  return x[0], ...

This has x fixedly bound to a particular list.  The default argument 
trick would have worked here.  In the future, this can and will be 
written more naturally as


def f(*args)
  x = 0
  def g()
nonlocal x
...
x += 1
...
  
  return x, ...

With x being rebound, the default argument trick would *not* work.  And, 
of course, lambda expressions are not in the picture.


Terry Jan Reedy

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


Re: PYTHON WORKING WITH PERL ??

2008-09-29 Thread D'Arcy J.M. Cain
On Mon, 29 Sep 2008 13:16:14 -0400
"Blubaugh, David A." <[EMAIL PROTECTED]> wrote:
> I was wondering if it was possible to have a situation where a
> programming project would utilized BOTH python and perl?  Such as
> utilizing python for internet programming and then utilize perl for text
> processing and systems programming?  Is this even feasible???

I don't see why not but I also question if it is a good idea.  Once you
have all your objects and low level methods written in Python it just
makes sense to re-use them rather than trying to duplicate the
functionality in another language.

Of course, sometimes we don't have control over our entire environment
so yes, you can mix them if you have to.

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: os.path.exists() function does not work for http paths

2008-09-29 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> Hi,
> 
> I have used os.path.exists() many a times for any file system paths in
> local system. But this does not seem to work for an Http path.
> 
> e.g:
> 
> 
> To check is the Results folder exists at the following path, I do:
> 
> 
> if not os.path.exists("http://subversion.myCom.com/Testing/Results";):
> print 'Path does not exist'
> 
> 
> This always prints the above print statements whether or not the Results
> folder exists or not.
> 
> Is there any such function to check existence of files. / folder at Http
> paths?
> 
You could use one of the URL libraries. The os.path module is for
dealing with the local filesystem.

The absence of any exception from

  f = urllib.urlopen("http://www.google.com/webhp/";)

is a good indication that the addressed page "exists" (but remember that
the web is a virtual address space, so it doesn't necessarily mean that
there's a real file or directory object behind ot).

regards
 Steve

-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Tkinter: scrollbar - unable to scroll the scrollbar if I click on arrow buttons of scroll bars

2008-09-29 Thread dudeja . rajat
On Mon, Sep 29, 2008 at 5:10 PM, <[EMAIL PROTECTED]> wrote:

>
>
> On Sun, Sep 28, 2008 at 4:51 PM, <[EMAIL PROTECTED]> wrote:
>
>>
>> Hi,
>>
>>
>> Im using a tkinter scrollbars for horinzontal and vertical scrolling. Well
>> the problem is I'm unable to scroll if I click on the arrows buttons of
>> scrollbars ( with both types of scrollbars)
>>
>>
>> Please suggest if I m missing some configuration.
>>
>>
>> My code is as below:
>>
>> self.hsb = Scrollbar(appGuiFrame, orient = HORIZONTAL)
>> self.hsb.grid(row = 2,column = 0, sticky = E+W)
>> #vertical scroll bar
>> self.vsb = Scrollbar(appGuiFrame)
>> self.vsb.grid(row = 1,column = 2, sticky = N+S)
>>
>>
>>
>> self.txtLogger = Text(appGuiFrame, \
>>  height = 20,\
>>  width = 100, \
>>  state = DISABLED, \
>>  xscrollcommand = self.hsb.set, \
>>  yscrollcommand = self.vsb.set, \
>>  wrap = NONE, \
>>  font = ("courier",12))
>>  self.hsb.config(command = self.txtLogger.xview())
>>  self.vsb.config(command = self.txtLogger.yview())
>>
>>
>> Please help.
>>
>>
>> Thanks and regards,
>> Rajat
>>
>
>
> Hi folks,
>
> Any help on the above problem.
>
> Regards,
> Rajat
>

Hi,

The problem got solved. After finding for such a long time I got a snippet
at google and used the same in my code. It solved the problem.
Here is the complete code now:

class cLogToGUI:

def __init__(self, logObj, appGUI):
self.__logger = logObj
self.__logger.debug("Inside cLogToGUI::__init__")
appGuiFrame = appGUI.frame4

#hor. scroll bar
self.hsb = Scrollbar(appGuiFrame, orient = HORIZONTAL)
self.hsb.grid(row = 2,column = 0, sticky = E+W)

#vertical scroll bar
self.vsb = Scrollbar(appGuiFrame)
self.vsb.grid(row = 1,column = 2, sticky = N+S)



self.txtLogger = Text(appGuiFrame, \
 height = 20,\
 width = 100, \
 state = DISABLED, \
 xscrollcommand = self.hsb.set, \
 yscrollcommand = self.vsb.set, \
 wrap = NONE, \
 font = ("courier",12))
#self.hsb.config(command = self.txtLogger.xview())
#self.vsb.config(command = self.txtLogger.yview())
self.hsb.config(command = self.__hsbScrollHandler)
self.vsb.config(command = self.__vsbScrollHandler)


self.txtLogger.bind("<>", self.outputText)
self.txtLogger.grid(row = 1)

self.txtLogger.tag_configure("error", foreground = "red")
self.txtLogger.tag_configure("warning", foreground = "orange")
self.txtLogger.tag_configure("success", foreground = "blue")
self.__logger.debug("return from cLogToGUI::__init__")



def outputText(self, event):
self.__logger.debug("Inside cLogToGUI::outputText()")
self.txtLogger.configure(state = NORMAL)
string = TASymbols.strScrolledTextLine
tag = TASymbols.strScrolledTextLineTag
if not string:
self.txtLogger.delete('1.0', END)
else:
self.txtLogger.insert(END, string, tag)
#self.txtLogger.focus()
self.txtLogger.see(END)
self.txtLogger.configure(state = DISABLED)
self.__logger.debug("return from cLogToGUI::outputText()")

def __hsbScrollHandler(self, *L):
op, howMany = L[0], L[1]

if op == "scroll":
units  =  L[2]
self.txtLogger.xview_scroll ( howMany, units )
elif op == "moveto":
self.txtLogger.xview_moveto ( howMany )

def __vsbScrollHandler(self, *L):
op, howMany = L[0], L[1]

if op == "scroll":
units  =  L[2]
self.txtLogger.yview_scroll ( howMany, units )
elif op == "moveto":
self.txtLogger.yview_moveto ( howMany )

Thanks and regards,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list

Re: PYTHON WORKING WITH PERL ??

2008-09-29 Thread Steve Holden
Blubaugh, David A. wrote:
> To All,
> 
> 
> I was wondering if it was possible to have a situation where a
> programming project would utilized BOTH python and perl?  Such as
> utilizing python for internet programming and then utilize perl for text
> processing and systems programming?  Is this even feasible???
> 
> 
> Thanks,
> 
So sorry to hear Google isn't available from your network ;-)

  http://search.cpan.org/~gaas/pyperl-1.0/perlmodule.pod

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: blocking all threads

2008-09-29 Thread sturlamolden
On Sep 29, 4:56 pm, Alexandru  Mosoi <[EMAIL PROTECTED]> wrote:

> how can I block all threads for a specific amount of time? (i need to
> sleep whole process for testing purposes). i thought of accessing GIL
> and sleep for some amount of time, but I don't know how to do this and
> whether GIL is recursive.


You could do this in C by sleeping while holding the GIL:

#ifdef WIN32
  #include 
  #define __sleep(ms) Sleep((DWORD)ms)
#else
  #include 
  #define __sleep(ms) usleep((useconds_t)ms)
#endif

__declspec(dllexport)
void sleep(int ms)
{
   __sleep(ms);
}


Save this in a file called "gilsleep.c" and compile it as a DLL
(gilslepp.dll in Windows, gilsleep.so in Linux). Then in Python:

import ctypes
sleep = ctypes.pydll.gilsleep.sleep
sleep.argtypes = (ctypes.c_int,)
sleep.restype = None

sleep(500) # blocks all threads for 500 ms





















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


Re: One class per file?

2008-09-29 Thread Tim Rowe
2008/9/29 Roy Smith <[EMAIL PROTECTED]>:

> That being said, the "one class per file" rule is a means to an end.

Although in some languages, the "end" is "code that runs". But Python
is not Java...

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


Re: Python is slow?

2008-09-29 Thread Victor Prosolin
[EMAIL PROTECTED] wrote:
> Lawrence D'Oliveiro:
>>> Gnuplot is non-Free software.
> 
> Fly Away:
>> Yes, it is.
> 
> From:
> http://www.gnuplot.info/faq/faq.txt
> 
> 1.7 Does gnuplot have anything to do with the FSF and the GNU project?
>[...]
>Gnuplot is freeware in the sense that you don't have to pay for it.
> However
>it is not freeware in the sense that you would be allowed to
> distribute a
>modified  version  of  your gnuplot freely. [...]

Yes, I did read this prior to posting.

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


Re: Python is slow?

2008-09-29 Thread r0g
[EMAIL PROTECTED] wrote:
> Lawrence D'Oliveiro:
>>> Gnuplot is non-Free software.
> 
> Fly Away:
>> Yes, it is.
> 
> From:
> http://www.gnuplot.info/faq/faq.txt
> 
> 1.7 Does gnuplot have anything to do with the FSF and the GNU project?
>[...]
>Gnuplot is freeware in the sense that you don't have to pay for it.
> However
>it is not freeware in the sense that you would be allowed to
> distribute a
>modified  version  of  your gnuplot freely. [...]
> 
> Bye,
> bearophile


Well, ish.  You can only distribute modifications to gnuplot itself as
patches, but you can distribute it freely and they publish the source
so, while it's not GPL free it's tending towards it.

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


Re: writing dll in python?

2008-09-29 Thread Terry Reedy

nishalrs wrote:

Hello All,

My main motivation is to build a collection of useful mathematical
models (that I have developed over the years) to design ultrasonic
sensors. This should be some sort of a library that should be able to
be used for desktop/web application development, to run in variety of
operating systems.


Interesting new applications of Python are welcome.  Googling "Python 
package (or module) ultrasonic sensor" did not turn up anything relevant 
that I saw.



I am more than convinced after looking at python.org website, it is
the right tool for the job. I intend to learn python, but I am not
really sure, where to begin. 


Start with the Python tutorial, perhaps parts of the reference manual, 
and definitely peruse the first chapters in the library manual on 
built-in functions and classes.


You will almost certainly want to use numpy (numpy.org) for numerical 
calculation and possibly existing modules in scipy (scipy.org) or elsewhere.



Should I write all the functions as simple python scripts? Or is there
some facility for creating a .dll like library, that could be more
suitable for what in intend to develop?


A module is a 'script' that is intended to be imported by other Python 
code.  In your Python installation directory, /Libs has numerous *.py 
examples.  A 'package' is a collection of modules in a directory that 
includes only called __init__.py (if I remember correctly).  Don't worry 
about details yet.  When you have something worth distributing, you can 
get help here or on other lists, such as the one for numpy/scipy.


When you are ready, you can announce it here and elsewhere and register 
it at the Python Package Index (pypi.python.org/pypi).


Terry Jan Reedy

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


Re: One class per file?

2008-09-29 Thread Bruno Desthuilliers

HCB a écrit :

Hello:

The book "Code Complete" recommends that you put only one class in a
source file,


That's possibly (don't know...) a good advice for C++, and that's 
mandatory (at least for 'public' classes) in Java. And that's totally 
pointless and counterproductive in Python. Also and FWIW, "this dead 
horse as been beaten to hell and back" (IOW : you'll find quite a couple 
thread discussing this in this newsgroup's archives).


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


Re: What is not objects in Python?

2008-09-29 Thread Terry Reedy

George Sakkis wrote:


Sure, "len" looks better than lambda x:x.__len__(), but the same would
be true if there was an "upper" builtin for the following example:


s = ['a', 'd', 'B', 'C']
s2 = [u'a', u'd', u'B', u'C']
upper = lambda x: x.upper()
sorted(s, key=upper)

['a', 'B', 'C', 'd']

sorted(s2, key=upper)

[u'a', u'B', u'C', u'd']

No difference in principle, just len() happens to be implemented more
often than upper().


I disagree.  One versus many classes is a principle.  If a method is 
used on objects of just one class, the class attribute can be used and 
passed directly.


sorted(s, key = str.upper)
sorted(s2, key = unicode.upper)

The problem is having two text classes, which Guido considers to be a 
mess and which Python did not have originally and which 3.0 also does 
not have, even though bytes keeps the string methods.  Mixing int, long, 
and float numbers is or should be more common than mixing str and 
unicode strings, and certainly more common than mixing str strings and 
bytes in 3.0 (which is actively discouraged).


To me, discerning the implicit principles of Python's design makes it 
easier to learn and remember, even if they are not as exact as one might 
like.  The choices are not random, and so one can do better than rote 
memory.


Terry Jan Reedy

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


Re: Music knowledge representation

2008-09-29 Thread Mr.SpOOn
On Mon, Sep 29, 2008 at 6:49 PM, D'Arcy J.M. Cain <[EMAIL PROTECTED]> wrote:
> On Sun, 28 Sep 2008 16:37:11 +0200
> "Mr.SpOOn" <[EMAIL PROTECTED]> wrote:
>> Hi,
>> I'm working on an application to analyse music (melodies, chord sequences 
>> etc.)
>
> Sounds interesting.  Will this be Open Source?

Well, yes, I think.

> Have you considered having the object take a key option with default to
> 'C' so that you don't have to mark as many accidentals - or, more
> correctly, mark actual accidentals rather than always marking the
> "black keys?"

Well, one of the analysis task would consist in finding a possible
tonality from a set of note. Or, more useful, give a set of playable
notes over certain given chords.


> Couldn't the note class simply have a list of all the notes and have a
> simple method calculate the actual pitch?

That's not really how it works. There exists just 12 octave
independent pitch classes. This means that there is a pitch class C
with all possible Cs. There ambiguities with accidentals, because
different named notes fall in the same pitch class. The difference is
important for the musical theory, because C# and Db belongs to the
same pitch class (actually they are the same note, they sounds
completely identical -- because on the piano you play them pressing
the same key), but in a scale they have a very different role.

For example, the interval C F# is an "augmented fourth", because what
really matters are the natural note (C and F), and their distance if
4. Then it is augmented due to the #-

But the interval C Gb (Gb is the same as F#) is a "diminished fifth".

So I can't list all pitches.


>def interval(self, lower, higher)
>if lower > higher:
># uncomment one of the two following lines depending
># on the behaviour you want
>#lower,higher = higher,lower
>#higher += 12
>
># could use some error trapping
>return self.interval_name[higher - lower]
>
> Note that lower and higher could be a note object that you have to
> convert to integers first.

I can't estabilish which note is higher, because all the analysis part
is octave independent. Anyway thanks for the ideas.

I think itertools is what I need.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python style: exceptions vs. sys.exit()

2008-09-29 Thread Bruno Desthuilliers

Lawrence D'Oliveiro a écrit :

In message <[EMAIL PROTECTED]>, Ross Ridge wrote:


You need either use trial and error to find out, or look at the source.


So what's wrong with using the source as documentation? :)


Don't know... Ok, having higher-level documentation  (the big picture, 
and quick description of what and how for classes and functions) really 
helps. But when it comes to nitty-gritty details, source code is the 
best documentation ever, since it's always accurate and up to date.


FWIW, I'm often surprised by people asking questions about some 
implementation detail of some open-source library or framework that are 
very easily answered just looking at the source code. Reading the source 
is 1/ the best way to really know how something is implemented and 2/ 
usually very instructive.

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


Re: closures and dynamic binding

2008-09-29 Thread Aaron "Castironpi" Brady
On Sep 29, 9:14 am, Paul Boddie <[EMAIL PROTECTED]> wrote:
> On 29 Sep, 05:56, Terry Reedy <[EMAIL PROTECTED]> wrote:
>
>
>
> > As I understand it, partly from postings here years ago...
>
> > Lexical: The namespace scope of 'n' in inner is determined by where
> > inner is located in the code -- where is is compiled.  This is Python
> > (and nearly all modern languages).  Even without closures, the global
> > scope of a function is the module it is defined in.
>
> This is how I understand it, too. The confusing part involves the
> definition of any inner function and how any "external" names are
> bound or defined. As we've seen...
>
>   def f(x):
>     def g():
>       return x
>     x += 1 # added for illustration
>     return g
>
> ...it might look at first glance like the function known as g (within
> f) should return the initial value of x (as known within f), since
> that was the value x had when g was defined. The following is an
> example execution trace based on that mental model:
>
> fn = f(1)
> -> def f(1):
> ->   def g(): # g defined with x as 1
> ->     return x # would be 1
> ->   x += 1 # x becomes 2
> ->   return g
> fn()
> -> def g():
> ->   return x # would still be 1
>
> However, as we know, this isn't the case in real Python since g isn't
> initialised with the value of x at the time of its definition - it
> instead maintains access to the namespace providing x. We must
> therefore revise the example:
>
> fn = f(1)
> -> def f(1):
> ->   def g(): # g refers to x within f(1)
> ->     return x # would be the current value of x within f(1)
> ->   x += 1 # x becomes 2
> ->   return g
> fn()
> -> def g(): # g refers to x within f(1)
> ->   return x # would be the current value of x within f(1), which is
> 2
>
> This is the dynamic aspect of closures: values aren't used to
> initialise inner functions; names are looked up from their origin.
>
> > Dynamic: The namespace scope of 'n' in inner, how it is looked up, is
> > determined by where inner is called from. This is what you seemed to be
> > suggesting -- look up 'n' based on the scope it is *used* in.
>
> Indeed. Dynamic scoping is confusing in that one has to set up an
> appropriate "environment" for the closure to access so that references
> to names can be meaningfully satisfied; obviously, this creates all
> sorts of encapsulation problems. The confusing aspect of lexical
> scoping, however, especially if non-local names can be changed, is
> that the effects of closures are potentially distant - one doesn't
> always invoke inner functions in the place where they were defined, as
> we see above - and such effects may thus happen within "abandoned
> namespaces" - that is, namespaces which can no longer be revisited and
> used in their original context. So, in the above, once f has been
> invoked, the namespace for that invocation effectively lives on, but
> that namespace is not a general one for f - if we invoke f again, we
> get another namespace as one should reasonably expect.
>
> A somewhat separate issue is illustrated by the modification of x
> within f. Although for most statements, we would expect the value of x
> to evolve following from a top-to-bottom traversal of the code within
> a unit, function definition statements do not behave like, say, "for",
> "if" or "while" statements. Now although this should be obvious at the
> module global level, I feel that it can be easy to overlook within a
> function where one normally expects to find plain old control-flow
> constructs, expressions, assignments and so on. It is pertinent to
> note, with respect to the original inquiry, that lambda functions are
> subject to the same caveats, and I believe that lexical scoping was
> introduced precisely to make lambda functions less cumbersome to
> employ, eliminating the need to explicitly initialise them using the
> "identity" default parameters trick, but obviously introducing the
> consequences and potential misunderstandings described above.
>
> Paul

I'm thinking of a comparison to try to see an example.

I tried this which still surprised me at first.

>>> g= [0]
>>> f= lambda: g
>>> del g
>>> f()
NameError: global name 'g' is not defined

It took a little thinking.  The namespace in 'f' is the global
namespace.  They are one in the same dictionary.  id( f.namespace ) ==
id( main.namespace ).  f.namespace is main.namespace.

When f gets a parameter, its namespace is different by one (or two
when two parameters, etc).

>>> g=[0]
>>> f= lambda h: lambda: h
>>> i= f( g )
>>> del g
>>> i()
[0]

The statement 'del g' removes 'g' from the module/global namespace,
but it lives on in the namespace of 'f', or more accurately, 'i'.

>>> g=[0]
>>> f= lambda h: lambda: h
>>> i= f( g )
>>> j= f( g )
>>> del g
>>> i().append(1)
>>> j()
[0, 1]

Here, the namespaces of 'main', 'i', and 'j', all have references to
'g'.  'i' and 'j' still have them when 'main' loses its.

The lambda might be confusing.  Take a simpler example of a namespace:

>>> g= [

Re: Cannot install pysqlite on Cygwin

2008-09-29 Thread Tilman Kispersky
On Sep 29, 7:49 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> Tilman Kispersky wrote:
> > I am trying to install sqlite for use with python oncygwin. I have
> > installed the sqlite packages fromcygwin(that is libsqlite3-devel
> > and libsqlite3_0).  When attempting to easy_install pysqlite I get:
>
> > $ easy_install pysqlite
> > Searching for pysqlite
> > Readinghttp://pypi.python.org/simple/pysqlite/
> > Readinghttp://pysqlite.org/
> > Readinghttp://initd.org/pub/software/pysqlite/releases/2.3/2.3.3/
> > Readinghttp://pysqlite.sourceforge.net/
> > Readinghttp://initd.org/pub/software/pysqlite/releases/2.3/2.3.4/
> > Readinghttp://initd.org/tracker/pysqlite/wiki/PysqliteDownloads
> > Readinghttp://oss.itsystementwicklung.de/trac/pysqlite
> > Readinghttp://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.0/
> > Readinghttp://initd.org/pub/software/pysqlite/releases/2.3/2.3.5/
> > Readinghttp://oss.itsystementwicklung.de/download/pysqlite/2.4/2.4.1/
> > Readinghttp://initd.org/pub/software/pysqlite/releases/2.4/2.4.0/
> > Best match: pysqlite 2.5.0
> > Downloadinghttp://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.0/pysqlit...
> > Processing pysqlite-2.5.0.tar.gz
> > Running pysqlite-2.5.0/setup.py -q bdist_egg --dist-dir /cygdrive/c/
> > Users/Tilman/AppData/Local/Temp/easy_install-876nHz/pysqlite-2.5.0/egg-
> > dist-tmp-7mr3WS
> > warning: no files found matching 'doc/*.html'
> > warning: no files found matching 'doc/code/*.py'
> > src/statement.c: In function `pysqlite_statement_recompile':
> > src/statement.c:351: warning: `sqlite3_transfer_bindings' is
> > deprecated (declared at /usr/include/sqlite3.h:3985)
> > build/temp.cygwin-1.5.25-i686-2.5/src/connection.o: In function
> > `pysqlite_enable_load_extension':
> > /cygdrive/c/Users/Tilman/AppData/Local/Temp/easy_install-876nHz/
> > pysqlite-2.5.0/src/connection.c:922: undefined reference to
> > `_sqlite3_enable_load_extension'
> > collect2: ld returned 1 exit status
> > error: Setup script exited with error: command 'gcc' failed with exit
> > status 1
> > $
>
> > It seems to me this is due to some missing library (undefined
> > reference...) but I have no idea what these missing files might be.
> > I've tried installing everything that made any reference to sqlite
> > form thecygwininterface.  Does anyone know how I might get a working
> > install of sqlite for python oncygwin?
>
> I believe it's a glitch in the 2.5.1 distribution current onCygwin- I
> had to install the _sqlite DLL separately to get it to work, but no
> recompilation was necessary AFAICR.
>
> Chui Tey detailed the necessary steps in his blog post "CygwinPython
> and sqlite3", but sadly it got lost and he hasn't replenished it, so you
> will have to stab around to see if there's a cached copy anywhere.
>
> regards
>  Steve
> --
> Steve Holden        +1 571 484 6266   +1 800 494 3119
> Holden Web LLC              http://www.holdenweb.com/

Well, I haven't managed to solve the problem.

I tried following these instructions but get the same error:
http://initd.org/pub/software/pysqlite/doc/install-source-win32.html

And I also tried downloading the dll from sqlite.org and putting it on
my path.

Since someone asked how I ended up solving this problem:
I'm just going to work on my Linux box where its relatively straight
forward to install
this stuff with the package manager.

If someone does have instructions for making this work on windows I'd
be very curious. I was unable to find an archived version of the blog
post referenced above.
--
http://mail.python.org/mailman/listinfo/python-list


Re: destructor not called

2008-09-29 Thread Bruno Desthuilliers

Marcin201 a écrit :

Others have already replied to your main question; in short you
shouldn't rely on __del__ being called. Regardless, is there a (good)
reason for having an instance reference to the method ? Without
further information, that seems like a code smell.


I have dictionary of fxns to do import/export based on the type of
request from user so I can call self.Import['html'] or
self.Import['text'].


getattr(obj, name) is your friend. And if you really want to maintain 
your own mapppings, do it at the appropriate level - that is, when it 
comes to methods, at the class level, not the instance level. You can 
even automate this using a decorator and a custom metaclass, ie 
(warning: Q&D code, not tested, may contain errors etc):


# myframework.py
def request_handler(func):
func._request_handler = True
return func

class RequestHandlerType(type):
def __init__(cls, name, bases, dic):
handlers = getattr(cls, '_handlers')
for name, attrib in dic:
if getattr(attrib, '_request_handler', False):
handlers[name] = attrib
cls._handlers = handlers


class BaseRequestHandler(object):
__metaclass__ = RequestHandlerType


# myapp.py
from myframework impoty request_handler, BaseRequestHandler

class MyHandler(BaseRequestHandler):
@request_handler
def html(self, *args, **kw):
# code here

@request_handler
def text(self, *args, **kw):
# code here

def dispatch(self, request):
format = request.format
try:
handler = self._handlers[format]
except KeyError:
# raise appropriate exception here
else:
return handler(self,  request)
--
http://mail.python.org/mailman/listinfo/python-list


Re: closures and dynamic binding

2008-09-29 Thread Paul Boddie
On 29 Sep, 19:26, Terry Reedy <[EMAIL PROTECTED]> wrote:
>
> Please: Python does not have 'lambda functions'.  Def statements and
> lambda expressions both define instances of the function class.  So this
> amounts to saying "functions are subject to the same caveats as functions."

I myself am aware of the nature of "lambda expressions", for want of a
better term, but it's important to emphasise their nature to anyone
reading who isn't fully aware of what they represent. My closing
paragraph touches on the issues of readability and programmer
expectation when I write that 'function definition statements do not
behave like, say, "for", "if" or "while" statements'. Although this
may seem obvious, a newcomer might overlook lambda expressions in this
regard.

Personally, I'm not a great enthusiast of closures, anyway. Perhaps I
spent too long writing Java to be able to look at them as being
anything other than a fairly imprecise way of encapsulating state in a
callable.

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


Finding subsets for a robust regression

2008-09-29 Thread tkpmep
I have coded a robust (Theil-Sen) regression routine which takes as
inputs two lists of numbers, x and y, and returns a robust estimate of
the slope and intercept of the best robust straight line fit.

In a pre-processing phase, I create two new lists, x1 and y1; x1 has
only the unique values in x, and for each unique value in x1, y1 has
the median of all such values in x. My code follows, and it seems a
bit clumsy - is there a cleaner way to do it? By the way, I'd be more
than happy to share the code for the entire algorithm - just let me
know and I will post it here.

Thanks in advance

Thomas Philips

d = {}  #identify unique instances of x and y
for xx,yy in zip(x,y):
if xx in d:
d[xx].append(yy)
else:
d[xx] = [yy]

x1 = [] #unique instances of x and y
y1 = [] #median(y) for each unique value of x
for xx,yy in d.iteritems():
x1.append(xx)
l = len(yy)
if l == 1:
y1.append(yy[0])
else:
yy.sort()
y1.append( (yy[l//2-1] + yy[l//2])/2.0 if l % 2 == 0 else
yy[l//2] )
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cannot install pysqlite on Cygwin

2008-09-29 Thread Tilman Kispersky
On Sep 29, 12:37 pm, Tilman  Kispersky <[EMAIL PROTECTED]> wrote:
> On Sep 29, 7:49 am, Steve Holden <[EMAIL PROTECTED]> wrote:
>
>
>
> > Tilman Kispersky wrote:
> > > I am trying to install sqlite for use with python oncygwin. I have
> > > installed the sqlite packages fromcygwin(that is libsqlite3-devel
> > > and libsqlite3_0).  When attempting to easy_install pysqlite I get:
>
> > > $ easy_install pysqlite
> > > Searching for pysqlite
> > > Readinghttp://pypi.python.org/simple/pysqlite/
> > > Readinghttp://pysqlite.org/
> > > Readinghttp://initd.org/pub/software/pysqlite/releases/2.3/2.3.3/
> > > Readinghttp://pysqlite.sourceforge.net/
> > > Readinghttp://initd.org/pub/software/pysqlite/releases/2.3/2.3.4/
> > > Readinghttp://initd.org/tracker/pysqlite/wiki/PysqliteDownloads
> > > Readinghttp://oss.itsystementwicklung.de/trac/pysqlite
> > > Readinghttp://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.0/
> > > Readinghttp://initd.org/pub/software/pysqlite/releases/2.3/2.3.5/
> > > Readinghttp://oss.itsystementwicklung.de/download/pysqlite/2.4/2.4.1/
> > > Readinghttp://initd.org/pub/software/pysqlite/releases/2.4/2.4.0/
> > > Best match: pysqlite 2.5.0
> > > Downloadinghttp://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.0/pysqlit...
> > > Processing pysqlite-2.5.0.tar.gz
> > > Running pysqlite-2.5.0/setup.py -q bdist_egg --dist-dir /cygdrive/c/
> > > Users/Tilman/AppData/Local/Temp/easy_install-876nHz/pysqlite-2.5.0/egg-
> > > dist-tmp-7mr3WS
> > > warning: no files found matching 'doc/*.html'
> > > warning: no files found matching 'doc/code/*.py'
> > > src/statement.c: In function `pysqlite_statement_recompile':
> > > src/statement.c:351: warning: `sqlite3_transfer_bindings' is
> > > deprecated (declared at /usr/include/sqlite3.h:3985)
> > > build/temp.cygwin-1.5.25-i686-2.5/src/connection.o: In function
> > > `pysqlite_enable_load_extension':
> > > /cygdrive/c/Users/Tilman/AppData/Local/Temp/easy_install-876nHz/
> > > pysqlite-2.5.0/src/connection.c:922: undefined reference to
> > > `_sqlite3_enable_load_extension'
> > > collect2: ld returned 1 exit status
> > > error: Setup script exited with error: command 'gcc' failed with exit
> > > status 1
> > > $
>
> > > It seems to me this is due to some missing library (undefined
> > > reference...) but I have no idea what these missing files might be.
> > > I've tried installing everything that made any reference to sqlite
> > > form thecygwininterface.  Does anyone know how I might get a working
> > > install of sqlite for python oncygwin?
>
> > I believe it's a glitch in the 2.5.1 distribution current onCygwin- I
> > had to install the _sqlite DLL separately to get it to work, but no
> > recompilation was necessary AFAICR.
>
> > Chui Tey detailed the necessary steps in his blog post "CygwinPython
> > and sqlite3", but sadly it got lost and he hasn't replenished it, so you
> > will have to stab around to see if there's a cached copy anywhere.
>
> > regards
> >  Steve
> > --
> > Steve Holden        +1 571 484 6266   +1 800 494 3119
> > Holden Web LLC              http://www.holdenweb.com/
>
> Well, I haven't managed to solve the problem.
>
> I tried following these instructions but get the same 
> error:http://initd.org/pub/software/pysqlite/doc/install-source-win32.html
>
> And I also tried downloading the dll from sqlite.org and putting it on
> my path.
>
> Since someone asked how I ended up solving this problem:
> I'm just going to work on my Linux box where its relatively straight
> forward to install
> this stuff with the package manager.
>
> If someone does have instructions for making this work on windows I'd
> be very curious. I was unable to find an archived version of the blog
> post referenced above.

I also managed to get it to work by not using cygwin's python.
I suppose this is sort of the obvious solution.

Just download the windows installers for python, pysqlite.
You can still run the windows installed version of python from cygwin
(I prefer that over the 'cmd' terminal) by specifying
the executable you want to use explicity eg:
$ /cygdrive/c/Python25/python
--
http://mail.python.org/mailman/listinfo/python-list


RE: PYTHON WORKING WITH PERL ??

2008-09-29 Thread Blubaugh, David A.
Sir,


You are absolutely correct.  I was praying to G_d I did not have to
slaughter my project's source code in this manner.  However, like life
itself, I was given legacy source code (i.e. someone else errors to fix)
in Perl.  However, I have just found out that there is a way to import
the Perl interpreter within Python!!!  I now believe I can utilize
python as the main platform to develop the project upon !!  


Thanks,

David


 

-Original Message-
From: D'Arcy J.M. Cain [mailto:[EMAIL PROTECTED] 
Sent: Monday, September 29, 2008 1:32 PM
To: Blubaugh, David A.
Cc: python-list@python.org
Subject: Re: PYTHON WORKING WITH PERL ??

On Mon, 29 Sep 2008 13:16:14 -0400
"Blubaugh, David A." <[EMAIL PROTECTED]> wrote:
> I was wondering if it was possible to have a situation where a 
> programming project would utilized BOTH python and perl?  Such as 
> utilizing python for internet programming and then utilize perl for 
> text processing and systems programming?  Is this even feasible???

I don't see why not but I also question if it is a good idea.  Once you
have all your objects and low level methods written in Python it just
makes sense to re-use them rather than trying to duplicate the
functionality in another language.

Of course, sometimes we don't have control over our entire environment
so yes, you can mix them if you have to.

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.

This e-mail transmission contains information that is confidential and may be 
privileged. It is intended only for the addressee(s) named above. If you 
receive 
this e-mail in error, please do not read, copy or disseminate it in any manner. 
If you are not the intended recipient, any disclosure, copying, distribution or 
use of the contents of this information is prohibited. Please reply to the 
message immediately by informing the sender that the message was misdirected. 
After replying, please erase it from your computer system. Your assistance in 
correcting this error is appreciated.

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


RE: PYTHON WORKING WITH PERL ??

2008-09-29 Thread Blubaugh, David A.
Thank You 

Steve!!!  


 

-Original Message-
From: Steve Holden [mailto:[EMAIL PROTECTED] 
Sent: Monday, September 29, 2008 1:38 PM
To: python-list@python.org
Subject: Re: PYTHON WORKING WITH PERL ??

Blubaugh, David A. wrote:
> To All,
> 
> 
> I was wondering if it was possible to have a situation where a 
> programming project would utilized BOTH python and perl?  Such as 
> utilizing python for internet programming and then utilize perl for 
> text processing and systems programming?  Is this even feasible???
> 
> 
> Thanks,
> 
So sorry to hear Google isn't available from your network ;-)

  http://search.cpan.org/~gaas/pyperl-1.0/perlmodule.pod

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/



This e-mail transmission contains information that is confidential and may be 
privileged. It is intended only for the addressee(s) named above. If you 
receive 
this e-mail in error, please do not read, copy or disseminate it in any manner. 
If you are not the intended recipient, any disclosure, copying, distribution or 
use of the contents of this information is prohibited. Please reply to the 
message immediately by informing the sender that the message was misdirected. 
After replying, please erase it from your computer system. Your assistance in 
correcting this error is appreciated.

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


Re: generate random digits with length of 5

2008-09-29 Thread sotirac
On Sep 28, 5:22 pm, "Aaron \"Castironpi\" Brady"
<[EMAIL PROTECTED]> wrote:
> On Sep 28, 4:08 pm, Michael Ströder <[EMAIL PROTECTED]> wrote:
>
>
>
> > Gary M. Josack wrote:
> > > Aaron "Castironpi" Brady wrote:
> > >> On Sep 28, 2:59 pm, sotirac <[EMAIL PROTECTED]> wrote:
>
> > >>> Wondering if there is a better way to generate string of numbers with
> > >>> a length of 5 which also can have a 0 in the front of the number.
>
> > >>> 
> > >>>  random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
> > >>> elements
> > >>>  code = 'this is a string' + str(random_number[0]) +
> > >>> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
> > >>> + str(random_number[4])
> > >>> 
>
> > >> '%05i'%random.randint(0,9)
> > >> --
> > >>http://mail.python.org/mailman/listinfo/python-list
>
> > > This produces numbers other than 5 digit numbers. making the start
> > > number 1 should be fine.
>
> > Why do you think it's wrong?
>
> > >>> import random
> > >>> '%05i'%random.randint(0,9)
> > '09449'
>
> > IMO it's exactly what was required.
>
> > Ciao, Michael.
>
> As you read, there isn't agreement on whether the OP wanted
> replacement.  His original code didn't; his spec seemed to.

My value of the result string can be '0' to '9'.
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to search multiple textfiles ? (Python is slow ?)

2008-09-29 Thread Stef Mientki

Lawrence D'Oliveiro wrote:

In message <[EMAIL PROTECTED]>, Stef
Mientki wrote:

  

- Pyscripter 110 sec ( PyScripter is the default IDE I use now)
- Delphi  20 .. 35 sec
- Findstr  4 sec



What order did you try try them in? Did you try each one more than once, in
different orders? Just to rule out filesystem caching effects.

  

I repeated all of them at least twice, to see if I got the same result.
And indeed the very first run (PyScripter)  was about 150 sec.
So I think the above mentioned values give a good impression, nothing more.

I'm really amazed by the speed of Python !!
It can only be beaten by findstr, which is only available on windows.



Did you try find -exec grep -F?
  

well my windows version doesn't understand that :

P:\Python>find /?
Searches for a text string in a file or files.

FIND [/V] [/C] [/N] [/I] [/OFF[LINE]] "string" [[drive:][path]filename[ 
...]]


 /V Displays all lines NOT containing the specified string.
 /C Displays only the count of lines containing the string.
 /N Displays line numbers with the displayed lines.
 /I Ignores the case of characters when searching for the string.
 /OFF[LINE] Do not skip files with offline attribute set.
 "string"   Specifies the text string to find.
 [drive:][path]filename
Specifies a file or files to search.

If a path is not specified, FIND searches the text typed at the prompt
or piped from another command.

cheers,
Stef


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


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


Re: Finding subsets for a robust regression

2008-09-29 Thread bearophileHUGS
[EMAIL PROTECTED]:

> My code follows, and it seems a bit clumsy - is there a cleaner way to do it?

The code doesn't look bad. I can suggest few things:
- When you have "paragraphs" of code that do something definite then
the comment before them can be written without indentation, to denote
it regards the whole little block. Or you can even call a subfunction
(a function inside another function/method)
- Finding good names for variables is important.

So this code:

> d = {}  #identify unique instances of x and y
> for xx,yy in zip(x,y):
> if xx in d:
> d[xx].append(yy)
> else:
> d[xx] = [yy]

May become (untested):

> # identify unique instances of x and y
> d = {}
> for xx, yy in zip(x, y):
> if xx in d:
> d[xx].append(yy)
> else:
> d[xx] = [yy]

Or better:

> # identify unique instances of seqx and seqx
> d = defaultdict(list)
> for x, y in izip(seqx, seqx):
> d[x].append(y)

Or even something like:

> def unique_x(seqx, seqx):
> """identify unique instances of seqx and seqx"""
> result = defaultdict(list)
> for x, y in izip(seqx, seqx):
> result[x].append(y)
> return result
> ...
> d = unique_x(x, y)

The following line is too much heavy, it looks like a misuse of the
inline if syntax:

> y1.append( (yy[l//2-1] + yy[l//2])/2.0 if l % 2 == 0 else
> yy[l//2] )

It was not added to python for that long lines. This looks better to
me:

l = len(yy)
if l == 1:
y_median = yy[0])
else:
yy.sort()
if l & 1:
y_median = yy[l // 2]
else:
y_median = yy[l // 2 - 1] + yy[l // 2]) / 2.0
y1.append(y_median)

But even better is to use a stronger library code, for example a
median() able to run in O(n), and a more strong unique(), like:
http://code.activestate.com/recipes/438599/
http://code.activestate.com/recipes/466330/
But using a stronger unique() this time isn't useful, so I like this
compromise:

# identify unique instances of seqx and seqx
uniques_x = defaultdict(list)
for x, y in izip(seqx, seqx):
uniques_x[x].append(y)

result_x = []
result_y = []
for x, ys in uniques_x.iteritems():
result_x.append(x)
result_y.append(median(ys))

If you want to use the last bit of semantics of CPython you can even
write that code like this:

# identify unique instances of seqx and seqx
uniques_x = defaultdict(list)
for x, y in izip(seqx, seqx):
uniques_x[x].append(y)

result_x = uniques_x.keys()
result_y = map(median, uniques_x.itervalues())

I think it works because keys and values are given in the same order,
but in real code I tend to avoid using such subtle things. Because if
you translate that code to another language, or you use another Python
implementation it may not work anymore, and lot of code sooner or
later becomes translated...

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


Re: One class per file?

2008-09-29 Thread HCB
To answer Ben Finney's questions:

The "Put one class in one file" statement is made in "Code Complete 2"
page 771.

HCB

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


Re: what does "python -i" use as input stream (stdin)?

2008-09-29 Thread Gabriel Genellina
En Fri, 26 Sep 2008 04:29:42 -0300, Almar Klein <[EMAIL PROTECTED]>  
escribió:


I would still like to hear if anyone knows how I can change the input  
stream

that
is used when running "python -i", but I would not be surprised if it is
impossible...


Sure you can. You have to replace the file descriptor 0, that is,  
"standard input"; sys.stdin reads from there. The standard way is to use  
os.dup2:


c:\temp>type foo.txt
This line read from foo.txt


c:\temp>type redirect.py
import os

inp = open("foo.txt","r")
os.dup2(inp.fileno(), 0)
print "raw_input->", raw_input()

c:\temp>python redirect.py
raw_input-> This line read from foo.txt

This is not

--
Gabriel Genellina

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


Re: unable to parse the content using the regular expression

2008-09-29 Thread Gabriel Genellina

En Thu, 25 Sep 2008 05:30:41 -0300, <[EMAIL PROTECTED]> escribió:

I've the following results from Difflib.Compare() which I want to parse  
them
using the regular expression to find out the the values that have  
changed.


  Results:-
  ---

- Analysis Time (Iterations = 1) = 0.0449145s
?   ^^ ^
+ Analysis Time (Iterations = 1) = 0.0447347s
?   ^^ ^


Here I want to display only the values that differ i.e. the lines prceded
with +,?,- signs >


Instead of parsing that generated file (intended for human usage), use  
difflib.Differ or difflib.SequenceMatcher - you get a programming  
interface to the same info, easier to use in a script.


--
Gabriel Genellina

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


Is Pyperl still active ??

2008-09-29 Thread Blubaugh, David A.

To All,


I was wondering if Pyperl is still active??  It appears as though it may
very well be no longer active at this time!!!  Is this correct??


Thanks,


David Blubaugh




This e-mail transmission contains information that is confidential and may be 
privileged. It is intended only for the addressee(s) named above. If you 
receive 
this e-mail in error, please do not read, copy or disseminate it in any manner. 
If you are not the intended recipient, any disclosure, copying, distribution or 
use of the contents of this information is prohibited. Please reply to the 
message immediately by informing the sender that the message was misdirected. 
After replying, please erase it from your computer system. Your assistance in 
correcting this error is appreciated.

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


Re: Finding subsets for a robust regression

2008-09-29 Thread Gerard flanagan

[EMAIL PROTECTED] wrote:



x1 = [] #unique instances of x and y
y1 = [] #median(y) for each unique value of x
for xx,yy in d.iteritems():
x1.append(xx)
l = len(yy)
if l == 1:
y1.append(yy[0])
else:
yy.sort()
y1.append( (yy[l//2-1] + yy[l//2])/2.0 if l % 2 == 0 else
yy[l//2] )
--


Not tested, but is this equivalent?

x1 = []
y1 = []
for xx, yy in d.iteritems():
L = len(yy) // 2
yy.sort()
y1.append(yy[L])
if not L & 1:
y1[-1] = (y1[-1] + yy[L-1]) / 2.0

It means that you have a pointless 'sort' when len(yy) == 1, but then 
you save an 'if' per-iteration.


G.

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


Source code for python nativ methods and classes

2008-09-29 Thread Mohed
Hello.
  I am interrested in seeing the source code for all the nativ builtin
methods and clases in python. Is there a webpage that lists them or is
this done easier some other way.
  This is my first post so feel free to creticue, the more you do the
faster i learn to post well.
  Mohed
--
http://mail.python.org/mailman/listinfo/python-list


Re: Music knowledge representation

2008-09-29 Thread D'Arcy J.M. Cain
On Mon, 29 Sep 2008 20:29:44 +0200
"Mr.SpOOn" <[EMAIL PROTECTED]> wrote:
> > Couldn't the note class simply have a list of all the notes and have a
> > simple method calculate the actual pitch?
> 
> That's not really how it works. There exists just 12 octave
> independent pitch classes. This means that there is a pitch class C
> with all possible Cs. There ambiguities with accidentals, because
> different named notes fall in the same pitch class. The difference is
> important for the musical theory, because C# and Db belongs to the
> same pitch class (actually they are the same note, they sounds
> completely identical -- because on the piano you play them pressing
> the same key), but in a scale they have a very different role.

Sure, they are enharmonically identical but in our tempered scale.
That's why my example showed it as (note, octave, accidental) rather
than a specific note.  It would differentiate between these.

> For example, the interval C F# is an "augmented fourth", because what
> really matters are the natural note (C and F), and their distance if
> 4. Then it is augmented due to the #-
> 
> But the interval C Gb (Gb is the same as F#) is a "diminished fifth".

This is true.  My simple example would not have dealt with this.  The
arguments would have to be the full tuple rather than the actual pitch.

> So I can't list all pitches.

You can but you can't store them as raw pitches.

> >def interval(self, lower, higher)
> >if lower > higher:
> ># uncomment one of the two following lines depending
> ># on the behaviour you want
> >#lower,higher = higher,lower
> >#higher += 12
> >
> ># could use some error trapping
> >return self.interval_name[higher - lower]
> >
> > Note that lower and higher could be a note object that you have to
> > convert to integers first.
> 
> I can't estabilish which note is higher, because all the analysis part
> is octave independent. Anyway thanks for the ideas.

I'm not sure I understand this.  You either have to assume that the
first note is the root or the lower one is.  What other options are
there?  It sounds like your requirement is "higher += 12" or some
variant.  It also depends on whether you need to deal with things like
ninths and thirteenths.

Anyway, I was just tossing out ideas.  You know what your requirements
are better than I.

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Source code for python nativ methods and classes

2008-09-29 Thread Bard Aase
On Mon, Sep 29, 2008 at 10:51 PM, Mohed <[EMAIL PROTECTED]> wrote:
> Hello.
>  I am interrested in seeing the source code for all the nativ builtin
> methods and clases in python. Is there a webpage that lists them or is
> this done easier some other way.

Check it out from svn?
svn co http://svn.python.org/projects/python/trunk/

or browse the code at http://svn.python.org/view/python/trunk/

or did I misinterpret your question?


-- 
mvh base (Bård Aase)
MSN: [EMAIL PROTECTED]
http://blog.elzapp.com
:wq
--
http://mail.python.org/mailman/listinfo/python-list


Re: Finding subsets for a robust regression

2008-09-29 Thread Gerard flanagan

Gerard flanagan wrote:

[EMAIL PROTECTED] wrote:



x1 = [] #unique instances of x and y
y1 = [] #median(y) for each unique value of x
for xx,yy in d.iteritems():
x1.append(xx)
l = len(yy)
if l == 1:
y1.append(yy[0])
else:
yy.sort()
y1.append( (yy[l//2-1] + yy[l//2])/2.0 if l % 2 == 0 else
yy[l//2] )
--


Not tested, but is this equivalent?

x1 = []
y1 = []
for xx, yy in d.iteritems():
L = len(yy) // 2
yy.sort()
y1.append(yy[L])
if not L & 1:
y1[-1] = (y1[-1] + yy[L-1]) / 2.0

It means that you have a pointless 'sort' when len(yy) == 1, but then 
you save an 'if' per-iteration.


G.

--


Maybe that should be:

if L and not L & 1:
   ...

anyway...



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


Converting a strng to an anonymous function

2008-09-29 Thread Nathan Seese
I'm writing a program to sort files with arbitrary python code. The 
method I'm using for that is to pass sort an anonymous function taken 
from the arguments. I'm wondering how to change a raw string into an 
anonyous function.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Source code for python nativ methods and classes

2008-09-29 Thread skip

mohed> I am interrested in seeing the source code for all the nativ
mohed> builtin methods and clases in python. Is there a webpage that
mohed> lists them or is this done easier some other way.

Browse the source.  You can download it then poke around using your favorite
editor:

http://www.python.org/download/

or browse the source online:

http://svn.python.org/view/python/trunk/

Skip

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


Re: Music knowledge representation

2008-09-29 Thread Aaron "Castironpi" Brady
On Sep 29, 3:56 pm, "D'Arcy J.M. Cain" <[EMAIL PROTECTED]> wrote:
> On Mon, 29 Sep 2008 20:29:44 +0200
>
> "Mr.SpOOn" <[EMAIL PROTECTED]> wrote:
> > > Couldn't the note class simply have a list of all the notes and have a
> > > simple method calculate the actual pitch?
>
> > That's not really how it works. There exists just 12 octave
> > independent pitch classes. This means that there is a pitch class C
> > with all possible Cs. There ambiguities with accidentals, because
> > different named notes fall in the same pitch class. The difference is
> > important for the musical theory, because C# and Db belongs to the
> > same pitch class (actually they are the same note, they sounds
> > completely identical -- because on the piano you play them pressing
> > the same key), but in a scale they have a very different role.
>
> Sure, they are enharmonically identical but in our tempered scale.
> That's why my example showed it as (note, octave, accidental) rather
> than a specific note.  It would differentiate between these.
>
> > For example, the interval C F# is an "augmented fourth", because what
> > really matters are the natural note (C and F), and their distance if
> > 4. Then it is augmented due to the #-
>
> > But the interval C Gb (Gb is the same as F#) is a "diminished fifth".
>
> This is true.  My simple example would not have dealt with this.  The
> arguments would have to be the full tuple rather than the actual pitch.
>
> > So I can't list all pitches.
>
> You can but you can't store them as raw pitches.
>
> > >    def interval(self, lower, higher)
> > >        if lower > higher:
> > >            # uncomment one of the two following lines depending
> > >            # on the behaviour you want
> > >            #lower,higher = higher,lower
> > >            #higher += 12
>
> > >        # could use some error trapping
> > >        return self.interval_name[higher - lower]
>
> > > Note that lower and higher could be a note object that you have to
> > > convert to integers first.
>
> > I can't estabilish which note is higher, because all the analysis part
> > is octave independent. Anyway thanks for the ideas.
>
> I'm not sure I understand this.  You either have to assume that the
> first note is the root or the lower one is.  What other options are
> there?  It sounds like your requirement is "higher += 12" or some
> variant.  It also depends on whether you need to deal with things like
> ninths and thirteenths.
>
> Anyway, I was just tossing out ideas.  You know what your requirements
> are better than I.
>
> --
> D'Arcy J.M. Cain <[EMAIL PROTECTED]>         |  Democracy is three 
> wolveshttp://www.druid.net/darcy/               |  and a sheep voting on
> +1 416 425 1212     (DoD#0082)    (eNTP)   |  what's for dinner.

I like D'Arcy's tuples so far.  You could have a 4th element that
contains adjustment for temper.  Octave could be None.

You want ( 4, None, 1 ) "sharp 4th" == ( 5, None, -1 ) "flat 5th", but
you can't have it.  The closest ones are Note( 4, None, 1 )== Note( 5,
None, -1 ) or Note(4, None, 1 ).enh_cmp( Note( 5, None, -1 ) ).  More
elaborate code means more options for calling, though: Note(4, None,
1 ).cmp_enh( 5, None, -1 ), and just call the constructor on the 3
arguments.  You also want Note( 9, None, 0 ).cmp_octave( 2, Rel+ 1,
0 ), 9th== 2nd + 1 octave, and Note( 9, None, 0 ).cmp_nooctave( 2,
None, 0 ), where cmp_... functions return in ( -1, 0, 1 ), and the
middle term can be a class Relative instance, which indicates a
relative octave instead of absolute... or just start at 4.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a strng to an anonymous function

2008-09-29 Thread bearophileHUGS
On Sep 29, 11:25 pm, Nathan Seese <[EMAIL PROTECTED]> wrote:
> I'm writing a program to sort files with arbitrary python code. The
> method I'm using for that is to pass sort an anonymous function taken
> from the arguments. I'm wondering how to change a raw string into an
> anonyous function.

Is this enough for you?

>>> L = [1, -5, 7, -9]
>>> sorted(L, key=abs)
[1, -5, 7, -9]
>>> func = "abs"
>>> sorted(L, key=eval(func))
[1, -5, 7, -9]
>>> func = "abs(x)"
>>> sorted(L, key=lambda x: eval(func))
[1, -5, 7, -9]

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


Re: Music knowledge representation

2008-09-29 Thread Mr.SpOOn
On Mon, Sep 29, 2008 at 10:56 PM, D'Arcy J.M. Cain <[EMAIL PROTECTED]> wrote:
>> I can't estabilish which note is higher, because all the analysis part
>> is octave independent. Anyway thanks for the ideas.
>
> I'm not sure I understand this.  You either have to assume that the
> first note is the root or the lower one is.  What other options are
> there?  It sounds like your requirement is "higher += 12" or some
> variant.  It also depends on whether you need to deal with things like
> ninths and thirteenths.
>
> Anyway, I was just tossing out ideas.  You know what your requirements
> are better than I.

Mmm, actually it's a good idea. I didn't get it right before. Thanks :D
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to search multiple textfiles ?

2008-09-29 Thread George Sakkis
On Sep 29, 5:16 am, Lawrence D'Oliveiro <[EMAIL PROTECTED]
central.gen.new_zealand> wrote:
> In message
> <[EMAIL PROTECTED]>, George
>
> Sakkis wrote:
> > $ find -name "*py" | xargs egrep "\bword\b"
>
> Better:
>
>     find -name '*.py' -exec grep -E "\bword\b" {} \;

In what way is this better ? I don't dispute it, I'm just curious.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a strng to an anonymous function

2008-09-29 Thread Bruno Desthuilliers

Nathan Seese a écrit :
I'm writing a program to sort files with arbitrary python code. The 
method I'm using for that is to pass sort an anonymous function taken 
from the arguments. I'm wondering how to change a raw string into an 
anonyous function.


Care to give a couple more explanation about your use case ? There might 
be better solutions than eval/exec...

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

Python arrays and sting formatting options

2008-09-29 Thread Ivan Reborin
Hello everyone,

I was wondering if anyone here has a moment of time to help me with 2
things that have been bugging me.

1. Multi dimensional arrays - how do you load them in python
For example, if I had:
---
1 2 3
4 5 6
7 8 9

10 11 12
13 14 15
16 17 18
---
with "i" being the row number, "j" the column number, and "k" the ..
uhmm, well, the "group" number, how would you load this ?

If fortran90 you would just do:

do 10 k=1,2
do 20 i=1,3

read(*,*)(a(i,j,k),j=1,3)

20 continue
10 continue

How would the python equivalent go ?

2. I've read the help on the next one but I just find it difficult
understanding it.
I have;
a=2.01
b=123456.789
c=1234.0001

How do you print them with the same number of decimals ?
(eg. 2.000, 123456.789, 1234.000)
and how do you print them with the same number of significant
decimals?
(eg. 2.01, 123456.7, 1234.000 - always 8 decimals) ?


Is something like this possible (built-in) in python ?

Really grateful for all the help and time you can spare.

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


Re: Converting a strng to an anonymous function

2008-09-29 Thread Nathan Seese
> On Sep 29, 11:25 pm, Nathan Seese <[EMAIL PROTECTED]> wrote:
>> I'm writing a program to sort files with arbitrary python code. The
>> method I'm using for that is to pass sort an anonymous function taken
>> from the arguments. I'm wondering how to change a raw string into an
>> anonyous function.
> 
> Is this enough for you?
> 
 L = [1, -5, 7, -9]
 sorted(L, key=abs)
> [1, -5, 7, -9]
 func = "abs"
 sorted(L, key=eval(func))
> [1, -5, 7, -9]
 func = "abs(x)"
 sorted(L, key=lambda x: eval(func))
> [1, -5, 7, -9]
> 
> Bye,
> bearophile

Thanks, that works great! 
--
http://mail.python.org/mailman/listinfo/python-list


Re: [wxpython-users] ANN: wxPython 2.8.9.0

2008-09-29 Thread Robin Dunn

Clay Hobbs wrote:




I'm curious, why do you package wxPython for Fedora 6 and 7, but not 8
and 9?



It's only because I haven't taken the time to update and retest those 
build boxes.



--
Robin Dunn
Software Craftsman
http://wxPython.org  Java give you jitters?  Relax with wxPython!

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


Re: Source code for python nativ methods and classes

2008-09-29 Thread Terry Reedy

Bard Aase wrote:

On Mon, Sep 29, 2008 at 10:51 PM, Mohed <[EMAIL PROTECTED]> wrote:

Hello.
 I am interrested in seeing the source code for all the nativ builtin
methods and clases in python. Is there a webpage that lists them or is
this done easier some other way.


Check it out from svn?
svn co http://svn.python.org/projects/python/trunk/

or browse the code at http://svn.python.org/view/python/trunk/


This has the code for the upcoming 2.6 release.  For other branches
http://svn.python.org/view/python/branches/
in particular py3k or release25-maint.

Built-in classes are in the Objects sub-directory.
(But there is a bit of math in the Python sub-dir).
Built-in modules are in the Modules sub-directory.
Python-coded modules are in the Lib sub-directory.
I don't know where the built-in functions are.

To see the current state of a file, click on the revision number in the 
second column.


Clicking on the name in the first column give a rather strange change 
log that goes forward through each year as it goes back through the years.


Terry Jan Reedy

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


  1   2   >