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?
>
> 
>
> 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?
>
> 

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"))
> ''
 repr(reversed("some string"))
> ''

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
gif&p=TAMA&fy=1900&ty=2005&m=21&r_type=TR&r_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.

 



-- 
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? 

Hello

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...)

 



-- 
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).

 



-- 
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'.*(?|$)')  # negative lookbehind
>     if allow.search(adr):
>         return True
>     return False

I'd point out that :
 allow = re.search(r'.*(?|$)',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  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/?download&picoLisp.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).

 



-- 
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? 
> 
> Hello

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

 



-- 
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)

 



-- 
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 , 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

 



-- 
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)

 



-- 
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.



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.

 



-- 
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.

 



-- 
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?
> >
> > Hello
>
> 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?


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.


-- 
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 wont feel a 
  need to apologise so much for your questions 
  too.
   
  As 
  to this question, people will really need to know which gui toolkit you 
  are using, and how you 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

 



-- 
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)
>
> 
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 Extending&Embedding 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  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)
>>
>> 
> 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 = u"bü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?

 



-- 
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 '%s' % value
def _toList(self, value):
return '%s' % 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: 
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"))
> > ''
>  repr(reversed("some string"))
> > ''
>
> 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?

 



-- 
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 try&fail.

> > 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  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  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.

 



-- 
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


Re: proper format for this database table

2006-10-20 Thread John Salerno
[EMAIL PROTECTED] wrote:

> you should rethink it as
> 
> [id] [university] [yearStart] [yearEnd] [degreeEarned]
> 1 U of I   19711975  BS
> 1 U of I   19751976  MS
> 1 U of I   19761977  PhD
> 

Thanks guys. I do plan to have an id entry for each person as well, I 
just forgot to mention that. But since it's a primary key, I didn't know 
I could list it more than once. Or does primary key not necessarily mean 
unique?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: proper format for this database table

2006-10-20 Thread John Salerno
Bruno Desthuilliers wrote:
> John Salerno a écrit :
>> Hi guys. I was wondering if someone could suggest some possible 
>> structures for an "Education" table in a database. 
> 
> Wrong newsgroup, then. comp.database.* is right next door...
> 

I know, I'm sorry. It's just that this newsgroup server doesn't have any 
database ngs on it. :(
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python module for finite element program

2006-10-20 Thread google
This isn't a python module, but python is embedded in the environment

http://salome-platform.org/

Also check out

http://www.caelinux.com/CMS/

for a live distro that contains several FE applications.

Andy

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


Re: python under the hood

2006-10-20 Thread John Salerno
[EMAIL PROTECTED] wrote:
> 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 :) )
> 

I found both Learning Python and Python in a Nutshell (both O'Reilly) to 
be really good at covering some of the details of what's happening in 
the language. Assuming you want to read whole books about it! :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode support in python

2006-10-20 Thread John Roth

sonald wrote:
> 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

As both of the other responders have said, the
coding comment at the front only affects source
text; it has absolutely no effect at run time. In
particular, it's not even necessary to use it to
handle non-English languages as long as you
don't want to write literals in those languages.

What seems to be missing is the notion that
external files are _always_ byte files, and have to
be _explicitly_ decoded into unicode strings,
and then encoded back to whatever the external
encoding needs to be, each and every time you
read or write a file, or copy string data from
byte strings to unicode strings and back.
There is no good way of handling this implicitly:
you can't simply say "utf-8" or "iso-8859-whatever"
in one place and expect it to work.

You've got to specify the encoding on each and
every open, or else use the encode and decode
string methods. This is a great motivation for
eliminating duplication and centralizing your
code!

For your other question: the general words
are localization and locale. Look up locale in
the index. It's a strange subject which I don't
know much about, but that should get you 
started.

John Roth

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


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

2006-10-20 Thread Carl Banks

[EMAIL PROTECTED] wrote:
> The extended slice notation comes from the
> numeric community though where they are probably all former FORTRAN
> programmers.  I think the concept of start, stop, step (or stride?) is
> pretty common there.

Yep.  I do a bit of numerical work and the meaning of abc[::-1] is
plain as day to me.

One thing I'd like to point out is that few people seem to be thrown
off when slices are used to twiddle list elements.  A few days back
there was a thread about reordering a list such as [1,2,3,4,5,6,7,8,9]
as [1,4,7,2,5,8,3,6,9], and the advice was along the lines of
a[0::3]+a[1::3]+a[2::3].  I don't remember any complaints about the the
notation there.

I think the problem here isn't the slice notation; it's the use of
slice notation for something that seems conceptually distinct.  People
who aren't used to doing a lot of slicing don't always have the
connection between "reversing" and "slicing" in mind.  It wouldn't
occur to them to accomplish a reverse with a slice, and it would
surprise them a bit to see it.


Carl

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


Re: help with my first use of a class

2006-10-20 Thread Bruno Desthuilliers
Fulvio wrote:
> ***
> 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?

Depends on the program.

> Fundamentally OOP is the way to assemble ready objects to get a "thing" 
> working, rather than worry about any single code line.

This is more a wishful dream than reality. While it can effectively be
pretty powerful - specially with dynamic languages like Python or Ruby -
OO is by no mean magical.

> Is this a concept of python?

If you mean "a concept specific to Python", well, not really - OO first
reared it's head with Simula in the sixties and matured in the seventies
with Smalltalk (which is still the reference IMHO). And it's (it->OO)
more an evolution/systematisation of concepts that already existed
before...

FWIW, I don't know if there's any truly Python-specific concept in
Python (except perhaps for the descriptor protocol, which is a somewhat
advanced topic if you're new to programming and OO...).



-- 
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


Using Python scripts in Windows Explorer

2006-10-20 Thread Ben Sizer
I'd like to be able to drag a file onto a Python script in Windows
Explorer, or send that file to the script via the Send To context-menu
option, so I can then process that file via sys.argc.

Unfortunately, I can't drag items onto the Python script, because
Windows doesn't recognise that the script is executable (unless I
double-click it, upon which it runs as usual, without the command line
parameter of course) and won't set it as a drop target. And it won't
even appear in the Send To menu after the usual steps are taken to get
it there.

I then tried to wrap it in a batch file, but encounter a problem, where
that batch file is able to execute the Python file if I double-click
the batch file, but if I drag a file onto it it says it can no longer
find the Python script.

Are there any simple and workable solutions for this sort of thing?

-- 
Ben Sizer

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


Python decorator article

2006-10-20 Thread gole
Hello,

I am writing to point interested readers to a few short articles on
decorators:

Please find them here:

http://muharem.wordpress.com/2006/10/18/3/

Best regards -- Muharem

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


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

2006-10-20 Thread Carl Banks

Demel, Jeff 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.

Say you're using a function from a third-party library that finds the
first character in a string that meets some requirement.  You need to
find the last such character.


Carl

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


Re: proper format for this database table

2006-10-20 Thread Carsten Haese
On Fri, 2006-10-20 at 10:57, John Salerno wrote:
> [EMAIL PROTECTED] wrote:
> 
> > you should rethink it as
> > 
> > [id] [university] [yearStart] [yearEnd] [degreeEarned]
> > 1 U of I   19711975  BS
> > 1 U of I   19751976  MS
> > 1 U of I   19761977  PhD
> > 
> 
> Thanks guys. I do plan to have an id entry for each person as well, I 
> just forgot to mention that. But since it's a primary key, I didn't know 
> I could list it more than once. Or does primary key not necessarily mean 
> unique?

Primary key *does* mean unique in the table that defines it. However, if
you take a primary key ID from one table and store it in a different
table, that's a foreign key. There are no inherent uniqueness
constraints on a foreign key.

-Carsten


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


Re: list comprehension (searching for onliners)

2006-10-20 Thread Carsten Haese
On Fri, 2006-10-20 at 10:53, Fredrik Lundh wrote:
> if you want to become a good Python programmer, you really need to get
> over that "I need a oneliner" idea.

+1 QOTW

-Carsten


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


Re: User Access to the docstring of a property

2006-10-20 Thread georgeryoung

Colin J. Williams wrote:
> Is there some way that the user can access the docstring specified for a
> property?

Do keep in mind that the docstring is not guaranteed to be available.
If
the application is run with optimization turned on, docstrings are
usually
optimized out.  Docstrings are handy for reading code and maybe for
debugging, but should not be relied upon for "users", as opposed to
developers.

-- George Young

> 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: FOR statement

2006-10-20 Thread Grant Edwards
On 2006-10-20, Lad <[EMAIL PROTECTED]> wrote:
> If I have a list
>
> Mylist=[1,2,3,4,5]

[...]

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

Another option:

>>> Mylist=[1,2,3,4,5]
>>> for i in Mylist[::-1]:
...   print i
... 
5
4
3
2
1

But, I think the reversed(Mylist) way is better.

-- 
Grant Edwards   grante Yow!  Where's the Coke
  at   machine? Tell me a joke!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: proper format for this database table

2006-10-20 Thread Neil Cerutti
On 2006-10-20, John Salerno <[EMAIL PROTECTED]> wrote:
> Bruno Desthuilliers wrote:
>> John Salerno a écrit :
>>> Hi guys. I was wondering if someone could suggest some possible 
>>> structures for an "Education" table in a database. 
>> 
>> Wrong newsgroup, then. comp.database.* is right next door...
>
> I know, I'm sorry. It's just that this newsgroup server doesn't
> have any database ngs on it. :(

Try Google Groups for these annoying cases.

-- 
Neil Cerutti
The audience is asked to remain seated until the end of the recession.
--Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >