ANN: ActivePython 2.4.1 for Mac OS X is now available!

2005-06-07 Thread Trent Mick

Today ActiveState is announcing support for Mac OS X.  I'm happy to
announce that ActivePython 2.4.1 for Mac OS X is now available for free
download from:

http://www.ActiveState.com/Products/ActivePython/

This brings the number of free ActivePython platforms to four -- with
the existing Linux, Solaris and Windows free downloads.

Meanwhile, some of you may be interested to know that we are busily
working on bringing Komodo to Mac OS X. We expect to offer a beta in
August and release later this year.

To keep up-to-date with our Mac OS X progress, betas and announcements,
we invite you to join our new mailing list:
[EMAIL PROTECTED]
You can join the OS X announce list on the ActiveState Programmer
Network (ASPN):
http://listserv.activestate.com/mailman/listinfo/osx-announce


What is ActivePython?
-

ActivePython is ActiveState's quality-assured binary distribution of
Python.  Builds for Linux, Mac OS X, Solaris and Windows are made freely
available.

ActivePython includes the Python core and core extensions (zlib 1.2.1,
bzip2 1.0.2, bsddb 4.2.52, Tk 8.4.9, and Tix 8.1.4) and is fully
compatible with other Python distributions of the same version.

ActivePython also includes a wealth of Python documentation, including:
- the core Python docs;
- Andrew Kuchling's What's New in Python series;
- the Non-Programmer's Tutorial for Python;
- Mark Pilgrim's excellent Dive into Python; and
- a snapshot of the Python FAQs, HOWTOs and PEPs.

Once installed on the Mac, you can find the ActivePython documentation
here:
/Library/Documentation/Help/ActivePython 2.4 Help/index.html
An online version of the docs can be found here:
 http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/welcome.html

Thanks, and enjoy!

Trent, Python Tech Lead

-- 
Trent Mick
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

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


Re: random module question

2005-06-07 Thread Roose
Raymond Hettinger wrote:
 The answer is a qualified Yes.  While the core generator (currently

Thanks!  That is the answer I'm looking for.

And to Paul Rubin, it is a good point that Jython might not support it, but 
at this point it doesn't interest me.  The program is only for myself 
anyway.

R


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


poker card game revisited (code included)

2005-06-07 Thread flupke
Hi,

i've included the code so interested people can take a look.
I've tried to expand on the thread of 26/05/2005 on Checking for a full
house. Code is suboptimal as I coded it rather quickly.
I've added the normal classes one would expect from a cardgame: card,
deck, hand etc.

1. I can detect most things except a straightflush. The problem with the
code now is that it only returns 1 straight which is enough for mere
straight detection but won't suffice for hand comparison and
especially detecting straight flushes. For use in straight flush
detection, the function would need to return all possible straights and
then these would need to be checked to see if they are flushes.
For instance a list [4,4,5,5,6,7,8] yields 4 different straights.
A hand like [4,4,5,5,6,7,8,9] gets even worse.
I can't see how i can do this using sets, i'll need to come up with
another method since the suit is important.

2. Hand comparison.
For this to succeed the getrank function would need to return the exact
5 cards that represent the highest hand. This could be less than 5 cards
if one uses wildcards. Then you not only have the correct rank but also
the highest hand so you can compare in case there are ties.

3. x wild.
For games like deuces wild, what would be the best way to manage
those? I tought about removing them from a hand before shipping it of to
the getrank function?

Any ideas?

Regards,
Benedict Verheyen

= CODE =

Attempt for a poker cardgame representation
Benedict Verheyen
Code additions from web (http://www.ibiblio.org/obp/thinkCSpy/) and
newsgroup comp.lang.python esp. Raymond Hettinger

import random

class Card(object):
  
  Represents a single card
  2,3,4, ... 10, 11 for Jack, 12 for Queen,
  13 for King, 14 for Ace
  
  suitList = [Clubs, Diamonds, Hearts, Spades]
  rankList = [ narf, narf, 2, 3, 4, 5, 6, 7, 8,
9, 10,
  Jack, Queen, King, Ace]

  def __init__(self, suit=0, rank=0):
  
  Initialise a card
  @type suit: int
  @param suit: suit of the card (see suitList)
  @type rank: int
  @param rank: rank of the card (see rankList)
  
  self.suit = suit
  self.rank = rank

  def __str__(self):
  
  Pretty print a card
  
  return self.rankList[self.rank] +  of  + 
self.suitList[self.suit]

  def __cmp__(self, other):
  
  Compare 2 cards
  @type other: card
  @param other: the card to compare with
  
  # check the suits
  if self.suit  other.suit: return 1
  if self.suit  other.suit: return -1
  # suits are the same... check ranks
  if self.rank  other.rank: return 1
  if self.rank  other.rank: return -1
  # ranks are the same... it's a tie
  return 0

class Deck(object):
  
  Represents a deck of cards. We can have different decks of cards
  
  DECK_NORMAL = 1 # 52 cards

  def __init__(self,decktype=DECK_NORMAL):
  
  Makes a deck of cards
  @type decktype: type of deck
  @param decktype: what type of deck is it? (DECK_NORMAL,...)
  
  self.cards = []
  for suit in range(4):
for rank in range(2, 15):
  self.cards.append(Card(suit, rank))

  def printdeck(self):
  
  Pretty print the deck
  
  for card in self.cards:
print card

  def __str__(self):
  
  Pretty print the deck
  
  s = 
  for i in range(len(self.cards)):
  s = s +  *i + str(self.cards[i]) + \n
  return s

  def sort(self,rank=True,suit=False):
  
  Sort the deck
  
  def sortonrank(x,y):
  if x.rank  y.rank: return 1
  if x.rank  y.rank: return -1
  return 0
  def sortonsuit(x,y):
  if x.suit  y.suit: return 1
  if x.suit  y.suit: return -1
  return 0
  def sortonboth(x,y):
  return cmp(x,y)

  if ( rank == True and suit == False):
  self.cards.sort(sortonrank)
  elif ( suit == True and rank == False ):
  self.cards.sort(sortonsuit)
  else:
  self.cards.sort(sortonboth) # roept sort van card op

  def shuffle(self,nshuffle=1):
  
  Shuffle the deck of cards. This happens by swapping cards
  @type nshuffle: int
  @param nshuffle: how many times do we shuffle
  
  import random
  nCards = len(self.cards)
  # swap cards on place i and j
  for shuffle in range(nshuffle):
  print  shuffle %s  % shuffle
  for i in range(nCards):
  j = random.randrange(i, nCards)
  [self.cards[i], self.cards[j]] = 

Re: split up a list by condition?

2005-06-07 Thread Raymond Hettinger
 while writing my solution for The python way?, I came across this fragment:
 vees = [c for c in wlist[::-1] if c in vocals]
 cons = [c for c in wlist[::-1] if c not in vocals]

 So I think: Have I overlooked a function which splits up a sequence
 into two,  based on a condition

Trying to compress too much into one line is not the python way ;-)


vees, cons = [], []
for c in reversed(wlist):
if c in vocals:
vees.append(c)
else:
cons.append(c)

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


Re: the python way?

2005-06-07 Thread Raymond Hettinger
import random
from itertools import ifilter, ifilterfalse

def reinterpolate(word):

word = list(word)
random.shuffle(word)

isvowel = dict.fromkeys('aeiouy').has_key
vowels = ifilterfalse(isvowel, word)
consonants = ifilter(isvowel, word)

result = []
for v, c in map(None, vowels, consonants):
if c:
result.append(c)
if v:
result.append(v)
return ''.join(result)

print reinterpolate(encyclopedias)

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


Re: random module question

2005-06-07 Thread Raymond Hettinger
 Is Mersenne Twister currently available at all in Jython, for example?

Googling for java mersenne twister provides multiple hits including:

http://www.axlradius.com/freestuff/Free.htm#MT


Raymond

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


reg php.ini equivalent file in python

2005-06-07 Thread praba kar
Dear All,

  I have one doubt. Is there python.ini
file like php.ini in Php?
  
  Actually php.ini file controls many aspects of
PHP's behavior. The following details of php.ini
will explain about it.

max_execution_time = 5000 ; Maximum execution time
of each script, in seconds (UNIX only)

memory_limit = 134217728; Maximum amount of
memory a script may consume (128MB)

post_max_size = 67108864; Maximum POST-Content
length (64MB)

If I want to update the above details in Python where
I need to change these things in Python

regards,
Prabahar



___
Too much spam in your inbox? Yahoo! Mail gives you the best spam protection for 
FREE! http://in.mail.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help with sending mail in Program

2005-06-07 Thread Fuzzyman


Ivan Shevanski wrote:
 Hey i'm new here and relatively new to python.  I've made a few small
 programs and now I'm making a program for my friends that at the end has a
 feedback form.  I want to send the feedback back to my email adress.  I know
 I should use the SMTP module and I have figured out how to send with it, but
 I can't figure out how to include my variables in it, such as the questions
 I ask them.  Can someone explain this to me?
 -Ivan

If you look at the cgiutils module at :
http://www.voidspace.org.uk/python/recipebook.shtml

It contains a couple of different functions for sending emails from
Python. One using SMTP (either with a login or without), or using the
sendmail program.

You pass the body of the message to them as a string - so it will be
easy enough to construct the string in the way you want.

Regards,


Fuzzy
http://www.voidspace.org.uk/python


 _
 On the road to retirement? Check out MSN Life Events for advice on how to
 get there! http://lifeevents.msn.com/category.aspx?cid=Retirement

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


Re: SMTP help please

2005-06-07 Thread Simon Brunning
On 6/7/05, Ivan Shevanski [EMAIL PROTECTED] wrote:
 I really can't figure out anything about the SMTP module. . .I think I'm in
 over my head( Im pretty new to python).  Can someone show me a really(and I
 mean REALLY) basic tutorial for smtp or explain it?

http://effbot.org/zone/librarybook/network-protocols.pdf

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


poker card game revisited (code included)

2005-06-07 Thread flupke
Hi,

i've included the code so people can take a look.
I've tried to expand on the thread of 26/05/2005 on Checking for a full
house. Code is suboptimal as I coded it rather quickly.
I've added the normal classes one would expect from a cardgame: card,
deck, hand etc.

1. I can detect most things except a straightflush. The problem with the
code now is that it only returns 1 straight which is enough for mere
straight detection but won't suffice for hand comparison and
especially detecting straight flushes. For use in straight flush
detection, the function would need to return all possible straights and
then these would need to be checked to see if they are flushes.
For instance a list [4,4,5,5,6,7,8] yields 4 different straights.
A hand like [4,4,5,5,6,7,8,9] gets even worse.
I can't see how i can do this using sets, i'll need to come up with
another method since the suit is important.

2. Hand comparison.
For this to succeed the getrank function would need to return the exact
5 cards that represent the highest hand. This could be less than 5 cards
if one uses wildcards. Then you not only have the correct rank but also
the highest hand so you can compare in case there are ties.

3. x wild.
For games like deuces wild, what would be the best way to manage
those? I tought about removing them from a hand before shipping it of to
the getrank function?

Any ideas?

Regards,
Benedict Verheyen

= CODE =

Attempt for a poker cardgame representation
Benedict Verheyen
Code additions from web (http://www.ibiblio.org/obp/thinkCSpy/) and
newsgroup comp.lang.python esp. Raymond Hettinger

import random

class Card(object):
  
  Represents a single card
  2,3,4, ... 10, 11 for Jack, 12 for Queen,
  13 for King, 14 for Ace
  
  suitList = [Clubs, Diamonds, Hearts, Spades]
  rankList = [ narf, narf, 2, 3, 4, 5, 6, 7, 8,
9, 10,
  Jack, Queen, King, Ace]

  def __init__(self, suit=0, rank=0):
  
  Initialise a card
  @type suit: int
  @param suit: suit of the card (see suitList)
  @type rank: int
  @param rank: rank of the card (see rankList)
  
  self.suit = suit
  self.rank = rank

  def __str__(self):
  
  Pretty print a card
  
  return self.rankList[self.rank] +  of  + 
self.suitList[self.suit]

  def __cmp__(self, other):
  
  Compare 2 cards
  @type other: card
  @param other: the card to compare with
  
  # check the suits
  if self.suit  other.suit: return 1
  if self.suit  other.suit: return -1
  # suits are the same... check ranks
  if self.rank  other.rank: return 1
  if self.rank  other.rank: return -1
  # ranks are the same... it's a tie
  return 0

class Deck(object):
  
  Represents a deck of cards. We can have different decks of cards
  
  DECK_NORMAL = 1 # 52 cards

  def __init__(self,decktype=DECK_NORMAL):
  
  Makes a deck of cards
  @type decktype: type of deck
  @param decktype: what type of deck is it? (DECK_NORMAL,...)
  
  self.cards = []
  for suit in range(4):
for rank in range(2, 15):
  self.cards.append(Card(suit, rank))

  def printdeck(self):
  
  Pretty print the deck
  
  for card in self.cards:
print card

  def __str__(self):
  
  Pretty print the deck
  
  s = 
  for i in range(len(self.cards)):
  s = s +  *i + str(self.cards[i]) + \n
  return s

  def sort(self,rank=True,suit=False):
  
  Sort the deck
  
  def sortonrank(x,y):
  if x.rank  y.rank: return 1
  if x.rank  y.rank: return -1
  return 0
  def sortonsuit(x,y):
  if x.suit  y.suit: return 1
  if x.suit  y.suit: return -1
  return 0
  def sortonboth(x,y):
  return cmp(x,y)

  if ( rank == True and suit == False):
  self.cards.sort(sortonrank)
  elif ( suit == True and rank == False ):
  self.cards.sort(sortonsuit)
  else:
  self.cards.sort(sortonboth) # roept sort van card op

  def shuffle(self,nshuffle=1):
  
  Shuffle the deck of cards. This happens by swapping cards
  @type nshuffle: int
  @param nshuffle: how many times do we shuffle
  
  import random
  nCards = len(self.cards)
  # swap cards on place i and j
  for shuffle in range(nshuffle):
  print  shuffle %s  % shuffle
  for i in range(nCards):
  j = random.randrange(i, nCards)
  [self.cards[i], self.cards[j]] = [self.cards[j],

Re: SMTP help please

2005-06-07 Thread Martin Franklin
Ivan Shevanski wrote:
 I really can't figure out anything about the SMTP module. . .I think I'm 
 in over my head( Im pretty new to python).  Can someone show me a 
 really(and I mean REALLY) basic tutorial for smtp or explain it?
 
 program:
 I want to make my program have a feedback form attached to it at the end 
 which sends me the form when they're done.  I don't especially want them 
 to have to input all the needed details though. . .Just thought I'd put 
 this in so you'd know what its for.
 
 
 
 -Ivan
 
 _
 Dont just search. Find. Check out the new MSN Search! 
 http://search.msn.click-url.com/go/onm00200636ave/direct/01/
 


Ivan,

import smtplib

server = smtplib.SMTP(mailserver.somewhere.com)

server.set_debuglevel(3)

fromaddr = [EMAIL PROTECTED]

toaddrs = [[EMAIL PROTECTED], [EMAIL PROTECTED]]

msg = Subject: Hi I'm great


Thats right I really am


server.sendmail(fromaddr, toaddrs, msg)
server.quit()



HTH
Martin

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


Re: the python way?

2005-06-07 Thread Greg McIntyre
I like this solution. For some reason it made me want to write a Ruby
version of it. Possibly something about the title and the fact that
Ruby enthusiasts are always going on about the Ruby way.

VOWELS = 'aeiouy'.split('')

def reinterpolate(word)
letters = word.split('').sort_by{rand}
vowels = letters.find_all{|l| VOWELS.include?(l) }
consonants = letters - vowels
return vowels.zip(consonants).map{|v, c| #{c}#{v} }.join('')
end

puts reinterpolate(encyclopedias)

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


Re: the python way?

2005-06-07 Thread Raymond Hettinger
Doh!

The ifilter() and ifilterfalse() calls should be swapped in the
previous post.

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


Re: Question about Object Oriented + functions/global vars?

2005-06-07 Thread bruno modulix
Christopher J. Bottaro wrote:
(snip)
 1.  The upload function is not an object.

Yes it is. In Python, everything's an object.

 ftp.storbinary.__class__.__name__
'instancemethod'
 ftp.storbinary.foobar = 42
Traceback (most recent call last):
  File stdin, line 1, in ?
AttributeError: 'instancemethod' object has no attribute 'foobar'


-- 
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: Question about Object Oriented + functions/global vars?

2005-06-07 Thread bruno modulix
gene tani wrote:
 #include canonical design pattern advice
 
 longjmp(Borders or other_big_chain_bookstore)
 
 opt1=fopen(Oreilly's Head first design pattern,r)
 opt2=fopen(design patterns book by Shalloway and trott (i think that's
 their names),r)
 
 another=poll(any other intro to  DP books that people like?)

another.append(what_about(GOF))

-- 
bruno desthuilliers
ruby -e print '[EMAIL PROTECTED]'.split('@').collect{|p|
p.split('.').collect{|w| w.reverse}.join('.')}.join('@')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: split up a list by condition?

2005-06-07 Thread Duncan Booth
Reinhold Birkenfeld wrote:

 Hi,
 
 while writing my solution for The python way?, I came across this
 fragment: 
 
 vees = [c for c in wlist[::-1] if c in vocals]
 cons = [c for c in wlist[::-1] if c not in vocals]
 
 So I think: Have I overlooked a function which splits up a sequence
 into two, based on a condition? Such as
 
 vees, cons = split(wlist[::-1], lambda c: c in vocals)
 
 Reinhold

If you really are being charged by the number of newline characters in your 
code you could write:

 wlist = list('The quick brown fox')
 vowels = 'aeiuo'
 cons = []
 vees = [ c for c in wlist if c in vowels or cons.append(c) ]
 cons
['T', 'h', ' ', 'q', 'c', 'k', ' ', 'b', 'r', 'w', 'n', ' ', 'f', 'x']
 vees
['e', 'u', 'i', 'o', 'o']
 cons = []
 vees = [ c for c in wlist[::-1] if c in vowels or cons.append(c) ]
 cons
['x', 'f', ' ', 'n', 'w', 'r', 'b', ' ', 'k', 'c', 'q', ' ', 'h', 'T']
 vees
['o', 'o', 'i', 'u', 'e']

but every penny you save writing a one liner will be tuppence extra on 
maintenance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SMTP help please

2005-06-07 Thread Tim Williams
- Original Message - 
From: Martin Franklin [EMAIL PROTECTED]

 server.sendmail(fromaddr, toaddrs, msg)

You can use this if you don't need to worry about whether the email was
successfully sent to all recipients.   Otherwise,  you need something like
this

(untested and partly copied from an earlier post of mine).

import smtplib
try:
   s = smtplib.SMTP(outgoing_server)
   failed = s.sendmail(fromaddr, toaddrs, msg)
except smtplib.SMTPRecipientsRefused, x :  # All failed
   do something  # for recip in x.recipients:  info = x.recipients[recip]
except smtplib.SMTPDataError, x:  # email failed after data stage
   do something  # x[0], x[1]
except smtplib.SMTPSenderRefused, x :  # the sender was refused
   do something  # x.sender, x.smtp_code, x.smtp_error
except:
   do something

try:
s.close()
except
pass

for recip in failed:
do something

--

(failed contains a list of failed recipients if *some* but not all failed,
if all failed then use :  except smtplib.SMTPRecipientsRefused, x :)


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


Re: reg php.ini equivalent file in python

2005-06-07 Thread flamesrock
I think it depends on your os variables

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


Re: SMTP help please

2005-06-07 Thread Tim Williams
- Original Message - 
From: Tim Williams [EMAIL PROTECTED]
 
 try:
 s.close()
 except
 pass

Typo!! 

That should be s.quit()   not s.close()  

:)




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


Re: Question about Object Oriented + functions/global vars?

2005-06-07 Thread bruno modulix
flamesrock wrote:
 ok, so to my knowledge, object oriented means splitting something into
 the simplest number of parts and going from there.

So you may want to refine your knowledge. What you're talking about is
top-down functional decomposition, and it's almost the opposite of OO.

overly-simplified
OO is about interacting objects. An object is defined by an identity, a
state, a behaviour, and (even if implicitely) an interface. Objects do
interact by sending messages to each others. The interface of a given
object is the list of *what* messages this object understands (ie: can
respond to). The behavior is defined by *how* a given object responds to
messages (different objects can respond differently to the same message,
and a given object may respond differently to the same message according
to it's current state). The state is made up of the object's internals
vars.
/overly-simplified

 But the question is-
 when is it enough?
 
 For example I have the following code:
 
 #def put_file(file_id, delete=False):
 #  Function to put the file on the FTP Server
 #
 #print [+file_id+] FTP for this file started
 #print [ + file_id + ] Connecting to machine  + global_addr

Where does this 'global_addr' var come from ?

 #ftp_pool = FTP_pool(file_id,1,40,global_uid,global_pwd)

idem for global_uid and global_pwd. And what are those magic numbers 1
and 40 ?

 #print 'in put_file'
 #try:
 #ftp = ftplib.FTP(global_addr)
 #ftp.login(global_uid, global_pwd)
 #print ftp.getwelcome() +'\n'
 #ftp.cwd(global_ftp_loc)
 
#ext = os.path.splitext(file_id)[1]
#if ext not in (.sc4, .snpickle):
#ftp.storlines(STOR  + file_id, open(file_id))
#else:
#ftp.storbinary(STOR  + file_id, open(file_id, rb), 1024)
 
 #ftp.quit()
 #ftp_pool.close_all()
 #except:

Take care of too-large-except-clause. Here it's ok since you re-raise
the exception, but this is usually a bad practice to not specify the
exception class(es) you want to catch. Hint: sys.exit() works by raising
 SystemExit.

 #ftp_pool.close_all()
 #print [ + file_id + ]Unable to access FTP location
 #print [ + file_id + ]Error: + str(sys.exc_info()[0]) +  
 + str(sys.exc_info()[1])
 #upload_status[file_id] = FAILED

Where does this upload_status comes from ?

 #raise
 #else:
 #print [ + file_id + ] FTP for file completed
 #upload_status[file_id] = SUCCESS

 
 would the lines with '#' best be split up into a seperate function,
 for example:
 
 #def upload(ftp, file):

dont use 'file', it shadows the builtin file class.

 #ext = os.path.splitext(file)[1]
 #if ext in (.txt, .htm, .html):
 #ftp.storlines(STOR  + file, open(file))
 #else:
 #ftp.storbinary(STOR  + file, open(file, rb), 1024)


Nope.

IMHO The calling code should not have to worry about this. This should
be a responsability of some object(s) abstracting the file, and should
be implemented as different behaviors (using text or binary) in response
to the same message./IMHO In short, this could look like:

the_file = FtpFileDescriptor(path)
try:
  # the_file objects knows if it must use text or binary.
  # we, as client, just don't care about this gory detail.
  the_file.store()
except MyFtpUploadError, e:
  # TODO
  pass

 
 and then doing the call 'upload(file_id)', or is it a better practice
 to leave things the way they were? I'm confused.
 
 Finally, is it considered 'un-object-oriented' in python to have
 functions inside a module that are called by objects (ie the upload
 function above) and/or use global variables in combination?

disgression
In Python, everything's an object (well... almost everything). At
runtime, a module is an object :

 ftplib
module 'ftplib' from '/usr/lib/python2.3/ftplib.pyc'
 ftplib.__class__
type 'module'
 ftplib.__class__.__name__
'module'

module-level 'functions' are methods of the given module object, and
'global' vars (the term 'global' is somewhat misleading, since it reaaly
means 'module-level') are attributes of the module object.
/disgression

Now what makes the difference between OO and non-OO is not the use of
classes, objects etc, but how you *design* your program. Your code
snippet makes use of OO features (classes, objects etc), but is typical
of procedural style. Not because you use 'module-level' functions and
vars, but because there's no abstraction, no separation of concerns and
responsabilities.


 -thanks in advance

HTH (not sure, but...)

-- 
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: SMTP help please

2005-06-07 Thread Martin Franklin
Tim Williams wrote:
 - Original Message - 
 From: Tim Williams [EMAIL PROTECTED]
 
try:
s.close()
except
pass
 
 
 Typo!! 
 
 That should be s.quit()   not s.close()  
 
 :)
 
 
 
 


and perhaps put into a finally:


Mart

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


Re: help with sending mail in Program

2005-06-07 Thread Kent Johnson
Ivan Shevanski wrote:
 Could someone send me a good tutorial for sending mail then? The one I 
 found is not what I'm looking for.  Also please dont send me the stmp 
 definition cause i've looked at that enough.

Here is a module I use to send mail to myself using smtplib:

#!/usr/local/bin/python

''' Send mail to me '''

from smtplib import SMTP


def sendToMe(subject, body):
me = 'Kent Johnson [EMAIL PROTECTED]'
send(me, me, subject, body)


def send(frm, to, subject, body):
s = SMTP()
#s.set_debuglevel(1)
s.connect('mail.mycompany.com')
s.ehlo('10.0.3.160') # IP address of my computer, I don't remember why I 
needed this

msg = '''From: %s
Subject: %s
To: %s

%s
''' % (frm, subject, to, body)

s.sendmail(frm, to, msg)
s.quit()


if __name__ == '__main__':

sendToMe('Testing', 'This is a test')

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


Trouble Encoding

2005-06-07 Thread fingermark
I'm using feedparser to parse the following:

div class=indent textAdv: Termite Inspections! Jenny Moyer welcomes
you to her HomeFinderResource.com TM A MUST See amp;hellip;/div

I'm receiveing the following error when i try to print the feedparser
parsing of the above text:

UnicodeEncodeError: 'latin-1' codec can't encode character u'\u201c' in
position 86: ordinal not in range(256)

Why is this happening and where does the problem lie?

thanks

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


Re: reg php.ini equivalent file in python

2005-06-07 Thread bruno modulix
praba kar wrote:
 Dear All,
 
   I have one doubt. Is there python.ini
 file like php.ini in Php?

[EMAIL PROTECTED] ~ $ python -h
usage: python [option] ... [-c cmd | file | -] [arg] ...
(snip)
PYTHONSTARTUP: file executed on interactive startup (no default)
(snip)

I guess this is the closer thing.

   Actually php.ini file controls many aspects of
 PHP's behavior. The following details of php.ini
 will explain about it.
 
 max_execution_time = 5000 ; Maximum execution time
 of each script, in seconds (UNIX only)
 
 memory_limit = 134217728; Maximum amount of
 memory a script may consume (128MB)
 
 post_max_size = 67108864; Maximum POST-Content
 length (64MB)

All those settings are somewhat web-specific, and would not have much
meaning in most Python usages.

 If I want to update the above details in Python where
 I need to change these things in Python

This (if possible) depends on the web developpement solution you use
(cgi, mod_python, CherryPy, Webware, Zope, other...).


-- 
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: Trouble Encoding

2005-06-07 Thread deelan
[EMAIL PROTECTED] wrote:
 I'm using feedparser to parse the following:
 
 div class=indent textAdv: Termite Inspections! Jenny Moyer welcomes
 you to her HomeFinderResource.com TM A MUST See amp;hellip;/div
 
 I'm receiveing the following error when i try to print the feedparser
 parsing of the above text:
 
 UnicodeEncodeError: 'latin-1' codec can't encode character u'\u201c' in
 position 86: ordinal not in range(256)
 
 Why is this happening and where does the problem lie?

it seems that the unicode character 0x201c isn't part
of the latin-1 charset, see:

LEFT DOUBLE QUOTATION MARK
http://www.fileformat.info/info/unicode/char/201c/index.htm

try to encode the feedparser output to UTF-8 instead, or
use the replace option for the encode() method.

  c = u'\u201c'
  c
u'\u201c'
  c.encode('utf-8')
'\xe2\x80\x9c'
  print c.encode('utf-8')

ok, let's try replace

  c.encode('latin-1', 'replace')
'?'

using replace will not throw an error, but it will replace
the offending characther with a question mark.

HTH.

-- 
deelan http://www.deelan.com/




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


Re: how to show simulation at web

2005-06-07 Thread Apoptozinho
If your problem is plotting graphics from numerical simulations perhaps this 
fragment of code from my learning python and mod_python may help you.

def show(req):
 req.content_type=image/png
 put,get=os.popen4('echo set term png size 400,400 ; set out ; 
splot(sin(x)*cos(y)) | gnuplot')
 img=get.read()
 
 req.write(img)
 put.close()
 get.close()
 return apache.OK

I feel there must be an easier, more elegant and performant method of doing 
this.


On Monday 06 June 2005 10:57, Hallo (Ha) wrote:
hi all,

I have tried making a simulation with python. I want it to be shown at
a web. It is ok when I run it. so, I decided using cgi. but, when I try
it using a web browser it doesn't work.

Is it problem in the header or something else ?

If there are any suggestions about this problem, I will be very happy.

thanks


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

Create our own python source repository

2005-06-07 Thread qwweeeit
Hi all,
beeing almost a newbie, I am trying to learn from experts.
For that reason I am collecting examples of Python sources (and
Pythonic way of programming...) on a CD, ready  to be searched.
By now, I extracted from web (using wget) all the examples of Cookbook
Python (35 Mb!). After some polishing and merging I obtained 20 files
(one for each Category), which sum up to 12 Mb).
To this source repository, I want also add my own scripts. But since my
programming habits are not very Pythonic, I should prefer to include
more meaningful examples.
In the web there is plenty of such material, but I need the advice of
experts to address me in the right direction...
Bye.

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


Re: file permissions on windows XP (home)

2005-06-07 Thread Peter Hansen
barney wrote (having trouble with a file):
[snip]
 IOError: [Errno 13] Permission denied: 02 - New Year's Day.mp3
[snip]
 I'm at a loss to understand what is going on.
 
 Why is python returing True from os.access?
 Why isn't chmod doing anything?

Check your results using os.stat() after doing that, perhaps?  If it 
shows the right values for the permissions, then clearly the problem has 
nothing to do with Python per se, or your own code.

 Why is cygwin able to sort the problem out?

I suggest (a) trying again, making sure that the file is not in use in 
another application such as the Media Player, and (b) trying with some 
other file that you've just created for the purpose of testing this to 
compare your results.

I just tried the whole sequence you showed without any problems, on a 
file called test that I created in my own My Music folder.  (Not using 
cygwin, however, since I don't use it, but in this case there was no 
need for me to use it anyway.)

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


Re: separate IE instances?

2005-06-07 Thread Martin Franklin
Chris Curvey wrote:
 Bummer.  No change at all.  (In fact, I can't even call Navigate()
 without throwing an error).  I'm on win2k, if that makes any difference.
 


I could be way off, but isn't windows one of those OS's that doesn't
allow you to have two instances of IEXPORE.EXE running IOW the OS is
preventing you from running two instances of this executable.  Someone
with a lot more knowledge of windows internals will I'm sure come along
and correct me ;-)

Mart

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


Re: If - Or statements

2005-06-07 Thread bruno modulix
Steven Bethard wrote:
 bruno modulix wrote:
(snip)
 ext = os.path.splitext(filename)
 

 Check the docs[1].  This should probably read: 
 _, ext = os.path.splitext(filename)

Of course. Au temps pour moi.

-- 
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: SMTP help please

2005-06-07 Thread Larry Bates
I have found that the SmtpWriter class hides all the
complexity in creating emails like you want to send.

Check it out here:

http://motion.sourceforge.net/related/send_jpg.py

HTH,
Larry Bates
Syscon, Inc.


Ivan Shevanski wrote:
 I really can't figure out anything about the SMTP module. . .I think I'm
 in over my head( Im pretty new to python).  Can someone show me a
 really(and I mean REALLY) basic tutorial for smtp or explain it?
 
 program:
 I want to make my program have a feedback form attached to it at the end
 which sends me the form when they're done.  I don't especially want them
 to have to input all the needed details though. . .Just thought I'd put
 this in so you'd know what its for.
 
 
 
 -Ivan
 
 _
 Dont just search. Find. Check out the new MSN Search!
 http://search.msn.click-url.com/go/onm00200636ave/direct/01/
 
-- 
http://mail.python.org/mailman/listinfo/python-list


how to export data from ZODB to text files

2005-06-07 Thread ls
Hi All,

I looking for help with ZODB data export to text file. I have file
Data.fs  (file becomes from Plone CMS) and I have to display content
structure, data like intro, body of article, etc and save it in to
simple file. However I can't use Plone XML export because is broken,
Zope Corp. set low priority for this bug, so I have to find other way
how to digg in  to data.

Could you point me in to some Python code examples, code contributions
and so on.

Thank you for any suggestions,

Lukasz

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


Re: file permissions on windows XP (home)

2005-06-07 Thread Duncan Booth
Peter Hansen wrote:

 
 Why is python returing True from os.access?
 Why isn't chmod doing anything?
 
 Check your results using os.stat() after doing that, perhaps?  If it 
 shows the right values for the permissions, then clearly the problem has 
 nothing to do with Python per se, or your own code.
 

And also remember that in windows the mode in os.chmod and os.stat is only 
loosely related to the actual permissions on the file. In particular there 
is a 'readonly' flag which is separate from whether any particular user 
or group has write access. The only way to tell whether you have access to 
a file in windows really is to try to open it and handle the exception.

Try using the properties panel, or the windows CACLS to display the 
security permissions on the file.

If you start with a plain file, then you and administrators probably have 
full access (CACLS will display 'your username:F'). If you use Python to 
set an access mode, it simply tries to toggle the attributes on the file 
itself. If you use Cygwin's chmod it will mess about with the security 
permissions in an attempt to get as close to the Unix file mode as it can, 
so your nice simple 'F' mode might become something truly horrendous:

Before:
C:\tempcacls testfile.txt
C:\temp\testfile.txt BUILTIN\Administrators:F
 NT AUTHORITY\SYSTEM:F
 DELL5150\Duncan:F
 BUILTIN\Users:R

C:\temp\cygwin\bin\chmod 744 testfile.txt

C:\tempcacls testfile.txt
C:\temp\testfile.txt DELL5150\Duncan:(special access:)
 STANDARD_RIGHTS_ALL
 DELETE
 READ_CONTROL
 WRITE_DAC
 WRITE_OWNER
 SYNCHRONIZE
 STANDARD_RIGHTS_REQUIRED
 FILE_GENERIC_READ
 FILE_GENERIC_WRITE
 FILE_GENERIC_EXECUTE
 FILE_READ_DATA
 FILE_WRITE_DATA
 FILE_APPEND_DATA
 FILE_READ_EA
 FILE_WRITE_EA
 FILE_EXECUTE
 FILE_READ_ATTRIBUTES
 FILE_WRITE_ATTRIBUTES

 DELL5150\None:(special access:)
   READ_CONTROL
   SYNCHRONIZE
   FILE_GENERIC_READ
   FILE_READ_DATA
   FILE_READ_EA
   FILE_READ_ATTRIBUTES

 Everyone:(special access:)
  READ_CONTROL
  SYNCHRONIZE
  FILE_GENERIC_READ
  FILE_READ_DATA
  FILE_READ_EA
  FILE_READ_ATTRIBUTES

 BUILTIN\Administrators:F
 NT AUTHORITY\SYSTEM:F
 BUILTIN\Users:R

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


Re: EnumKey vs EnumValue

2005-06-07 Thread Pykid
Ok, this was not how I understood it to work earlier when I was going
over this.

I do want to eventually see the values under each key, so I guess if I
want to see what is under each key I need to then reopen it and send
that value to EnumValue.  Tried that and ended up with this which seems
to work:

for i in range(25):
try:
regEndeca = EnumKey(regpath,i)
print regEndeca
regValue = OpenKey(HKEY_LOCAL_MACHINE, key + \\ + regEndeca)
for j in range(25):
try:
regstr,value,type = EnumValue(regValue,j)
print Value Name: , regstr,  - Value: ,value,  -
Data: ,type
except EnvironmentError:
print There are, j,values under,regEndeca
break
print That was using EnumValue.
except EnvironmentError:
print There are, i,keys under,key
break
print That was using EnumKey.

Thanks for the help

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


How do I know when a thread quits?

2005-06-07 Thread Prashanth Ellina
Hi,

I have used the low-level thread module to write a multi-threaded app.

tid = thread.start_new_thread(process, ())
tid is an integer thread ident.

the thread takes around 10 seconds to finish processing. Meanwhile the
main thread finished execution and exits. This causes an error because
the child thread tries to access something in the sys module which has
already  been GC'ed.  I want a reliable way of knowing when the child
thread finished execution so that I can make the main thread wait till
then.

Any ideas?

TIA,
Prashanth Ellina

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


Re: How do I know when a thread quits?

2005-06-07 Thread harold fellermann
Hi,

 I want a reliable way of knowing when the child
 thread finished execution so that I can make the main thread wait till
 then.

 Any ideas?

use a lock. the subthread allocates the lock and releases it after 
processing.
the main thread must wait until the lock is released. otherwiese, use 
the
higher level Threading module which provides a function Thread.join 
that allows
the main thread to wait for the subthread. I think it uses the same 
mechanism
that I explained above.

- harold -

--
Outside of a dog, a book is a man's best friend: and inside a
dog, it's too dark to read.
-- Groucho Marx

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


Re: how to export data from ZODB to text files

2005-06-07 Thread Peter Hansen
ls wrote:
 I looking for help with ZODB data export to text file. I have file
 Data.fs  
 [snip]
 Could you point me in to some Python code examples, code contributions
 and so on.

You can download the standalone ZODB code and run it under regular 
Python without Zope installed or involved, and use that to access your 
Data.fs file directly.  See http://www.zope.org/Products/StandaloneZODB

This page lists much documentation (near the bottom): 
http://www.zope.org/Wikis/ZODB/FrontPage

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


Re: How do I know when a thread quits?

2005-06-07 Thread Peter Hansen
Prashanth Ellina wrote:
 I have used the low-level thread module to write a multi-threaded app.
 
 tid = thread.start_new_thread(process, ())
 tid is an integer thread ident.
 
 the thread takes around 10 seconds to finish processing. Meanwhile the
 main thread finished execution and exits. This causes an error because
 the child thread tries to access something in the sys module which has
 already  been GC'ed.  I want a reliable way of knowing when the child
 thread finished execution so that I can make the main thread wait till
 then.
 
 Any ideas?

Yes, use the higher level threading module and either the isAlive() 
call on the Thread object, or just call join() on it to make the main 
thread wait till it finishes.  (By default the main thread will not exit 
until all threading Threads that aren't daemons have finished... maybe 
that's sufficient for your needs?)

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


Dr. Dobb's Python-URL! - weekly Python news and links (Jun 7)

2005-06-07 Thread Simon Brunning
QOTW: [expletives deleted] - John Machin, snipping a section of Perl code.

What sort of programmer are you?  If it works on your computer, it's done,
ship it! - Grant Edwards


Guido invites us to comment on PEP 343. This Python Enhancement
Proposal includes a 'with' statement, allowing you simply and
reliably wrap a block of code with entry and exit code, in which
resources can be acquired and released. It also proposes enhancements
to simple generators, making them easy to use to build these wrappers:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a9d9b591ca7b296d

Timothy Smith would like to truncate a Decimal. It's not as easy
as it sounds, but Raymond Hettinger has the definitive solution,
as is so often the case:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/f40d2863110dc81e

If you need to set Windows' environment variables persistently,
Gigi's recipe is what you need:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/416087

EasyInstall, Phillip J. Eby's CPAN clone is ready to go:
http://dirtsimple.org/2005/06/cpan-goodies-for-all.html

How does one check if a given datetime is within a specified
range? Andrew Dalke shows Maksim Kasimov how:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/e186c915a237c9a7

Robert Kern shows how to turn a CSV file into a list of
dictionaries, and Peter Otten shows off a lovely iterator
trick for turning adjacent list entries into dictionary elements:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/ed07b9f71724dcbd

Ryan Tomayko defends the LAMP (Linux, Apache, MySQL,
Python/Perl/PHP) platform:
http://naeblis.cx/rtomayko/2005/05/28/ibm-poop-heads

Skip Montanaro tells us why Emacs is the perfect IDE for him:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/6df813d2d8d187fb#8438e5f0d2352e5f

O'Reilly has published a couple of interesting articles by
Jeremy Jones, Python Standard Logging and  Writing Google
Desktop Search Plugins:
http://www.onlamp.com/pub/a/python/2005/06/02/logging.html
http://www.onlamp.com/pub/a/python/2005/06/01/kongulo.html

How can you reliably eradicate data from a hard disk? Nuke the
site from orbit; it's the only way to be sure.

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/2e73c88596c35427

Tomasz Bieruta shows us how to sort large files:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/415581

Google's new Sitemaps allow a Webmaster to tell Google what to
spider. They provide a Python script to get you started: 

https://www.google.com/webmasters/sitemaps/docs/en/sitemap-generator.html


Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily  
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html 
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

For far, FAR more Python reading than any one mind should
absorb, much of it quite interesting, several pages index
much of the universe of Pybloggers.
http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog
http://www.planetpython.org/
http://mechanicalcat.net/pyblagg.html

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djqas_ugroup=comp.lang.python.announce

Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous
tradition early borne by Andrew Kuchling, Michael Hudson and Brett
Cannon of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/   

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

The Python Business Forum further[s] the interests of companies
that 

RE: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 7)

2005-06-07 Thread Tim Golden
[Simon Brunning]
| Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 7)

[... snipped whole thing ...]

Just wanted to say thank you to Simon and all the
other people who have edited the Python-URL! weekly
digest over the years. Despite my being a pretty much
constant reader of c.l.py and various blogs and other
on-line sources, I still look forward to to its weekly 
arrival.

That's both because of the mild editorial introductions 
and also because it will almost certainly pick up
something I've missed (sometimes because it's a gem
buried deep within a thread which I've long since given
up on!)

Thanks, guys.

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: reloading my own modules

2005-06-07 Thread Skip Montanaro

Lowell import dbtest, util
Lowell for module in ['dbtest', 'util']:
Lowell  if module in sys.modules.keys():
Lowell  reload(sys.modules[module])

Lowell Is this the best way to do it? It seems a bit verbose, but not
Lowell really all that bad. I was just wondering if there is a more
Lowell standard way to do it?

Not that I'm aware of.  You don't need to request the keys() of a dict in
recent versions of Python:

import dbtest, util
for module in ['dbtest', 'util']:
 if module in sys.modules:
 reload(sys.modules[module])

Also, since it's clear you have already imported dbtest and util, there's no
need to check in sys.modules:

import dbtest, util
reload(dbtest)
reload(util)

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


Re: How do I know when a thread quits?

2005-06-07 Thread harold fellermann
we had some off-group mails. A summary is posted to improve the 
knowledge
base of the list.

Prashanth wrote:

 Hi,

 I can use the threading module but I am just looking if there is a
 reliable way using the thread module.

 If I use a lock...
 Let us assume that the child thread has done a lck.release() but does
 not get a chance to quit before execution is whisked away from it and
 given to the main thread. Now the main thread sees that the lock has
 been released and quits. The child thread hasn't quit yet and we are
 back in the same problem.

 Don't you think?

Harold wrote:

I think it depends on when you release the child lock. if you do it 
after
refering to any data, e.g. as the last command in the child thread, you
should be on the save side, no?

- harold -

 Yes, I can assume that in most cases. However I don't think it happens
 so always. Even though infinitesimal, there is still a chance that it
 will not quit. I am looking for a mechanism using which I can make
 sure.

I don't understand what you mean. Why should the following code fail in 
any
case?


import thread

def parentThread() :
lock = thread.allocate_lock()
child = thread.start_new_thread(childThread,(parent,))
lock.acquire()

def childThread(parent) :
parent.lock.acquire()
do_something_with_vars_from(parent)
parent.lock.release()
# don't do anything with parents vars after releasing the lock


I did not test it, but I cannot see any reason why this should fail.


 After the childThread executes parent.lock.release() execution may be
 taken away from it and given to the parent thread(note that the child
 thread hasn't quit yet). The parent thread which is waiting on the
 lock gets released and quits. Now the still running child thread
 tries to exit and based on my assumption attempts to call some cleanup
 func in some module which has been GC'ed due to the exit of the parent
 thread. This leads to an exception being thrown.


o.k. with this assumption, things might become a little more tricky.
one possibility: bind the modules you use to local variables in your 
child
thread. then they won't be GC'ed before childThread stops.
or (better): use Threading. it really isn't complicated to change your 
code
and timing issues become much simpler.

Referencing the module locally on the child thread does not seem like an
elegant solution besides I don't know which modules are involved in 
cleaning
up. Yes, I will use the Threading module but am just curious as to what 
can
be done to reliably use thread module.

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


redirecting messgaef from sys.stdout

2005-06-07 Thread Ahmad Hosseinzadeh
Hello,

I’m trying to run an external program in my
application. Both are coded in python. I need to write
an independent module that is used in the main
application. Its responsibility is to run the external
program and redirect its stdout and stderr to the main
application.
The application’s stdout and stderr are set to an
object and they are not command prompt anymore.
The output is selected by a flag; if true the stdout
and stderr will be redirected to application’s stdout
and stderr. If false, the stdout and stderr will be
redirected o command prompt. I don’t know how to
redirect the output.
Can anyone help please?

Regards,
Ahmad Hosseinzadeh

__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


re:how to export data from ZODB to text files

2005-06-07 Thread ls
Hi Peter,

Thank you for your reply. I already can access file using code


   from ZODB import FileStorage, DB
   storage =
FileStorage.FileStorage('mydatabase.fs')
   db = DB(storage)
   connection = db.open()
   root = connection.root()


But this is the point where my konwledge ends since I`m not a Python
programmer. 

I don`t know what is the structure of ZODB, I`m just looking for code,
or some tool, which I can use to export data from Data.ts file to
plain text file. 

I`m looking for easiest way to export data from ZODB and put it to
MySQL later. 

Do you know what way I should choose? I have to know Python language
to finish this task?

-- 
Lukasz

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


Re: redirecting messgaef from sys.stdout

2005-06-07 Thread harold fellermann

On 07.06.2005, at 16:43, Ahmad Hosseinzadeh wrote:

 Hello,

 Im trying to run an external program in my
 application. Both are coded in python. I need to write
 an independent module that is used in the main
 application. Its responsibility is to run the external
 program and redirect its stdout and stderr to the main
 application.
 The applications stdout and stderr are set to an
 object and they are not command prompt anymore.
 The output is selected by a flag; if true the stdout
 and stderr will be redirected to applications stdout
 and stderr. If false, the stdout and stderr will be
 redirected o command prompt. I dont know how to
 redirect the output.
 Can anyone help please?

have a look at:
http://www.python.org/doc/current/lib/module-popen2.html

--
Je me suis enferm dans mon amour -- je rve.
-- Paul Eluard

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


Re: Create our own python source repository

2005-06-07 Thread Rob Cowie
I'm not entirely sure what the point of your exercise is - if you have
access to the net, ,why do you want to collate code examples? They are
frequently updated in the cookbook so an offline repository would
quickly become out of date.

However you've aroused my interest in something related. We all
know Python is significantly easier   for novice programmers to grasp
than, say, Java - I too am a newbie who started at uni with java and
wished I hadn't.

Tutorials are great, self paced learning is great, BUT, for the
complete beginner a well structured, offline course with examples,
exercises, tips etc. would be a brilliant resource. Python would fit
the bill as a demonstration language to teach Object Orientation, flow
control statements, other common constructs etc. A quick canvas of some
IT teachers I know indicates support for such a thing - perhaps even in
secondary shools (pre-uni).

What does everyone think it would take to start such a project, and
distribute it? or has it been done already?

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


ANN: ActivePython 2.4.1 for Mac OS X is now available!

2005-06-07 Thread Trent Mick

Today ActiveState is announcing support for Mac OS X.  I'm happy to
announce that ActivePython 2.4.1 for Mac OS X is now available for free
download from:

http://www.ActiveState.com/Products/ActivePython/

This brings the number of free ActivePython platforms to four -- with
the existing Linux, Solaris and Windows free downloads.

Meanwhile, some of you may be interested to know that we are busily
working on bringing Komodo to Mac OS X. We expect to offer a beta in
August and release later this year.

To keep up-to-date with our Mac OS X progress, betas and announcements,
we invite you to join our new mailing list:
[EMAIL PROTECTED]
You can join the OS X announce list on the ActiveState Programmer
Network (ASPN):
http://listserv.activestate.com/mailman/listinfo/osx-announce


What is ActivePython?
-

ActivePython is ActiveState's quality-assured binary distribution of
Python.  Builds for Linux, Mac OS X, Solaris and Windows are made freely
available.

ActivePython includes the Python core and core extensions (zlib 1.2.1,
bzip2 1.0.2, bsddb 4.2.52, Tk 8.4.9, and Tix 8.1.4) and is fully
compatible with other Python distributions of the same version.

ActivePython also includes a wealth of Python documentation, including:
- the core Python docs;
- Andrew Kuchling's What's New in Python series;
- the Non-Programmer's Tutorial for Python;
- Mark Pilgrim's excellent Dive into Python; and
- a snapshot of the Python FAQs, HOWTOs and PEPs.

Once installed on the Mac, you can find the ActivePython documentation
here:
/Library/Documentation/Help/ActivePython 2.4 Help/index.html
An online version of the docs can be found here:
 http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/welcome.html

Thanks, and enjoy!

Trent, Python Tech Lead

-- 
Trent Mick
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Embedding Python in Multi-threading App. Any Guidelines, Hints, Recipes ??

2005-06-07 Thread adsheehan
Hi,

I am embedding Python into a multi-threaded application running on
Solaris. Python will enable end users to customize and re-program many
aspects of the application.

I expect that the C++ application will be natively multi-threaded and
will embed multiple Python sub-interpreters. Called Python scripts may
in turn call back into the C++ application via SWIG  wrappers of C++
objects.

I need advice and/or pointers to relevant documentation on the subject
if available please.

In particular, I need advice on the necessary housekeeping (set/reset
of GIL, PyThreadStates, PyInterpreterStates etc etc) to invoke a
sub-interpreter from a native thread. A native thread may call a number
of sub-interpreters in sequence or recursively (due to call backs) and
I cannot find specific information on this subject area.

Many thanks in advance.

Alan

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


Re: anygui,anydb, any opinions?

2005-06-07 Thread Thomas Bartkus
James Tanis [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 Previously, on Jun 6, Thomas Bartkus said:

 # James Tanis [EMAIL PROTECTED] wrote in message
 # news:[EMAIL PROTECTED]
 # 
 # 
 #  My 2 cents, I'm much more productive with Python and QT Builder as I
 #  am with VB and those aren't nearly as intergrated as VB's GUI/IDE. A
 #  language's productivity, I believe, rests on how high or low-level the
 #  language and its libraries are. Not just that though, productivity is
 #  also very much affected by the breadth of the libraries available.
 #
 # When scripting, Windows or Linux, I also am much more productive with
 # Python.
 # When automating a process for another human being, I am much more
productive
 # with a RAD tool like VB.  The effort involved in creating the user front
end
 # simply overwhelms  all the considerable efficiencies of Python.
 #
 # When I code wxPython, I find I want to use VB to create/model my user
 # interface.  Once I prototype my Windows (Frames!) using VB, I can then
xlate
 # this to wxPython code.  What I couldn't do without the VB IDE was
visualize
 # and experiment with the impact of various layouts *before* I lay down
code.
 # It is simply too onerous to experiment by code manipulation and too easy
to
 # swish around visually with a mouse.
 #
 # When I use a GUI designer like wxGlade, I still find it awkward enough
to
 # merit prototyping with the VB IDE and then mimic the windows I create
with
 # wxGlade.
 #
 #  Sure, GUI RAD solutions increase development in a very real way, but
you
 #  can find an offering for just about every language out there these
days.
 #
 # Yes.  But the tools available for Python are still primitive compared to
RAD
 # tools like Delphi/Visual Studio.  I still don't know enough wxPython to
 # understand what the barriers are to creating a RAD visual design and
 # construction tool similar to the Visual Studio environment.
 # My ravings here are simply the result of a suspicion -
 #
 # - The suspicion is that the only barrier is the Python (and Linux!)
 # communities grossly underestimating the value of such an undertaking.
 # Thomas Bartkus
 #

 Hmm, it's not that simple though. Unfortunately efforts get spread
 among the various projects, wxPython is only one among many.

I realize that.  And I wouldn't consider it unfortunate that efforts are
spread amongs various projects.  It adds richness to the whole environment
but, yes, it does dilute efforts.

 You seem set on wxPython, ...
The attractiveness of wxPython here is that it extends the platform
neutrality of Python to GUI interfaces.  On a Windows platform, the work
looks like any other Windows program.  On Gnome/Linux, the identical code
fits right into the Gnome desktop scheme.  *Big* plus.

But stuck?  There is so much going, there is so little time, and I wallow in
ignorance.  Justification for my ravings is to coax out the experience of
others.  One can't help feeling that one is missing something important
simply because there isn't the time to evaluate everything in depth. And
much of this stuff *needs* to be examined in depth to give it a fair shot.

What neat things am I missing and should be looking at ?

 ... and its true, RAD projects based around that toolkit
 still seem to be in alpha/beta stages, but that does not go for all the
 toolkits. There are no barriers that I know of, but your comparing an
 application (vb) that has been 11+ years with one (wxglade) that has
 been around what.. maybe three years?

Yes.  And I'm sorry to sound like I was complaining (but I was :-)
I'm here because MS is well along it's declining years and I've jumped off
the .NET bandwagon.  New/wonderful things are no longer forthcoming from
that world.  They are in Linux/Python.

Thomas Bartkus


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


Re: If - Or statements

2005-06-07 Thread Patrick Down
What about:

if True in [thefile.endswith(x) for x in
('mp3','mp4','ogg','aac','wma')]:

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


Dr. Dobb's Python-URL! - weekly Python news and links (Jun 7)

2005-06-07 Thread Simon Brunning
QOTW: [expletives deleted] - John Machin, snipping a section of Perl code.

What sort of programmer are you?  If it works on your computer, it's done,
ship it! - Grant Edwards


Guido invites us to comment on PEP 343. This Python Enhancement
Proposal includes a 'with' statement, allowing you simply and
reliably wrap a block of code with entry and exit code, in which
resources can be acquired and released. It also proposes enhancements
to simple generators, making them easy to use to build these wrappers:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a9d9b591ca7b296d

Timothy Smith would like to truncate a Decimal. It's not as easy
as it sounds, but Raymond Hettinger has the definitive solution,
as is so often the case:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/f40d2863110dc81e

If you need to set Windows' environment variables persistently,
Gigi's recipe is what you need:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/416087

EasyInstall, Phillip J. Eby's CPAN clone is ready to go:
http://dirtsimple.org/2005/06/cpan-goodies-for-all.html

How does one check if a given datetime is within a specified
range? Andrew Dalke shows Maksim Kasimov how:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/e186c915a237c9a7

Robert Kern shows how to turn a CSV file into a list of
dictionaries, and Peter Otten shows off a lovely iterator
trick for turning adjacent list entries into dictionary elements:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/ed07b9f71724dcbd

Ryan Tomayko defends the LAMP (Linux, Apache, MySQL,
Python/Perl/PHP) platform:
http://naeblis.cx/rtomayko/2005/05/28/ibm-poop-heads

Skip Montanaro tells us why Emacs is the perfect IDE for him:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/6df813d2d8d187fb#8438e5f0d2352e5f

O'Reilly has published a couple of interesting articles by
Jeremy Jones, Python Standard Logging and  Writing Google
Desktop Search Plugins:
http://www.onlamp.com/pub/a/python/2005/06/02/logging.html
http://www.onlamp.com/pub/a/python/2005/06/01/kongulo.html

How can you reliably eradicate data from a hard disk? Nuke the
site from orbit; it's the only way to be sure.

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/2e73c88596c35427

Tomasz Bieruta shows us how to sort large files:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/415581

Google's new Sitemaps allow a Webmaster to tell Google what to
spider. They provide a Python script to get you started: 

https://www.google.com/webmasters/sitemaps/docs/en/sitemap-generator.html


Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily  
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html 
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

For far, FAR more Python reading than any one mind should
absorb, much of it quite interesting, several pages index
much of the universe of Pybloggers.
http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog
http://www.planetpython.org/
http://mechanicalcat.net/pyblagg.html

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djqas_ugroup=comp.lang.python.announce

Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous
tradition early borne by Andrew Kuchling, Michael Hudson and Brett
Cannon of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/   

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

The Python Business Forum further[s] the interests of companies
that 

School Administration Software

2005-06-07 Thread Greg Lindstrom
Hello-

I just picked up my daughters' report cards for the year (they did well, 
thank-you) and was approached by the school administrator about writing 
an Acess application to help track attendance for next year 
(excused/unexcused, after so many unexcused absences a letter will be 
generated, etc.).  Since I have a feel for how large this request will 
become, I googled for school administration software on the Python site 
and was pleased to get 312 hits.  There's software out there but -- 
alas -- it's difficult to tell what is being used, what people think, 
what's being maintained, etc. 

So...do any of you have experience with any of this software?  This is 
for a small (~400 students k-12), private school that is not swimming in 
taxpayer dollars and I would rather use Open Source because we will 
probably need to customize some reports, etc.  Any advice you have would 
be welcome.

Thanks,
--greg

-- 
Greg Lindstrom   501 975.4859 (office)
Senior Programmer501 219-4455 (fax)
NovaSys Health   [EMAIL PROTECTED]
Little Rock, Arkansas

We are the music makers, and we are the dreamers of dreams.  W.W.


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


time consuming loops over lists

2005-06-07 Thread querypk
X-No-Archive: yes
Can some one help me improve this block of code...this jus converts the
list of data into tokens based on the range it falls into...but it
takes a long time.Can someone tell me what can i change to improve
it...

def Tkz(tk,data):
 no_of_bins = 10
 tkns = []
 dmax = max(data)+1
 dmin = min(data)
 rng = ceil(abs((dmax - dmin)/(no_of_bins*1.0)))
 rngs = zeros(no_of_bins+1)
 for i in xrange(no_of_bins+1):
  rngs[i] = dmin + (rng*i)
 for i in xrange(len(data)):
  for j in xrange(len(rngs)-1):
   if data[i] in xrange(rngs[j],rngs[j+1]):
tkns.append( str(tk)+str(j) )
 return tkns

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


Re: time consuming loops over lists

2005-06-07 Thread Diez B. Roggisch

[EMAIL PROTECTED] wrote:

X-No-Archive: yes
Can some one help me improve this block of code...this jus converts the
list of data into tokens based on the range it falls into...but it
takes a long time.Can someone tell me what can i change to improve
it...





   if data[i] in xrange(rngs[j],rngs[j+1]):



That's a bummer: You create a list and then search linearily in in - 
where all you want to know is


if rngs[j] = data[i]  rngs[j+1]

Attached is a script that does contain  your old and my enhanced version 
- and shows that the results are equal. Running only your version takes 
~35s, where mine uses ~1s!!!


Another optimization im too lazy now would be to do sort of a tree 
search of data[i] in rngs - as the ranges are ordered, you could find 
the proper one in log_2(len(rngs)) instead of len(rngs)/2.


Additional improvements can be achieved when data is sorted - but that 
depends on your application and actually sizes of data.


Diez
from math import *
from Numeric import *
from random import *
def Tkz2(tk,data):
 no_of_bins = 10
 tkns = []
 dmax = max(data)+1
 dmin = min(data)
 rng = ceil(abs((dmax - dmin)/(no_of_bins*1.0)))
 rngs = zeros(no_of_bins+1)
 for i in xrange(no_of_bins+1):
  rngs[i] = dmin + (rng*i)
 for i in xrange(len(data)):
  for j in xrange(len(rngs)-1):
   if rngs[j] = data[i]  rngs[j+1]:
tkns.append( str(tk)+str(j) )
 return tkns

def Tkz(tk,data):
 no_of_bins = 10
 tkns = []
 dmax = max(data)+1
 dmin = min(data)
 rng = ceil(abs((dmax - dmin)/(no_of_bins*1.0)))
 rngs = zeros(no_of_bins+1)
 for i in xrange(no_of_bins+1):
  rngs[i] = dmin + (rng*i)
 for i in xrange(len(data)):
  for j in xrange(len(rngs)-1):
   if data[i] in xrange(rngs[j], rngs[j+1]):
tkns.append( str(tk)+str(j) )
 return tkns


data = range(20,12312)
shuffle(data)
res1 = Tkz('A', data)
res2 = Tkz2('A', data)

print res1 == res2
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How do I know when a thread quits?

2005-06-07 Thread dowskimania
I'm no threads expert, but if you use the higher-level threading
module, you could try something like this:

import threading
import time

def countToTen():
for i in range(1,11):
print i
time.sleep(0.5)

child = threading.Thread(target=countToTen)

class masterThread(threading.Thread):
def run(self):
print Master Started
child.start()
while child.isAlive():
time.sleep(0.1)
print Master Finished

master = masterThread()
master.start()

---SCRIPT OUTPUT--

Master Started
1
2
3
4
5
6
7
8
9
10
Master Finished

Hope this helps.

Christian
http://www.dowski.com

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


Re: Reading a CSV file into a list of dictionaries

2005-06-07 Thread GMane Python
Sounds like you want to use the ConfigObject module.

http://www.voidspace.org.uk/python/modules.shtml#configobj

-dave

RFQ [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 Hi, I'm struggling here to do the following with any success:

 I have a comma delimited file where each line in the file is something
 like:

 PNumber,3056,Contractor,XYZ Contracting,Architect,ABC Architects,...

 So each line is intended to be: key1,value1,key2,value2,key3,value3...
 and each line is to be variable in length (although it will have to be
 an even number of records so that each key has a value).

 I want to read in this csv file and parse it into a list of
 dictionaries. So each record in the list is a dictionary:

 {PNumber:3056,Contractor:XYZ Contracting, ... }

 I have no problem reading in the CSV file to a list and splitting each
 line in the file into its comma separated values. But I can't figure
 out how to parse each resulting list into a dictionary.

 Any help on this?

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




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


Re: time consuming loops over lists

2005-06-07 Thread querypk
wow i dint know that a single statement like that would make such a
difference. Thanks you very much. that really improves the performance

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


Re: time consuming loops over lists

2005-06-07 Thread Peter Otten
[EMAIL PROTECTED] wrote:

 Can some one help me improve this block of code...this jus converts the
 list of data into tokens based on the range it falls into...but it
 takes a long time.Can someone tell me what can i change to improve
 it...
 
 def Tkz(tk,data):
  no_of_bins = 10
  tkns = []
  dmax = max(data)+1
  dmin = min(data)
  rng = ceil(abs((dmax - dmin)/(no_of_bins*1.0)))
  rngs = zeros(no_of_bins+1)
  for i in xrange(no_of_bins+1):
   rngs[i] = dmin + (rng*i)
  for i in xrange(len(data)):
   for j in xrange(len(rngs)-1):
if data[i] in xrange(rngs[j],rngs[j+1]):
 tkns.append( str(tk)+str(j) )
  return tkns

Use bisect(), e. g., with a slightly modified function signature:

from __future__ import division
import bisect
from math import ceil

def tkz(tk, data, no_of_bins=10):
dmax = max(data) + 1
dmin = min(data)
rng = ceil((dmax - dmin)/no_of_bins)
rngs = [dmin + rng*i for i in xrange(1, no_of_bins+1)]
tokens = [tk + str(i) for i in xrange(no_of_bins)]
return [tokens[bisect.bisect(rngs, v)] for v in data]

if __name__ == __main__:
print tkz(token_, [5, 7, 8, 9, 70, 200])

What are the tokens for, by the way? I'd recommend using the indices
directly if possible.

Peter

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


Re: School Administration Software

2005-06-07 Thread [EMAIL PROTECTED]
Greg Lindstrom wrote:
 Hello-

[snip]
 So...do any of you have experience with any of this software?  This is
 for a small (~400 students k-12), private school that is not swimming in
 taxpayer dollars and I would rather use Open Source because we will
 probably need to customize some reports, etc.  Any advice you have would
 be welcome.

 Thanks,
 --greg

 --
 Greg Lindstrom   501 975.4859 (office)
 Senior Programmer501 219-4455 (fax)
 NovaSys Health   [EMAIL PROTECTED]
 Little Rock, Arkansas

Schooltool ?
http://www.schooltool.org/
 We are the music makers, and we are the dreamers of dreams.  W.W.

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


xmlrpclib - methodHelp doesn't work

2005-06-07 Thread [EMAIL PROTECTED]
I tried out the examples in this website for XML-RPC using python -
http://www.onlamp.com/pub/a/python/2000/11/22/xmlrpcclient.html?page=2
But I get the following errors when I try to execute the code. Here is
the snippet of the code with the error messages.

snip

 meerkatsvr.system.methodSignature(meerkat.getChannels)
Traceback (most recent call last):
  File stdin, line 1, in ?
NameError: name 'meerkat' is not defined
 meerkatsvr.system.methodHelp(meerkat.getItems)
Traceback (most recent call last):
  File stdin, line 1, in ?
NameError: name 'meerkat' is not defined

/snip

can someone tell me what is wrong.

Also is there any good online resource for XML-RPC with Python.

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


DB API 2.0 and transactions

2005-06-07 Thread Christopher J. Bottaro
Hi,
Why is there no support for explicit transactions in the DB API?  I mean
like transaction() to start the trans and commit() and rollback() would end
the trans or something.

The reason why I ask is because I wrote a daemon that interacts with a
Postgres DB.  The value of CURRENT_TIMESTAMP according to Postgres is NOT
the actual walltime, but the walltime when the current transaction started.

This gets weird when using the Python DB API to interact with Postgres
because a transaction gets started in 3 places:  connection, commit,
rollback.

So consider the daemon:

[pseudo code]
connect # begin trans at 12:00
sleep waiting # lets say 15 mins
wake up
put entry in db using CURRENT_TIMESTAMP # oops
[/code]

Oops, the CURRENT_TIMESTAMP evaluates to 12:00, not 12:15.

Now I know there are ways around this...
1)  In Postgres, you can get the walltime and cast it to a timestamp.
2)  In Python, you can just do an empty commit in order to manually start
a new transaction.

I just think its a bit weird because this bit me in the butt for quite a
while and this didn't happen when doing the same thing in other langs.

Anyone have any opinions on this?

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


Re: xmlrpclib - methodHelp doesn't work

2005-06-07 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
 I tried out the examples in this website for XML-RPC using python -
 http://www.onlamp.com/pub/a/python/2000/11/22/xmlrpcclient.html?page=2
 But I get the following errors when I try to execute the code. Here is
 the snippet of the code with the error messages.

meerkatsvr.system.methodSignature(meerkat.getChannels)
 
 Traceback (most recent call last):
   File stdin, line 1, in ?
 NameError: name 'meerkat' is not defined
 
meerkatsvr.system.methodHelp(meerkat.getItems)
 
 Traceback (most recent call last):
   File stdin, line 1, in ?
 NameError: name 'meerkat' is not defined

You have to give the method names as strings. Your code is looking for a 
'getChannels' or 'getItems' attribute of something named 'meerkat', but there 
is no such name in the current scope. Try this:

Type help, copyright, credits or license for more information.
  import xmlrpclib
  meerkatURI = http://www.oreillynet.com/meerkat/xml-rpc/server.php;
  meerkatsvr = xmlrpclib.Server(meerkatURI)
  meerkatsvr.system.listMethods()
['meerkat.getChannels', 'meerkat.getCategories', 
'meerkat.getCategoriesBySubstring', 'meerkat.getChannelsByCategory', 
'meerkat.getChannelsBySubstring', 'meerkat.getItems', 'system.listMethods', 
'system.methodHelp', 'system.methodSignature']
  print meerkatsvr.system.methodSignature('meerkat.getChannels')
[['array']]
  print meerkatsvr.system.methodHelp('meerkat.getItems')
Returns an array of structs of RSS items given a recipe struct.
etc

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


Re: What are OOP's Jargons and Complexities?

2005-06-07 Thread Xah Lee
The Rise of Class Hierarchy

Because of psychological push for purity, in Java there are no longer
plain subroutines. Everything is a method of some class. Standard
functions like opening a file, square root a number, for loop thru a
list, if else branching statements, or simple arithmetic operations...
must now somehow become a method of some class. In this way, coupled
with the all-important need to manage data with inheritance, the OOP
Class Hierarchy is born.

Basic data types such as now the various classes of numbers, are now
grouped into a Number class hierarchy, each class having their own set
of methods. The characters, string or other data types, are lumped into
one hierarchy class of data types. Many types of lists (variously known
as arrays, vectors, lists, hashes...), are lumped into a one hierarchy,
with each Classe node having its own set methods as appropriate. Math
functions, are lumped into some math class hierarchy.

Now suppose the plus operation +, where does it go? Should it become
methods of the various classes under Number headings, or should it be
methods of the Math class set? Each language deals with these issues
differently. As a example, see this page for the hierarchy of Java's
core language classes:
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/package-tree.html
(local copy)

OOP being inherently complex exacerbated by marketing propaganda, and
the inheritance and hierarchy concept is so entangled in OOP, sometimes
OOP is erroneously thought of as languages with a hierarchy. (there are
now also so-called Object-Oriented databases that ride the fad of
all data are trees ...)

Normally in a program, when we want to do some operation we just call
the subroutine on some data. Such as
open(this_file)
square(4)

But now with the pure OOP style, there can no longer be just a number
or this_file path, because everything now must be a Object. So, the
this_file, usually being just a string representing the path to a
file on the disk, is now some file object. Initiated by something
like
this_file = new File(path to file);

where this file class has a bunch of methods such as reading or writing
to it.

see this page for the complexity of the IO tree
http://java.sun.com/j2se/1.4.2/docs/api/java/io/package-tree.html
(local copy)

see this page for the documentation of the File class itself, along
with its 40 or so methods and other things.
http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html (local copy)

---
to be continued...

This is part of an installment of the article
What are OOP's Jargons and Complexities
by Xah Lee, 20050128. The full text is at
 http://xahlee.org/Periodic_dosage_dir/t2/oop.html

 Copyright 2005 by Xah Lee. Verbatim duplication of the complete
article for non-profit purposes is granted.

The article is published in the following newsgroups:
comp.lang.c,comp.lang.c++,comp.lang.lisp,comp.unix.programmer
comp.lang.python,comp.lang.perl.misc,comp.lang.scheme,comp.lang.java.programmer
comp.lang.functional,comp.object,comp.software-eng,comp.software.patterns

 Xah
 [EMAIL PROTECTED]
 http://xahlee.org/

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

different time tuple format

2005-06-07 Thread Maksim Kasimov
hi all, sorry if i'm reposting

why time.strptime and time.localtime returns tuple with different DST (9 item 
of the tuple)?
is there some of setting to fix the problem?


Python 2.2.3 (#1, May 31 2005, 11:33:52)
[GCC 2.95.4 20020320 [FreeBSD]] on freebsd4
Type help, copyright, credits or license for more information.
  import time
  time.strptime(2005-06-07 21:00:00, %Y-%m-%d %H:%M:%S)
(2005, 6, 7, 21, 0, 0, 6, 1, 0)
  time.localtime()
(2005, 6, 7, 21, 2, 39, 1, 158, 1)
 


-- 
Best regards,
Maksim Kasimov
mailto: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


How to call python functions from matlab?

2005-06-07 Thread sdhyok
PyMat enables to call matlab functions from python.
But, what I want is  to call python functions from matlab.
Is there any library for it? Thanks.

Daehyok Shin

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


How to maintain scroll-region view while changing canvas size?

2005-06-07 Thread syed_saqib_ali


Please take a look at and run the code snippet shown below.

It creates a canvas with vertical  Horizontal scroll-bars.
If you shrink the window to smaller than the area of the canvas, the
scroll-bars work as advertised. That's great.

However, if you click the Left Mouse button, it calls code which
expands the width of the canvas by 100 pixels. The area being viewed
expands correspondingly. BUT I DON'T WANT IT TO!!

I want to know how to expand the size of a canvas without changing the
area/size of what is currently shown by the scroll bars. I would like
to find code that expands the width of the canvas and simply adjusts
the H-Scrollbar without changing what is shown on in the area of the
canvas being displayed.

I have tried seemingly every combination of messing with the
canvas.config and scrollregion parameters to no avail. Can someone out
there show me how its done??

-Saqib






-
import Tkinter

def _b1PressEvt(event):
print B1
_canvas.config(width=300)


tkRoot = Tkinter.Tk()
_canvas = Tkinter.Canvas(tkRoot, background=white, width=200,
height=200,)


# Scroll Bars
vScrollbar = Tkinter.Scrollbar(tkRoot)
vScrollbar.pack(side=Tkinter.RIGHT, expand=True, fill=Tkinter.Y)

hScrollbar = Tkinter.Scrollbar(tkRoot)
hScrollbar.pack(side=Tkinter.BOTTOM, expand=True, fill=Tkinter.X)


_canvas.config(
width=200,
height=200,
scrollregion=(0,0,100,100),
yscrollcommand=vScrollbar.set,
xscrollcommand=hScrollbar.set,
)

vScrollbar.config(orient=Tkinter.VERTICAL, command=_canvas.yview)
hScrollbar.config(orient=Tkinter.HORIZONTAL, command=_canvas.xview)

#tkRoot.pack()
_canvas.pack(expand=Tkinter.NO)
vScrollbar.pack(side=Tkinter.RIGHT, expand=True, fill=Tkinter.Y)
hScrollbar.pack(side=Tkinter.BOTTOM, expand=True, fill=Tkinter.X)


# Function Bindings
_canvas.bind(Button-1, _b1PressEvt)


tkRoot.mainloop()

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


Re: Create our own python source repository

2005-06-07 Thread qwweeeit
Hi Rob,
thank you for your reply. I am further commenting on your doubts (I'm
not entirely sure what the point of your exercise is) and on your
proposal of a project for more structured tutorials.

About the second item, I fully agree with you. I should be even more
drastic: for a certain argument I'd prefer an application fully
explained (also if not covering all the features) to a more general
tutorial with only brief and unrelated code snippets.
Unfortunately, that's not the way things are normally done, because it
is much harder to build a useful application and fully comment it (also
from the theoretical point of view, like, for example, OO or database
management)

As far as the 1st item is concerned, I know that Cookbook Python is
frequently updated, but for my purposes also a freezed situation is
OK, and grepping is much more useful than googling over the web.
For that reason I want also add to the repository my examples of
Python scripts, to build on already known tools.
To give an example, the other day I wanted to use writelines() to
save a list to a file. Having already used such a file method, but not
remembering where and when, I was obliged to consult the Library
Reference for the sintax and  for the type of list instead of merely
cutting and pasting from my code...
Bye.

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


Re: different time tuple format

2005-06-07 Thread [EMAIL PROTECTED]
http://docs.python.org/lib/module-time.html tells us the last element
is the DST flag, on your computer that applies for localtime(). To get
this with strptime() you have to tweak the %Z formatter - this is
platform specific.

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


Re: poker card game revisited (code included)

2005-06-07 Thread Erik Max Francis
flupke wrote:

 i've included the code so people can take a look.
 I've tried to expand on the thread of 26/05/2005 on Checking for a full
 house. Code is suboptimal as I coded it rather quickly.
 I've added the normal classes one would expect from a cardgame: card,
 deck, hand etc.
 
 1. I can detect most things except a straightflush. The problem with the
 code now is that it only returns 1 straight which is enough for mere
 straight detection but won't suffice for hand comparison and
 especially detecting straight flushes. For use in straight flush
 detection, the function would need to return all possible straights and
 then these would need to be checked to see if they are flushes.
 For instance a list [4,4,5,5,6,7,8] yields 4 different straights.
 A hand like [4,4,5,5,6,7,8,9] gets even worse.
 I can't see how i can do this using sets, i'll need to come up with
 another method since the suit is important.
 
 2. Hand comparison.
 For this to succeed the getrank function would need to return the exact
 5 cards that represent the highest hand. This could be less than 5 cards
 if one uses wildcards. Then you not only have the correct rank but also
 the highest hand so you can compare in case there are ties.

It looks like you're not approaching this in a systematic manner. 
Algorithms for determining poker hands are already pretty well-known; 
there are several open source projects that do it efficiently which you 
could learn from.

When you're evaluating poker hands, you're looking for three basic types 
of card groups:  matches, straights, and flushes.  The most efficient 
way to look for matches is with a histogram based on the card rank.  Bin 
the cards up by rank, and then build a second histogram of the counts 
of those ranks indexing into a list of the ranks which had those cards 
(sorted by rank, so you can pull off the highest ones).  Now determining 
all the rank-based hands is easy:  quads have a hit with four matches, a 
boat has a hit with two three matches (there's no two trips so this is 
a boat at best) or both three and two matches, two pair has two hits 
with two matches, etc.

Searching for straights and flushes is much better done by masks. 
Arrange all the possible cards in a huge masks based on both cards and 
ranks (easy to do in Python with the long type) and then build up rank 
masks that build up all possible straight combinations (sorted by the 
highest rank so you can search them in order), and then build up card 
mask ranks for each suit.  For straights, just iterate through the 
straight rank masks and see if you find one that's fully occupied; if 
you do, that's a straight.  For flushes, just iterate through the card 
suit masks and see if you find one that has more five or more unique 
cards in it.  You need to iterate through all four and find the one with 
the highest value (for games with lots of cards, you could have two 
flushes; you want to count the highest one).  Finally, to look for 
straight flushes, first apply the suit masks and then turn it into ranks 
and apply the straight masks.

Then will all this information you can easily arrange the code to select 
the best existing hand.  Note that these all use well-established 
techniques and reveal nothing secret.

 3. x wild.
 For games like deuces wild, what would be the best way to manage
 those? I tought about removing them from a hand before shipping it of to
 the getrank function?

I'll leave it up to you to try to figure out how to make a wild card 
algorithm.

-- 
Erik Max Francis  [EMAIL PROTECTED]  http://www.alcyone.com/max/
San Jose, CA, USA  37 20 N 121 53 W  AIM erikmaxfrancis
   Love is the selfishness of two persons.
   -- Antoine de la Salle
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: different time tuple format

2005-06-07 Thread Rick Holbert
Like the last poster said, use %Z.  On my Mandriva Linux system I get the
following results:

 time.localtime()
(2005, 6, 7, 15, 7, 12, 1, 158, 1)
 time.strptime(2005-06-07 15:07:12 EDT, %Y-%m-%d %H:%M:%S %Z)
(2005, 6, 7, 15, 7, 12, 1, 158, 1)

Rick

Maksim Kasimov wrote:

 hi all, sorry if i'm reposting
 
 why time.strptime and time.localtime returns tuple with different DST (9
 item of the tuple)? is there some of setting to fix the problem?
 
 
 Python 2.2.3 (#1, May 31 2005, 11:33:52)
 [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4
 Type help, copyright, credits or license for more information.
   import time
   time.strptime(2005-06-07 21:00:00, %Y-%m-%d %H:%M:%S)
 (2005, 6, 7, 21, 0, 0, 6, 1, 0)
   time.localtime()
 (2005, 6, 7, 21, 2, 39, 1, 158, 1)
  
 
 

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


Re: the python way?

2005-06-07 Thread Reinhold Birkenfeld
Andrew Dalke wrote:
 Reinhold Birkenfeld wrote:
 To make it short, my version is:
 
 import random
 def reinterpolate2(word, vocals='aeiouy'):
 wlist = list(word)
 random.shuffle(wlist)
 vees = [c for c in wlist[::-1] if c in vocals]
 cons = [c for c in wlist[::-1] if c not in vocals]
 
 Why the [::-1]?  If it's randomly shuffled the order isn't important.

I wanted to keep compatibility with Groops' version so that I could test
that my one works right. Since he did list.pop() it was necessary.

 short, long = sorted((cons, vees), key=len)
 return ''.join(long[i] + short[i] for i in range(len(short))) + 
 ''.join(long[len(short):])
 
 All the cool kids are using 2.4 these days.  :)

Yep, it's the best way to advertise for its cool features ;)


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


programmnig advise needed

2005-06-07 Thread mitsura
Hi,

I am writing a Python program that needs to read XML files and contruct
a tree object from the XML file (using wxTree).
The XML however is not an hiearchical XML file. It contains elements
and association tags. The assiociation tags link the elements
together.
Example:
element1
  ... element 1 attributes
/element1
element2
  ... element 2 attributes
/element2
element3
  ... element 3 attributes
/element3
association
 Nameelement1/Name
 Parentelement3/Parent
/association
association
 Nameelement2/Name
 Parentelement3/Parent
/association

In this case element3 is the parent of the two other elements.
The XML files I receive often contain thousands of elements so the tree
structure can be very large. Futhermore, the XML files are not
'sorted', like in the example above, the 'root' element object entry
might be somewhere in the middle of the XML file.

I don't really now to code this so any suggestions are welcome.

With kind regards,

Kris

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


Re: DB API 2.0 and transactions

2005-06-07 Thread vincent wehren
Christopher J. Bottaro [EMAIL PROTECTED] schrieb im
Newsbeitrag news:[EMAIL PROTECTED]
| Hi,
| Why is there no support for explicit transactions in the DB API?  I mean
| like transaction() to start the trans and commit() and rollback() would
end
| the trans or something.
|
| The reason why I ask is because I wrote a daemon that interacts with a
| Postgres DB.  The value of CURRENT_TIMESTAMP according to Postgres is NOT
| the actual walltime, but the walltime when the current transaction
started.
|
| This gets weird when using the Python DB API to interact with Postgres
| because a transaction gets started in 3 places:  connection, commit,
| rollback.
|
| So consider the daemon:
|
| [pseudo code]
| connect # begin trans at 12:00
| sleep waiting # lets say 15 mins
| wake up
| put entry in db using CURRENT_TIMESTAMP # oops
| [/code]
|
| Oops, the CURRENT_TIMESTAMP evaluates to 12:00, not 12:15.
|
| Now I know there are ways around this...
| 1)  In Postgres, you can get the walltime and cast it to a timestamp.
| 2)  In Python, you can just do an empty commit in order to manually
start
| a new transaction.
|
| I just think its a bit weird because this bit me in the butt for quite a
| while and this didn't happen when doing the same thing in other langs.
|
| Anyone have any opinions on this?

The described behavior seems to be totally in synch with expectations

(both in accordance with PostgreSQL docs and the DB-API.)

These other languages *must* be doing something wrong! ;)

( Auto-commit set to on perhaps? )



Regards,

-

Vincent Wehren


|



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


Re: different time tuple format

2005-06-07 Thread Maksim Kasimov
Rick Holbert wrote:
 Like the last poster said, use %Z.  On my Mandriva Linux system I get the
 following results:
 
 
time.localtime()
 
 (2005, 6, 7, 15, 7, 12, 1, 158, 1)
 
time.strptime(2005-06-07 15:07:12 EDT, %Y-%m-%d %H:%M:%S %Z)
  (2005, 6, 7, 15, 7, 12, 1, 158, 1)

does not work at all: ValueError: format mismatch

i've check the value of time.tzname:
('EET', 'EEST')

and get the following (again):

  time.strptime(2005-06-07 15:07:12 EET, %Y-%m-%d %H:%M:%S %Z)
(2005, 6, 7, 15, 7, 12, 6, 1, 0)









-- 
Best regards,
Maksim Kasimov
mailto: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: split up a list by condition?

2005-06-07 Thread Reinhold Birkenfeld
Raymond Hettinger wrote:
 while writing my solution for The python way?, I came across this 
 fragment:
 vees = [c for c in wlist[::-1] if c in vocals]
 cons = [c for c in wlist[::-1] if c not in vocals]

 So I think: Have I overlooked a function which splits up a sequence
 into two,  based on a condition
 
 Trying to compress too much into one line is not the python way ;-)

I know (there is a Guido quote about this, I just lost the source...)

 vees, cons = [], []
 for c in reversed(wlist):
 if c in vocals:
 vees.append(c)
 else:
 cons.append(c)
 

Well, I've found a uglier solution,

vees, cons = [], []
[(vees, cons)[ch in vocals].append(ch) for ch in wlist]

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


Re: split up a list by condition?

2005-06-07 Thread Reinhold Birkenfeld
Duncan Booth wrote:
 Reinhold Birkenfeld wrote:
 
 Hi,
 
 while writing my solution for The python way?, I came across this
 fragment: 
 
 vees = [c for c in wlist[::-1] if c in vocals]
 cons = [c for c in wlist[::-1] if c not in vocals]
 
 So I think: Have I overlooked a function which splits up a sequence
 into two, based on a condition? Such as
 
 vees, cons = split(wlist[::-1], lambda c: c in vocals)
 
 Reinhold
 
 If you really are being charged by the number of newline characters in your 
 code you could write:

[...]

 but every penny you save writing a one liner will be tuppence extra on 
 maintenance.

This is clear. I actually wanted to know if there is a function which I
overlooked which does that, which wouldn't be a maintenance nightmare at all.

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


Re: different time tuple format

2005-06-07 Thread [EMAIL PROTECTED]
In your case it is the EEST, as this is the DST timezone (see again:
http://docs.python.org/lib/module-time.html)

** [EMAIL PROTECTED]:~ $ python
** Python 2.4.1 (#2, Mar 30 2005, 21:51:10)
** [GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2
** Type help, copyright, credits or license for more
information.
**  import time
**  print time.tzname
** ('CET', 'CEST')
**  time.strptime(2005-06-07 15:07:12 CET, %Y-%m-%d %H:%M:%S %Z)
** (2005, 6, 7, 15, 7, 12, 1, 158, 0)
**  time.strptime(2005-06-07 15:07:12 CEST, %Y-%m-%d %H:%M:%S
%Z)
** (2005, 6, 7, 15, 7, 12, 1, 158, 1)
** 

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


Re: Wxpython demo crashes

2005-06-07 Thread Greg Krohn
Pekka Karjalainen wrote:
 I'm using WinXP (Finnish), Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC
 v.1310 32 bit (Intel)] on win32 and wxPython 2.6.0.1.
 
 When I go to the Process and Events section in the wxDemo and run the
 Process demo, bad things can happen. It crashes. I think the crash is
 caused by characters outside the basic ASCII range, but I haven't tested
 it in detail. 

Do you have the unicode version of wxPython?

http://prdownloads.sourceforge.net/wxpython/wxPython2.6-win32-unicode-2.6.1.0-py24.exe
   ^^^
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading a CSV file into a list of dictionaries

2005-06-07 Thread Laurent RAHUEL
RFQ wrote:

 Hi, I'm struggling here to do the following with any success:
 
 I have a comma delimited file where each line in the file is something
 like:
 
 PNumber,3056,Contractor,XYZ Contracting,Architect,ABC Architects,...

This is NOT a CSV file. A CSV file would be :

PNumber,Contractor,Architect,...
2056,XYZ Contracting,ABC Architects,...

Then, you could use the built-in CSV module of recent python versions.

 
 So each line is intended to be: key1,value1,key2,value2,key3,value3...
 and each line is to be variable in length (although it will have to be
 an even number of records so that each key has a value).
 
 I want to read in this csv file and parse it into a list of
 dictionaries. So each record in the list is a dictionary:
 
 {PNumber:3056,Contractor:XYZ Contracting, ... }
 
 I have no problem reading in the CSV file to a list and splitting each
 line in the file into its comma separated values. But I can't figure
 out how to parse each resulting list into a dictionary.
 
 Any help on this?

By,

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


Re: split up a list by condition?

2005-06-07 Thread Grooooops
 vees, cons = [], []
 [(vees, cons)[ch in vocals].append(ch) for ch in wlist]

Wow, that's horribly twisted Reinhold...
I spent about an hour last night trying something similar, to no end...
:)

Neat tricks people...
I like Duncan's use of or to solve it.
I didn't see that in the python docs on list comprehension.
Very cool.

There is a special place in my heart for obfuscated Python,
but of course, not in production code if there is a clearer solution
available.

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


Re: Trouble Encoding

2005-06-07 Thread fingermark
why is it even trying latin-1 at all?  I don't see it anywhere in
feedparser.py or my code.

deelan wrote:
 [EMAIL PROTECTED] wrote:
  I'm using feedparser to parse the following:
 
  div class=indent textAdv: Termite Inspections! Jenny Moyer welcomes
  you to her HomeFinderResource.com TM A MUST See amp;hellip;/div
 
  I'm receiveing the following error when i try to print the feedparser
  parsing of the above text:
 
  UnicodeEncodeError: 'latin-1' codec can't encode character u'\u201c' in
  position 86: ordinal not in range(256)
 
  Why is this happening and where does the problem lie?

 it seems that the unicode character 0x201c isn't part
 of the latin-1 charset, see:

 LEFT DOUBLE QUOTATION MARK
 http://www.fileformat.info/info/unicode/char/201c/index.htm

 try to encode the feedparser output to UTF-8 instead, or
 use the replace option for the encode() method.

   c = u'\u201c'
   c
 u'\u201c'
   c.encode('utf-8')
 '\xe2\x80\x9c'
   print c.encode('utf-8')

 ok, let's try replace

   c.encode('latin-1', 'replace')
 '?'

 using replace will not throw an error, but it will replace
 the offending characther with a question mark.
 
 HTH.
 
 -- 
 deelan http://www.deelan.com/

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


Re: Help with SMTP

2005-06-07 Thread Ivan Shevanski
Ok, all my problems are solved except for one. . .If I want my program to 
send a message back to me do I need the from adress? Because I don't 
specifically know it for the person using the program.  Any help is 
appreciated =D




-Ivan

_
FREE pop-up blocking with the new MSN Toolbar – get it now! 
http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/


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

Re: Reading a CSV file into a list of dictionaries

2005-06-07 Thread John Machin
Laurent RAHUEL wrote:
 RFQ wrote:
 
 
Hi, I'm struggling here to do the following with any success:

I have a comma delimited file where each line in the file is something
like:

PNumber,3056,Contractor,XYZ Contracting,Architect,ABC Architects,...
 
 
 This is NOT a CSV file. A CSV file would be :
 
 PNumber,Contractor,Architect,...
 2056,XYZ Contracting,ABC Architects,...
 

CSV is an acronym for Comma-Separated Values. It does not imply 
anything about the contents of the fields. The OP's file *is* a CSV 
file. Yes, the contents do represent an unusual application of the CSV 
format -- however a bus full of parcels instead of people is still a bus.

 Then, you could use the built-in CSV module of recent python versions.

Python is a case-sensitive language. The name of the module is csv. 
The OP could use the csv module with his data.
-- 
http://mail.python.org/mailman/listinfo/python-list


import error using BOOST in linux

2005-06-07 Thread GujuBoy
i am using BOOST in linux with python and i can compile my CPP file
just fine to make a .so but everytime i do a import i get this error

 import dirgesh
Traceback (most recent call last):
  File stdin, line 1, in ?
ImportError: libboost_python.so.1.32.0: cannot open shared object file:
No such file or directory


i also tried putting the libboost_python.so.1.32.0 file in the
/usr/lib/python2.3 dir.

please help

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


Re: ANN: ActivePython 2.4.1 for Mac OS X is now available!

2005-06-07 Thread Trent Mick
 Trent Mick wrote:
 Meanwhile, some of you may be interested to know that we are busily
 working on bringing Komodo to Mac OS X. We expect to offer a beta in
 August and release later this year.

[John Abel wrote]
 Komodo for OSX?  Now that's something I would be interested in
 purchasing.

We're workin' on it. :)

Trent

-- 
Trent Mick
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trouble Encoding

2005-06-07 Thread Jarek Zgoda
[EMAIL PROTECTED] napisa(a):

 why is it even trying latin-1 at all?  I don't see it anywhere in
 feedparser.py or my code.

Check your site.py or sitecustomize.py module, you can have non-standard 
default encoding set there.

-- 
Jarek Zgoda
http://jpa.berlios.de/ | http://www.zgodowie.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: separate IE instances?

2005-06-07 Thread J Correia
 Chris Curvey [EMAIL PROTECTED] wrote in message
 news:[EMAIL PROTECTED]
  I would have given up on this a long time ago, but I can create two
  IEXPLORE processes simultaneously (and get the behavior I want) by just
  manually launching them from the Start menu.   (Of course, that doesn't
  mean that I can launch them programmatically, but I'm hoping that
  someone can give me a definitive answer.)
 

J Correia [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 Right, I hadn't quite understood your problem when I posted my reply.  The
code
 posted does work and allow navigation, etc. but you do have the problem with
it
 sharing the same session cookies (I'm also on Win2k).  And to answer Martin,
you
 can definitely create as many iexplore.exe instances as you like in Windows.

 How to get Python to launch several instances with COM... not sure, although
I'm
 99% certain it is doable.  I'll hunt around and see if I can find a solution
 which I'll post back.

A very quick and very, very dirty method which might work is to start up
the instances as follows:
import win32api
a = win32api.ShellExecute(0,None,iexplore.exe,None,None,1)
b = win32api.ShellExecute(0,None,iexplore.exe,None,None,1)
 This creates the 2 instances of iexplore.exe in Windows you're looking for.

Then use code like this to attach to the already running instances:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/269345

Haven't tried it because I'm certain there's a much more elegant solution, but
depending on how quickly you need to get going it might be a possible short term
work around until someone posts the better way.  Perhaps you can also post some
more info on what you're actually trying to achieve... make it easier for
someone to
help or even suggest alternatives.

JC





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


Re: split up a list by condition?

2005-06-07 Thread Andrew Dalke
Reinhold Birkenfeld wrote:
 So I think: Have I overlooked a function which splits up a sequence
 into two, based on a condition? Such as
 
 vees, cons = split(wlist[::-1], lambda c: c in vocals)

 This is clear. I actually wanted to know if there is a function which I
 overlooked which does that, which wouldn't be a maintenance nightmare at
 all.

Not that I know of, but if there is one it should be named
bifilter, or difilter if you prefer Greek roots. :)


def bifilter(test, seq):
  passes = []
  fails = []
  for term in seq:
if test(term):
  passes.append(term)
else:
  fails.append(term)
  return passes, fails


 bifilter(aeiou.__contains__, This is a test)
(['i', 'i', 'a', 'e'], ['T', 'h', 's', ' ', 's', ' ', ' ', 't', 's', 't'])
 

Another implementation, though in this case I cheat because I
do the test twice, is

 from itertools import ifilter, ifilterfalse, tee
 def bifilter(test, seq):
...   seq1, seq2 = tee(seq)
...   return ifilter(test, seq1), ifilterfalse(test, seq2)
... 
 bifilter(aeiou.__contains__, This is another test)
(itertools.ifilter object at 0x57f050, itertools.ifilterfalse object at 
0x57f070)
 map(list, _)
[['i', 'i', 'a', 'o', 'e', 'e'], ['T', 'h', 's', ' ', 's', ' ', 'n', 't', 'h', 
'r', ' ', 't', 's', 't']]
 


Andrew
[EMAIL PROTECTED]

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


Re: file permissions on windows XP (home)

2005-06-07 Thread barney
Thanks,

I tried creating a test file but I get Access is denied from windows
explorer! The folder appears to be read only but when I try and uncheck
read only/apply/repopen the folder properties its still read only. This
read only flag seems to propagate down from the My Music directory but
unchecking it there also has no lasting effect.

I realise that theses are windows rather than python issues but I would
expect there would be some reliable way of changing the file
permissions from within python. I'm updating ID3 tags in MP3 file to
give some context. If I use something like winamp to make the change to
the ID3 tag then the file is updated with no permission errors so there
must be a way

I have added a stat call to the code which returns:

(33206, 0L, 2, 1, 0, 0, 4142103L, 1118176036, 920221388, 442057)

and this is the output of cacls (didn't know about this command):

C:\Users\Barney\My Music\U2\The Best Of 1980 - 1990 (US CD 1)\02 - New
Year's Day.mp3 XPHOME\Barney:(special access:)
STANDARD_RIGHTS_ALL
DELETE
READ_CONTROL
WRITE_DAC
WRITE_OWNER
SYNCHRONIZE
STANDARD_RIGHTS_REQUIRED
FILE_GENERIC_READ
FILE_READ_DATA
FILE_READ_EA
FILE_WRITE_EA
FILE_READ_ATTRIBUTES
FILE_WRITE_ATTRIBUTES

XPHOME\None:(special access:)
READ_CONTROL
SYNCHRONIZE
FILE_GENERIC_READ
FILE_READ_DATA
FILE_READ_EA
FILE_READ_ATTRIBUTES

Everyone:(special access:)
READ_CONTROL
SYNCHRONIZE
FILE_GENERIC_READ
FILE_READ_DATA
FILE_READ_EA
FILE_READ_ATTRIBUTES


I'm not entirely sure how to interpret these but will do some reading.
In the meantime if someone could show me some python to force the file
to be writeable that's all I really need at this stage.

Thanks
Barney

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


Re: time consuming loops over lists

2005-06-07 Thread Andrea Griffini
On Tue, 07 Jun 2005 18:13:01 +0200, Diez B. Roggisch [EMAIL PROTECTED]
wrote:

Another optimization im too lazy now would be to do sort of a tree 
search of data[i] in rngs - as the ranges are ordered, you could find 
the proper one in log_2(len(rngs)) instead of len(rngs)/2.

I don't see a break so why the /2 ? also IIUC the
ranges are more than just ordered... they're all equal
and computed by

 for i in xrange(no_of_bins+1):
  rngs[i] = dmin + (rng*i)

so my guess is that instead of searching with

  for j in xrange(len(rngs)-1):
   if rngs[j] = data[i]  rngs[j+1]:

one could just do

j = int((data[i] - dmin)/rng)

The code with this change gets roughly about twice faster.

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


Re: poker card game revisited (code included)

2005-06-07 Thread flupke
Erik Max Francis wrote:
 flupke wrote:
 
snip

First of all, my apologies for the double posts. I can only see this 
reply and can't see my original messages. I posted the message from home 
and work and they didn't show up. We use the same isp at home and at 
work so it's probably a problem on their end.

 It looks like you're not approaching this in a systematic manner. 
 Algorithms for determining poker hands are already pretty well-known; 
 there are several open source projects that do it efficiently which you 
 could learn from.

Which projects are you talking about? I only found a library in c to 
evaluat ranks but i didn't find the code to be very understandable.

 When you're evaluating poker hands, you're looking for three basic types 
 of card groups:  matches, straights, and flushes.  The most efficient 
 way to look for matches is with a histogram based on the card rank.  Bin 
 the cards up by rank, and then build a second histogram of the counts 
 of those ranks indexing into a list of the ranks which had those cards 
 (sorted by rank, so you can pull off the highest ones).  Now determining 
 all the rank-based hands is easy:  quads have a hit with four matches, a 
 boat has a hit with two three matches (there's no two trips so this is 
 a boat at best) or both three and two matches, two pair has two hits 
 with two matches, etc.

With histogram do you mean something like this:
Card hand: 2 clubs, 3 diamonds, 10 of diamonds, 4 of hearts,  3 of hearts

Histogram 1: list [2,3,4,10]
2 - 14  
Histogram 2: list [1,2,1,0,0,0,0,0,1,0,0,0,0]
or
list [1,2,1,1]
so index 0 is count of rank at index 0 of Histogram 1
index 1 is count of rank at index 1 of Histogram 1

 Searching for straights and flushes is much better done by masks.
 Arrange all the possible cards in a huge masks based on both cards and 
 ranks (easy to do in Python with the long type) and then build up rank 
 masks that build up all possible straight combinations (sorted by the 
 highest rank so you can search them in order), and then build up card 
 mask ranks for each suit.  For straights, just iterate through the 
 straight rank masks and see if you find one that's fully occupied; if 
 you do, that's a straight.  For flushes, just iterate through the card 
 suit masks and see if you find one that has more five or more unique 
 cards in it.  You need to iterate through all four and find the one with 
 the highest value (for games with lots of cards, you could have two 
 flushes; you want to count the highest one).  Finally, to look for 
 straight flushes, first apply the suit masks and then turn it into ranks 
 and apply the straight masks.

As for straights, if i understand correctly, you make all possible 
straights of the cards in the hand and then see if one matches?

 Then will all this information you can easily arrange the code to select 
 the best existing hand.  Note that these all use well-established 
 techniques and reveal nothing secret.

Well, it's all new to me :)

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


Re: SMTP help please

2005-06-07 Thread Ivan Shevanski


From: Larry Bates [EMAIL PROTECTED]
To: Ivan Shevanski [EMAIL PROTECTED]
Subject: Re: SMTP help please
Date: Tue, 07 Jun 2005 07:39:01 -0500

I have found that the SmtpWriter class hides all the
complexity in creating emails like you want to send.

Check it out here:

http://motion.sourceforge.net/related/send_jpg.py

This is good, but I don't want to send pictures and I don't know what to 
take out so it doesnt send pictures.  I fooled around with it a little bit 
and kept getting this error:

Traceback (most recent call last):
File mail.py, line 119, in ?
  writer.sendMessage()
File mail.py, line 94, in sendMessage
 aList = self.getImages()
File mail.py, line 90, in getImages
 attachList  =  os.listdir(self.__imageDir)
AttributeError: SmtpWriter instance has no attribute '_SmtpWriter__imageDir'


So. . .it was good but i still can't get it to work. . .Can you help?
-Ivan

_
Express yourself instantly with MSN Messenger! Download today - it's FREE! 
http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/

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


Re: Trouble Encoding

2005-06-07 Thread John Roth
[EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 I'm using feedparser to parse the following:

 div class=indent textAdv: Termite Inspections! Jenny Moyer welcomes
 you to her HomeFinderResource.com TM A MUST See amp;hellip;/div

 I'm receiveing the following error when i try to print the feedparser
 parsing of the above text:

 UnicodeEncodeError: 'latin-1' codec can't encode character u'\u201c' in
 position 86: ordinal not in range(256)

 Why is this happening and where does the problem lie?

Several different things are going on here. First, when you try to
print a unicode string using str() or a similar function, Python is going to
use the default encoding to render it. The default encoding is usually
ASCII-7. Why it's trying to use Latin-1 in this case is somewhat
of a mystery.

The quote in front of the word MUST is a smart quote, that is a
curly quote, and it is not a valid character in either ASCII or
Latin-1. Use Windows-1252 explicitly, and it should render
properly. Alternatively use UTF-8, as one of the other posters
suggested. Then it's up to whatever software you use to actually
put the ink on the paper to render it properly, but that's a different
issue.

John Roth

 thanks
 

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


Re: time consuming loops over lists

2005-06-07 Thread Diez B. Roggisch
 I don't see a break so why the /2 ? also IIUC the

That was the assumption of an equal distribution of the data. In 
O-notationn this would be O(n) of course.


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


Re: Reading a CSV file into a list of dictionaries

2005-06-07 Thread Laurent RAHUEL
John Machin wrote:

 Laurent RAHUEL wrote:
 RFQ wrote:
 
 
Hi, I'm struggling here to do the following with any success:

I have a comma delimited file where each line in the file is something
like:

PNumber,3056,Contractor,XYZ Contracting,Architect,ABC Architects,...
 
 
 This is NOT a CSV file. A CSV file would be :
 
 PNumber,Contractor,Architect,...
 2056,XYZ Contracting,ABC Architects,...
 
 
 CSV is an acronym for Comma-Separated Values. It does not imply
 anything about the contents of the fields. The OP's file *is* a CSV
 file. Yes, the contents do represent an unusual application of the CSV
 format -- however a bus full of parcels instead of people is still a bus.

I thought you knew the number of cols and what you should expect in each.
Then it sounded pretty easy to build a list of dictionaries. If you don't
know what you're supposed to find in your file and how this file is
structured I guess you don't know what you are doing.

 
 Then, you could use the built-in CSV module of recent python versions.
 
 Python is a case-sensitive language. The name of the module is csv.
 The OP could use the csv module with his data.

Damn, that's why I always see those annoynig import errors.

I just wanted to help, maybe you're to much case-sensitive.

Regards,

Laurent.

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


Re: programmnig advise needed

2005-06-07 Thread Andrea Griffini
On 7 Jun 2005 12:14:45 -0700, [EMAIL PROTECTED] wrote:

I am writing a Python program that needs to read XML files and contruct
a tree object from the XML file (using wxTree).

Supposing your XML file has a single top level node (so that it's a
legal XML file) then the following code should be able to read it...

#
from elementtree import ElementTree as ET

class Node:
def __init__(self, xmlnode):
self.xmlnode = xmlnode
self.children = []

def loadtree(f):
root = ET.parse(f).getroot()
nodes = {}
for x in root:
if x.tag.startswith(element):
nodes[x.tag] = Node(x)
for x in root.findall(association):
name = x.find(Name).text
parent = x.find(Parent).text
nodes[parent].children.append(nodes.pop(name))
assert len(nodes) == 1
return nodes.popitem()[1]
##

The idea is to create a node with an empty list of
logical children and then for every association
removing the child node from the global pool (a dict
indexed by node name) to place it in its parent.
I assumed that the nodes are in random order, but
that the associations are sorted bottom-up in
the tree. If this is not the case then you should
keep TWO dicts, removing from only one of them
the children when you process an association,
and looking up the parent in the *other* dict that
is not changed during processing of associations.
The dict from who you are removing the children
will allow you to detect logical errors in the file
(i.e. a node having two parents - you won't find
that node in the dict the second time - and absence
of a single root - you won't end up with a single
element in the dict after processing all
associations -).

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


Re: time consuming loops over lists

2005-06-07 Thread John Machin
Diez B. Roggisch wrote:
 [EMAIL PROTECTED] wrote:
 
 X-No-Archive: yes
 Can some one help me improve this block of code...this jus converts the
 list of data into tokens based on the range it falls into...but it
 takes a long time.Can someone tell me what can i change to improve
 it...

 
 
if data[i] in xrange(rngs[j],rngs[j+1]):

 
 That's a bummer: You create a list and then search linearily in in - 
 where all you want to know is
 
 if rngs[j] = data[i]  rngs[j+1]
 
 Attached is a script that does contain  your old and my enhanced version 
 - and shows that the results are equal. Running only your version takes 
 ~35s, where mine uses ~1s!!!
 
 Another optimization im too lazy now would be to do sort of a tree 
 search of data[i] in rngs - as the ranges are ordered, you could find 
 the proper one in log_2(len(rngs)) instead of len(rngs)/2.
 
 Additional improvements can be achieved when data is sorted - but that 
 depends on your application and actually sizes of data.
 
 Diez
 
[snip]
Make these changes/additions:
=
# from Numeric import *
# +1 for Overkill-of-the-Year
def zeros(n):
 return n * [0.0]

def Tkz3(tk, data, no_of_bins):
  # indent 5 ???
  # change other funcs to have no_of_bins as an arg
  tkns = []
  dmax = max(data)+1
  dmin = min(data)
  rng = int(ceil(abs((dmax - dmin)/(no_of_bins*1.0
  for datum in data:
   j = (datum - dmin) // rng
   tkns.append( str(tk)+str(j) )
  return tkns

for func in (Tkz, Tkz2, Tkz3):
 t0 = time.time()
 result = func('A', data, nbins)
 t1 = time.time()
 results.append(result)
 print function %s took %.2f seconds to produce %d tokens % 
(func.__name__, t1 - t0, len(result))

allsame = results [0] == results[1] == results[2]
print \nIdentical results:, allsame
===
and get this:

C:\junkranges.py
C:\junk\ranges.py:46: DeprecationWarning: integer argument expected, got 
float
   if data[i] in xrange(rngs[j], rngs[j+1]):
function Tkz took 12.13 seconds to produce 12292 tokens
function Tkz2 took 0.08 seconds to produce 12292 tokens
function Tkz3 took 0.02 seconds to produce 12292 tokens

Identical results: True

==
using Python 2.4.1 (win32) on a 3.2Ghz Intel P4
==

Notes: (1) The OP's code as well as being deliciously O(N**2) depends on 
the data beint *integers* -- otherwise it goes rapidly pear-shaped; see 
the deprecation warning above, and try running it with data = [0.1* 
x for x in range(20, 12312)]. Consequently the use of math.* is a /mild/ 
overkill.

(2) The OP's code produces bins of equal nominal width but depending in 
the range, the population of the last bin may be much less than the 
population of the other bins. Another way of doing it would be to 
produce bin widths so that the populations were more evenly spread. In 
any case determining the appropriate bin could still be done by formula 
rather than by searching.

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


Re: time consuming loops over lists

2005-06-07 Thread Andrea Griffini
On Tue, 07 Jun 2005 23:38:29 +0200, Diez B. Roggisch [EMAIL PROTECTED]
wrote:

 I don't see a break so why the /2 ? also IIUC the

That was the assumption of an equal distribution of the data. In 
O-notationn this would be O(n) of course.

It was a joke ... the issue is that there was no break
statement :-) i.e. your code kept searching even after
finding the proper range!

Actually that break (with 10 bins) is not terribly
important because the cost of the comparision is
small compared to the cost of append. The timings
I got are..

your code 1.26 sec
adding break  0.98 sec
direct index computation  0.56 sec

10 bins are so few that with just low-level speedups
(i.e. precomputing a list of ranges and str(j)) the
code that does a linear scan requires just 0.60 seconds.

Hand optimizing the direct computation code the
execution time gets down to 0.3 seconds; the inner loop
i used is:

 for i, x in enumerate(data):
  j = int((x - dmin)/rng)
  tkns[i] = tks + js[j]

with data = range(20, 123120)


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


Re: Reading a CSV file into a list of dictionaries

2005-06-07 Thread Robert Kern
Laurent RAHUEL wrote:

 I thought you knew the number of cols and what you should expect in each.
 Then it sounded pretty easy to build a list of dictionaries. If you don't
 know what you're supposed to find in your file and how this file is
 structured I guess you don't know what you are doing.

That's not what the OP asked about.

[RFQ:]
So each line is intended to be: key1,value1,key2,value2,key3,value3...
and each line is to be variable in length (although it will have to be
an even number of records so that each key has a value).

The rows are not all of the same format. The OP *does* know the 
structure, and he (?) *does* know what he's doing. It's just not the 
structure usually used in CSV files.

The csv module, of course, still reads these rows just fine; they just 
need to be processed a bit to get the correct dictionaries.

-- 
Robert Kern
[EMAIL PROTECTED]

In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die.
   -- Richard Harter

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


Re: SMTP help please

2005-06-07 Thread Mike Meyer
Martin Franklin [EMAIL PROTECTED] writes:
 server = smtplib.SMTP(mailserver.somewhere.com)

Why are you beating up Kee's mail server (hint: whois somewhere.com)?

See RFC 2606 URL: http://www.ietf.org/rfc/rfc2606.txt  and search
for example.com for how to pick example domain names properly.

mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >