ANN: wxPython 2.7.1.1 released

2006-10-20 Thread Robin Dunn
Announcing
--

The 2.7.1.1 release of wxPython is now available for download at
http://wxpython.org/download.php.  This release is the first offical
release in the 2.7.x development series, and includes a lot of new
features, enhancements and fixes.  Source and binaries are available
for both Python 2.4 and 2.5 for Windows and Mac, as well some pacakges
for varous Linux distributions.  A summary of changes is listed below
and also at http://wxpython.org/recentchanges.php.


What is wxPython?
-

wxPython is a GUI toolkit for the Python programming language. It
allows Python programmers to create programs with a robust, highly
functional graphical user interface, simply and easily. It is
implemented as a Python extension module that wraps the GUI components
of the popular wxWidgets cross platform library, which is written in
C++.

wxPython is a cross-platform toolkit. This means that the same program
will usually run on multiple platforms without modifications.
Currently supported platforms are 32-bit Microsoft Windows, most Linux
or other Unix-like systems using GTK2, and Mac OS X 10.3+, in most
cases the native widgets are used on each platform.


Changes in 2.7.1.1
--

The following deprecated items have been removed:

 * wx.Bitmap SetQuality and GetQuality methods

 * The wx.GetNumberFromUser function

 * wx.EVT_LIST_GET_INFO and wx.EVT_LIST_SET_INFO

 * wx.BookCtrlSizer and wx.NotebookSizer

 * The PostScript-specific methods of wx.PrintData

 * wx.PrintDialogData SetSetupDialog and GetSetupDialog methods

 * wx.FontMapper SetConfig method

 * wx.html.HtmlSearchStatus.GetContentsItem method

 * wx.html.HtmlHelpData.GetContents, GetContentsCnt, GetIndex, and
   GetIndexCnt methods


wx.EventLoop is now implemented for wxMac.

Added wxPython wrappers for the new wx.Treebook and wx.Toolbook
classes.

wx.DC.BeginDrawing and EndDrawing have been deprecated in the C++
code, so since they never really did anything before they are now just
empty stubs in wxPython.

Solved a problem that has been around for a very long time in how C++
methods are virtualized for overriding in derived Python classes.
Previously we couldn't do it for methods that needed to also exist in
the base class wrappers such that they could be called normally.  (The
reasons are long and complex, but suffice it to say that it was due to
mixing C++'s dynamic dispatch, and Python's runtime lookup of the
method attributes resulting in endless recursion of function calls.)
Because of this problem I used a hack that I have always hated, and
that is renaming the base class methods with a base_* prefix, for
example wx.Printout.base_OnBeginDocument.  Now that the problem has
finally been solved I have replaced all the base_Whatever() methods
with the real Whatever() method as well as a simple wrapper named
base_Whatever that is marked as deprecated.  So now instead of writing
your overridden methods like this::

 def OnBeginDocument(self, start, end):
# do something here
return self.base_OnBeginDocument(start, end)

You can now call the base class method the normal way, like this::

 def OnBeginDocument(self, start, end):
# do something here
return Printout.OnBeginDocument(self, start, end)

Or like this with super()::

 def OnBeginDocument(self, start, end):
# do something here
return super(MyPrintout, self).OnBeginDocument(start, end)

Note that the old way with the base_* function still works, but you
will get a DeprecationWarning from calling base_OnBeginDocument.  The
classes affected by this are:

 * wx.DropSource
 * wx.DropTarget
 * wx.TextDropTarget
 * wx.FileDropTarget
 * wx.PyLog   (also added the ability to override Flush)
 * wx.PyApp   (also added the ability to override ExitMainLoop)
 * wx.Printout
 * wx.PyPrintPreview
 * wx.PyPreviewFrame
 * wx.PreviewControlBar
 * wx.Process
 * wx.PyControl
 * wx.PyPanel
 * wx.PyScrolledWindow
 * wx.PyWindow
 * wx.Timer
 * wx.grid.PyGridCellRenderer
 * wx.grid.PyGridCellEditor
 * wx.grid.PyGridCellAttrProvider
 * wx.grid.PyGridTableBase
 * wx.html.HtmlWindow
 * wx.wizard.PyWizardPage


Added the wx.DC.GradientFillConcentric and wx.DC.GradientFillLinear
methods.

wxGTK: wx.ListBox and wx.CheckListBox are now using native GTK2
widgets.

Added wx.ListBox.HitTest() from patch 1446207

Bumped up to SWIG 1.3.29.  This provides some more runtime performance
boosts, gets rid of the dreaded Ptr classes, and some other nice new
things.

Added wx.Window.GetScreenPosition and GetScreenRect which returns the
position of the window in screen coordinates, even if the window is
not a top-level window.

Added GetResourcesDir and GetLocalizedResourcesDir to
wx.StandardPaths.

Added a GetReceivedFormat method to wx.DataObjectComposite.  You can
use this to find out what format of data object was 

help with my first use of a class

2006-10-20 Thread BartlebyScrivener
I am a mere hobbyist. Spent several hours trying to make a class,
because I think this is an occasion where I need one. But I can't make
it work.

This code works (only because of the global c, which I know I'm
supposed to avoid, by using a Class). I edited the rest to leave out
the irrelevant formatting and printing of the quotations.

I've read about Classes several times, but I don't get them yet.
Obviously. If I can solve one real life problem like this, then maybe
I'll see the light.

If I understand the power of Classes correctly, I could make one that
would allow me to make a new instance that would connect to, say, an
SQLite3 db instead of the Access db, as well as to create more methods
that will do different SQL searches.

Thank you for any help,

rd

--

import mx.ODBC.Windows as odbc
import sys
import random

def connect():
global c
db='DSN=Quotations'
conn = odbc.DriverConnect(db)
c = conn.cursor()

def random_quote():

Counts all of the quotes in MS Access database Quotations2005.mdb.
Picks one quote at random and displays it using textwrap.

c.execute (SELECT COUNT(Quote) FROM PythonQuoteQuery)
# Yields the number of rows with something in the quote field
total_quotes = c.fetchone()
# Get a random number somewhere between 1 and the number of total
quotes
quote_number = (random.randint(1, total_quotes[0]),)
# Select a quote where the ID matches that number
c.execute (SELECT Author, Quote FROM PythonQuoteQuery WHERE ID=?,
quote_number)
quote = c.fetchone()
blah blah blah

def print_quote()
code to format and print the quote (which will also have to be
global, unless I learn Classes!)


if __name__ == '__main__':
if len(sys.argv) == 1:
connect()
random_quote()
print_quote()

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


How to upgrade python from 2.4.3 to 2.4.4 ?

2006-10-20 Thread [EMAIL PROTECTED]
Hi,

I just want to upgrade my python version from 2.4.3 to 2.4.4,do I need 
to uninstall python 2.4.3 first ?

I'd rather not to do so, because I have installed some other python 
packages for python2.4.3.


Thanks.

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


Re: Need help in Py2exe

2006-10-20 Thread Kirt


 there's a page on the py2exe site about tweaks necessary for specific
 modules:

  http://www.py2exe.org/index.cgi/WorkingWithVariousPackagesAndModules

 look for:

  If you're getting File xml\sax\saxexts.pyc, line 77, in
  make_parser; xml.sax._exceptions.SAXReaderNotAvailable: No
  parsers found, read this
 
 /F

Thanx for the help. It worked.

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


Re: Help: Python2.3 Python2.4 on RHEL4 x86_64

2006-10-20 Thread Martin v. Löwis
Christopher Taylor schrieb:
 This basically means to me that Python2.4 is loading gloab.py from
 /usr/lib64/Python2.3 insead of /usr/lib/Python2.4  (even thought I
 wanted to install the related files in /usr/lib64/Python2.4)
 
 Can someome please help!

Can you please report what sys.path is? Do you have PYTHONPATH
set, by any chance? Python shouldn't normally look into the library
of a totally unrelated installation.

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


Re: How to upgrade python from 2.4.3 to 2.4.4 ?

2006-10-20 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

 I just want to upgrade my python version from 2.4.3 to 2.4.4,do I need 
 to uninstall python 2.4.3 first ?

afaik, no.

/F

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


Re: How to upgrade python from 2.4.3 to 2.4.4 ?

2006-10-20 Thread Martin v. Löwis
[EMAIL PROTECTED] schrieb:
 I just want to upgrade my python version from 2.4.3 to 2.4.4,do I need
 to uninstall python 2.4.3 first ?
 
 I'd rather not to do so, because I have installed some other python
 packages for python2.4.3.

You don't have to uninstall. Installing on top will work just fine;
both on Windows and Unix (not sure about Mac).

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


ANN compiler2 : Produce bytecode from Python 2.5 Abstract Syntax Trees

2006-10-20 Thread Michael Spencer

Announcing: compiler2
-

For all you bytecode enthusiasts:  'compiler2' is an alternative to the 
standard 
library 'compiler' package, with several advantages.

Improved pure-python compiler

- Produces identical bytecode* to the built-in compile function for all /Lib
   and Lib/test modules, including 'peephole' optimizations
- Works with 2.5's 'factory-installed' ASTs, rather than 2.4's 'after-market'
   version
- Is significantly faster

* Except for the pesky stack-depth calculation

Possible applications

- Understanding/documenting/verifying the compilation process
- Implementing experimental compilation features (compile-time constants,
   function in-lining anyone?)
- Whatever the old compiler package is used for ;-)


Getting started
---
Point your svn client to:
 http://svn.brownspencer.com/pycompiler/branches/new_ast/

Check out to a compiler2 directory on PYTHONPATH
Test with python test/test_compiler.py


Cheers
Michael

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


Re: help with my first use of a class

2006-10-20 Thread BartlebyScrivener
Whoah. At least I got the connection. I think. Maybe I can figure more
on my own. Any help appreciated.

Thanks

-

class Connection:
def __init__(self, aDatasource):
self.db = aDatasource
self.conn = odbc.DriverConnect(self.db)
self.conn.cursor()

def random_quote():

Counts all of the quotes in MS Access database Quotations2005.mdb.
Picks one quote at random and displays it using textwrap.

c = Connection('DSN=Quotations')
c.execute (SELECT COUNT(Quote) FROM PythonQuoteQuery)

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


Re: help with my first use of a class

2006-10-20 Thread [EMAIL PROTECTED]
BartlebyScrivener wrote:
 I am a mere hobbyist. Spent several hours trying to make a class,
 because I think this is an occasion where I need one. But I can't make
 it work.

 This code works (only because of the global c, which I know I'm
 supposed to avoid, by using a Class). I edited the rest to leave out
 the irrelevant formatting and printing of the quotations.

 I've read about Classes several times, but I don't get them yet.
 Obviously. If I can solve one real life problem like this, then maybe
 I'll see the light.

 If I understand the power of Classes correctly, I could make one that
 would allow me to make a new instance that would connect to, say, an
 SQLite3 db instead of the Access db, as well as to create more methods
 that will do different SQL searches.

 Thank you for any help,

 rd

 --

 import mx.ODBC.Windows as odbc
 import sys
 import random

 def connect():
 global c

This means you want to use a global variable c which doesn't exist yet,
an example would be to save this code to a file:

#!/usr/bin/env python

c = 0
def test_global():
global c
c = 1

print c

this will print 0 when you run it

 db='DSN=Quotations'
 conn = odbc.DriverConnect(db)
 c = conn.cursor()

 def random_quote():
 
 Counts all of the quotes in MS Access database Quotations2005.mdb.
 Picks one quote at random and displays it using textwrap.
 
 c.execute (SELECT COUNT(Quote) FROM PythonQuoteQuery)
 # Yields the number of rows with something in the quote field
 total_quotes = c.fetchone()
 # Get a random number somewhere between 1 and the number of total
 quotes
 quote_number = (random.randint(1, total_quotes[0]),)
 # Select a quote where the ID matches that number
 c.execute (SELECT Author, Quote FROM PythonQuoteQuery WHERE ID=?,
 quote_number)
 quote = c.fetchone()
 blah blah blah

 def print_quote()
 code to format and print the quote (which will also have to be
 global, unless I learn Classes!)



A class structure could look like - please bear in mind that I don't
know mx.ODBC.Windows - I guess it is not completely DB-API compliant,
as you don't use a connect method.

class SQLQuery(object):
Object which connects to the database and can execurte SQL
commands

def __init__(self, conn):
conn is a dictionary {'serverId': XX, 'userId': YY,
'passWord': ZZ}

self.connection = connect(conn['userId'], conn['passWord'],
conn['serverId'])
self.cursor = self.__connection.cursor()

def select(self, selectqry):
argument selectqry specifies a sql which returns data, like a
select

self.cursor.execute(selectqry)
return self.cursor.fetchall()

sql = SQLQuery('serverId': 'XX', 'userId': 'YY', 'passWord': 'ZZ')
qoutes = sql.select(SELECT COUNT(Quote) FROM PythonQuoteQuery)
print quotes

 if __name__ == '__main__':
 if len(sys.argv) == 1:

sys.argv is a list, where the first argument is the name of the running
script, the second element is the first argument, etc.

 connect()
 random_quote()
 print_quote()

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


Re: help with my first use of a class

2006-10-20 Thread James Stroud
BartlebyScrivener wrote:
 I am a mere hobbyist. Spent several hours trying to make a class,
 because I think this is an occasion where I need one. But I can't make
 it work.
 
 This code works (only because of the global c, which I know I'm
 supposed to avoid, by using a Class). I edited the rest to leave out
 the irrelevant formatting and printing of the quotations.
 
 I've read about Classes several times, but I don't get them yet.
 Obviously. If I can solve one real life problem like this, then maybe
 I'll see the light.
 
 If I understand the power of Classes correctly, I could make one that
 would allow me to make a new instance that would connect to, say, an
 SQLite3 db instead of the Access db, as well as to create more methods
 that will do different SQL searches.
 
 Thank you for any help,
 
 rd
 
 --
 
 import mx.ODBC.Windows as odbc
 import sys
 import random
 
 def connect():
 global c
 db='DSN=Quotations'
 conn = odbc.DriverConnect(db)
 c = conn.cursor()
 
 def random_quote():
 
 Counts all of the quotes in MS Access database Quotations2005.mdb.
 Picks one quote at random and displays it using textwrap.
 
 c.execute (SELECT COUNT(Quote) FROM PythonQuoteQuery)
 # Yields the number of rows with something in the quote field
 total_quotes = c.fetchone()
 # Get a random number somewhere between 1 and the number of total
 quotes
 quote_number = (random.randint(1, total_quotes[0]),)
 # Select a quote where the ID matches that number
 c.execute (SELECT Author, Quote FROM PythonQuoteQuery WHERE ID=?,
 quote_number)
 quote = c.fetchone()
 blah blah blah
 
 def print_quote()
 code to format and print the quote (which will also have to be
 global, unless I learn Classes!)
 
 
 if __name__ == '__main__':
 if len(sys.argv) == 1:
 connect()
 random_quote()
 print_quote()
 

You really don't need classes for this, just parameters + return values. 
Probably best would be to master the idea of parameters + return values 
before yo move on to classes. This is called procedural programming. 
Notice that there is no name collision because of strict python 
namespaces (a good idea, according to Tim Peters).


For example:

def connect():
 db='DSN=Quotations'
 conn = odbc.DriverConnect(db)
 c = conn.cursor()
 # NOTE THE RETURN VALUE:
 return c

def random_quote(c):  # == NOTE THE PARAMETER
 
 Counts all of the quotes in MS Access database Quotations2005.mdb.
 Picks one quote at random and displays it using textwrap.
 
 c.execute (SELECT COUNT(Quote) FROM PythonQuoteQuery)
 # Yields the number of rows with something in the quote field
 total_quotes = c.fetchone()
 # Get a random number somewhere between 1 and ...
 quote_number = (random.randint(1, total_quotes[0]),)
 # Select a quote where the ID matches that number
 q = SELECT Author, Quote FROM PythonQuoteQuery WHERE ID=?
 c.execute (q, quote_number)
 quote = c.fetchone()
 # NOTE THE RETURN VALUE:
 return quote

def print_quote(quote): # == NOTE THE PARAMETER
   print quote   # == WHATEVER YOU WANT TO DO

if __name__ == '__main__':
 if len(sys.argv) == 1:
 c = connect()# == NO COLLISION: NAMESPACES
 quote = random_quote(c)  # == DITTO
 print_quote(quote)   # THERE YOU HAVE IT


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


Re: help with my first use of a class

2006-10-20 Thread BartlebyScrivener
Wow,

That's great, James.

Thanks. I shall put it together.

Appreciate it.

rd

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


Re: Decorators and how they relate to Python - A little insight please!

2006-10-20 Thread Gabriel Genellina

At Friday 20/10/2006 02:38, [EMAIL PROTECTED] wrote:


it's handy for doing things like validation of parameter and return
types. Like...

@accepts(int,int)
@returns(int)
def add(a,b):
return a+b


So, it's handy for converting Python into another language :)


--
Gabriel Genellina
Softlab SRL 


__
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: invert or reverse a string... warning this is a rant

2006-10-20 Thread Hendrik van Rooyen
 Fredrik Lundh [EMAIL PROTECTED]wrote:
8---
 'a man a plan a canal panama' is not a palindrome
 
 ?

not if spaces count -

able was I ere I saw elba  - is one  - but its a tougher test...

- Hendrik

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


Re: Converting existing module/objects to threads

2006-10-20 Thread Hendrik van Rooyen
[EMAIL PROTECTED] wrote:
 I have inheirted some existing code, that i will explain in a moment,
 have needed to extend and ultimately should be able to run in threads.
 I've done a bunch of work with python but very little with threads and
 am looking for some pointers on how to implement, and if the lower
 level modules/objects need to be rewritten to use threading.local for
 all local variables.

 I have a module that communicates with a hardware device, which reads
 data off of sensors, that can only talk with one controller at a time.
 The controller (my module) needs to (in its simplest form) init,
 configure the device, request data, and write out xml, sleep, repeat.

 The new request is that the device needs to be queried until a
 condition is true, and then start requesting data.  So an instance of a
 controller needs to be deadicated to a hardware device forever, or
 until the program endswhich ever comes first.

 This currently works in a non-threaded version, but only for one device
 at a time, there is a need to create a single windows(yeach) service
 that talks to many of these devices at once.  I don't need worker
 threads that handle seperate portions of the entire job, i need a
 single application to spawn multiple processes to run through the
 entire communication from configure to report, sleep until the next
 interval time and run again.  The communication could last from 1
 minute to 10 minutes before it ends.

8--

not sure if I understand this correctly - but I would in this position spawn new
threads, and use a global list of queues to interface between the new threads
and the old comms module, still talking to one device at a time, but now time
sliced. - in the comms module:

for q in list_of_queues:
see if anything to ask:
continue if not
ask it and put answer on reply queue

but then I am a Philistine coder, interested only in getting the job done...

- Hendrik


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


Re: invert or reverse a string... warning this is a rant

2006-10-20 Thread Hendrik van Rooyen
 Brad [EMAIL PROTECTED] wrote:


 Steven D'Aprano wrote:

  Gah!!! That's *awful* in so many ways.

 Thanks... I'm used to hearing encouragement like that. After a while you
 begin to believe that everything you do will be awful, so why even
 bother trying?

 rant

 It has been my experience that Python has discouraging forums with
 someone always calling someone else an idiot or telling them they are
 awful in some way. I love Python, but the community is way too negative,
 uptight and generally down on users who do not have PhD's in CS or Math.

 Do you have children? How would your child feel if he brought you
 something he had made and you then told him it was awful in *sooo* many
 ways. How does that reflect on you and the community you represent?

 Cut people who don't think like you some slack, OK?

 /rant

8-

This is kind of sad to see - what seems not be appreciated here is the genuine
effort that was put in by Stephen to critique the piece of code - not just a one
liner putdown, but a reasoned exposition, taking time...

and yes - it hurts at first to have your ego bruised - but look past that - and
see the genuine attempt to help.

- Hendrik


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


Re: invert or reverse a string... warning this is a rant

2006-10-20 Thread Simon Forman
rick wrote:
...
 see that the sequence is reversed. Backwards is pure, simple and easy.
 This is not so in Python and it should be.

foo[::-1] isn't pure, simple and easy?

It derives cleanly from the slice notation, it does exactly what you
want, and it even works with lists and tuples and any other class
written to support slice notation.

Does ruby have a built in string function to do this: foo[::-2]?  How
about this: foo[-1::-2] or this: foo[-2::-2]?

See, it's not about blindly memorizing this stuff, it's about clever
abstractions that allow you to quickly, flexibly and powerfully program
your computer.  I'd rather learn a few well thought out abstractions
than memorize a set of methods.

The answer to your OP question, Why can't Python have a reverse()
function/method like Ruby? is It can.  You can build it yourself
quickly and easily, and a lot of other functions as well.

Peace,
~Simon

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


Re: invert or reverse a string... warning this is a rant

2006-10-20 Thread I V
On Fri, 20 Oct 2006 09:04:07 +1000, Steven D'Aprano wrote:
 I agree -- the reversed() function appears to be an obvious case of purity
 overriding practicality :(
 
 str(reversed(some string))
 'reversed object at 0xb7edca4c'
 repr(reversed(some string))
 'reversed object at 0xb7edca4c'

This doesn't seem particularly pure to me, either. I would
have thought str(some_iter) should build a string out of the iterator, as
list(some_iter) or dict(some_iter) do. I guess this might have to wait for
Python 3, but str ought to be a proper string constructor, not a produce
a printable representation of function, particularly when we have repr to
do the latter.
-- 
http://mail.python.org/mailman/listinfo/python-list


Downloading images with python

2006-10-20 Thread Hans Olav Hygen
On 23. of October last year a the follwing was posted to this group:

 htmlSource=urllib.urlopen(http://www.godandscience.org/images/nebula.jpg;)
 # Read from the object, storing the page's contents in 's'.
 s = htmlSource.read()
 htmlSource.close()
 myfile = open(myfile.jpg, w)
 myfile.write(s)
 myfile.close

There were two advices (use urllib2 and wb). I tried to build this  
script on this basis:

import win32api
import win32com
import urllib2
gifp=TAMAfy=1900ty=2005m=21r_type=TRr_no=1)
htmlSource=urllib2.urlopen(http://www.godandscience.org/images/nebula.jpg;)
# Read from the object, storing the page's contents in 's'.
s = htmlSource.read()
htmlSource.close()
myfile = open(P:\Jobb\Prosjekt\Maanedsoversikt\myfile.jpg, wb)
myfile.write(s)
myfile.close


But the images get cropped at the bottom. Any suggestions on how to get  
the whole image, and not only 80 - 90% (I run python 2.4 with PythonWin on  
a Windows XP)

-- 
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: invert or reverse a string... warning this is a rant

2006-10-20 Thread Demel, Jeff
Paul wrote:
.join(sum(map(list,zip(s,s[len(s)/2:])),[]))

perhaps?

Not quite as elegant as a string.shuffle would be, am I right?

-Jeff
This email is intended only for the individual or entity to which it is 
addressed.  This email may contain information that is privileged, confidential 
or otherwise protected from disclosure. Dissemination, distribution or copying 
of this e-mail or any attachments by anyone other than the intended recipient, 
or an employee or agent responsible for delivering the message to the intended 
recipient, is prohibited. If you are not the intended recipient of this message 
or the employee or agent responsible for delivery of this email to the intended 
recipient, please notify the sender by replying to this message and then delete 
it from your system.  Any use, dissemination, distribution, or reproduction of 
this message by unintended recipients is strictly prohibited and may be 
unlawful.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Downloading images with python

2006-10-20 Thread Fredrik Lundh
Hans Olav Hygen wrote:

 myfile = open(P:\Jobb\Prosjekt\Maanedsoversikt\myfile.jpg, wb)
 myfile.write(s)
 myfile.close

make that myfile.close()

 But the images get cropped at the bottom.

files are closed when the program exits (unless it does so in an uncontrolled 
way),
so I assume you were trying to access the file while your script was still 
running.

/F 



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


Convert binary image to JPEG with 72 dpi

2006-10-20 Thread Nico Grubert
Dear list members,I have the binary content of an image file and it's filename.I neither know the resolution nor the dpi of the image.No I need to convert this binary content into a 72 dpi jpeg image.
Furthermore I have to resize the image so neither the width nor the height is bigger than 250 pixels. I'd like to use PIL for this job. Any tips how to do it?Regards, Nico
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: invert or reverse a string... warning this is a rant

2006-10-20 Thread Kay Schluehr
 The Ruby approach makes sense to me as a human being.

http://happyfuncog.blogspot.com/2006/09/confessions-of-pseudo-misanthrope.html

 The Python approach is not easy for me (as a human being) to remember.

I always thought we Pythonistas are already idiots but whenever I meet
a Rubist it ( the human being ) appears completely retarded to me.

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


BeautifulSoup problem

2006-10-20 Thread placid
Hi all,

Just wondering if anyone knows how to get the text between the tags of
the following Tag object? 

span class=nametextHello/span

Cheers

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


Re: invert or reverse a string... warning this is a rant

2006-10-20 Thread Fredrik Lundh
Brad [EMAIL PROTECTED] wrote:

 Do you have children? How would your child feel if he brought you
 something he had made and you then told him it was awful in *sooo* many
 ways.

If you're arguing that everything a child does and says should be rewarded,
I seriously doubt that you have any.

(on the other hand, I didn't even have to tell my 3-year old that cutting the
whiskers off the kitten wasn't quite as clever as he had thought; he realized
that all by himself, but a bit too late for the poor animal...)

/F 



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


Re: invert or reverse a string... warning this is a rant

2006-10-20 Thread Fredrik Lundh
Hendrik van Rooyen wrote:

 'a man a plan a canal panama' is not a palindrome

 not if spaces count -

which they do if you rely on a single reverse operation (my point was
that it takes a bit more work than that to check for a palindrome).

/F 



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


Re: a little about regex

2006-10-20 Thread Fulvio
On Wednesday 18 October 2006 23:05, Ant wrote:
     allow = re.compile(r'.*(?!\.com)\.my(|$)')  # negative lookbehind
     if allow.search(adr):
         return True
     return False

I'd point out that :
 allow = re.search(r'.*(?!\.com)\.my(|$)',adr)

Will do as yours, since the call to 're' class will do the compilation as here 
it's doing separately.

 Though having the explicit allow and deny expressions may make what's
 going on clearer than the fairly esoteric negative lookbehind.

This makes me think that your point is truly correct.
The option for my case is meant as  deny all except those are specified. 
Also may go viceversa. Therefore I should refine the way the filtering act.
In fact the (temporarily) ignored score is the base of the method to be 
applied.
Obviously here mainly we are talking about email addresses, so my intention is 
like the mailfilter concept, which means the program may block an entire 
domain but some are allowed and all from .my are allowed but not those 
from .com.my (mostly annoying emails :P )

At the sum of the view I've considered a flexible programming as much as I'm 
thinking that may be published some time to benefit for multiplatform user as 
python is.
In such perspective I'm a bit curious to know if exist sites on the web where 
small program are welcomed and people like me can express all of their 
ignorance about the mode of using python. For such ignorance I may concour 
for the Nobel Price :)

Also the News Group doesn't contemplate the idea to split into beginners and 
high level programmers (HLP). Of course the HLP are welcome to discuss on 
such NG :).

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


Re: Tkinter--does anyone use it for sophisticated GUI development?

2006-10-20 Thread Alexander Burger
Paul Rubin http://[EMAIL PROTECTED] wrote:
 There's a language called Picolisp in which this is the standard way
 to do a gui.  Picolisp includes a java applet that can do some stuff
 that standard html widgets can't.  These days I suppose it should use
 AJAX.

Yes, in fact it does.

The currently active testing version

   http://www.software-lab.biz/1024/?downloadpicoLisp.tgz

also has a plain HTML GUI, enhanced by XMLHttpRequests, in a way that it
works transparently in browsers with or without JavaScript enabled. We
are using it in all our current projects.

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


Re: Lead Software Engineer

2006-10-20 Thread Nicola Musatti

James Stroud wrote:
 alex23 wrote:
  Emma wrote:
 
 5. Please provide us with a comparison of the following music discovery
 
 sites:
 
 http://www.blogmusik.net
 http://www.seeqpod.com/music
 http://www.finetune.com
 http://www.webjay.com
 
 For each of these we like to know:
 A) What you like and dislike about each of these.
 B) Which one you like the best.
 C) Which one you think others might like the best.
 D) How you would improve the one you like.
 
 
  There _are_ no jobs on offer here. This is just a cheap attempt at
  getting free survey data.
 
  - alex23
 

 They would get more data if they lowered their expectations for the
 programmer position.

They would get even more data if they specified where to reply...

Unless this is an incredibly lame attempt to increase those sites'
traffic.

Cheers,
Nicola Musatti

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


I like python.

2006-10-20 Thread Fidel
I'm not a coder.. I'm just a person that trys to do things with
languages he likes. Sometimes I'm successful, mostly not. I do know
that before I bother a list with a silly question I should do my best
to research for an answer myself. ala RTFM. That said my searches
haven't found me what I am looking.. lack of a decent keyword
sequence.. anywho..

Could someone please tell me what I need to put into a python script
to not have a window come up however briefly? Like when I double click
on the script, it will do it's job but won't open a command window
then close it.. I hope that explains what I'm looking for.  If I see
the line I can figure out by syntax where it should go. I'm really
good at learning the gist of languages by syntax.  Thank you all for
your time


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


Re: I like python.

2006-10-20 Thread Fredrik Lundh
Fidel wrote:

 Could someone please tell me what I need to put into a python script
 to not have a window come up however briefly?

assuming Windows, and assuming that you have a standard Python install for
Windows: use pyw instead of py as the script's extension.

(Windows applications come in two flavours: console applications and window
applications.  the default executable for py files is python.exe, which is 
a con-
sole application.  pyw uses pythonw.exe instead, which is exactly the same
program, but linked as a window application instead).

/F 



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


new multiplayer game (made with pygame) platform

2006-10-20 Thread maxime_phan
hello we would like to make you discover a new and free multiplayer
game platform: GameLAN.
All game are made with pygame, we have 3 multiplayer games now (Tetris
like game, Heroic fantaisy tactic game and gomoku game). We invite you
on the 22th of October at 4pm (Paris Time) to discover this platform.So
get ready to play and see you on sunday on our GameLAN games servers!
website: 
http://www.gamelan-project.com

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


Re: BeautifulSoup problem

2006-10-20 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], placid wrote:

 Hi all,
 
 Just wondering if anyone knows how to get the text between the tags of
 the following Tag object? 
 
 span class=nametextHello/span

Are you looking for a way to search for tag *and* attributes?  What about
this::

  In [12]: soup.find('span', {'class': 'nametext'}).contents
  Out[12]: [u'Hello']

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


Re: Can I use decorators to manipulate return type or create methods?

2006-10-20 Thread Diez B. Roggisch
WakeBdr schrieb:
 Diez,
 I get what that accomplishes now, but I'm having problems in my
 implementation.  I was able to write a standalone class that worked
 correctly.  However, in my code the class that I need to exhibit this
 functionality inherits from another class.  This seems to cause
 problems when I attempt to implement you solution.

You need to give a __metaclass__ to one of them, and I think they must 
be new-style-classes.


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


Unicode support in python

2006-10-20 Thread sonald
Hi,
I am using python2.4.1

I need to pass russian text into python and validate the same.
Can u plz guide me on how to make my existing code support the
russian  text.

Is there any module that can be used for unicode support in python?

Incase of decimal numbers, how to handle comma as a decimal point
within a number

Currently the existing code is woking fine for English text
Please help.

Thanks in advance.

regards
sonal

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


Re: Unicode support in python

2006-10-20 Thread Fredrik Lundh
sonald wrote:

 I need to pass russian text into python and validate the same.
 Can u plz guide me on how to make my existing code support the
 russian  text.

 Is there any module that can be used for unicode support in python?

Python has built-in Unicode support (which you would probably have noticed
if you'd looked Unicode up in the documentation index).  for a list of 
tutorials
and other documentation, see

http://www.google.com/search?q=python+unicode

/F 



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


Re: Unicode support in python

2006-10-20 Thread Fredrik Lundh
http://www.google.com/search?q=python+unicode

(and before anyone starts screaming about how they hate RTFM replies, look
at the search result)

/F 



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


Why the result

2006-10-20 Thread HYRY
Why the third print stement output 'comments': [(1, 2, 3)], I think
it should be [].
I am using
Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)]
on win32.

# program
class PicInfo:
def __init__(self, intro=, tags=, comments=[]):
self.picintro = intro
self.pictags = tags
self.comments = comments

def addcomment(self, comment):
self.comments.insert(0, comment)

dbdata = PicInfo()
print dbdata.__dict__
dbdata.addcomment((1,2,3))
print dbdata.__dict__
dbdata = PicInfo()
print dbdata.__dict__

# output
{'pictags': '', 'comments': [], 'picintro': ''}
{'pictags': '', 'comments': [(1, 2, 3)], 'picintro': ''}
{'pictags': '', 'comments': [(1, 2, 3)], 'picintro': ''} - why
comments is not []?

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


Re: help with my first use of a class

2006-10-20 Thread Bruno Desthuilliers
BartlebyScrivener wrote:
 I am a mere hobbyist. Spent several hours trying to make a class,
 because I think this is an occasion where I need one. But I can't make
 it work.
 
 This code works (only because of the global c, which I know I'm
 supposed to avoid, by using a Class). I edited the rest to leave out
 the irrelevant formatting and printing of the quotations.
 
 I've read about Classes several times, but I don't get them yet.

Think of a class as both a blueprint for objects and a factory
creating these objects. The class lets you define the attributes and
behaviors of it's instances.

 Obviously. If I can solve one real life problem like this, then maybe
 I'll see the light.
 
 If I understand the power of Classes correctly, I could make one that
 would allow me to make a new instance that would connect to, say, an
 SQLite3 db instead of the Access db, as well as to create more methods
 that will do different SQL searches.


 Thank you for any help,
 
 
 import mx.ODBC.Windows as odbc
 import sys
 import random
 
 def connect():
 global c
 db='DSN=Quotations'
 conn = odbc.DriverConnect(db)
 c = conn.cursor()
 
 def random_quote():
 
 Counts all of the quotes in MS Access database Quotations2005.mdb.
 Picks one quote at random and displays it using textwrap.
 
 c.execute (SELECT COUNT(Quote) FROM PythonQuoteQuery)
 # Yields the number of rows with something in the quote field
 total_quotes = c.fetchone()
 # Get a random number somewhere between 1 and the number of total
 quotes
 quote_number = (random.randint(1, total_quotes[0]),)
 # Select a quote where the ID matches that number
 c.execute (SELECT Author, Quote FROM PythonQuoteQuery WHERE ID=?,
 quote_number)
 quote = c.fetchone()
 blah blah blah
 
 def print_quote()
 code to format and print the quote (which will also have to be
 global, unless I learn Classes!)
 

Ever wondered what arguments and return values were for ?-)

 if __name__ == '__main__':
 if len(sys.argv) == 1:
 connect()
 random_quote()
 print_quote()
 

First, notice that you *don't* need a class here to avoid globals.
Learning to use function as *functions* (ie: taking arguments and
returning values) instead of procedure would help:

def random_quote(cursor):
  c.execute (SELECT COUNT(Quote) FROM PythonQuoteQuery)
  total_quotes = c.fetchone()
  quote_number = (random.randint(1, total_quotes[0]),)
  c.execute (
SELECT Author, Quote FROM PythonQuoteQuery WHERE ID=?,
 quote_number
  )
  return c.fetchone()

def format_quote(quote):
  # code here
  return formatted_quote

def main(*args):
  if len(args)  2:
print  sys.stderr, Missing dsn arg\nusage : %s dsn % args[0]
return 1
  dsn = args[1]
  try:
conn = odbc.DriverConnect(dsn)
  except SomeODBCErrorHere, e:
print  sys.stderr Cannot connect to %s : %s % (dsn, e)
return 1
  quote = random_quote(conn.cursor())
  print format_quote(quote)
  conn.close()
  return 0

if __name__ == '__main__':
  sys.exit(main(*sys.argv))


Now for an OO version - that won't buy you much IMHO:

class SQLFortune(object):
  def __init__(self, dsn):
self._dsn = dsn
self._cnx = None

  @apply
  def connection():
def fget(self):
  if self._cnx is None:
self._cnx = odbc.DriverConnect(self.dsn)
  return self._cnx
def fset(self, _):
  raise AttributeError(Attribute is read-only)
return property(**locals())

  def random_quote(self):
c = self.connection.cursor()
c.execute (SELECT COUNT(Quote) FROM PythonQuoteQuery)
total_quotes = c.fetchone()
quote_number = (random.randint(1, total_quotes[0]),)
c.execute (
  SELECT Author, Quote FROM PythonQuoteQuery WHERE ID=?,
   quote_number
)
return c.fetchone()

  def format_quote(self, quote):
# code here
return formatted_quote

  def close(self):
try: self._cnx.close()
except: pass

def main(*args):
  if len(args)  2:
print  sys.stderr, Missing dsn arg\nusage : %s dsn % args[0]
return 1
  dsn = args[1]
  fortune = SQLFortune(dsn)
  print fortune.format_quote(fortune.random_quote())
  fortune.close()
  return 0

if __name__ == '__main__':
  sys.exit(main(*sys.argv))


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


Re: help with my first use of a class

2006-10-20 Thread Bruno Desthuilliers
BartlebyScrivener wrote:
 Whoah. At least I got the connection. I think. Maybe I can figure more
 on my own. Any help appreciated.
 
 Thanks
 
 -
 
 class Connection:
 def __init__(self, aDatasource):
 self.db = aDatasource
 self.conn = odbc.DriverConnect(self.db)
 self.conn.cursor()

This creates a cursor, that's immediatly discarded.

 def random_quote():
 
 Counts all of the quotes in MS Access database Quotations2005.mdb.
 Picks one quote at random and displays it using textwrap.
 
 c = Connection('DSN=Quotations')
 c.execute (SELECT COUNT(Quote) FROM PythonQuoteQuery)

And this will raise an AttributeError, since your (mostly useless)
Connection class doesn't define an 'execute' method.

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


Re: Why the result

2006-10-20 Thread Fredrik Lundh
HYRY [EMAIL PROTECTED] wrote:

 Why the third print stement output 'comments': [(1, 2, 3)], I think
 it should be [].

default arguments are calculated once.  for details, see the tutorial

  http://docs.python.org/tut/node6.html#SECTION00671

and the FAQ:

  http://pyfaq.infogami.com/why-are-default-values-shared-between-objects

and the language reference:

  http://python.org/doc/ref/function.html
  http://pyref.infogami.com/def

/F 



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


Re: help with my first use of a class

2006-10-20 Thread Fredrik Lundh
Bruno Desthuilliers wrote:

 First, notice that you *don't* need a class here to avoid globals.
 Learning to use function as *functions* (ie: taking arguments and
 returning values) instead of procedure would help:

 def random_quote(cursor):
  c.execute (SELECT COUNT(Quote) FROM PythonQuoteQuery)

make that cursor.execute (etc)

/F 



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


Re: Why the result

2006-10-20 Thread Bruno Desthuilliers
HYRY wrote:
 Why the third print stement output 'comments': [(1, 2, 3)], I think
 it should be [].
 I am using
 Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)]
 on win32.
 
 # program
 class PicInfo:
 def __init__(self, intro=, tags=, comments=[]):

This is a FAQ - and one of the most (in)famous Python's gotchas. Default
arguments are eval'd *only once* - when the def statement is eval'd,
which is usually at import time. So using a mutable object as default
value makes this object behaving somehow like a C 'static' local
variable, ie it keeps it value from call to call.

The canonical idiom is to use None instead:

class PicInfo(object):
  def __init__(self, intro=, tags=, comments=None):
self.picintro = intro
self.pictags = tags
if comments is None:
  comments = []
self.comments = comments

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


Re: Flexible Collating (feedback please)

2006-10-20 Thread Leo Kislov
Ron Adam wrote:
 Leo Kislov wrote:
  Ron Adam wrote:
 
  locale.setlocale(locale.LC_ALL, '')  # use current locale settings
 
  It's not current locale settings, it's user's locale settings.
  Application can actually use something else and you will overwrite
  that. You can also affect (unexpectedly to the application)
  time.strftime() and C extensions. So you should move this call into the
  _test() function and put explanation into the documentation that
  application should call locale.setlocale

 I'll experiment with this a bit, I was under the impression that local.strxfrm
 needed the locale set for it to work correctly.

Actually locale.strxfrm and all other functions in locale module work
as designed: they work in C locale before the first call to
locale.setlocale. This is by design, call to locale.setlocale should be
done by an application, not by a 3rd party module like your collation
module.

 Maybe it would be better to have two (or more) versions?  A string, unicode, 
 and
 locale version or maybe add an option to __init__ to choose the behavior?

I don't think it should be two separate versions. Unicode support is
only a matter of code like this:

# in the constructor
self.encoding = locale.getpreferredencoding()

# class method
def strxfrm(self, s):
if type(s) is unicode:
return locale.strxfrm(s.encode(self.encoding,'replace')
return locale.strxfrm(s)

and then instead of locale.strxfrm call self.strxfrm. And similar code
for locale.atof

 This was the reason for using locale.strxfrm. It should let it work with 
 unicode
 strings from what I could figure out from the documents.

 Am I missing something?

strxfrm works only with byte strings encoded in the system encoding.

  -- Leo

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


Webprogr: Link with automatic submit

2006-10-20 Thread Gregor Horvath
Hi,

As I am no expert web programmer I thought I'd better ask the experts if
there is a simpler or better solution to my problem than the one I am
thinking of. (using TurboGears)

The problem
---

I have a form. Ok. you can submit, validate it etc.
Now I have a link on that form to another page.
What I want is that the form gets automatically submitted and validated
before the browser follows the link. If the validation has errors the
link should not be followed.

My solution
---

1. client side solution

First I thought I just make a little javascript function like this:

function xy(url) {
document.form.submit();
parent.location=url;
}

The problem is that submit works ansynchronisly. I do not get a return
code to decide if to follow the url or not. Furthermore the form does
not get submitted if there is the line parent.location=url; .

2. server side solution

I thought of including a hidden field and include directives for my
controller method to raise the redirection if no validation errors are
there.

a href=# onClick=xy('/somewhere')/a

function xy(url) {
document.form.hiddenfield.value = redirect_to:  + url;
document.form.submit();
}

@expose
def mycontroller(self, *args, **kwargs):
   #do the usual saving stuff

   if hasattr(kwargs, 'hiddenfield'):
  #parse the JSON or mini-langage and do the redirection, when no
  #validation errors


As there might be more other directives necessery for client-server
communciation I thought of setting the hiddenfield value to JSON or a
self made mini-language and parse this in the controller.

Is this a good solution?
Are there any other options?

--
Greg

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


Re: comparing Unicode and string

2006-10-20 Thread Leo Kislov

[EMAIL PROTECTED] wrote:
 Thanks, John and Neil, for your explanations.

 Still I find it rather difficult to explain to a Python beginner why
 this error occurs.

 Suggestion: shouldn't an error raise already when I try to assign s2? A
 normal string should never be allowed to contain characters that are
 not codable using the system encoding. This test could be made at
 compile time and would render Python more didadic.

This is impossible because of backward compatibility, your suggestion
will break a lot of existing programs. The change is planned to happen
in python 3.0 where it's ok to break backward compatibility if needed.

  -- Leo.

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


Re: comparing Unicode and string

2006-10-20 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

 Suggestion: shouldn't an error raise already when I try to assign s2?

variables are not typed in Python.  plain assignment will never raise an
exception.

/F 



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


Re: right curly quote and unicode

2006-10-20 Thread Leo Kislov
On 10/19/06, TiNo [EMAIL PROTECTED] wrote:
 Now I know where the problem lies. The character in the actual file path is
 u+00B4 (Acute accent) and in the Itunes library it is u+2019 (a right curly
 quote). Somehow Itunes manages to make these two the same...?

 As it is the only file that gave me trouble, I changed the accent in the
 file to an apostrophe and re-imported it in Itunes. But I would like to hear
 if there is a solution for this problem?

I remember once I imported a russian mp3 violating tagging standard by
encoding song name in windows-1251 encoding into itunes and itunes
converted the name without even asking me into standard compliant
utf-8. So there is some magic going on. In your case u+00B4 is a
compatibility character from unicode.org point of view and they
discourage usage of such characters. Perhaps itunes is eager to make
u+00B4 character history as soon as possible. Googling for itunes
replaces acute with quote reveals that char u+00B4 is not alone. Read
the first hit. I'm afraid you will have to reverse engeneer what
itunes is doing to some characters.

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


list2str and performance

2006-10-20 Thread spr
Hi,

I'm trying to learn Python and I'd appreciate any comments about my
small snippets of code. I read an old anecdote about performance here:

http://www.python.org/doc/essays/list2str/

First, I tried to figure out what would be the most pythonic approach by
today's standards:


def ListToStr(l):
Convert a list of integers into a string.

return .join([chr(n) for n in l])

def StrToList(s):
Convert a string into a list of integers.

return [ord(c) for c in s]


By the way, using a generator expression in this case seem a bit slower
than a list comprehension and I'm not sure why.

I tried to improve the performance with Psyco and it became about 6
times as fast just for free. Then, I quickly tried Pyrex but I didn't
feel comfortable with using a dialect. So I trying Boost.Python, and as
I optimized the code it became more and more C-ish. The result is this:


// Convert a list of integers into a string.
PyObject* ListToStr(const boost::python::list l)
{
PyObject* s;
Py_BEGIN_ALLOW_THREADS

const size_t length = PyList_GET_SIZE(l.ptr());

// Couldn't find a function for allocating a PyString from scratch.
s = (PyObject*)_PyObject_NewVar(PyString_Type, length);
((PyStringObject*)s)-ob_shash = -1;
((PyStringObject*)s)-ob_sstate = SSTATE_NOT_INTERNED;
((PyStringObject*)s)-ob_sval[((PyStringObject*)s)-ob_size] = '\0';

char* s_items = PyString_AS_STRING(s);
char* ps = s_items, *ps_end = ps + length;
PyIntObject** pl = (PyIntObject**)((PyListObject*)l.ptr())-ob_item;

while (ps  ps_end)
{
*ps++ = (char)(*pl++)-ob_ival;
}

Py_END_ALLOW_THREADS
return s;
}

// Convert a string into a list of integers.
PyObject* StrToList(const boost::python::str s)
{
PyObject* l;
Py_BEGIN_ALLOW_THREADS

const size_t length = PyString_GET_SIZE(s.ptr());
l = PyList_New(length);

PyObject** pl = ((PyListObject*)l)-ob_item, **pl_end = pl + length;
unsigned char* ps = (unsigned char*)PyString_AS_STRING(s.ptr());

while (pl  pl_end)
{
*pl++ = PyInt_FromLong(*ps++);
}

Py_END_ALLOW_THREADS
return l;
}

Is it safe here to use Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS?
On my machine this is about 50 times as fast as plain Python, but is
this as fast as it can get?

When performance matters and you have to develop a CPU-bound
application, do you think it is possible to eventually achieve nearly
the best performance by extending Python with C or C++ modules, or is it
better to take the embedding approach, that is, use a C or C++ core that
calls Python scripts?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list2str and performance

2006-10-20 Thread Fredrik Lundh
spr wrote:

 When performance matters and you have to develop a CPU-bound
 application, do you think it is possible to eventually achieve nearly
 the best performance by extending Python with C or C++ modules, or is it
 better to take the embedding approach, that is, use a C or C++ core that
 calls Python scripts?

the embedding approach only makes sense if you 1) have an existing application
that you want to extend with Python, or 2) are trying to sneak Python into an 
exist-
ing project (it's just a library, you know ;-).

for any other case, putting Python at the top is a lot more practical.

/F 



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


RE: Tkinter--does anyone use it for sophisticated GUI development?

2006-10-20 Thread Matthew Warren
 

 -Original Message-
 From: 
 [EMAIL PROTECTED] 
 [mailto:[EMAIL PROTECTED]
 rg] On Behalf Of Fredrik Lundh
 Sent: 20 October 2006 06:43
 To: python-list@python.org
 Subject: Re: Tkinter--does anyone use it for sophisticated 
 GUI development?
 
 Kevin Walzer wrote:
 
  Coming from Tcl/Tk, where there are a huge number of 
 extension packages
  to enhance the Tk widgets and which allow you to make 
 really polished
  GUI's, I'm struck mainly by how little of this stuff has 
 made it over
  into Tkinter/Python. For instance, I've developed several Tcl
  applications that use the core Tk widgets, the Tile theming 
 package, the
  Bwidget set (great tree widget and listbox, which allows 
 you to embed
  images), and tablelist (an extremely flexible muti-column listbox
  display). I've found Python wrappers for some of this 
 stuff, but almost
  no documentation on how to use them, and very little in the way of
  actual applications making use of them--which is itself a red flag.
 
 on the other hand, such wrappers are usually extremely 
 simple, and the 
 mapping between Python and Tk is trivial.  there's simply not much to 
 add to the existing Tk module docs.
 
  Am I better off biting the bullet and learning wxPython--a 
 different GUI
  paradigm to go with the new language I'm trying to learn?
 
 that's almost designed to get wx rul3z d00d replies from 
 the wx crowd. 
   let's see if they bite.
 

Weell,  I'm in no position to evangelise it, but alongised other things
for the past two or three weeks I've been looking into different gui
building tools for python, wxDesigner, BoaConstructor, pythonCard and a
couple of others using both tkInter and wxPython.

I've given up trying to find a good one who's method of operation was
quick to pick up, and I've since written the basics of my GUI by hand in
TkInter and now wxPython (was doing that last night as it goes).

..aand so far wxPython is winning easily on the hand-coded front,
especially once you find the demo package and use it. TkInter took me 3
or 4 days without help to work out and build what I needed. WxPython
took an evening and 1 usenet post. And I think it looks much nicer.
I've yet to see what happens with the event loop of either when I start
to use the threaded scheduler I need in the app but hey...


Matt.

(in wrong place to get to google groups again.. As always apologies for
appended text)
--


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

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

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

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


Re: BeautifulSoup problem

2006-10-20 Thread placid

Marc 'BlackJack' Rintsch wrote:
 In [EMAIL PROTECTED], placid wrote:

  Hi all,
 
  Just wondering if anyone knows how to get the text between the tags of
  the following Tag object?
 
  span class=nametextHello/span

 Are you looking for a way to search for tag *and* attributes?  What about
 this::

   In [12]: soup.find('span', {'class': 'nametext'}).contents
   Out[12]: [u'Hello']

No this wasnt what i was looking for because i didnt know you could do
this. Thanks for that, this is better.

Cheers

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


Re: Webprogr: Link with automatic submit

2006-10-20 Thread Bruno Desthuilliers
Gregor Horvath wrote:
 Hi,
 
 As I am no expert web programmer I thought I'd better ask the experts if
 there is a simpler or better solution to my problem than the one I am
 thinking of. (using TurboGears)
 
 The problem
 ---
 
 I have a form. Ok. you can submit, validate it etc.
 Now I have a link on that form to another page.
 What I want is that the form gets automatically submitted and validated
 before the browser follows the link. If the validation has errors the
 link should not be followed.
 
 My solution
 ---
(snip)
 Are there any other options?

OT
yes : replace the link with another submit button, then in your
controller check which submit has been successful and take appropriate
action.

Links are for GET request (which are supposed to be idempotent), and are
definitively *not* supposed to issue (even if indirectly) a POST request.
/OT

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


Re: help with my first use of a class

2006-10-20 Thread Bruno Desthuilliers
Fredrik Lundh wrote:
 Bruno Desthuilliers wrote:
 
 First, notice that you *don't* need a class here to avoid globals.
 Learning to use function as *functions* (ie: taking arguments and
 returning values) instead of procedure would help:

 def random_quote(cursor):
  c.execute (SELECT COUNT(Quote) FROM PythonQuoteQuery)
 
 make that cursor.execute (etc)

oops, sorry - not enough coffein, I guess.
Thanks for the correction.

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


RE: [Tutor] How to get the width of teh button widget..??

2006-10-20 Thread Matthew Warren







  
  
  
  Folks,
  
  Sorry for asking you such a trivial question.!!! But i want to size up 
  all the buttons with the same size as the largest one in the interface.. And 
  thats why I am asking this question..
  
  Regards,
  Asrarahmed
  
  
  Hi 
  Asrarahmed. I think, from your recent posts asking questions regarding 
  help with python on this list, you may benefit from reading this 
  document;
  
  http://catb.org/~esr/faqs/smart-questions.html
  
  You'll find you wontfeel a 
  needto apologise so much for your questions 
  too.
  
  As 
  to this question,people will really need to know which gui toolkit you 
  are using, and howyou have used it to build your buttons. So please post 
  more information regarding the problem, and code you have written and tried to 
  use so far.
  
  :)
  
  
  Matt.
  
  --


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


This message has been scanned for viruses by BlackSpider in Partnership with Digica


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

python under the hood

2006-10-20 Thread tpochep
Hello.

Is there any good information about python's internals and semantic? I
mean under the hood.
For example, I want to understant what do these strings

x = 10
y = 10
x = 20

mean (memory allocation for object? ctors? etc.)
Unfortynatly, I'm too lazy to read python's source code :) (and I
guess, it's not very easy :) )

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


Logging with Logger hierarchies

2006-10-20 Thread Robert
Hi all

I have been trying to set up a framework with logging implemented using
the built in Python logging module. For better or worse, I have decided
to base the logger names on the module names. This means that I am
using multiple layers of name, eg logging.getLogger(a.b.c). I am also
using logging.config to load a file configuration but have been
experiencing some unexpected behaviour.

If for instance I have something resembling the following code:

import logging
import logging.config
logging.config.fileConfig(logging.conf)
logger = logging.getLogger(a.b.c)
logger.debug(Debug message)

and the file logging.conf describes only the root logger configuration
and specifies level=DEBUG. I get an message saying no handler found for
logger a.b.c. What I would have expected was that my logger would
have inherited its handlers from root, ie through the parents a.b, up
to a and finally up to root.

I delved in the code and found that when my logger a.b.c is created,
it doesn't create Loggers for a.b or a but rather instances of a
PlaceHolder class. If I actually call logging.getLogger(a.b) and
logging.getLogger(a)  then the PlaceHolders get converted to Loggers
and the hierarchy suddenly works.

My feeling is that either the PlaceHolder objects should be modified to
make them work properly in the hierarchy, or probably more simply, they
should just be replaced by Loggers immediately when the hierarchy is
first created. In that case, I believe that my expected behaviour would
just work. Now I am beginning to wonder if I have missed something,
ie is there some reason why this is not a good idea and hasn't been
done? Otherwise, what do people generally think? Is it as simple as I
haven't set something up right, or do I have to declare the
intermediate loggers, or does having multiple layers just suck!!!

Useful comment welcome!
Robert

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


Re: python under the hood

2006-10-20 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

 Is there any good information about python's internals and semantic? I
 mean under the hood.
 For example, I want to understant what do these strings

 x = 10
 y = 10
 x = 20

 mean (memory allocation for object? ctors? etc.)

reading this might help:

http://effbot.org/zone/python-objects.htm

/F 



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


Re: invert or reverse a string... warning this is a rant

2006-10-20 Thread rick
Fredrik Lundh wrote:
 Brad [EMAIL PROTECTED] wrote:
 
 Do you have children? How would your child feel if he brought you
 something he had made and you then told him it was awful in *sooo* many
 ways.
 
 If you're arguing that everything a child does and says should be rewarded...


I'm not arguing that. Only that one should be polite and considerate 
when giving advice. That's all.

foo[::-1] is acceptable. So is the helper function that you posted:

 def reverse(s):
 return s[::-1]

My 2 min hack is awful to some, and I'm OK with that and fully expect 
it. But it works OK for me. Is there not room for solutions such as this 
in Python?

No hard feelings. Let's close this thread. I'll accept the slicing and 
memorize it.

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


Re: wxPython and PIL

2006-10-20 Thread Odalrick
Thanks for the answer.

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


Re: Unicode support in python

2006-10-20 Thread sonald

Fredrik Lundh wrote:
 http://www.google.com/search?q=python+unicode

 (and before anyone starts screaming about how they hate RTFM replies, look
 at the search result)

 /F
Thanks!! but i have already tried this...
and let me tell you what i am trying now...

I have added the following line in the script

# -*- coding: utf-8 -*-

I have also modified the site.py in ./Python24/Lib as
def setencoding():
Set the string encoding used by the Unicode implementation.  The
default is 'ascii', but if you're willing to experiment, you can
change this.
encoding = utf-8 # Default value set by _PyUnicode_Init()
if 0:
# Enable to support locale aware default string encodings.
import locale
loc = locale.getdefaultlocale()
if loc[1]:
encoding = loc[1]
if 0:
# Enable to switch off string to Unicode coercion and implicit
# Unicode to string conversion.
encoding = undefined
if encoding != ascii:
# On Non-Unicode builds this will raise an AttributeError...
sys.setdefaultencoding(encoding) # Needs Python Unicode build !

Now when I try to validate the data in the text file
say abc.txt (saved as with utf-8 encoding) containing either english or
russian text,

some junk character (box like) is added as the first character
what must be the reason for this?
and how do I handle it?

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


Re: Book about database application development?

2006-10-20 Thread Wolfgang Keller
 does anyone know of a good book that about development of database 
 applications?
 
 Scott Ambler's Agile Database Techniques

Thanks for the hint, the summaries indicate that this one could be very 
useful indeed.

Sincerely,

Wolfgang Keller

-- 
My email-address is correct.
Do NOT remove .nospam to reply.

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


list comprehension (searching for onliners)

2006-10-20 Thread Gerardo Herzig
Hi all: I have this list thing as a result of a db.query: (short version)
result = [{'service_id' : 1, 'value': 10},
{'service_id': 2, 'value': 5},
{'service_id': 1, 'value': 15},
{'service_id': 2, 'value': 15},
 ]

and so on...what i need to do is some list comprehension that returns me 
something like

result = [
{
'service_id' : 1, 'values': [ {'value': 10}, 
{'value': 15}]
 },
{
  'service_id' : 2, 'values': [ {'value': 5}, {'value': 15}]
}
   

My problem now is i cant avoid have repeteated entries, lets say, in 
this particular case, 2 entries for service_id = 1, and other 2 for 
service_id =2.
Ill keeping blew off my hair and drinking more cofee while searching for 
this damn onliner im looking for.

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


Re: python under the hood

2006-10-20 Thread A.T.Hofkamp
On 2006-10-20, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 Hello.

 Is there any good information about python's internals and semantic? I
 mean under the hood.

Not exactly 'under the hood', but very close is the Python/C API.
You can learn a great deal by reading the ExtendingEmbedding manual as well as
the Python/C API reference manual.

 Unfortynatly, I'm too lazy to read python's source code :) (and I
 guess, it's not very easy :) )

After the above, some parts should be familiar. The functions in the Python/C
API are also being used inside Python.

I also found the source code pretty understandable, although I read only a
small part of it.

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


RE: invert or reverse a string... warning this is a rant

2006-10-20 Thread Duncan Booth
Demel, Jeff [EMAIL PROTECTED] wrote:

 I've been programming professionally for over 10 years, and have never
 once needed to reverse a string.  Maybe it's a lack of imagination on my
 part, but I can't think of a single instance this might be necessary.

I did want to reverse some strings once, but it may have been nearly 10 
years ago now.

If I remember correctly the situation was that I wanted to store a lot of 
strings on a pda with limited memory and no gzip library. One way of 
doing simple compression would be to store them sorted with the first byte 
simply containing the number of characters in common with the previous 
string. It happened that the strings in question had common suffixes more 
than prefixes, so I stored them sorted by the reverse of the strings with a 
lead byte containing the number of common characters at the tail of the 
string.

Shortly afterwards I ported gzip to the target platform.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help with my first use of a class

2006-10-20 Thread BartlebyScrivener
Thanks, Bruno. Very educational.

rd

Bruno Desthuilliers wrote:

 Think of a class as both a blueprint for objects and a factory
 creating these objects. The class lets you define the attributes and
 behaviors of it's instances.

 First, notice that you *don't* need a class here to avoid globals.
 Learning to use function as *functions* (ie: taking arguments and
 returning values) instead of procedure would help:
 
 Now for an OO version - that won't buy you much IMHO:


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


Re: help with my first use of a class

2006-10-20 Thread BartlebyScrivener
Thank you all!

My main problem is going away from Python and programming for weeks or
months at a time, then picking up where I left off.  But Python is much
better in this regard than Perl.

I appreciate the help.

rd

-

Dennis Lee Bieber wrote:

 If using a db-api compliant adapter, and using minimal common
 features, the main thing one would have to worry about is the different
 placeholders used by the adapter.

   I'd be more likely to do something like

 import pick-a-db-adapter as db

 and then have a class query the db connection for what type of
 placeholder it uses, then modify any queries the class uses.

   You might make a class for each database /table/, and each
 instance of that class would be one record in the table. The class would
 have the methods for retrieval/update/delete/insert, when given the key
 value, perhaps.
 --
   WulfraedDennis Lee Bieber   KD6MOG
   [EMAIL PROTECTED]   [EMAIL PROTECTED]
   HTTP://wlfraed.home.netcom.com/
   (Bestiaria Support Staff:   [EMAIL PROTECTED])
   HTTP://www.bestiaria.com/

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


Re: list comprehension (searching for onliners)

2006-10-20 Thread Max Erickson
Gerardo Herzig [EMAIL PROTECTED] wrote:

 Hi all: I have this list thing as a result of a db.query: (short
 version) result = [{'service_id' : 1, 'value': 10},
 {'service_id': 2, 'value': 5},
 {'service_id': 1, 'value': 15},
 {'service_id': 2, 'value': 15},
  ]
 
 and so on...what i need to do is some list comprehension that
 returns me something like
 
 result = [
 {
 'service_id' : 1, 'values': [ {'value': 10}, 
 {'value': 15}]
  },
 {
   'service_id' : 2, 'values': [ {'value': 5},
   {'value': 15}] 
 }

 
 My problem now is i cant avoid have repeteated entries, lets
 say, in this particular case, 2 entries for service_id = 1, and
 other 2 for service_id =2.
 Ill keeping blew off my hair and drinking more cofee while
 searching for this damn onliner im looking for.
 
 Thanks dudes.
 Gerardo

Is three lines ok?

 output=dict()
 for record in result:
output.setdefault(record['service_id'], list()).append(record
['value'])


 output
{1: [10, 15], 2: [5, 15]}
 

Creating the more verbose output that you specified should be 
pretty straighforward from there.

max

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


Re: Integration of globalization data in Python web frameworks

2006-10-20 Thread GinTon
The project web is activated
http://webda.python-hosting.com/

GinTon wrote:
 I have created several tables in CSV format with globalization data
 (G11n). There are tables for countries, areas, languages, countries 
 languages, time zones, phones. And they are licensed under a Creative
 Commons license.

 http://svn.webda.python-hosting.com/trunk/G11n_data/

 I created a new discussion group in order to facilitate the integration
 of G11n data in any framework. It's focused on integrate it on Django
 and TurboGears, but it could be integrated in whatever application with
 the help of the discussions on this group.

 It's necessary to discuss several subjects before beginning with the
 integration in the web frameworks. So I ask your collaboration. Thanks!

 http://groups.google.com/group/webda

 P.S.: I hope that you don't see this post as SPAM. This is something
 very interesting for administrators and users of those web frameworks.

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


Re: list comprehension (searching for onliners)

2006-10-20 Thread Tim Chase
 result = [{'service_id' : 1, 'value': 10},
 {'service_id': 2, 'value': 5},
 {'service_id': 1, 'value': 15},
 {'service_id': 2, 'value': 15},
  ]
 
 and so on...what i need to do is some list comprehension that returns me 
 something like
 
 result = [
 {
 'service_id' : 1, 'values': [ {'value': 10}, 
 {'value': 15}]
  },
 {
   'service_id' : 2, 'values': [ {'value': 5}, {'value': 15}]
 }

 
 My problem now is i cant avoid have repeteated entries, lets say, in 
 this particular case, 2 entries for service_id = 1, and other 2 for 
 service_id =2.

Okay...while I'm not sure the opacity of a one-liner is actually 
productive, it *can* be done.  Whether it should, I leave that to 
your discernment. :)

  [{'service_id': i, 'values':[{'value':d2['value']} for d2 in 
result if d2['service_id'] == i ]} for i in set(d['service_id'] 
for d in result)]

[{'service_id': 1, 'values': [{'value': 10}, {'value': 15}]}, 
{'service_id': 2, 'values': [{'value': 5}, {'value': 15}]}]


There's no claiming it's efficient, as it looks like there may be 
some O(N^2) logic going on under the hood (or possibly O(N*M) 
where N is the size of the result-set and M is the count of 
unique service_id values), as it's iterating over the result-set 
in two dimensions...once to create the set of top-level indices, 
and once for each result.

If you didn't have to have all those dictionaries around, it 
might come out more cleanly to just have some result-set that 
came out to be

{1: [10,15], 2: [5,15]}

Just a few thoughts...

-tkc



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


Re: Unicode support in python

2006-10-20 Thread Diez B. Roggisch
sonald schrieb:
 Fredrik Lundh wrote:
http://www.google.com/search?q=python+unicode
 (and before anyone starts screaming about how they hate RTFM replies, look
 at the search result)

 /F
 Thanks!! but i have already tried this...

Tried - might be. But you certainly didn't understand it. So I suggest 
that you read it again.

 and let me tell you what i am trying now...
 
 I have added the following line in the script
 
 # -*- coding: utf-8 -*-

This will _only_ affect unicode literals inside the script itself - 
nothing else! No files read, no files written, and additionally the path 
of sun, earth and moon are unaffected as well - just in case you wondered.

This is an example of what is affected now:



# -*- coding: utf-8 -*-
# this string is a byte string. it is created as such,
# regardless of the above encoding. instead, only
# what is in the bytes of the file itself is taken into account
some_string = büchsenböller

# this is a unicode literal (note the leading u).
# it will be _decoded_ using the above
# mentioned encoding. So make sure, your file is written in the
# proper encoding
some_unicode_object = ubüchsenböller
-




 I have also modified the site.py in ./Python24/Lib as
 def setencoding():
 Set the string encoding used by the Unicode implementation.  The
 default is 'ascii', but if you're willing to experiment, you can
 change this.
 encoding = utf-8 # Default value set by _PyUnicode_Init()
 if 0:
 # Enable to support locale aware default string encodings.
 import locale
 loc = locale.getdefaultlocale()
 if loc[1]:
 encoding = loc[1]
 if 0:
 # Enable to switch off string to Unicode coercion and implicit
 # Unicode to string conversion.
 encoding = undefined
 if encoding != ascii:
 # On Non-Unicode builds this will raise an AttributeError...
 sys.setdefaultencoding(encoding) # Needs Python Unicode build !
 
 Now when I try to validate the data in the text file
 say abc.txt (saved as with utf-8 encoding) containing either english or
 russian text,
 
 some junk character (box like) is added as the first character
 what must be the reason for this?
 and how do I handle it?

You shouldn't tamper with the site-wide encoding, as this will mask 
errors you made in the best case, let alone not producing new ones.

And what do you think it would help you anyway? Pythons unicode support 
would be stupid to say the least if it required the installation changed 
before dealing with files of different encodings - don't you think?

As you don't show us the code you actually use to read that file, I'm 
down to guessing here, but if you just open it as binary file with

content = open(test.txt).read()

there won't be any magic decoding happening.

What you need to do instead is this (if you happen to know that test.txt 
is encoded in utf-8):

content = open(test.txt).read().decode(utf-8)


Then you have a unicode object. Now if you need that to be written to a 
terminal (or wherever your boxes appear - guessing here too, no code, 
you remember?), you need to make sure that

  - you know the terminals encoding

  - you properly endcode the unicode content to that encoding before 
printing, as otherwise the default-encoding will be used


So, in case your terminal uses utf-8, you do

print content.encode(utf-8)


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


Re: Unicode support in python

2006-10-20 Thread Fredrik Lundh
sonald wrote:

 I have added the following line in the script

 # -*- coding: utf-8 -*-

that's good.

 I have also modified the site.py

that's bad, because this means that your code won't work on standard
Python installations.

 Now when I try to validate the data in the text file
 say abc.txt (saved as with utf-8 encoding) containing either english or
 russian text,

what does the word validate mean here?

 some junk character (box like) is added as the first character
 what must be the reason for this?

what did you do to determine that there's a box-like character at the start
of the file?

can you post some code?

/F 



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


Re: advice for web-based image annotation

2006-10-20 Thread Brian Blais
Paul Rubin wrote:
 Brian Blais [EMAIL PROTECTED] writes:
 I want to set up a system where I can have my family members write
 comments about a number of pictures, as part of a family tree project.
 ...Any suggestions would be greatly appreciated!
 
 How about a wiki?

So I thought about a wiki (again having no experience there either...sigh).  
You can
put images in a wiki?  I had a quick look at pytw, but haven't had the time to 
really
dive into it to see if I could get it going, and if it would work for me.


bb


-- 
-

  [EMAIL PROTECTED]
  http://web.bryant.edu/~bblais

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


Re: list comprehension (searching for onliners)

2006-10-20 Thread Jon Clements

Gerardo Herzig wrote:

 Hi all: I have this list thing as a result of a db.query: (short version)
 result = [{'service_id' : 1, 'value': 10},
 {'service_id': 2, 'value': 5},
 {'service_id': 1, 'value': 15},
 {'service_id': 2, 'value': 15},
  ]

 and so on...what i need to do is some list comprehension that returns me
 something like

 result = [
 {
 'service_id' : 1, 'values': [ {'value': 10},
 {'value': 15}]
  },
 {
   'service_id' : 2, 'values': [ {'value': 5}, {'value': 15}]
 }


 My problem now is i cant avoid have repeteated entries, lets say, in
 this particular case, 2 entries for service_id = 1, and other 2 for
 service_id =2.
 Ill keeping blew off my hair and drinking more cofee while searching for
 this damn onliner im looking for.

If you import itertools and have your DB query return in order of
service_id (or sort the list after retrieving result), then...


[ [dict(service_id=key),[dict(value=n['value']) for n in value]] for
key,value in itertools.groupby(result,lambda x: x['service_id']) ]

... is more or less what you want.

Jon.

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


Re: Tkinter--does anyone use it for sophisticated GUI development?

2006-10-20 Thread Kevin Walzer
James Stroud wrote:

 Also, look at my modest program at passerby.sf.net.
 Not so sophisticated, but not completely simple either.
 

I did look at passerby--a nice app, and in a native Mac OS X version
also! (I'm a Mac developer.) Thanks for the pointer.

-- 
Kevin Walzer
Poetic Code
http://www.kevin-walzer.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: advice for web-based image annotation

2006-10-20 Thread Paul Rubin
Brian Blais [EMAIL PROTECTED] writes:
  How about a wiki?
 
 So I thought about a wiki (again having no experience there
 either...sigh).  You can put images in a wiki?  I had a quick look
 at pytw, but haven't had the time to really dive into it to see if I
 could get it going, and if it would work for me.

Yes, generally speaking you can put images in a wiki (look at wikipedia,
it's got tons of images) but I don't know anything about pytw.  The
best-known wiki written in Python is probably MoinMoin.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python module for finite element program

2006-10-20 Thread Larry Bates
[EMAIL PROTECTED] wrote:
 Hello,
 
 Is there any add on python modules suitable for finite element 3D mesh
 such as to create (beam, plate, etc) ?
 
 Best Regards,
 ajikoe
 

Google is your friend:

http://www.python.org/pycon/papers/pysparse.html
http://sourceforge.net/projects/feval/
http://www.code-aster.org/ (French site)
http://www.icivilengineer.com/Open_Source/
http://adsabs.harvard.edu/abs/2000APS..DPPHP1088P

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


Re: Tkinter--does anyone use it for sophisticated GUI development?

2006-10-20 Thread Kevin Walzer
Fredrik Lundh wrote:

 
 on the other hand, such wrappers are usually extremely simple, and the
 mapping between Python and Tk is trivial.  there's simply not much to
 add to the existing Tk module docs.

I think I might simply have to bite the bullet, actually use some of
these documented wrappers, perhaps even tweak/improve them, and then
release something that shows what's possible with them. And perhaps even
write up some user-friendly docs.  :-)

 
 Am I better off biting the bullet and learning wxPython--a different GUI
 paradigm to go with the new language I'm trying to learn?
 
 that's almost designed to get wx rul3z d00d replies from the wx crowd.
  let's see if they bite.

That certainly wasn't my intention.
 
 What do other Tkinter developers think?
 
 Those people who have nothing better to do than post on the Internet
 all day long are rarely the ones who have the most insights
 
 if you want to reach Tkinter developers, the following forum might be
 more appropriate:
 
 http://mail.python.org/mailman/listinfo/tkinter-discuss
 
 that list is more focussed on solving specific problems, though; Tkinter
 developers just don't seem very interested in arguments about world
 domination.  guess we've inherited that from the Tcl world, or maybe
 we're just too busy doing stuff ;-)
 

I subscribe to that list. I agree that this particular question is
off-topic for that list.

By way of clarification, one of the things I have in mind in terms of
sophisticated GUI's can be found on these pages at the Tcl'ers wiki:

http://wiki.tcl.tk/13636

This page is focused on Tcl/Tk apps using the Tile extension, but many
of these apps also use extensions like Tablelist and Tktreectrl. I
haven't seen any shiny screenshots of Python apps using these extensions
yet.

Another example, that doesn't use Tile, is PgAccess:

http://www.pgaccess.org/index.php?page=NewPgAccessEnglish

This app makes use of BWidgets and Tablelist, in particular, to good
effect.

This gives you some idea of the target I'm aiming at, anyway.

-- 
Kevin Walzer
Poetic Code
http://www.kevin-walzer.com/software/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I use decorators to manipulate return type or create methods?

2006-10-20 Thread WakeBdr
OK, I think I'm close now.  I just can't get past this one error.  Here
is my code, followed by the output produced when I run it.

class Magic(type):
def __new__(cls, name, bases, d):
for name, function in d.items():
try:
function._marked
print 'Class: %s' % cls
print 'Method: %s' % name
def toXML(self, *args, **kwargs):
return
self._toXML(function(self, *args, **kwargs))
def toList(self, *args, **kwargs):
return
self._toList(function(self, *args, **kwargs))
d[name+'XML'] = toXML
d[name+'List'] = toList
except AttributeError:
#traceback.print_exc()
pass
return type(name, bases, d)

def mark(f):
f._marked = True
return f

class test(object):

def _toXML(self, value):
return 'xml%s/xml' % value
def _toList(self, value):
return 'list%s/list' % value

class testtest(test):

__metaclass__ = Magic

@mark
def printData(self, data):
return 'child-%s' % data


t = testtest()
print t.printData('data')
print t.printDataXML('data')
print t.printDataList('data')

===OUTPUT=
Class: class '__main__.Magic'
Method: printData
child-data
Traceback (most recent call last):
  File test.py, line 43, in ?
print t.printDataXML('data')
  File test.py, line 11, in toXML
return self._toXML(function(self, *args, **kwargs))
TypeError: __new__() takes exactly 4 arguments (3 given)



Diez B. Roggisch wrote:
 WakeBdr schrieb:
  Diez,
  I get what that accomplishes now, but I'm having problems in my
  implementation.  I was able to write a standalone class that worked
  correctly.  However, in my code the class that I need to exhibit this
  functionality inherits from another class.  This seems to cause
  problems when I attempt to implement you solution.

 You need to give a __metaclass__ to one of them, and I think they must
 be new-style-classes.
 
 
 Diez

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


FTP over SSL

2006-10-20 Thread Tor Erik Soenvisen
Hi,

Anyone know about existing code supporting FTP over SSL?
I guess pycurl http://pycurl.sourceforge.net/ could be used, but that
requires knowledge of libcurl, which I haven't.

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


Re: Logging with Logger hierarchies

2006-10-20 Thread Vinay Sajip
 I delved in the code and found that when my logger a.b.c is created,
 it doesn't create Loggers for a.b or a but rather instances of a
 PlaceHolder class. If I actually call logging.getLogger(a.b) and
 logging.getLogger(a)  then the PlaceHolders get converted to Loggers
 and the hierarchy suddenly works.

 My feeling is that either the PlaceHolder objects should be modified to
 make them work properly in the hierarchy, or probably more simply, they
 should just be replaced by Loggers immediately when the hierarchy is
 first created. In that case, I believe that my expected behaviour would
 just work. Now I am beginning to wonder if I have missed something,
 ie is there some reason why this is not a good idea and hasn't been
 done? Otherwise, what do people generally think? Is it as simple as I
 haven't set something up right, or do I have to declare the
 intermediate loggers, or does having multiple layers just suck!!!

There is nothing wrong with the way you are naming your loggers - and
there is nothing wrong with the way PlaceHolders work, either. They do
just work, AFAIK. If there were something wrong with your config
file, no handler might get configured on the root logger, which would
lead to the observed behaviour when you log to a.b.c.

With the simple script

import logging

logging.basicConfig(level=logging.DEBUG,
format=%(name)s: %(levelname)-5s: %(message)s)
logging.getLogger(a.b.c).debug(Hello, world!)

I get the output

a.b.c: DEBUG: Hello, world!

which is as expected.

Regards,

Vinay Sajip

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


Re: invert or reverse a string... warning this is a rant

2006-10-20 Thread Tim N. van der Leeuw

I V wrote:
 On Fri, 20 Oct 2006 09:04:07 +1000, Steven D'Aprano wrote:
  I agree -- the reversed() function appears to be an obvious case of purity
  overriding practicality :(
 
  str(reversed(some string))
  'reversed object at 0xb7edca4c'
  repr(reversed(some string))
  'reversed object at 0xb7edca4c'

 This doesn't seem particularly pure to me, either. I would
 have thought str(some_iter) should build a string out of the iterator, as
 list(some_iter) or dict(some_iter) do. I guess this might have to wait for
 Python 3, but str ought to be a proper string constructor, not a produce
 a printable representation of function, particularly when we have repr to
 do the latter.

The failing of str(reversed('the string')) caught me off-guard too. I
think you're quite right that it would be good if str() becomes a
proper constructor.

In practice, the short-term fix would be to add a __str__ method to the
'reversed' object, and perhaps to all iterators too (so that trying to
build a string from an iterator would do the obvious thing).

Cheers,

--Tim

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


Re: Can I use decorators to manipulate return type or create methods?

2006-10-20 Thread Diez B. Roggisch

WakeBdr schrieb:

OK, I think I'm close now.  I just can't get past this one error.  Here
is my code, followed by the output produced when I run it.


Stupid mistake of me - I didn't properly create a closure for the 
functions to set. See the corrected version in the attachment.


Diez


test2.py
Description: application/python
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: invert or reverse a string... warning this is a rant

2006-10-20 Thread Fredrik Lundh
Tim N. van der Leeuw wrote:

 In practice, the short-term fix would be to add a __str__ method to the
 'reversed' object

so what should

str(reversed(range(10)))

do ?

 and perhaps to all iterators too (so that trying to build a string from an
 iterator would do the obvious thing).

all iterators?  who's going to do that?

/F 



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


User Access to the docstring of a property

2006-10-20 Thread Colin J. Williams
Is there some way that the user can access the docstring specified for a 
property?

Please see the example below:

# propDocTest
class A(object):
   def __init__(self, value):
 self.value= value
   def vGet(self):
 return self.value
   V= property (fget= vGet, doc=Get Value.)

a= A(22)
print a.vGet()
print a.V
print a.V.__doc__ # this gives the docstring for the value returned
help(a.V) # this gives the docstring for the class/type of 
the value returned

Colin W.

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


Re: [OT] a little about regex

2006-10-20 Thread Fulvio
On Friday 20 October 2006 02:40, Ron Adam wrote:
 I see, is this a cleanup script to remove the least wanted items?

Yes. Probably will remain in this mode for a while.
I'm not prepaired to bring out a new algorithm

 Or is it a bit of both?  Why the score?

As exposed on another post. There should be a way to define a deny/allow with 
some particular exception.( I.e deny all .com but not 
[EMAIL PROTECTED])

 I would think the allow(keep?) filters would always have priority over deny
 filters.

It's a term which discerning capacity are involved. The previous post got this 
point up. I think to allow all .uk (let us say) but not info.uk (all 
reference are purely meant as example). Therefore if applying regex denial 
on .info.uk surely that doesn't match only .uk.


 I think keeping the allow filter seperate from the deny filter is good.
Agreed with you. Simply I was supposing the regex can do negative matching.

 You might be able to merge the header lines and run the filters across the
 whole header at once instead of each line.

I got into this idea, which is good, I still need a bit of thinking to code 
it. It need to remember what will be the right separator between fields, 
otherwise may cause problems with different charset.

  Actually I've problem on issuing the command to imap server to flag
  Deleted the message which count as spam. I only know the message

 I can't help you here.  Sorry.

Found it :), by tryfail.

  BTW whose Fred?
    
 news://news.cox.net:119/[EMAIL PROTECTED]

I can't link foreigner NG than my isp giving me. I'm curious and I'll give it  
a try.

F

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


Re: I would like write some data recovery software

2006-10-20 Thread Fulvio
***
Your mail has been scanned by InterScan MSS.
***


On Friday 20 October 2006 07:29, gel wrote:
  Once you get a way to access the bytes to recover... the Hachoir library
  can be interresting as a model to map structures on these data.
 
    http://hachoir.org/

 Cheers, I am having a bit of look at it now

Bacula, may be interesting too. (if my infos are correct).

F


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


Re: help with my first use of a class

2006-10-20 Thread Fulvio
***
Your mail has been scanned by InterScan MSS.
***


On Friday 20 October 2006 14:34, James Stroud wrote:
 You really don't need classes for this

I'm in that matter too. Doesn't classes make the main program neater?
Fundamentally OOP is the way to assemble ready objects to get a thing 
working, rather than worry about any single code line.
Is this a concept of python?

F


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


Use I the classes?

2006-10-20 Thread Fulvio
***
Your mail has been scanned by InterScan MSS.
***


Hello,

I'm used to put up programs (small right now), but I could find the only way 
to define some functions.
I'm interested to split some function into class, but I don't have know-how 
for these beasts.
Looking for documents (free download) which clearly explain the way of 
programming python classes and lots of examples as a bonus.

Thanks

F


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


Re: User Access to the docstring of a property

2006-10-20 Thread Diez B. Roggisch
Colin J. Williams schrieb:
 Is there some way that the user can access the docstring specified for a 
 property?

You need to access it using the class, not an instance of it.

class Foo(object):

 @apply
 def prop():
 def fget(self):
 return 10
 def fset(self, value):
 pass
 doc = this is a docstring
 return property(**locals())

f = Foo()
print f.prop


print Foo.prop.__doc__

print f.__class__.prop.__doc__


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


Re: Tkinter--does anyone use it for sophisticated GUI development?

2006-10-20 Thread Christophe
Kevin Walzer a écrit :
 Am I better off biting the bullet and learning wxPython--a different GUI
 paradigm to go with the new language I'm trying to learn? I had hoped to
 reduce my learning curve, but I'm very concerned that I simply can't do
 what I want to do with Tkinter. What do other Tkinter developers think?

Nobody mentionned it, but I think you should try PyQT and PyGTK before 
wxPython. Myself, I do not like wx : it looks too much like the MFC.

PyGTK is good, but GTK doesn't work that well on windows. PyQT is very 
good but you need Qt4 to get a free version for Windows. And it is GPL 
so it might not be what you are looking for. Or you can pay for it and 
get the non GPL version.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Logging with Logger hierarchies

2006-10-20 Thread Robert
Hi again

I have seen my error! I was mistakenly occasionally creating the logger
using

logger = logging.Logger(a.b.c)

instead of

logger = logging.getLogger(a.b.c)

Doh. I miss my private constructors to save me from such embarrasment
;^)

Cheers
Robert

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


FOR statement

2006-10-20 Thread Lad
If I have a list

Mylist=[1,2,3,4,5]
I can print it

for i in Mylist:
   print i

and results is
1
2
3
4
5


But how can I  print it in a reverse order so that I get
5
4
3
2
1



?


Thanks.
L

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


Re: Use I the classes?

2006-10-20 Thread BartlebyScrivener
Fulvio wrote:

 Looking for documents (free download) which clearly explain the way of
 programming python classes and lots of examples as a bonus.

http://www.freenetpages.co.uk/hp/alan.gauld/

On the frames page, go down to Advanced Topics and Object Oriented
Programming

And from the other thread we were on:

 Think of a class as both a blueprint for objects and a factory
 creating these objects. The class lets you define the attributes and
 behaviors of it's instances. 

http://tinyurl.com/yd97t5

rd

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


Re: FOR statement

2006-10-20 Thread Christophe
Lad a écrit :
 If I have a list
 
 Mylist=[1,2,3,4,5]
 I can print it
 
 for i in Mylist:
print i
 
 and results is
 1
 2
 3
 4
 5
 
 
 But how can I  print it in a reverse order so that I get
 5
 4
 3
 2
 1
 
 
 
 ?
 
 
 Thanks.
 L
 

for i in reversed(Mylist):
 print i
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list comprehension (searching for onliners)

2006-10-20 Thread Gerardo Herzig
You are the man, you are the man!! Yes, i need those dicts in order to 
assign them to a nested TMPL_LOOP for the htmltmpl templating engine. 
Thats why i cant use the solution provided by Max, and thanks to Jon too!!
Thanks a lot dudes, i hope someday ill turn myself into some of you guys 
who can actually answer questions ;)

Gerardo

 result = [{'service_id' : 1, 'value': 10},
 {'service_id': 2, 'value': 5},
 {'service_id': 1, 'value': 15},
 {'service_id': 2, 'value': 15},
  ]

 and so on...what i need to do is some list comprehension that returns 
 me something like

 result = [
 {
 'service_id' : 1, 'values': [ {'value': 10}, 
 {'value': 15}]
  },
 {
   'service_id' : 2, 'values': [ {'value': 5}, {'value': 15}]
 }
   
 My problem now is i cant avoid have repeteated entries, lets say, 
 in this particular case, 2 entries for service_id = 1, and other 2 
 for service_id =2.


 Okay...while I'm not sure the opacity of a one-liner is actually 
 productive, it *can* be done.  Whether it should, I leave that to your 
 discernment. :)

  [{'service_id': i, 'values':[{'value':d2['value']} for d2 in 
 result if d2['service_id'] == i ]} for i in set(d['service_id'] for d 
 in result)]

 [{'service_id': 1, 'values': [{'value': 10}, {'value': 15}]}, 
 {'service_id': 2, 'values': [{'value': 5}, {'value': 15}]}]


 There's no claiming it's efficient, as it looks like there may be some 
 O(N^2) logic going on under the hood (or possibly O(N*M) where N is 
 the size of the result-set and M is the count of unique service_id 
 values), as it's iterating over the result-set in two 
 dimensions...once to create the set of top-level indices, and once for 
 each result.

 If you didn't have to have all those dictionaries around, it might 
 come out more cleanly to just have some result-set that came out to be

 {1: [10,15], 2: [5,15]}

 Just a few thoughts...

 -tkc





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


Re: list comprehension (searching for onliners)

2006-10-20 Thread Paul Rubin
Gerardo Herzig [EMAIL PROTECTED] writes:
 You are the man, you are the man!! Yes, i need those dicts in order to
 assign them to a nested TMPL_LOOP for the htmltmpl templating
 engine. Thats why i cant use the solution provided by Max, and thanks
 to Jon too!!

I'm confused, can't you write a multi-line function and pass that?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: FOR statement

2006-10-20 Thread [EMAIL PROTECTED]

Lad wrote:
 If I have a list

 Mylist=[1,2,3,4,5]
 I can print it

 for i in Mylist:
print i

 and results is
 1
 2
 3
 4
 5


 But how can I  print it in a reverse order so that I get
 5
 4
 3
 2
 1



 ?


 Thanks.
 L

reverse the list in place with reverse method

l.reverse()
for i in l:
print i

and the reverse it back if needed

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


Re: list comprehension (searching for onliners)

2006-10-20 Thread Fredrik Lundh
Gerardo Herzig wrote:

 Thanks a lot dudes, i hope someday ill turn myself into some of you guys
 who can actually answer questions ;)

if you want to become a good Python programmer, you really need to get
over that I need a oneliner idea.

/F 



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


Re: list comprehension (searching for onliners)

2006-10-20 Thread Roberto Bonvallet
Gerardo Herzig wrote:
[...]
 and so on...what i need to do is some list comprehension that returns me 
 something like
[...]

You don't _need_ a list comprehension, you just _want_ one :)

[...]
 Ill keeping blew off my hair and drinking more cofee while searching for 
 this damn onliner im looking for.

I know, trying to put complex logic in one line makes you do all that.

Go for the multiliner!
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >