Can any one help with solving this program it just doesnt take probability of the second team

2006-10-26 Thread Arun Nair
''' Can anyone help me with this program it just takes probability of
the first team and runs the program doesnt takes the probability of the
second team even though specified'''

from random import *

def volleySimulation():
printInstructions()
probA, probB, n = getInputs()
winA, winB = simGames(n, probA, probB)
printSummary(winA, winB)

def printInstructions():
print "This program stimulates a game of Volley Ball between two
teams i.e. Team A and Team B"
print "The abilities of each team is indicated by a probability
that determines which team wins the points."
print "We assume that Team A always serves first"

def getInputs():
print "Enter the probability for both team winning the serve in
between 0 and 1"
probA = input("Enter the probability of Team A winning a serve")
probB = input("Enter the probability of Team B winning a serve")
n = input("Enter the number of games that you want to simulate:")
return probA, probB, n

def simGames(n, probA, probB):
winA = 0
winB = 0
for i in range(n):
scoreA, scoreB = simGame(probA, probB)
if scoreA > scoreB:
winA = winA + 1
else:
winB = winB + 1
return winA, winB

def simGame(probA, probB):
scoreA = 0
scoreB = 0
serving = "A"
while not gameOver(scoreA, scoreB):
if serving == "A":
if random() < probA:
scoreA = scoreA + 1
else:
serving == "B"
else:
if random() < probB:
scoreB = scoreB + 1
else:
serving == "A"
return scoreA, scoreB

def gameOver(a, b):
return (a == 15 or b == 15) and ((a - b) > 2 ) or ((a - b) < -2)

def printSummary(winA, winB):
n = winA + winB
print "Games simulated:", n
print "Wins for A: %d (%0.1f%%)" % (winA, float(winA)/n*100)
print "Wins for B: %d (%0.1f%%)" % (winB, float(winB)/n*100)

volleySimulation()

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


Re: python html 2 image (png)

2006-10-26 Thread baur79
thanks Diez
i will start with your suggestions

let see what happen

On Oct 25, 11:27 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] schrieb:
>
> >> what tools are you using to do that today?
>
> > where are many of EXE programs
> > but i need python solution for adding it to my automate program under
> > lunixWhatever lunix is, under linux, a popular free OS you could e.g. use
> PyKDE and let Qt render a KHTML-component into an image.
> 
> Diez

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


iterator idea

2006-10-26 Thread Paul Rubin
I wonder if Python would benefit from letting a generator jump to
another iterator, i.e. something like

   yield return *seq

would be the equivalent of

   for s in seq: yield s
   return

except that it would work by transferring control directly to seq's
iterator (like a goto) instead of calling it like a subroutine.  The
idea is to solve one of the perennial iterator annoyances, the
inability to push items back on an iterator.  For example, the
annoyance means itertools.takewhile consumes an extra element with no
reasonable way to retrieve it.  The new feature would let us write
something like (obviously untested):

  def takewhile_exact (pred, seq):
 """return two iterators (head,tail).  head is the same as
itertools.takewhile(pred,seq).  tail is the rest of the
elements of seq, with none missing.  You can't use tail
until you've iterated through head."""
 buf = []
 def head():
for s in seq:
   if pred(s): yield s
# save non-matching item so that tail can find it
buf.append(s)

 def tail():
if not buf:
   raise IndexError, "not yet ready"
yield buf.pop()
yield return *seq   # transfer control to seq

 return head(), tail()

The reason tail() can't just iterate through seq is that you
might call takewhile_exact many times:

   def is_even(n): return (n%2 == 0)
   def is_odd(n): return (n%2 != 0) 

   # we want to do something with all the runs of even numbers
   # in the sequence, and similarly with the odds.  seq is an 
   # infinite sequence.
   while True:
   evens, seq = takewhile_exact(is_even, seq)
   do_something_with (evens)
   odds, seq = takewhile_exact(is_odd, seq)
   do_something_else_with (odds)

Without the "goto"-like transfer, we'd get deeper and deeper in nested
iterators and eventually overflow the call stack.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python html 2 image (png)

2006-10-26 Thread joe Li
class Bunch(object):    def __init__(self, **fields):     self.__dict__ = fields    p = Bunch(x=2.3, y=4.5)print p 
print p.__dict__I dont' understand the usage of the double * here, could anyone explain it for me? thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Can any one help with solving this program it just doesnt take probability of the second team

2006-10-26 Thread Peter Otten
Arun Nair wrote:

> ''' Can anyone help me with this program it just takes probability of
> the first team and runs the program doesnt takes the probability of the
> second team even though specified'''

> def simGame(probA, probB):
> scoreA = 0
> scoreB = 0
> serving = "A"
> while not gameOver(scoreA, scoreB):
> if serving == "A":
> if random() < probA:
> scoreA = scoreA + 1
> else:
> serving == "B"

Hint: this is not an assignment.

> else:
> if random() < probB:
> scoreB = scoreB + 1
> else:
> serving == "A"

Same thing.

> return scoreA, scoreB

Peter

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


Re: Fatal Python error: deallocating None

2006-10-26 Thread Fredrik Lundh
Gabriel Genellina wrote:

> Mmm, it appears that one of these C extensions isn't managing the ref 
> count correctly - perhaps there is a return Py_None without a previous 
> Py_INCREF? If None were returned in certain functions to indicate 
> failure or something exceptional - and not a regular condition - that 
> would explain that it doesn't fail very often.
> Unfortunately I don't know how to debug this - except by carefully 
> inspecting the C code :(

inserting

 print sys.getrefcount(None)

at strategic locations in your code will usually help you identify the
culprit.

(last time I stumbled upon this was in an earlier release of "sqlite",
which leaked one Py_None every time you connected to the database.  our
application contained a separate task that created it's own database
connection every 15:th minute or so, to calculate some statistics.  and
a fresh Python interpreter contains 500-600 references to Py_None...)



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


Re: using mmap on large (> 2 Gig) files

2006-10-26 Thread Chetan
Paul Rubin  writes:

> "sturlamolden" <[EMAIL PROTECTED]> writes:
>> However, "memory mapping" a file by means of fseek() is probably more
>> efficient than using UNIX' mmap() or Windows'
>> CreateFileMapping()/MapViewOfFile().
>
> Why on would you think that?!  It is counterintuitive.  fseek beyond
> whatever is buffered in stdio (usually no more than 1kbyte or so)
> requires a system call, while mmap is just a memory access.
And the buffer copy required with every I/O from/to the application. 

>> In Python, we don't always need the file memory mapped, we normally
>> just want to use slicing-operators, for-loops and other goodies on
>> the file object -- i.e. we just want to treat the file as a Python
>> container object. There are many ways of achieving that.
>
> Some of the time we want to share the region with other processes.
> Sometimes we just want random access to a big file on disk without
> having to do a lot of context switches seeking around in the file.
>
>> There are in any case room for improving Python's mmap object.
>
> IMO it should have some kind of IPC locking mechanism added, in
> addition to the offset stuff suggested.
The type of IPC required differs depending on who is using the shared region -
either another python process or another external program. Apart from the
spinlock primitives, other types of synchronization mechanisms are provided by
the OS. However, I do see value in providing a shared memory based spinlock
mechanism. These services can be built on top of the shared memory
infrastructure. I am not sure what kind or real world python applications use
it. 

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


Re: python html 2 image (png)

2006-10-26 Thread Fredrik Lundh
joe Li wrote:

> **class Bunch(object):
> def __init__(self, **fields):
> self.__dict__ = fields
>
> p = Bunch(x=2.3, y=4.5)
> print p
> 
> print p.__dict__
> 
> I dont' understand the usage of the double * here, could anyone explain 
> it for me?

if you're going to post questions to arbitrarily chosen threads, you 
could at least change the subject (but it's a lot nicer to open a new 
thread).

the "**" prefix tells Python to stuff any excess keyword arguments into 
the given variable:

 >>> def func(**kwargs):
... print kwargs
...
 >>> func()
{}
 >>> func(spam=1, egg=2)
{'egg': 2, 'spam': 1}

for more on Python's parameter syntax, see the section on "def" in the 
language reference; see e.g.

 http://effbot.org/pyref/def.htm



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


Re: using mmap on large (> 2 Gig) files

2006-10-26 Thread Paul Rubin
Chetan <[EMAIL PROTECTED]> writes:
> > Why on would you think that?!  It is counterintuitive.  fseek beyond
> > whatever is buffered in stdio (usually no more than 1kbyte or so)
> > requires a system call, while mmap is just a memory access.
> And the buffer copy required with every I/O from/to the application. 

Even that can probably be avoided since the mmap region has to start
on a page boundary, but anyway regular I/O definitely has to copy the
data.  For mmap, I'm thinking mostly of the case where the entire file
is paged in through most of the program's execution though.  That
obviously wouldn't apply to every application.

> > IMO it should have some kind of IPC locking mechanism added, in
> > addition to the offset stuff suggested.
> The type of IPC required differs depending on who is using the
> shared region - either another python process or another external
> program. Apart from the spinlock primitives, other types of
> synchronization mechanisms are provided by the OS. However, I do see
> value in providing a shared memory based spinlock mechanism. 

I mean just have an interface to OS locks (Linux futex and whatever
the Windows counterpart is) and maybe also a utility function to do a
compare-and-swap in user space.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can any one help with solving this program it just doesnt take probability of the second team

2006-10-26 Thread Arun Nair
Thanks a ton peter its working.


Peter Otten wrote:
> Arun Nair wrote:
>
> > ''' Can anyone help me with this program it just takes probability of
> > the first team and runs the program doesnt takes the probability of the
> > second team even though specified'''
>
> > def simGame(probA, probB):
> > scoreA = 0
> > scoreB = 0
> > serving = "A"
> > while not gameOver(scoreA, scoreB):
> > if serving == "A":
> > if random() < probA:
> > scoreA = scoreA + 1
> > else:
> > serving == "B"
>
> Hint: this is not an assignment.
>
> > else:
> > if random() < probB:
> > scoreB = scoreB + 1
> > else:
> > serving == "A"
> 
> Same thing.
> 
> > return scoreA, scoreB
> 
> Peter

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


Re: To remove some lines from a file

2006-10-26 Thread Chetan
Sebastian Busch <[EMAIL PROTECTED]> writes:

> Steve Holden wrote:
>> Sebastian Busch wrote:
>>> [EMAIL PROTECTED] wrote:
 ... I would like to remove two lines from a file. ...
>>> ... grep -v ...
>> ... show ...
>
> grep -v "`grep -v "commentsymbol" yourfile | head -2`" yourfile
>
>
> i frankly admit that there is also 'head' invoved ;)
>
> i really have no idea -- but i always thought that these coreutils and
> colleagues do their jobs as fast as possible, in particular faster than
> interpreted languages... however, as i posted last time, i was actually
> not aware that you have to call three of them.
>
> sebastian.
I don't have the original post to know exactly what is needed, but looks like
something that can be done by a single sed script. 

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


Problem Commenting within Filehandle Iteration

2006-10-26 Thread Wijaya Edward

Hi all,
 
I have the following code:
 
 
import sys   
import re

ham_count = 0
spam_count = 0
myfile = open('full/index')
for line in myfile.readlines():
p = re.compile('ham')
m = p.match(line)
if m:
print line,
else:
#print 'SPAM -- %s' % line
myfile.close()

Sometime while developing/debugging the code we usually 
put in such situation. Where expression under "else"
is not yet supplied, yet we would like see the printout of the
previous "if" condition. 
 
Notice that I wanted to comment out the #print line there.
However I found problem with myfile.close(), with identation error.
This error doesn't occur when commenting (#) is not in use.
 
Why so?  Is there away to do the commenting in correct way
under this circumstances?
 
-- 
Edward WIJAYA
SINGAPORE
 
 

 Institute For Infocomm Research - Disclaimer -
This email is confidential and may be privileged.  If you are not the intended 
recipient, please delete it and notify us immediately. Please do not copy or 
use it for any purpose, or disclose its contents to any other person. Thank you.

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


Re: Sorting by item_in_another_list

2006-10-26 Thread Steven Bethard
Cameron Walsh wrote:
> Which brings me to the question, would this solution:
> 
> B = set(B)
> A = B + list(x for x in A if x not in B)
> 
> be faster than this solution:
> 
> B = set(B)
> A.sort(key=B.__contains__, reverse=True)
> 
> My guess is yes, since while the __contains__ method is only run once 
> for each object, the list still does not require sorting.

You're probably going to need to time that for your particular data. 
Here's what it looks like on an artificial data set:

$ python -m timeit -s "A = range(100); B = range(40, 60, 2); B_set = 
set(B)" "A = B + list(x for x in A if x not in B_set)"
1 loops, best of 3: 54.5 usec per loop

$ python -m timeit -s "A = range(100); B = range(40, 60, 2); B_set = 
set(B)" "A.sort(key=B_set.__contains__, reverse=True)"
1 loops, best of 3: 39.7 usec per loop

That said, I'd probably still use the first solution -- it's more 
immediately obvious why that one works.

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


Re: python html 2 image (png)

2006-10-26 Thread joe Li
Thanks a lot.Please forgive my careless mistake, I am completely a new user^-^2006/10/26, Fredrik Lundh <[EMAIL PROTECTED]>:
joe Li wrote:> **class Bunch(object):> def __init__(self, **fields):
> self.__dict__ = fields>> p = Bunch(x=2.3, y=4.5)> print p>> print p.__dict__>> I dont' understand the usage of the double * here, could anyone explain> it for me?
if you're going to post questions to arbitrarily chosen threads, youcould at least change the subject (but it's a lot nicer to open a newthread).the "**" prefix tells Python to stuff any excess keyword arguments into
the given variable: >>> def func(**kwargs):... print kwargs... >>> func(){} >>> func(spam=1, egg=2){'egg': 2, 'spam': 1}for more on Python's parameter syntax, see the section on "def" in the
language reference; see e.g. http://effbot.org/pyref/def.htm--http://mail.python.org/mailman/listinfo/python-list

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

Re: Sorting by item_in_another_list

2006-10-26 Thread Paul Rubin
Steven Bethard <[EMAIL PROTECTED]> writes:
> Cameron Walsh wrote:
> > Which brings me to the question, would this solution:
> > B = set(B)
> > A = B + list(x for x in A if x not in B)
> > be faster than this solution:
> > B = set(B)
> > A.sort(key=B.__contains__, reverse=True)
> [timings deleted]
> That said, I'd probably still use the first solution -- it's more
> immediately obvious why that one works.

Wait a minute, the first example looks wrong, B has gotten replaced by
a set and then it's added to a list.

Anyway how about timing

   C = set(A) - set(B)
   A = B + filter(C.__contains__, A)

This scans A twice, but it does more of the work in native code,
without sorting.
-- 
http://mail.python.org/mailman/listinfo/python-list


Slightly OT: Is pyhelp.cgi documentation search broken?

2006-10-26 Thread Joel Hedlund
Hi!

For a number of days I haven't been able to search the online python 
docs at:

http://starship.python.net/crew/theller/pyhelp.cgi

that is the "search the docs with" link at this page:

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

Instead of the search engine, I get Error 404. This is a real bother for 
me, since I rely heavily on it for my work.

Is it broken? If so, is anybody trying to get it back up again, and 
what's the time scale in that case? Is there an alternative available 
somewhere?

Cheers!
/Joel Hedlund
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN compiler2 : Produce bytecode from Python 2.5 Abstract Syntax Trees

2006-10-26 Thread [EMAIL PROTECTED]
Martin v. Löwis wrote:
> >> Let me second this. The compiler package is largely unmaintained and
> >> was known to be broken (and perhaps still is). A replacement
> >> implementation, especially if it comes with a new maintainer, would
> >> be welcome.
>
> Many of these are fixed, but it wouldn't surprise me if there are
> still bugs remaining.

There's no maybe about it.  http://python.org/sf/1544277
There were also problems with the global statement and something with
keyword args.  Though, both of those may have been fixed.  Georg would
probably remember, I think he fixed at least one of them.

It's definitely broken unless someone fixed it when I wasn't looking.
:-)

I agree with Martin, a new maintainer would be nice.  I plan to look at
compiler2 when I get a chance.

n

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


Re: Problem Commenting within Filehandle Iteration

2006-10-26 Thread Fredrik Lundh
Wijaya Edward wrote:

> if m:
> print line,
> else:
> #print 'SPAM -- %s' % line
> myfile.close()
> 
> Sometime while developing/debugging the code we usually 
> put in such situation. Where expression under "else"
> is not yet supplied, yet we would like see the printout of the
> previous "if" condition. 
>  
> Notice that I wanted to comment out the #print line there.
> However I found problem with myfile.close(), with identation error.
> This error doesn't occur when commenting (#) is not in use.
>  
> Why so?  Is there away to do the commenting in correct way
> under this circumstances?

statement suites cannot be empty in Python (and comments don't count). 
to fix this, insert a "pass" statement:

 if m:
 print line,
 else:
 pass # print 'SPAM -- %s' % line

also see:

 http://effbot.org/pyref/pass.htm



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


Re: Problem Commenting within Filehandle Iteration

2006-10-26 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Wijaya Edward
wrote:

> if m:
> print line,
> else:
> #print 'SPAM -- %s' % line
> myfile.close()
> 
> […]
>
> Notice that I wanted to comment out the #print line there.
> However I found problem with myfile.close(), with identation error.
> This error doesn't occur when commenting (#) is not in use.
>  
> Why so?  Is there away to do the commenting in correct way
> under this circumstances?

There has to be code in the ``else`` block.  So either comment out the
``else`` line too, or insert a ``pass`` statement.

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

Re: Problem Commenting within Filehandle Iteration

2006-10-26 Thread Ben Finney
Wijaya Edward <[EMAIL PROTECTED]> writes:

> if m:
> print line,
> else:
> #print 'SPAM -- %s' % line

Simple answer:

if m:
print line,
# else:
# print 'SPAM'


My preferred answer:

if m:
print line,

and get the lines back again later from your version control system.

-- 
 \ "I am an optimist. It does not seem too much use being anything |
  `\  else."  -- Winston Churchill |
_o__)  |
Ben Finney

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


Re: Slightly OT: Is pyhelp.cgi documentation search broken?

2006-10-26 Thread Thomas Heller
Joel Hedlund schrieb:
> Hi!
> 
> For a number of days I haven't been able to search the online python 
> docs at:
> 
> http://starship.python.net/crew/theller/pyhelp.cgi
> 
> that is the "search the docs with" link at this page:
> 
> http://www.python.org/doc/
> 
> Instead of the search engine, I get Error 404. This is a real bother for 
> me, since I rely heavily on it for my work.
> 
> Is it broken? If so, is anybody trying to get it back up again, and 
> what's the time scale in that case? Is there an alternative available 
> somewhere?

The operating system on the starship.python.net machine was reinstalled from 
scratch;
but the 'crew' pages still have to be restored.  This will take some days, IMO.

Thomas

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


Re: Problem Commenting within Filehandle Iteration

2006-10-26 Thread Fredrik Lundh
Ben Finney wrote:

> My preferred answer:
> 
> if m:
> print line,
> 
> and get the lines back again later from your version control system.

switching debugging statements on and off by rolling back to an earlier 
release strikes me as a somewhat misguided use of version control.



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


Printing Hidden Character in Python

2006-10-26 Thread Wijaya Edward

Hi,
 
How can we print out the hidden character like
"\n", "\r" etc in Python?
 
-- Edward WIJAYA
SINGAPORE

 Institute For Infocomm Research - Disclaimer -
This email is confidential and may be privileged.  If you are not the intended 
recipient, please delete it and notify us immediately. Please do not copy or 
use it for any purpose, or disclose its contents to any other person. Thank you.

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


Re: Problem Commenting within Filehandle Iteration

2006-10-26 Thread Ben Finney
Fredrik Lundh <[EMAIL PROTECTED]> writes:

> Ben Finney wrote:
>
> > My preferred answer:
> > 
> > if m:
> > print line,
> > 
> > and get the lines back again later from your version control system.
>
> switching debugging statements on and off by rolling back to an
> earlier release strikes me as a somewhat misguided use of version
> control.

That didn't seem to me to be a debugging statement being disabled, but
rather a "let's try changing the program this way".

-- 
 \ "[T]he question of whether machines can think [...] is about as |
  `\ relevant as the question of whether submarines can swim."  -- |
_o__)   Edsger W. Dijkstra |
Ben Finney

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


Make alternative like NAnt, rake, ... written in python?

2006-10-26 Thread Achim Domma
Hi,

I'm looking for a tool to automate build tasks like copying files, 
zipping them up, change config files  NAnt works fine, because it's 
quite easy to extend in C#, but it would even easier to write tasks in 
Python.

SCons is the only Python tool of this kind which I know. But SCons is 
much to complicated and not easy to extend. Rake looks very nice, but is 
written in Ruby. Is there something similar in Python?

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


Re: unsigned 32 bit arithmetic type?

2006-10-26 Thread Robin Becker
sturlamolden wrote:
> Robin Becker wrote:
> 
>> it's probably wonderful, but I don't think I can ask people to add numpy to 
>> the
>> list of requirements for reportlab :)
> 

> This was Matlab, but the same holds for Python and NumPy. The overhead
> in the first code sniplet comes from calling the interpreter inside a
> tight loop. That is why loops are the root of evilness when doung CPU
> bound tasks in an interpreted language. I would think that 9 out of 10
> tasks most Python users think require a C extension is actually more
> easily solved with NumPy. This is old knowledge from the Matlab
> community: even if you think you need a "MEX file" (that is, a C
> extension for Matlab), you probably don't. Vectorize and it will be
> fast enough.
> 

I think you're preaching to the converted. The very first serious thing I did 
in 
python involved a generational accounting model calculation that was translated 
from matlab into Numeric/python. It ran about 10 times faster than matlab and 
about 5 times faster than a matlab compiler.
-- 
Robin Becker

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


Re: Sending Dictionary via Network

2006-10-26 Thread Frithiof Andreas Jensen

"Leif K-Brooks" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Frithiof Andreas Jensen wrote:
> >> "mumebuhi" <[EMAIL PROTECTED]> wrote in message
> > news:[EMAIL PROTECTED]
> >> The simplejson module is really cool and simple to use. This is great!
> >
> > JUST what I need for some configuration files!!
> > Thanks for the link (die, configparse, dieee).
>
>
> I would personally use YAML for configuration files instead of JSON,
> because it's more human-readable. But it's a matter of personal preference.

Hehe: I am using YAML now. I find it readable - human ... hmm ;-)


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


Re: chained attrgetter

2006-10-26 Thread Brian Beck
Alexey Borzenkov wrote:
> Do you mean something like
>
> class cattrgetter:
> def __init__(self, name):
> self.names = name.split('.')
> def __call__(self, obj):
> for name in self.names:
> obj = getattr(obj, name)
> return obj

I'll raise you one:

def cattrgetter(attr):
   return lambda obj: reduce(getattr, attr.split('.'), obj)

py> class A: pass
py> a = A
py> a.b = A
py> a.b.c = "Hey!"
py> cattrgetter('b.c')(a)
'Hey!'

--
Brian Beck
Adventurer of the First Order

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


Re: Printing Hidden Character in Python

2006-10-26 Thread Ben Finney
Wijaya Edward <[EMAIL PROTECTED]> writes:

> How can we print out the hidden character like "\n", "\r" etc in
> Python?

What result do you want that you're not getting with:

print "\n"

-- 
 \  "Two rules to success in life: 1. Don't tell people everything |
  `\ you know."  -- Sassan Tat |
_o__)  |
Ben Finney

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


Get coordinates of a cell

2006-10-26 Thread Teja
I have a GUI application with a Frame and a grid in it. I want to popup
a menu after the user enters some text in a cell and hits ENTER key. I
was able to popup the menu. However the menu is not popping up exactly
at the position where I want it. It should be popped up immediately
after the cell in which the user has entered the text. To get the co
ordinates I am using the function event.GetPosition(). Here event is
wx.EVT_KEY_DOWN. Any pointers please?

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


Re: chained attrgetter

2006-10-26 Thread Brian Beck
David S. wrote:
> Does something like operator.getattr exist to perform a chained attr
> lookup?
>
> I came up with the following, but I can not help but think it is
> already done and done better.

You were on the right track, but the built-in getattr is a perfectly
good argument to reduce(), using operator.attrgetter just makes the
definition more complicated (see my other post).

--
Brian Beck
Adventurer of the First Order

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


Re: cleaner way to write this?

2006-10-26 Thread Hendrik van Rooyen
 "John Salerno" <[EMAIL PROTECTED]> wrote:
8<-
> 
> LOL. Guess I'm doing things right, then? ;)
> 

you can NEVER be sure

- Hendrik

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


RE: Printing Hidden Character in Python

2006-10-26 Thread Wijaya Edward

Ben,
 
I mean while opening a file, like this

for line in open('somefile.txt'):
print line

printing "line" will not show the hidden chars like "\n","\r".
Is there  a way to print it out?
 
-- Edward WIJAYA
SINGAPORE



From: [EMAIL PROTECTED] on behalf of Ben Finney
Sent: Thu 10/26/2006 4:59 PM
To: python-list@python.org
Subject: Re: Printing Hidden Character in Python



Wijaya Edward <[EMAIL PROTECTED]> writes:

> How can we print out the hidden character like "\n", "\r" etc in
> Python?

What result do you want that you're not getting with:

print "\n"

--
 \  "Two rules to success in life: 1. Don't tell people everything |
  `\ you know."  -- Sassan Tat |
_o__)  |
Ben Finney

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



 Institute For Infocomm Research - Disclaimer -
This email is confidential and may be privileged.  If you are not the intended 
recipient, please delete it and notify us immediately. Please do not copy or 
use it for any purpose, or disclose its contents to any other person. Thank you.

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


Re: To remove some lines from a file

2006-10-26 Thread Sebastian Busch
Chetan wrote:
> Sebastian Busch <[EMAIL PROTECTED]> writes:
> 
>> Steve Holden wrote:
>>> Sebastian Busch wrote:
 [EMAIL PROTECTED] wrote:
> ... I would like to remove two lines from a file. ...
 ... grep -v ...
>>> ... show ...
>> grep -v "`grep -v "commentsymbol" yourfile | head -2`" yourfile
>> ...
> I don't have the original post to know exactly what is needed, but looks like
> something that can be done by a single sed script. 
> 
> -Chetan

Hey!

The task is:

"Remove the first two lines that don't begin with "@" from a file."


Actually, the grep-thing I offered will also delete copies of these two
lines that occur in another place. That should be no problem if the file
is something like

@comment
deleteme
deleteme
@comment
data: x-y-dy

However, if this is not the case, it cannot be done this way.
How would you do it with sed?

Best,
Sebastian.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Printing Hidden Character in Python

2006-10-26 Thread Ben Finney
[Please don't top-post replies. I've corrected it in this post.]

Wijaya Edward <[EMAIL PROTECTED]> writes:

> Ben Finney wrote:
> > Wijaya Edward <[EMAIL PROTECTED]> writes:
> > > How can we print out the hidden character like "\n", "\r" etc in
> > > Python?
> > What result do you want that you're not getting with:
> > print "\n"
>
> printing "line" will not show the hidden chars like "\n","\r".
> Is there  a way to print it out?

Again, I don't know what result you want to see. The characters are
non-printable; what output do you expect?

If you want to see a Python string representation of the input, maybe
the 'repr' function is what you want.

>>> foo = "bar\tbaz\r\n"
>>> print foo
bar baz

>>> print repr(foo)
'bar\tbaz\r\n'

-- 
 \  "The most common way people give up their power is by thinking |
  `\they don't have any."  -- Alice Walker |
_o__)  |
Ben Finney

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


Re: Printing Hidden Character in Python

2006-10-26 Thread Fredrik Lundh
"Wijaya Edward" wrote:

> I mean while opening a file, like this
>
> for line in open('somefile.txt'):
>print line
>
> printing "line" will not show the hidden chars like "\n","\r".
> Is there  a way to print it out?

print repr(line)

 



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


Re: Printing Hidden Character in Python

2006-10-26 Thread [EMAIL PROTECTED]
Just escape the '\' character. So you would do:

print "\\n"

On Oct 26, 2:06 am, Wijaya Edward <[EMAIL PROTECTED]> wrote:
> Ben,
>
> I mean while opening a file, like this
>
> for line in open('somefile.txt'):
> print line
>
> printing "line" will not show the hidden chars like "\n","\r".
> Is there  a way to print it out?
>
> -- Edward WIJAYA
> SINGAPORE
>
> 
>
> From: [EMAIL PROTECTED] on behalf of Ben Finney
> Sent: Thu 10/26/2006 4:59 PM
> To: [EMAIL PROTECTED]
> Subject: Re: Printing Hidden Character in Python
>
> Wijaya Edward <[EMAIL PROTECTED]> writes:
> > How can we print out the hidden character like "\n", "\r" etc in
> > Python?What result do you want that you're not getting with:
>
> print "\n"
>
> --
>  \  "Two rules to success in life: 1. Don't tell people everything |
>   `\ you know."  -- Sassan Tat |
> _o__)  |
> Ben Finney
>
> --http://mail.python.org/mailman/listinfo/python-list
>
>  Institute For Infocomm Research - Disclaimer -
> This email is confidential and may be privileged.  If you are not the 
> intended recipient, please delete it and notify us immediately. Please do not 
> copy or use it for any purpose, or disclose its contents to any other person. 
> Thank you.
> 

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


Re: Make alternative like NAnt, rake, ... written in python?

2006-10-26 Thread Paul Boddie
Achim Domma wrote:
>
> I'm looking for a tool to automate build tasks like copying files,
> zipping them up, change config files  NAnt works fine, because it's
> quite easy to extend in C#, but it would even easier to write tasks in
> Python.
>
> SCons is the only Python tool of this kind which I know. But SCons is
> much to complicated and not easy to extend. Rake looks very nice, but is
> written in Ruby. Is there something similar in Python?

The Waf build system might be something to consider:

http://freehackers.org/~tnagy/bksys.html

The claim is that it's better architected and faster than SCons,
although I haven't investigated this myself.

Paul

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


Re: using mmap on large (> 2 Gig) files

2006-10-26 Thread Chetan
Paul Rubin  writes:

> I mean just have an interface to OS locks (Linux futex and whatever
> the Windows counterpart is) and maybe also a utility function to do a
> compare-and-swap in user space.
There is code for spinlocks, but it allocates the lockword in the process
memory. This can be used for thread synchronization, but not for IPC with
external python or non-python processes.
I found a PyIPC IPC package that seems to provide interface to Sys V shared
memory and semaphore  - but I just found it, so cannot comment on it at this
time.
-- 
http://mail.python.org/mailman/listinfo/python-list


Cards deck problem

2006-10-26 Thread Arun Nair
Can any one help me with this im not getting it even after reading
books because there is not much of discussion anywhere

a>
 Implement a calss that represents a playing card.  The class should
implement the following methods:
_ _ init _ _ (self, rank, suit) Creates a card.
rank is an integer in range of 1 to 13 (Ace:1, King 13), suit is a
character in set {'h','d','c','s'}
getRank(self) Returns the rank of the card
getSuit(self) Returns the suit of the card
BJValue(self) Returns the 'Blackjack Value' of the card (Ace:1, Face
card:10)
_ _ str _ _ (self) Returns a string naming the card. For example: 'Ace
of Spades'

Test your class by writing a 'test harness' that generates 'n' randomly
generated cards, where 'n' is supplied by the user.  Print out the
string associated with each card and it's 'Blackjack value'


b>
Extend the card class to display in a graphics window.  the new class
should support the following method: draw(self, win, center) Draws a
card in a window.
Use the extended class to display a hand of five random cards.


c> Write a program that creates a list of card objects as above and
print out the cards grouped by suit and in rank order in each suit.
the program should read the values for the list of cards from a file,
where each line in the file specifies a single card with the rank and
then the suit separated by a space. Hint: sort the list first by rank,
and then by suit.


d> Create a new class deck that represents a pack of 52 cards.  Which
supports the following methods:

_ _init_ _ (self) - Creates a deck of cards in standard order.
shuffle(self) - Randomizes the order of the cards
dealCard(self) - Returns a single card from the top of the deck, and
removes the card from the deck.
cardsLeft(self) - Returns the number of cards left in the deck.
Test your class by having it deal out a sequence of 'n' cards where 'n'
is a number input by the user.  The program should either print out the
cards, or display them in a window.

Your urgent and quick reply help will be appreciated the most.

Arun Nair

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


Re: Cards deck problem

2006-10-26 Thread Paul Rubin
"Arun Nair" <[EMAIL PROTECTED]> writes:
> Your urgent and quick reply help will be appreciated the most.

Do you have a specific question?  What are you having trouble with?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cards deck problem

2006-10-26 Thread Ben Finney
"Arun Nair" <[EMAIL PROTECTED]> writes:

> Can any one help me with this im not getting it even after reading
> books because there is not much of discussion anywhere

Perhaps the discussion should be between yourself and your teacher, or
the other students in your class. We're not here to do your homework
assignments.

-- 
 \   "It is seldom that liberty of any kind is lost all at once."  |
  `\ -- David Hume |
_o__)  |
Ben Finney

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


Re: Cards deck problem

2006-10-26 Thread Arun Nair
Hey paul i dont know how to implement this stuff if you have any ebook
or any notes which can halp me then i would like to try it and
implement my and refer back to you for any errors comming out of it

Regards,

Arun

On Oct 26, 7:39 pm, Paul Rubin  wrote:
> "Arun Nair" <[EMAIL PROTECTED]> writes:
> > Your urgent and quick reply help will be appreciated the most.Do you have a 
> > specific question?  What are you having trouble with?

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


Re: Cards deck problem

2006-10-26 Thread Arun Nair
Im so sorry about that but the lecturer doesnt teaches anything so its
become very difficult for me to do it if you guys have any notes on
classes it will be very helpfull. and i can try on my own.

regards,

Arun

On Oct 26, 7:47 pm, Ben Finney <[EMAIL PROTECTED]>
wrote:
> "Arun Nair" <[EMAIL PROTECTED]> writes:
> > Can any one help me with this im not getting it even after reading
> > books because there is not much of discussion anywherePerhaps the 
> > discussion should be between yourself and your teacher, or
> the other students in your class. We're not here to do your homework
> assignments.
>
> --
>  \   "It is seldom that liberty of any kind is lost all at once."  |
>   `\ -- David Hume |
> _o__)  |
> Ben Finney

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


Re: Cards deck problem

2006-10-26 Thread Fredrik Lundh
Arun Nair wrote:

> Hey paul i dont know how to implement this stuff if you have any ebook
> or any notes which can halp me then i would like to try it and
> implement my and refer back to you for any errors comming out of it

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

 



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


Re: question about True values

2006-10-26 Thread John Coleman

Donn Cave wrote:
> In article <[EMAIL PROTECTED]>,
>  "John Coleman" <[EMAIL PROTECTED]> wrote:
>
> > Very good point, though one could argue perhaps that when one is
> > comparing an object with a truth value then one is implicitly asking
> > for the truth value of that object
>
> On the contrary -- since there is normally no need to ever
> compare an object with a truth value, then I would interpret
> this usage as an attempt to distinguish True or False from
> other objects in general.  Some kind of placeholders for
> missing values, who knows.  I'm not saying it's a great idea,
> but it could work in recent versions of Python.
>
> > This would make code like 'if s: ' equivalent
> > to 'if s == True:' with a possible gain in readability. But - as you
> > demonstrate the cost of that (minimal) gain in readability would be too
> > high. In any event - I think it is mostly bad style to use a
> > non-boolean variable in 'if s:' - it reminds me too much of obscure C
> > code (though others might disagree).
>
> Others will indeed disagree.  I don't think you'll find
> much support for this position.  But it's not as bad as
> your notion that "if s == True", where s is not a boolean
> object, might represent a gain in readability.  That really
> redefines readability.
>
>Donn Cave, [EMAIL PROTECTED]

As far as readability goes - most computer languages have a surface
syntax which is (by design) vaguely similiar to the syntax of a natural
language like English. Thus statements roughly correspond to sentences.
For example, you can see a subject-verb-object pattern in "x=3". Given
a genuinely boolean construct like x < 2, "if x < 2:" *sounds* right to
a human reader. Similarly, given a good boolean variable with a
descriptive name like "found", the fragment "if found:" sounds ok. But
- given a non-boolean variable like "product_name" -  writing "if
product_name:" sounds (to my ears) a little jarring - it sounds like a
sentence fragment. It's like saying "If Bob" - If Bob *what*? Goes to
the store? answers the telephone? Finish the damn thought! Now, if you
were to (from some strange reason) use "product_name" as if it were a
truth value then (to my ears) it would both make your intentions more
clear and sound less fragmentary if you could say "if product_name ==
True:". When you use "product_name" as the condition of an if statement
then in that context it is *functioning* as a truth value so (naively)
what could be wrong with comparing it to a truth value? I don't
advocate any change in Python here - just pointing out that the idea of
allowing "if s:" and "if s == True:" to be always equivalent in the
interest of readability isn't *that* strange. It doesn't constitute a
redefinition of readability.

As far as using non-booleans as conditions - I just think that if you
want a certain block of code to be executed only if, for example, a
list is non-empty, why not *say* so? I think "if my_list != []:" just
reads better than "if my_list:". I would think that my preferences
there mesh with "Explicit is better than implicit" but apparently not.

I'm just starting out with Python with most of my programming in recent
years being in various dialects of Visual Basic (which probably
explains a lot). What attracts me to Python so far is the cool slice
operations, the iterators, the libraries and the convience of
programming in a REPL environment. So far, the ability to use "cat" as
a part-time substitute for True just strikes me as a curiousity - but
maybe that will change with time.

-John Coleman

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


Re: To remove some lines from a file

2006-10-26 Thread Roberto Bonvallet
Sebastian Busch wrote:
> The task is:
> 
> "Remove the first two lines that don't begin with "@" from a file."

awk 'BEGIN {c = 0} c < 2 && !/^@/ {c += 1; next} {print}' < mybeautifulfile

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


Error to be resolved

2006-10-26 Thread Arun Nair
Hey guys can you help me resolve this error

Thanks & Regards,

Arun Nair
This is the program

from random import *
from string import *
class Card:

def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
self.rank = ["None","Clubs","Diamonds","Hearts","Spades"]
self.suit = ["zero", "Ace", "2", "3", "4", "5", "6", "7", "8",
"9", "10", "Jack", "Queen", "King"]
self.BJ = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

def getRank(self):
return self.rank

def getSuit(self):
return self.suit

def BJValue(self):
return self.BJ

def __str__(self):
return " %s of %s(%s)" % (self.rank[self.rank],
self.suit[self.suit], self.BJ[self.rank])

def main():
n = input("How many cards do you want to draw from the deck?")
for i in range(n):
a = randrange(1,13)
b = randrange(1,4)
c = Card(a,b)
print c

main()
=
This is the error
>>
>>> Traceback (most recent call last):
  File
"C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
line 310, in RunScript
exec codeObject in __main__.__dict__
  File "D:\A2_3.1.py", line 32, in ?
main()
  File "D:\A2_3.1.py", line 30, in main
print c
  File "D:\A2_3.1.py", line 22, in __str__
return " %s of %s(%s)" % (self.rank[self.rank],
self.suit[self.suit], self.BJ[self.rank])
TypeError: list indices must be integers
>

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


Re: question about True values

2006-10-26 Thread Steve Holden
John Coleman wrote:
> Donn Cave wrote:
> 
>>In article <[EMAIL PROTECTED]>,
>> "John Coleman" <[EMAIL PROTECTED]> wrote:
>>
>>
>>>Very good point, though one could argue perhaps that when one is
>>>comparing an object with a truth value then one is implicitly asking
>>>for the truth value of that object
>>
>>On the contrary -- since there is normally no need to ever
>>compare an object with a truth value, then I would interpret
>>this usage as an attempt to distinguish True or False from
>>other objects in general.  Some kind of placeholders for
>>missing values, who knows.  I'm not saying it's a great idea,
>>but it could work in recent versions of Python.
>>
>>
>>>This would make code like 'if s: ' equivalent
>>>to 'if s == True:' with a possible gain in readability. But - as you
>>>demonstrate the cost of that (minimal) gain in readability would be too
>>>high. In any event - I think it is mostly bad style to use a
>>>non-boolean variable in 'if s:' - it reminds me too much of obscure C
>>>code (though others might disagree).
>>
>>Others will indeed disagree.  I don't think you'll find
>>much support for this position.  But it's not as bad as
>>your notion that "if s == True", where s is not a boolean
>>object, might represent a gain in readability.  That really
>>redefines readability.
>>
>>   Donn Cave, [EMAIL PROTECTED]
> 
> 
> As far as readability goes - most computer languages have a surface
> syntax which is (by design) vaguely similiar to the syntax of a natural
> language like English. Thus statements roughly correspond to sentences.
> For example, you can see a subject-verb-object pattern in "x=3". Given
> a genuinely boolean construct like x < 2, "if x < 2:" *sounds* right to
> a human reader. Similarly, given a good boolean variable with a
> descriptive name like "found", the fragment "if found:" sounds ok. But
> - given a non-boolean variable like "product_name" -  writing "if
> product_name:" sounds (to my ears) a little jarring - it sounds like a
> sentence fragment. It's like saying "If Bob" - If Bob *what*? Goes to
> the store? answers the telephone? Finish the damn thought! Now, if you
> were to (from some strange reason) use "product_name" as if it were a
> truth value then (to my ears) it would both make your intentions more
> clear and sound less fragmentary if you could say "if product_name ==
> True:". When you use "product_name" as the condition of an if statement
> then in that context it is *functioning* as a truth value so (naively)
> what could be wrong with comparing it to a truth value? I don't
> advocate any change in Python here - just pointing out that the idea of
> allowing "if s:" and "if s == True:" to be always equivalent in the
> interest of readability isn't *that* strange. It doesn't constitute a
> redefinition of readability.
> 
Yes, but you're talking about *your* ears there. I was pointing out, as 
others have, that "if product_name" is such a deeply-ingrained Python 
idiom that you can use how natural it "sounds" to you as a measure of 
your progress in the language.

> As far as using non-booleans as conditions - I just think that if you
> want a certain block of code to be executed only if, for example, a
> list is non-empty, why not *say* so? I think "if my_list != []:" just
> reads better than "if my_list:". I would think that my preferences
> there mesh with "Explicit is better than implicit" but apparently not.
> 
Maybe so, but that "rule" (and let's not forget that the zen is not 
actually a set of prescriptive rules but rather guidelines for the 
informed) is immediately preceded by the most important "rule" of all: 
"Beautiful is better than ugly". Nobody will shout at you (well, 
hopefully, not on this list they won't) for writing

   if my_list != []:
 ...

in your code, but if they have to incorporate it into their own they 
will almost certainly reduce it to

   if my_list:
 

It's just idiomatic in Python, the same way that "'Sup?" is idiomatic in 
English (or what passes for it nowadays ;-) but grates on those who 
aren't used to hearing it.

> I'm just starting out with Python with most of my programming in recent
> years being in various dialects of Visual Basic (which probably
> explains a lot). What attracts me to Python so far is the cool slice
> operations, the iterators, the libraries and the convience of
> programming in a REPL environment. So far, the ability to use "cat" as
> a part-time substitute for True just strikes me as a curiousity - but
> maybe that will change with time.
> 
It probably will, but I wouldn't get too hung up on what's definitely a 
small point. Enjoy Python the way it is, and the way you are. You and 
Python will definitely come to an accommodation (and you will love the 
combination of discipline and freedom that it brings to programming 
style). Welcome to the language!

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skyp

Re: The format of filename

2006-10-26 Thread Neil Cerutti
On 2006-10-26, Tim Roberts <[EMAIL PROTECTED]> wrote:
> Neil Cerutti <[EMAIL PROTECTED]> wrote:
>>
>>Some experimentation shows that Python does seem to provide
>>*some* translation. Windows lets me use '/' as a path separator,
>>but not as the name of the root of a partition name. But perhaps
>>this a peculiarity of the commands themselves, and not of Windows
>>path names in particular.
>>
>>  C:\PYTHON24>CD /
>>  The syntax of the command is incorrect.
>>  
>>  C:\PYTHON24>CD \
>>  C:\>EDIT /PYTHON24/README
>>  The syntax of the command is incorrect.
>
> The Windows APIs all accept either forward slashes or back, and
> have done so clear back to Windows 3.0.  However, the Windows
> command shells do not.  That's what you're seeing here.

Well, kudos to Windows then for making Python look really smart
while making itself look like a dufus. ;-)

Seriously, experiments show the forward slash is OK as a
seperator, it just can't be root.

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


Re: Error to be resolved

2006-10-26 Thread Fredrik Lundh
Arun Nair wrote:

>self.rank = rank
>self.rank = ["None","Clubs","Diamonds","Hearts","Spades"]

hint: what's "self.rank" after you've executed the above?

 



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


problem using subprocess.call

2006-10-26 Thread Alex Kachanov
Hi!
running py module with the following code from shell:
__
dir=os.path.join(os.path.expanduser("~/domains/domain.com/html"),'test')
subprocess.call(['find',dir+" -name '*.zip' -execdir unzip {} \;"])
__
returns:
__
find: /home/clients/alex291_ftp0/domains/domain.com/html/test -name 
'*.zip' -execdir unzip {} \;: No such file or directory
__

Maybe I should change some escape-symbols? Which of them?
Tricks with
r"..."
"""..."""
\\
didn't help...



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


Re: The format of filename

2006-10-26 Thread Fredrik Lundh
Neil Cerutti wrote:

> Seriously, experiments show the forward slash is OK as a
> seperator, it just can't be root.

do you think you can figure out why, even without reading the various MSDN
pages you've been pointed to ?

 



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


Re: The format of filename

2006-10-26 Thread Neil Cerutti
On 2006-10-26, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Neil Cerutti wrote:
>> Seriously, experiments show the forward slash is OK as a
>> seperator, it just can't be root.
>
> do you think you can figure out why, even without reading the
> various MSDN pages you've been pointed to ?

Too late. Plus somebody else already pointed it out: command line
arguments.

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


Re: Error to be resolved

2006-10-26 Thread Arun Nair
These is the latest with the changes made:
=
from random import *
from string import *
class Card:

def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
self.suit = ["None","Clubs","Diamonds","Hearts","Spades"]
self.rank = ["zero", "Ace", "2", "3", "4", "5", "6", "7", "8",
"9", "10", "Jack", "Queen", "King"]
self.BJ = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

def getRank(self):
return self.rank

def getSuit(self):
return self.suit

def BJValue(self):
return self.BJ

def __str__(self):
'''return " %s of %s(%s)" % (self.rank[self.rank],
self.suit[self.suit], self.BJ[self.rank])'''
return self.rank + " of " + self.suit

def main():
n = input("How many cards do you want to draw from the deck?")
for i in range(n):
a = randrange(1,13)
b = randrange(1,4)
c = Card(a,b)
print c

main()
===
Still get an error:
>>
>>> Traceback (most recent call last):
  File
"C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
line 310, in RunScript
exec codeObject in __main__.__dict__
  File "D:\Charles Sturt University\ITC106
200670\Assignment2\A2_3.1.py", line 33, in ?
main()
  File "D:\Charles Sturt University\ITC106
200670\Assignment2\A2_3.1.py", line 31, in main
print c
  File "D:\Charles Sturt University\ITC106
200670\Assignment2\A2_3.1.py", line 23, in __str__
return self.rank + " of " + self.suit
TypeError: can only concatenate list (not "str") to list


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


Re: problem using subprocess.call

2006-10-26 Thread Fredrik Lundh
Alex Kachanov wrote:

> running py module with the following code from shell:
> __
>dir=os.path.join(os.path.expanduser("~/domains/domain.com/html"),'test')
>subprocess.call(['find',dir+" -name '*.zip' -execdir unzip {} \;"])

subprocess.call(["find", dir, "-name", "*.zip", "-execdir", "unzip", "{}", 
";"])

 



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


Re: Error to be resolved

2006-10-26 Thread Bruno Desthuilliers
Arun Nair wrote:
> Hey guys can you help me resolve this error
> 
> Thanks & Regards,
> 
> Arun Nair
> This is the program
> 
> from random import *
> from string import *

Avoid the from XXX import * idiom whenever possible. Better to
explicitely tell what you intend to use, and where it comes from.

> class Card:

Make this

class Card(object):

> def __init__(self, suit, rank):
> self.suit = suit
> self.rank = rank
=> here you assign rank to self.rank
> self.rank = ["None","Clubs","Diamonds","Hearts","Spades"]
=> and here you overwrite self.rank
> self.suit = ["zero", "Ace", "2", "3", "4", "5", "6", "7", "8",
> "9", "10", "Jack", "Queen", "King"]
=> and here you overwrite self.suit

You have to use different names for the effective values of rank and
suit for a given instance of Card than for the lists of possible values
(hint : usually, one uses plural forms for collections - so the list of
possible ranks should be named 'ranks').

Also, since these lists of possible values are common to all cards,
you'd better define them as class attributes (ie: define them in the
class statement block but outside the __init__() method), so they'll be
shared by all Card instances.


 While we're at it, I think that you inverted suits and ranks... Please
someone correct me if I'm wrong.


> self.BJ = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

Idem, this is a list of possible blackjack values, not the effective BJ
value for a given instance.

> def getRank(self):
> return self.rank
> 
> def getSuit(self):
> return self.suit
> 
> def BJValue(self):
> return self.BJ
This will return the whole list of BJ values, not the effective value
for the current Card instance

> def __str__(self):
> return " %s of %s(%s)" % (self.rank[self.rank],
> self.suit[self.suit], self.BJ[self.rank])

> def main():
> n = input("How many cards do you want to draw from the deck?")

better to use raw_input() and validate/convert the user's inputs by
yourself.

(snip)
> =
> This is the error
 Traceback (most recent call last):
>   File
> "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
> line 310, in RunScript
> exec codeObject in __main__.__dict__
>   File "D:\A2_3.1.py", line 32, in ?
> main()
>   File "D:\A2_3.1.py", line 30, in main
> print c
>   File "D:\A2_3.1.py", line 22, in __str__
> return " %s of %s(%s)" % (self.rank[self.rank],
> self.suit[self.suit], self.BJ[self.rank])
> TypeError: list indices must be integers

of course. You're trying to use self.rank (which is now a list) as an
index to itself (dito for self.suit).

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


subprocess-how to suppress the stdout

2006-10-26 Thread alf
Hi,
I use subprocess to execute another program but need to suppress its stdout.

I can achieve it by using Popen(...,stdout=subprocess.PIPE,...) but 
wonder where the all stdout actually goes. Is it buffered (to eventually 
fill up)or just discarded?

Or there is a better solution ...

Thx, alf
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Error to be resolved

2006-10-26 Thread Fredrik Lundh
Arun Nair wrote:

>self.suit = suit
>self.rank = rank
>self.suit = ["None","Clubs","Diamonds","Hearts","Spades"]
>self.rank = ["zero", "Ace", "2", "3", "4", "5", "6", "7", "8", "9", 
> "10", "Jack", "Queen", 
> "King"]

hint: what happens if two variables have the same name ?  can Python magically 
figure
   out which one you mean when you try to use one of them, or does something 
else
   happen?

> File "D:\Charles Sturt University\

could you perhaps ask your advisors to drop by and tell us why he/she expects 
us to
do their job ?

 



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


displaying \n-less prompts in a pythonic way

2006-10-26 Thread alf
Hi,

I have a command line program which also does some interaction with the 
user using stdin and stdout.

My requirement is to print prompt so the user can answer in the same 
line. Unfortunately:

  print 'enter command:',


does not really work as the comma is carried over to the following lines 
and the indentation gets messed up.


I can use sys.stdout.write('enter command:') instead but kind of do not 
like sys.stdout.write mixed up with print's statements used to display 
other informations.


Is there a pythonic solution for the problem?

Thx, alf
-- 
http://mail.python.org/mailman/listinfo/python-list


http://tipc.sourceforge.net support

2006-10-26 Thread alf
Hi,

I did my homework and researched the net - can not find the python 
support for TIPC.

Does anybody know if there are plans to implement it?

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


Re: problem using subprocess.call

2006-10-26 Thread Alex Kachanov
>> 
>> dir=os.path.join(os.path.expanduser("~/domains/domain.com/html"),'test')
>>subprocess.call(['find',dir+" -name '*.zip' -execdir unzip {} \;"])
>
>subprocess.call(["find", dir, "-name", "*.zip", "-execdir", "unzip", 
> "{}", ";"])

Ok, thanks, it works.
But what's the difference? Why I can't pass all parameters as one string? 


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


Re: subprocess-how to suppress the stdout

2006-10-26 Thread Fredrik Lundh
"alf" <[EMAIL PROTECTED]> wrote:

> I can achieve it by using Popen(...,stdout=subprocess.PIPE,...) but
> wonder where the all stdout actually goes. Is it buffered (to eventually
> fill up)

it ends up in a pipe buffer, yes.

> Or there is a better solution ...

/dev/null is your friend:

Popen(..., stdout=open("/dev/null", "w"), stderr=subprocess.STDOUT, ...)

 



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


Re: problem using subprocess.call

2006-10-26 Thread Fredrik Lundh
Alex Kachanov wrote:

>>subprocess.call(["find", dir, "-name", "*.zip", "-execdir", "unzip", 
>> "{}", ";"])
>
> Ok, thanks, it works.
> But what's the difference? Why I can't pass all parameters as one string?

because there's no one around to split them up for you.

after all, that's the whole point of running another program without going 
though the
shell: what you pass in ends up, as is, in the other program's argument array.

 



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


Re: displaying \n-less prompts in a pythonic way

2006-10-26 Thread Sybren Stuvel
alf enlightened us with:
> I have a command line program which also does some interaction with the 
> user using stdin and stdout.
>
> My requirement is to print prompt so the user can answer in the same 
> line. Unfortunately:
>
>   print 'enter command:',
>
>
> does not really work as the comma is carried over to the following lines 
> and the indentation gets messed up.
>
>
> I can use sys.stdout.write('enter command:') instead but kind of do not 
> like sys.stdout.write mixed up with print's statements used to display 
> other informations.
>
>
> Is there a pythonic solution for the problem?

Yeah, write a function:

def prompt(label):
'''Prompts the user, returning the typed text'''

sys.stdout.write(label)
return sys.stdin.readline()

Sybren
-- 
Sybren Stüvel
Stüvel IT - http://www.stuvel.eu/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess-how to suppress the stdout

2006-10-26 Thread alf
Fredrik Lundh wrote:
> "alf" <[EMAIL PROTECTED]> wrote:
> 
> 
>>I can achieve it by using Popen(...,stdout=subprocess.PIPE,...) but
>>wonder where the all stdout actually goes. Is it buffered (to eventually
>>fill up)
> 
> 
> it ends up in a pipe buffer, yes.
> 
> 
>>Or there is a better solution ...
> 
> 
> /dev/null is your friend:
> 
> Popen(..., stdout=open("/dev/null", "w"), stderr=subprocess.STDOUT, ...)
> 

I am forced to use win32 :-( plus it needs to be platform independent ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's the best IDE?

2006-10-26 Thread Colin J. Williams
Josh Bloom wrote:
> I'm not going to call it the 'best' ide as thats just silly.
> 
> But if your developing on Windows pyscripter 
> http://mmm-experts.com/Products.aspx?ProductId=4 is a great IDE.
> 
> -Josh
> 
+1

Colin W.

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


Re: What's the best IDE?

2006-10-26 Thread Colin J. Williams
[EMAIL PROTECTED] wrote:
> After researching Komodo, I found it's not free. The only funds I have
> are a college fund, and I can't start diping into that until I'm going
> to college. Any free AND good IDEs?
> 
PyScripter has already been suggested.  It is both of these.

Colin W.

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


PythonMagic - has any body played with it recently

2006-10-26 Thread alf
Hi,

I downloaded the latest found version and untared it - but can not find 
any information how to install it. I guess it is boost based ...

Has any body played with it recently?
-- 
alf
-- 
http://mail.python.org/mailman/listinfo/python-list


my first software

2006-10-26 Thread [EMAIL PROTECTED]
I am a beginner of programming and started to learn Python a week ago.
last 3 days, i write this little tool for Renju.if you have any advice
on my code,please tell me
ps:sorry for my poor english
bow.

#!C:\\Python25
# -*- coding: GBK -*-
from Tkinter import *
import os
import tkFileDialog
import sys
import re
from tkMessageBox import *
import win32clipboard

root = Tk()

interator = 0
done = []
donebac = []
mark = []
step = []
beensaved = 0
code = ''
pastes = ''
mainname = ''
button_frame = Frame(root,width= 640,height = 50)
button_frame.pack(fill = BOTH)

class main_frame(Frame):


def __init__( self, master = None):

Frame.__init__( self ,master)
self.master.geometry( '640x685')
self.master.title(u'PALALA   speeder-x版')

self.pack(expand = YES, fill = BOTH)

self.myCanvas = Canvas(self, bg = '#f8dc59')
self.myCanvas.pack(expand = YES, fill = BOTH)
for x in range(40, 640, 40 ):
for y in range(40,640,40):
self.myCanvas.create_oval(x,y,x,640-y,fill = 'black')
self.myCanvas.create_oval(x,y,640-x,y,fill = 'black')

 #creat 5 masks
self.myCanvas.create_oval(155,155,165,165,fill = 'black', tags
= 'circle')
self.myCanvas.create_oval(155,475,165,485,fill = 'black', tags
= 'circle')
self.myCanvas.create_oval(475,155,485,165,fill = 'black', tags
= 'circle')
self.myCanvas.create_oval(475,475,485,485,fill = 'black', tags
= 'circle')
self.myCanvas.create_oval(315,315,325,325,fill = 'black', tags
= 'circle')

for x in range(40,640,40):
self.myCanvas.create_text(15, x, text = 16-x/40 ,font =
'Times 16')
for x in range(40,640,40):
charlist =
['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O']
self.myCanvas.create_text(x, 625,text
=charlist[x/40-1],font = 'Times 16')

mainframe = main_frame(master = root)



def clickevent(event):
global interator
global done
global mark
global step
global beensaved
if 20 < event.x < 620 and 20 < event.y < 620:
 event.x = event.x + 20 - (event.x + 20) % 40
 event.y = event.y + 20 - (event.y + 20) % 40

 charlist =
['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O']

 for item in done:
if item ==  (charlist[event.x / 40 -1], 16 - event.y / 40):

return
print item

 done.append((charlist[event.x / 40 -1], 16 - event.y / 40))

 if (interator % 2) == 0:
 mark.append(mainframe.myCanvas.create_oval(event.x-15,
event.y-15, event.x+15, event.y+15, fill = 'black', tags = 'circle'))
 step.append(mainframe.myCanvas.create_text(event.x,
event.y, text = interator + 1, fill = 'red', font = 'Simsun 16'))
 else:
 mark.append(mainframe.myCanvas.create_oval(event.x-15,
event.y-15, event.x+15, event.y+15, fill = 'white', tags = 'circle'))
 step.append(mainframe.myCanvas.create_text(event.x,
event.y, text = interator + 1, fill = 'red', font = 'Simsun 16'))



 interator = interator + 1
 print done
beensaved = 0
def undo(event):

global interator
global mark
global step
global done
global beensaved
if interator > 0:
 mainframe.myCanvas.delete(mark[interator - 1])
 del mark[interator - 1]
 mainframe.myCanvas.delete(step[interator - 1])
 del step[interator - 1]
 del done[interator - 1]
 interator = interator - 1
beensaved = 0
def savefile():

global done
global donebac
global mainname
global beensaved

if done == []:
info_blank()
return

if beensaved == 0 and mainname == '':
filename = tkFileDialog.asksaveasfilename(filetypes =
[('savefile','*.txt')], initialdir = './')
else:
filename = mainname

s = ''

for i in range (0,len(done) - 1):
s = s +str(done[i][0]) + str(done[i][1]) + '\n'
s = s + str(done[len(done) - 1][0]) + str(done[len(done) - 1][1])



if filename:
filename = re.sub('.txt','',filename)
savefile = open(filename + '.txt', 'w')
savefile.write(s)
savefile.close()
beensaved = 1
mainname = filename
donebac = done
def saveasfile():
global done
global donebac
global mainname
global beensaved

if done == []:
info_blank()
return

filename = tkFileDialog.asksaveasfilename(filetypes =
[('savefile','*.txt')], initialdir = './')
s = ''

for i in range (0,len(done) - 1):
s = s +str(done[i][0]) + str(done[i][1]) + '\n'
s = s + str(done[len(done) - 1][0]) + str(done[len(done) - 1][1])

if filename:
filename = re.sub('.txt','',filename)
savefile = open(filename + '.txt', 'w')
savefile.write(s)
savefile.close()
beensaved = 1
mainname = filename
donebac = done

def stringTocode(

Re: Debugging

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


On Wednesday 25 October 2006 06:13, Bruno Desthuilliers wrote:
> The bp #1 should only trigger if y >= 6

This give me the right point.

> > Supposing to have a function on program's variables the statement like "
> > if myvar == True: break" doesn't gives power to the BP.
>
> I definitively don't understand you. How does statements in your program
> relates to setting conditions on a bp in the debugger ?

The online help states :
|(Pdb) h b
|b(reak) ([file:]lineno | function) [, condition]
|With a line number argument, set a break there in the current
|file.  With a function name, set a break at first executable line
|of that function.  Without argument, list all breaks.  If a second
|argument is present, it is a string specifying an expression
|which must evaluate to true before the breakpoint is honored.

"(Pdb)" is the prompt, as you can see.

I was thinking the "condition" is anything python can digest .Therefore an 'if 
condition: code' should be accepted. Editing a BP with a condition like that 
is taken as good (perhaps there's no check on its validity)

> Did you really bother reading the doc
http://www.python.it/doc/Python-Docs/html/lib/debugger-commands.html
I downloaded all directory tree :)
Doesn't make difference in what is wrote on those and what is given at command 
line help. If my ignorance disturbing too much, feel free to ignore it any 
time. (No flame intention, however) I appreciate your help and these replies 
will make easier for somebody else when a search engine will hit this post.

|(Pdb) b 17
|Breakpoint 3 at /home/user/tmp/mbxreader.py:17
|(Pdb) cl 3
|No breakpoint numbered 3
|(Pdb) h cl
|cl(ear) filename:lineno
|cl(ear) [bpnumber [bpnumber...]]
|With a space separated list of breakpoint numbers, clear
|those breakpoints.  Without argument, clear all breaks 

Do I input wrongly?
Finally I've done some test on pydb, I felt no much differences. But also the 
author tried to keep compatibility with Pdb/Bdb, except some more functions.

F


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


Re: Handling emails

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


On Wednesday 25 October 2006 13:06, Dennis Lee Bieber wrote:

> #   based upon bits from the (Active)Python 2.4 help system and other
> code...
OK, good help, Thank you.
As I had confessed, that code was extrapolated from other sources and I took 
it for granted as long  as is working on my purpose.
Most of my purpose is to get the whole mail. Last function has no use.
Both code doing well the only difference is the way to call 
email.message_from_(file|string)

F


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


Re: python html 2 image (png)

2006-10-26 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Diez B. Roggisch wrote:

> Whatever lunix is, […]

An operating system for the Commodore 64.  `LUnix NG` Website:

  http://lng.sourceforge.net/

:-)

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

Re: The format of filename

2006-10-26 Thread Tim Chase
>> Some experimentation shows that Python does seem to provide
>> *some* translation. Windows lets me use '/' as a path separator,
>> but not as the name of the root of a partition name. But perhaps
>> this a peculiarity of the commands themselves, and not of Windows
>> path names in particular.
>>
>>  C:\PYTHON24>CD /
>>  The syntax of the command is incorrect.
>>  
>>  C:\PYTHON24>CD \
>>  C:\>EDIT /PYTHON24/README
>>  The syntax of the command is incorrect.
> 
> The Windows APIs all accept either forward slashes or back, and have done
> so clear back to Windows 3.0.  However, the Windows command shells do not.
> That's what you're seeing here.

What one finds is that the command-shell is self-inconsistant:

C:\temp>md foo
C:\temp>md foo\bar
C:\temp>cd foo/bar
C:\temp\foo\bar>cd ..
C:\temp\foo>cd ..
C:\temp>cd /foo/bar
C:\temp\foo\bar>cd \temp
C:\temp>md foo/baz
The syntax of the command is incorrect
C:\temp>echo dir > foo/bar/pip
C:\temp>echo dir > /foo/bar/pip
The system cannot find the path specified.
C:\temp>dir foo/bar
Parameter format not correct - "bar".
C:\temp>dir /b foo\bar
pip
C:\temp>type foo/bar/pip
The syntax of the command is incorrect.
C:\temp>type foo\bar\pip
dir
C:\temp>cmd < foo/bar/pip
[directory listing within a subshell]
C:\temp>cmd < /foo/bar/pip
The system cannot find the path specified.


The CD, MD, TYPE, ECHO and redirection are all shell-builtins, 
yet they seem to be conflictingly quasi-smart about forward slashes.

Sometimes leading slashes matter.  Sometimes they don't. 
Sometimes forward slashes are acceptable.  Sometimes they aren't. 
  All within the shell's built-in mechanisms.  Go figure.

-tkc




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


Re: Debugging

2006-10-26 Thread Ben Finney
Fulvio <[EMAIL PROTECTED]> writes:

> ***
> Your mail has been scanned by InterScan MSS.
> ***

Please stop sending messages with obnoxious headers like this.

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


Re: return tuple from C to python (extending python)

2006-10-26 Thread Kiran

Farshid Lashkari wrote:
> Simon Forman wrote:
> > I have not done a great deal of extension work with python, however, I
> > do not believe you can simply cast an int (or pointer to int, which is
> > what you say dat is declared as, unless my C is /really/ rusty) to
> > PyObject*.
> >
> > I think you need to do something like Py_BuildValue("i", 123), but see
> > http://docs.python.org/ext/buildValue.html for more info.
>
> Simon is correct. You need to create a python object from your unsigned
> int. Try the following instead:
>
> PyTuple_SET_ITEM(toRet, i, PyInt_FromLong(dat[i]) );
> 
> -Farshid

That did the trick.  thanks guys both for your help!

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


Re: Get coordinates of a cell

2006-10-26 Thread [EMAIL PROTECTED]
I will give it a try if you have source code so that I can test it..

https://sourceforge.net/project/showfiles.php?group_id=156455&package_id=202823
http://www.dexrow.com


Teja wrote:
> I have a GUI application with a Frame and a grid in it. I want to popup
> a menu after the user enters some text in a cell and hits ENTER key. I
> was able to popup the menu. However the menu is not popping up exactly
> at the position where I want it. It should be popped up immediately
> after the cell in which the user has entered the text. To get the co
> ordinates I am using the function event.GetPosition(). Here event is
> wx.EVT_KEY_DOWN. Any pointers please?

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


Re: Handling emails

2006-10-26 Thread Ben Finney
Fulvio <[EMAIL PROTECTED]> writes:

> ***
> Your mail has been scanned by InterScan MSS.
> ***

Please stop sending messages with obnoxious headers like this.

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


Re: displaying \n-less prompts in a pythonic way

2006-10-26 Thread bearophileHUGS
Sybren Stuvel:
> def prompt(label):
> '''Prompts the user, returning the typed text'''

> sys.stdout.write(label)
> return sys.stdin.readline()

Maybe raw_input function may help too.

Bye,
bearophile

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


Re: chained attrgetter

2006-10-26 Thread David S.
Ah, pretty Python.  

Thanks, all.

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


Re: Handling emails

2006-10-26 Thread Steve Holden
Ben Finney wrote:
> Fulvio <[EMAIL PROTECTED]> writes:
> 
> 
>>***
>>Your mail has been scanned by InterScan MSS.
>>***
> 
> 
> Please stop sending messages with obnoxious headers like this.
> 
Please stop sending messages with obnoxious content like this.

If you insist on telling someone off publicly via a newsgroup, once is 
enough. I agree it's a pain, but Fulvio may not have it in his power to 
switch the header off. Mail admins do some incredibly stupid things.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: displaying \n-less prompts in a pythonic way

2006-10-26 Thread Steve Holden
Sybren Stuvel wrote:
> alf enlightened us with:
> 
>>I have a command line program which also does some interaction with the 
>>user using stdin and stdout.
>>
>>My requirement is to print prompt so the user can answer in the same 
>>line. Unfortunately:
>>
>>  print 'enter command:',
>>
>>
>>does not really work as the comma is carried over to the following lines 
>>and the indentation gets messed up.
>>
>>
>>I can use sys.stdout.write('enter command:') instead but kind of do not 
>>like sys.stdout.write mixed up with print's statements used to display 
>>other informations.
>>
>>
>>Is there a pythonic solution for the problem?
> 
> 
> Yeah, write a function:
> 
> def prompt(label):
> '''Prompts the user, returning the typed text'''
> 
> sys.stdout.write(label)
> return sys.stdin.readline()
> 
Or use raw_input(), which was designed for such situations:

  >>> mystr = raw_input("Who is this? ")
Who is this? Steve

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


doesnt seems to work can any help be provided

2006-10-26 Thread Arun Nair
import string

class Card:

# Not sure if I need to set these first???
# suitList = ()
# rankList = ()

def __init__(self,suit,rank):
self.suit = suit
self.rank = rank

def __repr__(self):
return str(self)

def __str__(self):
return "%s of %s" %
(self.rankList[self.rank],self.suitList[self.suit])

def __cmp__(self,other):
if self.suit > other.suit:
return 1
if self.suit < other.suit:
return -1
if self.rank > other.rank:
return 1
if self.rank < other.rank:
return -1
else:
return 0

def getCard(cards):
# Break each card into suit and rank
rankList , suitList = string.split(cards," ")
return Card(rankList,suitList)

class Deck:
def __init__(self):
self.cards = []
for suit in range(4):
for rank in range(1,14):
self.cards.append(Card(suit,rank))

def main():
# Open the file with the cards in them
filename = raw_input('Enter the file name for the cards >>')
infile = open(filename,'r')

# Set the first card in the list
cards = getCard(infile.readline())

# Process the extra lines
for line in infile:
s = getCard(line)
infile.close()
a=Deck()   
print a


main()

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


Re: Can any one help with solving this program it just doesnt take probability of the second team

2006-10-26 Thread Paul McGuire
"Arun Nair" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> ''' Can anyone help me with this program it just takes probability of
> the first team and runs the program doesnt takes the probability of the
> second team even though specified'''
>
> from random import *
>
> def volleySimulation():
>printInstructions()
>probA, probB, n = getInputs()
>winA, winB = simGames(n, probA, probB)
>printSummary(winA, winB)
>
> def printInstructions():
>print "This program stimulates a game of Volley Ball between two
> teams i.e. Team A and Team B"

While I was "stimulated" by reading this post, I think you mean "simulates" 
here. :)

-- Paul


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


Re: iterator idea

2006-10-26 Thread Duncan Booth
Paul Rubin  wrote:
...
> For example, the annoyance means itertools.takewhile consumes an extra
> element with no reasonable way to retrieve it. 
...
>
>def is_even(n): return (n%2 == 0)
>def is_odd(n): return (n%2 != 0) 
> 
># we want to do something with all the runs of even numbers
># in the sequence, and similarly with the odds.  seq is an 
># infinite sequence.
>while True:
>evens, seq = takewhile_exact(is_even, seq)
>do_something_with (evens)
>odds, seq = takewhile_exact(is_odd, seq)
>do_something_else_with (odds)
> 
> Without the "goto"-like transfer, we'd get deeper and deeper in nested
> iterators and eventually overflow the call stack.

I wouldn't agree that there is no way reasonable way to get the terminating 
value with takewhile, you just need another generator or two:

>>> def repeatable(iterator):
it = iter(iterator)
for v in it:
while (yield v):
yield None


>>> def takeparts(predicates, iterator):
iterator = repeatable(iterator)
while True:
for pred in predicates:
yield takewhile(pred, iterator)
iterator.send(True)


>>> for seq in takeparts([is_even, is_odd], [2,2,4,5,6,6,7]):
print list(seq)


[2, 2, 4]
[5]
[6, 6]
[7]

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


Re: question about True values

2006-10-26 Thread skip

Skip> string  ""
Skip> list[]
Skip> tuple   ()
Skip> dict{}
Skip> int 0
Skip> float   0.0
Skip> complex 0j
Skip> set set()
Skip> 
Skip> Any other value besides the above will compare as "not false".

>> And today's question for the novices is: which Python type did Skip
>> miss from the above list?

Ben>bool False

In my rush to reply I missed several others as well.  Elucidation left as an
exercise for the reader.

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


Re: iterator idea

2006-10-26 Thread Paul Rubin
Duncan Booth <[EMAIL PROTECTED]> writes:
> I wouldn't agree that there is no way reasonable way to get the terminating 
> value with takewhile, you just need another generator or two:

Hmm, I hadn't thought about iterator.send.  I'll have to look at that
more carefully and re-read the PEP.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: doesnt seems to work can any help be provided

2006-10-26 Thread Bruno Desthuilliers
Arun Nair wrote:

> import string

You don't need it. Use "some string".split() instead

> class Card:

class Card(object):

> # Not sure if I need to set these first???
Not only do you need to define them, but it would probably be a good
idea to populate them. And BTW, () is a tuple, not a list (but tuples
are perfectly ok for this use case).
> # suitList = ()
> # rankList = ()


(snip whole code listing)

Do you really expect us to run your code, fix the bugs and send it back?
Or are we supposed to guess what's "not working" ?

Please take a few minutes to read this:
http://catb.org/esr/faqs/smart-questions.html

with particular attention to the following point:
http://catb.org/esr/faqs/smart-questions.html#beprecise

HTH


-- 
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: doesnt seems to work can any help be provided

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

> Please take a few minutes to read this:
> http://catb.org/esr/faqs/smart-questions.html

or better, check if the the academic misconduct rules for the university you're
attending happens to say anything about "collusion".

 



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


Re: doesnt seems to work can any help be provided

2006-10-26 Thread Steve Holden
Arun Nair wrote:
[stuff]

You will find people are willing to help, even sometimes with homework 
questions, when questioners show some evidence that they are looking to 
learn rather than simply to have their problems solved for them.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: doesnt seems to work can any help be provided

2006-10-26 Thread Grant Edwards
On 2006-10-26, Arun Nair <[EMAIL PROTECTED]> wrote:
> import string
>
> class Card:

Could you please keep this homework assignment in a single
thread in order to make it easier to ignore for those of us who
don't want to work on this particular homework problem for you?

If not, then you're likely to get get killfiled by many people
(all your postings will get ignored).

-- 
Grant Edwards   grante Yow!  Why is everything
  at   made of Lycra Spandex?
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Slightly OT: Is pyhelp.cgi documentation search broken?

2006-10-26 Thread jim-on-linux
On Thursday 26 October 2006 04:01, you wrote:
> Hi!
>
> For a number of days I haven't been able to
> search the online python docs at:
>
> http://starship.python.net/crew/theller/pyhelp.
>cgi
>

Joel, 


Try here,
[EMAIL PROTECTED]

jim-on-linux
http://www.inqvista.com



> that is the "search the docs with" link at this
> page:
>
> http://www.python.org/doc/
>
> Instead of the search engine, I get Error 404.
> This is a real bother for me, since I rely
> heavily on it for my work.
>
> Is it broken? If so, is anybody trying to get
> it back up again, and what's the time scale in
> that case? Is there an alternative available
> somewhere?
>
> Cheers!
> /Joel Hedlund
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about True values

2006-10-26 Thread Steven D'Aprano
On Wed, 25 Oct 2006 19:19:59 +, John Salerno wrote:

> Oh!!! I get it now! I was thinking that
> 
> if s
> 
> was the same as
> 
> if s == True

No. But you know that now :)

> because I know sometimes you can write if statements this way (though 
> it's wordy). 

You can, but shouldn't.


> But what I didn't realize was that in the cases I was 
> thinking of, 's' was an expression that evaluated to a boolean value, 
> not an actual value of some other type!
> 
> So I suppose
> 
> if (10 > 5)

Is the same as:

if True

because (10 > 5) evaluates as True.

 
> would be the same as
> 
> if (10 > 5) == True

Did you mean

if (10 > 5) == True == True

or 

if (10 > 5) == True == True == True

or even 

if (10 > 5) == True == True == True == True

I hope you see my point now.


> because (10 > 5) does evaluate to "True".

I think it is a good time to remind people of some extremely well-thought
out opposition to the introduction of bools to Python from Laura Creighton:

http://mail.python.org/pipermail/python-list/2002-April/095878.html

She lost the debate, Guido had the final word and Python now has bools.
Take particular note of her description of Python distinguishing between
Something ("cat", 4, [0, 1, 2] etc) and Nothing ("", 0, [] etc).



-- 
Steven.

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


Re: cleaner way to write this?

2006-10-26 Thread John Salerno
Steve Holden wrote:

> I suspect you need to use a validator so the user can't click OK until 
> they've put a value int eh text entry item.

wow, didn't think of that. that might end up being simpler than anything 
else i've considered! :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cleaner way to write this?

2006-10-26 Thread John Salerno
Paul Rubin wrote:
> Bruno Desthuilliers <[EMAIL PROTECTED]> writes:
>>> But if the user doesn't enter any text, I don't want the method to
>>> return at all (even None).
>> John, please re-read the FineManual(tm). None is the default return
>> value of a function - even if there's no return statement.
> 
> Correct, but if the user doesn't enter text, the function is supposed
> to loop and prompt for text again, instead of returning.

Yes, that's what I meant. I didn't want it to return *yet* until a value 
was entered.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's the best IDE?

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

> as I have yet to try Vim - maybe I'll try tomarrow.

Warning: Vim isn't something you just "try tomorrow"  :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess-how to suppress the stdout

2006-10-26 Thread Fredrik Lundh
alf wrote:

>> /dev/null is your friend:
>>
>> Popen(..., stdout=open("/dev/null", "w"), stderr=subprocess.STDOUT, ...)
>>
> 
> I am forced to use win32 :-( plus it needs to be platform independent ...

alright, os.devnull is your friend:

  Popen(..., stdout=open(os.devnull, "w"), stderr=subprocess.STDOUT, ...)



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


Re: What's the best IDE?

2006-10-26 Thread Neil Cerutti
On 2006-10-26, John Salerno <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
>> as I have yet to try Vim - maybe I'll try tomarrow.
>
> Warning: Vim isn't something you just "try tomorrow"  :)

You can become proficient enough for basic editing in about 20
minutes with the built-in tutorial.

Getting it to work seemlessly with Python code will take
considerably longer.

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


[ANN] IronPython Community Edition r3

2006-10-26 Thread Sanghyeon Seo
This is the third release of IronPython Community Edition (IPCE).

Get it here.
http://sparcs.kaist.ac.kr/~tinuviel/download/IPCE-r3.zip

This release is also available on SourceForge mirrors near you.
http://sourceforge.net/projects/fepy

IPCE has a homepage. You can read about licenses and patches there.
There's also some new documentations like FePy Library Reference.
http://fepy.sourceforge.net/

Changes in this release:

* Latest and greatest!

Updated to IronPython 1.0.1.
Updated to CPython 2.4.4.
Compiled with Mono 1.1.18.

* Relicensed under the MIT license, for those who found previous
license terms (Do What The Fuck You Want To Public License) offensive,
or humor-impaired.

* New CPython-compatible wrappers.

zlib, using System.IO.Compression.
hashlib, using System.Security.Cryptography.
sqlite3, using generic DB-API module already developed.

hashlib and sqlite3 are modules new in CPython 2.5.

* Updated CPython-compatible wrappers.

Numerous updates to pyexpat. Previously, pyexpat.py was only intended
to run ElementTree. It is now compatible enough to run xml.dom and
xml.sax codes.

* Patches to Python standard library.

patch-stdlib-tarfile-null-terminated fixes (arguably) a bug.

patch-stdlib-httplib-disable-idna and patch-stdlib-xml-sax-import are
workarounds, but changes are minimal and make using httplib and
xml.sax much better on IronPython.

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


Debugging/Networking ?s.

2006-10-26 Thread Michael B. Trausch
I am having a little bit of trouble figuring out what to do about a
problem that I am having with the program I am working with.

I had it working yesterday, and up through till this morning.  I hadn't
thought about putting it in version control until now, so whatever it
was I did, I can't just hit a revert button... that'll teach me.  :-)

Anyway, it opens a socket, and is capable of fetching the first output
from it and displaying it in the TextCtrl that it is using.  It also
says that it is successfully sending what is typed, be it an alias for
something else, or a straight command that needs to be sent.  However,
after the initial text is received, it says that it doesn't receive anymore.

I would believe that, if I could duplicate it with a known working
program (such as telnet)... but, I can't.  The server that I am working
with is working perfectly fine -- e.g., it is replying just as it should
be.  However, it is also not detecting any problem with the socket,
either.  :-/

The code is at http://fd0man.theunixplace.org/Tmud.tar.gz and if someone
could give me some insight as to what I might be doing wrong in
PlayWindow.py, method CheckAndProcessGameOutput, that would be
wonderfully appreciated.  I am out of ideas, myself.  It never comes up
with error, and never says that the socket is ready, either (using
select.select()).

Beware that the code isn't likely to be very pretty -- I am not an
experienced programmer.  Even some of the ideas I got from the ANSI
thread are likely to look not so pretty, because I probably mangled a
lot of that, too, though, it *was* working.  The only thing that
irritates me is that the changes I have been working on today have all
been in the SendOut method in PlayWindow.py, which should have no
bearing on CheckAndProcessGameOutput, so I don't know what really caused
it to stop working.

Thanks in advance for any assistance!

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


  1   2   3   >